[x86] Fix PR22524: the DAG combiner was incorrectly handling illegal
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue 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 CombineExtLoad(SDNode *N);
331     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
332     SDValue BuildSDIV(SDNode *N);
333     SDValue BuildSDIVPow2(SDNode *N);
334     SDValue BuildUDIV(SDNode *N);
335     SDValue BuildReciprocalEstimate(SDValue Op);
336     SDValue BuildRsqrtEstimate(SDValue Op);
337     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
338     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
339     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
340                                bool DemandHighBits = true);
341     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
342     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
343                               SDValue InnerPos, SDValue InnerNeg,
344                               unsigned PosOpcode, unsigned NegOpcode,
345                               SDLoc DL);
346     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
347     SDValue ReduceLoadWidth(SDNode *N);
348     SDValue ReduceLoadOpStoreWidth(SDNode *N);
349     SDValue TransformFPLoadStorePair(SDNode *N);
350     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
351     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
352
353     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
354
355     /// Walk up chain skipping non-aliasing memory nodes,
356     /// looking for aliasing nodes and adding them to the Aliases vector.
357     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
358                           SmallVectorImpl<SDValue> &Aliases);
359
360     /// Return true if there is any possibility that the two addresses overlap.
361     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
362
363     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
364     /// chain (aliasing node.)
365     SDValue FindBetterChain(SDNode *N, SDValue Chain);
366
367     /// Holds a pointer to an LSBaseSDNode as well as information on where it
368     /// is located in a sequence of memory operations connected by a chain.
369     struct MemOpLink {
370       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
371       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
372       // Ptr to the mem node.
373       LSBaseSDNode *MemNode;
374       // Offset from the base ptr.
375       int64_t OffsetFromBase;
376       // What is the sequence number of this mem node.
377       // Lowest mem operand in the DAG starts at zero.
378       unsigned SequenceNum;
379     };
380
381     /// This is a helper function for MergeConsecutiveStores. When the source
382     /// elements of the consecutive stores are all constants or all extracted
383     /// vector elements, try to merge them into one larger store.
384     /// \return True if a merged store was created.
385     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
386                                          EVT MemVT, unsigned NumElem,
387                                          bool IsConstantSrc, bool UseVector);
388     
389     /// Merge consecutive store operations into a wide store.
390     /// This optimization uses wide integers or vectors when possible.
391     /// \return True if some memory operations were changed.
392     bool MergeConsecutiveStores(StoreSDNode *N);
393
394     /// \brief Try to transform a truncation where C is a constant:
395     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
396     ///
397     /// \p N needs to be a truncation and its first operand an AND. Other
398     /// requirements are checked by the function (e.g. that trunc is
399     /// single-use) and if missed an empty SDValue is returned.
400     SDValue distributeTruncateThroughAnd(SDNode *N);
401
402   public:
403     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
404         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
405           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
406       AttributeSet FnAttrs =
407           DAG.getMachineFunction().getFunction()->getAttributes();
408       ForCodeSize =
409           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
410                                Attribute::OptimizeForSize) ||
411           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
412     }
413
414     /// Runs the dag combiner on all nodes in the work list
415     void Run(CombineLevel AtLevel);
416
417     SelectionDAG &getDAG() const { return DAG; }
418
419     /// Returns a type large enough to hold any valid shift amount - before type
420     /// legalization these can be huge.
421     EVT getShiftAmountTy(EVT LHSTy) {
422       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
423       if (LHSTy.isVector())
424         return LHSTy;
425       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
426                         : TLI.getPointerTy();
427     }
428
429     /// This method returns true if we are running before type legalization or
430     /// if the specified VT is legal.
431     bool isTypeLegal(const EVT &VT) {
432       if (!LegalTypes) return true;
433       return TLI.isTypeLegal(VT);
434     }
435
436     /// Convenience wrapper around TargetLowering::getSetCCResultType
437     EVT getSetCCResultType(EVT VT) const {
438       return TLI.getSetCCResultType(*DAG.getContext(), VT);
439     }
440   };
441 }
442
443
444 namespace {
445 /// This class is a DAGUpdateListener that removes any deleted
446 /// nodes from the worklist.
447 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
448   DAGCombiner &DC;
449 public:
450   explicit WorklistRemover(DAGCombiner &dc)
451     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
452
453   void NodeDeleted(SDNode *N, SDNode *E) override {
454     DC.removeFromWorklist(N);
455   }
456 };
457 }
458
459 //===----------------------------------------------------------------------===//
460 //  TargetLowering::DAGCombinerInfo implementation
461 //===----------------------------------------------------------------------===//
462
463 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
464   ((DAGCombiner*)DC)->AddToWorklist(N);
465 }
466
467 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
468   ((DAGCombiner*)DC)->removeFromWorklist(N);
469 }
470
471 SDValue TargetLowering::DAGCombinerInfo::
472 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
473   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
479 }
480
481
482 SDValue TargetLowering::DAGCombinerInfo::
483 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
484   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
485 }
486
487 void TargetLowering::DAGCombinerInfo::
488 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
489   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
490 }
491
492 //===----------------------------------------------------------------------===//
493 // Helper Functions
494 //===----------------------------------------------------------------------===//
495
496 void DAGCombiner::deleteAndRecombine(SDNode *N) {
497   removeFromWorklist(N);
498
499   // If the operands of this node are only used by the node, they will now be
500   // dead. Make sure to re-visit them and recursively delete dead nodes.
501   for (const SDValue &Op : N->ops())
502     // For an operand generating multiple values, one of the values may
503     // become dead allowing further simplification (e.g. split index
504     // arithmetic from an indexed load).
505     if (Op->hasOneUse() || Op->getNumValues() > 1)
506       AddToWorklist(Op.getNode());
507
508   DAG.DeleteNode(N);
509 }
510
511 /// Return 1 if we can compute the negated form of the specified expression for
512 /// the same cost as the expression itself, or 2 if we can compute the negated
513 /// form more cheaply than the expression itself.
514 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
515                                const TargetLowering &TLI,
516                                const TargetOptions *Options,
517                                unsigned Depth = 0) {
518   // fneg is removable even if it has multiple uses.
519   if (Op.getOpcode() == ISD::FNEG) return 2;
520
521   // Don't allow anything with multiple uses.
522   if (!Op.hasOneUse()) return 0;
523
524   // Don't recurse exponentially.
525   if (Depth > 6) return 0;
526
527   switch (Op.getOpcode()) {
528   default: return false;
529   case ISD::ConstantFP:
530     // Don't invert constant FP values after legalize.  The negated constant
531     // isn't necessarily legal.
532     return LegalOperations ? 0 : 1;
533   case ISD::FADD:
534     // FIXME: determine better conditions for this xform.
535     if (!Options->UnsafeFPMath) return 0;
536
537     // After operation legalization, it might not be legal to create new FSUBs.
538     if (LegalOperations &&
539         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
540       return 0;
541
542     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
543     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
544                                     Options, Depth + 1))
545       return V;
546     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
547     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
548                               Depth + 1);
549   case ISD::FSUB:
550     // We can't turn -(A-B) into B-A when we honor signed zeros.
551     if (!Options->UnsafeFPMath) return 0;
552
553     // fold (fneg (fsub A, B)) -> (fsub B, A)
554     return 1;
555
556   case ISD::FMUL:
557   case ISD::FDIV:
558     if (Options->HonorSignDependentRoundingFPMath()) return 0;
559
560     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
561     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
562                                     Options, Depth + 1))
563       return V;
564
565     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
566                               Depth + 1);
567
568   case ISD::FP_EXTEND:
569   case ISD::FP_ROUND:
570   case ISD::FSIN:
571     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
572                               Depth + 1);
573   }
574 }
575
576 /// If isNegatibleForFree returns true, return the newly negated expression.
577 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
578                                     bool LegalOperations, unsigned Depth = 0) {
579   const TargetOptions &Options = DAG.getTarget().Options;
580   // fneg is removable even if it has multiple uses.
581   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
582
583   // Don't allow anything with multiple uses.
584   assert(Op.hasOneUse() && "Unknown reuse!");
585
586   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
587   switch (Op.getOpcode()) {
588   default: llvm_unreachable("Unknown code");
589   case ISD::ConstantFP: {
590     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
591     V.changeSign();
592     return DAG.getConstantFP(V, Op.getValueType());
593   }
594   case ISD::FADD:
595     // FIXME: determine better conditions for this xform.
596     assert(Options.UnsafeFPMath);
597
598     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
599     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
600                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
601       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
602                          GetNegatedExpression(Op.getOperand(0), DAG,
603                                               LegalOperations, Depth+1),
604                          Op.getOperand(1));
605     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
606     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                        GetNegatedExpression(Op.getOperand(1), DAG,
608                                             LegalOperations, Depth+1),
609                        Op.getOperand(0));
610   case ISD::FSUB:
611     // We can't turn -(A-B) into B-A when we honor signed zeros.
612     assert(Options.UnsafeFPMath);
613
614     // fold (fneg (fsub 0, B)) -> B
615     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
616       if (N0CFP->getValueAPF().isZero())
617         return Op.getOperand(1);
618
619     // fold (fneg (fsub A, B)) -> (fsub B, A)
620     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
621                        Op.getOperand(1), Op.getOperand(0));
622
623   case ISD::FMUL:
624   case ISD::FDIV:
625     assert(!Options.HonorSignDependentRoundingFPMath());
626
627     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
628     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
629                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
630       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
631                          GetNegatedExpression(Op.getOperand(0), DAG,
632                                               LegalOperations, Depth+1),
633                          Op.getOperand(1));
634
635     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
636     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
637                        Op.getOperand(0),
638                        GetNegatedExpression(Op.getOperand(1), DAG,
639                                             LegalOperations, Depth+1));
640
641   case ISD::FP_EXTEND:
642   case ISD::FSIN:
643     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
644                        GetNegatedExpression(Op.getOperand(0), DAG,
645                                             LegalOperations, Depth+1));
646   case ISD::FP_ROUND:
647       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
648                          GetNegatedExpression(Op.getOperand(0), DAG,
649                                               LegalOperations, Depth+1),
650                          Op.getOperand(1));
651   }
652 }
653
654 // Return true if this node is a setcc, or is a select_cc
655 // that selects between the target values used for true and false, making it
656 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
657 // the appropriate nodes based on the type of node we are checking. This
658 // simplifies life a bit for the callers.
659 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
660                                     SDValue &CC) const {
661   if (N.getOpcode() == ISD::SETCC) {
662     LHS = N.getOperand(0);
663     RHS = N.getOperand(1);
664     CC  = N.getOperand(2);
665     return true;
666   }
667
668   if (N.getOpcode() != ISD::SELECT_CC ||
669       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
670       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
671     return false;
672
673   if (TLI.getBooleanContents(N.getValueType()) ==
674       TargetLowering::UndefinedBooleanContent)
675     return false;
676
677   LHS = N.getOperand(0);
678   RHS = N.getOperand(1);
679   CC  = N.getOperand(4);
680   return true;
681 }
682
683 /// Return true if this is a SetCC-equivalent operation with only one use.
684 /// If this is true, it allows the users to invert the operation for free when
685 /// it is profitable to do so.
686 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
687   SDValue N0, N1, N2;
688   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
689     return true;
690   return false;
691 }
692
693 /// Returns true if N is a BUILD_VECTOR node whose
694 /// elements are all the same constant or undefined.
695 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
696   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
697   if (!C)
698     return false;
699
700   APInt SplatUndef;
701   unsigned SplatBitSize;
702   bool HasAnyUndefs;
703   EVT EltVT = N->getValueType(0).getVectorElementType();
704   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
705                              HasAnyUndefs) &&
706           EltVT.getSizeInBits() >= SplatBitSize);
707 }
708
709 // \brief Returns the SDNode if it is a constant BuildVector or constant.
710 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
711   if (isa<ConstantSDNode>(N))
712     return N.getNode();
713   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
714   if (BV && BV->isConstant())
715     return BV;
716   return nullptr;
717 }
718
719 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
720 // int.
721 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
722   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
723     return CN;
724
725   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
726     BitVector UndefElements;
727     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
728
729     // BuildVectors can truncate their operands. Ignore that case here.
730     // FIXME: We blindly ignore splats which include undef which is overly
731     // pessimistic.
732     if (CN && UndefElements.none() &&
733         CN->getValueType(0) == N.getValueType().getScalarType())
734       return CN;
735   }
736
737   return nullptr;
738 }
739
740 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
741 // float.
742 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
743   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
744     return CN;
745
746   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
747     BitVector UndefElements;
748     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
749
750     if (CN && UndefElements.none())
751       return CN;
752   }
753
754   return nullptr;
755 }
756
757 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
758                                     SDValue N0, SDValue N1) {
759   EVT VT = N0.getValueType();
760   if (N0.getOpcode() == Opc) {
761     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
762       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
763         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
764         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
765           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
766         return SDValue();
767       }
768       if (N0.hasOneUse()) {
769         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
770         // use
771         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
772         if (!OpNode.getNode())
773           return SDValue();
774         AddToWorklist(OpNode.getNode());
775         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
776       }
777     }
778   }
779
780   if (N1.getOpcode() == Opc) {
781     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
782       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
783         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
784         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
785           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
786         return SDValue();
787       }
788       if (N1.hasOneUse()) {
789         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
790         // use
791         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
792         if (!OpNode.getNode())
793           return SDValue();
794         AddToWorklist(OpNode.getNode());
795         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
796       }
797     }
798   }
799
800   return SDValue();
801 }
802
803 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
804                                bool AddTo) {
805   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
806   ++NodesCombined;
807   DEBUG(dbgs() << "\nReplacing.1 ";
808         N->dump(&DAG);
809         dbgs() << "\nWith: ";
810         To[0].getNode()->dump(&DAG);
811         dbgs() << " and " << NumTo-1 << " other values\n");
812   for (unsigned i = 0, e = NumTo; i != e; ++i)
813     assert((!To[i].getNode() ||
814             N->getValueType(i) == To[i].getValueType()) &&
815            "Cannot combine value to value of different type!");
816
817   WorklistRemover DeadNodes(*this);
818   DAG.ReplaceAllUsesWith(N, To);
819   if (AddTo) {
820     // Push the new nodes and any users onto the worklist
821     for (unsigned i = 0, e = NumTo; i != e; ++i) {
822       if (To[i].getNode()) {
823         AddToWorklist(To[i].getNode());
824         AddUsersToWorklist(To[i].getNode());
825       }
826     }
827   }
828
829   // Finally, if the node is now dead, remove it from the graph.  The node
830   // may not be dead if the replacement process recursively simplified to
831   // something else needing this node.
832   if (N->use_empty())
833     deleteAndRecombine(N);
834   return SDValue(N, 0);
835 }
836
837 void DAGCombiner::
838 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
839   // Replace all uses.  If any nodes become isomorphic to other nodes and
840   // are deleted, make sure to remove them from our worklist.
841   WorklistRemover DeadNodes(*this);
842   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
843
844   // Push the new node and any (possibly new) users onto the worklist.
845   AddToWorklist(TLO.New.getNode());
846   AddUsersToWorklist(TLO.New.getNode());
847
848   // Finally, if the node is now dead, remove it from the graph.  The node
849   // may not be dead if the replacement process recursively simplified to
850   // something else needing this node.
851   if (TLO.Old.getNode()->use_empty())
852     deleteAndRecombine(TLO.Old.getNode());
853 }
854
855 /// Check the specified integer node value to see if it can be simplified or if
856 /// things it uses can be simplified by bit propagation. If so, return true.
857 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
858   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
859   APInt KnownZero, KnownOne;
860   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
861     return false;
862
863   // Revisit the node.
864   AddToWorklist(Op.getNode());
865
866   // Replace the old value with the new one.
867   ++NodesCombined;
868   DEBUG(dbgs() << "\nReplacing.2 ";
869         TLO.Old.getNode()->dump(&DAG);
870         dbgs() << "\nWith: ";
871         TLO.New.getNode()->dump(&DAG);
872         dbgs() << '\n');
873
874   CommitTargetLoweringOpt(TLO);
875   return true;
876 }
877
878 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
879   SDLoc dl(Load);
880   EVT VT = Load->getValueType(0);
881   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
882
883   DEBUG(dbgs() << "\nReplacing.9 ";
884         Load->dump(&DAG);
885         dbgs() << "\nWith: ";
886         Trunc.getNode()->dump(&DAG);
887         dbgs() << '\n');
888   WorklistRemover DeadNodes(*this);
889   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
890   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
891   deleteAndRecombine(Load);
892   AddToWorklist(Trunc.getNode());
893 }
894
895 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
896   Replace = false;
897   SDLoc dl(Op);
898   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
899     EVT MemVT = LD->getMemoryVT();
900     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
901       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
902                                                        : ISD::EXTLOAD)
903       : LD->getExtensionType();
904     Replace = true;
905     return DAG.getExtLoad(ExtType, dl, PVT,
906                           LD->getChain(), LD->getBasePtr(),
907                           MemVT, LD->getMemOperand());
908   }
909
910   unsigned Opc = Op.getOpcode();
911   switch (Opc) {
912   default: break;
913   case ISD::AssertSext:
914     return DAG.getNode(ISD::AssertSext, dl, PVT,
915                        SExtPromoteOperand(Op.getOperand(0), PVT),
916                        Op.getOperand(1));
917   case ISD::AssertZext:
918     return DAG.getNode(ISD::AssertZext, dl, PVT,
919                        ZExtPromoteOperand(Op.getOperand(0), PVT),
920                        Op.getOperand(1));
921   case ISD::Constant: {
922     unsigned ExtOpc =
923       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
924     return DAG.getNode(ExtOpc, dl, PVT, Op);
925   }
926   }
927
928   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
929     return SDValue();
930   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
931 }
932
933 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
934   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
935     return SDValue();
936   EVT OldVT = Op.getValueType();
937   SDLoc dl(Op);
938   bool Replace = false;
939   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
940   if (!NewOp.getNode())
941     return SDValue();
942   AddToWorklist(NewOp.getNode());
943
944   if (Replace)
945     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
946   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
947                      DAG.getValueType(OldVT));
948 }
949
950 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
962 }
963
964 /// Promote the specified integer binary operation if the target indicates it is
965 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
966 /// i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
968   if (!LegalOperations)
969     return SDValue();
970
971   EVT VT = Op.getValueType();
972   if (VT.isVector() || !VT.isInteger())
973     return SDValue();
974
975   // If operation type is 'undesirable', e.g. i16 on x86, consider
976   // promoting it.
977   unsigned Opc = Op.getOpcode();
978   if (TLI.isTypeDesirableForOp(Opc, VT))
979     return SDValue();
980
981   EVT PVT = VT;
982   // Consult target whether it is a good idea to promote this operation and
983   // what's the right type to promote it to.
984   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985     assert(PVT != VT && "Don't know what type to promote to!");
986
987     bool Replace0 = false;
988     SDValue N0 = Op.getOperand(0);
989     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
990     if (!NN0.getNode())
991       return SDValue();
992
993     bool Replace1 = false;
994     SDValue N1 = Op.getOperand(1);
995     SDValue NN1;
996     if (N0 == N1)
997       NN1 = NN0;
998     else {
999       NN1 = PromoteOperand(N1, PVT, Replace1);
1000       if (!NN1.getNode())
1001         return SDValue();
1002     }
1003
1004     AddToWorklist(NN0.getNode());
1005     if (NN1.getNode())
1006       AddToWorklist(NN1.getNode());
1007
1008     if (Replace0)
1009       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1010     if (Replace1)
1011       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1012
1013     DEBUG(dbgs() << "\nPromoting ";
1014           Op.getNode()->dump(&DAG));
1015     SDLoc dl(Op);
1016     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1017                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1018   }
1019   return SDValue();
1020 }
1021
1022 /// Promote the specified integer shift operation if the target indicates it is
1023 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1024 /// i32 since i16 instructions are longer.
1025 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1026   if (!LegalOperations)
1027     return SDValue();
1028
1029   EVT VT = Op.getValueType();
1030   if (VT.isVector() || !VT.isInteger())
1031     return SDValue();
1032
1033   // If operation type is 'undesirable', e.g. i16 on x86, consider
1034   // promoting it.
1035   unsigned Opc = Op.getOpcode();
1036   if (TLI.isTypeDesirableForOp(Opc, VT))
1037     return SDValue();
1038
1039   EVT PVT = VT;
1040   // Consult target whether it is a good idea to promote this operation and
1041   // what's the right type to promote it to.
1042   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1043     assert(PVT != VT && "Don't know what type to promote to!");
1044
1045     bool Replace = false;
1046     SDValue N0 = Op.getOperand(0);
1047     if (Opc == ISD::SRA)
1048       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1049     else if (Opc == ISD::SRL)
1050       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1051     else
1052       N0 = PromoteOperand(N0, PVT, Replace);
1053     if (!N0.getNode())
1054       return SDValue();
1055
1056     AddToWorklist(N0.getNode());
1057     if (Replace)
1058       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1059
1060     DEBUG(dbgs() << "\nPromoting ";
1061           Op.getNode()->dump(&DAG));
1062     SDLoc dl(Op);
1063     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1064                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1065   }
1066   return SDValue();
1067 }
1068
1069 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1070   if (!LegalOperations)
1071     return SDValue();
1072
1073   EVT VT = Op.getValueType();
1074   if (VT.isVector() || !VT.isInteger())
1075     return SDValue();
1076
1077   // If operation type is 'undesirable', e.g. i16 on x86, consider
1078   // promoting it.
1079   unsigned Opc = Op.getOpcode();
1080   if (TLI.isTypeDesirableForOp(Opc, VT))
1081     return SDValue();
1082
1083   EVT PVT = VT;
1084   // Consult target whether it is a good idea to promote this operation and
1085   // what's the right type to promote it to.
1086   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1087     assert(PVT != VT && "Don't know what type to promote to!");
1088     // fold (aext (aext x)) -> (aext x)
1089     // fold (aext (zext x)) -> (zext x)
1090     // fold (aext (sext x)) -> (sext x)
1091     DEBUG(dbgs() << "\nPromoting ";
1092           Op.getNode()->dump(&DAG));
1093     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1094   }
1095   return SDValue();
1096 }
1097
1098 bool DAGCombiner::PromoteLoad(SDValue Op) {
1099   if (!LegalOperations)
1100     return false;
1101
1102   EVT VT = Op.getValueType();
1103   if (VT.isVector() || !VT.isInteger())
1104     return false;
1105
1106   // If operation type is 'undesirable', e.g. i16 on x86, consider
1107   // promoting it.
1108   unsigned Opc = Op.getOpcode();
1109   if (TLI.isTypeDesirableForOp(Opc, VT))
1110     return false;
1111
1112   EVT PVT = VT;
1113   // Consult target whether it is a good idea to promote this operation and
1114   // what's the right type to promote it to.
1115   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1116     assert(PVT != VT && "Don't know what type to promote to!");
1117
1118     SDLoc dl(Op);
1119     SDNode *N = Op.getNode();
1120     LoadSDNode *LD = cast<LoadSDNode>(N);
1121     EVT MemVT = LD->getMemoryVT();
1122     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1123       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1124                                                        : ISD::EXTLOAD)
1125       : LD->getExtensionType();
1126     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1127                                    LD->getChain(), LD->getBasePtr(),
1128                                    MemVT, LD->getMemOperand());
1129     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1130
1131     DEBUG(dbgs() << "\nPromoting ";
1132           N->dump(&DAG);
1133           dbgs() << "\nTo: ";
1134           Result.getNode()->dump(&DAG);
1135           dbgs() << '\n');
1136     WorklistRemover DeadNodes(*this);
1137     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1138     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1139     deleteAndRecombine(N);
1140     AddToWorklist(Result.getNode());
1141     return true;
1142   }
1143   return false;
1144 }
1145
1146 /// \brief Recursively delete a node which has no uses and any operands for
1147 /// which it is the only use.
1148 ///
1149 /// Note that this both deletes the nodes and removes them from the worklist.
1150 /// It also adds any nodes who have had a user deleted to the worklist as they
1151 /// may now have only one use and subject to other combines.
1152 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1153   if (!N->use_empty())
1154     return false;
1155
1156   SmallSetVector<SDNode *, 16> Nodes;
1157   Nodes.insert(N);
1158   do {
1159     N = Nodes.pop_back_val();
1160     if (!N)
1161       continue;
1162
1163     if (N->use_empty()) {
1164       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1165         Nodes.insert(N->getOperand(i).getNode());
1166
1167       removeFromWorklist(N);
1168       DAG.DeleteNode(N);
1169     } else {
1170       AddToWorklist(N);
1171     }
1172   } while (!Nodes.empty());
1173   return true;
1174 }
1175
1176 //===----------------------------------------------------------------------===//
1177 //  Main DAG Combiner implementation
1178 //===----------------------------------------------------------------------===//
1179
1180 void DAGCombiner::Run(CombineLevel AtLevel) {
1181   // set the instance variables, so that the various visit routines may use it.
1182   Level = AtLevel;
1183   LegalOperations = Level >= AfterLegalizeVectorOps;
1184   LegalTypes = Level >= AfterLegalizeTypes;
1185
1186   // Early exit if this basic block is in an optnone function.
1187   AttributeSet FnAttrs =
1188     DAG.getMachineFunction().getFunction()->getAttributes();
1189   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1190                            Attribute::OptimizeNone))
1191     return;
1192
1193   // Add all the dag nodes to the worklist.
1194   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1195        E = DAG.allnodes_end(); I != E; ++I)
1196     AddToWorklist(I);
1197
1198   // Create a dummy node (which is not added to allnodes), that adds a reference
1199   // to the root node, preventing it from being deleted, and tracking any
1200   // changes of the root.
1201   HandleSDNode Dummy(DAG.getRoot());
1202
1203   // while the worklist isn't empty, find a node and
1204   // try and combine it.
1205   while (!WorklistMap.empty()) {
1206     SDNode *N;
1207     // The Worklist holds the SDNodes in order, but it may contain null entries.
1208     do {
1209       N = Worklist.pop_back_val();
1210     } while (!N);
1211
1212     bool GoodWorklistEntry = WorklistMap.erase(N);
1213     (void)GoodWorklistEntry;
1214     assert(GoodWorklistEntry &&
1215            "Found a worklist entry without a corresponding map entry!");
1216
1217     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1218     // N is deleted from the DAG, since they too may now be dead or may have a
1219     // reduced number of uses, allowing other xforms.
1220     if (recursivelyDeleteUnusedNodes(N))
1221       continue;
1222
1223     WorklistRemover DeadNodes(*this);
1224
1225     // If this combine is running after legalizing the DAG, re-legalize any
1226     // nodes pulled off the worklist.
1227     if (Level == AfterLegalizeDAG) {
1228       SmallSetVector<SDNode *, 16> UpdatedNodes;
1229       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1230
1231       for (SDNode *LN : UpdatedNodes) {
1232         AddToWorklist(LN);
1233         AddUsersToWorklist(LN);
1234       }
1235       if (!NIsValid)
1236         continue;
1237     }
1238
1239     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1240
1241     // Add any operands of the new node which have not yet been combined to the
1242     // worklist as well. Because the worklist uniques things already, this
1243     // won't repeatedly process the same operand.
1244     CombinedNodes.insert(N);
1245     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1246       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1247         AddToWorklist(N->getOperand(i).getNode());
1248
1249     SDValue RV = combine(N);
1250
1251     if (!RV.getNode())
1252       continue;
1253
1254     ++NodesCombined;
1255
1256     // If we get back the same node we passed in, rather than a new node or
1257     // zero, we know that the node must have defined multiple values and
1258     // CombineTo was used.  Since CombineTo takes care of the worklist
1259     // mechanics for us, we have no work to do in this case.
1260     if (RV.getNode() == N)
1261       continue;
1262
1263     assert(N->getOpcode() != ISD::DELETED_NODE &&
1264            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1265            "Node was deleted but visit returned new node!");
1266
1267     DEBUG(dbgs() << " ... into: ";
1268           RV.getNode()->dump(&DAG));
1269
1270     // Transfer debug value.
1271     DAG.TransferDbgValues(SDValue(N, 0), RV);
1272     if (N->getNumValues() == RV.getNode()->getNumValues())
1273       DAG.ReplaceAllUsesWith(N, RV.getNode());
1274     else {
1275       assert(N->getValueType(0) == RV.getValueType() &&
1276              N->getNumValues() == 1 && "Type mismatch");
1277       SDValue OpV = RV;
1278       DAG.ReplaceAllUsesWith(N, &OpV);
1279     }
1280
1281     // Push the new node and any users onto the worklist
1282     AddToWorklist(RV.getNode());
1283     AddUsersToWorklist(RV.getNode());
1284
1285     // Finally, if the node is now dead, remove it from the graph.  The node
1286     // may not be dead if the replacement process recursively simplified to
1287     // something else needing this node. This will also take care of adding any
1288     // operands which have lost a user to the worklist.
1289     recursivelyDeleteUnusedNodes(N);
1290   }
1291
1292   // If the root changed (e.g. it was a dead load, update the root).
1293   DAG.setRoot(Dummy.getValue());
1294   DAG.RemoveDeadNodes();
1295 }
1296
1297 SDValue DAGCombiner::visit(SDNode *N) {
1298   switch (N->getOpcode()) {
1299   default: break;
1300   case ISD::TokenFactor:        return visitTokenFactor(N);
1301   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1302   case ISD::ADD:                return visitADD(N);
1303   case ISD::SUB:                return visitSUB(N);
1304   case ISD::ADDC:               return visitADDC(N);
1305   case ISD::SUBC:               return visitSUBC(N);
1306   case ISD::ADDE:               return visitADDE(N);
1307   case ISD::SUBE:               return visitSUBE(N);
1308   case ISD::MUL:                return visitMUL(N);
1309   case ISD::SDIV:               return visitSDIV(N);
1310   case ISD::UDIV:               return visitUDIV(N);
1311   case ISD::SREM:               return visitSREM(N);
1312   case ISD::UREM:               return visitUREM(N);
1313   case ISD::MULHU:              return visitMULHU(N);
1314   case ISD::MULHS:              return visitMULHS(N);
1315   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1316   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1317   case ISD::SMULO:              return visitSMULO(N);
1318   case ISD::UMULO:              return visitUMULO(N);
1319   case ISD::SDIVREM:            return visitSDIVREM(N);
1320   case ISD::UDIVREM:            return visitUDIVREM(N);
1321   case ISD::AND:                return visitAND(N);
1322   case ISD::OR:                 return visitOR(N);
1323   case ISD::XOR:                return visitXOR(N);
1324   case ISD::SHL:                return visitSHL(N);
1325   case ISD::SRA:                return visitSRA(N);
1326   case ISD::SRL:                return visitSRL(N);
1327   case ISD::ROTR:
1328   case ISD::ROTL:               return visitRotate(N);
1329   case ISD::CTLZ:               return visitCTLZ(N);
1330   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1331   case ISD::CTTZ:               return visitCTTZ(N);
1332   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1333   case ISD::CTPOP:              return visitCTPOP(N);
1334   case ISD::SELECT:             return visitSELECT(N);
1335   case ISD::VSELECT:            return visitVSELECT(N);
1336   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1337   case ISD::SETCC:              return visitSETCC(N);
1338   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1339   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1340   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1341   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1342   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1343   case ISD::BITCAST:            return visitBITCAST(N);
1344   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1345   case ISD::FADD:               return visitFADD(N);
1346   case ISD::FSUB:               return visitFSUB(N);
1347   case ISD::FMUL:               return visitFMUL(N);
1348   case ISD::FMA:                return visitFMA(N);
1349   case ISD::FDIV:               return visitFDIV(N);
1350   case ISD::FREM:               return visitFREM(N);
1351   case ISD::FSQRT:              return visitFSQRT(N);
1352   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1353   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1354   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1355   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1356   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1357   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1358   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1359   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1360   case ISD::FNEG:               return visitFNEG(N);
1361   case ISD::FABS:               return visitFABS(N);
1362   case ISD::FFLOOR:             return visitFFLOOR(N);
1363   case ISD::FMINNUM:            return visitFMINNUM(N);
1364   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1365   case ISD::FCEIL:              return visitFCEIL(N);
1366   case ISD::FTRUNC:             return visitFTRUNC(N);
1367   case ISD::BRCOND:             return visitBRCOND(N);
1368   case ISD::BR_CC:              return visitBR_CC(N);
1369   case ISD::LOAD:               return visitLOAD(N);
1370   case ISD::STORE:              return visitSTORE(N);
1371   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1372   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1373   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1374   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1375   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1376   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1377   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1378   case ISD::MLOAD:              return visitMLOAD(N);
1379   case ISD::MSTORE:             return visitMSTORE(N);
1380   }
1381   return SDValue();
1382 }
1383
1384 SDValue DAGCombiner::combine(SDNode *N) {
1385   SDValue RV = visit(N);
1386
1387   // If nothing happened, try a target-specific DAG combine.
1388   if (!RV.getNode()) {
1389     assert(N->getOpcode() != ISD::DELETED_NODE &&
1390            "Node was deleted but visit returned NULL!");
1391
1392     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1393         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1394
1395       // Expose the DAG combiner to the target combiner impls.
1396       TargetLowering::DAGCombinerInfo
1397         DagCombineInfo(DAG, Level, false, this);
1398
1399       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1400     }
1401   }
1402
1403   // If nothing happened still, try promoting the operation.
1404   if (!RV.getNode()) {
1405     switch (N->getOpcode()) {
1406     default: break;
1407     case ISD::ADD:
1408     case ISD::SUB:
1409     case ISD::MUL:
1410     case ISD::AND:
1411     case ISD::OR:
1412     case ISD::XOR:
1413       RV = PromoteIntBinOp(SDValue(N, 0));
1414       break;
1415     case ISD::SHL:
1416     case ISD::SRA:
1417     case ISD::SRL:
1418       RV = PromoteIntShiftOp(SDValue(N, 0));
1419       break;
1420     case ISD::SIGN_EXTEND:
1421     case ISD::ZERO_EXTEND:
1422     case ISD::ANY_EXTEND:
1423       RV = PromoteExtend(SDValue(N, 0));
1424       break;
1425     case ISD::LOAD:
1426       if (PromoteLoad(SDValue(N, 0)))
1427         RV = SDValue(N, 0);
1428       break;
1429     }
1430   }
1431
1432   // If N is a commutative binary node, try commuting it to enable more
1433   // sdisel CSE.
1434   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1435       N->getNumValues() == 1) {
1436     SDValue N0 = N->getOperand(0);
1437     SDValue N1 = N->getOperand(1);
1438
1439     // Constant operands are canonicalized to RHS.
1440     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1441       SDValue Ops[] = {N1, N0};
1442       SDNode *CSENode;
1443       if (const BinaryWithFlagsSDNode *BinNode =
1444               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1445         CSENode = DAG.getNodeIfExists(
1446             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1447             BinNode->hasNoSignedWrap(), BinNode->isExact());
1448       } else {
1449         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1450       }
1451       if (CSENode)
1452         return SDValue(CSENode, 0);
1453     }
1454   }
1455
1456   return RV;
1457 }
1458
1459 /// Given a node, return its input chain if it has one, otherwise return a null
1460 /// sd operand.
1461 static SDValue getInputChainForNode(SDNode *N) {
1462   if (unsigned NumOps = N->getNumOperands()) {
1463     if (N->getOperand(0).getValueType() == MVT::Other)
1464       return N->getOperand(0);
1465     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1466       return N->getOperand(NumOps-1);
1467     for (unsigned i = 1; i < NumOps-1; ++i)
1468       if (N->getOperand(i).getValueType() == MVT::Other)
1469         return N->getOperand(i);
1470   }
1471   return SDValue();
1472 }
1473
1474 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1475   // If N has two operands, where one has an input chain equal to the other,
1476   // the 'other' chain is redundant.
1477   if (N->getNumOperands() == 2) {
1478     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1479       return N->getOperand(0);
1480     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1481       return N->getOperand(1);
1482   }
1483
1484   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1485   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1486   SmallPtrSet<SDNode*, 16> SeenOps;
1487   bool Changed = false;             // If we should replace this token factor.
1488
1489   // Start out with this token factor.
1490   TFs.push_back(N);
1491
1492   // Iterate through token factors.  The TFs grows when new token factors are
1493   // encountered.
1494   for (unsigned i = 0; i < TFs.size(); ++i) {
1495     SDNode *TF = TFs[i];
1496
1497     // Check each of the operands.
1498     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1499       SDValue Op = TF->getOperand(i);
1500
1501       switch (Op.getOpcode()) {
1502       case ISD::EntryToken:
1503         // Entry tokens don't need to be added to the list. They are
1504         // rededundant.
1505         Changed = true;
1506         break;
1507
1508       case ISD::TokenFactor:
1509         if (Op.hasOneUse() &&
1510             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1511           // Queue up for processing.
1512           TFs.push_back(Op.getNode());
1513           // Clean up in case the token factor is removed.
1514           AddToWorklist(Op.getNode());
1515           Changed = true;
1516           break;
1517         }
1518         // Fall thru
1519
1520       default:
1521         // Only add if it isn't already in the list.
1522         if (SeenOps.insert(Op.getNode()).second)
1523           Ops.push_back(Op);
1524         else
1525           Changed = true;
1526         break;
1527       }
1528     }
1529   }
1530
1531   SDValue Result;
1532
1533   // If we've change things around then replace token factor.
1534   if (Changed) {
1535     if (Ops.empty()) {
1536       // The entry token is the only possible outcome.
1537       Result = DAG.getEntryNode();
1538     } else {
1539       // New and improved token factor.
1540       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1541     }
1542
1543     // Don't add users to work list.
1544     return CombineTo(N, Result, false);
1545   }
1546
1547   return Result;
1548 }
1549
1550 /// MERGE_VALUES can always be eliminated.
1551 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1552   WorklistRemover DeadNodes(*this);
1553   // Replacing results may cause a different MERGE_VALUES to suddenly
1554   // be CSE'd with N, and carry its uses with it. Iterate until no
1555   // uses remain, to ensure that the node can be safely deleted.
1556   // First add the users of this node to the work list so that they
1557   // can be tried again once they have new operands.
1558   AddUsersToWorklist(N);
1559   do {
1560     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1561       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1562   } while (!N->use_empty());
1563   deleteAndRecombine(N);
1564   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1565 }
1566
1567 SDValue DAGCombiner::visitADD(SDNode *N) {
1568   SDValue N0 = N->getOperand(0);
1569   SDValue N1 = N->getOperand(1);
1570   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1571   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1572   EVT VT = N0.getValueType();
1573
1574   // fold vector ops
1575   if (VT.isVector()) {
1576     SDValue FoldedVOp = SimplifyVBinOp(N);
1577     if (FoldedVOp.getNode()) return FoldedVOp;
1578
1579     // fold (add x, 0) -> x, vector edition
1580     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1581       return N0;
1582     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1583       return N1;
1584   }
1585
1586   // fold (add x, undef) -> undef
1587   if (N0.getOpcode() == ISD::UNDEF)
1588     return N0;
1589   if (N1.getOpcode() == ISD::UNDEF)
1590     return N1;
1591   // fold (add c1, c2) -> c1+c2
1592   if (N0C && N1C)
1593     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1594   // canonicalize constant to RHS
1595   if (N0C && !N1C)
1596     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1597   // fold (add x, 0) -> x
1598   if (N1C && N1C->isNullValue())
1599     return N0;
1600   // fold (add Sym, c) -> Sym+c
1601   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1602     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1603         GA->getOpcode() == ISD::GlobalAddress)
1604       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1605                                   GA->getOffset() +
1606                                     (uint64_t)N1C->getSExtValue());
1607   // fold ((c1-A)+c2) -> (c1+c2)-A
1608   if (N1C && N0.getOpcode() == ISD::SUB)
1609     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1610       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1611                          DAG.getConstant(N1C->getAPIntValue()+
1612                                          N0C->getAPIntValue(), VT),
1613                          N0.getOperand(1));
1614   // reassociate add
1615   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1616   if (RADD.getNode())
1617     return RADD;
1618   // fold ((0-A) + B) -> B-A
1619   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1620       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1621     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1622   // fold (A + (0-B)) -> A-B
1623   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1624       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1625     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1626   // fold (A+(B-A)) -> B
1627   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1628     return N1.getOperand(0);
1629   // fold ((B-A)+A) -> B
1630   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1631     return N0.getOperand(0);
1632   // fold (A+(B-(A+C))) to (B-C)
1633   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1634       N0 == N1.getOperand(1).getOperand(0))
1635     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1636                        N1.getOperand(1).getOperand(1));
1637   // fold (A+(B-(C+A))) to (B-C)
1638   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1639       N0 == N1.getOperand(1).getOperand(1))
1640     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1641                        N1.getOperand(1).getOperand(0));
1642   // fold (A+((B-A)+or-C)) to (B+or-C)
1643   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1644       N1.getOperand(0).getOpcode() == ISD::SUB &&
1645       N0 == N1.getOperand(0).getOperand(1))
1646     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1647                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1648
1649   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1650   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1651     SDValue N00 = N0.getOperand(0);
1652     SDValue N01 = N0.getOperand(1);
1653     SDValue N10 = N1.getOperand(0);
1654     SDValue N11 = N1.getOperand(1);
1655
1656     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1657       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1658                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1659                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1660   }
1661
1662   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1663     return SDValue(N, 0);
1664
1665   // fold (a+b) -> (a|b) iff a and b share no bits.
1666   if (VT.isInteger() && !VT.isVector()) {
1667     APInt LHSZero, LHSOne;
1668     APInt RHSZero, RHSOne;
1669     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1670
1671     if (LHSZero.getBoolValue()) {
1672       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1673
1674       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1675       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1676       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1677         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1678           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1679       }
1680     }
1681   }
1682
1683   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1684   if (N1.getOpcode() == ISD::SHL &&
1685       N1.getOperand(0).getOpcode() == ISD::SUB)
1686     if (ConstantSDNode *C =
1687           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1688       if (C->getAPIntValue() == 0)
1689         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1690                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1691                                        N1.getOperand(0).getOperand(1),
1692                                        N1.getOperand(1)));
1693   if (N0.getOpcode() == ISD::SHL &&
1694       N0.getOperand(0).getOpcode() == ISD::SUB)
1695     if (ConstantSDNode *C =
1696           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1697       if (C->getAPIntValue() == 0)
1698         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1699                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1700                                        N0.getOperand(0).getOperand(1),
1701                                        N0.getOperand(1)));
1702
1703   if (N1.getOpcode() == ISD::AND) {
1704     SDValue AndOp0 = N1.getOperand(0);
1705     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1706     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1707     unsigned DestBits = VT.getScalarType().getSizeInBits();
1708
1709     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1710     // and similar xforms where the inner op is either ~0 or 0.
1711     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1712       SDLoc DL(N);
1713       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1714     }
1715   }
1716
1717   // add (sext i1), X -> sub X, (zext i1)
1718   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1719       N0.getOperand(0).getValueType() == MVT::i1 &&
1720       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1721     SDLoc DL(N);
1722     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1723     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1724   }
1725
1726   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1727   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1728     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1729     if (TN->getVT() == MVT::i1) {
1730       SDLoc DL(N);
1731       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1732                                  DAG.getConstant(1, VT));
1733       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1734     }
1735   }
1736
1737   return SDValue();
1738 }
1739
1740 SDValue DAGCombiner::visitADDC(SDNode *N) {
1741   SDValue N0 = N->getOperand(0);
1742   SDValue N1 = N->getOperand(1);
1743   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1745   EVT VT = N0.getValueType();
1746
1747   // If the flag result is dead, turn this into an ADD.
1748   if (!N->hasAnyUseOfValue(1))
1749     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1750                      DAG.getNode(ISD::CARRY_FALSE,
1751                                  SDLoc(N), MVT::Glue));
1752
1753   // canonicalize constant to RHS.
1754   if (N0C && !N1C)
1755     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1756
1757   // fold (addc x, 0) -> x + no carry out
1758   if (N1C && N1C->isNullValue())
1759     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1760                                         SDLoc(N), MVT::Glue));
1761
1762   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1763   APInt LHSZero, LHSOne;
1764   APInt RHSZero, RHSOne;
1765   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1766
1767   if (LHSZero.getBoolValue()) {
1768     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1769
1770     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1771     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1772     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1773       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1774                        DAG.getNode(ISD::CARRY_FALSE,
1775                                    SDLoc(N), MVT::Glue));
1776   }
1777
1778   return SDValue();
1779 }
1780
1781 SDValue DAGCombiner::visitADDE(SDNode *N) {
1782   SDValue N0 = N->getOperand(0);
1783   SDValue N1 = N->getOperand(1);
1784   SDValue CarryIn = N->getOperand(2);
1785   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1786   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1787
1788   // canonicalize constant to RHS
1789   if (N0C && !N1C)
1790     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1791                        N1, N0, CarryIn);
1792
1793   // fold (adde x, y, false) -> (addc x, y)
1794   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1795     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1796
1797   return SDValue();
1798 }
1799
1800 // Since it may not be valid to emit a fold to zero for vector initializers
1801 // check if we can before folding.
1802 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1803                              SelectionDAG &DAG,
1804                              bool LegalOperations, bool LegalTypes) {
1805   if (!VT.isVector())
1806     return DAG.getConstant(0, VT);
1807   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1808     return DAG.getConstant(0, VT);
1809   return SDValue();
1810 }
1811
1812 SDValue DAGCombiner::visitSUB(SDNode *N) {
1813   SDValue N0 = N->getOperand(0);
1814   SDValue N1 = N->getOperand(1);
1815   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1816   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1817   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1818     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1819   EVT VT = N0.getValueType();
1820
1821   // fold vector ops
1822   if (VT.isVector()) {
1823     SDValue FoldedVOp = SimplifyVBinOp(N);
1824     if (FoldedVOp.getNode()) return FoldedVOp;
1825
1826     // fold (sub x, 0) -> x, vector edition
1827     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1828       return N0;
1829   }
1830
1831   // fold (sub x, x) -> 0
1832   // FIXME: Refactor this and xor and other similar operations together.
1833   if (N0 == N1)
1834     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1835   // fold (sub c1, c2) -> c1-c2
1836   if (N0C && N1C)
1837     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1838   // fold (sub x, c) -> (add x, -c)
1839   if (N1C)
1840     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1841                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1842   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1843   if (N0C && N0C->isAllOnesValue())
1844     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1845   // fold A-(A-B) -> B
1846   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1847     return N1.getOperand(1);
1848   // fold (A+B)-A -> B
1849   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1850     return N0.getOperand(1);
1851   // fold (A+B)-B -> A
1852   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1853     return N0.getOperand(0);
1854   // fold C2-(A+C1) -> (C2-C1)-A
1855   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1856     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1857                                    VT);
1858     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1859                        N1.getOperand(0));
1860   }
1861   // fold ((A+(B+or-C))-B) -> A+or-C
1862   if (N0.getOpcode() == ISD::ADD &&
1863       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1864        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1865       N0.getOperand(1).getOperand(0) == N1)
1866     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1867                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1868   // fold ((A+(C+B))-B) -> A+C
1869   if (N0.getOpcode() == ISD::ADD &&
1870       N0.getOperand(1).getOpcode() == ISD::ADD &&
1871       N0.getOperand(1).getOperand(1) == N1)
1872     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1873                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1874   // fold ((A-(B-C))-C) -> A-B
1875   if (N0.getOpcode() == ISD::SUB &&
1876       N0.getOperand(1).getOpcode() == ISD::SUB &&
1877       N0.getOperand(1).getOperand(1) == N1)
1878     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1879                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1880
1881   // If either operand of a sub is undef, the result is undef
1882   if (N0.getOpcode() == ISD::UNDEF)
1883     return N0;
1884   if (N1.getOpcode() == ISD::UNDEF)
1885     return N1;
1886
1887   // If the relocation model supports it, consider symbol offsets.
1888   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1889     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1890       // fold (sub Sym, c) -> Sym-c
1891       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1892         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1893                                     GA->getOffset() -
1894                                       (uint64_t)N1C->getSExtValue());
1895       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1896       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1897         if (GA->getGlobal() == GB->getGlobal())
1898           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1899                                  VT);
1900     }
1901
1902   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1903   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1904     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1905     if (TN->getVT() == MVT::i1) {
1906       SDLoc DL(N);
1907       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1908                                  DAG.getConstant(1, VT));
1909       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1910     }
1911   }
1912
1913   return SDValue();
1914 }
1915
1916 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1917   SDValue N0 = N->getOperand(0);
1918   SDValue N1 = N->getOperand(1);
1919   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1920   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1921   EVT VT = N0.getValueType();
1922
1923   // If the flag result is dead, turn this into an SUB.
1924   if (!N->hasAnyUseOfValue(1))
1925     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1926                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1927                                  MVT::Glue));
1928
1929   // fold (subc x, x) -> 0 + no borrow
1930   if (N0 == N1)
1931     return CombineTo(N, DAG.getConstant(0, VT),
1932                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1933                                  MVT::Glue));
1934
1935   // fold (subc x, 0) -> x + no borrow
1936   if (N1C && N1C->isNullValue())
1937     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1938                                         MVT::Glue));
1939
1940   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1941   if (N0C && N0C->isAllOnesValue())
1942     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1943                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1944                                  MVT::Glue));
1945
1946   return SDValue();
1947 }
1948
1949 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1950   SDValue N0 = N->getOperand(0);
1951   SDValue N1 = N->getOperand(1);
1952   SDValue CarryIn = N->getOperand(2);
1953
1954   // fold (sube x, y, false) -> (subc x, y)
1955   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1956     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1957
1958   return SDValue();
1959 }
1960
1961 SDValue DAGCombiner::visitMUL(SDNode *N) {
1962   SDValue N0 = N->getOperand(0);
1963   SDValue N1 = N->getOperand(1);
1964   EVT VT = N0.getValueType();
1965
1966   // fold (mul x, undef) -> 0
1967   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1968     return DAG.getConstant(0, VT);
1969
1970   bool N0IsConst = false;
1971   bool N1IsConst = false;
1972   APInt ConstValue0, ConstValue1;
1973   // fold vector ops
1974   if (VT.isVector()) {
1975     SDValue FoldedVOp = SimplifyVBinOp(N);
1976     if (FoldedVOp.getNode()) return FoldedVOp;
1977
1978     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1979     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1980   } else {
1981     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1982     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1983                             : APInt();
1984     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1985     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1986                             : APInt();
1987   }
1988
1989   // fold (mul c1, c2) -> c1*c2
1990   if (N0IsConst && N1IsConst)
1991     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1992
1993   // canonicalize constant to RHS
1994   if (N0IsConst && !N1IsConst)
1995     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1996   // fold (mul x, 0) -> 0
1997   if (N1IsConst && ConstValue1 == 0)
1998     return N1;
1999   // We require a splat of the entire scalar bit width for non-contiguous
2000   // bit patterns.
2001   bool IsFullSplat =
2002     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2003   // fold (mul x, 1) -> x
2004   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2005     return N0;
2006   // fold (mul x, -1) -> 0-x
2007   if (N1IsConst && ConstValue1.isAllOnesValue())
2008     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2009                        DAG.getConstant(0, VT), N0);
2010   // fold (mul x, (1 << c)) -> x << c
2011   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2012     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2013                        DAG.getConstant(ConstValue1.logBase2(),
2014                                        getShiftAmountTy(N0.getValueType())));
2015   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2016   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2017     unsigned Log2Val = (-ConstValue1).logBase2();
2018     // FIXME: If the input is something that is easily negated (e.g. a
2019     // single-use add), we should put the negate there.
2020     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021                        DAG.getConstant(0, VT),
2022                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2023                             DAG.getConstant(Log2Val,
2024                                       getShiftAmountTy(N0.getValueType()))));
2025   }
2026
2027   APInt Val;
2028   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2029   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2030       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2031                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2032     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2033                              N1, N0.getOperand(1));
2034     AddToWorklist(C3.getNode());
2035     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2036                        N0.getOperand(0), C3);
2037   }
2038
2039   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2040   // use.
2041   {
2042     SDValue Sh(nullptr,0), Y(nullptr,0);
2043     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2044     if (N0.getOpcode() == ISD::SHL &&
2045         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2046                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2047         N0.getNode()->hasOneUse()) {
2048       Sh = N0; Y = N1;
2049     } else if (N1.getOpcode() == ISD::SHL &&
2050                isa<ConstantSDNode>(N1.getOperand(1)) &&
2051                N1.getNode()->hasOneUse()) {
2052       Sh = N1; Y = N0;
2053     }
2054
2055     if (Sh.getNode()) {
2056       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2057                                 Sh.getOperand(0), Y);
2058       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2059                          Mul, Sh.getOperand(1));
2060     }
2061   }
2062
2063   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2064   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2065       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2066                      isa<ConstantSDNode>(N0.getOperand(1))))
2067     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2068                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2069                                    N0.getOperand(0), N1),
2070                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2071                                    N0.getOperand(1), N1));
2072
2073   // reassociate mul
2074   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2075   if (RMUL.getNode())
2076     return RMUL;
2077
2078   return SDValue();
2079 }
2080
2081 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2082   SDValue N0 = N->getOperand(0);
2083   SDValue N1 = N->getOperand(1);
2084   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2085   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2086   EVT VT = N->getValueType(0);
2087
2088   // fold vector ops
2089   if (VT.isVector()) {
2090     SDValue FoldedVOp = SimplifyVBinOp(N);
2091     if (FoldedVOp.getNode()) return FoldedVOp;
2092   }
2093
2094   // fold (sdiv c1, c2) -> c1/c2
2095   if (N0C && N1C && !N1C->isNullValue())
2096     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2097   // fold (sdiv X, 1) -> X
2098   if (N1C && N1C->getAPIntValue() == 1LL)
2099     return N0;
2100   // fold (sdiv X, -1) -> 0-X
2101   if (N1C && N1C->isAllOnesValue())
2102     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2103                        DAG.getConstant(0, VT), N0);
2104   // If we know the sign bits of both operands are zero, strength reduce to a
2105   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2106   if (!VT.isVector()) {
2107     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2108       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2109                          N0, N1);
2110   }
2111
2112   // fold (sdiv X, pow2) -> simple ops after legalize
2113   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2114                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2115     // If dividing by powers of two is cheap, then don't perform the following
2116     // fold.
2117     if (TLI.isPow2SDivCheap())
2118       return SDValue();
2119
2120     // Target-specific implementation of sdiv x, pow2.
2121     SDValue Res = BuildSDIVPow2(N);
2122     if (Res.getNode())
2123       return Res;
2124
2125     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2126
2127     // Splat the sign bit into the register
2128     SDValue SGN =
2129         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2130                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2131                                     getShiftAmountTy(N0.getValueType())));
2132     AddToWorklist(SGN.getNode());
2133
2134     // Add (N0 < 0) ? abs2 - 1 : 0;
2135     SDValue SRL =
2136         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2137                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2138                                     getShiftAmountTy(SGN.getValueType())));
2139     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2140     AddToWorklist(SRL.getNode());
2141     AddToWorklist(ADD.getNode());    // Divide by pow2
2142     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2143                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2144
2145     // If we're dividing by a positive value, we're done.  Otherwise, we must
2146     // negate the result.
2147     if (N1C->getAPIntValue().isNonNegative())
2148       return SRA;
2149
2150     AddToWorklist(SRA.getNode());
2151     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2152   }
2153
2154   // if integer divide is expensive and we satisfy the requirements, emit an
2155   // alternate sequence.
2156   if (N1C && !TLI.isIntDivCheap()) {
2157     SDValue Op = BuildSDIV(N);
2158     if (Op.getNode()) return Op;
2159   }
2160
2161   // undef / X -> 0
2162   if (N0.getOpcode() == ISD::UNDEF)
2163     return DAG.getConstant(0, VT);
2164   // X / undef -> undef
2165   if (N1.getOpcode() == ISD::UNDEF)
2166     return N1;
2167
2168   return SDValue();
2169 }
2170
2171 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2172   SDValue N0 = N->getOperand(0);
2173   SDValue N1 = N->getOperand(1);
2174   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2175   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2176   EVT VT = N->getValueType(0);
2177
2178   // fold vector ops
2179   if (VT.isVector()) {
2180     SDValue FoldedVOp = SimplifyVBinOp(N);
2181     if (FoldedVOp.getNode()) return FoldedVOp;
2182   }
2183
2184   // fold (udiv c1, c2) -> c1/c2
2185   if (N0C && N1C && !N1C->isNullValue())
2186     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2187   // fold (udiv x, (1 << c)) -> x >>u c
2188   if (N1C && N1C->getAPIntValue().isPowerOf2())
2189     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2190                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2191                                        getShiftAmountTy(N0.getValueType())));
2192   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2193   if (N1.getOpcode() == ISD::SHL) {
2194     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2195       if (SHC->getAPIntValue().isPowerOf2()) {
2196         EVT ADDVT = N1.getOperand(1).getValueType();
2197         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2198                                   N1.getOperand(1),
2199                                   DAG.getConstant(SHC->getAPIntValue()
2200                                                                   .logBase2(),
2201                                                   ADDVT));
2202         AddToWorklist(Add.getNode());
2203         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2204       }
2205     }
2206   }
2207   // fold (udiv x, c) -> alternate
2208   if (N1C && !TLI.isIntDivCheap()) {
2209     SDValue Op = BuildUDIV(N);
2210     if (Op.getNode()) return Op;
2211   }
2212
2213   // undef / X -> 0
2214   if (N0.getOpcode() == ISD::UNDEF)
2215     return DAG.getConstant(0, VT);
2216   // X / undef -> undef
2217   if (N1.getOpcode() == ISD::UNDEF)
2218     return N1;
2219
2220   return SDValue();
2221 }
2222
2223 SDValue DAGCombiner::visitSREM(SDNode *N) {
2224   SDValue N0 = N->getOperand(0);
2225   SDValue N1 = N->getOperand(1);
2226   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2227   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2228   EVT VT = N->getValueType(0);
2229
2230   // fold (srem c1, c2) -> c1%c2
2231   if (N0C && N1C && !N1C->isNullValue())
2232     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2233   // If we know the sign bits of both operands are zero, strength reduce to a
2234   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2235   if (!VT.isVector()) {
2236     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2237       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2238   }
2239
2240   // If X/C can be simplified by the division-by-constant logic, lower
2241   // X%C to the equivalent of X-X/C*C.
2242   if (N1C && !N1C->isNullValue()) {
2243     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2244     AddToWorklist(Div.getNode());
2245     SDValue OptimizedDiv = combine(Div.getNode());
2246     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2247       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2248                                 OptimizedDiv, N1);
2249       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2250       AddToWorklist(Mul.getNode());
2251       return Sub;
2252     }
2253   }
2254
2255   // undef % X -> 0
2256   if (N0.getOpcode() == ISD::UNDEF)
2257     return DAG.getConstant(0, VT);
2258   // X % undef -> undef
2259   if (N1.getOpcode() == ISD::UNDEF)
2260     return N1;
2261
2262   return SDValue();
2263 }
2264
2265 SDValue DAGCombiner::visitUREM(SDNode *N) {
2266   SDValue N0 = N->getOperand(0);
2267   SDValue N1 = N->getOperand(1);
2268   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2269   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2270   EVT VT = N->getValueType(0);
2271
2272   // fold (urem c1, c2) -> c1%c2
2273   if (N0C && N1C && !N1C->isNullValue())
2274     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2275   // fold (urem x, pow2) -> (and x, pow2-1)
2276   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2277     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2278                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2279   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2280   if (N1.getOpcode() == ISD::SHL) {
2281     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2282       if (SHC->getAPIntValue().isPowerOf2()) {
2283         SDValue Add =
2284           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2285                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2286                                  VT));
2287         AddToWorklist(Add.getNode());
2288         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2289       }
2290     }
2291   }
2292
2293   // If X/C can be simplified by the division-by-constant logic, lower
2294   // X%C to the equivalent of X-X/C*C.
2295   if (N1C && !N1C->isNullValue()) {
2296     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2297     AddToWorklist(Div.getNode());
2298     SDValue OptimizedDiv = combine(Div.getNode());
2299     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2300       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2301                                 OptimizedDiv, N1);
2302       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2303       AddToWorklist(Mul.getNode());
2304       return Sub;
2305     }
2306   }
2307
2308   // undef % X -> 0
2309   if (N0.getOpcode() == ISD::UNDEF)
2310     return DAG.getConstant(0, VT);
2311   // X % undef -> undef
2312   if (N1.getOpcode() == ISD::UNDEF)
2313     return N1;
2314
2315   return SDValue();
2316 }
2317
2318 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2319   SDValue N0 = N->getOperand(0);
2320   SDValue N1 = N->getOperand(1);
2321   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2322   EVT VT = N->getValueType(0);
2323   SDLoc DL(N);
2324
2325   // fold (mulhs x, 0) -> 0
2326   if (N1C && N1C->isNullValue())
2327     return N1;
2328   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2329   if (N1C && N1C->getAPIntValue() == 1)
2330     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2331                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2332                                        getShiftAmountTy(N0.getValueType())));
2333   // fold (mulhs x, undef) -> 0
2334   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2335     return DAG.getConstant(0, VT);
2336
2337   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2338   // plus a shift.
2339   if (VT.isSimple() && !VT.isVector()) {
2340     MVT Simple = VT.getSimpleVT();
2341     unsigned SimpleSize = Simple.getSizeInBits();
2342     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2343     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2344       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2345       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2346       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2347       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2348             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2349       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2350     }
2351   }
2352
2353   return SDValue();
2354 }
2355
2356 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2357   SDValue N0 = N->getOperand(0);
2358   SDValue N1 = N->getOperand(1);
2359   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2360   EVT VT = N->getValueType(0);
2361   SDLoc DL(N);
2362
2363   // fold (mulhu x, 0) -> 0
2364   if (N1C && N1C->isNullValue())
2365     return N1;
2366   // fold (mulhu x, 1) -> 0
2367   if (N1C && N1C->getAPIntValue() == 1)
2368     return DAG.getConstant(0, N0.getValueType());
2369   // fold (mulhu x, undef) -> 0
2370   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2371     return DAG.getConstant(0, VT);
2372
2373   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2374   // plus a shift.
2375   if (VT.isSimple() && !VT.isVector()) {
2376     MVT Simple = VT.getSimpleVT();
2377     unsigned SimpleSize = Simple.getSizeInBits();
2378     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2379     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2380       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2381       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2382       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2383       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2384             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2385       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2386     }
2387   }
2388
2389   return SDValue();
2390 }
2391
2392 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2393 /// give the opcodes for the two computations that are being performed. Return
2394 /// true if a simplification was made.
2395 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2396                                                 unsigned HiOp) {
2397   // If the high half is not needed, just compute the low half.
2398   bool HiExists = N->hasAnyUseOfValue(1);
2399   if (!HiExists &&
2400       (!LegalOperations ||
2401        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2402     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2403     return CombineTo(N, Res, Res);
2404   }
2405
2406   // If the low half is not needed, just compute the high half.
2407   bool LoExists = N->hasAnyUseOfValue(0);
2408   if (!LoExists &&
2409       (!LegalOperations ||
2410        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2411     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2412     return CombineTo(N, Res, Res);
2413   }
2414
2415   // If both halves are used, return as it is.
2416   if (LoExists && HiExists)
2417     return SDValue();
2418
2419   // If the two computed results can be simplified separately, separate them.
2420   if (LoExists) {
2421     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2422     AddToWorklist(Lo.getNode());
2423     SDValue LoOpt = combine(Lo.getNode());
2424     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2425         (!LegalOperations ||
2426          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2427       return CombineTo(N, LoOpt, LoOpt);
2428   }
2429
2430   if (HiExists) {
2431     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2432     AddToWorklist(Hi.getNode());
2433     SDValue HiOpt = combine(Hi.getNode());
2434     if (HiOpt.getNode() && HiOpt != Hi &&
2435         (!LegalOperations ||
2436          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2437       return CombineTo(N, HiOpt, HiOpt);
2438   }
2439
2440   return SDValue();
2441 }
2442
2443 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2444   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2445   if (Res.getNode()) return Res;
2446
2447   EVT VT = N->getValueType(0);
2448   SDLoc DL(N);
2449
2450   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2451   // plus a shift.
2452   if (VT.isSimple() && !VT.isVector()) {
2453     MVT Simple = VT.getSimpleVT();
2454     unsigned SimpleSize = Simple.getSizeInBits();
2455     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2456     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2457       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2458       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2459       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2460       // Compute the high part as N1.
2461       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2462             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2463       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2464       // Compute the low part as N0.
2465       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2466       return CombineTo(N, Lo, Hi);
2467     }
2468   }
2469
2470   return SDValue();
2471 }
2472
2473 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2474   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2475   if (Res.getNode()) return Res;
2476
2477   EVT VT = N->getValueType(0);
2478   SDLoc DL(N);
2479
2480   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2481   // plus a shift.
2482   if (VT.isSimple() && !VT.isVector()) {
2483     MVT Simple = VT.getSimpleVT();
2484     unsigned SimpleSize = Simple.getSizeInBits();
2485     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2486     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2487       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2488       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2489       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2490       // Compute the high part as N1.
2491       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2492             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2493       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2494       // Compute the low part as N0.
2495       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2496       return CombineTo(N, Lo, Hi);
2497     }
2498   }
2499
2500   return SDValue();
2501 }
2502
2503 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2504   // (smulo x, 2) -> (saddo x, x)
2505   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2506     if (C2->getAPIntValue() == 2)
2507       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2508                          N->getOperand(0), N->getOperand(0));
2509
2510   return SDValue();
2511 }
2512
2513 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2514   // (umulo x, 2) -> (uaddo x, x)
2515   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2516     if (C2->getAPIntValue() == 2)
2517       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2518                          N->getOperand(0), N->getOperand(0));
2519
2520   return SDValue();
2521 }
2522
2523 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2524   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2525   if (Res.getNode()) return Res;
2526
2527   return SDValue();
2528 }
2529
2530 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2531   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2532   if (Res.getNode()) return Res;
2533
2534   return SDValue();
2535 }
2536
2537 /// If this is a binary operator with two operands of the same opcode, try to
2538 /// simplify it.
2539 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2540   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2541   EVT VT = N0.getValueType();
2542   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2543
2544   // Bail early if none of these transforms apply.
2545   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2546
2547   // For each of OP in AND/OR/XOR:
2548   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2549   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2550   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2551   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2552   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2553   //
2554   // do not sink logical op inside of a vector extend, since it may combine
2555   // into a vsetcc.
2556   EVT Op0VT = N0.getOperand(0).getValueType();
2557   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2558        N0.getOpcode() == ISD::SIGN_EXTEND ||
2559        N0.getOpcode() == ISD::BSWAP ||
2560        // Avoid infinite looping with PromoteIntBinOp.
2561        (N0.getOpcode() == ISD::ANY_EXTEND &&
2562         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2563        (N0.getOpcode() == ISD::TRUNCATE &&
2564         (!TLI.isZExtFree(VT, Op0VT) ||
2565          !TLI.isTruncateFree(Op0VT, VT)) &&
2566         TLI.isTypeLegal(Op0VT))) &&
2567       !VT.isVector() &&
2568       Op0VT == N1.getOperand(0).getValueType() &&
2569       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2570     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2571                                  N0.getOperand(0).getValueType(),
2572                                  N0.getOperand(0), N1.getOperand(0));
2573     AddToWorklist(ORNode.getNode());
2574     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2575   }
2576
2577   // For each of OP in SHL/SRL/SRA/AND...
2578   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2579   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2580   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2581   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2582        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2583       N0.getOperand(1) == N1.getOperand(1)) {
2584     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2585                                  N0.getOperand(0).getValueType(),
2586                                  N0.getOperand(0), N1.getOperand(0));
2587     AddToWorklist(ORNode.getNode());
2588     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2589                        ORNode, N0.getOperand(1));
2590   }
2591
2592   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2593   // Only perform this optimization after type legalization and before
2594   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2595   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2596   // we don't want to undo this promotion.
2597   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2598   // on scalars.
2599   if ((N0.getOpcode() == ISD::BITCAST ||
2600        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2601       Level == AfterLegalizeTypes) {
2602     SDValue In0 = N0.getOperand(0);
2603     SDValue In1 = N1.getOperand(0);
2604     EVT In0Ty = In0.getValueType();
2605     EVT In1Ty = In1.getValueType();
2606     SDLoc DL(N);
2607     // If both incoming values are integers, and the original types are the
2608     // same.
2609     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2610       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2611       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2612       AddToWorklist(Op.getNode());
2613       return BC;
2614     }
2615   }
2616
2617   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2618   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2619   // If both shuffles use the same mask, and both shuffle within a single
2620   // vector, then it is worthwhile to move the swizzle after the operation.
2621   // The type-legalizer generates this pattern when loading illegal
2622   // vector types from memory. In many cases this allows additional shuffle
2623   // optimizations.
2624   // There are other cases where moving the shuffle after the xor/and/or
2625   // is profitable even if shuffles don't perform a swizzle.
2626   // If both shuffles use the same mask, and both shuffles have the same first
2627   // or second operand, then it might still be profitable to move the shuffle
2628   // after the xor/and/or operation.
2629   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2630     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2631     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2632
2633     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2634            "Inputs to shuffles are not the same type");
2635
2636     // Check that both shuffles use the same mask. The masks are known to be of
2637     // the same length because the result vector type is the same.
2638     // Check also that shuffles have only one use to avoid introducing extra
2639     // instructions.
2640     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2641         SVN0->getMask().equals(SVN1->getMask())) {
2642       SDValue ShOp = N0->getOperand(1);
2643
2644       // Don't try to fold this node if it requires introducing a
2645       // build vector of all zeros that might be illegal at this stage.
2646       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2647         if (!LegalTypes)
2648           ShOp = DAG.getConstant(0, VT);
2649         else
2650           ShOp = SDValue();
2651       }
2652
2653       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2654       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2655       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2656       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2657         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2658                                       N0->getOperand(0), N1->getOperand(0));
2659         AddToWorklist(NewNode.getNode());
2660         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2661                                     &SVN0->getMask()[0]);
2662       }
2663
2664       // Don't try to fold this node if it requires introducing a
2665       // build vector of all zeros that might be illegal at this stage.
2666       ShOp = N0->getOperand(0);
2667       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2668         if (!LegalTypes)
2669           ShOp = DAG.getConstant(0, VT);
2670         else
2671           ShOp = SDValue();
2672       }
2673
2674       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2675       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2676       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2677       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2678         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2679                                       N0->getOperand(1), N1->getOperand(1));
2680         AddToWorklist(NewNode.getNode());
2681         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2682                                     &SVN0->getMask()[0]);
2683       }
2684     }
2685   }
2686
2687   return SDValue();
2688 }
2689
2690 SDValue DAGCombiner::visitAND(SDNode *N) {
2691   SDValue N0 = N->getOperand(0);
2692   SDValue N1 = N->getOperand(1);
2693   SDValue LL, LR, RL, RR, CC0, CC1;
2694   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2695   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2696   EVT VT = N1.getValueType();
2697   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2698
2699   // fold vector ops
2700   if (VT.isVector()) {
2701     SDValue FoldedVOp = SimplifyVBinOp(N);
2702     if (FoldedVOp.getNode()) return FoldedVOp;
2703
2704     // fold (and x, 0) -> 0, vector edition
2705     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2706       // do not return N0, because undef node may exist in N0
2707       return DAG.getConstant(
2708           APInt::getNullValue(
2709               N0.getValueType().getScalarType().getSizeInBits()),
2710           N0.getValueType());
2711     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2712       // do not return N1, because undef node may exist in N1
2713       return DAG.getConstant(
2714           APInt::getNullValue(
2715               N1.getValueType().getScalarType().getSizeInBits()),
2716           N1.getValueType());
2717
2718     // fold (and x, -1) -> x, vector edition
2719     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2720       return N1;
2721     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2722       return N0;
2723   }
2724
2725   // fold (and x, undef) -> 0
2726   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2727     return DAG.getConstant(0, VT);
2728   // fold (and c1, c2) -> c1&c2
2729   if (N0C && N1C)
2730     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2731   // canonicalize constant to RHS
2732   if (N0C && !N1C)
2733     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2734   // fold (and x, -1) -> x
2735   if (N1C && N1C->isAllOnesValue())
2736     return N0;
2737   // if (and x, c) is known to be zero, return 0
2738   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2739                                    APInt::getAllOnesValue(BitWidth)))
2740     return DAG.getConstant(0, VT);
2741   // reassociate and
2742   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2743   if (RAND.getNode())
2744     return RAND;
2745   // fold (and (or x, C), D) -> D if (C & D) == D
2746   if (N1C && N0.getOpcode() == ISD::OR)
2747     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2748       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2749         return N1;
2750   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2751   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2752     SDValue N0Op0 = N0.getOperand(0);
2753     APInt Mask = ~N1C->getAPIntValue();
2754     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2755     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2756       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2757                                  N0.getValueType(), N0Op0);
2758
2759       // Replace uses of the AND with uses of the Zero extend node.
2760       CombineTo(N, Zext);
2761
2762       // We actually want to replace all uses of the any_extend with the
2763       // zero_extend, to avoid duplicating things.  This will later cause this
2764       // AND to be folded.
2765       CombineTo(N0.getNode(), Zext);
2766       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2767     }
2768   }
2769   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2770   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2771   // already be zero by virtue of the width of the base type of the load.
2772   //
2773   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2774   // more cases.
2775   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2776        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2777       N0.getOpcode() == ISD::LOAD) {
2778     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2779                                          N0 : N0.getOperand(0) );
2780
2781     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2782     // This can be a pure constant or a vector splat, in which case we treat the
2783     // vector as a scalar and use the splat value.
2784     APInt Constant = APInt::getNullValue(1);
2785     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2786       Constant = C->getAPIntValue();
2787     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2788       APInt SplatValue, SplatUndef;
2789       unsigned SplatBitSize;
2790       bool HasAnyUndefs;
2791       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2792                                              SplatBitSize, HasAnyUndefs);
2793       if (IsSplat) {
2794         // Undef bits can contribute to a possible optimisation if set, so
2795         // set them.
2796         SplatValue |= SplatUndef;
2797
2798         // The splat value may be something like "0x00FFFFFF", which means 0 for
2799         // the first vector value and FF for the rest, repeating. We need a mask
2800         // that will apply equally to all members of the vector, so AND all the
2801         // lanes of the constant together.
2802         EVT VT = Vector->getValueType(0);
2803         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2804
2805         // If the splat value has been compressed to a bitlength lower
2806         // than the size of the vector lane, we need to re-expand it to
2807         // the lane size.
2808         if (BitWidth > SplatBitSize)
2809           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2810                SplatBitSize < BitWidth;
2811                SplatBitSize = SplatBitSize * 2)
2812             SplatValue |= SplatValue.shl(SplatBitSize);
2813
2814         Constant = APInt::getAllOnesValue(BitWidth);
2815         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2816           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2817       }
2818     }
2819
2820     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2821     // actually legal and isn't going to get expanded, else this is a false
2822     // optimisation.
2823     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2824                                                     Load->getValueType(0),
2825                                                     Load->getMemoryVT());
2826
2827     // Resize the constant to the same size as the original memory access before
2828     // extension. If it is still the AllOnesValue then this AND is completely
2829     // unneeded.
2830     Constant =
2831       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2832
2833     bool B;
2834     switch (Load->getExtensionType()) {
2835     default: B = false; break;
2836     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2837     case ISD::ZEXTLOAD:
2838     case ISD::NON_EXTLOAD: B = true; break;
2839     }
2840
2841     if (B && Constant.isAllOnesValue()) {
2842       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2843       // preserve semantics once we get rid of the AND.
2844       SDValue NewLoad(Load, 0);
2845       if (Load->getExtensionType() == ISD::EXTLOAD) {
2846         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2847                               Load->getValueType(0), SDLoc(Load),
2848                               Load->getChain(), Load->getBasePtr(),
2849                               Load->getOffset(), Load->getMemoryVT(),
2850                               Load->getMemOperand());
2851         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2852         if (Load->getNumValues() == 3) {
2853           // PRE/POST_INC loads have 3 values.
2854           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2855                            NewLoad.getValue(2) };
2856           CombineTo(Load, To, 3, true);
2857         } else {
2858           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2859         }
2860       }
2861
2862       // Fold the AND away, taking care not to fold to the old load node if we
2863       // replaced it.
2864       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2865
2866       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2867     }
2868   }
2869   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2870   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2871     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2872     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2873
2874     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2875         LL.getValueType().isInteger()) {
2876       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2877       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2878         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2879                                      LR.getValueType(), LL, RL);
2880         AddToWorklist(ORNode.getNode());
2881         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2882       }
2883       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2884       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2885         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2886                                       LR.getValueType(), LL, RL);
2887         AddToWorklist(ANDNode.getNode());
2888         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2889       }
2890       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2891       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2892         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2893                                      LR.getValueType(), LL, RL);
2894         AddToWorklist(ORNode.getNode());
2895         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2896       }
2897     }
2898     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2899     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2900         Op0 == Op1 && LL.getValueType().isInteger() &&
2901       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2902                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2903                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2904                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2905       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2906                                     LL, DAG.getConstant(1, LL.getValueType()));
2907       AddToWorklist(ADDNode.getNode());
2908       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2909                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2910     }
2911     // canonicalize equivalent to ll == rl
2912     if (LL == RR && LR == RL) {
2913       Op1 = ISD::getSetCCSwappedOperands(Op1);
2914       std::swap(RL, RR);
2915     }
2916     if (LL == RL && LR == RR) {
2917       bool isInteger = LL.getValueType().isInteger();
2918       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2919       if (Result != ISD::SETCC_INVALID &&
2920           (!LegalOperations ||
2921            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2922             TLI.isOperationLegal(ISD::SETCC,
2923                             getSetCCResultType(N0.getSimpleValueType())))))
2924         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2925                             LL, LR, Result);
2926     }
2927   }
2928
2929   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2930   if (N0.getOpcode() == N1.getOpcode()) {
2931     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2932     if (Tmp.getNode()) return Tmp;
2933   }
2934
2935   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2936   // fold (and (sra)) -> (and (srl)) when possible.
2937   if (!VT.isVector() &&
2938       SimplifyDemandedBits(SDValue(N, 0)))
2939     return SDValue(N, 0);
2940
2941   // fold (zext_inreg (extload x)) -> (zextload x)
2942   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2943     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2944     EVT MemVT = LN0->getMemoryVT();
2945     // If we zero all the possible extended bits, then we can turn this into
2946     // a zextload if we are running before legalize or the operation is legal.
2947     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2948     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2949                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2950         ((!LegalOperations && !LN0->isVolatile()) ||
2951          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2952       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2953                                        LN0->getChain(), LN0->getBasePtr(),
2954                                        MemVT, LN0->getMemOperand());
2955       AddToWorklist(N);
2956       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2957       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2958     }
2959   }
2960   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2961   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2962       N0.hasOneUse()) {
2963     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2964     EVT MemVT = LN0->getMemoryVT();
2965     // If we zero all the possible extended bits, then we can turn this into
2966     // a zextload if we are running before legalize or the operation is legal.
2967     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2968     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2969                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2970         ((!LegalOperations && !LN0->isVolatile()) ||
2971          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2972       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2973                                        LN0->getChain(), LN0->getBasePtr(),
2974                                        MemVT, LN0->getMemOperand());
2975       AddToWorklist(N);
2976       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2977       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2978     }
2979   }
2980
2981   // fold (and (load x), 255) -> (zextload x, i8)
2982   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2983   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2984   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2985               (N0.getOpcode() == ISD::ANY_EXTEND &&
2986                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2987     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2988     LoadSDNode *LN0 = HasAnyExt
2989       ? cast<LoadSDNode>(N0.getOperand(0))
2990       : cast<LoadSDNode>(N0);
2991     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2992         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2993       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2994       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2995         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2996         EVT LoadedVT = LN0->getMemoryVT();
2997         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2998
2999         if (ExtVT == LoadedVT &&
3000             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3001                                                     ExtVT))) {
3002
3003           SDValue NewLoad =
3004             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3005                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3006                            LN0->getMemOperand());
3007           AddToWorklist(N);
3008           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3009           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3010         }
3011
3012         // Do not change the width of a volatile load.
3013         // Do not generate loads of non-round integer types since these can
3014         // be expensive (and would be wrong if the type is not byte sized).
3015         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3016             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3017                                                     ExtVT))) {
3018           EVT PtrType = LN0->getOperand(1).getValueType();
3019
3020           unsigned Alignment = LN0->getAlignment();
3021           SDValue NewPtr = LN0->getBasePtr();
3022
3023           // For big endian targets, we need to add an offset to the pointer
3024           // to load the correct bytes.  For little endian systems, we merely
3025           // need to read fewer bytes from the same pointer.
3026           if (TLI.isBigEndian()) {
3027             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3028             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3029             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3030             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3031                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3032             Alignment = MinAlign(Alignment, PtrOff);
3033           }
3034
3035           AddToWorklist(NewPtr.getNode());
3036
3037           SDValue Load =
3038             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3039                            LN0->getChain(), NewPtr,
3040                            LN0->getPointerInfo(),
3041                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3042                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3043           AddToWorklist(N);
3044           CombineTo(LN0, Load, Load.getValue(1));
3045           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3046         }
3047       }
3048     }
3049   }
3050
3051   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3052       VT.getSizeInBits() <= 64) {
3053     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3054       APInt ADDC = ADDI->getAPIntValue();
3055       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3056         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3057         // immediate for an add, but it is legal if its top c2 bits are set,
3058         // transform the ADD so the immediate doesn't need to be materialized
3059         // in a register.
3060         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3061           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3062                                              SRLI->getZExtValue());
3063           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3064             ADDC |= Mask;
3065             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3066               SDValue NewAdd =
3067                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3068                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3069               CombineTo(N0.getNode(), NewAdd);
3070               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3071             }
3072           }
3073         }
3074       }
3075     }
3076   }
3077
3078   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3079   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3080     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3081                                        N0.getOperand(1), false);
3082     if (BSwap.getNode())
3083       return BSwap;
3084   }
3085
3086   return SDValue();
3087 }
3088
3089 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3090 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3091                                         bool DemandHighBits) {
3092   if (!LegalOperations)
3093     return SDValue();
3094
3095   EVT VT = N->getValueType(0);
3096   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3097     return SDValue();
3098   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3099     return SDValue();
3100
3101   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3102   bool LookPassAnd0 = false;
3103   bool LookPassAnd1 = false;
3104   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3105       std::swap(N0, N1);
3106   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3107       std::swap(N0, N1);
3108   if (N0.getOpcode() == ISD::AND) {
3109     if (!N0.getNode()->hasOneUse())
3110       return SDValue();
3111     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3112     if (!N01C || N01C->getZExtValue() != 0xFF00)
3113       return SDValue();
3114     N0 = N0.getOperand(0);
3115     LookPassAnd0 = true;
3116   }
3117
3118   if (N1.getOpcode() == ISD::AND) {
3119     if (!N1.getNode()->hasOneUse())
3120       return SDValue();
3121     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3122     if (!N11C || N11C->getZExtValue() != 0xFF)
3123       return SDValue();
3124     N1 = N1.getOperand(0);
3125     LookPassAnd1 = true;
3126   }
3127
3128   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3129     std::swap(N0, N1);
3130   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3131     return SDValue();
3132   if (!N0.getNode()->hasOneUse() ||
3133       !N1.getNode()->hasOneUse())
3134     return SDValue();
3135
3136   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3137   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3138   if (!N01C || !N11C)
3139     return SDValue();
3140   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3141     return SDValue();
3142
3143   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3144   SDValue N00 = N0->getOperand(0);
3145   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3146     if (!N00.getNode()->hasOneUse())
3147       return SDValue();
3148     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3149     if (!N001C || N001C->getZExtValue() != 0xFF)
3150       return SDValue();
3151     N00 = N00.getOperand(0);
3152     LookPassAnd0 = true;
3153   }
3154
3155   SDValue N10 = N1->getOperand(0);
3156   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3157     if (!N10.getNode()->hasOneUse())
3158       return SDValue();
3159     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3160     if (!N101C || N101C->getZExtValue() != 0xFF00)
3161       return SDValue();
3162     N10 = N10.getOperand(0);
3163     LookPassAnd1 = true;
3164   }
3165
3166   if (N00 != N10)
3167     return SDValue();
3168
3169   // Make sure everything beyond the low halfword gets set to zero since the SRL
3170   // 16 will clear the top bits.
3171   unsigned OpSizeInBits = VT.getSizeInBits();
3172   if (DemandHighBits && OpSizeInBits > 16) {
3173     // If the left-shift isn't masked out then the only way this is a bswap is
3174     // if all bits beyond the low 8 are 0. In that case the entire pattern
3175     // reduces to a left shift anyway: leave it for other parts of the combiner.
3176     if (!LookPassAnd0)
3177       return SDValue();
3178
3179     // However, if the right shift isn't masked out then it might be because
3180     // it's not needed. See if we can spot that too.
3181     if (!LookPassAnd1 &&
3182         !DAG.MaskedValueIsZero(
3183             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3184       return SDValue();
3185   }
3186
3187   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3188   if (OpSizeInBits > 16)
3189     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3190                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3191   return Res;
3192 }
3193
3194 /// Return true if the specified node is an element that makes up a 32-bit
3195 /// packed halfword byteswap.
3196 /// ((x & 0x000000ff) << 8) |
3197 /// ((x & 0x0000ff00) >> 8) |
3198 /// ((x & 0x00ff0000) << 8) |
3199 /// ((x & 0xff000000) >> 8)
3200 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3201   if (!N.getNode()->hasOneUse())
3202     return false;
3203
3204   unsigned Opc = N.getOpcode();
3205   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3206     return false;
3207
3208   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3209   if (!N1C)
3210     return false;
3211
3212   unsigned Num;
3213   switch (N1C->getZExtValue()) {
3214   default:
3215     return false;
3216   case 0xFF:       Num = 0; break;
3217   case 0xFF00:     Num = 1; break;
3218   case 0xFF0000:   Num = 2; break;
3219   case 0xFF000000: Num = 3; break;
3220   }
3221
3222   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3223   SDValue N0 = N.getOperand(0);
3224   if (Opc == ISD::AND) {
3225     if (Num == 0 || Num == 2) {
3226       // (x >> 8) & 0xff
3227       // (x >> 8) & 0xff0000
3228       if (N0.getOpcode() != ISD::SRL)
3229         return false;
3230       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3231       if (!C || C->getZExtValue() != 8)
3232         return false;
3233     } else {
3234       // (x << 8) & 0xff00
3235       // (x << 8) & 0xff000000
3236       if (N0.getOpcode() != ISD::SHL)
3237         return false;
3238       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3239       if (!C || C->getZExtValue() != 8)
3240         return false;
3241     }
3242   } else if (Opc == ISD::SHL) {
3243     // (x & 0xff) << 8
3244     // (x & 0xff0000) << 8
3245     if (Num != 0 && Num != 2)
3246       return false;
3247     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3248     if (!C || C->getZExtValue() != 8)
3249       return false;
3250   } else { // Opc == ISD::SRL
3251     // (x & 0xff00) >> 8
3252     // (x & 0xff000000) >> 8
3253     if (Num != 1 && Num != 3)
3254       return false;
3255     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3256     if (!C || C->getZExtValue() != 8)
3257       return false;
3258   }
3259
3260   if (Parts[Num])
3261     return false;
3262
3263   Parts[Num] = N0.getOperand(0).getNode();
3264   return true;
3265 }
3266
3267 /// Match a 32-bit packed halfword bswap. That is
3268 /// ((x & 0x000000ff) << 8) |
3269 /// ((x & 0x0000ff00) >> 8) |
3270 /// ((x & 0x00ff0000) << 8) |
3271 /// ((x & 0xff000000) >> 8)
3272 /// => (rotl (bswap x), 16)
3273 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3274   if (!LegalOperations)
3275     return SDValue();
3276
3277   EVT VT = N->getValueType(0);
3278   if (VT != MVT::i32)
3279     return SDValue();
3280   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3281     return SDValue();
3282
3283   // Look for either
3284   // (or (or (and), (and)), (or (and), (and)))
3285   // (or (or (or (and), (and)), (and)), (and))
3286   if (N0.getOpcode() != ISD::OR)
3287     return SDValue();
3288   SDValue N00 = N0.getOperand(0);
3289   SDValue N01 = N0.getOperand(1);
3290   SDNode *Parts[4] = {};
3291
3292   if (N1.getOpcode() == ISD::OR &&
3293       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3294     // (or (or (and), (and)), (or (and), (and)))
3295     SDValue N000 = N00.getOperand(0);
3296     if (!isBSwapHWordElement(N000, Parts))
3297       return SDValue();
3298
3299     SDValue N001 = N00.getOperand(1);
3300     if (!isBSwapHWordElement(N001, Parts))
3301       return SDValue();
3302     SDValue N010 = N01.getOperand(0);
3303     if (!isBSwapHWordElement(N010, Parts))
3304       return SDValue();
3305     SDValue N011 = N01.getOperand(1);
3306     if (!isBSwapHWordElement(N011, Parts))
3307       return SDValue();
3308   } else {
3309     // (or (or (or (and), (and)), (and)), (and))
3310     if (!isBSwapHWordElement(N1, Parts))
3311       return SDValue();
3312     if (!isBSwapHWordElement(N01, Parts))
3313       return SDValue();
3314     if (N00.getOpcode() != ISD::OR)
3315       return SDValue();
3316     SDValue N000 = N00.getOperand(0);
3317     if (!isBSwapHWordElement(N000, Parts))
3318       return SDValue();
3319     SDValue N001 = N00.getOperand(1);
3320     if (!isBSwapHWordElement(N001, Parts))
3321       return SDValue();
3322   }
3323
3324   // Make sure the parts are all coming from the same node.
3325   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3326     return SDValue();
3327
3328   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3329                               SDValue(Parts[0],0));
3330
3331   // Result of the bswap should be rotated by 16. If it's not legal, then
3332   // do  (x << 16) | (x >> 16).
3333   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3334   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3335     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3336   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3337     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3338   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3339                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3340                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3341 }
3342
3343 SDValue DAGCombiner::visitOR(SDNode *N) {
3344   SDValue N0 = N->getOperand(0);
3345   SDValue N1 = N->getOperand(1);
3346   SDValue LL, LR, RL, RR, CC0, CC1;
3347   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3348   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3349   EVT VT = N1.getValueType();
3350
3351   // fold vector ops
3352   if (VT.isVector()) {
3353     SDValue FoldedVOp = SimplifyVBinOp(N);
3354     if (FoldedVOp.getNode()) return FoldedVOp;
3355
3356     // fold (or x, 0) -> x, vector edition
3357     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3358       return N1;
3359     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3360       return N0;
3361
3362     // fold (or x, -1) -> -1, vector edition
3363     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3364       // do not return N0, because undef node may exist in N0
3365       return DAG.getConstant(
3366           APInt::getAllOnesValue(
3367               N0.getValueType().getScalarType().getSizeInBits()),
3368           N0.getValueType());
3369     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3370       // do not return N1, because undef node may exist in N1
3371       return DAG.getConstant(
3372           APInt::getAllOnesValue(
3373               N1.getValueType().getScalarType().getSizeInBits()),
3374           N1.getValueType());
3375
3376     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3377     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3378     // Do this only if the resulting shuffle is legal.
3379     if (isa<ShuffleVectorSDNode>(N0) &&
3380         isa<ShuffleVectorSDNode>(N1) &&
3381         // Avoid folding a node with illegal type.
3382         TLI.isTypeLegal(VT) &&
3383         N0->getOperand(1) == N1->getOperand(1) &&
3384         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3385       bool CanFold = true;
3386       unsigned NumElts = VT.getVectorNumElements();
3387       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3388       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3389       // We construct two shuffle masks:
3390       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3391       // and N1 as the second operand.
3392       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3393       // and N0 as the second operand.
3394       // We do this because OR is commutable and therefore there might be
3395       // two ways to fold this node into a shuffle.
3396       SmallVector<int,4> Mask1;
3397       SmallVector<int,4> Mask2;
3398
3399       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3400         int M0 = SV0->getMaskElt(i);
3401         int M1 = SV1->getMaskElt(i);
3402
3403         // Both shuffle indexes are undef. Propagate Undef.
3404         if (M0 < 0 && M1 < 0) {
3405           Mask1.push_back(M0);
3406           Mask2.push_back(M0);
3407           continue;
3408         }
3409
3410         if (M0 < 0 || M1 < 0 ||
3411             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3412             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3413           CanFold = false;
3414           break;
3415         }
3416
3417         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3418         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3419       }
3420
3421       if (CanFold) {
3422         // Fold this sequence only if the resulting shuffle is 'legal'.
3423         if (TLI.isShuffleMaskLegal(Mask1, VT))
3424           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3425                                       N1->getOperand(0), &Mask1[0]);
3426         if (TLI.isShuffleMaskLegal(Mask2, VT))
3427           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3428                                       N0->getOperand(0), &Mask2[0]);
3429       }
3430     }
3431   }
3432
3433   // fold (or x, undef) -> -1
3434   if (!LegalOperations &&
3435       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3436     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3437     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3438   }
3439   // fold (or c1, c2) -> c1|c2
3440   if (N0C && N1C)
3441     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3442   // canonicalize constant to RHS
3443   if (N0C && !N1C)
3444     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3445   // fold (or x, 0) -> x
3446   if (N1C && N1C->isNullValue())
3447     return N0;
3448   // fold (or x, -1) -> -1
3449   if (N1C && N1C->isAllOnesValue())
3450     return N1;
3451   // fold (or x, c) -> c iff (x & ~c) == 0
3452   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3453     return N1;
3454
3455   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3456   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3457   if (BSwap.getNode())
3458     return BSwap;
3459   BSwap = MatchBSwapHWordLow(N, N0, N1);
3460   if (BSwap.getNode())
3461     return BSwap;
3462
3463   // reassociate or
3464   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3465   if (ROR.getNode())
3466     return ROR;
3467   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3468   // iff (c1 & c2) == 0.
3469   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3470              isa<ConstantSDNode>(N0.getOperand(1))) {
3471     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3472     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3473       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3474         return DAG.getNode(
3475             ISD::AND, SDLoc(N), VT,
3476             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3477       return SDValue();
3478     }
3479   }
3480   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3481   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3482     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3483     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3484
3485     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3486         LL.getValueType().isInteger()) {
3487       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3488       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3489       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3490           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3491         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3492                                      LR.getValueType(), LL, RL);
3493         AddToWorklist(ORNode.getNode());
3494         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3495       }
3496       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3497       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3498       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3499           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3500         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3501                                       LR.getValueType(), LL, RL);
3502         AddToWorklist(ANDNode.getNode());
3503         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3504       }
3505     }
3506     // canonicalize equivalent to ll == rl
3507     if (LL == RR && LR == RL) {
3508       Op1 = ISD::getSetCCSwappedOperands(Op1);
3509       std::swap(RL, RR);
3510     }
3511     if (LL == RL && LR == RR) {
3512       bool isInteger = LL.getValueType().isInteger();
3513       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3514       if (Result != ISD::SETCC_INVALID &&
3515           (!LegalOperations ||
3516            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3517             TLI.isOperationLegal(ISD::SETCC,
3518               getSetCCResultType(N0.getValueType())))))
3519         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3520                             LL, LR, Result);
3521     }
3522   }
3523
3524   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3525   if (N0.getOpcode() == N1.getOpcode()) {
3526     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3527     if (Tmp.getNode()) return Tmp;
3528   }
3529
3530   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3531   if (N0.getOpcode() == ISD::AND &&
3532       N1.getOpcode() == ISD::AND &&
3533       N0.getOperand(1).getOpcode() == ISD::Constant &&
3534       N1.getOperand(1).getOpcode() == ISD::Constant &&
3535       // Don't increase # computations.
3536       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3537     // We can only do this xform if we know that bits from X that are set in C2
3538     // but not in C1 are already zero.  Likewise for Y.
3539     const APInt &LHSMask =
3540       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3541     const APInt &RHSMask =
3542       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3543
3544     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3545         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3546       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3547                               N0.getOperand(0), N1.getOperand(0));
3548       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3549                          DAG.getConstant(LHSMask | RHSMask, VT));
3550     }
3551   }
3552
3553   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3554   if (N0.getOpcode() == ISD::AND &&
3555       N1.getOpcode() == ISD::AND &&
3556       N0.getOperand(0) == N1.getOperand(0) &&
3557       // Don't increase # computations.
3558       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3559     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3560                             N0.getOperand(1), N1.getOperand(1));
3561     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), X);
3562   }
3563
3564   // See if this is some rotate idiom.
3565   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3566     return SDValue(Rot, 0);
3567
3568   // Simplify the operands using demanded-bits information.
3569   if (!VT.isVector() &&
3570       SimplifyDemandedBits(SDValue(N, 0)))
3571     return SDValue(N, 0);
3572
3573   return SDValue();
3574 }
3575
3576 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3577 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3578   if (Op.getOpcode() == ISD::AND) {
3579     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3580       Mask = Op.getOperand(1);
3581       Op = Op.getOperand(0);
3582     } else {
3583       return false;
3584     }
3585   }
3586
3587   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3588     Shift = Op;
3589     return true;
3590   }
3591
3592   return false;
3593 }
3594
3595 // Return true if we can prove that, whenever Neg and Pos are both in the
3596 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3597 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3598 //
3599 //     (or (shift1 X, Neg), (shift2 X, Pos))
3600 //
3601 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3602 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3603 // to consider shift amounts with defined behavior.
3604 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3605   // If OpSize is a power of 2 then:
3606   //
3607   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3608   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3609   //
3610   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3611   // for the stronger condition:
3612   //
3613   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3614   //
3615   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3616   // we can just replace Neg with Neg' for the rest of the function.
3617   //
3618   // In other cases we check for the even stronger condition:
3619   //
3620   //     Neg == OpSize - Pos                                    [B]
3621   //
3622   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3623   // behavior if Pos == 0 (and consequently Neg == OpSize).
3624   //
3625   // We could actually use [A] whenever OpSize is a power of 2, but the
3626   // only extra cases that it would match are those uninteresting ones
3627   // where Neg and Pos are never in range at the same time.  E.g. for
3628   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3629   // as well as (sub 32, Pos), but:
3630   //
3631   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3632   //
3633   // always invokes undefined behavior for 32-bit X.
3634   //
3635   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3636   unsigned MaskLoBits = 0;
3637   if (Neg.getOpcode() == ISD::AND &&
3638       isPowerOf2_64(OpSize) &&
3639       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3640       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3641     Neg = Neg.getOperand(0);
3642     MaskLoBits = Log2_64(OpSize);
3643   }
3644
3645   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3646   if (Neg.getOpcode() != ISD::SUB)
3647     return 0;
3648   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3649   if (!NegC)
3650     return 0;
3651   SDValue NegOp1 = Neg.getOperand(1);
3652
3653   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3654   // Pos'.  The truncation is redundant for the purpose of the equality.
3655   if (MaskLoBits &&
3656       Pos.getOpcode() == ISD::AND &&
3657       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3658       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3659     Pos = Pos.getOperand(0);
3660
3661   // The condition we need is now:
3662   //
3663   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3664   //
3665   // If NegOp1 == Pos then we need:
3666   //
3667   //              OpSize & Mask == NegC & Mask
3668   //
3669   // (because "x & Mask" is a truncation and distributes through subtraction).
3670   APInt Width;
3671   if (Pos == NegOp1)
3672     Width = NegC->getAPIntValue();
3673   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3674   // Then the condition we want to prove becomes:
3675   //
3676   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3677   //
3678   // which, again because "x & Mask" is a truncation, becomes:
3679   //
3680   //                NegC & Mask == (OpSize - PosC) & Mask
3681   //              OpSize & Mask == (NegC + PosC) & Mask
3682   else if (Pos.getOpcode() == ISD::ADD &&
3683            Pos.getOperand(0) == NegOp1 &&
3684            Pos.getOperand(1).getOpcode() == ISD::Constant)
3685     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3686              NegC->getAPIntValue());
3687   else
3688     return false;
3689
3690   // Now we just need to check that OpSize & Mask == Width & Mask.
3691   if (MaskLoBits)
3692     // Opsize & Mask is 0 since Mask is Opsize - 1.
3693     return Width.getLoBits(MaskLoBits) == 0;
3694   return Width == OpSize;
3695 }
3696
3697 // A subroutine of MatchRotate used once we have found an OR of two opposite
3698 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3699 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3700 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3701 // Neg with outer conversions stripped away.
3702 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3703                                        SDValue Neg, SDValue InnerPos,
3704                                        SDValue InnerNeg, unsigned PosOpcode,
3705                                        unsigned NegOpcode, SDLoc DL) {
3706   // fold (or (shl x, (*ext y)),
3707   //          (srl x, (*ext (sub 32, y)))) ->
3708   //   (rotl x, y) or (rotr x, (sub 32, y))
3709   //
3710   // fold (or (shl x, (*ext (sub 32, y))),
3711   //          (srl x, (*ext y))) ->
3712   //   (rotr x, y) or (rotl x, (sub 32, y))
3713   EVT VT = Shifted.getValueType();
3714   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3715     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3716     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3717                        HasPos ? Pos : Neg).getNode();
3718   }
3719
3720   return nullptr;
3721 }
3722
3723 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3724 // idioms for rotate, and if the target supports rotation instructions, generate
3725 // a rot[lr].
3726 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3727   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3728   EVT VT = LHS.getValueType();
3729   if (!TLI.isTypeLegal(VT)) return nullptr;
3730
3731   // The target must have at least one rotate flavor.
3732   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3733   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3734   if (!HasROTL && !HasROTR) return nullptr;
3735
3736   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3737   SDValue LHSShift;   // The shift.
3738   SDValue LHSMask;    // AND value if any.
3739   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3740     return nullptr; // Not part of a rotate.
3741
3742   SDValue RHSShift;   // The shift.
3743   SDValue RHSMask;    // AND value if any.
3744   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3745     return nullptr; // Not part of a rotate.
3746
3747   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3748     return nullptr;   // Not shifting the same value.
3749
3750   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3751     return nullptr;   // Shifts must disagree.
3752
3753   // Canonicalize shl to left side in a shl/srl pair.
3754   if (RHSShift.getOpcode() == ISD::SHL) {
3755     std::swap(LHS, RHS);
3756     std::swap(LHSShift, RHSShift);
3757     std::swap(LHSMask , RHSMask );
3758   }
3759
3760   unsigned OpSizeInBits = VT.getSizeInBits();
3761   SDValue LHSShiftArg = LHSShift.getOperand(0);
3762   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3763   SDValue RHSShiftArg = RHSShift.getOperand(0);
3764   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3765
3766   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3767   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3768   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3769       RHSShiftAmt.getOpcode() == ISD::Constant) {
3770     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3771     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3772     if ((LShVal + RShVal) != OpSizeInBits)
3773       return nullptr;
3774
3775     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3776                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3777
3778     // If there is an AND of either shifted operand, apply it to the result.
3779     if (LHSMask.getNode() || RHSMask.getNode()) {
3780       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3781
3782       if (LHSMask.getNode()) {
3783         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3784         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3785       }
3786       if (RHSMask.getNode()) {
3787         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3788         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3789       }
3790
3791       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3792     }
3793
3794     return Rot.getNode();
3795   }
3796
3797   // If there is a mask here, and we have a variable shift, we can't be sure
3798   // that we're masking out the right stuff.
3799   if (LHSMask.getNode() || RHSMask.getNode())
3800     return nullptr;
3801
3802   // If the shift amount is sign/zext/any-extended just peel it off.
3803   SDValue LExtOp0 = LHSShiftAmt;
3804   SDValue RExtOp0 = RHSShiftAmt;
3805   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3806        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3807        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3808        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3809       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3810        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3811        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3812        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3813     LExtOp0 = LHSShiftAmt.getOperand(0);
3814     RExtOp0 = RHSShiftAmt.getOperand(0);
3815   }
3816
3817   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3818                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3819   if (TryL)
3820     return TryL;
3821
3822   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3823                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3824   if (TryR)
3825     return TryR;
3826
3827   return nullptr;
3828 }
3829
3830 SDValue DAGCombiner::visitXOR(SDNode *N) {
3831   SDValue N0 = N->getOperand(0);
3832   SDValue N1 = N->getOperand(1);
3833   SDValue LHS, RHS, CC;
3834   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3835   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3836   EVT VT = N0.getValueType();
3837
3838   // fold vector ops
3839   if (VT.isVector()) {
3840     SDValue FoldedVOp = SimplifyVBinOp(N);
3841     if (FoldedVOp.getNode()) return FoldedVOp;
3842
3843     // fold (xor x, 0) -> x, vector edition
3844     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3845       return N1;
3846     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3847       return N0;
3848   }
3849
3850   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3851   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3852     return DAG.getConstant(0, VT);
3853   // fold (xor x, undef) -> undef
3854   if (N0.getOpcode() == ISD::UNDEF)
3855     return N0;
3856   if (N1.getOpcode() == ISD::UNDEF)
3857     return N1;
3858   // fold (xor c1, c2) -> c1^c2
3859   if (N0C && N1C)
3860     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3861   // canonicalize constant to RHS
3862   if (N0C && !N1C)
3863     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3864   // fold (xor x, 0) -> x
3865   if (N1C && N1C->isNullValue())
3866     return N0;
3867   // reassociate xor
3868   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3869   if (RXOR.getNode())
3870     return RXOR;
3871
3872   // fold !(x cc y) -> (x !cc y)
3873   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3874     bool isInt = LHS.getValueType().isInteger();
3875     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3876                                                isInt);
3877
3878     if (!LegalOperations ||
3879         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3880       switch (N0.getOpcode()) {
3881       default:
3882         llvm_unreachable("Unhandled SetCC Equivalent!");
3883       case ISD::SETCC:
3884         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3885       case ISD::SELECT_CC:
3886         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3887                                N0.getOperand(3), NotCC);
3888       }
3889     }
3890   }
3891
3892   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3893   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3894       N0.getNode()->hasOneUse() &&
3895       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3896     SDValue V = N0.getOperand(0);
3897     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3898                     DAG.getConstant(1, V.getValueType()));
3899     AddToWorklist(V.getNode());
3900     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3901   }
3902
3903   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3904   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3905       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3906     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3907     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3908       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3909       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3910       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3911       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3912       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3913     }
3914   }
3915   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3916   if (N1C && N1C->isAllOnesValue() &&
3917       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3918     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3919     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3920       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3921       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3922       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3923       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3924       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3925     }
3926   }
3927   // fold (xor (and x, y), y) -> (and (not x), y)
3928   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3929       N0->getOperand(1) == N1) {
3930     SDValue X = N0->getOperand(0);
3931     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3932     AddToWorklist(NotX.getNode());
3933     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3934   }
3935   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3936   if (N1C && N0.getOpcode() == ISD::XOR) {
3937     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3938     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3939     if (N00C)
3940       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3941                          DAG.getConstant(N1C->getAPIntValue() ^
3942                                          N00C->getAPIntValue(), VT));
3943     if (N01C)
3944       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3945                          DAG.getConstant(N1C->getAPIntValue() ^
3946                                          N01C->getAPIntValue(), VT));
3947   }
3948   // fold (xor x, x) -> 0
3949   if (N0 == N1)
3950     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3951
3952   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3953   if (N0.getOpcode() == N1.getOpcode()) {
3954     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3955     if (Tmp.getNode()) return Tmp;
3956   }
3957
3958   // Simplify the expression using non-local knowledge.
3959   if (!VT.isVector() &&
3960       SimplifyDemandedBits(SDValue(N, 0)))
3961     return SDValue(N, 0);
3962
3963   return SDValue();
3964 }
3965
3966 /// Handle transforms common to the three shifts, when the shift amount is a
3967 /// constant.
3968 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3969   // We can't and shouldn't fold opaque constants.
3970   if (Amt->isOpaque())
3971     return SDValue();
3972
3973   SDNode *LHS = N->getOperand(0).getNode();
3974   if (!LHS->hasOneUse()) return SDValue();
3975
3976   // We want to pull some binops through shifts, so that we have (and (shift))
3977   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3978   // thing happens with address calculations, so it's important to canonicalize
3979   // it.
3980   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3981
3982   switch (LHS->getOpcode()) {
3983   default: return SDValue();
3984   case ISD::OR:
3985   case ISD::XOR:
3986     HighBitSet = false; // We can only transform sra if the high bit is clear.
3987     break;
3988   case ISD::AND:
3989     HighBitSet = true;  // We can only transform sra if the high bit is set.
3990     break;
3991   case ISD::ADD:
3992     if (N->getOpcode() != ISD::SHL)
3993       return SDValue(); // only shl(add) not sr[al](add).
3994     HighBitSet = false; // We can only transform sra if the high bit is clear.
3995     break;
3996   }
3997
3998   // We require the RHS of the binop to be a constant and not opaque as well.
3999   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4000   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4001
4002   // FIXME: disable this unless the input to the binop is a shift by a constant.
4003   // If it is not a shift, it pessimizes some common cases like:
4004   //
4005   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4006   //    int bar(int *X, int i) { return X[i & 255]; }
4007   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4008   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4009        BinOpLHSVal->getOpcode() != ISD::SRA &&
4010        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4011       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4012     return SDValue();
4013
4014   EVT VT = N->getValueType(0);
4015
4016   // If this is a signed shift right, and the high bit is modified by the
4017   // logical operation, do not perform the transformation. The highBitSet
4018   // boolean indicates the value of the high bit of the constant which would
4019   // cause it to be modified for this operation.
4020   if (N->getOpcode() == ISD::SRA) {
4021     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4022     if (BinOpRHSSignSet != HighBitSet)
4023       return SDValue();
4024   }
4025
4026   if (!TLI.isDesirableToCommuteWithShift(LHS))
4027     return SDValue();
4028
4029   // Fold the constants, shifting the binop RHS by the shift amount.
4030   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4031                                N->getValueType(0),
4032                                LHS->getOperand(1), N->getOperand(1));
4033   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4034
4035   // Create the new shift.
4036   SDValue NewShift = DAG.getNode(N->getOpcode(),
4037                                  SDLoc(LHS->getOperand(0)),
4038                                  VT, LHS->getOperand(0), N->getOperand(1));
4039
4040   // Create the new binop.
4041   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4042 }
4043
4044 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4045   assert(N->getOpcode() == ISD::TRUNCATE);
4046   assert(N->getOperand(0).getOpcode() == ISD::AND);
4047
4048   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4049   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4050     SDValue N01 = N->getOperand(0).getOperand(1);
4051
4052     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4053       EVT TruncVT = N->getValueType(0);
4054       SDValue N00 = N->getOperand(0).getOperand(0);
4055       APInt TruncC = N01C->getAPIntValue();
4056       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4057
4058       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4059                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4060                          DAG.getConstant(TruncC, TruncVT));
4061     }
4062   }
4063
4064   return SDValue();
4065 }
4066
4067 SDValue DAGCombiner::visitRotate(SDNode *N) {
4068   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4069   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4070       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4071     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4072     if (NewOp1.getNode())
4073       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4074                          N->getOperand(0), NewOp1);
4075   }
4076   return SDValue();
4077 }
4078
4079 SDValue DAGCombiner::visitSHL(SDNode *N) {
4080   SDValue N0 = N->getOperand(0);
4081   SDValue N1 = N->getOperand(1);
4082   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4083   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4084   EVT VT = N0.getValueType();
4085   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4086
4087   // fold vector ops
4088   if (VT.isVector()) {
4089     SDValue FoldedVOp = SimplifyVBinOp(N);
4090     if (FoldedVOp.getNode()) return FoldedVOp;
4091
4092     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4093     // If setcc produces all-one true value then:
4094     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4095     if (N1CV && N1CV->isConstant()) {
4096       if (N0.getOpcode() == ISD::AND) {
4097         SDValue N00 = N0->getOperand(0);
4098         SDValue N01 = N0->getOperand(1);
4099         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4100
4101         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4102             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4103                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4104           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4105             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4106         }
4107       } else {
4108         N1C = isConstOrConstSplat(N1);
4109       }
4110     }
4111   }
4112
4113   // fold (shl c1, c2) -> c1<<c2
4114   if (N0C && N1C)
4115     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4116   // fold (shl 0, x) -> 0
4117   if (N0C && N0C->isNullValue())
4118     return N0;
4119   // fold (shl x, c >= size(x)) -> undef
4120   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4121     return DAG.getUNDEF(VT);
4122   // fold (shl x, 0) -> x
4123   if (N1C && N1C->isNullValue())
4124     return N0;
4125   // fold (shl undef, x) -> 0
4126   if (N0.getOpcode() == ISD::UNDEF)
4127     return DAG.getConstant(0, VT);
4128   // if (shl x, c) is known to be zero, return 0
4129   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4130                             APInt::getAllOnesValue(OpSizeInBits)))
4131     return DAG.getConstant(0, VT);
4132   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4133   if (N1.getOpcode() == ISD::TRUNCATE &&
4134       N1.getOperand(0).getOpcode() == ISD::AND) {
4135     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4136     if (NewOp1.getNode())
4137       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4138   }
4139
4140   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4141     return SDValue(N, 0);
4142
4143   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4144   if (N1C && N0.getOpcode() == ISD::SHL) {
4145     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4146       uint64_t c1 = N0C1->getZExtValue();
4147       uint64_t c2 = N1C->getZExtValue();
4148       if (c1 + c2 >= OpSizeInBits)
4149         return DAG.getConstant(0, VT);
4150       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4151                          DAG.getConstant(c1 + c2, N1.getValueType()));
4152     }
4153   }
4154
4155   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4156   // For this to be valid, the second form must not preserve any of the bits
4157   // that are shifted out by the inner shift in the first form.  This means
4158   // the outer shift size must be >= the number of bits added by the ext.
4159   // As a corollary, we don't care what kind of ext it is.
4160   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4161               N0.getOpcode() == ISD::ANY_EXTEND ||
4162               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4163       N0.getOperand(0).getOpcode() == ISD::SHL) {
4164     SDValue N0Op0 = N0.getOperand(0);
4165     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4166       uint64_t c1 = N0Op0C1->getZExtValue();
4167       uint64_t c2 = N1C->getZExtValue();
4168       EVT InnerShiftVT = N0Op0.getValueType();
4169       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4170       if (c2 >= OpSizeInBits - InnerShiftSize) {
4171         if (c1 + c2 >= OpSizeInBits)
4172           return DAG.getConstant(0, VT);
4173         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4174                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4175                                        N0Op0->getOperand(0)),
4176                            DAG.getConstant(c1 + c2, N1.getValueType()));
4177       }
4178     }
4179   }
4180
4181   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4182   // Only fold this if the inner zext has no other uses to avoid increasing
4183   // the total number of instructions.
4184   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4185       N0.getOperand(0).getOpcode() == ISD::SRL) {
4186     SDValue N0Op0 = N0.getOperand(0);
4187     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4188       uint64_t c1 = N0Op0C1->getZExtValue();
4189       if (c1 < VT.getScalarSizeInBits()) {
4190         uint64_t c2 = N1C->getZExtValue();
4191         if (c1 == c2) {
4192           SDValue NewOp0 = N0.getOperand(0);
4193           EVT CountVT = NewOp0.getOperand(1).getValueType();
4194           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4195                                        NewOp0, DAG.getConstant(c2, CountVT));
4196           AddToWorklist(NewSHL.getNode());
4197           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4198         }
4199       }
4200     }
4201   }
4202
4203   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4204   //                               (and (srl x, (sub c1, c2), MASK)
4205   // Only fold this if the inner shift has no other uses -- if it does, folding
4206   // this will increase the total number of instructions.
4207   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4208     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4209       uint64_t c1 = N0C1->getZExtValue();
4210       if (c1 < OpSizeInBits) {
4211         uint64_t c2 = N1C->getZExtValue();
4212         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4213         SDValue Shift;
4214         if (c2 > c1) {
4215           Mask = Mask.shl(c2 - c1);
4216           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4217                               DAG.getConstant(c2 - c1, N1.getValueType()));
4218         } else {
4219           Mask = Mask.lshr(c1 - c2);
4220           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4221                               DAG.getConstant(c1 - c2, N1.getValueType()));
4222         }
4223         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4224                            DAG.getConstant(Mask, VT));
4225       }
4226     }
4227   }
4228   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4229   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4230     unsigned BitSize = VT.getScalarSizeInBits();
4231     SDValue HiBitsMask =
4232       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4233                                             BitSize - N1C->getZExtValue()), VT);
4234     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4235                        HiBitsMask);
4236   }
4237
4238   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4239   // Variant of version done on multiply, except mul by a power of 2 is turned
4240   // into a shift.
4241   APInt Val;
4242   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4243       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4244        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4245     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4246     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4247     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4248   }
4249
4250   if (N1C) {
4251     SDValue NewSHL = visitShiftByConstant(N, N1C);
4252     if (NewSHL.getNode())
4253       return NewSHL;
4254   }
4255
4256   return SDValue();
4257 }
4258
4259 SDValue DAGCombiner::visitSRA(SDNode *N) {
4260   SDValue N0 = N->getOperand(0);
4261   SDValue N1 = N->getOperand(1);
4262   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4263   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4264   EVT VT = N0.getValueType();
4265   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4266
4267   // fold vector ops
4268   if (VT.isVector()) {
4269     SDValue FoldedVOp = SimplifyVBinOp(N);
4270     if (FoldedVOp.getNode()) return FoldedVOp;
4271
4272     N1C = isConstOrConstSplat(N1);
4273   }
4274
4275   // fold (sra c1, c2) -> (sra c1, c2)
4276   if (N0C && N1C)
4277     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4278   // fold (sra 0, x) -> 0
4279   if (N0C && N0C->isNullValue())
4280     return N0;
4281   // fold (sra -1, x) -> -1
4282   if (N0C && N0C->isAllOnesValue())
4283     return N0;
4284   // fold (sra x, (setge c, size(x))) -> undef
4285   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4286     return DAG.getUNDEF(VT);
4287   // fold (sra x, 0) -> x
4288   if (N1C && N1C->isNullValue())
4289     return N0;
4290   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4291   // sext_inreg.
4292   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4293     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4294     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4295     if (VT.isVector())
4296       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4297                                ExtVT, VT.getVectorNumElements());
4298     if ((!LegalOperations ||
4299          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4300       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4301                          N0.getOperand(0), DAG.getValueType(ExtVT));
4302   }
4303
4304   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4305   if (N1C && N0.getOpcode() == ISD::SRA) {
4306     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4307       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4308       if (Sum >= OpSizeInBits)
4309         Sum = OpSizeInBits - 1;
4310       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4311                          DAG.getConstant(Sum, N1.getValueType()));
4312     }
4313   }
4314
4315   // fold (sra (shl X, m), (sub result_size, n))
4316   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4317   // result_size - n != m.
4318   // If truncate is free for the target sext(shl) is likely to result in better
4319   // code.
4320   if (N0.getOpcode() == ISD::SHL && N1C) {
4321     // Get the two constanst of the shifts, CN0 = m, CN = n.
4322     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4323     if (N01C) {
4324       LLVMContext &Ctx = *DAG.getContext();
4325       // Determine what the truncate's result bitsize and type would be.
4326       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4327
4328       if (VT.isVector())
4329         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4330
4331       // Determine the residual right-shift amount.
4332       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4333
4334       // If the shift is not a no-op (in which case this should be just a sign
4335       // extend already), the truncated to type is legal, sign_extend is legal
4336       // on that type, and the truncate to that type is both legal and free,
4337       // perform the transform.
4338       if ((ShiftAmt > 0) &&
4339           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4340           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4341           TLI.isTruncateFree(VT, TruncVT)) {
4342
4343           SDValue Amt = DAG.getConstant(ShiftAmt,
4344               getShiftAmountTy(N0.getOperand(0).getValueType()));
4345           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4346                                       N0.getOperand(0), Amt);
4347           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4348                                       Shift);
4349           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4350                              N->getValueType(0), Trunc);
4351       }
4352     }
4353   }
4354
4355   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4356   if (N1.getOpcode() == ISD::TRUNCATE &&
4357       N1.getOperand(0).getOpcode() == ISD::AND) {
4358     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4359     if (NewOp1.getNode())
4360       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4361   }
4362
4363   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4364   //      if c1 is equal to the number of bits the trunc removes
4365   if (N0.getOpcode() == ISD::TRUNCATE &&
4366       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4367        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4368       N0.getOperand(0).hasOneUse() &&
4369       N0.getOperand(0).getOperand(1).hasOneUse() &&
4370       N1C) {
4371     SDValue N0Op0 = N0.getOperand(0);
4372     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4373       unsigned LargeShiftVal = LargeShift->getZExtValue();
4374       EVT LargeVT = N0Op0.getValueType();
4375
4376       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4377         SDValue Amt =
4378           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4379                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4380         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4381                                   N0Op0.getOperand(0), Amt);
4382         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4383       }
4384     }
4385   }
4386
4387   // Simplify, based on bits shifted out of the LHS.
4388   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4389     return SDValue(N, 0);
4390
4391
4392   // If the sign bit is known to be zero, switch this to a SRL.
4393   if (DAG.SignBitIsZero(N0))
4394     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4395
4396   if (N1C) {
4397     SDValue NewSRA = visitShiftByConstant(N, N1C);
4398     if (NewSRA.getNode())
4399       return NewSRA;
4400   }
4401
4402   return SDValue();
4403 }
4404
4405 SDValue DAGCombiner::visitSRL(SDNode *N) {
4406   SDValue N0 = N->getOperand(0);
4407   SDValue N1 = N->getOperand(1);
4408   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4409   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4410   EVT VT = N0.getValueType();
4411   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4412
4413   // fold vector ops
4414   if (VT.isVector()) {
4415     SDValue FoldedVOp = SimplifyVBinOp(N);
4416     if (FoldedVOp.getNode()) return FoldedVOp;
4417
4418     N1C = isConstOrConstSplat(N1);
4419   }
4420
4421   // fold (srl c1, c2) -> c1 >>u c2
4422   if (N0C && N1C)
4423     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4424   // fold (srl 0, x) -> 0
4425   if (N0C && N0C->isNullValue())
4426     return N0;
4427   // fold (srl x, c >= size(x)) -> undef
4428   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4429     return DAG.getUNDEF(VT);
4430   // fold (srl x, 0) -> x
4431   if (N1C && N1C->isNullValue())
4432     return N0;
4433   // if (srl x, c) is known to be zero, return 0
4434   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4435                                    APInt::getAllOnesValue(OpSizeInBits)))
4436     return DAG.getConstant(0, VT);
4437
4438   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4439   if (N1C && N0.getOpcode() == ISD::SRL) {
4440     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4441       uint64_t c1 = N01C->getZExtValue();
4442       uint64_t c2 = N1C->getZExtValue();
4443       if (c1 + c2 >= OpSizeInBits)
4444         return DAG.getConstant(0, VT);
4445       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4446                          DAG.getConstant(c1 + c2, N1.getValueType()));
4447     }
4448   }
4449
4450   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4451   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4452       N0.getOperand(0).getOpcode() == ISD::SRL &&
4453       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4454     uint64_t c1 =
4455       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4456     uint64_t c2 = N1C->getZExtValue();
4457     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4458     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4459     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4460     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4461     if (c1 + OpSizeInBits == InnerShiftSize) {
4462       if (c1 + c2 >= InnerShiftSize)
4463         return DAG.getConstant(0, VT);
4464       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4465                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4466                                      N0.getOperand(0)->getOperand(0),
4467                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4468     }
4469   }
4470
4471   // fold (srl (shl x, c), c) -> (and x, cst2)
4472   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4473     unsigned BitSize = N0.getScalarValueSizeInBits();
4474     if (BitSize <= 64) {
4475       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4476       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4477                          DAG.getConstant(~0ULL >> ShAmt, VT));
4478     }
4479   }
4480
4481   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4482   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4483     // Shifting in all undef bits?
4484     EVT SmallVT = N0.getOperand(0).getValueType();
4485     unsigned BitSize = SmallVT.getScalarSizeInBits();
4486     if (N1C->getZExtValue() >= BitSize)
4487       return DAG.getUNDEF(VT);
4488
4489     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4490       uint64_t ShiftAmt = N1C->getZExtValue();
4491       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4492                                        N0.getOperand(0),
4493                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4494       AddToWorklist(SmallShift.getNode());
4495       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4496       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4497                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4498                          DAG.getConstant(Mask, VT));
4499     }
4500   }
4501
4502   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4503   // bit, which is unmodified by sra.
4504   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4505     if (N0.getOpcode() == ISD::SRA)
4506       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4507   }
4508
4509   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4510   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4511       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4512     APInt KnownZero, KnownOne;
4513     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4514
4515     // If any of the input bits are KnownOne, then the input couldn't be all
4516     // zeros, thus the result of the srl will always be zero.
4517     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4518
4519     // If all of the bits input the to ctlz node are known to be zero, then
4520     // the result of the ctlz is "32" and the result of the shift is one.
4521     APInt UnknownBits = ~KnownZero;
4522     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4523
4524     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4525     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4526       // Okay, we know that only that the single bit specified by UnknownBits
4527       // could be set on input to the CTLZ node. If this bit is set, the SRL
4528       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4529       // to an SRL/XOR pair, which is likely to simplify more.
4530       unsigned ShAmt = UnknownBits.countTrailingZeros();
4531       SDValue Op = N0.getOperand(0);
4532
4533       if (ShAmt) {
4534         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4535                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4536         AddToWorklist(Op.getNode());
4537       }
4538
4539       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4540                          Op, DAG.getConstant(1, VT));
4541     }
4542   }
4543
4544   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4545   if (N1.getOpcode() == ISD::TRUNCATE &&
4546       N1.getOperand(0).getOpcode() == ISD::AND) {
4547     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4548     if (NewOp1.getNode())
4549       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4550   }
4551
4552   // fold operands of srl based on knowledge that the low bits are not
4553   // demanded.
4554   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4555     return SDValue(N, 0);
4556
4557   if (N1C) {
4558     SDValue NewSRL = visitShiftByConstant(N, N1C);
4559     if (NewSRL.getNode())
4560       return NewSRL;
4561   }
4562
4563   // Attempt to convert a srl of a load into a narrower zero-extending load.
4564   SDValue NarrowLoad = ReduceLoadWidth(N);
4565   if (NarrowLoad.getNode())
4566     return NarrowLoad;
4567
4568   // Here is a common situation. We want to optimize:
4569   //
4570   //   %a = ...
4571   //   %b = and i32 %a, 2
4572   //   %c = srl i32 %b, 1
4573   //   brcond i32 %c ...
4574   //
4575   // into
4576   //
4577   //   %a = ...
4578   //   %b = and %a, 2
4579   //   %c = setcc eq %b, 0
4580   //   brcond %c ...
4581   //
4582   // However when after the source operand of SRL is optimized into AND, the SRL
4583   // itself may not be optimized further. Look for it and add the BRCOND into
4584   // the worklist.
4585   if (N->hasOneUse()) {
4586     SDNode *Use = *N->use_begin();
4587     if (Use->getOpcode() == ISD::BRCOND)
4588       AddToWorklist(Use);
4589     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4590       // Also look pass the truncate.
4591       Use = *Use->use_begin();
4592       if (Use->getOpcode() == ISD::BRCOND)
4593         AddToWorklist(Use);
4594     }
4595   }
4596
4597   return SDValue();
4598 }
4599
4600 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4601   SDValue N0 = N->getOperand(0);
4602   EVT VT = N->getValueType(0);
4603
4604   // fold (ctlz c1) -> c2
4605   if (isa<ConstantSDNode>(N0))
4606     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4607   return SDValue();
4608 }
4609
4610 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4611   SDValue N0 = N->getOperand(0);
4612   EVT VT = N->getValueType(0);
4613
4614   // fold (ctlz_zero_undef c1) -> c2
4615   if (isa<ConstantSDNode>(N0))
4616     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4617   return SDValue();
4618 }
4619
4620 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4621   SDValue N0 = N->getOperand(0);
4622   EVT VT = N->getValueType(0);
4623
4624   // fold (cttz c1) -> c2
4625   if (isa<ConstantSDNode>(N0))
4626     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4627   return SDValue();
4628 }
4629
4630 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4631   SDValue N0 = N->getOperand(0);
4632   EVT VT = N->getValueType(0);
4633
4634   // fold (cttz_zero_undef c1) -> c2
4635   if (isa<ConstantSDNode>(N0))
4636     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4637   return SDValue();
4638 }
4639
4640 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4641   SDValue N0 = N->getOperand(0);
4642   EVT VT = N->getValueType(0);
4643
4644   // fold (ctpop c1) -> c2
4645   if (isa<ConstantSDNode>(N0))
4646     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4647   return SDValue();
4648 }
4649
4650
4651 /// \brief Generate Min/Max node
4652 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4653                                    SDValue True, SDValue False,
4654                                    ISD::CondCode CC, const TargetLowering &TLI,
4655                                    SelectionDAG &DAG) {
4656   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4657     return SDValue();
4658
4659   switch (CC) {
4660   case ISD::SETOLT:
4661   case ISD::SETOLE:
4662   case ISD::SETLT:
4663   case ISD::SETLE:
4664   case ISD::SETULT:
4665   case ISD::SETULE: {
4666     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4667     if (TLI.isOperationLegal(Opcode, VT))
4668       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4669     return SDValue();
4670   }
4671   case ISD::SETOGT:
4672   case ISD::SETOGE:
4673   case ISD::SETGT:
4674   case ISD::SETGE:
4675   case ISD::SETUGT:
4676   case ISD::SETUGE: {
4677     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4678     if (TLI.isOperationLegal(Opcode, VT))
4679       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4680     return SDValue();
4681   }
4682   default:
4683     return SDValue();
4684   }
4685 }
4686
4687 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4688   SDValue N0 = N->getOperand(0);
4689   SDValue N1 = N->getOperand(1);
4690   SDValue N2 = N->getOperand(2);
4691   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4692   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4693   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4694   EVT VT = N->getValueType(0);
4695   EVT VT0 = N0.getValueType();
4696
4697   // fold (select C, X, X) -> X
4698   if (N1 == N2)
4699     return N1;
4700   // fold (select true, X, Y) -> X
4701   if (N0C && !N0C->isNullValue())
4702     return N1;
4703   // fold (select false, X, Y) -> Y
4704   if (N0C && N0C->isNullValue())
4705     return N2;
4706   // fold (select C, 1, X) -> (or C, X)
4707   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4708     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4709   // fold (select C, 0, 1) -> (xor C, 1)
4710   // We can't do this reliably if integer based booleans have different contents
4711   // to floating point based booleans. This is because we can't tell whether we
4712   // have an integer-based boolean or a floating-point-based boolean unless we
4713   // can find the SETCC that produced it and inspect its operands. This is
4714   // fairly easy if C is the SETCC node, but it can potentially be
4715   // undiscoverable (or not reasonably discoverable). For example, it could be
4716   // in another basic block or it could require searching a complicated
4717   // expression.
4718   if (VT.isInteger() &&
4719       (VT0 == MVT::i1 || (VT0.isInteger() &&
4720                           TLI.getBooleanContents(false, false) ==
4721                               TLI.getBooleanContents(false, true) &&
4722                           TLI.getBooleanContents(false, false) ==
4723                               TargetLowering::ZeroOrOneBooleanContent)) &&
4724       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4725     SDValue XORNode;
4726     if (VT == VT0)
4727       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4728                          N0, DAG.getConstant(1, VT0));
4729     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4730                           N0, DAG.getConstant(1, VT0));
4731     AddToWorklist(XORNode.getNode());
4732     if (VT.bitsGT(VT0))
4733       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4734     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4735   }
4736   // fold (select C, 0, X) -> (and (not C), X)
4737   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4738     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4739     AddToWorklist(NOTNode.getNode());
4740     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4741   }
4742   // fold (select C, X, 1) -> (or (not C), X)
4743   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4744     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4745     AddToWorklist(NOTNode.getNode());
4746     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4747   }
4748   // fold (select C, X, 0) -> (and C, X)
4749   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4750     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4751   // fold (select X, X, Y) -> (or X, Y)
4752   // fold (select X, 1, Y) -> (or X, Y)
4753   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4754     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4755   // fold (select X, Y, X) -> (and X, Y)
4756   // fold (select X, Y, 0) -> (and X, Y)
4757   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4758     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4759
4760   // If we can fold this based on the true/false value, do so.
4761   if (SimplifySelectOps(N, N1, N2))
4762     return SDValue(N, 0);  // Don't revisit N.
4763
4764   // fold selects based on a setcc into other things, such as min/max/abs
4765   if (N0.getOpcode() == ISD::SETCC) {
4766     // select x, y (fcmp lt x, y) -> fminnum x, y
4767     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4768     //
4769     // This is OK if we don't care about what happens if either operand is a
4770     // NaN.
4771     //
4772
4773     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4774     // no signed zeros as well as no nans.
4775     const TargetOptions &Options = DAG.getTarget().Options;
4776     if (Options.UnsafeFPMath &&
4777         VT.isFloatingPoint() && N0.hasOneUse() &&
4778         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4779       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4780
4781       SDValue FMinMax =
4782           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4783                               N1, N2, CC, TLI, DAG);
4784       if (FMinMax)
4785         return FMinMax;
4786     }
4787
4788     if ((!LegalOperations &&
4789          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4790         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4791       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4792                          N0.getOperand(0), N0.getOperand(1),
4793                          N1, N2, N0.getOperand(2));
4794     return SimplifySelect(SDLoc(N), N0, N1, N2);
4795   }
4796
4797   return SDValue();
4798 }
4799
4800 static
4801 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4802   SDLoc DL(N);
4803   EVT LoVT, HiVT;
4804   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4805
4806   // Split the inputs.
4807   SDValue Lo, Hi, LL, LH, RL, RH;
4808   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4809   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4810
4811   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4812   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4813
4814   return std::make_pair(Lo, Hi);
4815 }
4816
4817 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4818 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4819 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4820   SDLoc dl(N);
4821   SDValue Cond = N->getOperand(0);
4822   SDValue LHS = N->getOperand(1);
4823   SDValue RHS = N->getOperand(2);
4824   EVT VT = N->getValueType(0);
4825   int NumElems = VT.getVectorNumElements();
4826   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4827          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4828          Cond.getOpcode() == ISD::BUILD_VECTOR);
4829
4830   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4831   // binary ones here.
4832   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4833     return SDValue();
4834
4835   // We're sure we have an even number of elements due to the
4836   // concat_vectors we have as arguments to vselect.
4837   // Skip BV elements until we find one that's not an UNDEF
4838   // After we find an UNDEF element, keep looping until we get to half the
4839   // length of the BV and see if all the non-undef nodes are the same.
4840   ConstantSDNode *BottomHalf = nullptr;
4841   for (int i = 0; i < NumElems / 2; ++i) {
4842     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4843       continue;
4844
4845     if (BottomHalf == nullptr)
4846       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4847     else if (Cond->getOperand(i).getNode() != BottomHalf)
4848       return SDValue();
4849   }
4850
4851   // Do the same for the second half of the BuildVector
4852   ConstantSDNode *TopHalf = nullptr;
4853   for (int i = NumElems / 2; i < NumElems; ++i) {
4854     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4855       continue;
4856
4857     if (TopHalf == nullptr)
4858       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4859     else if (Cond->getOperand(i).getNode() != TopHalf)
4860       return SDValue();
4861   }
4862
4863   assert(TopHalf && BottomHalf &&
4864          "One half of the selector was all UNDEFs and the other was all the "
4865          "same value. This should have been addressed before this function.");
4866   return DAG.getNode(
4867       ISD::CONCAT_VECTORS, dl, VT,
4868       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4869       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4870 }
4871
4872 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4873
4874   if (Level >= AfterLegalizeTypes)
4875     return SDValue();
4876
4877   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4878   SDValue Mask = MST->getMask();
4879   SDValue Data  = MST->getValue();
4880   SDLoc DL(N);
4881
4882   // If the MSTORE data type requires splitting and the mask is provided by a
4883   // SETCC, then split both nodes and its operands before legalization. This
4884   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4885   // and enables future optimizations (e.g. min/max pattern matching on X86).
4886   if (Mask.getOpcode() == ISD::SETCC) {
4887
4888     // Check if any splitting is required.
4889     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4890         TargetLowering::TypeSplitVector)
4891       return SDValue();
4892
4893     SDValue MaskLo, MaskHi, Lo, Hi;
4894     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4895
4896     EVT LoVT, HiVT;
4897     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4898
4899     SDValue Chain = MST->getChain();
4900     SDValue Ptr   = MST->getBasePtr();
4901
4902     EVT MemoryVT = MST->getMemoryVT();
4903     unsigned Alignment = MST->getOriginalAlignment();
4904
4905     // if Alignment is equal to the vector size,
4906     // take the half of it for the second part
4907     unsigned SecondHalfAlignment =
4908       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4909          Alignment/2 : Alignment;
4910
4911     EVT LoMemVT, HiMemVT;
4912     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4913
4914     SDValue DataLo, DataHi;
4915     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4916
4917     MachineMemOperand *MMO = DAG.getMachineFunction().
4918       getMachineMemOperand(MST->getPointerInfo(), 
4919                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4920                            Alignment, MST->getAAInfo(), MST->getRanges());
4921
4922     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
4923                             MST->isTruncatingStore());
4924
4925     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4926     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4927                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4928
4929     MMO = DAG.getMachineFunction().
4930       getMachineMemOperand(MST->getPointerInfo(), 
4931                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4932                            SecondHalfAlignment, MST->getAAInfo(),
4933                            MST->getRanges());
4934
4935     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
4936                             MST->isTruncatingStore());
4937
4938     AddToWorklist(Lo.getNode());
4939     AddToWorklist(Hi.getNode());
4940
4941     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4942   }
4943   return SDValue();
4944 }
4945
4946 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4947
4948   if (Level >= AfterLegalizeTypes)
4949     return SDValue();
4950
4951   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4952   SDValue Mask = MLD->getMask();
4953   SDLoc DL(N);
4954
4955   // If the MLOAD result requires splitting and the mask is provided by a
4956   // SETCC, then split both nodes and its operands before legalization. This
4957   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4958   // and enables future optimizations (e.g. min/max pattern matching on X86).
4959
4960   if (Mask.getOpcode() == ISD::SETCC) {
4961     EVT VT = N->getValueType(0);
4962
4963     // Check if any splitting is required.
4964     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4965         TargetLowering::TypeSplitVector)
4966       return SDValue();
4967
4968     SDValue MaskLo, MaskHi, Lo, Hi;
4969     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4970
4971     SDValue Src0 = MLD->getSrc0();
4972     SDValue Src0Lo, Src0Hi;
4973     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4974
4975     EVT LoVT, HiVT;
4976     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4977
4978     SDValue Chain = MLD->getChain();
4979     SDValue Ptr   = MLD->getBasePtr();
4980     EVT MemoryVT = MLD->getMemoryVT();
4981     unsigned Alignment = MLD->getOriginalAlignment();
4982
4983     // if Alignment is equal to the vector size,
4984     // take the half of it for the second part
4985     unsigned SecondHalfAlignment =
4986       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4987          Alignment/2 : Alignment;
4988
4989     EVT LoMemVT, HiMemVT;
4990     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4991
4992     MachineMemOperand *MMO = DAG.getMachineFunction().
4993     getMachineMemOperand(MLD->getPointerInfo(), 
4994                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4995                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4996
4997     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
4998                            ISD::NON_EXTLOAD);
4999
5000     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5001     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5002                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5003
5004     MMO = DAG.getMachineFunction().
5005     getMachineMemOperand(MLD->getPointerInfo(), 
5006                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5007                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5008
5009     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5010                            ISD::NON_EXTLOAD);
5011
5012     AddToWorklist(Lo.getNode());
5013     AddToWorklist(Hi.getNode());
5014
5015     // Build a factor node to remember that this load is independent of the
5016     // other one.
5017     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5018                         Hi.getValue(1));
5019
5020     // Legalized the chain result - switch anything that used the old chain to
5021     // use the new one.
5022     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5023
5024     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5025
5026     SDValue RetOps[] = { LoadRes, Chain };
5027     return DAG.getMergeValues(RetOps, DL);
5028   }
5029   return SDValue();
5030 }
5031
5032 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5033   SDValue N0 = N->getOperand(0);
5034   SDValue N1 = N->getOperand(1);
5035   SDValue N2 = N->getOperand(2);
5036   SDLoc DL(N);
5037
5038   // Canonicalize integer abs.
5039   // vselect (setg[te] X,  0),  X, -X ->
5040   // vselect (setgt    X, -1),  X, -X ->
5041   // vselect (setl[te] X,  0), -X,  X ->
5042   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5043   if (N0.getOpcode() == ISD::SETCC) {
5044     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5045     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5046     bool isAbs = false;
5047     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5048
5049     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5050          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5051         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5052       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5053     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5054              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5055       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5056
5057     if (isAbs) {
5058       EVT VT = LHS.getValueType();
5059       SDValue Shift = DAG.getNode(
5060           ISD::SRA, DL, VT, LHS,
5061           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5062       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5063       AddToWorklist(Shift.getNode());
5064       AddToWorklist(Add.getNode());
5065       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5066     }
5067   }
5068
5069   // If the VSELECT result requires splitting and the mask is provided by a
5070   // SETCC, then split both nodes and its operands before legalization. This
5071   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5072   // and enables future optimizations (e.g. min/max pattern matching on X86).
5073   if (N0.getOpcode() == ISD::SETCC) {
5074     EVT VT = N->getValueType(0);
5075
5076     // Check if any splitting is required.
5077     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5078         TargetLowering::TypeSplitVector)
5079       return SDValue();
5080
5081     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5082     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5083     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5084     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5085
5086     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5087     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5088
5089     // Add the new VSELECT nodes to the work list in case they need to be split
5090     // again.
5091     AddToWorklist(Lo.getNode());
5092     AddToWorklist(Hi.getNode());
5093
5094     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5095   }
5096
5097   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5098   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5099     return N1;
5100   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5101   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5102     return N2;
5103
5104   // The ConvertSelectToConcatVector function is assuming both the above
5105   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5106   // and addressed.
5107   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5108       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5109       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5110     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5111     if (CV.getNode())
5112       return CV;
5113   }
5114
5115   return SDValue();
5116 }
5117
5118 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5119   SDValue N0 = N->getOperand(0);
5120   SDValue N1 = N->getOperand(1);
5121   SDValue N2 = N->getOperand(2);
5122   SDValue N3 = N->getOperand(3);
5123   SDValue N4 = N->getOperand(4);
5124   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5125
5126   // fold select_cc lhs, rhs, x, x, cc -> x
5127   if (N2 == N3)
5128     return N2;
5129
5130   // Determine if the condition we're dealing with is constant
5131   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5132                               N0, N1, CC, SDLoc(N), false);
5133   if (SCC.getNode()) {
5134     AddToWorklist(SCC.getNode());
5135
5136     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5137       if (!SCCC->isNullValue())
5138         return N2;    // cond always true -> true val
5139       else
5140         return N3;    // cond always false -> false val
5141     } else if (SCC->getOpcode() == ISD::UNDEF) {
5142       // When the condition is UNDEF, just return the first operand. This is
5143       // coherent the DAG creation, no setcc node is created in this case
5144       return N2;
5145     } else if (SCC.getOpcode() == ISD::SETCC) {
5146       // Fold to a simpler select_cc
5147       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5148                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5149                          SCC.getOperand(2));
5150     }
5151   }
5152
5153   // If we can fold this based on the true/false value, do so.
5154   if (SimplifySelectOps(N, N2, N3))
5155     return SDValue(N, 0);  // Don't revisit N.
5156
5157   // fold select_cc into other things, such as min/max/abs
5158   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5159 }
5160
5161 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5162   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5163                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5164                        SDLoc(N));
5165 }
5166
5167 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5168 // dag node into a ConstantSDNode or a build_vector of constants.
5169 // This function is called by the DAGCombiner when visiting sext/zext/aext
5170 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5171 // Vector extends are not folded if operations are legal; this is to
5172 // avoid introducing illegal build_vector dag nodes.
5173 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5174                                          SelectionDAG &DAG, bool LegalTypes,
5175                                          bool LegalOperations) {
5176   unsigned Opcode = N->getOpcode();
5177   SDValue N0 = N->getOperand(0);
5178   EVT VT = N->getValueType(0);
5179
5180   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5181          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5182
5183   // fold (sext c1) -> c1
5184   // fold (zext c1) -> c1
5185   // fold (aext c1) -> c1
5186   if (isa<ConstantSDNode>(N0))
5187     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5188
5189   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5190   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5191   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5192   EVT SVT = VT.getScalarType();
5193   if (!(VT.isVector() &&
5194       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5195       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5196     return nullptr;
5197
5198   // We can fold this node into a build_vector.
5199   unsigned VTBits = SVT.getSizeInBits();
5200   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5201   unsigned ShAmt = VTBits - EVTBits;
5202   SmallVector<SDValue, 8> Elts;
5203   unsigned NumElts = N0->getNumOperands();
5204   SDLoc DL(N);
5205
5206   for (unsigned i=0; i != NumElts; ++i) {
5207     SDValue Op = N0->getOperand(i);
5208     if (Op->getOpcode() == ISD::UNDEF) {
5209       Elts.push_back(DAG.getUNDEF(SVT));
5210       continue;
5211     }
5212
5213     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5214     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5215     if (Opcode == ISD::SIGN_EXTEND)
5216       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5217                                      SVT));
5218     else
5219       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5220                                      SVT));
5221   }
5222
5223   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5224 }
5225
5226 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5227 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5228 // transformation. Returns true if extension are possible and the above
5229 // mentioned transformation is profitable.
5230 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5231                                     unsigned ExtOpc,
5232                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5233                                     const TargetLowering &TLI) {
5234   bool HasCopyToRegUses = false;
5235   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5236   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5237                             UE = N0.getNode()->use_end();
5238        UI != UE; ++UI) {
5239     SDNode *User = *UI;
5240     if (User == N)
5241       continue;
5242     if (UI.getUse().getResNo() != N0.getResNo())
5243       continue;
5244     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5245     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5246       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5247       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5248         // Sign bits will be lost after a zext.
5249         return false;
5250       bool Add = false;
5251       for (unsigned i = 0; i != 2; ++i) {
5252         SDValue UseOp = User->getOperand(i);
5253         if (UseOp == N0)
5254           continue;
5255         if (!isa<ConstantSDNode>(UseOp))
5256           return false;
5257         Add = true;
5258       }
5259       if (Add)
5260         ExtendNodes.push_back(User);
5261       continue;
5262     }
5263     // If truncates aren't free and there are users we can't
5264     // extend, it isn't worthwhile.
5265     if (!isTruncFree)
5266       return false;
5267     // Remember if this value is live-out.
5268     if (User->getOpcode() == ISD::CopyToReg)
5269       HasCopyToRegUses = true;
5270   }
5271
5272   if (HasCopyToRegUses) {
5273     bool BothLiveOut = false;
5274     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5275          UI != UE; ++UI) {
5276       SDUse &Use = UI.getUse();
5277       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5278         BothLiveOut = true;
5279         break;
5280       }
5281     }
5282     if (BothLiveOut)
5283       // Both unextended and extended values are live out. There had better be
5284       // a good reason for the transformation.
5285       return ExtendNodes.size();
5286   }
5287   return true;
5288 }
5289
5290 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5291                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5292                                   ISD::NodeType ExtType) {
5293   // Extend SetCC uses if necessary.
5294   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5295     SDNode *SetCC = SetCCs[i];
5296     SmallVector<SDValue, 4> Ops;
5297
5298     for (unsigned j = 0; j != 2; ++j) {
5299       SDValue SOp = SetCC->getOperand(j);
5300       if (SOp == Trunc)
5301         Ops.push_back(ExtLoad);
5302       else
5303         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5304     }
5305
5306     Ops.push_back(SetCC->getOperand(2));
5307     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5308   }
5309 }
5310
5311 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5312 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5313   SDValue N0 = N->getOperand(0);
5314   EVT DstVT = N->getValueType(0);
5315   EVT SrcVT = N0.getValueType();
5316
5317   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5318           N->getOpcode() == ISD::ZERO_EXTEND) &&
5319          "Unexpected node type (not an extend)!");
5320
5321   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5322   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5323   //   (v8i32 (sext (v8i16 (load x))))
5324   // into:
5325   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5326   //                          (v4i32 (sextload (x + 16)))))
5327   // Where uses of the original load, i.e.:
5328   //   (v8i16 (load x))
5329   // are replaced with:
5330   //   (v8i16 (truncate
5331   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5332   //                            (v4i32 (sextload (x + 16)))))))
5333   //
5334   // This combine is only applicable to illegal, but splittable, vectors.
5335   // All legal types, and illegal non-vector types, are handled elsewhere.
5336   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5337   //
5338   if (N0->getOpcode() != ISD::LOAD)
5339     return SDValue();
5340
5341   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5342
5343   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5344       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5345       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5346     return SDValue();
5347
5348   SmallVector<SDNode *, 4> SetCCs;
5349   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5350     return SDValue();
5351
5352   ISD::LoadExtType ExtType =
5353       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5354
5355   // Try to split the vector types to get down to legal types.
5356   EVT SplitSrcVT = SrcVT;
5357   EVT SplitDstVT = DstVT;
5358   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5359          SplitSrcVT.getVectorNumElements() > 1) {
5360     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5361     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5362   }
5363
5364   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5365     return SDValue();
5366
5367   SDLoc DL(N);
5368   const unsigned NumSplits =
5369       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5370   const unsigned Stride = SplitSrcVT.getStoreSize();
5371   SmallVector<SDValue, 4> Loads;
5372   SmallVector<SDValue, 4> Chains;
5373
5374   SDValue BasePtr = LN0->getBasePtr();
5375   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5376     const unsigned Offset = Idx * Stride;
5377     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5378
5379     SDValue SplitLoad = DAG.getExtLoad(
5380         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5381         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5382         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5383         Align, LN0->getAAInfo());
5384
5385     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5386                           DAG.getConstant(Stride, BasePtr.getValueType()));
5387
5388     Loads.push_back(SplitLoad.getValue(0));
5389     Chains.push_back(SplitLoad.getValue(1));
5390   }
5391
5392   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5393   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5394
5395   CombineTo(N, NewValue);
5396
5397   // Replace uses of the original load (before extension)
5398   // with a truncate of the concatenated sextloaded vectors.
5399   SDValue Trunc =
5400       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5401   CombineTo(N0.getNode(), Trunc, NewChain);
5402   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5403                   (ISD::NodeType)N->getOpcode());
5404   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5405 }
5406
5407 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5408   SDValue N0 = N->getOperand(0);
5409   EVT VT = N->getValueType(0);
5410
5411   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5412                                               LegalOperations))
5413     return SDValue(Res, 0);
5414
5415   // fold (sext (sext x)) -> (sext x)
5416   // fold (sext (aext x)) -> (sext x)
5417   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5418     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5419                        N0.getOperand(0));
5420
5421   if (N0.getOpcode() == ISD::TRUNCATE) {
5422     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5423     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5424     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5425     if (NarrowLoad.getNode()) {
5426       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5427       if (NarrowLoad.getNode() != N0.getNode()) {
5428         CombineTo(N0.getNode(), NarrowLoad);
5429         // CombineTo deleted the truncate, if needed, but not what's under it.
5430         AddToWorklist(oye);
5431       }
5432       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5433     }
5434
5435     // See if the value being truncated is already sign extended.  If so, just
5436     // eliminate the trunc/sext pair.
5437     SDValue Op = N0.getOperand(0);
5438     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5439     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5440     unsigned DestBits = VT.getScalarType().getSizeInBits();
5441     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5442
5443     if (OpBits == DestBits) {
5444       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5445       // bits, it is already ready.
5446       if (NumSignBits > DestBits-MidBits)
5447         return Op;
5448     } else if (OpBits < DestBits) {
5449       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5450       // bits, just sext from i32.
5451       if (NumSignBits > OpBits-MidBits)
5452         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5453     } else {
5454       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5455       // bits, just truncate to i32.
5456       if (NumSignBits > OpBits-MidBits)
5457         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5458     }
5459
5460     // fold (sext (truncate x)) -> (sextinreg x).
5461     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5462                                                  N0.getValueType())) {
5463       if (OpBits < DestBits)
5464         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5465       else if (OpBits > DestBits)
5466         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5467       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5468                          DAG.getValueType(N0.getValueType()));
5469     }
5470   }
5471
5472   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5473   // Only generate vector extloads when 1) they're legal, and 2) they are
5474   // deemed desirable by the target.
5475   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5476       ((!LegalOperations && !VT.isVector() &&
5477         !cast<LoadSDNode>(N0)->isVolatile()) ||
5478        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5479     bool DoXform = true;
5480     SmallVector<SDNode*, 4> SetCCs;
5481     if (!N0.hasOneUse())
5482       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5483     if (VT.isVector())
5484       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5485     if (DoXform) {
5486       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5487       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5488                                        LN0->getChain(),
5489                                        LN0->getBasePtr(), N0.getValueType(),
5490                                        LN0->getMemOperand());
5491       CombineTo(N, ExtLoad);
5492       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5493                                   N0.getValueType(), ExtLoad);
5494       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5495       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5496                       ISD::SIGN_EXTEND);
5497       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5498     }
5499   }
5500
5501   // fold (sext (load x)) to multiple smaller sextloads.
5502   // Only on illegal but splittable vectors.
5503   if (SDValue ExtLoad = CombineExtLoad(N))
5504     return ExtLoad;
5505
5506   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5507   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5508   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5509       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5510     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5511     EVT MemVT = LN0->getMemoryVT();
5512     if ((!LegalOperations && !LN0->isVolatile()) ||
5513         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5514       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5515                                        LN0->getChain(),
5516                                        LN0->getBasePtr(), MemVT,
5517                                        LN0->getMemOperand());
5518       CombineTo(N, ExtLoad);
5519       CombineTo(N0.getNode(),
5520                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5521                             N0.getValueType(), ExtLoad),
5522                 ExtLoad.getValue(1));
5523       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5524     }
5525   }
5526
5527   // fold (sext (and/or/xor (load x), cst)) ->
5528   //      (and/or/xor (sextload x), (sext cst))
5529   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5530        N0.getOpcode() == ISD::XOR) &&
5531       isa<LoadSDNode>(N0.getOperand(0)) &&
5532       N0.getOperand(1).getOpcode() == ISD::Constant &&
5533       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5534       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5535     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5536     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5537       bool DoXform = true;
5538       SmallVector<SDNode*, 4> SetCCs;
5539       if (!N0.hasOneUse())
5540         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5541                                           SetCCs, TLI);
5542       if (DoXform) {
5543         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5544                                          LN0->getChain(), LN0->getBasePtr(),
5545                                          LN0->getMemoryVT(),
5546                                          LN0->getMemOperand());
5547         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5548         Mask = Mask.sext(VT.getSizeInBits());
5549         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5550                                   ExtLoad, DAG.getConstant(Mask, VT));
5551         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5552                                     SDLoc(N0.getOperand(0)),
5553                                     N0.getOperand(0).getValueType(), ExtLoad);
5554         CombineTo(N, And);
5555         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5556         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5557                         ISD::SIGN_EXTEND);
5558         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5559       }
5560     }
5561   }
5562
5563   if (N0.getOpcode() == ISD::SETCC) {
5564     EVT N0VT = N0.getOperand(0).getValueType();
5565     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5566     // Only do this before legalize for now.
5567     if (VT.isVector() && !LegalOperations &&
5568         TLI.getBooleanContents(N0VT) ==
5569             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5570       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5571       // of the same size as the compared operands. Only optimize sext(setcc())
5572       // if this is the case.
5573       EVT SVT = getSetCCResultType(N0VT);
5574
5575       // We know that the # elements of the results is the same as the
5576       // # elements of the compare (and the # elements of the compare result
5577       // for that matter).  Check to see that they are the same size.  If so,
5578       // we know that the element size of the sext'd result matches the
5579       // element size of the compare operands.
5580       if (VT.getSizeInBits() == SVT.getSizeInBits())
5581         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5582                              N0.getOperand(1),
5583                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5584
5585       // If the desired elements are smaller or larger than the source
5586       // elements we can use a matching integer vector type and then
5587       // truncate/sign extend
5588       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5589       if (SVT == MatchingVectorType) {
5590         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5591                                N0.getOperand(0), N0.getOperand(1),
5592                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5593         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5594       }
5595     }
5596
5597     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5598     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5599     SDValue NegOne =
5600       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5601     SDValue SCC =
5602       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5603                        NegOne, DAG.getConstant(0, VT),
5604                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5605     if (SCC.getNode()) return SCC;
5606
5607     if (!VT.isVector()) {
5608       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5609       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5610         SDLoc DL(N);
5611         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5612         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5613                                      N0.getOperand(0), N0.getOperand(1), CC);
5614         return DAG.getSelect(DL, VT, SetCC,
5615                              NegOne, DAG.getConstant(0, VT));
5616       }
5617     }
5618   }
5619
5620   // fold (sext x) -> (zext x) if the sign bit is known zero.
5621   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5622       DAG.SignBitIsZero(N0))
5623     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5624
5625   return SDValue();
5626 }
5627
5628 // isTruncateOf - If N is a truncate of some other value, return true, record
5629 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5630 // This function computes KnownZero to avoid a duplicated call to
5631 // computeKnownBits in the caller.
5632 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5633                          APInt &KnownZero) {
5634   APInt KnownOne;
5635   if (N->getOpcode() == ISD::TRUNCATE) {
5636     Op = N->getOperand(0);
5637     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5638     return true;
5639   }
5640
5641   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5642       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5643     return false;
5644
5645   SDValue Op0 = N->getOperand(0);
5646   SDValue Op1 = N->getOperand(1);
5647   assert(Op0.getValueType() == Op1.getValueType());
5648
5649   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5650   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5651   if (COp0 && COp0->isNullValue())
5652     Op = Op1;
5653   else if (COp1 && COp1->isNullValue())
5654     Op = Op0;
5655   else
5656     return false;
5657
5658   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5659
5660   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5661     return false;
5662
5663   return true;
5664 }
5665
5666 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5667   SDValue N0 = N->getOperand(0);
5668   EVT VT = N->getValueType(0);
5669
5670   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5671                                               LegalOperations))
5672     return SDValue(Res, 0);
5673
5674   // fold (zext (zext x)) -> (zext x)
5675   // fold (zext (aext x)) -> (zext x)
5676   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5677     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5678                        N0.getOperand(0));
5679
5680   // fold (zext (truncate x)) -> (zext x) or
5681   //      (zext (truncate x)) -> (truncate x)
5682   // This is valid when the truncated bits of x are already zero.
5683   // FIXME: We should extend this to work for vectors too.
5684   SDValue Op;
5685   APInt KnownZero;
5686   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5687     APInt TruncatedBits =
5688       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5689       APInt(Op.getValueSizeInBits(), 0) :
5690       APInt::getBitsSet(Op.getValueSizeInBits(),
5691                         N0.getValueSizeInBits(),
5692                         std::min(Op.getValueSizeInBits(),
5693                                  VT.getSizeInBits()));
5694     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5695       if (VT.bitsGT(Op.getValueType()))
5696         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5697       if (VT.bitsLT(Op.getValueType()))
5698         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5699
5700       return Op;
5701     }
5702   }
5703
5704   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5705   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5706   if (N0.getOpcode() == ISD::TRUNCATE) {
5707     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5708     if (NarrowLoad.getNode()) {
5709       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5710       if (NarrowLoad.getNode() != N0.getNode()) {
5711         CombineTo(N0.getNode(), NarrowLoad);
5712         // CombineTo deleted the truncate, if needed, but not what's under it.
5713         AddToWorklist(oye);
5714       }
5715       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5716     }
5717   }
5718
5719   // fold (zext (truncate x)) -> (and x, mask)
5720   if (N0.getOpcode() == ISD::TRUNCATE &&
5721       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5722
5723     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5724     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5725     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5726     if (NarrowLoad.getNode()) {
5727       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5728       if (NarrowLoad.getNode() != N0.getNode()) {
5729         CombineTo(N0.getNode(), NarrowLoad);
5730         // CombineTo deleted the truncate, if needed, but not what's under it.
5731         AddToWorklist(oye);
5732       }
5733       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5734     }
5735
5736     SDValue Op = N0.getOperand(0);
5737     if (Op.getValueType().bitsLT(VT)) {
5738       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5739       AddToWorklist(Op.getNode());
5740     } else if (Op.getValueType().bitsGT(VT)) {
5741       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5742       AddToWorklist(Op.getNode());
5743     }
5744     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5745                                   N0.getValueType().getScalarType());
5746   }
5747
5748   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5749   // if either of the casts is not free.
5750   if (N0.getOpcode() == ISD::AND &&
5751       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5752       N0.getOperand(1).getOpcode() == ISD::Constant &&
5753       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5754                            N0.getValueType()) ||
5755        !TLI.isZExtFree(N0.getValueType(), VT))) {
5756     SDValue X = N0.getOperand(0).getOperand(0);
5757     if (X.getValueType().bitsLT(VT)) {
5758       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5759     } else if (X.getValueType().bitsGT(VT)) {
5760       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5761     }
5762     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5763     Mask = Mask.zext(VT.getSizeInBits());
5764     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5765                        X, DAG.getConstant(Mask, VT));
5766   }
5767
5768   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5769   // Only generate vector extloads when 1) they're legal, and 2) they are
5770   // deemed desirable by the target.
5771   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5772       ((!LegalOperations && !VT.isVector() &&
5773         !cast<LoadSDNode>(N0)->isVolatile()) ||
5774        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5775     bool DoXform = true;
5776     SmallVector<SDNode*, 4> SetCCs;
5777     if (!N0.hasOneUse())
5778       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5779     if (VT.isVector())
5780       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5781     if (DoXform) {
5782       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5783       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5784                                        LN0->getChain(),
5785                                        LN0->getBasePtr(), N0.getValueType(),
5786                                        LN0->getMemOperand());
5787       CombineTo(N, ExtLoad);
5788       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5789                                   N0.getValueType(), ExtLoad);
5790       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5791
5792       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5793                       ISD::ZERO_EXTEND);
5794       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5795     }
5796   }
5797
5798   // fold (zext (load x)) to multiple smaller zextloads.
5799   // Only on illegal but splittable vectors.
5800   if (SDValue ExtLoad = CombineExtLoad(N))
5801     return ExtLoad;
5802
5803   // fold (zext (and/or/xor (load x), cst)) ->
5804   //      (and/or/xor (zextload x), (zext cst))
5805   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5806        N0.getOpcode() == ISD::XOR) &&
5807       isa<LoadSDNode>(N0.getOperand(0)) &&
5808       N0.getOperand(1).getOpcode() == ISD::Constant &&
5809       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5810       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5811     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5812     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5813       bool DoXform = true;
5814       SmallVector<SDNode*, 4> SetCCs;
5815       if (!N0.hasOneUse())
5816         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5817                                           SetCCs, TLI);
5818       if (DoXform) {
5819         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5820                                          LN0->getChain(), LN0->getBasePtr(),
5821                                          LN0->getMemoryVT(),
5822                                          LN0->getMemOperand());
5823         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5824         Mask = Mask.zext(VT.getSizeInBits());
5825         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5826                                   ExtLoad, DAG.getConstant(Mask, VT));
5827         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5828                                     SDLoc(N0.getOperand(0)),
5829                                     N0.getOperand(0).getValueType(), ExtLoad);
5830         CombineTo(N, And);
5831         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5832         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5833                         ISD::ZERO_EXTEND);
5834         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5835       }
5836     }
5837   }
5838
5839   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5840   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5841   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5842       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5843     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5844     EVT MemVT = LN0->getMemoryVT();
5845     if ((!LegalOperations && !LN0->isVolatile()) ||
5846         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5847       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5848                                        LN0->getChain(),
5849                                        LN0->getBasePtr(), MemVT,
5850                                        LN0->getMemOperand());
5851       CombineTo(N, ExtLoad);
5852       CombineTo(N0.getNode(),
5853                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5854                             ExtLoad),
5855                 ExtLoad.getValue(1));
5856       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5857     }
5858   }
5859
5860   if (N0.getOpcode() == ISD::SETCC) {
5861     if (!LegalOperations && VT.isVector() &&
5862         N0.getValueType().getVectorElementType() == MVT::i1) {
5863       EVT N0VT = N0.getOperand(0).getValueType();
5864       if (getSetCCResultType(N0VT) == N0.getValueType())
5865         return SDValue();
5866
5867       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5868       // Only do this before legalize for now.
5869       EVT EltVT = VT.getVectorElementType();
5870       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5871                                     DAG.getConstant(1, EltVT));
5872       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5873         // We know that the # elements of the results is the same as the
5874         // # elements of the compare (and the # elements of the compare result
5875         // for that matter).  Check to see that they are the same size.  If so,
5876         // we know that the element size of the sext'd result matches the
5877         // element size of the compare operands.
5878         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5879                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5880                                          N0.getOperand(1),
5881                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5882                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5883                                        OneOps));
5884
5885       // If the desired elements are smaller or larger than the source
5886       // elements we can use a matching integer vector type and then
5887       // truncate/sign extend
5888       EVT MatchingElementType =
5889         EVT::getIntegerVT(*DAG.getContext(),
5890                           N0VT.getScalarType().getSizeInBits());
5891       EVT MatchingVectorType =
5892         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5893                          N0VT.getVectorNumElements());
5894       SDValue VsetCC =
5895         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5896                       N0.getOperand(1),
5897                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5898       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5899                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5900                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5901     }
5902
5903     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5904     SDValue SCC =
5905       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5906                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5907                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5908     if (SCC.getNode()) return SCC;
5909   }
5910
5911   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5912   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5913       isa<ConstantSDNode>(N0.getOperand(1)) &&
5914       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5915       N0.hasOneUse()) {
5916     SDValue ShAmt = N0.getOperand(1);
5917     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5918     if (N0.getOpcode() == ISD::SHL) {
5919       SDValue InnerZExt = N0.getOperand(0);
5920       // If the original shl may be shifting out bits, do not perform this
5921       // transformation.
5922       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5923         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5924       if (ShAmtVal > KnownZeroBits)
5925         return SDValue();
5926     }
5927
5928     SDLoc DL(N);
5929
5930     // Ensure that the shift amount is wide enough for the shifted value.
5931     if (VT.getSizeInBits() >= 256)
5932       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5933
5934     return DAG.getNode(N0.getOpcode(), DL, VT,
5935                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5936                        ShAmt);
5937   }
5938
5939   return SDValue();
5940 }
5941
5942 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5943   SDValue N0 = N->getOperand(0);
5944   EVT VT = N->getValueType(0);
5945
5946   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5947                                               LegalOperations))
5948     return SDValue(Res, 0);
5949
5950   // fold (aext (aext x)) -> (aext x)
5951   // fold (aext (zext x)) -> (zext x)
5952   // fold (aext (sext x)) -> (sext x)
5953   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5954       N0.getOpcode() == ISD::ZERO_EXTEND ||
5955       N0.getOpcode() == ISD::SIGN_EXTEND)
5956     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5957
5958   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5959   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5960   if (N0.getOpcode() == ISD::TRUNCATE) {
5961     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5962     if (NarrowLoad.getNode()) {
5963       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5964       if (NarrowLoad.getNode() != N0.getNode()) {
5965         CombineTo(N0.getNode(), NarrowLoad);
5966         // CombineTo deleted the truncate, if needed, but not what's under it.
5967         AddToWorklist(oye);
5968       }
5969       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5970     }
5971   }
5972
5973   // fold (aext (truncate x))
5974   if (N0.getOpcode() == ISD::TRUNCATE) {
5975     SDValue TruncOp = N0.getOperand(0);
5976     if (TruncOp.getValueType() == VT)
5977       return TruncOp; // x iff x size == zext size.
5978     if (TruncOp.getValueType().bitsGT(VT))
5979       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5980     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5981   }
5982
5983   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5984   // if the trunc is not free.
5985   if (N0.getOpcode() == ISD::AND &&
5986       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5987       N0.getOperand(1).getOpcode() == ISD::Constant &&
5988       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5989                           N0.getValueType())) {
5990     SDValue X = N0.getOperand(0).getOperand(0);
5991     if (X.getValueType().bitsLT(VT)) {
5992       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5993     } else if (X.getValueType().bitsGT(VT)) {
5994       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5995     }
5996     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5997     Mask = Mask.zext(VT.getSizeInBits());
5998     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5999                        X, DAG.getConstant(Mask, VT));
6000   }
6001
6002   // fold (aext (load x)) -> (aext (truncate (extload x)))
6003   // None of the supported targets knows how to perform load and any_ext
6004   // on vectors in one instruction.  We only perform this transformation on
6005   // scalars.
6006   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6007       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6008       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6009     bool DoXform = true;
6010     SmallVector<SDNode*, 4> SetCCs;
6011     if (!N0.hasOneUse())
6012       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6013     if (DoXform) {
6014       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6015       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6016                                        LN0->getChain(),
6017                                        LN0->getBasePtr(), N0.getValueType(),
6018                                        LN0->getMemOperand());
6019       CombineTo(N, ExtLoad);
6020       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6021                                   N0.getValueType(), ExtLoad);
6022       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6023       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6024                       ISD::ANY_EXTEND);
6025       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6026     }
6027   }
6028
6029   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6030   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6031   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6032   if (N0.getOpcode() == ISD::LOAD &&
6033       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6034       N0.hasOneUse()) {
6035     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6036     ISD::LoadExtType ExtType = LN0->getExtensionType();
6037     EVT MemVT = LN0->getMemoryVT();
6038     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6039       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6040                                        VT, LN0->getChain(), LN0->getBasePtr(),
6041                                        MemVT, LN0->getMemOperand());
6042       CombineTo(N, ExtLoad);
6043       CombineTo(N0.getNode(),
6044                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6045                             N0.getValueType(), ExtLoad),
6046                 ExtLoad.getValue(1));
6047       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6048     }
6049   }
6050
6051   if (N0.getOpcode() == ISD::SETCC) {
6052     // For vectors:
6053     // aext(setcc) -> vsetcc
6054     // aext(setcc) -> truncate(vsetcc)
6055     // aext(setcc) -> aext(vsetcc)
6056     // Only do this before legalize for now.
6057     if (VT.isVector() && !LegalOperations) {
6058       EVT N0VT = N0.getOperand(0).getValueType();
6059         // We know that the # elements of the results is the same as the
6060         // # elements of the compare (and the # elements of the compare result
6061         // for that matter).  Check to see that they are the same size.  If so,
6062         // we know that the element size of the sext'd result matches the
6063         // element size of the compare operands.
6064       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6065         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6066                              N0.getOperand(1),
6067                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6068       // If the desired elements are smaller or larger than the source
6069       // elements we can use a matching integer vector type and then
6070       // truncate/any extend
6071       else {
6072         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6073         SDValue VsetCC =
6074           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6075                         N0.getOperand(1),
6076                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6077         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6078       }
6079     }
6080
6081     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6082     SDValue SCC =
6083       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6084                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6085                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6086     if (SCC.getNode())
6087       return SCC;
6088   }
6089
6090   return SDValue();
6091 }
6092
6093 /// See if the specified operand can be simplified with the knowledge that only
6094 /// the bits specified by Mask are used.  If so, return the simpler operand,
6095 /// otherwise return a null SDValue.
6096 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6097   switch (V.getOpcode()) {
6098   default: break;
6099   case ISD::Constant: {
6100     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6101     assert(CV && "Const value should be ConstSDNode.");
6102     const APInt &CVal = CV->getAPIntValue();
6103     APInt NewVal = CVal & Mask;
6104     if (NewVal != CVal)
6105       return DAG.getConstant(NewVal, V.getValueType());
6106     break;
6107   }
6108   case ISD::OR:
6109   case ISD::XOR:
6110     // If the LHS or RHS don't contribute bits to the or, drop them.
6111     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6112       return V.getOperand(1);
6113     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6114       return V.getOperand(0);
6115     break;
6116   case ISD::SRL:
6117     // Only look at single-use SRLs.
6118     if (!V.getNode()->hasOneUse())
6119       break;
6120     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6121       // See if we can recursively simplify the LHS.
6122       unsigned Amt = RHSC->getZExtValue();
6123
6124       // Watch out for shift count overflow though.
6125       if (Amt >= Mask.getBitWidth()) break;
6126       APInt NewMask = Mask << Amt;
6127       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6128       if (SimplifyLHS.getNode())
6129         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6130                            SimplifyLHS, V.getOperand(1));
6131     }
6132   }
6133   return SDValue();
6134 }
6135
6136 /// If the result of a wider load is shifted to right of N  bits and then
6137 /// truncated to a narrower type and where N is a multiple of number of bits of
6138 /// the narrower type, transform it to a narrower load from address + N / num of
6139 /// bits of new type. If the result is to be extended, also fold the extension
6140 /// to form a extending load.
6141 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6142   unsigned Opc = N->getOpcode();
6143
6144   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6145   SDValue N0 = N->getOperand(0);
6146   EVT VT = N->getValueType(0);
6147   EVT ExtVT = VT;
6148
6149   // This transformation isn't valid for vector loads.
6150   if (VT.isVector())
6151     return SDValue();
6152
6153   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6154   // extended to VT.
6155   if (Opc == ISD::SIGN_EXTEND_INREG) {
6156     ExtType = ISD::SEXTLOAD;
6157     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6158   } else if (Opc == ISD::SRL) {
6159     // Another special-case: SRL is basically zero-extending a narrower value.
6160     ExtType = ISD::ZEXTLOAD;
6161     N0 = SDValue(N, 0);
6162     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6163     if (!N01) return SDValue();
6164     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6165                               VT.getSizeInBits() - N01->getZExtValue());
6166   }
6167   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6168     return SDValue();
6169
6170   unsigned EVTBits = ExtVT.getSizeInBits();
6171
6172   // Do not generate loads of non-round integer types since these can
6173   // be expensive (and would be wrong if the type is not byte sized).
6174   if (!ExtVT.isRound())
6175     return SDValue();
6176
6177   unsigned ShAmt = 0;
6178   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6179     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6180       ShAmt = N01->getZExtValue();
6181       // Is the shift amount a multiple of size of VT?
6182       if ((ShAmt & (EVTBits-1)) == 0) {
6183         N0 = N0.getOperand(0);
6184         // Is the load width a multiple of size of VT?
6185         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6186           return SDValue();
6187       }
6188
6189       // At this point, we must have a load or else we can't do the transform.
6190       if (!isa<LoadSDNode>(N0)) return SDValue();
6191
6192       // Because a SRL must be assumed to *need* to zero-extend the high bits
6193       // (as opposed to anyext the high bits), we can't combine the zextload
6194       // lowering of SRL and an sextload.
6195       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6196         return SDValue();
6197
6198       // If the shift amount is larger than the input type then we're not
6199       // accessing any of the loaded bytes.  If the load was a zextload/extload
6200       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6201       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6202         return SDValue();
6203     }
6204   }
6205
6206   // If the load is shifted left (and the result isn't shifted back right),
6207   // we can fold the truncate through the shift.
6208   unsigned ShLeftAmt = 0;
6209   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6210       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6211     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6212       ShLeftAmt = N01->getZExtValue();
6213       N0 = N0.getOperand(0);
6214     }
6215   }
6216
6217   // If we haven't found a load, we can't narrow it.  Don't transform one with
6218   // multiple uses, this would require adding a new load.
6219   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6220     return SDValue();
6221
6222   // Don't change the width of a volatile load.
6223   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6224   if (LN0->isVolatile())
6225     return SDValue();
6226
6227   // Verify that we are actually reducing a load width here.
6228   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6229     return SDValue();
6230
6231   // For the transform to be legal, the load must produce only two values
6232   // (the value loaded and the chain).  Don't transform a pre-increment
6233   // load, for example, which produces an extra value.  Otherwise the
6234   // transformation is not equivalent, and the downstream logic to replace
6235   // uses gets things wrong.
6236   if (LN0->getNumValues() > 2)
6237     return SDValue();
6238
6239   // If the load that we're shrinking is an extload and we're not just
6240   // discarding the extension we can't simply shrink the load. Bail.
6241   // TODO: It would be possible to merge the extensions in some cases.
6242   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6243       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6244     return SDValue();
6245
6246   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6247     return SDValue();
6248
6249   EVT PtrType = N0.getOperand(1).getValueType();
6250
6251   if (PtrType == MVT::Untyped || PtrType.isExtended())
6252     // It's not possible to generate a constant of extended or untyped type.
6253     return SDValue();
6254
6255   // For big endian targets, we need to adjust the offset to the pointer to
6256   // load the correct bytes.
6257   if (TLI.isBigEndian()) {
6258     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6259     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6260     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6261   }
6262
6263   uint64_t PtrOff = ShAmt / 8;
6264   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6265   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6266                                PtrType, LN0->getBasePtr(),
6267                                DAG.getConstant(PtrOff, PtrType));
6268   AddToWorklist(NewPtr.getNode());
6269
6270   SDValue Load;
6271   if (ExtType == ISD::NON_EXTLOAD)
6272     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6273                         LN0->getPointerInfo().getWithOffset(PtrOff),
6274                         LN0->isVolatile(), LN0->isNonTemporal(),
6275                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6276   else
6277     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6278                           LN0->getPointerInfo().getWithOffset(PtrOff),
6279                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6280                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6281
6282   // Replace the old load's chain with the new load's chain.
6283   WorklistRemover DeadNodes(*this);
6284   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6285
6286   // Shift the result left, if we've swallowed a left shift.
6287   SDValue Result = Load;
6288   if (ShLeftAmt != 0) {
6289     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6290     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6291       ShImmTy = VT;
6292     // If the shift amount is as large as the result size (but, presumably,
6293     // no larger than the source) then the useful bits of the result are
6294     // zero; we can't simply return the shortened shift, because the result
6295     // of that operation is undefined.
6296     if (ShLeftAmt >= VT.getSizeInBits())
6297       Result = DAG.getConstant(0, VT);
6298     else
6299       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6300                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6301   }
6302
6303   // Return the new loaded value.
6304   return Result;
6305 }
6306
6307 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6308   SDValue N0 = N->getOperand(0);
6309   SDValue N1 = N->getOperand(1);
6310   EVT VT = N->getValueType(0);
6311   EVT EVT = cast<VTSDNode>(N1)->getVT();
6312   unsigned VTBits = VT.getScalarType().getSizeInBits();
6313   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6314
6315   // fold (sext_in_reg c1) -> c1
6316   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6317     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6318
6319   // If the input is already sign extended, just drop the extension.
6320   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6321     return N0;
6322
6323   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6324   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6325       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6326     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6327                        N0.getOperand(0), N1);
6328
6329   // fold (sext_in_reg (sext x)) -> (sext x)
6330   // fold (sext_in_reg (aext x)) -> (sext x)
6331   // if x is small enough.
6332   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6333     SDValue N00 = N0.getOperand(0);
6334     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6335         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6336       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6337   }
6338
6339   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6340   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6341     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6342
6343   // fold operands of sext_in_reg based on knowledge that the top bits are not
6344   // demanded.
6345   if (SimplifyDemandedBits(SDValue(N, 0)))
6346     return SDValue(N, 0);
6347
6348   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6349   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6350   SDValue NarrowLoad = ReduceLoadWidth(N);
6351   if (NarrowLoad.getNode())
6352     return NarrowLoad;
6353
6354   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6355   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6356   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6357   if (N0.getOpcode() == ISD::SRL) {
6358     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6359       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6360         // We can turn this into an SRA iff the input to the SRL is already sign
6361         // extended enough.
6362         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6363         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6364           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6365                              N0.getOperand(0), N0.getOperand(1));
6366       }
6367   }
6368
6369   // fold (sext_inreg (extload x)) -> (sextload x)
6370   if (ISD::isEXTLoad(N0.getNode()) &&
6371       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6372       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6373       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6374        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6375     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6376     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6377                                      LN0->getChain(),
6378                                      LN0->getBasePtr(), EVT,
6379                                      LN0->getMemOperand());
6380     CombineTo(N, ExtLoad);
6381     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6382     AddToWorklist(ExtLoad.getNode());
6383     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6384   }
6385   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6386   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6387       N0.hasOneUse() &&
6388       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6389       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6390        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6391     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6392     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6393                                      LN0->getChain(),
6394                                      LN0->getBasePtr(), EVT,
6395                                      LN0->getMemOperand());
6396     CombineTo(N, ExtLoad);
6397     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6398     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6399   }
6400
6401   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6402   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6403     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6404                                        N0.getOperand(1), false);
6405     if (BSwap.getNode())
6406       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6407                          BSwap, N1);
6408   }
6409
6410   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6411   // into a build_vector.
6412   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6413     SmallVector<SDValue, 8> Elts;
6414     unsigned NumElts = N0->getNumOperands();
6415     unsigned ShAmt = VTBits - EVTBits;
6416
6417     for (unsigned i = 0; i != NumElts; ++i) {
6418       SDValue Op = N0->getOperand(i);
6419       if (Op->getOpcode() == ISD::UNDEF) {
6420         Elts.push_back(Op);
6421         continue;
6422       }
6423
6424       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6425       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6426       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6427                                      Op.getValueType()));
6428     }
6429
6430     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6431   }
6432
6433   return SDValue();
6434 }
6435
6436 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6437   SDValue N0 = N->getOperand(0);
6438   EVT VT = N->getValueType(0);
6439   bool isLE = TLI.isLittleEndian();
6440
6441   // noop truncate
6442   if (N0.getValueType() == N->getValueType(0))
6443     return N0;
6444   // fold (truncate c1) -> c1
6445   if (isa<ConstantSDNode>(N0))
6446     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6447   // fold (truncate (truncate x)) -> (truncate x)
6448   if (N0.getOpcode() == ISD::TRUNCATE)
6449     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6450   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6451   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6452       N0.getOpcode() == ISD::SIGN_EXTEND ||
6453       N0.getOpcode() == ISD::ANY_EXTEND) {
6454     if (N0.getOperand(0).getValueType().bitsLT(VT))
6455       // if the source is smaller than the dest, we still need an extend
6456       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6457                          N0.getOperand(0));
6458     if (N0.getOperand(0).getValueType().bitsGT(VT))
6459       // if the source is larger than the dest, than we just need the truncate
6460       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6461     // if the source and dest are the same type, we can drop both the extend
6462     // and the truncate.
6463     return N0.getOperand(0);
6464   }
6465
6466   // Fold extract-and-trunc into a narrow extract. For example:
6467   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6468   //   i32 y = TRUNCATE(i64 x)
6469   //        -- becomes --
6470   //   v16i8 b = BITCAST (v2i64 val)
6471   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6472   //
6473   // Note: We only run this optimization after type legalization (which often
6474   // creates this pattern) and before operation legalization after which
6475   // we need to be more careful about the vector instructions that we generate.
6476   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6477       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6478
6479     EVT VecTy = N0.getOperand(0).getValueType();
6480     EVT ExTy = N0.getValueType();
6481     EVT TrTy = N->getValueType(0);
6482
6483     unsigned NumElem = VecTy.getVectorNumElements();
6484     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6485
6486     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6487     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6488
6489     SDValue EltNo = N0->getOperand(1);
6490     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6491       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6492       EVT IndexTy = TLI.getVectorIdxTy();
6493       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6494
6495       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6496                               NVT, N0.getOperand(0));
6497
6498       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6499                          SDLoc(N), TrTy, V,
6500                          DAG.getConstant(Index, IndexTy));
6501     }
6502   }
6503
6504   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6505   if (N0.getOpcode() == ISD::SELECT) {
6506     EVT SrcVT = N0.getValueType();
6507     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6508         TLI.isTruncateFree(SrcVT, VT)) {
6509       SDLoc SL(N0);
6510       SDValue Cond = N0.getOperand(0);
6511       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6512       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6513       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6514     }
6515   }
6516
6517   // Fold a series of buildvector, bitcast, and truncate if possible.
6518   // For example fold
6519   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6520   //   (2xi32 (buildvector x, y)).
6521   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6522       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6523       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6524       N0.getOperand(0).hasOneUse()) {
6525
6526     SDValue BuildVect = N0.getOperand(0);
6527     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6528     EVT TruncVecEltTy = VT.getVectorElementType();
6529
6530     // Check that the element types match.
6531     if (BuildVectEltTy == TruncVecEltTy) {
6532       // Now we only need to compute the offset of the truncated elements.
6533       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6534       unsigned TruncVecNumElts = VT.getVectorNumElements();
6535       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6536
6537       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6538              "Invalid number of elements");
6539
6540       SmallVector<SDValue, 8> Opnds;
6541       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6542         Opnds.push_back(BuildVect.getOperand(i));
6543
6544       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6545     }
6546   }
6547
6548   // See if we can simplify the input to this truncate through knowledge that
6549   // only the low bits are being used.
6550   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6551   // Currently we only perform this optimization on scalars because vectors
6552   // may have different active low bits.
6553   if (!VT.isVector()) {
6554     SDValue Shorter =
6555       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6556                                                VT.getSizeInBits()));
6557     if (Shorter.getNode())
6558       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6559   }
6560   // fold (truncate (load x)) -> (smaller load x)
6561   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6562   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6563     SDValue Reduced = ReduceLoadWidth(N);
6564     if (Reduced.getNode())
6565       return Reduced;
6566     // Handle the case where the load remains an extending load even
6567     // after truncation.
6568     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6569       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6570       if (!LN0->isVolatile() &&
6571           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6572         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6573                                          VT, LN0->getChain(), LN0->getBasePtr(),
6574                                          LN0->getMemoryVT(),
6575                                          LN0->getMemOperand());
6576         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6577         return NewLoad;
6578       }
6579     }
6580   }
6581   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6582   // where ... are all 'undef'.
6583   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6584     SmallVector<EVT, 8> VTs;
6585     SDValue V;
6586     unsigned Idx = 0;
6587     unsigned NumDefs = 0;
6588
6589     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6590       SDValue X = N0.getOperand(i);
6591       if (X.getOpcode() != ISD::UNDEF) {
6592         V = X;
6593         Idx = i;
6594         NumDefs++;
6595       }
6596       // Stop if more than one members are non-undef.
6597       if (NumDefs > 1)
6598         break;
6599       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6600                                      VT.getVectorElementType(),
6601                                      X.getValueType().getVectorNumElements()));
6602     }
6603
6604     if (NumDefs == 0)
6605       return DAG.getUNDEF(VT);
6606
6607     if (NumDefs == 1) {
6608       assert(V.getNode() && "The single defined operand is empty!");
6609       SmallVector<SDValue, 8> Opnds;
6610       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6611         if (i != Idx) {
6612           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6613           continue;
6614         }
6615         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6616         AddToWorklist(NV.getNode());
6617         Opnds.push_back(NV);
6618       }
6619       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6620     }
6621   }
6622
6623   // Simplify the operands using demanded-bits information.
6624   if (!VT.isVector() &&
6625       SimplifyDemandedBits(SDValue(N, 0)))
6626     return SDValue(N, 0);
6627
6628   return SDValue();
6629 }
6630
6631 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6632   SDValue Elt = N->getOperand(i);
6633   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6634     return Elt.getNode();
6635   return Elt.getOperand(Elt.getResNo()).getNode();
6636 }
6637
6638 /// build_pair (load, load) -> load
6639 /// if load locations are consecutive.
6640 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6641   assert(N->getOpcode() == ISD::BUILD_PAIR);
6642
6643   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6644   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6645   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6646       LD1->getAddressSpace() != LD2->getAddressSpace())
6647     return SDValue();
6648   EVT LD1VT = LD1->getValueType(0);
6649
6650   if (ISD::isNON_EXTLoad(LD2) &&
6651       LD2->hasOneUse() &&
6652       // If both are volatile this would reduce the number of volatile loads.
6653       // If one is volatile it might be ok, but play conservative and bail out.
6654       !LD1->isVolatile() &&
6655       !LD2->isVolatile() &&
6656       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6657     unsigned Align = LD1->getAlignment();
6658     unsigned NewAlign = TLI.getDataLayout()->
6659       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6660
6661     if (NewAlign <= Align &&
6662         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6663       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6664                          LD1->getBasePtr(), LD1->getPointerInfo(),
6665                          false, false, false, Align);
6666   }
6667
6668   return SDValue();
6669 }
6670
6671 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6672   SDValue N0 = N->getOperand(0);
6673   EVT VT = N->getValueType(0);
6674
6675   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6676   // Only do this before legalize, since afterward the target may be depending
6677   // on the bitconvert.
6678   // First check to see if this is all constant.
6679   if (!LegalTypes &&
6680       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6681       VT.isVector()) {
6682     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6683
6684     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6685     assert(!DestEltVT.isVector() &&
6686            "Element type of vector ValueType must not be vector!");
6687     if (isSimple)
6688       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6689   }
6690
6691   // If the input is a constant, let getNode fold it.
6692   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6693     // If we can't allow illegal operations, we need to check that this is just
6694     // a fp -> int or int -> conversion and that the resulting operation will
6695     // be legal.
6696     if (!LegalOperations ||
6697         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6698          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6699         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6700          TLI.isOperationLegal(ISD::Constant, VT)))
6701       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6702   }
6703
6704   // (conv (conv x, t1), t2) -> (conv x, t2)
6705   if (N0.getOpcode() == ISD::BITCAST)
6706     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6707                        N0.getOperand(0));
6708
6709   // fold (conv (load x)) -> (load (conv*)x)
6710   // If the resultant load doesn't need a higher alignment than the original!
6711   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6712       // Do not change the width of a volatile load.
6713       !cast<LoadSDNode>(N0)->isVolatile() &&
6714       // Do not remove the cast if the types differ in endian layout.
6715       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6716       TLI.hasBigEndianPartOrdering(VT) &&
6717       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6718       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6719     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6720     unsigned Align = TLI.getDataLayout()->
6721       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6722     unsigned OrigAlign = LN0->getAlignment();
6723
6724     if (Align <= OrigAlign) {
6725       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6726                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6727                                  LN0->isVolatile(), LN0->isNonTemporal(),
6728                                  LN0->isInvariant(), OrigAlign,
6729                                  LN0->getAAInfo());
6730       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6731       return Load;
6732     }
6733   }
6734
6735   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6736   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6737   // This often reduces constant pool loads.
6738   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6739        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6740       N0.getNode()->hasOneUse() && VT.isInteger() &&
6741       !VT.isVector() && !N0.getValueType().isVector()) {
6742     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6743                                   N0.getOperand(0));
6744     AddToWorklist(NewConv.getNode());
6745
6746     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6747     if (N0.getOpcode() == ISD::FNEG)
6748       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6749                          NewConv, DAG.getConstant(SignBit, VT));
6750     assert(N0.getOpcode() == ISD::FABS);
6751     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6752                        NewConv, DAG.getConstant(~SignBit, VT));
6753   }
6754
6755   // fold (bitconvert (fcopysign cst, x)) ->
6756   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6757   // Note that we don't handle (copysign x, cst) because this can always be
6758   // folded to an fneg or fabs.
6759   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6760       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6761       VT.isInteger() && !VT.isVector()) {
6762     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6763     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6764     if (isTypeLegal(IntXVT)) {
6765       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6766                               IntXVT, N0.getOperand(1));
6767       AddToWorklist(X.getNode());
6768
6769       // If X has a different width than the result/lhs, sext it or truncate it.
6770       unsigned VTWidth = VT.getSizeInBits();
6771       if (OrigXWidth < VTWidth) {
6772         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6773         AddToWorklist(X.getNode());
6774       } else if (OrigXWidth > VTWidth) {
6775         // To get the sign bit in the right place, we have to shift it right
6776         // before truncating.
6777         X = DAG.getNode(ISD::SRL, SDLoc(X),
6778                         X.getValueType(), X,
6779                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6780         AddToWorklist(X.getNode());
6781         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6782         AddToWorklist(X.getNode());
6783       }
6784
6785       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6786       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6787                       X, DAG.getConstant(SignBit, VT));
6788       AddToWorklist(X.getNode());
6789
6790       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6791                                 VT, N0.getOperand(0));
6792       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6793                         Cst, DAG.getConstant(~SignBit, VT));
6794       AddToWorklist(Cst.getNode());
6795
6796       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6797     }
6798   }
6799
6800   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6801   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6802     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6803     if (CombineLD.getNode())
6804       return CombineLD;
6805   }
6806
6807   return SDValue();
6808 }
6809
6810 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6811   EVT VT = N->getValueType(0);
6812   return CombineConsecutiveLoads(N, VT);
6813 }
6814
6815 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6816 /// operands. DstEltVT indicates the destination element value type.
6817 SDValue DAGCombiner::
6818 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6819   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6820
6821   // If this is already the right type, we're done.
6822   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6823
6824   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6825   unsigned DstBitSize = DstEltVT.getSizeInBits();
6826
6827   // If this is a conversion of N elements of one type to N elements of another
6828   // type, convert each element.  This handles FP<->INT cases.
6829   if (SrcBitSize == DstBitSize) {
6830     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6831                               BV->getValueType(0).getVectorNumElements());
6832
6833     // Due to the FP element handling below calling this routine recursively,
6834     // we can end up with a scalar-to-vector node here.
6835     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6836       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6837                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6838                                      DstEltVT, BV->getOperand(0)));
6839
6840     SmallVector<SDValue, 8> Ops;
6841     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6842       SDValue Op = BV->getOperand(i);
6843       // If the vector element type is not legal, the BUILD_VECTOR operands
6844       // are promoted and implicitly truncated.  Make that explicit here.
6845       if (Op.getValueType() != SrcEltVT)
6846         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6847       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6848                                 DstEltVT, Op));
6849       AddToWorklist(Ops.back().getNode());
6850     }
6851     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6852   }
6853
6854   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6855   // handle annoying details of growing/shrinking FP values, we convert them to
6856   // int first.
6857   if (SrcEltVT.isFloatingPoint()) {
6858     // Convert the input float vector to a int vector where the elements are the
6859     // same sizes.
6860     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6861     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6862     SrcEltVT = IntVT;
6863   }
6864
6865   // Now we know the input is an integer vector.  If the output is a FP type,
6866   // convert to integer first, then to FP of the right size.
6867   if (DstEltVT.isFloatingPoint()) {
6868     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6869     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6870
6871     // Next, convert to FP elements of the same size.
6872     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6873   }
6874
6875   // Okay, we know the src/dst types are both integers of differing types.
6876   // Handling growing first.
6877   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6878   if (SrcBitSize < DstBitSize) {
6879     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6880
6881     SmallVector<SDValue, 8> Ops;
6882     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6883          i += NumInputsPerOutput) {
6884       bool isLE = TLI.isLittleEndian();
6885       APInt NewBits = APInt(DstBitSize, 0);
6886       bool EltIsUndef = true;
6887       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6888         // Shift the previously computed bits over.
6889         NewBits <<= SrcBitSize;
6890         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6891         if (Op.getOpcode() == ISD::UNDEF) continue;
6892         EltIsUndef = false;
6893
6894         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6895                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6896       }
6897
6898       if (EltIsUndef)
6899         Ops.push_back(DAG.getUNDEF(DstEltVT));
6900       else
6901         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6902     }
6903
6904     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6905     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6906   }
6907
6908   // Finally, this must be the case where we are shrinking elements: each input
6909   // turns into multiple outputs.
6910   bool isS2V = ISD::isScalarToVector(BV);
6911   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6912   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6913                             NumOutputsPerInput*BV->getNumOperands());
6914   SmallVector<SDValue, 8> Ops;
6915
6916   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6917     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6918       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6919         Ops.push_back(DAG.getUNDEF(DstEltVT));
6920       continue;
6921     }
6922
6923     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6924                   getAPIntValue().zextOrTrunc(SrcBitSize);
6925
6926     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6927       APInt ThisVal = OpVal.trunc(DstBitSize);
6928       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6929       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6930         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6931         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6932                            Ops[0]);
6933       OpVal = OpVal.lshr(DstBitSize);
6934     }
6935
6936     // For big endian targets, swap the order of the pieces of each element.
6937     if (TLI.isBigEndian())
6938       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6939   }
6940
6941   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6942 }
6943
6944 SDValue DAGCombiner::visitFADD(SDNode *N) {
6945   SDValue N0 = N->getOperand(0);
6946   SDValue N1 = N->getOperand(1);
6947   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6948   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6949   EVT VT = N->getValueType(0);
6950   const TargetOptions &Options = DAG.getTarget().Options;
6951
6952   // fold vector ops
6953   if (VT.isVector()) {
6954     SDValue FoldedVOp = SimplifyVBinOp(N);
6955     if (FoldedVOp.getNode()) return FoldedVOp;
6956   }
6957
6958   // fold (fadd c1, c2) -> c1 + c2
6959   if (N0CFP && N1CFP)
6960     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6961
6962   // canonicalize constant to RHS
6963   if (N0CFP && !N1CFP)
6964     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6965
6966   // fold (fadd A, (fneg B)) -> (fsub A, B)
6967   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6968       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6969     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6970                        GetNegatedExpression(N1, DAG, LegalOperations));
6971
6972   // fold (fadd (fneg A), B) -> (fsub B, A)
6973   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6974       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6975     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6976                        GetNegatedExpression(N0, DAG, LegalOperations));
6977
6978   // If 'unsafe math' is enabled, fold lots of things.
6979   if (Options.UnsafeFPMath) {
6980     // No FP constant should be created after legalization as Instruction
6981     // Selection pass has a hard time dealing with FP constants.
6982     bool AllowNewConst = (Level < AfterLegalizeDAG);
6983
6984     // fold (fadd A, 0) -> A
6985     if (N1CFP && N1CFP->getValueAPF().isZero())
6986       return N0;
6987
6988     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6989     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6990         isa<ConstantFPSDNode>(N0.getOperand(1)))
6991       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6992                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6993                                      N0.getOperand(1), N1));
6994
6995     // If allowed, fold (fadd (fneg x), x) -> 0.0
6996     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6997       return DAG.getConstantFP(0.0, VT);
6998
6999     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7000     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7001       return DAG.getConstantFP(0.0, VT);
7002
7003     // We can fold chains of FADD's of the same value into multiplications.
7004     // This transform is not safe in general because we are reducing the number
7005     // of rounding steps.
7006     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7007       if (N0.getOpcode() == ISD::FMUL) {
7008         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7009         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7010
7011         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7012         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7013           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7014                                        SDValue(CFP01, 0),
7015                                        DAG.getConstantFP(1.0, VT));
7016           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7017         }
7018
7019         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7020         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7021             N1.getOperand(0) == N1.getOperand(1) &&
7022             N0.getOperand(0) == N1.getOperand(0)) {
7023           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7024                                        SDValue(CFP01, 0),
7025                                        DAG.getConstantFP(2.0, VT));
7026           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7027                              N0.getOperand(0), NewCFP);
7028         }
7029       }
7030
7031       if (N1.getOpcode() == ISD::FMUL) {
7032         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7033         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7034
7035         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7036         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7037           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7038                                        SDValue(CFP11, 0),
7039                                        DAG.getConstantFP(1.0, VT));
7040           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7041         }
7042
7043         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7044         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7045             N0.getOperand(0) == N0.getOperand(1) &&
7046             N1.getOperand(0) == N0.getOperand(0)) {
7047           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7048                                        SDValue(CFP11, 0),
7049                                        DAG.getConstantFP(2.0, VT));
7050           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7051         }
7052       }
7053
7054       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7055         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7056         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7057         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7058             (N0.getOperand(0) == N1))
7059           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7060                              N1, DAG.getConstantFP(3.0, VT));
7061       }
7062
7063       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7064         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7065         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7066         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7067             N1.getOperand(0) == N0)
7068           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7069                              N0, DAG.getConstantFP(3.0, VT));
7070       }
7071
7072       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7073       if (AllowNewConst &&
7074           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7075           N0.getOperand(0) == N0.getOperand(1) &&
7076           N1.getOperand(0) == N1.getOperand(1) &&
7077           N0.getOperand(0) == N1.getOperand(0))
7078         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7079                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7080     }
7081   } // enable-unsafe-fp-math
7082
7083   // FADD -> FMA combines:
7084   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7085       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7086       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7087
7088     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7089     if (N0.getOpcode() == ISD::FMUL &&
7090         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7091       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7092                          N0.getOperand(0), N0.getOperand(1), N1);
7093
7094     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7095     // Note: Commutes FADD operands.
7096     if (N1.getOpcode() == ISD::FMUL &&
7097         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7098       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7099                          N1.getOperand(0), N1.getOperand(1), N0);
7100
7101     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7102     // to combine into FMA, arrange such nodes accordingly.
7103     if (TLI.isFPExtFree(VT)) {
7104
7105       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7106       if (N0.getOpcode() == ISD::FP_EXTEND) {
7107         SDValue N00 = N0.getOperand(0);
7108         if (N00.getOpcode() == ISD::FMUL)
7109           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7110                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7111                                          N00.getOperand(0)),
7112                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7113                                          N00.getOperand(1)), N1);
7114       }
7115
7116       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7117       // Note: Commutes FADD operands.
7118       if (N1.getOpcode() == ISD::FP_EXTEND) {
7119         SDValue N10 = N1.getOperand(0);
7120         if (N10.getOpcode() == ISD::FMUL)
7121           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7122                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7123                                          N10.getOperand(0)),
7124                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7125                                          N10.getOperand(1)), N0);
7126       }
7127     }
7128
7129     // More folding opportunities when target permits.
7130     if (TLI.enableAggressiveFMAFusion(VT)) {
7131
7132       // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7133       if (N0.getOpcode() == ISD::FMA &&
7134           N0.getOperand(2).getOpcode() == ISD::FMUL)
7135         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7136                            N0.getOperand(0), N0.getOperand(1),
7137                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7138                                        N0.getOperand(2).getOperand(0),
7139                                        N0.getOperand(2).getOperand(1),
7140                                        N1));
7141
7142       // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7143       if (N1->getOpcode() == ISD::FMA &&
7144           N1.getOperand(2).getOpcode() == ISD::FMUL)
7145         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7146                            N1.getOperand(0), N1.getOperand(1),
7147                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7148                                        N1.getOperand(2).getOperand(0),
7149                                        N1.getOperand(2).getOperand(1),
7150                                        N0));
7151     }
7152   }
7153
7154   return SDValue();
7155 }
7156
7157 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7158   SDValue N0 = N->getOperand(0);
7159   SDValue N1 = N->getOperand(1);
7160   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7161   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7162   EVT VT = N->getValueType(0);
7163   SDLoc dl(N);
7164   const TargetOptions &Options = DAG.getTarget().Options;
7165
7166   // fold vector ops
7167   if (VT.isVector()) {
7168     SDValue FoldedVOp = SimplifyVBinOp(N);
7169     if (FoldedVOp.getNode()) return FoldedVOp;
7170   }
7171
7172   // fold (fsub c1, c2) -> c1-c2
7173   if (N0CFP && N1CFP)
7174     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7175
7176   // fold (fsub A, (fneg B)) -> (fadd A, B)
7177   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7178     return DAG.getNode(ISD::FADD, dl, VT, N0,
7179                        GetNegatedExpression(N1, DAG, LegalOperations));
7180
7181   // If 'unsafe math' is enabled, fold lots of things.
7182   if (Options.UnsafeFPMath) {
7183     // (fsub A, 0) -> A
7184     if (N1CFP && N1CFP->getValueAPF().isZero())
7185       return N0;
7186
7187     // (fsub 0, B) -> -B
7188     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7189       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7190         return GetNegatedExpression(N1, DAG, LegalOperations);
7191       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7192         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7193     }
7194
7195     // (fsub x, x) -> 0.0
7196     if (N0 == N1)
7197       return DAG.getConstantFP(0.0f, VT);
7198
7199     // (fsub x, (fadd x, y)) -> (fneg y)
7200     // (fsub x, (fadd y, x)) -> (fneg y)
7201     if (N1.getOpcode() == ISD::FADD) {
7202       SDValue N10 = N1->getOperand(0);
7203       SDValue N11 = N1->getOperand(1);
7204
7205       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7206         return GetNegatedExpression(N11, DAG, LegalOperations);
7207
7208       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7209         return GetNegatedExpression(N10, DAG, LegalOperations);
7210     }
7211   }
7212
7213   // FSUB -> FMA combines:
7214   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7215       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7216       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7217
7218     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7219     if (N0.getOpcode() == ISD::FMUL &&
7220         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7221       return DAG.getNode(ISD::FMA, dl, VT,
7222                          N0.getOperand(0), N0.getOperand(1),
7223                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7224
7225     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7226     // Note: Commutes FSUB operands.
7227     if (N1.getOpcode() == ISD::FMUL &&
7228         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7229       return DAG.getNode(ISD::FMA, dl, VT,
7230                          DAG.getNode(ISD::FNEG, dl, VT,
7231                          N1.getOperand(0)),
7232                          N1.getOperand(1), N0);
7233
7234     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7235     if (N0.getOpcode() == ISD::FNEG &&
7236         N0.getOperand(0).getOpcode() == ISD::FMUL &&
7237         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7238             TLI.enableAggressiveFMAFusion(VT))) {
7239       SDValue N00 = N0.getOperand(0).getOperand(0);
7240       SDValue N01 = N0.getOperand(0).getOperand(1);
7241       return DAG.getNode(ISD::FMA, dl, VT,
7242                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7243                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7244     }
7245
7246     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7247     // to combine into FMA, arrange such nodes accordingly.
7248     if (TLI.isFPExtFree(VT)) {
7249
7250       // fold (fsub (fpext (fmul x, y)), z)
7251       //   -> (fma (fpext x), (fpext y), (fneg z))
7252       if (N0.getOpcode() == ISD::FP_EXTEND) {
7253         SDValue N00 = N0.getOperand(0);
7254         if (N00.getOpcode() == ISD::FMUL)
7255           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7256                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7257                                          N00.getOperand(0)),
7258                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7259                                          N00.getOperand(1)),
7260                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7261       }
7262
7263       // fold (fsub x, (fpext (fmul y, z)))
7264       //   -> (fma (fneg (fpext y)), (fpext z), x)
7265       // Note: Commutes FSUB operands.
7266       if (N1.getOpcode() == ISD::FP_EXTEND) {
7267         SDValue N10 = N1.getOperand(0);
7268         if (N10.getOpcode() == ISD::FMUL)
7269           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7270                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7271                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7272                                                      VT, N10.getOperand(0))),
7273                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7274                                          N10.getOperand(1)),
7275                              N0);
7276       }
7277
7278       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7279       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7280       if (N0.getOpcode() == ISD::FP_EXTEND) {
7281         SDValue N00 = N0.getOperand(0);
7282         if (N00.getOpcode() == ISD::FNEG) {
7283           SDValue N000 = N00.getOperand(0);
7284           if (N000.getOpcode() == ISD::FMUL) {
7285             return DAG.getNode(ISD::FMA, dl, VT,
7286                                DAG.getNode(ISD::FNEG, dl, VT,
7287                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7288                                                        VT, N000.getOperand(0))),
7289                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7290                                            N000.getOperand(1)),
7291                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7292           }
7293         }
7294       }
7295
7296       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7297       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7298       if (N0.getOpcode() == ISD::FNEG) {
7299         SDValue N00 = N0.getOperand(0);
7300         if (N00.getOpcode() == ISD::FP_EXTEND) {
7301           SDValue N000 = N00.getOperand(0);
7302           if (N000.getOpcode() == ISD::FMUL) {
7303             return DAG.getNode(ISD::FMA, dl, VT,
7304                                DAG.getNode(ISD::FNEG, dl, VT,
7305                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7306                                            VT, N000.getOperand(0))),
7307                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7308                                            N000.getOperand(1)),
7309                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7310           }
7311         }
7312       }
7313     }
7314
7315     // More folding opportunities when target permits.
7316     if (TLI.enableAggressiveFMAFusion(VT)) {
7317
7318       // fold (fsub (fma x, y, (fmul u, v)), z)
7319       //   -> (fma x, y (fma u, v, (fneg z)))
7320       if (N0.getOpcode() == ISD::FMA &&
7321           N0.getOperand(2).getOpcode() == ISD::FMUL)
7322         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7323                            N0.getOperand(0), N0.getOperand(1),
7324                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7325                                        N0.getOperand(2).getOperand(0),
7326                                        N0.getOperand(2).getOperand(1),
7327                                        DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7328                                                    N1)));
7329
7330       // fold (fsub x, (fma y, z, (fmul u, v)))
7331       //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7332       if (N1.getOpcode() == ISD::FMA &&
7333           N1.getOperand(2).getOpcode() == ISD::FMUL) {
7334         SDValue N20 = N1.getOperand(2).getOperand(0);
7335         SDValue N21 = N1.getOperand(2).getOperand(1);
7336         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7337                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7338                                        N1.getOperand(0)),
7339                            N1.getOperand(1),
7340                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7341                                        DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7342                                                    N20),
7343                                        N21, N0));
7344       }
7345     }
7346   }
7347
7348   return SDValue();
7349 }
7350
7351 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7352   SDValue N0 = N->getOperand(0);
7353   SDValue N1 = N->getOperand(1);
7354   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7355   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7356   EVT VT = N->getValueType(0);
7357   const TargetOptions &Options = DAG.getTarget().Options;
7358
7359   // fold vector ops
7360   if (VT.isVector()) {
7361     // This just handles C1 * C2 for vectors. Other vector folds are below.
7362     SDValue FoldedVOp = SimplifyVBinOp(N);
7363     if (FoldedVOp.getNode())
7364       return FoldedVOp;
7365     // Canonicalize vector constant to RHS.
7366     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7367         N1.getOpcode() != ISD::BUILD_VECTOR)
7368       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7369         if (BV0->isConstant())
7370           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7371   }
7372
7373   // fold (fmul c1, c2) -> c1*c2
7374   if (N0CFP && N1CFP)
7375     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7376
7377   // canonicalize constant to RHS
7378   if (N0CFP && !N1CFP)
7379     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7380
7381   // fold (fmul A, 1.0) -> A
7382   if (N1CFP && N1CFP->isExactlyValue(1.0))
7383     return N0;
7384
7385   if (Options.UnsafeFPMath) {
7386     // fold (fmul A, 0) -> 0
7387     if (N1CFP && N1CFP->getValueAPF().isZero())
7388       return N1;
7389
7390     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7391     if (N0.getOpcode() == ISD::FMUL) {
7392       // Fold scalars or any vector constants (not just splats).
7393       // This fold is done in general by InstCombine, but extra fmul insts
7394       // may have been generated during lowering.
7395       SDValue N01 = N0.getOperand(1);
7396       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7397       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7398       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7399           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7400         SDLoc SL(N);
7401         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7402         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7403       }
7404     }
7405
7406     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7407     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7408     // during an early run of DAGCombiner can prevent folding with fmuls
7409     // inserted during lowering.
7410     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7411       SDLoc SL(N);
7412       const SDValue Two = DAG.getConstantFP(2.0, VT);
7413       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7414       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7415     }
7416   }
7417
7418   // fold (fmul X, 2.0) -> (fadd X, X)
7419   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7420     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7421
7422   // fold (fmul X, -1.0) -> (fneg X)
7423   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7424     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7425       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7426
7427   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7428   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7429     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7430       // Both can be negated for free, check to see if at least one is cheaper
7431       // negated.
7432       if (LHSNeg == 2 || RHSNeg == 2)
7433         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7434                            GetNegatedExpression(N0, DAG, LegalOperations),
7435                            GetNegatedExpression(N1, DAG, LegalOperations));
7436     }
7437   }
7438
7439   return SDValue();
7440 }
7441
7442 SDValue DAGCombiner::visitFMA(SDNode *N) {
7443   SDValue N0 = N->getOperand(0);
7444   SDValue N1 = N->getOperand(1);
7445   SDValue N2 = N->getOperand(2);
7446   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7447   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7448   EVT VT = N->getValueType(0);
7449   SDLoc dl(N);
7450   const TargetOptions &Options = DAG.getTarget().Options;
7451
7452   // Constant fold FMA.
7453   if (isa<ConstantFPSDNode>(N0) &&
7454       isa<ConstantFPSDNode>(N1) &&
7455       isa<ConstantFPSDNode>(N2)) {
7456     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7457   }
7458
7459   if (Options.UnsafeFPMath) {
7460     if (N0CFP && N0CFP->isZero())
7461       return N2;
7462     if (N1CFP && N1CFP->isZero())
7463       return N2;
7464   }
7465   if (N0CFP && N0CFP->isExactlyValue(1.0))
7466     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7467   if (N1CFP && N1CFP->isExactlyValue(1.0))
7468     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7469
7470   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7471   if (N0CFP && !N1CFP)
7472     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7473
7474   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7475   if (Options.UnsafeFPMath && N1CFP &&
7476       N2.getOpcode() == ISD::FMUL &&
7477       N0 == N2.getOperand(0) &&
7478       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7479     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7480                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7481   }
7482
7483
7484   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7485   if (Options.UnsafeFPMath &&
7486       N0.getOpcode() == ISD::FMUL && N1CFP &&
7487       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7488     return DAG.getNode(ISD::FMA, dl, VT,
7489                        N0.getOperand(0),
7490                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7491                        N2);
7492   }
7493
7494   // (fma x, 1, y) -> (fadd x, y)
7495   // (fma x, -1, y) -> (fadd (fneg x), y)
7496   if (N1CFP) {
7497     if (N1CFP->isExactlyValue(1.0))
7498       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7499
7500     if (N1CFP->isExactlyValue(-1.0) &&
7501         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7502       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7503       AddToWorklist(RHSNeg.getNode());
7504       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7505     }
7506   }
7507
7508   // (fma x, c, x) -> (fmul x, (c+1))
7509   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7510     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7511                        DAG.getNode(ISD::FADD, dl, VT,
7512                                    N1, DAG.getConstantFP(1.0, VT)));
7513
7514   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7515   if (Options.UnsafeFPMath && N1CFP &&
7516       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7517     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7518                        DAG.getNode(ISD::FADD, dl, VT,
7519                                    N1, DAG.getConstantFP(-1.0, VT)));
7520
7521
7522   return SDValue();
7523 }
7524
7525 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7526   SDValue N0 = N->getOperand(0);
7527   SDValue N1 = N->getOperand(1);
7528   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7529   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7530   EVT VT = N->getValueType(0);
7531   SDLoc DL(N);
7532   const TargetOptions &Options = DAG.getTarget().Options;
7533
7534   // fold vector ops
7535   if (VT.isVector()) {
7536     SDValue FoldedVOp = SimplifyVBinOp(N);
7537     if (FoldedVOp.getNode()) return FoldedVOp;
7538   }
7539
7540   // fold (fdiv c1, c2) -> c1/c2
7541   if (N0CFP && N1CFP)
7542     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7543
7544   if (Options.UnsafeFPMath) {
7545     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7546     if (N1CFP) {
7547       // Compute the reciprocal 1.0 / c2.
7548       APFloat N1APF = N1CFP->getValueAPF();
7549       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7550       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7551       // Only do the transform if the reciprocal is a legal fp immediate that
7552       // isn't too nasty (eg NaN, denormal, ...).
7553       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7554           (!LegalOperations ||
7555            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7556            // backend)... we should handle this gracefully after Legalize.
7557            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7558            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7559            TLI.isFPImmLegal(Recip, VT)))
7560         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7561                            DAG.getConstantFP(Recip, VT));
7562     }
7563
7564     // If this FDIV is part of a reciprocal square root, it may be folded
7565     // into a target-specific square root estimate instruction.
7566     if (N1.getOpcode() == ISD::FSQRT) {
7567       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7568         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7569       }
7570     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7571                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7572       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7573         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7574         AddToWorklist(RV.getNode());
7575         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7576       }
7577     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7578                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7579       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7580         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7581         AddToWorklist(RV.getNode());
7582         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7583       }
7584     } else if (N1.getOpcode() == ISD::FMUL) {
7585       // Look through an FMUL. Even though this won't remove the FDIV directly,
7586       // it's still worthwhile to get rid of the FSQRT if possible.
7587       SDValue SqrtOp;
7588       SDValue OtherOp;
7589       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7590         SqrtOp = N1.getOperand(0);
7591         OtherOp = N1.getOperand(1);
7592       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7593         SqrtOp = N1.getOperand(1);
7594         OtherOp = N1.getOperand(0);
7595       }
7596       if (SqrtOp.getNode()) {
7597         // We found a FSQRT, so try to make this fold:
7598         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7599         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7600           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7601           AddToWorklist(RV.getNode());
7602           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7603         }
7604       }
7605     }
7606
7607     // Fold into a reciprocal estimate and multiply instead of a real divide.
7608     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7609       AddToWorklist(RV.getNode());
7610       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7611     }
7612   }
7613
7614   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7615   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7616     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7617       // Both can be negated for free, check to see if at least one is cheaper
7618       // negated.
7619       if (LHSNeg == 2 || RHSNeg == 2)
7620         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7621                            GetNegatedExpression(N0, DAG, LegalOperations),
7622                            GetNegatedExpression(N1, DAG, LegalOperations));
7623     }
7624   }
7625
7626   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7627   // reciprocal.
7628   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7629   // Notice that this is not always beneficial. One reason is different target
7630   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7631   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7632   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7633   if (Options.UnsafeFPMath) {
7634     // Skip if current node is a reciprocal.
7635     if (N0CFP && N0CFP->isExactlyValue(1.0))
7636       return SDValue();
7637
7638     SmallVector<SDNode *, 4> Users;
7639     // Find all FDIV users of the same divisor.
7640     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7641                               UE = N1.getNode()->use_end();
7642          UI != UE; ++UI) {
7643       SDNode *User = UI.getUse().getUser();
7644       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7645         Users.push_back(User);
7646     }
7647
7648     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7649       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7650       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7651
7652       // Dividend / Divisor -> Dividend * Reciprocal
7653       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7654         if ((*I)->getOperand(0) != FPOne) {
7655           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7656                                         (*I)->getOperand(0), Reciprocal);
7657           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7658         }
7659       }
7660       return SDValue();
7661     }
7662   }
7663
7664   return SDValue();
7665 }
7666
7667 SDValue DAGCombiner::visitFREM(SDNode *N) {
7668   SDValue N0 = N->getOperand(0);
7669   SDValue N1 = N->getOperand(1);
7670   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7671   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7672   EVT VT = N->getValueType(0);
7673
7674   // fold (frem c1, c2) -> fmod(c1,c2)
7675   if (N0CFP && N1CFP)
7676     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7677
7678   return SDValue();
7679 }
7680
7681 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7682   if (DAG.getTarget().Options.UnsafeFPMath &&
7683       !TLI.isFsqrtCheap()) {
7684     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7685     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7686       EVT VT = RV.getValueType();
7687       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7688       AddToWorklist(RV.getNode());
7689
7690       // Unfortunately, RV is now NaN if the input was exactly 0.
7691       // Select out this case and force the answer to 0.
7692       SDValue Zero = DAG.getConstantFP(0.0, VT);
7693       SDValue ZeroCmp =
7694         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7695                      N->getOperand(0), Zero, ISD::SETEQ);
7696       AddToWorklist(ZeroCmp.getNode());
7697       AddToWorklist(RV.getNode());
7698
7699       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7700                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7701       return RV;
7702     }
7703   }
7704   return SDValue();
7705 }
7706
7707 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7708   SDValue N0 = N->getOperand(0);
7709   SDValue N1 = N->getOperand(1);
7710   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7711   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7712   EVT VT = N->getValueType(0);
7713
7714   if (N0CFP && N1CFP)  // Constant fold
7715     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7716
7717   if (N1CFP) {
7718     const APFloat& V = N1CFP->getValueAPF();
7719     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7720     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7721     if (!V.isNegative()) {
7722       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7723         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7724     } else {
7725       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7726         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7727                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7728     }
7729   }
7730
7731   // copysign(fabs(x), y) -> copysign(x, y)
7732   // copysign(fneg(x), y) -> copysign(x, y)
7733   // copysign(copysign(x,z), y) -> copysign(x, y)
7734   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7735       N0.getOpcode() == ISD::FCOPYSIGN)
7736     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7737                        N0.getOperand(0), N1);
7738
7739   // copysign(x, abs(y)) -> abs(x)
7740   if (N1.getOpcode() == ISD::FABS)
7741     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7742
7743   // copysign(x, copysign(y,z)) -> copysign(x, z)
7744   if (N1.getOpcode() == ISD::FCOPYSIGN)
7745     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7746                        N0, N1.getOperand(1));
7747
7748   // copysign(x, fp_extend(y)) -> copysign(x, y)
7749   // copysign(x, fp_round(y)) -> copysign(x, y)
7750   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7751     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7752                        N0, N1.getOperand(0));
7753
7754   return SDValue();
7755 }
7756
7757 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7758   SDValue N0 = N->getOperand(0);
7759   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7760   EVT VT = N->getValueType(0);
7761   EVT OpVT = N0.getValueType();
7762
7763   // fold (sint_to_fp c1) -> c1fp
7764   if (N0C &&
7765       // ...but only if the target supports immediate floating-point values
7766       (!LegalOperations ||
7767        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7768     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7769
7770   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7771   // but UINT_TO_FP is legal on this target, try to convert.
7772   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7773       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7774     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7775     if (DAG.SignBitIsZero(N0))
7776       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7777   }
7778
7779   // The next optimizations are desirable only if SELECT_CC can be lowered.
7780   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7781     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7782     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7783         !VT.isVector() &&
7784         (!LegalOperations ||
7785          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7786       SDValue Ops[] =
7787         { N0.getOperand(0), N0.getOperand(1),
7788           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7789           N0.getOperand(2) };
7790       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7791     }
7792
7793     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7794     //      (select_cc x, y, 1.0, 0.0,, cc)
7795     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7796         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7797         (!LegalOperations ||
7798          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7799       SDValue Ops[] =
7800         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7801           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7802           N0.getOperand(0).getOperand(2) };
7803       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7804     }
7805   }
7806
7807   return SDValue();
7808 }
7809
7810 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7811   SDValue N0 = N->getOperand(0);
7812   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7813   EVT VT = N->getValueType(0);
7814   EVT OpVT = N0.getValueType();
7815
7816   // fold (uint_to_fp c1) -> c1fp
7817   if (N0C &&
7818       // ...but only if the target supports immediate floating-point values
7819       (!LegalOperations ||
7820        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7821     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7822
7823   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7824   // but SINT_TO_FP is legal on this target, try to convert.
7825   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7826       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7827     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7828     if (DAG.SignBitIsZero(N0))
7829       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7830   }
7831
7832   // The next optimizations are desirable only if SELECT_CC can be lowered.
7833   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7834     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7835
7836     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7837         (!LegalOperations ||
7838          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7839       SDValue Ops[] =
7840         { N0.getOperand(0), N0.getOperand(1),
7841           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7842           N0.getOperand(2) };
7843       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7844     }
7845   }
7846
7847   return SDValue();
7848 }
7849
7850 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7851   SDValue N0 = N->getOperand(0);
7852   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7853   EVT VT = N->getValueType(0);
7854
7855   // fold (fp_to_sint c1fp) -> c1
7856   if (N0CFP)
7857     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7858
7859   return SDValue();
7860 }
7861
7862 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7863   SDValue N0 = N->getOperand(0);
7864   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7865   EVT VT = N->getValueType(0);
7866
7867   // fold (fp_to_uint c1fp) -> c1
7868   if (N0CFP)
7869     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7870
7871   return SDValue();
7872 }
7873
7874 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7875   SDValue N0 = N->getOperand(0);
7876   SDValue N1 = N->getOperand(1);
7877   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7878   EVT VT = N->getValueType(0);
7879
7880   // fold (fp_round c1fp) -> c1fp
7881   if (N0CFP)
7882     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7883
7884   // fold (fp_round (fp_extend x)) -> x
7885   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7886     return N0.getOperand(0);
7887
7888   // fold (fp_round (fp_round x)) -> (fp_round x)
7889   if (N0.getOpcode() == ISD::FP_ROUND) {
7890     // This is a value preserving truncation if both round's are.
7891     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7892                    N0.getNode()->getConstantOperandVal(1) == 1;
7893     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7894                        DAG.getIntPtrConstant(IsTrunc));
7895   }
7896
7897   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7898   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7899     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7900                               N0.getOperand(0), N1);
7901     AddToWorklist(Tmp.getNode());
7902     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7903                        Tmp, N0.getOperand(1));
7904   }
7905
7906   return SDValue();
7907 }
7908
7909 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7910   SDValue N0 = N->getOperand(0);
7911   EVT VT = N->getValueType(0);
7912   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7913   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7914
7915   // fold (fp_round_inreg c1fp) -> c1fp
7916   if (N0CFP && isTypeLegal(EVT)) {
7917     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7918     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7919   }
7920
7921   return SDValue();
7922 }
7923
7924 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7925   SDValue N0 = N->getOperand(0);
7926   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7927   EVT VT = N->getValueType(0);
7928
7929   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7930   if (N->hasOneUse() &&
7931       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7932     return SDValue();
7933
7934   // fold (fp_extend c1fp) -> c1fp
7935   if (N0CFP)
7936     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7937
7938   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7939   // value of X.
7940   if (N0.getOpcode() == ISD::FP_ROUND
7941       && N0.getNode()->getConstantOperandVal(1) == 1) {
7942     SDValue In = N0.getOperand(0);
7943     if (In.getValueType() == VT) return In;
7944     if (VT.bitsLT(In.getValueType()))
7945       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7946                          In, N0.getOperand(1));
7947     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7948   }
7949
7950   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7951   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7952        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7953     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7954     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7955                                      LN0->getChain(),
7956                                      LN0->getBasePtr(), N0.getValueType(),
7957                                      LN0->getMemOperand());
7958     CombineTo(N, ExtLoad);
7959     CombineTo(N0.getNode(),
7960               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7961                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7962               ExtLoad.getValue(1));
7963     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7964   }
7965
7966   return SDValue();
7967 }
7968
7969 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7970   SDValue N0 = N->getOperand(0);
7971   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7972   EVT VT = N->getValueType(0);
7973
7974   // fold (fceil c1) -> fceil(c1)
7975   if (N0CFP)
7976     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7977
7978   return SDValue();
7979 }
7980
7981 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7982   SDValue N0 = N->getOperand(0);
7983   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7984   EVT VT = N->getValueType(0);
7985
7986   // fold (ftrunc c1) -> ftrunc(c1)
7987   if (N0CFP)
7988     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7989
7990   return SDValue();
7991 }
7992
7993 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7994   SDValue N0 = N->getOperand(0);
7995   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7996   EVT VT = N->getValueType(0);
7997
7998   // fold (ffloor c1) -> ffloor(c1)
7999   if (N0CFP)
8000     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8001
8002   return SDValue();
8003 }
8004
8005 // FIXME: FNEG and FABS have a lot in common; refactor.
8006 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8007   SDValue N0 = N->getOperand(0);
8008   EVT VT = N->getValueType(0);
8009
8010   if (VT.isVector()) {
8011     SDValue FoldedVOp = SimplifyVUnaryOp(N);
8012     if (FoldedVOp.getNode()) return FoldedVOp;
8013   }
8014
8015   // Constant fold FNEG.
8016   if (isa<ConstantFPSDNode>(N0))
8017     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8018
8019   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8020                          &DAG.getTarget().Options))
8021     return GetNegatedExpression(N0, DAG, LegalOperations);
8022
8023   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8024   // constant pool values.
8025   if (!TLI.isFNegFree(VT) &&
8026       N0.getOpcode() == ISD::BITCAST &&
8027       N0.getNode()->hasOneUse()) {
8028     SDValue Int = N0.getOperand(0);
8029     EVT IntVT = Int.getValueType();
8030     if (IntVT.isInteger() && !IntVT.isVector()) {
8031       APInt SignMask;
8032       if (N0.getValueType().isVector()) {
8033         // For a vector, get a mask such as 0x80... per scalar element
8034         // and splat it.
8035         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8036         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8037       } else {
8038         // For a scalar, just generate 0x80...
8039         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8040       }
8041       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8042                         DAG.getConstant(SignMask, IntVT));
8043       AddToWorklist(Int.getNode());
8044       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8045     }
8046   }
8047
8048   // (fneg (fmul c, x)) -> (fmul -c, x)
8049   if (N0.getOpcode() == ISD::FMUL) {
8050     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8051     if (CFP1) {
8052       APFloat CVal = CFP1->getValueAPF();
8053       CVal.changeSign();
8054       if (Level >= AfterLegalizeDAG &&
8055           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8056            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8057         return DAG.getNode(
8058             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8059             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8060     }
8061   }
8062
8063   return SDValue();
8064 }
8065
8066 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8067   SDValue N0 = N->getOperand(0);
8068   SDValue N1 = N->getOperand(1);
8069   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8070   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8071
8072   if (N0CFP && N1CFP) {
8073     const APFloat &C0 = N0CFP->getValueAPF();
8074     const APFloat &C1 = N1CFP->getValueAPF();
8075     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8076   }
8077
8078   if (N0CFP) {
8079     EVT VT = N->getValueType(0);
8080     // Canonicalize to constant on RHS.
8081     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8082   }
8083
8084   return SDValue();
8085 }
8086
8087 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8088   SDValue N0 = N->getOperand(0);
8089   SDValue N1 = N->getOperand(1);
8090   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8091   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8092
8093   if (N0CFP && N1CFP) {
8094     const APFloat &C0 = N0CFP->getValueAPF();
8095     const APFloat &C1 = N1CFP->getValueAPF();
8096     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8097   }
8098
8099   if (N0CFP) {
8100     EVT VT = N->getValueType(0);
8101     // Canonicalize to constant on RHS.
8102     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8103   }
8104
8105   return SDValue();
8106 }
8107
8108 SDValue DAGCombiner::visitFABS(SDNode *N) {
8109   SDValue N0 = N->getOperand(0);
8110   EVT VT = N->getValueType(0);
8111
8112   if (VT.isVector()) {
8113     SDValue FoldedVOp = SimplifyVUnaryOp(N);
8114     if (FoldedVOp.getNode()) return FoldedVOp;
8115   }
8116
8117   // fold (fabs c1) -> fabs(c1)
8118   if (isa<ConstantFPSDNode>(N0))
8119     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8120
8121   // fold (fabs (fabs x)) -> (fabs x)
8122   if (N0.getOpcode() == ISD::FABS)
8123     return N->getOperand(0);
8124
8125   // fold (fabs (fneg x)) -> (fabs x)
8126   // fold (fabs (fcopysign x, y)) -> (fabs x)
8127   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8128     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8129
8130   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8131   // constant pool values.
8132   if (!TLI.isFAbsFree(VT) &&
8133       N0.getOpcode() == ISD::BITCAST &&
8134       N0.getNode()->hasOneUse()) {
8135     SDValue Int = N0.getOperand(0);
8136     EVT IntVT = Int.getValueType();
8137     if (IntVT.isInteger() && !IntVT.isVector()) {
8138       APInt SignMask;
8139       if (N0.getValueType().isVector()) {
8140         // For a vector, get a mask such as 0x7f... per scalar element
8141         // and splat it.
8142         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8143         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8144       } else {
8145         // For a scalar, just generate 0x7f...
8146         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8147       }
8148       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8149                         DAG.getConstant(SignMask, IntVT));
8150       AddToWorklist(Int.getNode());
8151       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8152     }
8153   }
8154
8155   return SDValue();
8156 }
8157
8158 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8159   SDValue Chain = N->getOperand(0);
8160   SDValue N1 = N->getOperand(1);
8161   SDValue N2 = N->getOperand(2);
8162
8163   // If N is a constant we could fold this into a fallthrough or unconditional
8164   // branch. However that doesn't happen very often in normal code, because
8165   // Instcombine/SimplifyCFG should have handled the available opportunities.
8166   // If we did this folding here, it would be necessary to update the
8167   // MachineBasicBlock CFG, which is awkward.
8168
8169   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8170   // on the target.
8171   if (N1.getOpcode() == ISD::SETCC &&
8172       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8173                                    N1.getOperand(0).getValueType())) {
8174     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8175                        Chain, N1.getOperand(2),
8176                        N1.getOperand(0), N1.getOperand(1), N2);
8177   }
8178
8179   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8180       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8181        (N1.getOperand(0).hasOneUse() &&
8182         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8183     SDNode *Trunc = nullptr;
8184     if (N1.getOpcode() == ISD::TRUNCATE) {
8185       // Look pass the truncate.
8186       Trunc = N1.getNode();
8187       N1 = N1.getOperand(0);
8188     }
8189
8190     // Match this pattern so that we can generate simpler code:
8191     //
8192     //   %a = ...
8193     //   %b = and i32 %a, 2
8194     //   %c = srl i32 %b, 1
8195     //   brcond i32 %c ...
8196     //
8197     // into
8198     //
8199     //   %a = ...
8200     //   %b = and i32 %a, 2
8201     //   %c = setcc eq %b, 0
8202     //   brcond %c ...
8203     //
8204     // This applies only when the AND constant value has one bit set and the
8205     // SRL constant is equal to the log2 of the AND constant. The back-end is
8206     // smart enough to convert the result into a TEST/JMP sequence.
8207     SDValue Op0 = N1.getOperand(0);
8208     SDValue Op1 = N1.getOperand(1);
8209
8210     if (Op0.getOpcode() == ISD::AND &&
8211         Op1.getOpcode() == ISD::Constant) {
8212       SDValue AndOp1 = Op0.getOperand(1);
8213
8214       if (AndOp1.getOpcode() == ISD::Constant) {
8215         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8216
8217         if (AndConst.isPowerOf2() &&
8218             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8219           SDValue SetCC =
8220             DAG.getSetCC(SDLoc(N),
8221                          getSetCCResultType(Op0.getValueType()),
8222                          Op0, DAG.getConstant(0, Op0.getValueType()),
8223                          ISD::SETNE);
8224
8225           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8226                                           MVT::Other, Chain, SetCC, N2);
8227           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8228           // will convert it back to (X & C1) >> C2.
8229           CombineTo(N, NewBRCond, false);
8230           // Truncate is dead.
8231           if (Trunc)
8232             deleteAndRecombine(Trunc);
8233           // Replace the uses of SRL with SETCC
8234           WorklistRemover DeadNodes(*this);
8235           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8236           deleteAndRecombine(N1.getNode());
8237           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8238         }
8239       }
8240     }
8241
8242     if (Trunc)
8243       // Restore N1 if the above transformation doesn't match.
8244       N1 = N->getOperand(1);
8245   }
8246
8247   // Transform br(xor(x, y)) -> br(x != y)
8248   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8249   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8250     SDNode *TheXor = N1.getNode();
8251     SDValue Op0 = TheXor->getOperand(0);
8252     SDValue Op1 = TheXor->getOperand(1);
8253     if (Op0.getOpcode() == Op1.getOpcode()) {
8254       // Avoid missing important xor optimizations.
8255       SDValue Tmp = visitXOR(TheXor);
8256       if (Tmp.getNode()) {
8257         if (Tmp.getNode() != TheXor) {
8258           DEBUG(dbgs() << "\nReplacing.8 ";
8259                 TheXor->dump(&DAG);
8260                 dbgs() << "\nWith: ";
8261                 Tmp.getNode()->dump(&DAG);
8262                 dbgs() << '\n');
8263           WorklistRemover DeadNodes(*this);
8264           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8265           deleteAndRecombine(TheXor);
8266           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8267                              MVT::Other, Chain, Tmp, N2);
8268         }
8269
8270         // visitXOR has changed XOR's operands or replaced the XOR completely,
8271         // bail out.
8272         return SDValue(N, 0);
8273       }
8274     }
8275
8276     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8277       bool Equal = false;
8278       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8279         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8280             Op0.getOpcode() == ISD::XOR) {
8281           TheXor = Op0.getNode();
8282           Equal = true;
8283         }
8284
8285       EVT SetCCVT = N1.getValueType();
8286       if (LegalTypes)
8287         SetCCVT = getSetCCResultType(SetCCVT);
8288       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8289                                    SetCCVT,
8290                                    Op0, Op1,
8291                                    Equal ? ISD::SETEQ : ISD::SETNE);
8292       // Replace the uses of XOR with SETCC
8293       WorklistRemover DeadNodes(*this);
8294       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8295       deleteAndRecombine(N1.getNode());
8296       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8297                          MVT::Other, Chain, SetCC, N2);
8298     }
8299   }
8300
8301   return SDValue();
8302 }
8303
8304 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8305 //
8306 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8307   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8308   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8309
8310   // If N is a constant we could fold this into a fallthrough or unconditional
8311   // branch. However that doesn't happen very often in normal code, because
8312   // Instcombine/SimplifyCFG should have handled the available opportunities.
8313   // If we did this folding here, it would be necessary to update the
8314   // MachineBasicBlock CFG, which is awkward.
8315
8316   // Use SimplifySetCC to simplify SETCC's.
8317   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8318                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8319                                false);
8320   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8321
8322   // fold to a simpler setcc
8323   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8324     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8325                        N->getOperand(0), Simp.getOperand(2),
8326                        Simp.getOperand(0), Simp.getOperand(1),
8327                        N->getOperand(4));
8328
8329   return SDValue();
8330 }
8331
8332 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8333 /// and that N may be folded in the load / store addressing mode.
8334 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8335                                     SelectionDAG &DAG,
8336                                     const TargetLowering &TLI) {
8337   EVT VT;
8338   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8339     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8340       return false;
8341     VT = Use->getValueType(0);
8342   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8343     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8344       return false;
8345     VT = ST->getValue().getValueType();
8346   } else
8347     return false;
8348
8349   TargetLowering::AddrMode AM;
8350   if (N->getOpcode() == ISD::ADD) {
8351     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8352     if (Offset)
8353       // [reg +/- imm]
8354       AM.BaseOffs = Offset->getSExtValue();
8355     else
8356       // [reg +/- reg]
8357       AM.Scale = 1;
8358   } else if (N->getOpcode() == ISD::SUB) {
8359     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8360     if (Offset)
8361       // [reg +/- imm]
8362       AM.BaseOffs = -Offset->getSExtValue();
8363     else
8364       // [reg +/- reg]
8365       AM.Scale = 1;
8366   } else
8367     return false;
8368
8369   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8370 }
8371
8372 /// Try turning a load/store into a pre-indexed load/store when the base
8373 /// pointer is an add or subtract and it has other uses besides the load/store.
8374 /// After the transformation, the new indexed load/store has effectively folded
8375 /// the add/subtract in and all of its other uses are redirected to the
8376 /// new load/store.
8377 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8378   if (Level < AfterLegalizeDAG)
8379     return false;
8380
8381   bool isLoad = true;
8382   SDValue Ptr;
8383   EVT VT;
8384   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8385     if (LD->isIndexed())
8386       return false;
8387     VT = LD->getMemoryVT();
8388     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8389         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8390       return false;
8391     Ptr = LD->getBasePtr();
8392   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8393     if (ST->isIndexed())
8394       return false;
8395     VT = ST->getMemoryVT();
8396     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8397         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8398       return false;
8399     Ptr = ST->getBasePtr();
8400     isLoad = false;
8401   } else {
8402     return false;
8403   }
8404
8405   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8406   // out.  There is no reason to make this a preinc/predec.
8407   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8408       Ptr.getNode()->hasOneUse())
8409     return false;
8410
8411   // Ask the target to do addressing mode selection.
8412   SDValue BasePtr;
8413   SDValue Offset;
8414   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8415   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8416     return false;
8417
8418   // Backends without true r+i pre-indexed forms may need to pass a
8419   // constant base with a variable offset so that constant coercion
8420   // will work with the patterns in canonical form.
8421   bool Swapped = false;
8422   if (isa<ConstantSDNode>(BasePtr)) {
8423     std::swap(BasePtr, Offset);
8424     Swapped = true;
8425   }
8426
8427   // Don't create a indexed load / store with zero offset.
8428   if (isa<ConstantSDNode>(Offset) &&
8429       cast<ConstantSDNode>(Offset)->isNullValue())
8430     return false;
8431
8432   // Try turning it into a pre-indexed load / store except when:
8433   // 1) The new base ptr is a frame index.
8434   // 2) If N is a store and the new base ptr is either the same as or is a
8435   //    predecessor of the value being stored.
8436   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8437   //    that would create a cycle.
8438   // 4) All uses are load / store ops that use it as old base ptr.
8439
8440   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8441   // (plus the implicit offset) to a register to preinc anyway.
8442   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8443     return false;
8444
8445   // Check #2.
8446   if (!isLoad) {
8447     SDValue Val = cast<StoreSDNode>(N)->getValue();
8448     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8449       return false;
8450   }
8451
8452   // If the offset is a constant, there may be other adds of constants that
8453   // can be folded with this one. We should do this to avoid having to keep
8454   // a copy of the original base pointer.
8455   SmallVector<SDNode *, 16> OtherUses;
8456   if (isa<ConstantSDNode>(Offset))
8457     for (SDNode *Use : BasePtr.getNode()->uses()) {
8458       if (Use == Ptr.getNode())
8459         continue;
8460
8461       if (Use->isPredecessorOf(N))
8462         continue;
8463
8464       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8465         OtherUses.clear();
8466         break;
8467       }
8468
8469       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8470       if (Op1.getNode() == BasePtr.getNode())
8471         std::swap(Op0, Op1);
8472       assert(Op0.getNode() == BasePtr.getNode() &&
8473              "Use of ADD/SUB but not an operand");
8474
8475       if (!isa<ConstantSDNode>(Op1)) {
8476         OtherUses.clear();
8477         break;
8478       }
8479
8480       // FIXME: In some cases, we can be smarter about this.
8481       if (Op1.getValueType() != Offset.getValueType()) {
8482         OtherUses.clear();
8483         break;
8484       }
8485
8486       OtherUses.push_back(Use);
8487     }
8488
8489   if (Swapped)
8490     std::swap(BasePtr, Offset);
8491
8492   // Now check for #3 and #4.
8493   bool RealUse = false;
8494
8495   // Caches for hasPredecessorHelper
8496   SmallPtrSet<const SDNode *, 32> Visited;
8497   SmallVector<const SDNode *, 16> Worklist;
8498
8499   for (SDNode *Use : Ptr.getNode()->uses()) {
8500     if (Use == N)
8501       continue;
8502     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8503       return false;
8504
8505     // If Ptr may be folded in addressing mode of other use, then it's
8506     // not profitable to do this transformation.
8507     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8508       RealUse = true;
8509   }
8510
8511   if (!RealUse)
8512     return false;
8513
8514   SDValue Result;
8515   if (isLoad)
8516     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8517                                 BasePtr, Offset, AM);
8518   else
8519     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8520                                  BasePtr, Offset, AM);
8521   ++PreIndexedNodes;
8522   ++NodesCombined;
8523   DEBUG(dbgs() << "\nReplacing.4 ";
8524         N->dump(&DAG);
8525         dbgs() << "\nWith: ";
8526         Result.getNode()->dump(&DAG);
8527         dbgs() << '\n');
8528   WorklistRemover DeadNodes(*this);
8529   if (isLoad) {
8530     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8531     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8532   } else {
8533     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8534   }
8535
8536   // Finally, since the node is now dead, remove it from the graph.
8537   deleteAndRecombine(N);
8538
8539   if (Swapped)
8540     std::swap(BasePtr, Offset);
8541
8542   // Replace other uses of BasePtr that can be updated to use Ptr
8543   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8544     unsigned OffsetIdx = 1;
8545     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8546       OffsetIdx = 0;
8547     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8548            BasePtr.getNode() && "Expected BasePtr operand");
8549
8550     // We need to replace ptr0 in the following expression:
8551     //   x0 * offset0 + y0 * ptr0 = t0
8552     // knowing that
8553     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8554     //
8555     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8556     // indexed load/store and the expresion that needs to be re-written.
8557     //
8558     // Therefore, we have:
8559     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8560
8561     ConstantSDNode *CN =
8562       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8563     int X0, X1, Y0, Y1;
8564     APInt Offset0 = CN->getAPIntValue();
8565     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8566
8567     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8568     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8569     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8570     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8571
8572     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8573
8574     APInt CNV = Offset0;
8575     if (X0 < 0) CNV = -CNV;
8576     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8577     else CNV = CNV - Offset1;
8578
8579     // We can now generate the new expression.
8580     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8581     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8582
8583     SDValue NewUse = DAG.getNode(Opcode,
8584                                  SDLoc(OtherUses[i]),
8585                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8586     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8587     deleteAndRecombine(OtherUses[i]);
8588   }
8589
8590   // Replace the uses of Ptr with uses of the updated base value.
8591   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8592   deleteAndRecombine(Ptr.getNode());
8593
8594   return true;
8595 }
8596
8597 /// Try to combine a load/store with a add/sub of the base pointer node into a
8598 /// post-indexed load/store. The transformation folded the add/subtract into the
8599 /// new indexed load/store effectively and all of its uses are redirected to the
8600 /// new load/store.
8601 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8602   if (Level < AfterLegalizeDAG)
8603     return false;
8604
8605   bool isLoad = true;
8606   SDValue Ptr;
8607   EVT VT;
8608   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8609     if (LD->isIndexed())
8610       return false;
8611     VT = LD->getMemoryVT();
8612     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8613         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8614       return false;
8615     Ptr = LD->getBasePtr();
8616   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8617     if (ST->isIndexed())
8618       return false;
8619     VT = ST->getMemoryVT();
8620     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8621         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8622       return false;
8623     Ptr = ST->getBasePtr();
8624     isLoad = false;
8625   } else {
8626     return false;
8627   }
8628
8629   if (Ptr.getNode()->hasOneUse())
8630     return false;
8631
8632   for (SDNode *Op : Ptr.getNode()->uses()) {
8633     if (Op == N ||
8634         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8635       continue;
8636
8637     SDValue BasePtr;
8638     SDValue Offset;
8639     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8640     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8641       // Don't create a indexed load / store with zero offset.
8642       if (isa<ConstantSDNode>(Offset) &&
8643           cast<ConstantSDNode>(Offset)->isNullValue())
8644         continue;
8645
8646       // Try turning it into a post-indexed load / store except when
8647       // 1) All uses are load / store ops that use it as base ptr (and
8648       //    it may be folded as addressing mmode).
8649       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8650       //    nor a successor of N. Otherwise, if Op is folded that would
8651       //    create a cycle.
8652
8653       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8654         continue;
8655
8656       // Check for #1.
8657       bool TryNext = false;
8658       for (SDNode *Use : BasePtr.getNode()->uses()) {
8659         if (Use == Ptr.getNode())
8660           continue;
8661
8662         // If all the uses are load / store addresses, then don't do the
8663         // transformation.
8664         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8665           bool RealUse = false;
8666           for (SDNode *UseUse : Use->uses()) {
8667             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8668               RealUse = true;
8669           }
8670
8671           if (!RealUse) {
8672             TryNext = true;
8673             break;
8674           }
8675         }
8676       }
8677
8678       if (TryNext)
8679         continue;
8680
8681       // Check for #2
8682       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8683         SDValue Result = isLoad
8684           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8685                                BasePtr, Offset, AM)
8686           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8687                                 BasePtr, Offset, AM);
8688         ++PostIndexedNodes;
8689         ++NodesCombined;
8690         DEBUG(dbgs() << "\nReplacing.5 ";
8691               N->dump(&DAG);
8692               dbgs() << "\nWith: ";
8693               Result.getNode()->dump(&DAG);
8694               dbgs() << '\n');
8695         WorklistRemover DeadNodes(*this);
8696         if (isLoad) {
8697           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8698           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8699         } else {
8700           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8701         }
8702
8703         // Finally, since the node is now dead, remove it from the graph.
8704         deleteAndRecombine(N);
8705
8706         // Replace the uses of Use with uses of the updated base value.
8707         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8708                                       Result.getValue(isLoad ? 1 : 0));
8709         deleteAndRecombine(Op);
8710         return true;
8711       }
8712     }
8713   }
8714
8715   return false;
8716 }
8717
8718 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8719 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8720   ISD::MemIndexedMode AM = LD->getAddressingMode();
8721   assert(AM != ISD::UNINDEXED);
8722   SDValue BP = LD->getOperand(1);
8723   SDValue Inc = LD->getOperand(2);
8724
8725   // Some backends use TargetConstants for load offsets, but don't expect
8726   // TargetConstants in general ADD nodes. We can convert these constants into
8727   // regular Constants (if the constant is not opaque).
8728   assert((Inc.getOpcode() != ISD::TargetConstant ||
8729           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8730          "Cannot split out indexing using opaque target constants");
8731   if (Inc.getOpcode() == ISD::TargetConstant) {
8732     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8733     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8734                           ConstInc->getValueType(0));
8735   }
8736
8737   unsigned Opc =
8738       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8739   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8740 }
8741
8742 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8743   LoadSDNode *LD  = cast<LoadSDNode>(N);
8744   SDValue Chain = LD->getChain();
8745   SDValue Ptr   = LD->getBasePtr();
8746
8747   // If load is not volatile and there are no uses of the loaded value (and
8748   // the updated indexed value in case of indexed loads), change uses of the
8749   // chain value into uses of the chain input (i.e. delete the dead load).
8750   if (!LD->isVolatile()) {
8751     if (N->getValueType(1) == MVT::Other) {
8752       // Unindexed loads.
8753       if (!N->hasAnyUseOfValue(0)) {
8754         // It's not safe to use the two value CombineTo variant here. e.g.
8755         // v1, chain2 = load chain1, loc
8756         // v2, chain3 = load chain2, loc
8757         // v3         = add v2, c
8758         // Now we replace use of chain2 with chain1.  This makes the second load
8759         // isomorphic to the one we are deleting, and thus makes this load live.
8760         DEBUG(dbgs() << "\nReplacing.6 ";
8761               N->dump(&DAG);
8762               dbgs() << "\nWith chain: ";
8763               Chain.getNode()->dump(&DAG);
8764               dbgs() << "\n");
8765         WorklistRemover DeadNodes(*this);
8766         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8767
8768         if (N->use_empty())
8769           deleteAndRecombine(N);
8770
8771         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8772       }
8773     } else {
8774       // Indexed loads.
8775       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8776
8777       // If this load has an opaque TargetConstant offset, then we cannot split
8778       // the indexing into an add/sub directly (that TargetConstant may not be
8779       // valid for a different type of node, and we cannot convert an opaque
8780       // target constant into a regular constant).
8781       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8782                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8783
8784       if (!N->hasAnyUseOfValue(0) &&
8785           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8786         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8787         SDValue Index;
8788         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8789           Index = SplitIndexingFromLoad(LD);
8790           // Try to fold the base pointer arithmetic into subsequent loads and
8791           // stores.
8792           AddUsersToWorklist(N);
8793         } else
8794           Index = DAG.getUNDEF(N->getValueType(1));
8795         DEBUG(dbgs() << "\nReplacing.7 ";
8796               N->dump(&DAG);
8797               dbgs() << "\nWith: ";
8798               Undef.getNode()->dump(&DAG);
8799               dbgs() << " and 2 other values\n");
8800         WorklistRemover DeadNodes(*this);
8801         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8802         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8803         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8804         deleteAndRecombine(N);
8805         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8806       }
8807     }
8808   }
8809
8810   // If this load is directly stored, replace the load value with the stored
8811   // value.
8812   // TODO: Handle store large -> read small portion.
8813   // TODO: Handle TRUNCSTORE/LOADEXT
8814   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8815     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8816       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8817       if (PrevST->getBasePtr() == Ptr &&
8818           PrevST->getValue().getValueType() == N->getValueType(0))
8819       return CombineTo(N, Chain.getOperand(1), Chain);
8820     }
8821   }
8822
8823   // Try to infer better alignment information than the load already has.
8824   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8825     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8826       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8827         SDValue NewLoad =
8828                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8829                               LD->getValueType(0),
8830                               Chain, Ptr, LD->getPointerInfo(),
8831                               LD->getMemoryVT(),
8832                               LD->isVolatile(), LD->isNonTemporal(),
8833                               LD->isInvariant(), Align, LD->getAAInfo());
8834         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8835       }
8836     }
8837   }
8838
8839   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8840                                                   : DAG.getSubtarget().useAA();
8841 #ifndef NDEBUG
8842   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8843       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8844     UseAA = false;
8845 #endif
8846   if (UseAA && LD->isUnindexed()) {
8847     // Walk up chain skipping non-aliasing memory nodes.
8848     SDValue BetterChain = FindBetterChain(N, Chain);
8849
8850     // If there is a better chain.
8851     if (Chain != BetterChain) {
8852       SDValue ReplLoad;
8853
8854       // Replace the chain to void dependency.
8855       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8856         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8857                                BetterChain, Ptr, LD->getMemOperand());
8858       } else {
8859         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8860                                   LD->getValueType(0),
8861                                   BetterChain, Ptr, LD->getMemoryVT(),
8862                                   LD->getMemOperand());
8863       }
8864
8865       // Create token factor to keep old chain connected.
8866       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8867                                   MVT::Other, Chain, ReplLoad.getValue(1));
8868
8869       // Make sure the new and old chains are cleaned up.
8870       AddToWorklist(Token.getNode());
8871
8872       // Replace uses with load result and token factor. Don't add users
8873       // to work list.
8874       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8875     }
8876   }
8877
8878   // Try transforming N to an indexed load.
8879   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8880     return SDValue(N, 0);
8881
8882   // Try to slice up N to more direct loads if the slices are mapped to
8883   // different register banks or pairing can take place.
8884   if (SliceUpLoad(N))
8885     return SDValue(N, 0);
8886
8887   return SDValue();
8888 }
8889
8890 namespace {
8891 /// \brief Helper structure used to slice a load in smaller loads.
8892 /// Basically a slice is obtained from the following sequence:
8893 /// Origin = load Ty1, Base
8894 /// Shift = srl Ty1 Origin, CstTy Amount
8895 /// Inst = trunc Shift to Ty2
8896 ///
8897 /// Then, it will be rewriten into:
8898 /// Slice = load SliceTy, Base + SliceOffset
8899 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8900 ///
8901 /// SliceTy is deduced from the number of bits that are actually used to
8902 /// build Inst.
8903 struct LoadedSlice {
8904   /// \brief Helper structure used to compute the cost of a slice.
8905   struct Cost {
8906     /// Are we optimizing for code size.
8907     bool ForCodeSize;
8908     /// Various cost.
8909     unsigned Loads;
8910     unsigned Truncates;
8911     unsigned CrossRegisterBanksCopies;
8912     unsigned ZExts;
8913     unsigned Shift;
8914
8915     Cost(bool ForCodeSize = false)
8916         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8917           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8918
8919     /// \brief Get the cost of one isolated slice.
8920     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8921         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8922           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8923       EVT TruncType = LS.Inst->getValueType(0);
8924       EVT LoadedType = LS.getLoadedType();
8925       if (TruncType != LoadedType &&
8926           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8927         ZExts = 1;
8928     }
8929
8930     /// \brief Account for slicing gain in the current cost.
8931     /// Slicing provide a few gains like removing a shift or a
8932     /// truncate. This method allows to grow the cost of the original
8933     /// load with the gain from this slice.
8934     void addSliceGain(const LoadedSlice &LS) {
8935       // Each slice saves a truncate.
8936       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8937       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8938                               LS.Inst->getOperand(0).getValueType()))
8939         ++Truncates;
8940       // If there is a shift amount, this slice gets rid of it.
8941       if (LS.Shift)
8942         ++Shift;
8943       // If this slice can merge a cross register bank copy, account for it.
8944       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8945         ++CrossRegisterBanksCopies;
8946     }
8947
8948     Cost &operator+=(const Cost &RHS) {
8949       Loads += RHS.Loads;
8950       Truncates += RHS.Truncates;
8951       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8952       ZExts += RHS.ZExts;
8953       Shift += RHS.Shift;
8954       return *this;
8955     }
8956
8957     bool operator==(const Cost &RHS) const {
8958       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8959              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8960              ZExts == RHS.ZExts && Shift == RHS.Shift;
8961     }
8962
8963     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8964
8965     bool operator<(const Cost &RHS) const {
8966       // Assume cross register banks copies are as expensive as loads.
8967       // FIXME: Do we want some more target hooks?
8968       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8969       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8970       // Unless we are optimizing for code size, consider the
8971       // expensive operation first.
8972       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8973         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8974       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8975              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8976     }
8977
8978     bool operator>(const Cost &RHS) const { return RHS < *this; }
8979
8980     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8981
8982     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8983   };
8984   // The last instruction that represent the slice. This should be a
8985   // truncate instruction.
8986   SDNode *Inst;
8987   // The original load instruction.
8988   LoadSDNode *Origin;
8989   // The right shift amount in bits from the original load.
8990   unsigned Shift;
8991   // The DAG from which Origin came from.
8992   // This is used to get some contextual information about legal types, etc.
8993   SelectionDAG *DAG;
8994
8995   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8996               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8997       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8998
8999   LoadedSlice(const LoadedSlice &LS)
9000       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
9001
9002   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9003   /// \return Result is \p BitWidth and has used bits set to 1 and
9004   ///         not used bits set to 0.
9005   APInt getUsedBits() const {
9006     // Reproduce the trunc(lshr) sequence:
9007     // - Start from the truncated value.
9008     // - Zero extend to the desired bit width.
9009     // - Shift left.
9010     assert(Origin && "No original load to compare against.");
9011     unsigned BitWidth = Origin->getValueSizeInBits(0);
9012     assert(Inst && "This slice is not bound to an instruction");
9013     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9014            "Extracted slice is bigger than the whole type!");
9015     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9016     UsedBits.setAllBits();
9017     UsedBits = UsedBits.zext(BitWidth);
9018     UsedBits <<= Shift;
9019     return UsedBits;
9020   }
9021
9022   /// \brief Get the size of the slice to be loaded in bytes.
9023   unsigned getLoadedSize() const {
9024     unsigned SliceSize = getUsedBits().countPopulation();
9025     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9026     return SliceSize / 8;
9027   }
9028
9029   /// \brief Get the type that will be loaded for this slice.
9030   /// Note: This may not be the final type for the slice.
9031   EVT getLoadedType() const {
9032     assert(DAG && "Missing context");
9033     LLVMContext &Ctxt = *DAG->getContext();
9034     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9035   }
9036
9037   /// \brief Get the alignment of the load used for this slice.
9038   unsigned getAlignment() const {
9039     unsigned Alignment = Origin->getAlignment();
9040     unsigned Offset = getOffsetFromBase();
9041     if (Offset != 0)
9042       Alignment = MinAlign(Alignment, Alignment + Offset);
9043     return Alignment;
9044   }
9045
9046   /// \brief Check if this slice can be rewritten with legal operations.
9047   bool isLegal() const {
9048     // An invalid slice is not legal.
9049     if (!Origin || !Inst || !DAG)
9050       return false;
9051
9052     // Offsets are for indexed load only, we do not handle that.
9053     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9054       return false;
9055
9056     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9057
9058     // Check that the type is legal.
9059     EVT SliceType = getLoadedType();
9060     if (!TLI.isTypeLegal(SliceType))
9061       return false;
9062
9063     // Check that the load is legal for this type.
9064     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9065       return false;
9066
9067     // Check that the offset can be computed.
9068     // 1. Check its type.
9069     EVT PtrType = Origin->getBasePtr().getValueType();
9070     if (PtrType == MVT::Untyped || PtrType.isExtended())
9071       return false;
9072
9073     // 2. Check that it fits in the immediate.
9074     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9075       return false;
9076
9077     // 3. Check that the computation is legal.
9078     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9079       return false;
9080
9081     // Check that the zext is legal if it needs one.
9082     EVT TruncateType = Inst->getValueType(0);
9083     if (TruncateType != SliceType &&
9084         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9085       return false;
9086
9087     return true;
9088   }
9089
9090   /// \brief Get the offset in bytes of this slice in the original chunk of
9091   /// bits.
9092   /// \pre DAG != nullptr.
9093   uint64_t getOffsetFromBase() const {
9094     assert(DAG && "Missing context.");
9095     bool IsBigEndian =
9096         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9097     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9098     uint64_t Offset = Shift / 8;
9099     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9100     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9101            "The size of the original loaded type is not a multiple of a"
9102            " byte.");
9103     // If Offset is bigger than TySizeInBytes, it means we are loading all
9104     // zeros. This should have been optimized before in the process.
9105     assert(TySizeInBytes > Offset &&
9106            "Invalid shift amount for given loaded size");
9107     if (IsBigEndian)
9108       Offset = TySizeInBytes - Offset - getLoadedSize();
9109     return Offset;
9110   }
9111
9112   /// \brief Generate the sequence of instructions to load the slice
9113   /// represented by this object and redirect the uses of this slice to
9114   /// this new sequence of instructions.
9115   /// \pre this->Inst && this->Origin are valid Instructions and this
9116   /// object passed the legal check: LoadedSlice::isLegal returned true.
9117   /// \return The last instruction of the sequence used to load the slice.
9118   SDValue loadSlice() const {
9119     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9120     const SDValue &OldBaseAddr = Origin->getBasePtr();
9121     SDValue BaseAddr = OldBaseAddr;
9122     // Get the offset in that chunk of bytes w.r.t. the endianess.
9123     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9124     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9125     if (Offset) {
9126       // BaseAddr = BaseAddr + Offset.
9127       EVT ArithType = BaseAddr.getValueType();
9128       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9129                               DAG->getConstant(Offset, ArithType));
9130     }
9131
9132     // Create the type of the loaded slice according to its size.
9133     EVT SliceType = getLoadedType();
9134
9135     // Create the load for the slice.
9136     SDValue LastInst = DAG->getLoad(
9137         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9138         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9139         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9140     // If the final type is not the same as the loaded type, this means that
9141     // we have to pad with zero. Create a zero extend for that.
9142     EVT FinalType = Inst->getValueType(0);
9143     if (SliceType != FinalType)
9144       LastInst =
9145           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9146     return LastInst;
9147   }
9148
9149   /// \brief Check if this slice can be merged with an expensive cross register
9150   /// bank copy. E.g.,
9151   /// i = load i32
9152   /// f = bitcast i32 i to float
9153   bool canMergeExpensiveCrossRegisterBankCopy() const {
9154     if (!Inst || !Inst->hasOneUse())
9155       return false;
9156     SDNode *Use = *Inst->use_begin();
9157     if (Use->getOpcode() != ISD::BITCAST)
9158       return false;
9159     assert(DAG && "Missing context");
9160     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9161     EVT ResVT = Use->getValueType(0);
9162     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9163     const TargetRegisterClass *ArgRC =
9164         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9165     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9166       return false;
9167
9168     // At this point, we know that we perform a cross-register-bank copy.
9169     // Check if it is expensive.
9170     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9171     // Assume bitcasts are cheap, unless both register classes do not
9172     // explicitly share a common sub class.
9173     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9174       return false;
9175
9176     // Check if it will be merged with the load.
9177     // 1. Check the alignment constraint.
9178     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9179         ResVT.getTypeForEVT(*DAG->getContext()));
9180
9181     if (RequiredAlignment > getAlignment())
9182       return false;
9183
9184     // 2. Check that the load is a legal operation for that type.
9185     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9186       return false;
9187
9188     // 3. Check that we do not have a zext in the way.
9189     if (Inst->getValueType(0) != getLoadedType())
9190       return false;
9191
9192     return true;
9193   }
9194 };
9195 }
9196
9197 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9198 /// \p UsedBits looks like 0..0 1..1 0..0.
9199 static bool areUsedBitsDense(const APInt &UsedBits) {
9200   // If all the bits are one, this is dense!
9201   if (UsedBits.isAllOnesValue())
9202     return true;
9203
9204   // Get rid of the unused bits on the right.
9205   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9206   // Get rid of the unused bits on the left.
9207   if (NarrowedUsedBits.countLeadingZeros())
9208     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9209   // Check that the chunk of bits is completely used.
9210   return NarrowedUsedBits.isAllOnesValue();
9211 }
9212
9213 /// \brief Check whether or not \p First and \p Second are next to each other
9214 /// in memory. This means that there is no hole between the bits loaded
9215 /// by \p First and the bits loaded by \p Second.
9216 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9217                                      const LoadedSlice &Second) {
9218   assert(First.Origin == Second.Origin && First.Origin &&
9219          "Unable to match different memory origins.");
9220   APInt UsedBits = First.getUsedBits();
9221   assert((UsedBits & Second.getUsedBits()) == 0 &&
9222          "Slices are not supposed to overlap.");
9223   UsedBits |= Second.getUsedBits();
9224   return areUsedBitsDense(UsedBits);
9225 }
9226
9227 /// \brief Adjust the \p GlobalLSCost according to the target
9228 /// paring capabilities and the layout of the slices.
9229 /// \pre \p GlobalLSCost should account for at least as many loads as
9230 /// there is in the slices in \p LoadedSlices.
9231 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9232                                  LoadedSlice::Cost &GlobalLSCost) {
9233   unsigned NumberOfSlices = LoadedSlices.size();
9234   // If there is less than 2 elements, no pairing is possible.
9235   if (NumberOfSlices < 2)
9236     return;
9237
9238   // Sort the slices so that elements that are likely to be next to each
9239   // other in memory are next to each other in the list.
9240   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9241             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9242     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9243     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9244   });
9245   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9246   // First (resp. Second) is the first (resp. Second) potentially candidate
9247   // to be placed in a paired load.
9248   const LoadedSlice *First = nullptr;
9249   const LoadedSlice *Second = nullptr;
9250   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9251                 // Set the beginning of the pair.
9252                                                            First = Second) {
9253
9254     Second = &LoadedSlices[CurrSlice];
9255
9256     // If First is NULL, it means we start a new pair.
9257     // Get to the next slice.
9258     if (!First)
9259       continue;
9260
9261     EVT LoadedType = First->getLoadedType();
9262
9263     // If the types of the slices are different, we cannot pair them.
9264     if (LoadedType != Second->getLoadedType())
9265       continue;
9266
9267     // Check if the target supplies paired loads for this type.
9268     unsigned RequiredAlignment = 0;
9269     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9270       // move to the next pair, this type is hopeless.
9271       Second = nullptr;
9272       continue;
9273     }
9274     // Check if we meet the alignment requirement.
9275     if (RequiredAlignment > First->getAlignment())
9276       continue;
9277
9278     // Check that both loads are next to each other in memory.
9279     if (!areSlicesNextToEachOther(*First, *Second))
9280       continue;
9281
9282     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9283     --GlobalLSCost.Loads;
9284     // Move to the next pair.
9285     Second = nullptr;
9286   }
9287 }
9288
9289 /// \brief Check the profitability of all involved LoadedSlice.
9290 /// Currently, it is considered profitable if there is exactly two
9291 /// involved slices (1) which are (2) next to each other in memory, and
9292 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9293 ///
9294 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9295 /// the elements themselves.
9296 ///
9297 /// FIXME: When the cost model will be mature enough, we can relax
9298 /// constraints (1) and (2).
9299 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9300                                 const APInt &UsedBits, bool ForCodeSize) {
9301   unsigned NumberOfSlices = LoadedSlices.size();
9302   if (StressLoadSlicing)
9303     return NumberOfSlices > 1;
9304
9305   // Check (1).
9306   if (NumberOfSlices != 2)
9307     return false;
9308
9309   // Check (2).
9310   if (!areUsedBitsDense(UsedBits))
9311     return false;
9312
9313   // Check (3).
9314   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9315   // The original code has one big load.
9316   OrigCost.Loads = 1;
9317   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9318     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9319     // Accumulate the cost of all the slices.
9320     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9321     GlobalSlicingCost += SliceCost;
9322
9323     // Account as cost in the original configuration the gain obtained
9324     // with the current slices.
9325     OrigCost.addSliceGain(LS);
9326   }
9327
9328   // If the target supports paired load, adjust the cost accordingly.
9329   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9330   return OrigCost > GlobalSlicingCost;
9331 }
9332
9333 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9334 /// operations, split it in the various pieces being extracted.
9335 ///
9336 /// This sort of thing is introduced by SROA.
9337 /// This slicing takes care not to insert overlapping loads.
9338 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9339 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9340   if (Level < AfterLegalizeDAG)
9341     return false;
9342
9343   LoadSDNode *LD = cast<LoadSDNode>(N);
9344   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9345       !LD->getValueType(0).isInteger())
9346     return false;
9347
9348   // Keep track of already used bits to detect overlapping values.
9349   // In that case, we will just abort the transformation.
9350   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9351
9352   SmallVector<LoadedSlice, 4> LoadedSlices;
9353
9354   // Check if this load is used as several smaller chunks of bits.
9355   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9356   // of computation for each trunc.
9357   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9358        UI != UIEnd; ++UI) {
9359     // Skip the uses of the chain.
9360     if (UI.getUse().getResNo() != 0)
9361       continue;
9362
9363     SDNode *User = *UI;
9364     unsigned Shift = 0;
9365
9366     // Check if this is a trunc(lshr).
9367     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9368         isa<ConstantSDNode>(User->getOperand(1))) {
9369       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9370       User = *User->use_begin();
9371     }
9372
9373     // At this point, User is a Truncate, iff we encountered, trunc or
9374     // trunc(lshr).
9375     if (User->getOpcode() != ISD::TRUNCATE)
9376       return false;
9377
9378     // The width of the type must be a power of 2 and greater than 8-bits.
9379     // Otherwise the load cannot be represented in LLVM IR.
9380     // Moreover, if we shifted with a non-8-bits multiple, the slice
9381     // will be across several bytes. We do not support that.
9382     unsigned Width = User->getValueSizeInBits(0);
9383     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9384       return 0;
9385
9386     // Build the slice for this chain of computations.
9387     LoadedSlice LS(User, LD, Shift, &DAG);
9388     APInt CurrentUsedBits = LS.getUsedBits();
9389
9390     // Check if this slice overlaps with another.
9391     if ((CurrentUsedBits & UsedBits) != 0)
9392       return false;
9393     // Update the bits used globally.
9394     UsedBits |= CurrentUsedBits;
9395
9396     // Check if the new slice would be legal.
9397     if (!LS.isLegal())
9398       return false;
9399
9400     // Record the slice.
9401     LoadedSlices.push_back(LS);
9402   }
9403
9404   // Abort slicing if it does not seem to be profitable.
9405   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9406     return false;
9407
9408   ++SlicedLoads;
9409
9410   // Rewrite each chain to use an independent load.
9411   // By construction, each chain can be represented by a unique load.
9412
9413   // Prepare the argument for the new token factor for all the slices.
9414   SmallVector<SDValue, 8> ArgChains;
9415   for (SmallVectorImpl<LoadedSlice>::const_iterator
9416            LSIt = LoadedSlices.begin(),
9417            LSItEnd = LoadedSlices.end();
9418        LSIt != LSItEnd; ++LSIt) {
9419     SDValue SliceInst = LSIt->loadSlice();
9420     CombineTo(LSIt->Inst, SliceInst, true);
9421     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9422       SliceInst = SliceInst.getOperand(0);
9423     assert(SliceInst->getOpcode() == ISD::LOAD &&
9424            "It takes more than a zext to get to the loaded slice!!");
9425     ArgChains.push_back(SliceInst.getValue(1));
9426   }
9427
9428   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9429                               ArgChains);
9430   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9431   return true;
9432 }
9433
9434 /// Check to see if V is (and load (ptr), imm), where the load is having
9435 /// specific bytes cleared out.  If so, return the byte size being masked out
9436 /// and the shift amount.
9437 static std::pair<unsigned, unsigned>
9438 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9439   std::pair<unsigned, unsigned> Result(0, 0);
9440
9441   // Check for the structure we're looking for.
9442   if (V->getOpcode() != ISD::AND ||
9443       !isa<ConstantSDNode>(V->getOperand(1)) ||
9444       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9445     return Result;
9446
9447   // Check the chain and pointer.
9448   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9449   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9450
9451   // The store should be chained directly to the load or be an operand of a
9452   // tokenfactor.
9453   if (LD == Chain.getNode())
9454     ; // ok.
9455   else if (Chain->getOpcode() != ISD::TokenFactor)
9456     return Result; // Fail.
9457   else {
9458     bool isOk = false;
9459     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9460       if (Chain->getOperand(i).getNode() == LD) {
9461         isOk = true;
9462         break;
9463       }
9464     if (!isOk) return Result;
9465   }
9466
9467   // This only handles simple types.
9468   if (V.getValueType() != MVT::i16 &&
9469       V.getValueType() != MVT::i32 &&
9470       V.getValueType() != MVT::i64)
9471     return Result;
9472
9473   // Check the constant mask.  Invert it so that the bits being masked out are
9474   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9475   // follow the sign bit for uniformity.
9476   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9477   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9478   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9479   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9480   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9481   if (NotMaskLZ == 64) return Result;  // All zero mask.
9482
9483   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9484   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9485     return Result;
9486
9487   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9488   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9489     NotMaskLZ -= 64-V.getValueSizeInBits();
9490
9491   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9492   switch (MaskedBytes) {
9493   case 1:
9494   case 2:
9495   case 4: break;
9496   default: return Result; // All one mask, or 5-byte mask.
9497   }
9498
9499   // Verify that the first bit starts at a multiple of mask so that the access
9500   // is aligned the same as the access width.
9501   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9502
9503   Result.first = MaskedBytes;
9504   Result.second = NotMaskTZ/8;
9505   return Result;
9506 }
9507
9508
9509 /// Check to see if IVal is something that provides a value as specified by
9510 /// MaskInfo. If so, replace the specified store with a narrower store of
9511 /// truncated IVal.
9512 static SDNode *
9513 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9514                                 SDValue IVal, StoreSDNode *St,
9515                                 DAGCombiner *DC) {
9516   unsigned NumBytes = MaskInfo.first;
9517   unsigned ByteShift = MaskInfo.second;
9518   SelectionDAG &DAG = DC->getDAG();
9519
9520   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9521   // that uses this.  If not, this is not a replacement.
9522   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9523                                   ByteShift*8, (ByteShift+NumBytes)*8);
9524   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9525
9526   // Check that it is legal on the target to do this.  It is legal if the new
9527   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9528   // legalization.
9529   MVT VT = MVT::getIntegerVT(NumBytes*8);
9530   if (!DC->isTypeLegal(VT))
9531     return nullptr;
9532
9533   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9534   // shifted by ByteShift and truncated down to NumBytes.
9535   if (ByteShift)
9536     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9537                        DAG.getConstant(ByteShift*8,
9538                                     DC->getShiftAmountTy(IVal.getValueType())));
9539
9540   // Figure out the offset for the store and the alignment of the access.
9541   unsigned StOffset;
9542   unsigned NewAlign = St->getAlignment();
9543
9544   if (DAG.getTargetLoweringInfo().isLittleEndian())
9545     StOffset = ByteShift;
9546   else
9547     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9548
9549   SDValue Ptr = St->getBasePtr();
9550   if (StOffset) {
9551     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9552                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9553     NewAlign = MinAlign(NewAlign, StOffset);
9554   }
9555
9556   // Truncate down to the new size.
9557   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9558
9559   ++OpsNarrowed;
9560   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9561                       St->getPointerInfo().getWithOffset(StOffset),
9562                       false, false, NewAlign).getNode();
9563 }
9564
9565
9566 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9567 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9568 /// narrowing the load and store if it would end up being a win for performance
9569 /// or code size.
9570 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9571   StoreSDNode *ST  = cast<StoreSDNode>(N);
9572   if (ST->isVolatile())
9573     return SDValue();
9574
9575   SDValue Chain = ST->getChain();
9576   SDValue Value = ST->getValue();
9577   SDValue Ptr   = ST->getBasePtr();
9578   EVT VT = Value.getValueType();
9579
9580   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9581     return SDValue();
9582
9583   unsigned Opc = Value.getOpcode();
9584
9585   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9586   // is a byte mask indicating a consecutive number of bytes, check to see if
9587   // Y is known to provide just those bytes.  If so, we try to replace the
9588   // load + replace + store sequence with a single (narrower) store, which makes
9589   // the load dead.
9590   if (Opc == ISD::OR) {
9591     std::pair<unsigned, unsigned> MaskedLoad;
9592     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9593     if (MaskedLoad.first)
9594       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9595                                                   Value.getOperand(1), ST,this))
9596         return SDValue(NewST, 0);
9597
9598     // Or is commutative, so try swapping X and Y.
9599     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9600     if (MaskedLoad.first)
9601       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9602                                                   Value.getOperand(0), ST,this))
9603         return SDValue(NewST, 0);
9604   }
9605
9606   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9607       Value.getOperand(1).getOpcode() != ISD::Constant)
9608     return SDValue();
9609
9610   SDValue N0 = Value.getOperand(0);
9611   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9612       Chain == SDValue(N0.getNode(), 1)) {
9613     LoadSDNode *LD = cast<LoadSDNode>(N0);
9614     if (LD->getBasePtr() != Ptr ||
9615         LD->getPointerInfo().getAddrSpace() !=
9616         ST->getPointerInfo().getAddrSpace())
9617       return SDValue();
9618
9619     // Find the type to narrow it the load / op / store to.
9620     SDValue N1 = Value.getOperand(1);
9621     unsigned BitWidth = N1.getValueSizeInBits();
9622     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9623     if (Opc == ISD::AND)
9624       Imm ^= APInt::getAllOnesValue(BitWidth);
9625     if (Imm == 0 || Imm.isAllOnesValue())
9626       return SDValue();
9627     unsigned ShAmt = Imm.countTrailingZeros();
9628     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9629     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9630     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9631     // The narrowing should be profitable, the load/store operation should be
9632     // legal (or custom) and the store size should be equal to the NewVT width.
9633     while (NewBW < BitWidth &&
9634            (NewVT.getStoreSizeInBits() != NewBW ||
9635             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9636             !TLI.isNarrowingProfitable(VT, NewVT))) {
9637       NewBW = NextPowerOf2(NewBW);
9638       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9639     }
9640     if (NewBW >= BitWidth)
9641       return SDValue();
9642
9643     // If the lsb changed does not start at the type bitwidth boundary,
9644     // start at the previous one.
9645     if (ShAmt % NewBW)
9646       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9647     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9648                                    std::min(BitWidth, ShAmt + NewBW));
9649     if ((Imm & Mask) == Imm) {
9650       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9651       if (Opc == ISD::AND)
9652         NewImm ^= APInt::getAllOnesValue(NewBW);
9653       uint64_t PtrOff = ShAmt / 8;
9654       // For big endian targets, we need to adjust the offset to the pointer to
9655       // load the correct bytes.
9656       if (TLI.isBigEndian())
9657         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9658
9659       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9660       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9661       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9662         return SDValue();
9663
9664       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9665                                    Ptr.getValueType(), Ptr,
9666                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9667       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9668                                   LD->getChain(), NewPtr,
9669                                   LD->getPointerInfo().getWithOffset(PtrOff),
9670                                   LD->isVolatile(), LD->isNonTemporal(),
9671                                   LD->isInvariant(), NewAlign,
9672                                   LD->getAAInfo());
9673       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9674                                    DAG.getConstant(NewImm, NewVT));
9675       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9676                                    NewVal, NewPtr,
9677                                    ST->getPointerInfo().getWithOffset(PtrOff),
9678                                    false, false, NewAlign);
9679
9680       AddToWorklist(NewPtr.getNode());
9681       AddToWorklist(NewLD.getNode());
9682       AddToWorklist(NewVal.getNode());
9683       WorklistRemover DeadNodes(*this);
9684       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9685       ++OpsNarrowed;
9686       return NewST;
9687     }
9688   }
9689
9690   return SDValue();
9691 }
9692
9693 /// For a given floating point load / store pair, if the load value isn't used
9694 /// by any other operations, then consider transforming the pair to integer
9695 /// load / store operations if the target deems the transformation profitable.
9696 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9697   StoreSDNode *ST  = cast<StoreSDNode>(N);
9698   SDValue Chain = ST->getChain();
9699   SDValue Value = ST->getValue();
9700   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9701       Value.hasOneUse() &&
9702       Chain == SDValue(Value.getNode(), 1)) {
9703     LoadSDNode *LD = cast<LoadSDNode>(Value);
9704     EVT VT = LD->getMemoryVT();
9705     if (!VT.isFloatingPoint() ||
9706         VT != ST->getMemoryVT() ||
9707         LD->isNonTemporal() ||
9708         ST->isNonTemporal() ||
9709         LD->getPointerInfo().getAddrSpace() != 0 ||
9710         ST->getPointerInfo().getAddrSpace() != 0)
9711       return SDValue();
9712
9713     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9714     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9715         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9716         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9717         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9718       return SDValue();
9719
9720     unsigned LDAlign = LD->getAlignment();
9721     unsigned STAlign = ST->getAlignment();
9722     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9723     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9724     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9725       return SDValue();
9726
9727     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9728                                 LD->getChain(), LD->getBasePtr(),
9729                                 LD->getPointerInfo(),
9730                                 false, false, false, LDAlign);
9731
9732     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9733                                  NewLD, ST->getBasePtr(),
9734                                  ST->getPointerInfo(),
9735                                  false, false, STAlign);
9736
9737     AddToWorklist(NewLD.getNode());
9738     AddToWorklist(NewST.getNode());
9739     WorklistRemover DeadNodes(*this);
9740     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9741     ++LdStFP2Int;
9742     return NewST;
9743   }
9744
9745   return SDValue();
9746 }
9747
9748 /// Helper struct to parse and store a memory address as base + index + offset.
9749 /// We ignore sign extensions when it is safe to do so.
9750 /// The following two expressions are not equivalent. To differentiate we need
9751 /// to store whether there was a sign extension involved in the index
9752 /// computation.
9753 ///  (load (i64 add (i64 copyfromreg %c)
9754 ///                 (i64 signextend (add (i8 load %index)
9755 ///                                      (i8 1))))
9756 /// vs
9757 ///
9758 /// (load (i64 add (i64 copyfromreg %c)
9759 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9760 ///                                         (i32 1)))))
9761 struct BaseIndexOffset {
9762   SDValue Base;
9763   SDValue Index;
9764   int64_t Offset;
9765   bool IsIndexSignExt;
9766
9767   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9768
9769   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9770                   bool IsIndexSignExt) :
9771     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9772
9773   bool equalBaseIndex(const BaseIndexOffset &Other) {
9774     return Other.Base == Base && Other.Index == Index &&
9775       Other.IsIndexSignExt == IsIndexSignExt;
9776   }
9777
9778   /// Parses tree in Ptr for base, index, offset addresses.
9779   static BaseIndexOffset match(SDValue Ptr) {
9780     bool IsIndexSignExt = false;
9781
9782     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9783     // instruction, then it could be just the BASE or everything else we don't
9784     // know how to handle. Just use Ptr as BASE and give up.
9785     if (Ptr->getOpcode() != ISD::ADD)
9786       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9787
9788     // We know that we have at least an ADD instruction. Try to pattern match
9789     // the simple case of BASE + OFFSET.
9790     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9791       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9792       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9793                               IsIndexSignExt);
9794     }
9795
9796     // Inside a loop the current BASE pointer is calculated using an ADD and a
9797     // MUL instruction. In this case Ptr is the actual BASE pointer.
9798     // (i64 add (i64 %array_ptr)
9799     //          (i64 mul (i64 %induction_var)
9800     //                   (i64 %element_size)))
9801     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9802       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9803
9804     // Look at Base + Index + Offset cases.
9805     SDValue Base = Ptr->getOperand(0);
9806     SDValue IndexOffset = Ptr->getOperand(1);
9807
9808     // Skip signextends.
9809     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9810       IndexOffset = IndexOffset->getOperand(0);
9811       IsIndexSignExt = true;
9812     }
9813
9814     // Either the case of Base + Index (no offset) or something else.
9815     if (IndexOffset->getOpcode() != ISD::ADD)
9816       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9817
9818     // Now we have the case of Base + Index + offset.
9819     SDValue Index = IndexOffset->getOperand(0);
9820     SDValue Offset = IndexOffset->getOperand(1);
9821
9822     if (!isa<ConstantSDNode>(Offset))
9823       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9824
9825     // Ignore signextends.
9826     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9827       Index = Index->getOperand(0);
9828       IsIndexSignExt = true;
9829     } else IsIndexSignExt = false;
9830
9831     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9832     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9833   }
9834 };
9835
9836 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
9837                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
9838                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
9839   // Make sure we have something to merge.
9840   if (NumElem < 2)
9841     return false;
9842   
9843   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
9844   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9845   unsigned EarliestNodeUsed = 0;
9846   
9847   for (unsigned i=0; i < NumElem; ++i) {
9848     // Find a chain for the new wide-store operand. Notice that some
9849     // of the store nodes that we found may not be selected for inclusion
9850     // in the wide store. The chain we use needs to be the chain of the
9851     // earliest store node which is *used* and replaced by the wide store.
9852     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9853       EarliestNodeUsed = i;
9854   }
9855   
9856   // The earliest Node in the DAG.
9857   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9858   SDLoc DL(StoreNodes[0].MemNode);
9859   
9860   SDValue StoredVal;
9861   if (UseVector) {
9862     // Find a legal type for the vector store.
9863     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9864     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9865     if (IsConstantSrc) {
9866       // A vector store with a constant source implies that the constant is
9867       // zero; we only handle merging stores of constant zeros because the zero
9868       // can be materialized without a load.
9869       // It may be beneficial to loosen this restriction to allow non-zero
9870       // store merging.
9871       StoredVal = DAG.getConstant(0, Ty);
9872     } else {
9873       SmallVector<SDValue, 8> Ops;
9874       for (unsigned i = 0; i < NumElem ; ++i) {
9875         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9876         SDValue Val = St->getValue();
9877         // All of the operands of a BUILD_VECTOR must have the same type.
9878         if (Val.getValueType() != MemVT)
9879           return false;
9880         Ops.push_back(Val);
9881       }
9882       
9883       // Build the extracted vector elements back into a vector.
9884       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
9885     }
9886   } else {
9887     // We should always use a vector store when merging extracted vector
9888     // elements, so this path implies a store of constants.
9889     assert(IsConstantSrc && "Merged vector elements should use vector store");
9890
9891     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9892     APInt StoreInt(StoreBW, 0);
9893     
9894     // Construct a single integer constant which is made of the smaller
9895     // constant inputs.
9896     bool IsLE = TLI.isLittleEndian();
9897     for (unsigned i = 0; i < NumElem ; ++i) {
9898       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
9899       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9900       SDValue Val = St->getValue();
9901       StoreInt <<= ElementSizeBytes*8;
9902       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9903         StoreInt |= C->getAPIntValue().zext(StoreBW);
9904       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9905         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9906       } else {
9907         llvm_unreachable("Invalid constant element type");
9908       }
9909     }
9910     
9911     // Create the new Load and Store operations.
9912     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9913     StoredVal = DAG.getConstant(StoreInt, StoreTy);
9914   }
9915   
9916   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9917                                   FirstInChain->getBasePtr(),
9918                                   FirstInChain->getPointerInfo(),
9919                                   false, false,
9920                                   FirstInChain->getAlignment());
9921   
9922   // Replace the first store with the new store
9923   CombineTo(EarliestOp, NewStore);
9924   // Erase all other stores.
9925   for (unsigned i = 0; i < NumElem ; ++i) {
9926     if (StoreNodes[i].MemNode == EarliestOp)
9927       continue;
9928     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9929     // ReplaceAllUsesWith will replace all uses that existed when it was
9930     // called, but graph optimizations may cause new ones to appear. For
9931     // example, the case in pr14333 looks like
9932     //
9933     //  St's chain -> St -> another store -> X
9934     //
9935     // And the only difference from St to the other store is the chain.
9936     // When we change it's chain to be St's chain they become identical,
9937     // get CSEed and the net result is that X is now a use of St.
9938     // Since we know that St is redundant, just iterate.
9939     while (!St->use_empty())
9940       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9941     deleteAndRecombine(St);
9942   }
9943   
9944   return true;
9945 }
9946
9947 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9948   EVT MemVT = St->getMemoryVT();
9949   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9950   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9951     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9952
9953   // Don't merge vectors into wider inputs.
9954   if (MemVT.isVector() || !MemVT.isSimple())
9955     return false;
9956
9957   // Perform an early exit check. Do not bother looking at stored values that
9958   // are not constants, loads, or extracted vector elements.
9959   SDValue StoredVal = St->getValue();
9960   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9961   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
9962                        isa<ConstantFPSDNode>(StoredVal);
9963   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
9964    
9965   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
9966     return false;
9967
9968   // Only look at ends of store sequences.
9969   SDValue Chain = SDValue(St, 0);
9970   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9971     return false;
9972
9973   // This holds the base pointer, index, and the offset in bytes from the base
9974   // pointer.
9975   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9976
9977   // We must have a base and an offset.
9978   if (!BasePtr.Base.getNode())
9979     return false;
9980
9981   // Do not handle stores to undef base pointers.
9982   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9983     return false;
9984
9985   // Save the LoadSDNodes that we find in the chain.
9986   // We need to make sure that these nodes do not interfere with
9987   // any of the store nodes.
9988   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9989
9990   // Save the StoreSDNodes that we find in the chain.
9991   SmallVector<MemOpLink, 8> StoreNodes;
9992
9993   // Walk up the chain and look for nodes with offsets from the same
9994   // base pointer. Stop when reaching an instruction with a different kind
9995   // or instruction which has a different base pointer.
9996   unsigned Seq = 0;
9997   StoreSDNode *Index = St;
9998   while (Index) {
9999     // If the chain has more than one use, then we can't reorder the mem ops.
10000     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10001       break;
10002
10003     // Find the base pointer and offset for this memory node.
10004     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10005
10006     // Check that the base pointer is the same as the original one.
10007     if (!Ptr.equalBaseIndex(BasePtr))
10008       break;
10009
10010     // Check that the alignment is the same.
10011     if (Index->getAlignment() != St->getAlignment())
10012       break;
10013
10014     // The memory operands must not be volatile.
10015     if (Index->isVolatile() || Index->isIndexed())
10016       break;
10017
10018     // No truncation.
10019     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10020       if (St->isTruncatingStore())
10021         break;
10022
10023     // The stored memory type must be the same.
10024     if (Index->getMemoryVT() != MemVT)
10025       break;
10026
10027     // We do not allow unaligned stores because we want to prevent overriding
10028     // stores.
10029     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10030       break;
10031
10032     // We found a potential memory operand to merge.
10033     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10034
10035     // Find the next memory operand in the chain. If the next operand in the
10036     // chain is a store then move up and continue the scan with the next
10037     // memory operand. If the next operand is a load save it and use alias
10038     // information to check if it interferes with anything.
10039     SDNode *NextInChain = Index->getChain().getNode();
10040     while (1) {
10041       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10042         // We found a store node. Use it for the next iteration.
10043         Index = STn;
10044         break;
10045       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10046         if (Ldn->isVolatile()) {
10047           Index = nullptr;
10048           break;
10049         }
10050
10051         // Save the load node for later. Continue the scan.
10052         AliasLoadNodes.push_back(Ldn);
10053         NextInChain = Ldn->getChain().getNode();
10054         continue;
10055       } else {
10056         Index = nullptr;
10057         break;
10058       }
10059     }
10060   }
10061
10062   // Check if there is anything to merge.
10063   if (StoreNodes.size() < 2)
10064     return false;
10065
10066   // Sort the memory operands according to their distance from the base pointer.
10067   std::sort(StoreNodes.begin(), StoreNodes.end(),
10068             [](MemOpLink LHS, MemOpLink RHS) {
10069     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10070            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10071             LHS.SequenceNum > RHS.SequenceNum);
10072   });
10073
10074   // Scan the memory operations on the chain and find the first non-consecutive
10075   // store memory address.
10076   unsigned LastConsecutiveStore = 0;
10077   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10078   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10079
10080     // Check that the addresses are consecutive starting from the second
10081     // element in the list of stores.
10082     if (i > 0) {
10083       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10084       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10085         break;
10086     }
10087
10088     bool Alias = false;
10089     // Check if this store interferes with any of the loads that we found.
10090     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10091       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10092         Alias = true;
10093         break;
10094       }
10095     // We found a load that alias with this store. Stop the sequence.
10096     if (Alias)
10097       break;
10098
10099     // Mark this node as useful.
10100     LastConsecutiveStore = i;
10101   }
10102
10103   // The node with the lowest store address.
10104   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10105
10106   // Store the constants into memory as one consecutive store.
10107   if (IsConstantSrc) {
10108     unsigned LastLegalType = 0;
10109     unsigned LastLegalVectorType = 0;
10110     bool NonZero = false;
10111     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10112       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10113       SDValue StoredVal = St->getValue();
10114
10115       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10116         NonZero |= !C->isNullValue();
10117       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10118         NonZero |= !C->getConstantFPValue()->isNullValue();
10119       } else {
10120         // Non-constant.
10121         break;
10122       }
10123
10124       // Find a legal type for the constant store.
10125       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10126       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10127       if (TLI.isTypeLegal(StoreTy))
10128         LastLegalType = i+1;
10129       // Or check whether a truncstore is legal.
10130       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10131                TargetLowering::TypePromoteInteger) {
10132         EVT LegalizedStoredValueTy =
10133           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10134         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10135           LastLegalType = i+1;
10136       }
10137
10138       // Find a legal type for the vector store.
10139       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10140       if (TLI.isTypeLegal(Ty))
10141         LastLegalVectorType = i + 1;
10142     }
10143
10144     // We only use vectors if the constant is known to be zero and the
10145     // function is not marked with the noimplicitfloat attribute.
10146     if (NonZero || NoVectors)
10147       LastLegalVectorType = 0;
10148
10149     // Check if we found a legal integer type to store.
10150     if (LastLegalType == 0 && LastLegalVectorType == 0)
10151       return false;
10152
10153     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10154     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10155
10156     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10157                                            true, UseVector);
10158   }
10159
10160   // When extracting multiple vector elements, try to store them
10161   // in one vector store rather than a sequence of scalar stores.
10162   if (IsExtractVecEltSrc) {
10163     unsigned NumElem = 0;
10164     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10165       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10166       SDValue StoredVal = St->getValue();
10167       // This restriction could be loosened.
10168       // Bail out if any stored values are not elements extracted from a vector.
10169       // It should be possible to handle mixed sources, but load sources need
10170       // more careful handling (see the block of code below that handles
10171       // consecutive loads).
10172       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10173         return false;
10174       
10175       // Find a legal type for the vector store.
10176       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10177       if (TLI.isTypeLegal(Ty))
10178         NumElem = i + 1;
10179     }
10180
10181     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10182                                            false, true);
10183   }
10184
10185   // Below we handle the case of multiple consecutive stores that
10186   // come from multiple consecutive loads. We merge them into a single
10187   // wide load and a single wide store.
10188
10189   // Look for load nodes which are used by the stored values.
10190   SmallVector<MemOpLink, 8> LoadNodes;
10191
10192   // Find acceptable loads. Loads need to have the same chain (token factor),
10193   // must not be zext, volatile, indexed, and they must be consecutive.
10194   BaseIndexOffset LdBasePtr;
10195   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10196     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10197     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10198     if (!Ld) break;
10199
10200     // Loads must only have one use.
10201     if (!Ld->hasNUsesOfValue(1, 0))
10202       break;
10203
10204     // Check that the alignment is the same as the stores.
10205     if (Ld->getAlignment() != St->getAlignment())
10206       break;
10207
10208     // The memory operands must not be volatile.
10209     if (Ld->isVolatile() || Ld->isIndexed())
10210       break;
10211
10212     // We do not accept ext loads.
10213     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10214       break;
10215
10216     // The stored memory type must be the same.
10217     if (Ld->getMemoryVT() != MemVT)
10218       break;
10219
10220     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10221     // If this is not the first ptr that we check.
10222     if (LdBasePtr.Base.getNode()) {
10223       // The base ptr must be the same.
10224       if (!LdPtr.equalBaseIndex(LdBasePtr))
10225         break;
10226     } else {
10227       // Check that all other base pointers are the same as this one.
10228       LdBasePtr = LdPtr;
10229     }
10230
10231     // We found a potential memory operand to merge.
10232     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10233   }
10234
10235   if (LoadNodes.size() < 2)
10236     return false;
10237
10238   // If we have load/store pair instructions and we only have two values,
10239   // don't bother.
10240   unsigned RequiredAlignment;
10241   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10242       St->getAlignment() >= RequiredAlignment)
10243     return false;
10244
10245   // Scan the memory operations on the chain and find the first non-consecutive
10246   // load memory address. These variables hold the index in the store node
10247   // array.
10248   unsigned LastConsecutiveLoad = 0;
10249   // This variable refers to the size and not index in the array.
10250   unsigned LastLegalVectorType = 0;
10251   unsigned LastLegalIntegerType = 0;
10252   StartAddress = LoadNodes[0].OffsetFromBase;
10253   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10254   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10255     // All loads much share the same chain.
10256     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10257       break;
10258
10259     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10260     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10261       break;
10262     LastConsecutiveLoad = i;
10263
10264     // Find a legal type for the vector store.
10265     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10266     if (TLI.isTypeLegal(StoreTy))
10267       LastLegalVectorType = i + 1;
10268
10269     // Find a legal type for the integer store.
10270     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10271     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10272     if (TLI.isTypeLegal(StoreTy))
10273       LastLegalIntegerType = i + 1;
10274     // Or check whether a truncstore and extload is legal.
10275     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10276              TargetLowering::TypePromoteInteger) {
10277       EVT LegalizedStoredValueTy =
10278         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10279       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10280           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10281           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10282           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10283         LastLegalIntegerType = i+1;
10284     }
10285   }
10286
10287   // Only use vector types if the vector type is larger than the integer type.
10288   // If they are the same, use integers.
10289   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10290   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10291
10292   // We add +1 here because the LastXXX variables refer to location while
10293   // the NumElem refers to array/index size.
10294   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10295   NumElem = std::min(LastLegalType, NumElem);
10296
10297   if (NumElem < 2)
10298     return false;
10299
10300   // The earliest Node in the DAG.
10301   unsigned EarliestNodeUsed = 0;
10302   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10303   for (unsigned i=1; i<NumElem; ++i) {
10304     // Find a chain for the new wide-store operand. Notice that some
10305     // of the store nodes that we found may not be selected for inclusion
10306     // in the wide store. The chain we use needs to be the chain of the
10307     // earliest store node which is *used* and replaced by the wide store.
10308     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10309       EarliestNodeUsed = i;
10310   }
10311
10312   // Find if it is better to use vectors or integers to load and store
10313   // to memory.
10314   EVT JointMemOpVT;
10315   if (UseVectorTy) {
10316     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10317   } else {
10318     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10319     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10320   }
10321
10322   SDLoc LoadDL(LoadNodes[0].MemNode);
10323   SDLoc StoreDL(StoreNodes[0].MemNode);
10324
10325   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10326   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10327                                 FirstLoad->getChain(),
10328                                 FirstLoad->getBasePtr(),
10329                                 FirstLoad->getPointerInfo(),
10330                                 false, false, false,
10331                                 FirstLoad->getAlignment());
10332
10333   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10334                                   FirstInChain->getBasePtr(),
10335                                   FirstInChain->getPointerInfo(), false, false,
10336                                   FirstInChain->getAlignment());
10337
10338   // Replace one of the loads with the new load.
10339   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10340   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10341                                 SDValue(NewLoad.getNode(), 1));
10342
10343   // Remove the rest of the load chains.
10344   for (unsigned i = 1; i < NumElem ; ++i) {
10345     // Replace all chain users of the old load nodes with the chain of the new
10346     // load node.
10347     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10348     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10349   }
10350
10351   // Replace the first store with the new store.
10352   CombineTo(EarliestOp, NewStore);
10353   // Erase all other stores.
10354   for (unsigned i = 0; i < NumElem ; ++i) {
10355     // Remove all Store nodes.
10356     if (StoreNodes[i].MemNode == EarliestOp)
10357       continue;
10358     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10359     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10360     deleteAndRecombine(St);
10361   }
10362
10363   return true;
10364 }
10365
10366 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10367   StoreSDNode *ST  = cast<StoreSDNode>(N);
10368   SDValue Chain = ST->getChain();
10369   SDValue Value = ST->getValue();
10370   SDValue Ptr   = ST->getBasePtr();
10371
10372   // If this is a store of a bit convert, store the input value if the
10373   // resultant store does not need a higher alignment than the original.
10374   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10375       ST->isUnindexed()) {
10376     unsigned OrigAlign = ST->getAlignment();
10377     EVT SVT = Value.getOperand(0).getValueType();
10378     unsigned Align = TLI.getDataLayout()->
10379       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10380     if (Align <= OrigAlign &&
10381         ((!LegalOperations && !ST->isVolatile()) ||
10382          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10383       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10384                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10385                           ST->isNonTemporal(), OrigAlign,
10386                           ST->getAAInfo());
10387   }
10388
10389   // Turn 'store undef, Ptr' -> nothing.
10390   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10391     return Chain;
10392
10393   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10394   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10395     // NOTE: If the original store is volatile, this transform must not increase
10396     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10397     // processor operation but an i64 (which is not legal) requires two.  So the
10398     // transform should not be done in this case.
10399     if (Value.getOpcode() != ISD::TargetConstantFP) {
10400       SDValue Tmp;
10401       switch (CFP->getSimpleValueType(0).SimpleTy) {
10402       default: llvm_unreachable("Unknown FP type");
10403       case MVT::f16:    // We don't do this for these yet.
10404       case MVT::f80:
10405       case MVT::f128:
10406       case MVT::ppcf128:
10407         break;
10408       case MVT::f32:
10409         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10410             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10411           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10412                               bitcastToAPInt().getZExtValue(), MVT::i32);
10413           return DAG.getStore(Chain, SDLoc(N), Tmp,
10414                               Ptr, ST->getMemOperand());
10415         }
10416         break;
10417       case MVT::f64:
10418         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10419              !ST->isVolatile()) ||
10420             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10421           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10422                                 getZExtValue(), MVT::i64);
10423           return DAG.getStore(Chain, SDLoc(N), Tmp,
10424                               Ptr, ST->getMemOperand());
10425         }
10426
10427         if (!ST->isVolatile() &&
10428             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10429           // Many FP stores are not made apparent until after legalize, e.g. for
10430           // argument passing.  Since this is so common, custom legalize the
10431           // 64-bit integer store into two 32-bit stores.
10432           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10433           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10434           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10435           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10436
10437           unsigned Alignment = ST->getAlignment();
10438           bool isVolatile = ST->isVolatile();
10439           bool isNonTemporal = ST->isNonTemporal();
10440           AAMDNodes AAInfo = ST->getAAInfo();
10441
10442           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10443                                      Ptr, ST->getPointerInfo(),
10444                                      isVolatile, isNonTemporal,
10445                                      ST->getAlignment(), AAInfo);
10446           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10447                             DAG.getConstant(4, Ptr.getValueType()));
10448           Alignment = MinAlign(Alignment, 4U);
10449           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10450                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10451                                      isVolatile, isNonTemporal,
10452                                      Alignment, AAInfo);
10453           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10454                              St0, St1);
10455         }
10456
10457         break;
10458       }
10459     }
10460   }
10461
10462   // Try to infer better alignment information than the store already has.
10463   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10464     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10465       if (Align > ST->getAlignment())
10466         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10467                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10468                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10469                                  ST->getAAInfo());
10470     }
10471   }
10472
10473   // Try transforming a pair floating point load / store ops to integer
10474   // load / store ops.
10475   SDValue NewST = TransformFPLoadStorePair(N);
10476   if (NewST.getNode())
10477     return NewST;
10478
10479   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10480                                                   : DAG.getSubtarget().useAA();
10481 #ifndef NDEBUG
10482   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10483       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10484     UseAA = false;
10485 #endif
10486   if (UseAA && ST->isUnindexed()) {
10487     // Walk up chain skipping non-aliasing memory nodes.
10488     SDValue BetterChain = FindBetterChain(N, Chain);
10489
10490     // If there is a better chain.
10491     if (Chain != BetterChain) {
10492       SDValue ReplStore;
10493
10494       // Replace the chain to avoid dependency.
10495       if (ST->isTruncatingStore()) {
10496         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10497                                       ST->getMemoryVT(), ST->getMemOperand());
10498       } else {
10499         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10500                                  ST->getMemOperand());
10501       }
10502
10503       // Create token to keep both nodes around.
10504       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10505                                   MVT::Other, Chain, ReplStore);
10506
10507       // Make sure the new and old chains are cleaned up.
10508       AddToWorklist(Token.getNode());
10509
10510       // Don't add users to work list.
10511       return CombineTo(N, Token, false);
10512     }
10513   }
10514
10515   // Try transforming N to an indexed store.
10516   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10517     return SDValue(N, 0);
10518
10519   // FIXME: is there such a thing as a truncating indexed store?
10520   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10521       Value.getValueType().isInteger()) {
10522     // See if we can simplify the input to this truncstore with knowledge that
10523     // only the low bits are being used.  For example:
10524     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10525     SDValue Shorter =
10526       GetDemandedBits(Value,
10527                       APInt::getLowBitsSet(
10528                         Value.getValueType().getScalarType().getSizeInBits(),
10529                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10530     AddToWorklist(Value.getNode());
10531     if (Shorter.getNode())
10532       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10533                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10534
10535     // Otherwise, see if we can simplify the operation with
10536     // SimplifyDemandedBits, which only works if the value has a single use.
10537     if (SimplifyDemandedBits(Value,
10538                         APInt::getLowBitsSet(
10539                           Value.getValueType().getScalarType().getSizeInBits(),
10540                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10541       return SDValue(N, 0);
10542   }
10543
10544   // If this is a load followed by a store to the same location, then the store
10545   // is dead/noop.
10546   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10547     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10548         ST->isUnindexed() && !ST->isVolatile() &&
10549         // There can't be any side effects between the load and store, such as
10550         // a call or store.
10551         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10552       // The store is dead, remove it.
10553       return Chain;
10554     }
10555   }
10556
10557   // If this is a store followed by a store with the same value to the same
10558   // location, then the store is dead/noop.
10559   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10560     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10561         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10562         ST1->isUnindexed() && !ST1->isVolatile()) {
10563       // The store is dead, remove it.
10564       return Chain;
10565     }
10566   }
10567
10568   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10569   // truncating store.  We can do this even if this is already a truncstore.
10570   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10571       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10572       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10573                             ST->getMemoryVT())) {
10574     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10575                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10576   }
10577
10578   // Only perform this optimization before the types are legal, because we
10579   // don't want to perform this optimization on every DAGCombine invocation.
10580   if (!LegalTypes) {
10581     bool EverChanged = false;
10582
10583     do {
10584       // There can be multiple store sequences on the same chain.
10585       // Keep trying to merge store sequences until we are unable to do so
10586       // or until we merge the last store on the chain.
10587       bool Changed = MergeConsecutiveStores(ST);
10588       EverChanged |= Changed;
10589       if (!Changed) break;
10590     } while (ST->getOpcode() != ISD::DELETED_NODE);
10591
10592     if (EverChanged)
10593       return SDValue(N, 0);
10594   }
10595
10596   return ReduceLoadOpStoreWidth(N);
10597 }
10598
10599 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10600   SDValue InVec = N->getOperand(0);
10601   SDValue InVal = N->getOperand(1);
10602   SDValue EltNo = N->getOperand(2);
10603   SDLoc dl(N);
10604
10605   // If the inserted element is an UNDEF, just use the input vector.
10606   if (InVal.getOpcode() == ISD::UNDEF)
10607     return InVec;
10608
10609   EVT VT = InVec.getValueType();
10610
10611   // If we can't generate a legal BUILD_VECTOR, exit
10612   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10613     return SDValue();
10614
10615   // Check that we know which element is being inserted
10616   if (!isa<ConstantSDNode>(EltNo))
10617     return SDValue();
10618   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10619
10620   // Canonicalize insert_vector_elt dag nodes.
10621   // Example:
10622   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10623   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10624   //
10625   // Do this only if the child insert_vector node has one use; also
10626   // do this only if indices are both constants and Idx1 < Idx0.
10627   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10628       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10629     unsigned OtherElt =
10630       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10631     if (Elt < OtherElt) {
10632       // Swap nodes.
10633       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10634                                   InVec.getOperand(0), InVal, EltNo);
10635       AddToWorklist(NewOp.getNode());
10636       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10637                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10638     }
10639   }
10640
10641   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10642   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10643   // vector elements.
10644   SmallVector<SDValue, 8> Ops;
10645   // Do not combine these two vectors if the output vector will not replace
10646   // the input vector.
10647   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10648     Ops.append(InVec.getNode()->op_begin(),
10649                InVec.getNode()->op_end());
10650   } else if (InVec.getOpcode() == ISD::UNDEF) {
10651     unsigned NElts = VT.getVectorNumElements();
10652     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10653   } else {
10654     return SDValue();
10655   }
10656
10657   // Insert the element
10658   if (Elt < Ops.size()) {
10659     // All the operands of BUILD_VECTOR must have the same type;
10660     // we enforce that here.
10661     EVT OpVT = Ops[0].getValueType();
10662     if (InVal.getValueType() != OpVT)
10663       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10664                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10665                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10666     Ops[Elt] = InVal;
10667   }
10668
10669   // Return the new vector
10670   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10671 }
10672
10673 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10674     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10675   EVT ResultVT = EVE->getValueType(0);
10676   EVT VecEltVT = InVecVT.getVectorElementType();
10677   unsigned Align = OriginalLoad->getAlignment();
10678   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10679       VecEltVT.getTypeForEVT(*DAG.getContext()));
10680
10681   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10682     return SDValue();
10683
10684   Align = NewAlign;
10685
10686   SDValue NewPtr = OriginalLoad->getBasePtr();
10687   SDValue Offset;
10688   EVT PtrType = NewPtr.getValueType();
10689   MachinePointerInfo MPI;
10690   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10691     int Elt = ConstEltNo->getZExtValue();
10692     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10693     if (TLI.isBigEndian())
10694       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10695     Offset = DAG.getConstant(PtrOff, PtrType);
10696     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10697   } else {
10698     Offset = DAG.getNode(
10699         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10700         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10701     if (TLI.isBigEndian())
10702       Offset = DAG.getNode(
10703           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10704           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10705     MPI = OriginalLoad->getPointerInfo();
10706   }
10707   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10708
10709   // The replacement we need to do here is a little tricky: we need to
10710   // replace an extractelement of a load with a load.
10711   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10712   // Note that this replacement assumes that the extractvalue is the only
10713   // use of the load; that's okay because we don't want to perform this
10714   // transformation in other cases anyway.
10715   SDValue Load;
10716   SDValue Chain;
10717   if (ResultVT.bitsGT(VecEltVT)) {
10718     // If the result type of vextract is wider than the load, then issue an
10719     // extending load instead.
10720     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10721                                                   VecEltVT)
10722                                    ? ISD::ZEXTLOAD
10723                                    : ISD::EXTLOAD;
10724     Load = DAG.getExtLoad(
10725         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10726         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10727         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10728     Chain = Load.getValue(1);
10729   } else {
10730     Load = DAG.getLoad(
10731         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10732         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10733         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10734     Chain = Load.getValue(1);
10735     if (ResultVT.bitsLT(VecEltVT))
10736       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10737     else
10738       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10739   }
10740   WorklistRemover DeadNodes(*this);
10741   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10742   SDValue To[] = { Load, Chain };
10743   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10744   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10745   // worklist explicitly as well.
10746   AddToWorklist(Load.getNode());
10747   AddUsersToWorklist(Load.getNode()); // Add users too
10748   // Make sure to revisit this node to clean it up; it will usually be dead.
10749   AddToWorklist(EVE);
10750   ++OpsNarrowed;
10751   return SDValue(EVE, 0);
10752 }
10753
10754 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10755   // (vextract (scalar_to_vector val, 0) -> val
10756   SDValue InVec = N->getOperand(0);
10757   EVT VT = InVec.getValueType();
10758   EVT NVT = N->getValueType(0);
10759
10760   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10761     // Check if the result type doesn't match the inserted element type. A
10762     // SCALAR_TO_VECTOR may truncate the inserted element and the
10763     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10764     SDValue InOp = InVec.getOperand(0);
10765     if (InOp.getValueType() != NVT) {
10766       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10767       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10768     }
10769     return InOp;
10770   }
10771
10772   SDValue EltNo = N->getOperand(1);
10773   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10774
10775   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10776   // We only perform this optimization before the op legalization phase because
10777   // we may introduce new vector instructions which are not backed by TD
10778   // patterns. For example on AVX, extracting elements from a wide vector
10779   // without using extract_subvector. However, if we can find an underlying
10780   // scalar value, then we can always use that.
10781   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10782       && ConstEltNo) {
10783     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10784     int NumElem = VT.getVectorNumElements();
10785     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10786     // Find the new index to extract from.
10787     int OrigElt = SVOp->getMaskElt(Elt);
10788
10789     // Extracting an undef index is undef.
10790     if (OrigElt == -1)
10791       return DAG.getUNDEF(NVT);
10792
10793     // Select the right vector half to extract from.
10794     SDValue SVInVec;
10795     if (OrigElt < NumElem) {
10796       SVInVec = InVec->getOperand(0);
10797     } else {
10798       SVInVec = InVec->getOperand(1);
10799       OrigElt -= NumElem;
10800     }
10801
10802     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10803       SDValue InOp = SVInVec.getOperand(OrigElt);
10804       if (InOp.getValueType() != NVT) {
10805         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10806         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10807       }
10808
10809       return InOp;
10810     }
10811
10812     // FIXME: We should handle recursing on other vector shuffles and
10813     // scalar_to_vector here as well.
10814
10815     if (!LegalOperations) {
10816       EVT IndexTy = TLI.getVectorIdxTy();
10817       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10818                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10819     }
10820   }
10821
10822   bool BCNumEltsChanged = false;
10823   EVT ExtVT = VT.getVectorElementType();
10824   EVT LVT = ExtVT;
10825
10826   // If the result of load has to be truncated, then it's not necessarily
10827   // profitable.
10828   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10829     return SDValue();
10830
10831   if (InVec.getOpcode() == ISD::BITCAST) {
10832     // Don't duplicate a load with other uses.
10833     if (!InVec.hasOneUse())
10834       return SDValue();
10835
10836     EVT BCVT = InVec.getOperand(0).getValueType();
10837     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10838       return SDValue();
10839     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10840       BCNumEltsChanged = true;
10841     InVec = InVec.getOperand(0);
10842     ExtVT = BCVT.getVectorElementType();
10843   }
10844
10845   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10846   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10847       ISD::isNormalLoad(InVec.getNode()) &&
10848       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10849     SDValue Index = N->getOperand(1);
10850     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10851       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10852                                                            OrigLoad);
10853   }
10854
10855   // Perform only after legalization to ensure build_vector / vector_shuffle
10856   // optimizations have already been done.
10857   if (!LegalOperations) return SDValue();
10858
10859   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10860   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10861   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10862
10863   if (ConstEltNo) {
10864     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10865
10866     LoadSDNode *LN0 = nullptr;
10867     const ShuffleVectorSDNode *SVN = nullptr;
10868     if (ISD::isNormalLoad(InVec.getNode())) {
10869       LN0 = cast<LoadSDNode>(InVec);
10870     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10871                InVec.getOperand(0).getValueType() == ExtVT &&
10872                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10873       // Don't duplicate a load with other uses.
10874       if (!InVec.hasOneUse())
10875         return SDValue();
10876
10877       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10878     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10879       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10880       // =>
10881       // (load $addr+1*size)
10882
10883       // Don't duplicate a load with other uses.
10884       if (!InVec.hasOneUse())
10885         return SDValue();
10886
10887       // If the bit convert changed the number of elements, it is unsafe
10888       // to examine the mask.
10889       if (BCNumEltsChanged)
10890         return SDValue();
10891
10892       // Select the input vector, guarding against out of range extract vector.
10893       unsigned NumElems = VT.getVectorNumElements();
10894       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10895       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10896
10897       if (InVec.getOpcode() == ISD::BITCAST) {
10898         // Don't duplicate a load with other uses.
10899         if (!InVec.hasOneUse())
10900           return SDValue();
10901
10902         InVec = InVec.getOperand(0);
10903       }
10904       if (ISD::isNormalLoad(InVec.getNode())) {
10905         LN0 = cast<LoadSDNode>(InVec);
10906         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10907         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10908       }
10909     }
10910
10911     // Make sure we found a non-volatile load and the extractelement is
10912     // the only use.
10913     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10914       return SDValue();
10915
10916     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10917     if (Elt == -1)
10918       return DAG.getUNDEF(LVT);
10919
10920     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10921   }
10922
10923   return SDValue();
10924 }
10925
10926 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10927 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10928   // We perform this optimization post type-legalization because
10929   // the type-legalizer often scalarizes integer-promoted vectors.
10930   // Performing this optimization before may create bit-casts which
10931   // will be type-legalized to complex code sequences.
10932   // We perform this optimization only before the operation legalizer because we
10933   // may introduce illegal operations.
10934   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10935     return SDValue();
10936
10937   unsigned NumInScalars = N->getNumOperands();
10938   SDLoc dl(N);
10939   EVT VT = N->getValueType(0);
10940
10941   // Check to see if this is a BUILD_VECTOR of a bunch of values
10942   // which come from any_extend or zero_extend nodes. If so, we can create
10943   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10944   // optimizations. We do not handle sign-extend because we can't fill the sign
10945   // using shuffles.
10946   EVT SourceType = MVT::Other;
10947   bool AllAnyExt = true;
10948
10949   for (unsigned i = 0; i != NumInScalars; ++i) {
10950     SDValue In = N->getOperand(i);
10951     // Ignore undef inputs.
10952     if (In.getOpcode() == ISD::UNDEF) continue;
10953
10954     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10955     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10956
10957     // Abort if the element is not an extension.
10958     if (!ZeroExt && !AnyExt) {
10959       SourceType = MVT::Other;
10960       break;
10961     }
10962
10963     // The input is a ZeroExt or AnyExt. Check the original type.
10964     EVT InTy = In.getOperand(0).getValueType();
10965
10966     // Check that all of the widened source types are the same.
10967     if (SourceType == MVT::Other)
10968       // First time.
10969       SourceType = InTy;
10970     else if (InTy != SourceType) {
10971       // Multiple income types. Abort.
10972       SourceType = MVT::Other;
10973       break;
10974     }
10975
10976     // Check if all of the extends are ANY_EXTENDs.
10977     AllAnyExt &= AnyExt;
10978   }
10979
10980   // In order to have valid types, all of the inputs must be extended from the
10981   // same source type and all of the inputs must be any or zero extend.
10982   // Scalar sizes must be a power of two.
10983   EVT OutScalarTy = VT.getScalarType();
10984   bool ValidTypes = SourceType != MVT::Other &&
10985                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10986                  isPowerOf2_32(SourceType.getSizeInBits());
10987
10988   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10989   // turn into a single shuffle instruction.
10990   if (!ValidTypes)
10991     return SDValue();
10992
10993   bool isLE = TLI.isLittleEndian();
10994   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10995   assert(ElemRatio > 1 && "Invalid element size ratio");
10996   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10997                                DAG.getConstant(0, SourceType);
10998
10999   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11000   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11001
11002   // Populate the new build_vector
11003   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11004     SDValue Cast = N->getOperand(i);
11005     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11006             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11007             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11008     SDValue In;
11009     if (Cast.getOpcode() == ISD::UNDEF)
11010       In = DAG.getUNDEF(SourceType);
11011     else
11012       In = Cast->getOperand(0);
11013     unsigned Index = isLE ? (i * ElemRatio) :
11014                             (i * ElemRatio + (ElemRatio - 1));
11015
11016     assert(Index < Ops.size() && "Invalid index");
11017     Ops[Index] = In;
11018   }
11019
11020   // The type of the new BUILD_VECTOR node.
11021   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11022   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11023          "Invalid vector size");
11024   // Check if the new vector type is legal.
11025   if (!isTypeLegal(VecVT)) return SDValue();
11026
11027   // Make the new BUILD_VECTOR.
11028   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11029
11030   // The new BUILD_VECTOR node has the potential to be further optimized.
11031   AddToWorklist(BV.getNode());
11032   // Bitcast to the desired type.
11033   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11034 }
11035
11036 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11037   EVT VT = N->getValueType(0);
11038
11039   unsigned NumInScalars = N->getNumOperands();
11040   SDLoc dl(N);
11041
11042   EVT SrcVT = MVT::Other;
11043   unsigned Opcode = ISD::DELETED_NODE;
11044   unsigned NumDefs = 0;
11045
11046   for (unsigned i = 0; i != NumInScalars; ++i) {
11047     SDValue In = N->getOperand(i);
11048     unsigned Opc = In.getOpcode();
11049
11050     if (Opc == ISD::UNDEF)
11051       continue;
11052
11053     // If all scalar values are floats and converted from integers.
11054     if (Opcode == ISD::DELETED_NODE &&
11055         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11056       Opcode = Opc;
11057     }
11058
11059     if (Opc != Opcode)
11060       return SDValue();
11061
11062     EVT InVT = In.getOperand(0).getValueType();
11063
11064     // If all scalar values are typed differently, bail out. It's chosen to
11065     // simplify BUILD_VECTOR of integer types.
11066     if (SrcVT == MVT::Other)
11067       SrcVT = InVT;
11068     if (SrcVT != InVT)
11069       return SDValue();
11070     NumDefs++;
11071   }
11072
11073   // If the vector has just one element defined, it's not worth to fold it into
11074   // a vectorized one.
11075   if (NumDefs < 2)
11076     return SDValue();
11077
11078   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11079          && "Should only handle conversion from integer to float.");
11080   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11081
11082   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11083
11084   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11085     return SDValue();
11086
11087   SmallVector<SDValue, 8> Opnds;
11088   for (unsigned i = 0; i != NumInScalars; ++i) {
11089     SDValue In = N->getOperand(i);
11090
11091     if (In.getOpcode() == ISD::UNDEF)
11092       Opnds.push_back(DAG.getUNDEF(SrcVT));
11093     else
11094       Opnds.push_back(In.getOperand(0));
11095   }
11096   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11097   AddToWorklist(BV.getNode());
11098
11099   return DAG.getNode(Opcode, dl, VT, BV);
11100 }
11101
11102 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11103   unsigned NumInScalars = N->getNumOperands();
11104   SDLoc dl(N);
11105   EVT VT = N->getValueType(0);
11106
11107   // A vector built entirely of undefs is undef.
11108   if (ISD::allOperandsUndef(N))
11109     return DAG.getUNDEF(VT);
11110
11111   SDValue V = reduceBuildVecExtToExtBuildVec(N);
11112   if (V.getNode())
11113     return V;
11114
11115   V = reduceBuildVecConvertToConvertBuildVec(N);
11116   if (V.getNode())
11117     return V;
11118
11119   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11120   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11121   // at most two distinct vectors, turn this into a shuffle node.
11122
11123   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11124   if (!isTypeLegal(VT))
11125     return SDValue();
11126
11127   // May only combine to shuffle after legalize if shuffle is legal.
11128   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11129     return SDValue();
11130
11131   SDValue VecIn1, VecIn2;
11132   bool UsesZeroVector = false;
11133   for (unsigned i = 0; i != NumInScalars; ++i) {
11134     SDValue Op = N->getOperand(i);
11135     // Ignore undef inputs.
11136     if (Op.getOpcode() == ISD::UNDEF) continue;
11137
11138     // See if we can combine this build_vector into a blend with a zero vector.
11139     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11140         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11141         (Op.getOpcode() == ISD::ConstantFP &&
11142         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11143       UsesZeroVector = true;
11144       continue;
11145     }
11146
11147     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11148     // constant index, bail out.
11149     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11150         !isa<ConstantSDNode>(Op.getOperand(1))) {
11151       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11152       break;
11153     }
11154
11155     // We allow up to two distinct input vectors.
11156     SDValue ExtractedFromVec = Op.getOperand(0);
11157     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11158       continue;
11159
11160     if (!VecIn1.getNode()) {
11161       VecIn1 = ExtractedFromVec;
11162     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11163       VecIn2 = ExtractedFromVec;
11164     } else {
11165       // Too many inputs.
11166       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11167       break;
11168     }
11169   }
11170
11171   // If everything is good, we can make a shuffle operation.
11172   if (VecIn1.getNode()) {
11173     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11174     SmallVector<int, 8> Mask;
11175     for (unsigned i = 0; i != NumInScalars; ++i) {
11176       unsigned Opcode = N->getOperand(i).getOpcode();
11177       if (Opcode == ISD::UNDEF) {
11178         Mask.push_back(-1);
11179         continue;
11180       }
11181
11182       // Operands can also be zero.
11183       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11184         assert(UsesZeroVector &&
11185                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11186                "Unexpected node found!");
11187         Mask.push_back(NumInScalars+i);
11188         continue;
11189       }
11190
11191       // If extracting from the first vector, just use the index directly.
11192       SDValue Extract = N->getOperand(i);
11193       SDValue ExtVal = Extract.getOperand(1);
11194       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11195       if (Extract.getOperand(0) == VecIn1) {
11196         Mask.push_back(ExtIndex);
11197         continue;
11198       }
11199
11200       // Otherwise, use InIdx + InputVecSize
11201       Mask.push_back(InNumElements + ExtIndex);
11202     }
11203
11204     // Avoid introducing illegal shuffles with zero.
11205     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11206       return SDValue();
11207
11208     // We can't generate a shuffle node with mismatched input and output types.
11209     // Attempt to transform a single input vector to the correct type.
11210     if ((VT != VecIn1.getValueType())) {
11211       // If the input vector type has a different base type to the output
11212       // vector type, bail out.
11213       EVT VTElemType = VT.getVectorElementType();
11214       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11215           (VecIn2.getNode() &&
11216            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11217         return SDValue();
11218
11219       // If the input vector is too small, widen it.
11220       // We only support widening of vectors which are half the size of the
11221       // output registers. For example XMM->YMM widening on X86 with AVX.
11222       EVT VecInT = VecIn1.getValueType();
11223       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11224         // If we only have one small input, widen it by adding undef values.
11225         if (!VecIn2.getNode())
11226           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11227                                DAG.getUNDEF(VecIn1.getValueType()));
11228         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11229           // If we have two small inputs of the same type, try to concat them.
11230           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11231           VecIn2 = SDValue(nullptr, 0);
11232         } else
11233           return SDValue();
11234       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11235         // If the input vector is too large, try to split it.
11236         // We don't support having two input vectors that are too large.
11237         if (VecIn2.getNode())
11238           return SDValue();
11239
11240         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11241           return SDValue();
11242         
11243         // Try to replace VecIn1 with two extract_subvectors
11244         // No need to update the masks, they should still be correct.
11245         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 
11246           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11247         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11248           DAG.getConstant(0, TLI.getVectorIdxTy()));
11249         UsesZeroVector = false;
11250       } else
11251         return SDValue();
11252     }
11253
11254     if (UsesZeroVector)
11255       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11256                                 DAG.getConstantFP(0.0, VT);
11257     else
11258       // If VecIn2 is unused then change it to undef.
11259       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11260
11261     // Check that we were able to transform all incoming values to the same
11262     // type.
11263     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11264         VecIn1.getValueType() != VT)
11265           return SDValue();
11266
11267     // Return the new VECTOR_SHUFFLE node.
11268     SDValue Ops[2];
11269     Ops[0] = VecIn1;
11270     Ops[1] = VecIn2;
11271     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11272   }
11273
11274   return SDValue();
11275 }
11276
11277 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11278   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11279   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11280   // inputs come from at most two distinct vectors, turn this into a shuffle
11281   // node.
11282
11283   // If we only have one input vector, we don't need to do any concatenation.
11284   if (N->getNumOperands() == 1)
11285     return N->getOperand(0);
11286
11287   // Check if all of the operands are undefs.
11288   EVT VT = N->getValueType(0);
11289   if (ISD::allOperandsUndef(N))
11290     return DAG.getUNDEF(VT);
11291
11292   // Optimize concat_vectors where one of the vectors is undef.
11293   if (N->getNumOperands() == 2 &&
11294       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11295     SDValue In = N->getOperand(0);
11296     assert(In.getValueType().isVector() && "Must concat vectors");
11297
11298     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11299     if (In->getOpcode() == ISD::BITCAST &&
11300         !In->getOperand(0)->getValueType(0).isVector()) {
11301       SDValue Scalar = In->getOperand(0);
11302       EVT SclTy = Scalar->getValueType(0);
11303
11304       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11305         return SDValue();
11306
11307       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11308                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11309       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11310         return SDValue();
11311
11312       SDLoc dl = SDLoc(N);
11313       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11314       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11315     }
11316   }
11317
11318   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11319   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11320   if (N->getNumOperands() == 2 &&
11321       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11322       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11323     EVT VT = N->getValueType(0);
11324     SDValue N0 = N->getOperand(0);
11325     SDValue N1 = N->getOperand(1);
11326     SmallVector<SDValue, 8> Opnds;
11327     unsigned BuildVecNumElts =  N0.getNumOperands();
11328
11329     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11330     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11331     if (SclTy0.isFloatingPoint()) {
11332       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11333         Opnds.push_back(N0.getOperand(i));
11334       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11335         Opnds.push_back(N1.getOperand(i));
11336     } else {
11337       // If BUILD_VECTOR are from built from integer, they may have different
11338       // operand types. Get the smaller type and truncate all operands to it.
11339       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11340       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11341         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11342                         N0.getOperand(i)));
11343       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11344         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11345                         N1.getOperand(i)));
11346     }
11347
11348     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11349   }
11350
11351   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11352   // nodes often generate nop CONCAT_VECTOR nodes.
11353   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11354   // place the incoming vectors at the exact same location.
11355   SDValue SingleSource = SDValue();
11356   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11357
11358   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11359     SDValue Op = N->getOperand(i);
11360
11361     if (Op.getOpcode() == ISD::UNDEF)
11362       continue;
11363
11364     // Check if this is the identity extract:
11365     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11366       return SDValue();
11367
11368     // Find the single incoming vector for the extract_subvector.
11369     if (SingleSource.getNode()) {
11370       if (Op.getOperand(0) != SingleSource)
11371         return SDValue();
11372     } else {
11373       SingleSource = Op.getOperand(0);
11374
11375       // Check the source type is the same as the type of the result.
11376       // If not, this concat may extend the vector, so we can not
11377       // optimize it away.
11378       if (SingleSource.getValueType() != N->getValueType(0))
11379         return SDValue();
11380     }
11381
11382     unsigned IdentityIndex = i * PartNumElem;
11383     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11384     // The extract index must be constant.
11385     if (!CS)
11386       return SDValue();
11387
11388     // Check that we are reading from the identity index.
11389     if (CS->getZExtValue() != IdentityIndex)
11390       return SDValue();
11391   }
11392
11393   if (SingleSource.getNode())
11394     return SingleSource;
11395
11396   return SDValue();
11397 }
11398
11399 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11400   EVT NVT = N->getValueType(0);
11401   SDValue V = N->getOperand(0);
11402
11403   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11404     // Combine:
11405     //    (extract_subvec (concat V1, V2, ...), i)
11406     // Into:
11407     //    Vi if possible
11408     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11409     // type.
11410     if (V->getOperand(0).getValueType() != NVT)
11411       return SDValue();
11412     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11413     unsigned NumElems = NVT.getVectorNumElements();
11414     assert((Idx % NumElems) == 0 &&
11415            "IDX in concat is not a multiple of the result vector length.");
11416     return V->getOperand(Idx / NumElems);
11417   }
11418
11419   // Skip bitcasting
11420   if (V->getOpcode() == ISD::BITCAST)
11421     V = V.getOperand(0);
11422
11423   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11424     SDLoc dl(N);
11425     // Handle only simple case where vector being inserted and vector
11426     // being extracted are of same type, and are half size of larger vectors.
11427     EVT BigVT = V->getOperand(0).getValueType();
11428     EVT SmallVT = V->getOperand(1).getValueType();
11429     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11430       return SDValue();
11431
11432     // Only handle cases where both indexes are constants with the same type.
11433     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11434     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11435
11436     if (InsIdx && ExtIdx &&
11437         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11438         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11439       // Combine:
11440       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11441       // Into:
11442       //    indices are equal or bit offsets are equal => V1
11443       //    otherwise => (extract_subvec V1, ExtIdx)
11444       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11445           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11446         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11447       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11448                          DAG.getNode(ISD::BITCAST, dl,
11449                                      N->getOperand(0).getValueType(),
11450                                      V->getOperand(0)), N->getOperand(1));
11451     }
11452   }
11453
11454   return SDValue();
11455 }
11456
11457 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11458                                                  SDValue V, SelectionDAG &DAG) {
11459   SDLoc DL(V);
11460   EVT VT = V.getValueType();
11461
11462   switch (V.getOpcode()) {
11463   default:
11464     return V;
11465
11466   case ISD::CONCAT_VECTORS: {
11467     EVT OpVT = V->getOperand(0).getValueType();
11468     int OpSize = OpVT.getVectorNumElements();
11469     SmallBitVector OpUsedElements(OpSize, false);
11470     bool FoundSimplification = false;
11471     SmallVector<SDValue, 4> NewOps;
11472     NewOps.reserve(V->getNumOperands());
11473     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11474       SDValue Op = V->getOperand(i);
11475       bool OpUsed = false;
11476       for (int j = 0; j < OpSize; ++j)
11477         if (UsedElements[i * OpSize + j]) {
11478           OpUsedElements[j] = true;
11479           OpUsed = true;
11480         }
11481       NewOps.push_back(
11482           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11483                  : DAG.getUNDEF(OpVT));
11484       FoundSimplification |= Op == NewOps.back();
11485       OpUsedElements.reset();
11486     }
11487     if (FoundSimplification)
11488       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11489     return V;
11490   }
11491
11492   case ISD::INSERT_SUBVECTOR: {
11493     SDValue BaseV = V->getOperand(0);
11494     SDValue SubV = V->getOperand(1);
11495     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11496     if (!IdxN)
11497       return V;
11498
11499     int SubSize = SubV.getValueType().getVectorNumElements();
11500     int Idx = IdxN->getZExtValue();
11501     bool SubVectorUsed = false;
11502     SmallBitVector SubUsedElements(SubSize, false);
11503     for (int i = 0; i < SubSize; ++i)
11504       if (UsedElements[i + Idx]) {
11505         SubVectorUsed = true;
11506         SubUsedElements[i] = true;
11507         UsedElements[i + Idx] = false;
11508       }
11509
11510     // Now recurse on both the base and sub vectors.
11511     SDValue SimplifiedSubV =
11512         SubVectorUsed
11513             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11514             : DAG.getUNDEF(SubV.getValueType());
11515     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11516     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11517       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11518                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11519     return V;
11520   }
11521   }
11522 }
11523
11524 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11525                                        SDValue N1, SelectionDAG &DAG) {
11526   EVT VT = SVN->getValueType(0);
11527   int NumElts = VT.getVectorNumElements();
11528   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11529   for (int M : SVN->getMask())
11530     if (M >= 0 && M < NumElts)
11531       N0UsedElements[M] = true;
11532     else if (M >= NumElts)
11533       N1UsedElements[M - NumElts] = true;
11534
11535   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11536   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11537   if (S0 == N0 && S1 == N1)
11538     return SDValue();
11539
11540   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11541 }
11542
11543 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11544 // or turn a shuffle of a single concat into simpler shuffle then concat.
11545 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11546   EVT VT = N->getValueType(0);
11547   unsigned NumElts = VT.getVectorNumElements();
11548
11549   SDValue N0 = N->getOperand(0);
11550   SDValue N1 = N->getOperand(1);
11551   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11552
11553   SmallVector<SDValue, 4> Ops;
11554   EVT ConcatVT = N0.getOperand(0).getValueType();
11555   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11556   unsigned NumConcats = NumElts / NumElemsPerConcat;
11557
11558   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11559   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11560   // half vector elements.
11561   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11562       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11563                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11564     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11565                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11566     N1 = DAG.getUNDEF(ConcatVT);
11567     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11568   }
11569
11570   // Look at every vector that's inserted. We're looking for exact
11571   // subvector-sized copies from a concatenated vector
11572   for (unsigned I = 0; I != NumConcats; ++I) {
11573     // Make sure we're dealing with a copy.
11574     unsigned Begin = I * NumElemsPerConcat;
11575     bool AllUndef = true, NoUndef = true;
11576     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11577       if (SVN->getMaskElt(J) >= 0)
11578         AllUndef = false;
11579       else
11580         NoUndef = false;
11581     }
11582
11583     if (NoUndef) {
11584       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11585         return SDValue();
11586
11587       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11588         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11589           return SDValue();
11590
11591       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11592       if (FirstElt < N0.getNumOperands())
11593         Ops.push_back(N0.getOperand(FirstElt));
11594       else
11595         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11596
11597     } else if (AllUndef) {
11598       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11599     } else { // Mixed with general masks and undefs, can't do optimization.
11600       return SDValue();
11601     }
11602   }
11603
11604   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11605 }
11606
11607 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11608   EVT VT = N->getValueType(0);
11609   unsigned NumElts = VT.getVectorNumElements();
11610
11611   SDValue N0 = N->getOperand(0);
11612   SDValue N1 = N->getOperand(1);
11613
11614   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11615
11616   // Canonicalize shuffle undef, undef -> undef
11617   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11618     return DAG.getUNDEF(VT);
11619
11620   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11621
11622   // Canonicalize shuffle v, v -> v, undef
11623   if (N0 == N1) {
11624     SmallVector<int, 8> NewMask;
11625     for (unsigned i = 0; i != NumElts; ++i) {
11626       int Idx = SVN->getMaskElt(i);
11627       if (Idx >= (int)NumElts) Idx -= NumElts;
11628       NewMask.push_back(Idx);
11629     }
11630     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11631                                 &NewMask[0]);
11632   }
11633
11634   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11635   if (N0.getOpcode() == ISD::UNDEF) {
11636     SmallVector<int, 8> NewMask;
11637     for (unsigned i = 0; i != NumElts; ++i) {
11638       int Idx = SVN->getMaskElt(i);
11639       if (Idx >= 0) {
11640         if (Idx >= (int)NumElts)
11641           Idx -= NumElts;
11642         else
11643           Idx = -1; // remove reference to lhs
11644       }
11645       NewMask.push_back(Idx);
11646     }
11647     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11648                                 &NewMask[0]);
11649   }
11650
11651   // Remove references to rhs if it is undef
11652   if (N1.getOpcode() == ISD::UNDEF) {
11653     bool Changed = false;
11654     SmallVector<int, 8> NewMask;
11655     for (unsigned i = 0; i != NumElts; ++i) {
11656       int Idx = SVN->getMaskElt(i);
11657       if (Idx >= (int)NumElts) {
11658         Idx = -1;
11659         Changed = true;
11660       }
11661       NewMask.push_back(Idx);
11662     }
11663     if (Changed)
11664       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11665   }
11666
11667   // If it is a splat, check if the argument vector is another splat or a
11668   // build_vector.
11669   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11670     SDNode *V = N0.getNode();
11671
11672     // If this is a bit convert that changes the element type of the vector but
11673     // not the number of vector elements, look through it.  Be careful not to
11674     // look though conversions that change things like v4f32 to v2f64.
11675     if (V->getOpcode() == ISD::BITCAST) {
11676       SDValue ConvInput = V->getOperand(0);
11677       if (ConvInput.getValueType().isVector() &&
11678           ConvInput.getValueType().getVectorNumElements() == NumElts)
11679         V = ConvInput.getNode();
11680     }
11681
11682     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11683       assert(V->getNumOperands() == NumElts &&
11684              "BUILD_VECTOR has wrong number of operands");
11685       SDValue Base;
11686       bool AllSame = true;
11687       for (unsigned i = 0; i != NumElts; ++i) {
11688         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11689           Base = V->getOperand(i);
11690           break;
11691         }
11692       }
11693       // Splat of <u, u, u, u>, return <u, u, u, u>
11694       if (!Base.getNode())
11695         return N0;
11696       for (unsigned i = 0; i != NumElts; ++i) {
11697         if (V->getOperand(i) != Base) {
11698           AllSame = false;
11699           break;
11700         }
11701       }
11702       // Splat of <x, x, x, x>, return <x, x, x, x>
11703       if (AllSame)
11704         return N0;
11705
11706       // If the splatted element is a constant, just build the vector out of
11707       // constants directly.
11708       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11709       if (isa<ConstantSDNode>(Splatted) || isa<ConstantFPSDNode>(Splatted)) {
11710         SmallVector<SDValue, 8> Ops;
11711         for (unsigned i = 0; i != NumElts; ++i) {
11712           Ops.push_back(Splatted);
11713         }
11714         SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11715           V->getValueType(0), Ops);
11716
11717         // We may have jumped through bitcasts, so the type of the
11718         // BUILD_VECTOR may not match the type of the shuffle.
11719         if (V->getValueType(0) != VT)
11720            NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11721         return NewBV;
11722       }
11723     }
11724   }
11725
11726   // There are various patterns used to build up a vector from smaller vectors,
11727   // subvectors, or elements. Scan chains of these and replace unused insertions
11728   // or components with undef.
11729   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11730     return S;
11731
11732   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11733       Level < AfterLegalizeVectorOps &&
11734       (N1.getOpcode() == ISD::UNDEF ||
11735       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11736        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11737     SDValue V = partitionShuffleOfConcats(N, DAG);
11738
11739     if (V.getNode())
11740       return V;
11741   }
11742
11743   // Canonicalize shuffles according to rules:
11744   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11745   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11746   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11747   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11748       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11749       TLI.isTypeLegal(VT)) {
11750     // The incoming shuffle must be of the same type as the result of the
11751     // current shuffle.
11752     assert(N1->getOperand(0).getValueType() == VT &&
11753            "Shuffle types don't match");
11754
11755     SDValue SV0 = N1->getOperand(0);
11756     SDValue SV1 = N1->getOperand(1);
11757     bool HasSameOp0 = N0 == SV0;
11758     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11759     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11760       // Commute the operands of this shuffle so that next rule
11761       // will trigger.
11762       return DAG.getCommutedVectorShuffle(*SVN);
11763   }
11764
11765   // Try to fold according to rules:
11766   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11767   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11768   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11769   // Don't try to fold shuffles with illegal type.
11770   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11771       TLI.isTypeLegal(VT)) {
11772     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11773
11774     // The incoming shuffle must be of the same type as the result of the
11775     // current shuffle.
11776     assert(OtherSV->getOperand(0).getValueType() == VT &&
11777            "Shuffle types don't match");
11778
11779     SDValue SV0, SV1;
11780     SmallVector<int, 4> Mask;
11781     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11782     // operand, and SV1 as the second operand.
11783     for (unsigned i = 0; i != NumElts; ++i) {
11784       int Idx = SVN->getMaskElt(i);
11785       if (Idx < 0) {
11786         // Propagate Undef.
11787         Mask.push_back(Idx);
11788         continue;
11789       }
11790
11791       SDValue CurrentVec;
11792       if (Idx < (int)NumElts) {
11793         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11794         // shuffle mask to identify which vector is actually referenced.
11795         Idx = OtherSV->getMaskElt(Idx);
11796         if (Idx < 0) {
11797           // Propagate Undef.
11798           Mask.push_back(Idx);
11799           continue;
11800         }
11801
11802         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11803                                            : OtherSV->getOperand(1);
11804       } else {
11805         // This shuffle index references an element within N1.
11806         CurrentVec = N1;
11807       }
11808
11809       // Simple case where 'CurrentVec' is UNDEF.
11810       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11811         Mask.push_back(-1);
11812         continue;
11813       }
11814
11815       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11816       // will be the first or second operand of the combined shuffle.
11817       Idx = Idx % NumElts;
11818       if (!SV0.getNode() || SV0 == CurrentVec) {
11819         // Ok. CurrentVec is the left hand side.
11820         // Update the mask accordingly.
11821         SV0 = CurrentVec;
11822         Mask.push_back(Idx);
11823         continue;
11824       }
11825
11826       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11827       if (SV1.getNode() && SV1 != CurrentVec)
11828         return SDValue();
11829
11830       // Ok. CurrentVec is the right hand side.
11831       // Update the mask accordingly.
11832       SV1 = CurrentVec;
11833       Mask.push_back(Idx + NumElts);
11834     }
11835
11836     // Check if all indices in Mask are Undef. In case, propagate Undef.
11837     bool isUndefMask = true;
11838     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11839       isUndefMask &= Mask[i] < 0;
11840
11841     if (isUndefMask)
11842       return DAG.getUNDEF(VT);
11843
11844     if (!SV0.getNode())
11845       SV0 = DAG.getUNDEF(VT);
11846     if (!SV1.getNode())
11847       SV1 = DAG.getUNDEF(VT);
11848
11849     // Avoid introducing shuffles with illegal mask.
11850     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11851       // Compute the commuted shuffle mask and test again.
11852       for (unsigned i = 0; i != NumElts; ++i) {
11853         int idx = Mask[i];
11854         if (idx < 0)
11855           continue;
11856         else if (idx < (int)NumElts)
11857           Mask[i] = idx + NumElts;
11858         else
11859           Mask[i] = idx - NumElts;
11860       }
11861
11862       if (!TLI.isShuffleMaskLegal(Mask, VT))
11863         return SDValue();
11864  
11865       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11866       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11867       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11868       std::swap(SV0, SV1);
11869     }
11870
11871     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11872     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11873     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11874     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11875   }
11876
11877   return SDValue();
11878 }
11879
11880 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11881   SDValue N0 = N->getOperand(0);
11882   SDValue N2 = N->getOperand(2);
11883
11884   // If the input vector is a concatenation, and the insert replaces
11885   // one of the halves, we can optimize into a single concat_vectors.
11886   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11887       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11888     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11889     EVT VT = N->getValueType(0);
11890
11891     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11892     // (concat_vectors Z, Y)
11893     if (InsIdx == 0)
11894       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11895                          N->getOperand(1), N0.getOperand(1));
11896
11897     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11898     // (concat_vectors X, Z)
11899     if (InsIdx == VT.getVectorNumElements()/2)
11900       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11901                          N0.getOperand(0), N->getOperand(1));
11902   }
11903
11904   return SDValue();
11905 }
11906
11907 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11908 /// with the destination vector and a zero vector.
11909 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11910 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11911 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11912   EVT VT = N->getValueType(0);
11913   SDLoc dl(N);
11914   SDValue LHS = N->getOperand(0);
11915   SDValue RHS = N->getOperand(1);
11916   if (N->getOpcode() == ISD::AND) {
11917     if (RHS.getOpcode() == ISD::BITCAST)
11918       RHS = RHS.getOperand(0);
11919     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11920       SmallVector<int, 8> Indices;
11921       unsigned NumElts = RHS.getNumOperands();
11922       for (unsigned i = 0; i != NumElts; ++i) {
11923         SDValue Elt = RHS.getOperand(i);
11924         if (!isa<ConstantSDNode>(Elt))
11925           return SDValue();
11926
11927         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11928           Indices.push_back(i);
11929         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11930           Indices.push_back(NumElts+i);
11931         else
11932           return SDValue();
11933       }
11934
11935       // Let's see if the target supports this vector_shuffle.
11936       EVT RVT = RHS.getValueType();
11937       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11938         return SDValue();
11939
11940       // Return the new VECTOR_SHUFFLE node.
11941       EVT EltVT = RVT.getVectorElementType();
11942       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11943                                      DAG.getConstant(0, EltVT));
11944       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11945       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11946       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11947       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11948     }
11949   }
11950
11951   return SDValue();
11952 }
11953
11954 /// Visit a binary vector operation, like ADD.
11955 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11956   assert(N->getValueType(0).isVector() &&
11957          "SimplifyVBinOp only works on vectors!");
11958
11959   SDValue LHS = N->getOperand(0);
11960   SDValue RHS = N->getOperand(1);
11961   SDValue Shuffle = XformToShuffleWithZero(N);
11962   if (Shuffle.getNode()) return Shuffle;
11963
11964   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11965   // this operation.
11966   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11967       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11968     // Check if both vectors are constants. If not bail out.
11969     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11970           cast<BuildVectorSDNode>(RHS)->isConstant()))
11971       return SDValue();
11972
11973     SmallVector<SDValue, 8> Ops;
11974     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11975       SDValue LHSOp = LHS.getOperand(i);
11976       SDValue RHSOp = RHS.getOperand(i);
11977
11978       // Can't fold divide by zero.
11979       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11980           N->getOpcode() == ISD::FDIV) {
11981         if ((RHSOp.getOpcode() == ISD::Constant &&
11982              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11983             (RHSOp.getOpcode() == ISD::ConstantFP &&
11984              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11985           break;
11986       }
11987
11988       EVT VT = LHSOp.getValueType();
11989       EVT RVT = RHSOp.getValueType();
11990       if (RVT != VT) {
11991         // Integer BUILD_VECTOR operands may have types larger than the element
11992         // size (e.g., when the element type is not legal).  Prior to type
11993         // legalization, the types may not match between the two BUILD_VECTORS.
11994         // Truncate one of the operands to make them match.
11995         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11996           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11997         } else {
11998           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11999           VT = RVT;
12000         }
12001       }
12002       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12003                                    LHSOp, RHSOp);
12004       if (FoldOp.getOpcode() != ISD::UNDEF &&
12005           FoldOp.getOpcode() != ISD::Constant &&
12006           FoldOp.getOpcode() != ISD::ConstantFP)
12007         break;
12008       Ops.push_back(FoldOp);
12009       AddToWorklist(FoldOp.getNode());
12010     }
12011
12012     if (Ops.size() == LHS.getNumOperands())
12013       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12014   }
12015
12016   // Type legalization might introduce new shuffles in the DAG.
12017   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12018   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12019   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12020       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12021       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12022       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12023     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12024     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12025
12026     if (SVN0->getMask().equals(SVN1->getMask())) {
12027       EVT VT = N->getValueType(0);
12028       SDValue UndefVector = LHS.getOperand(1);
12029       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12030                                      LHS.getOperand(0), RHS.getOperand(0));
12031       AddUsersToWorklist(N);
12032       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12033                                   &SVN0->getMask()[0]);
12034     }
12035   }
12036
12037   return SDValue();
12038 }
12039
12040 /// Visit a binary vector operation, like FABS/FNEG.
12041 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
12042   assert(N->getValueType(0).isVector() &&
12043          "SimplifyVUnaryOp only works on vectors!");
12044
12045   SDValue N0 = N->getOperand(0);
12046
12047   if (N0.getOpcode() != ISD::BUILD_VECTOR)
12048     return SDValue();
12049
12050   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12051   SmallVector<SDValue, 8> Ops;
12052   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12053     SDValue Op = N0.getOperand(i);
12054     if (Op.getOpcode() != ISD::UNDEF &&
12055         Op.getOpcode() != ISD::ConstantFP)
12056       break;
12057     EVT EltVT = Op.getValueType();
12058     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
12059     if (FoldOp.getOpcode() != ISD::UNDEF &&
12060         FoldOp.getOpcode() != ISD::ConstantFP)
12061       break;
12062     Ops.push_back(FoldOp);
12063     AddToWorklist(FoldOp.getNode());
12064   }
12065
12066   if (Ops.size() != N0.getNumOperands())
12067     return SDValue();
12068
12069   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
12070 }
12071
12072 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12073                                     SDValue N1, SDValue N2){
12074   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12075
12076   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12077                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12078
12079   // If we got a simplified select_cc node back from SimplifySelectCC, then
12080   // break it down into a new SETCC node, and a new SELECT node, and then return
12081   // the SELECT node, since we were called with a SELECT node.
12082   if (SCC.getNode()) {
12083     // Check to see if we got a select_cc back (to turn into setcc/select).
12084     // Otherwise, just return whatever node we got back, like fabs.
12085     if (SCC.getOpcode() == ISD::SELECT_CC) {
12086       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12087                                   N0.getValueType(),
12088                                   SCC.getOperand(0), SCC.getOperand(1),
12089                                   SCC.getOperand(4));
12090       AddToWorklist(SETCC.getNode());
12091       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12092                            SCC.getOperand(2), SCC.getOperand(3));
12093     }
12094
12095     return SCC;
12096   }
12097   return SDValue();
12098 }
12099
12100 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12101 /// being selected between, see if we can simplify the select.  Callers of this
12102 /// should assume that TheSelect is deleted if this returns true.  As such, they
12103 /// should return the appropriate thing (e.g. the node) back to the top-level of
12104 /// the DAG combiner loop to avoid it being looked at.
12105 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12106                                     SDValue RHS) {
12107
12108   // Cannot simplify select with vector condition
12109   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12110
12111   // If this is a select from two identical things, try to pull the operation
12112   // through the select.
12113   if (LHS.getOpcode() != RHS.getOpcode() ||
12114       !LHS.hasOneUse() || !RHS.hasOneUse())
12115     return false;
12116
12117   // If this is a load and the token chain is identical, replace the select
12118   // of two loads with a load through a select of the address to load from.
12119   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12120   // constants have been dropped into the constant pool.
12121   if (LHS.getOpcode() == ISD::LOAD) {
12122     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12123     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12124
12125     // Token chains must be identical.
12126     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12127         // Do not let this transformation reduce the number of volatile loads.
12128         LLD->isVolatile() || RLD->isVolatile() ||
12129         // If this is an EXTLOAD, the VT's must match.
12130         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12131         // If this is an EXTLOAD, the kind of extension must match.
12132         (LLD->getExtensionType() != RLD->getExtensionType() &&
12133          // The only exception is if one of the extensions is anyext.
12134          LLD->getExtensionType() != ISD::EXTLOAD &&
12135          RLD->getExtensionType() != ISD::EXTLOAD) ||
12136         // FIXME: this discards src value information.  This is
12137         // over-conservative. It would be beneficial to be able to remember
12138         // both potential memory locations.  Since we are discarding
12139         // src value info, don't do the transformation if the memory
12140         // locations are not in the default address space.
12141         LLD->getPointerInfo().getAddrSpace() != 0 ||
12142         RLD->getPointerInfo().getAddrSpace() != 0 ||
12143         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12144                                       LLD->getBasePtr().getValueType()))
12145       return false;
12146
12147     // Check that the select condition doesn't reach either load.  If so,
12148     // folding this will induce a cycle into the DAG.  If not, this is safe to
12149     // xform, so create a select of the addresses.
12150     SDValue Addr;
12151     if (TheSelect->getOpcode() == ISD::SELECT) {
12152       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12153       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12154           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12155         return false;
12156       // The loads must not depend on one another.
12157       if (LLD->isPredecessorOf(RLD) ||
12158           RLD->isPredecessorOf(LLD))
12159         return false;
12160       Addr = DAG.getSelect(SDLoc(TheSelect),
12161                            LLD->getBasePtr().getValueType(),
12162                            TheSelect->getOperand(0), LLD->getBasePtr(),
12163                            RLD->getBasePtr());
12164     } else {  // Otherwise SELECT_CC
12165       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12166       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12167
12168       if ((LLD->hasAnyUseOfValue(1) &&
12169            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12170           (RLD->hasAnyUseOfValue(1) &&
12171            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12172         return false;
12173
12174       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12175                          LLD->getBasePtr().getValueType(),
12176                          TheSelect->getOperand(0),
12177                          TheSelect->getOperand(1),
12178                          LLD->getBasePtr(), RLD->getBasePtr(),
12179                          TheSelect->getOperand(4));
12180     }
12181
12182     SDValue Load;
12183     // It is safe to replace the two loads if they have different alignments,
12184     // but the new load must be the minimum (most restrictive) alignment of the
12185     // inputs.
12186     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12187     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12188     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12189       Load = DAG.getLoad(TheSelect->getValueType(0),
12190                          SDLoc(TheSelect),
12191                          // FIXME: Discards pointer and AA info.
12192                          LLD->getChain(), Addr, MachinePointerInfo(),
12193                          LLD->isVolatile(), LLD->isNonTemporal(),
12194                          isInvariant, Alignment);
12195     } else {
12196       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12197                             RLD->getExtensionType() : LLD->getExtensionType(),
12198                             SDLoc(TheSelect),
12199                             TheSelect->getValueType(0),
12200                             // FIXME: Discards pointer and AA info.
12201                             LLD->getChain(), Addr, MachinePointerInfo(),
12202                             LLD->getMemoryVT(), LLD->isVolatile(),
12203                             LLD->isNonTemporal(), isInvariant, Alignment);
12204     }
12205
12206     // Users of the select now use the result of the load.
12207     CombineTo(TheSelect, Load);
12208
12209     // Users of the old loads now use the new load's chain.  We know the
12210     // old-load value is dead now.
12211     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12212     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12213     return true;
12214   }
12215
12216   return false;
12217 }
12218
12219 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12220 /// where 'cond' is the comparison specified by CC.
12221 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12222                                       SDValue N2, SDValue N3,
12223                                       ISD::CondCode CC, bool NotExtCompare) {
12224   // (x ? y : y) -> y.
12225   if (N2 == N3) return N2;
12226
12227   EVT VT = N2.getValueType();
12228   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12229   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12230   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12231
12232   // Determine if the condition we're dealing with is constant
12233   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12234                               N0, N1, CC, DL, false);
12235   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12236   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12237
12238   // fold select_cc true, x, y -> x
12239   if (SCCC && !SCCC->isNullValue())
12240     return N2;
12241   // fold select_cc false, x, y -> y
12242   if (SCCC && SCCC->isNullValue())
12243     return N3;
12244
12245   // Check to see if we can simplify the select into an fabs node
12246   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12247     // Allow either -0.0 or 0.0
12248     if (CFP->getValueAPF().isZero()) {
12249       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12250       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12251           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12252           N2 == N3.getOperand(0))
12253         return DAG.getNode(ISD::FABS, DL, VT, N0);
12254
12255       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12256       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12257           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12258           N2.getOperand(0) == N3)
12259         return DAG.getNode(ISD::FABS, DL, VT, N3);
12260     }
12261   }
12262
12263   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12264   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12265   // in it.  This is a win when the constant is not otherwise available because
12266   // it replaces two constant pool loads with one.  We only do this if the FP
12267   // type is known to be legal, because if it isn't, then we are before legalize
12268   // types an we want the other legalization to happen first (e.g. to avoid
12269   // messing with soft float) and if the ConstantFP is not legal, because if
12270   // it is legal, we may not need to store the FP constant in a constant pool.
12271   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12272     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12273       if (TLI.isTypeLegal(N2.getValueType()) &&
12274           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12275                TargetLowering::Legal &&
12276            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12277            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12278           // If both constants have multiple uses, then we won't need to do an
12279           // extra load, they are likely around in registers for other users.
12280           (TV->hasOneUse() || FV->hasOneUse())) {
12281         Constant *Elts[] = {
12282           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12283           const_cast<ConstantFP*>(TV->getConstantFPValue())
12284         };
12285         Type *FPTy = Elts[0]->getType();
12286         const DataLayout &TD = *TLI.getDataLayout();
12287
12288         // Create a ConstantArray of the two constants.
12289         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12290         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12291                                             TD.getPrefTypeAlignment(FPTy));
12292         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12293
12294         // Get the offsets to the 0 and 1 element of the array so that we can
12295         // select between them.
12296         SDValue Zero = DAG.getIntPtrConstant(0);
12297         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12298         SDValue One = DAG.getIntPtrConstant(EltSize);
12299
12300         SDValue Cond = DAG.getSetCC(DL,
12301                                     getSetCCResultType(N0.getValueType()),
12302                                     N0, N1, CC);
12303         AddToWorklist(Cond.getNode());
12304         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12305                                           Cond, One, Zero);
12306         AddToWorklist(CstOffset.getNode());
12307         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12308                             CstOffset);
12309         AddToWorklist(CPIdx.getNode());
12310         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12311                            MachinePointerInfo::getConstantPool(), false,
12312                            false, false, Alignment);
12313
12314       }
12315     }
12316
12317   // Check to see if we can perform the "gzip trick", transforming
12318   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12319   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12320       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12321        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12322     EVT XType = N0.getValueType();
12323     EVT AType = N2.getValueType();
12324     if (XType.bitsGE(AType)) {
12325       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12326       // single-bit constant.
12327       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12328         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12329         ShCtV = XType.getSizeInBits()-ShCtV-1;
12330         SDValue ShCt = DAG.getConstant(ShCtV,
12331                                        getShiftAmountTy(N0.getValueType()));
12332         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12333                                     XType, N0, ShCt);
12334         AddToWorklist(Shift.getNode());
12335
12336         if (XType.bitsGT(AType)) {
12337           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12338           AddToWorklist(Shift.getNode());
12339         }
12340
12341         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12342       }
12343
12344       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12345                                   XType, N0,
12346                                   DAG.getConstant(XType.getSizeInBits()-1,
12347                                          getShiftAmountTy(N0.getValueType())));
12348       AddToWorklist(Shift.getNode());
12349
12350       if (XType.bitsGT(AType)) {
12351         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12352         AddToWorklist(Shift.getNode());
12353       }
12354
12355       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12356     }
12357   }
12358
12359   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12360   // where y is has a single bit set.
12361   // A plaintext description would be, we can turn the SELECT_CC into an AND
12362   // when the condition can be materialized as an all-ones register.  Any
12363   // single bit-test can be materialized as an all-ones register with
12364   // shift-left and shift-right-arith.
12365   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12366       N0->getValueType(0) == VT &&
12367       N1C && N1C->isNullValue() &&
12368       N2C && N2C->isNullValue()) {
12369     SDValue AndLHS = N0->getOperand(0);
12370     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12371     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12372       // Shift the tested bit over the sign bit.
12373       APInt AndMask = ConstAndRHS->getAPIntValue();
12374       SDValue ShlAmt =
12375         DAG.getConstant(AndMask.countLeadingZeros(),
12376                         getShiftAmountTy(AndLHS.getValueType()));
12377       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12378
12379       // Now arithmetic right shift it all the way over, so the result is either
12380       // all-ones, or zero.
12381       SDValue ShrAmt =
12382         DAG.getConstant(AndMask.getBitWidth()-1,
12383                         getShiftAmountTy(Shl.getValueType()));
12384       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12385
12386       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12387     }
12388   }
12389
12390   // fold select C, 16, 0 -> shl C, 4
12391   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12392       TLI.getBooleanContents(N0.getValueType()) ==
12393           TargetLowering::ZeroOrOneBooleanContent) {
12394
12395     // If the caller doesn't want us to simplify this into a zext of a compare,
12396     // don't do it.
12397     if (NotExtCompare && N2C->getAPIntValue() == 1)
12398       return SDValue();
12399
12400     // Get a SetCC of the condition
12401     // NOTE: Don't create a SETCC if it's not legal on this target.
12402     if (!LegalOperations ||
12403         TLI.isOperationLegal(ISD::SETCC,
12404           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12405       SDValue Temp, SCC;
12406       // cast from setcc result type to select result type
12407       if (LegalTypes) {
12408         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12409                             N0, N1, CC);
12410         if (N2.getValueType().bitsLT(SCC.getValueType()))
12411           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12412                                         N2.getValueType());
12413         else
12414           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12415                              N2.getValueType(), SCC);
12416       } else {
12417         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12418         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12419                            N2.getValueType(), SCC);
12420       }
12421
12422       AddToWorklist(SCC.getNode());
12423       AddToWorklist(Temp.getNode());
12424
12425       if (N2C->getAPIntValue() == 1)
12426         return Temp;
12427
12428       // shl setcc result by log2 n2c
12429       return DAG.getNode(
12430           ISD::SHL, DL, N2.getValueType(), Temp,
12431           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12432                           getShiftAmountTy(Temp.getValueType())));
12433     }
12434   }
12435
12436   // Check to see if this is the equivalent of setcc
12437   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12438   // otherwise, go ahead with the folds.
12439   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12440     EVT XType = N0.getValueType();
12441     if (!LegalOperations ||
12442         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12443       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12444       if (Res.getValueType() != VT)
12445         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12446       return Res;
12447     }
12448
12449     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12450     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12451         (!LegalOperations ||
12452          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12453       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12454       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12455                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12456                                        getShiftAmountTy(Ctlz.getValueType())));
12457     }
12458     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12459     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12460       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12461                                   XType, DAG.getConstant(0, XType), N0);
12462       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12463       return DAG.getNode(ISD::SRL, DL, XType,
12464                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12465                          DAG.getConstant(XType.getSizeInBits()-1,
12466                                          getShiftAmountTy(XType)));
12467     }
12468     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12469     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12470       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12471                                  DAG.getConstant(XType.getSizeInBits()-1,
12472                                          getShiftAmountTy(N0.getValueType())));
12473       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12474     }
12475   }
12476
12477   // Check to see if this is an integer abs.
12478   // select_cc setg[te] X,  0,  X, -X ->
12479   // select_cc setgt    X, -1,  X, -X ->
12480   // select_cc setl[te] X,  0, -X,  X ->
12481   // select_cc setlt    X,  1, -X,  X ->
12482   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12483   if (N1C) {
12484     ConstantSDNode *SubC = nullptr;
12485     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12486          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12487         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12488       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12489     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12490               (N1C->isOne() && CC == ISD::SETLT)) &&
12491              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12492       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12493
12494     EVT XType = N0.getValueType();
12495     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12496       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12497                                   N0,
12498                                   DAG.getConstant(XType.getSizeInBits()-1,
12499                                          getShiftAmountTy(N0.getValueType())));
12500       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12501                                 XType, N0, Shift);
12502       AddToWorklist(Shift.getNode());
12503       AddToWorklist(Add.getNode());
12504       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12505     }
12506   }
12507
12508   return SDValue();
12509 }
12510
12511 /// This is a stub for TargetLowering::SimplifySetCC.
12512 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12513                                    SDValue N1, ISD::CondCode Cond,
12514                                    SDLoc DL, bool foldBooleans) {
12515   TargetLowering::DAGCombinerInfo
12516     DagCombineInfo(DAG, Level, false, this);
12517   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12518 }
12519
12520 /// Given an ISD::SDIV node expressing a divide by constant, return
12521 /// a DAG expression to select that will generate the same value by multiplying
12522 /// by a magic number.
12523 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12524 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12525   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12526   if (!C)
12527     return SDValue();
12528
12529   // Avoid division by zero.
12530   if (!C->getAPIntValue())
12531     return SDValue();
12532
12533   std::vector<SDNode*> Built;
12534   SDValue S =
12535       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12536
12537   for (SDNode *N : Built)
12538     AddToWorklist(N);
12539   return S;
12540 }
12541
12542 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12543 /// DAG expression that will generate the same value by right shifting.
12544 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12545   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12546   if (!C)
12547     return SDValue();
12548
12549   // Avoid division by zero.
12550   if (!C->getAPIntValue())
12551     return SDValue();
12552
12553   std::vector<SDNode *> Built;
12554   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12555
12556   for (SDNode *N : Built)
12557     AddToWorklist(N);
12558   return S;
12559 }
12560
12561 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12562 /// expression that will generate the same value by multiplying by a magic
12563 /// number.
12564 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12565 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12566   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12567   if (!C)
12568     return SDValue();
12569
12570   // Avoid division by zero.
12571   if (!C->getAPIntValue())
12572     return SDValue();
12573
12574   std::vector<SDNode*> Built;
12575   SDValue S =
12576       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12577
12578   for (SDNode *N : Built)
12579     AddToWorklist(N);
12580   return S;
12581 }
12582
12583 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12584   if (Level >= AfterLegalizeDAG)
12585     return SDValue();
12586
12587   // Expose the DAG combiner to the target combiner implementations.
12588   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12589
12590   unsigned Iterations = 0;
12591   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12592     if (Iterations) {
12593       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12594       // For the reciprocal, we need to find the zero of the function:
12595       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12596       //     =>
12597       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12598       //     does not require additional intermediate precision]
12599       EVT VT = Op.getValueType();
12600       SDLoc DL(Op);
12601       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12602
12603       AddToWorklist(Est.getNode());
12604
12605       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12606       for (unsigned i = 0; i < Iterations; ++i) {
12607         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12608         AddToWorklist(NewEst.getNode());
12609
12610         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12611         AddToWorklist(NewEst.getNode());
12612
12613         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12614         AddToWorklist(NewEst.getNode());
12615
12616         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12617         AddToWorklist(Est.getNode());
12618       }
12619     }
12620     return Est;
12621   }
12622
12623   return SDValue();
12624 }
12625
12626 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12627 /// For the reciprocal sqrt, we need to find the zero of the function:
12628 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12629 ///     =>
12630 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12631 /// As a result, we precompute A/2 prior to the iteration loop.
12632 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12633                                           unsigned Iterations) {
12634   EVT VT = Arg.getValueType();
12635   SDLoc DL(Arg);
12636   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12637
12638   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12639   // this entire sequence requires only one FP constant.
12640   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12641   AddToWorklist(HalfArg.getNode());
12642
12643   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12644   AddToWorklist(HalfArg.getNode());
12645
12646   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12647   for (unsigned i = 0; i < Iterations; ++i) {
12648     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12649     AddToWorklist(NewEst.getNode());
12650
12651     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12652     AddToWorklist(NewEst.getNode());
12653
12654     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12655     AddToWorklist(NewEst.getNode());
12656
12657     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12658     AddToWorklist(Est.getNode());
12659   }
12660   return Est;
12661 }
12662
12663 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12664 /// For the reciprocal sqrt, we need to find the zero of the function:
12665 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12666 ///     =>
12667 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12668 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12669                                           unsigned Iterations) {
12670   EVT VT = Arg.getValueType();
12671   SDLoc DL(Arg);
12672   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12673   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12674
12675   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12676   for (unsigned i = 0; i < Iterations; ++i) {
12677     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12678     AddToWorklist(HalfEst.getNode());
12679
12680     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12681     AddToWorklist(Est.getNode());
12682
12683     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12684     AddToWorklist(Est.getNode());
12685
12686     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12687     AddToWorklist(Est.getNode());
12688
12689     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12690     AddToWorklist(Est.getNode());
12691   }
12692   return Est;
12693 }
12694
12695 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12696   if (Level >= AfterLegalizeDAG)
12697     return SDValue();
12698
12699   // Expose the DAG combiner to the target combiner implementations.
12700   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12701   unsigned Iterations = 0;
12702   bool UseOneConstNR = false;
12703   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12704     AddToWorklist(Est.getNode());
12705     if (Iterations) {
12706       Est = UseOneConstNR ?
12707         BuildRsqrtNROneConst(Op, Est, Iterations) :
12708         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12709     }
12710     return Est;
12711   }
12712
12713   return SDValue();
12714 }
12715
12716 /// Return true if base is a frame index, which is known not to alias with
12717 /// anything but itself.  Provides base object and offset as results.
12718 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12719                            const GlobalValue *&GV, const void *&CV) {
12720   // Assume it is a primitive operation.
12721   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12722
12723   // If it's an adding a simple constant then integrate the offset.
12724   if (Base.getOpcode() == ISD::ADD) {
12725     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12726       Base = Base.getOperand(0);
12727       Offset += C->getZExtValue();
12728     }
12729   }
12730
12731   // Return the underlying GlobalValue, and update the Offset.  Return false
12732   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12733   // by multiple nodes with different offsets.
12734   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12735     GV = G->getGlobal();
12736     Offset += G->getOffset();
12737     return false;
12738   }
12739
12740   // Return the underlying Constant value, and update the Offset.  Return false
12741   // for ConstantSDNodes since the same constant pool entry may be represented
12742   // by multiple nodes with different offsets.
12743   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12744     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12745                                          : (const void *)C->getConstVal();
12746     Offset += C->getOffset();
12747     return false;
12748   }
12749   // If it's any of the following then it can't alias with anything but itself.
12750   return isa<FrameIndexSDNode>(Base);
12751 }
12752
12753 /// Return true if there is any possibility that the two addresses overlap.
12754 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12755   // If they are the same then they must be aliases.
12756   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12757
12758   // If they are both volatile then they cannot be reordered.
12759   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12760
12761   // Gather base node and offset information.
12762   SDValue Base1, Base2;
12763   int64_t Offset1, Offset2;
12764   const GlobalValue *GV1, *GV2;
12765   const void *CV1, *CV2;
12766   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12767                                       Base1, Offset1, GV1, CV1);
12768   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12769                                       Base2, Offset2, GV2, CV2);
12770
12771   // If they have a same base address then check to see if they overlap.
12772   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12773     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12774              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12775
12776   // It is possible for different frame indices to alias each other, mostly
12777   // when tail call optimization reuses return address slots for arguments.
12778   // To catch this case, look up the actual index of frame indices to compute
12779   // the real alias relationship.
12780   if (isFrameIndex1 && isFrameIndex2) {
12781     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12782     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12783     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12784     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12785              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12786   }
12787
12788   // Otherwise, if we know what the bases are, and they aren't identical, then
12789   // we know they cannot alias.
12790   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12791     return false;
12792
12793   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12794   // compared to the size and offset of the access, we may be able to prove they
12795   // do not alias.  This check is conservative for now to catch cases created by
12796   // splitting vector types.
12797   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12798       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12799       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12800        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12801       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12802     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12803     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12804
12805     // There is no overlap between these relatively aligned accesses of similar
12806     // size, return no alias.
12807     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12808         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12809       return false;
12810   }
12811
12812   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12813                    ? CombinerGlobalAA
12814                    : DAG.getSubtarget().useAA();
12815 #ifndef NDEBUG
12816   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12817       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12818     UseAA = false;
12819 #endif
12820   if (UseAA &&
12821       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12822     // Use alias analysis information.
12823     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12824                                  Op1->getSrcValueOffset());
12825     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12826         Op0->getSrcValueOffset() - MinOffset;
12827     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12828         Op1->getSrcValueOffset() - MinOffset;
12829     AliasAnalysis::AliasResult AAResult =
12830         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12831                                          Overlap1,
12832                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12833                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12834                                          Overlap2,
12835                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12836     if (AAResult == AliasAnalysis::NoAlias)
12837       return false;
12838   }
12839
12840   // Otherwise we have to assume they alias.
12841   return true;
12842 }
12843
12844 /// Walk up chain skipping non-aliasing memory nodes,
12845 /// looking for aliasing nodes and adding them to the Aliases vector.
12846 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12847                                    SmallVectorImpl<SDValue> &Aliases) {
12848   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12849   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12850
12851   // Get alias information for node.
12852   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12853
12854   // Starting off.
12855   Chains.push_back(OriginalChain);
12856   unsigned Depth = 0;
12857
12858   // Look at each chain and determine if it is an alias.  If so, add it to the
12859   // aliases list.  If not, then continue up the chain looking for the next
12860   // candidate.
12861   while (!Chains.empty()) {
12862     SDValue Chain = Chains.back();
12863     Chains.pop_back();
12864
12865     // For TokenFactor nodes, look at each operand and only continue up the
12866     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12867     // find more and revert to original chain since the xform is unlikely to be
12868     // profitable.
12869     //
12870     // FIXME: The depth check could be made to return the last non-aliasing
12871     // chain we found before we hit a tokenfactor rather than the original
12872     // chain.
12873     if (Depth > 6 || Aliases.size() == 2) {
12874       Aliases.clear();
12875       Aliases.push_back(OriginalChain);
12876       return;
12877     }
12878
12879     // Don't bother if we've been before.
12880     if (!Visited.insert(Chain.getNode()).second)
12881       continue;
12882
12883     switch (Chain.getOpcode()) {
12884     case ISD::EntryToken:
12885       // Entry token is ideal chain operand, but handled in FindBetterChain.
12886       break;
12887
12888     case ISD::LOAD:
12889     case ISD::STORE: {
12890       // Get alias information for Chain.
12891       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12892           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12893
12894       // If chain is alias then stop here.
12895       if (!(IsLoad && IsOpLoad) &&
12896           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12897         Aliases.push_back(Chain);
12898       } else {
12899         // Look further up the chain.
12900         Chains.push_back(Chain.getOperand(0));
12901         ++Depth;
12902       }
12903       break;
12904     }
12905
12906     case ISD::TokenFactor:
12907       // We have to check each of the operands of the token factor for "small"
12908       // token factors, so we queue them up.  Adding the operands to the queue
12909       // (stack) in reverse order maintains the original order and increases the
12910       // likelihood that getNode will find a matching token factor (CSE.)
12911       if (Chain.getNumOperands() > 16) {
12912         Aliases.push_back(Chain);
12913         break;
12914       }
12915       for (unsigned n = Chain.getNumOperands(); n;)
12916         Chains.push_back(Chain.getOperand(--n));
12917       ++Depth;
12918       break;
12919
12920     default:
12921       // For all other instructions we will just have to take what we can get.
12922       Aliases.push_back(Chain);
12923       break;
12924     }
12925   }
12926
12927   // We need to be careful here to also search for aliases through the
12928   // value operand of a store, etc. Consider the following situation:
12929   //   Token1 = ...
12930   //   L1 = load Token1, %52
12931   //   S1 = store Token1, L1, %51
12932   //   L2 = load Token1, %52+8
12933   //   S2 = store Token1, L2, %51+8
12934   //   Token2 = Token(S1, S2)
12935   //   L3 = load Token2, %53
12936   //   S3 = store Token2, L3, %52
12937   //   L4 = load Token2, %53+8
12938   //   S4 = store Token2, L4, %52+8
12939   // If we search for aliases of S3 (which loads address %52), and we look
12940   // only through the chain, then we'll miss the trivial dependence on L1
12941   // (which also loads from %52). We then might change all loads and
12942   // stores to use Token1 as their chain operand, which could result in
12943   // copying %53 into %52 before copying %52 into %51 (which should
12944   // happen first).
12945   //
12946   // The problem is, however, that searching for such data dependencies
12947   // can become expensive, and the cost is not directly related to the
12948   // chain depth. Instead, we'll rule out such configurations here by
12949   // insisting that we've visited all chain users (except for users
12950   // of the original chain, which is not necessary). When doing this,
12951   // we need to look through nodes we don't care about (otherwise, things
12952   // like register copies will interfere with trivial cases).
12953
12954   SmallVector<const SDNode *, 16> Worklist;
12955   for (const SDNode *N : Visited)
12956     if (N != OriginalChain.getNode())
12957       Worklist.push_back(N);
12958
12959   while (!Worklist.empty()) {
12960     const SDNode *M = Worklist.pop_back_val();
12961
12962     // We have already visited M, and want to make sure we've visited any uses
12963     // of M that we care about. For uses that we've not visisted, and don't
12964     // care about, queue them to the worklist.
12965
12966     for (SDNode::use_iterator UI = M->use_begin(),
12967          UIE = M->use_end(); UI != UIE; ++UI)
12968       if (UI.getUse().getValueType() == MVT::Other &&
12969           Visited.insert(*UI).second) {
12970         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12971           // We've not visited this use, and we care about it (it could have an
12972           // ordering dependency with the original node).
12973           Aliases.clear();
12974           Aliases.push_back(OriginalChain);
12975           return;
12976         }
12977
12978         // We've not visited this use, but we don't care about it. Mark it as
12979         // visited and enqueue it to the worklist.
12980         Worklist.push_back(*UI);
12981       }
12982   }
12983 }
12984
12985 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12986 /// (aliasing node.)
12987 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12988   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12989
12990   // Accumulate all the aliases to this node.
12991   GatherAllAliases(N, OldChain, Aliases);
12992
12993   // If no operands then chain to entry token.
12994   if (Aliases.size() == 0)
12995     return DAG.getEntryNode();
12996
12997   // If a single operand then chain to it.  We don't need to revisit it.
12998   if (Aliases.size() == 1)
12999     return Aliases[0];
13000
13001   // Construct a custom tailored token factor.
13002   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13003 }
13004
13005 /// This is the entry point for the file.
13006 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13007                            CodeGenOpt::Level OptLevel) {
13008   /// This is the main entry point to this class.
13009   DAGCombiner(*this, AA, OptLevel).Run(Level);
13010 }