Simplify creation of a bunch of ArrayRefs by using None, makeArrayRef or just letting...
[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/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.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 //------------------------------ DAGCombiner ---------------------------------//
81
82   class DAGCombiner {
83     SelectionDAG &DAG;
84     const TargetLowering &TLI;
85     CombineLevel Level;
86     CodeGenOpt::Level OptLevel;
87     bool LegalOperations;
88     bool LegalTypes;
89     bool ForCodeSize;
90
91     /// \brief Worklist of all of the nodes that need to be simplified.
92     ///
93     /// This must behave as a stack -- new nodes to process are pushed onto the
94     /// back and when processing we pop off of the back.
95     ///
96     /// The worklist will not contain duplicates but may contain null entries
97     /// due to nodes being deleted from the underlying DAG.
98     SmallVector<SDNode *, 64> Worklist;
99
100     /// \brief Mapping from an SDNode to its position on the worklist.
101     ///
102     /// This is used to find and remove nodes from the worklist (by nulling
103     /// them) when they are deleted from the underlying DAG. It relies on
104     /// stable indices of nodes within the worklist.
105     DenseMap<SDNode *, unsigned> WorklistMap;
106
107     /// \brief Set of nodes which have been combined (at least once).
108     ///
109     /// This is used to allow us to reliably add any operands of a DAG node
110     /// which have not yet been combined to the worklist.
111     SmallPtrSet<SDNode *, 64> CombinedNodes;
112
113     // AA - Used for DAG load/store alias analysis.
114     AliasAnalysis &AA;
115
116     /// AddUsersToWorklist - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorklist(SDNode *N) {
121       for (SDNode *Node : N->uses())
122         AddToWorklist(Node);
123     }
124
125     /// visit - call the node-specific routine that knows how to fold each
126     /// particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// AddToWorklist - Add to the work list making sure its instance is at the
131     /// back (next to be processed.)
132     void AddToWorklist(SDNode *N) {
133       // Skip handle nodes as they can't usefully be combined and confuse the
134       // zero-use deletion strategy.
135       if (N->getOpcode() == ISD::HANDLENODE)
136         return;
137
138       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139         Worklist.push_back(N);
140     }
141
142     /// removeFromWorklist - remove all instances of N from the worklist.
143     ///
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     /// SimplifyDemandedBits - Check the specified integer node value to see if
177     /// it can be simplified or if things it uses can be simplified by bit
178     /// propagation.  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     bool SliceUpLoad(SDNode *N);
190
191     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
192     ///   load.
193     ///
194     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
195     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
196     /// \param EltNo index of the vector element to load.
197     /// \param OriginalLoad load that EVE came from to be replaced.
198     /// \returns EVE on success SDValue() on failure.
199     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
200         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
201     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
202     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
203     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
204     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue PromoteIntBinOp(SDValue Op);
206     SDValue PromoteIntShiftOp(SDValue Op);
207     SDValue PromoteExtend(SDValue Op);
208     bool PromoteLoad(SDValue Op);
209
210     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
211                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
212                          ISD::NodeType ExtType);
213
214     /// combine - call the node-specific routine that knows how to fold each
215     /// particular type of node. If that doesn't do anything, try the
216     /// target-specific DAG combines.
217     SDValue combine(SDNode *N);
218
219     // Visitation implementation - Implement dag node combining for different
220     // node types.  The semantics are as follows:
221     // Return Value:
222     //   SDValue.getNode() == 0 - No change was made
223     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
224     //   otherwise              - N should be replaced by the returned Operand.
225     //
226     SDValue visitTokenFactor(SDNode *N);
227     SDValue visitMERGE_VALUES(SDNode *N);
228     SDValue visitADD(SDNode *N);
229     SDValue visitSUB(SDNode *N);
230     SDValue visitADDC(SDNode *N);
231     SDValue visitSUBC(SDNode *N);
232     SDValue visitADDE(SDNode *N);
233     SDValue visitSUBE(SDNode *N);
234     SDValue visitMUL(SDNode *N);
235     SDValue visitSDIV(SDNode *N);
236     SDValue visitUDIV(SDNode *N);
237     SDValue visitSREM(SDNode *N);
238     SDValue visitUREM(SDNode *N);
239     SDValue visitMULHU(SDNode *N);
240     SDValue visitMULHS(SDNode *N);
241     SDValue visitSMUL_LOHI(SDNode *N);
242     SDValue visitUMUL_LOHI(SDNode *N);
243     SDValue visitSMULO(SDNode *N);
244     SDValue visitUMULO(SDNode *N);
245     SDValue visitSDIVREM(SDNode *N);
246     SDValue visitUDIVREM(SDNode *N);
247     SDValue visitAND(SDNode *N);
248     SDValue visitOR(SDNode *N);
249     SDValue visitXOR(SDNode *N);
250     SDValue SimplifyVBinOp(SDNode *N);
251     SDValue SimplifyVUnaryOp(SDNode *N);
252     SDValue visitSHL(SDNode *N);
253     SDValue visitSRA(SDNode *N);
254     SDValue visitSRL(SDNode *N);
255     SDValue visitRotate(SDNode *N);
256     SDValue visitCTLZ(SDNode *N);
257     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
258     SDValue visitCTTZ(SDNode *N);
259     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTPOP(SDNode *N);
261     SDValue visitSELECT(SDNode *N);
262     SDValue visitVSELECT(SDNode *N);
263     SDValue visitSELECT_CC(SDNode *N);
264     SDValue visitSETCC(SDNode *N);
265     SDValue visitSIGN_EXTEND(SDNode *N);
266     SDValue visitZERO_EXTEND(SDNode *N);
267     SDValue visitANY_EXTEND(SDNode *N);
268     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
269     SDValue visitTRUNCATE(SDNode *N);
270     SDValue visitBITCAST(SDNode *N);
271     SDValue visitBUILD_PAIR(SDNode *N);
272     SDValue visitFADD(SDNode *N);
273     SDValue visitFSUB(SDNode *N);
274     SDValue visitFMUL(SDNode *N);
275     SDValue visitFMA(SDNode *N);
276     SDValue visitFDIV(SDNode *N);
277     SDValue visitFREM(SDNode *N);
278     SDValue visitFCOPYSIGN(SDNode *N);
279     SDValue visitSINT_TO_FP(SDNode *N);
280     SDValue visitUINT_TO_FP(SDNode *N);
281     SDValue visitFP_TO_SINT(SDNode *N);
282     SDValue visitFP_TO_UINT(SDNode *N);
283     SDValue visitFP_ROUND(SDNode *N);
284     SDValue visitFP_ROUND_INREG(SDNode *N);
285     SDValue visitFP_EXTEND(SDNode *N);
286     SDValue visitFNEG(SDNode *N);
287     SDValue visitFABS(SDNode *N);
288     SDValue visitFCEIL(SDNode *N);
289     SDValue visitFTRUNC(SDNode *N);
290     SDValue visitFFLOOR(SDNode *N);
291     SDValue visitBRCOND(SDNode *N);
292     SDValue visitBR_CC(SDNode *N);
293     SDValue visitLOAD(SDNode *N);
294     SDValue visitSTORE(SDNode *N);
295     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
296     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
297     SDValue visitBUILD_VECTOR(SDNode *N);
298     SDValue visitCONCAT_VECTORS(SDNode *N);
299     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
300     SDValue visitVECTOR_SHUFFLE(SDNode *N);
301     SDValue visitINSERT_SUBVECTOR(SDNode *N);
302
303     SDValue XformToShuffleWithZero(SDNode *N);
304     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
305
306     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
307
308     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
309     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
310     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
311     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
312                              SDValue N3, ISD::CondCode CC,
313                              bool NotExtCompare = false);
314     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
315                           SDLoc DL, bool foldBooleans = true);
316
317     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
318                            SDValue &CC) const;
319     bool isOneUseSetCC(SDValue N) const;
320
321     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
322                                          unsigned HiOp);
323     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
324     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
325     SDValue BuildSDIV(SDNode *N);
326     SDValue BuildSDIVPow2(SDNode *N);
327     SDValue BuildUDIV(SDNode *N);
328     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
329                                bool DemandHighBits = true);
330     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
331     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
332                               SDValue InnerPos, SDValue InnerNeg,
333                               unsigned PosOpcode, unsigned NegOpcode,
334                               SDLoc DL);
335     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
336     SDValue ReduceLoadWidth(SDNode *N);
337     SDValue ReduceLoadOpStoreWidth(SDNode *N);
338     SDValue TransformFPLoadStorePair(SDNode *N);
339     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
340     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
341
342     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
343
344     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
345     /// looking for aliasing nodes and adding them to the Aliases vector.
346     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
347                           SmallVectorImpl<SDValue> &Aliases);
348
349     /// isAlias - Return true if there is any possibility that the two addresses
350     /// overlap.
351     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
352
353     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
354     /// looking for a better chain (aliasing node.)
355     SDValue FindBetterChain(SDNode *N, SDValue Chain);
356
357     /// Merge consecutive store operations into a wide store.
358     /// This optimization uses wide integers or vectors when possible.
359     /// \return True if some memory operations were changed.
360     bool MergeConsecutiveStores(StoreSDNode *N);
361
362     /// \brief Try to transform a truncation where C is a constant:
363     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
364     ///
365     /// \p N needs to be a truncation and its first operand an AND. Other
366     /// requirements are checked by the function (e.g. that trunc is
367     /// single-use) and if missed an empty SDValue is returned.
368     SDValue distributeTruncateThroughAnd(SDNode *N);
369
370   public:
371     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374       AttributeSet FnAttrs =
375           DAG.getMachineFunction().getFunction()->getAttributes();
376       ForCodeSize =
377           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378                                Attribute::OptimizeForSize) ||
379           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
380     }
381
382     /// Run - runs the dag combiner on all nodes in the work list
383     void Run(CombineLevel AtLevel);
384
385     SelectionDAG &getDAG() const { return DAG; }
386
387     /// getShiftAmountTy - Returns a type large enough to hold any valid
388     /// shift amount - before type legalization these can be huge.
389     EVT getShiftAmountTy(EVT LHSTy) {
390       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391       if (LHSTy.isVector())
392         return LHSTy;
393       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394                         : TLI.getPointerTy();
395     }
396
397     /// isTypeLegal - This method returns true if we are running before type
398     /// legalization or if the specified VT is legal.
399     bool isTypeLegal(const EVT &VT) {
400       if (!LegalTypes) return true;
401       return TLI.isTypeLegal(VT);
402     }
403
404     /// getSetCCResultType - Convenience wrapper around
405     /// TargetLowering::getSetCCResultType
406     EVT getSetCCResultType(EVT VT) const {
407       return TLI.getSetCCResultType(*DAG.getContext(), VT);
408     }
409   };
410 }
411
412
413 namespace {
414 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
415 /// nodes from the worklist.
416 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
417   DAGCombiner &DC;
418 public:
419   explicit WorklistRemover(DAGCombiner &dc)
420     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
421
422   void NodeDeleted(SDNode *N, SDNode *E) override {
423     DC.removeFromWorklist(N);
424   }
425 };
426 }
427
428 //===----------------------------------------------------------------------===//
429 //  TargetLowering::DAGCombinerInfo implementation
430 //===----------------------------------------------------------------------===//
431
432 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
433   ((DAGCombiner*)DC)->AddToWorklist(N);
434 }
435
436 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
437   ((DAGCombiner*)DC)->removeFromWorklist(N);
438 }
439
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
442   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
443 }
444
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
447   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
448 }
449
450
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
453   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
454 }
455
456 void TargetLowering::DAGCombinerInfo::
457 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
458   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
459 }
460
461 //===----------------------------------------------------------------------===//
462 // Helper Functions
463 //===----------------------------------------------------------------------===//
464
465 void DAGCombiner::deleteAndRecombine(SDNode *N) {
466   removeFromWorklist(N);
467
468   // If the operands of this node are only used by the node, they will now be
469   // dead. Make sure to re-visit them and recursively delete dead nodes.
470   for (const SDValue &Op : N->ops())
471     if (Op->hasOneUse())
472       AddToWorklist(Op.getNode());
473
474   DAG.DeleteNode(N);
475 }
476
477 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
478 /// specified expression for the same cost as the expression itself, or 2 if we
479 /// can compute the negated form more cheaply than the expression itself.
480 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
481                                const TargetLowering &TLI,
482                                const TargetOptions *Options,
483                                unsigned Depth = 0) {
484   // fneg is removable even if it has multiple uses.
485   if (Op.getOpcode() == ISD::FNEG) return 2;
486
487   // Don't allow anything with multiple uses.
488   if (!Op.hasOneUse()) return 0;
489
490   // Don't recurse exponentially.
491   if (Depth > 6) return 0;
492
493   switch (Op.getOpcode()) {
494   default: return false;
495   case ISD::ConstantFP:
496     // Don't invert constant FP values after legalize.  The negated constant
497     // isn't necessarily legal.
498     return LegalOperations ? 0 : 1;
499   case ISD::FADD:
500     // FIXME: determine better conditions for this xform.
501     if (!Options->UnsafeFPMath) return 0;
502
503     // After operation legalization, it might not be legal to create new FSUBs.
504     if (LegalOperations &&
505         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
506       return 0;
507
508     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
509     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
510                                     Options, Depth + 1))
511       return V;
512     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
513     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
514                               Depth + 1);
515   case ISD::FSUB:
516     // We can't turn -(A-B) into B-A when we honor signed zeros.
517     if (!Options->UnsafeFPMath) return 0;
518
519     // fold (fneg (fsub A, B)) -> (fsub B, A)
520     return 1;
521
522   case ISD::FMUL:
523   case ISD::FDIV:
524     if (Options->HonorSignDependentRoundingFPMath()) return 0;
525
526     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
527     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
528                                     Options, Depth + 1))
529       return V;
530
531     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
532                               Depth + 1);
533
534   case ISD::FP_EXTEND:
535   case ISD::FP_ROUND:
536   case ISD::FSIN:
537     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
538                               Depth + 1);
539   }
540 }
541
542 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
543 /// returns the newly negated expression.
544 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
545                                     bool LegalOperations, unsigned Depth = 0) {
546   // fneg is removable even if it has multiple uses.
547   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
548
549   // Don't allow anything with multiple uses.
550   assert(Op.hasOneUse() && "Unknown reuse!");
551
552   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
553   switch (Op.getOpcode()) {
554   default: llvm_unreachable("Unknown code");
555   case ISD::ConstantFP: {
556     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
557     V.changeSign();
558     return DAG.getConstantFP(V, Op.getValueType());
559   }
560   case ISD::FADD:
561     // FIXME: determine better conditions for this xform.
562     assert(DAG.getTarget().Options.UnsafeFPMath);
563
564     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
565     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
566                            DAG.getTargetLoweringInfo(),
567                            &DAG.getTarget().Options, Depth+1))
568       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
569                          GetNegatedExpression(Op.getOperand(0), DAG,
570                                               LegalOperations, Depth+1),
571                          Op.getOperand(1));
572     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
573     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574                        GetNegatedExpression(Op.getOperand(1), DAG,
575                                             LegalOperations, Depth+1),
576                        Op.getOperand(0));
577   case ISD::FSUB:
578     // We can't turn -(A-B) into B-A when we honor signed zeros.
579     assert(DAG.getTarget().Options.UnsafeFPMath);
580
581     // fold (fneg (fsub 0, B)) -> B
582     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
583       if (N0CFP->getValueAPF().isZero())
584         return Op.getOperand(1);
585
586     // fold (fneg (fsub A, B)) -> (fsub B, A)
587     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
588                        Op.getOperand(1), Op.getOperand(0));
589
590   case ISD::FMUL:
591   case ISD::FDIV:
592     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
593
594     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
595     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
596                            DAG.getTargetLoweringInfo(),
597                            &DAG.getTarget().Options, Depth+1))
598       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599                          GetNegatedExpression(Op.getOperand(0), DAG,
600                                               LegalOperations, Depth+1),
601                          Op.getOperand(1));
602
603     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
605                        Op.getOperand(0),
606                        GetNegatedExpression(Op.getOperand(1), DAG,
607                                             LegalOperations, Depth+1));
608
609   case ISD::FP_EXTEND:
610   case ISD::FSIN:
611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(0), DAG,
613                                             LegalOperations, Depth+1));
614   case ISD::FP_ROUND:
615       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616                          GetNegatedExpression(Op.getOperand(0), DAG,
617                                               LegalOperations, Depth+1),
618                          Op.getOperand(1));
619   }
620 }
621
622 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
628                                     SDValue &CC) const {
629   if (N.getOpcode() == ISD::SETCC) {
630     LHS = N.getOperand(0);
631     RHS = N.getOperand(1);
632     CC  = N.getOperand(2);
633     return true;
634   }
635
636   if (N.getOpcode() != ISD::SELECT_CC ||
637       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
639     return false;
640
641   LHS = N.getOperand(0);
642   RHS = N.getOperand(1);
643   CC  = N.getOperand(4);
644   return true;
645 }
646
647 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
648 // one use.  If this is true, it allows the users to invert the operation for
649 // free when it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
651   SDValue N0, N1, N2;
652   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
653     return true;
654   return false;
655 }
656
657 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
661   if (!C)
662     return false;
663
664   APInt SplatUndef;
665   unsigned SplatBitSize;
666   bool HasAnyUndefs;
667   EVT EltVT = N->getValueType(0).getVectorElementType();
668   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
669                              HasAnyUndefs) &&
670           EltVT.getSizeInBits() >= SplatBitSize);
671 }
672
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675   if (isa<ConstantSDNode>(N))
676     return N.getNode();
677   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678   if(BV && BV->isConstant())
679     return BV;
680   return nullptr;
681 }
682
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
684 // int.
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
687     return CN;
688
689   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690     BitVector UndefElements;
691     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
692
693     // BuildVectors can truncate their operands. Ignore that case here.
694     // FIXME: We blindly ignore splats which include undef which is overly
695     // pessimistic.
696     if (CN && UndefElements.none() &&
697         CN->getValueType(0) == N.getValueType().getScalarType())
698       return CN;
699   }
700
701   return nullptr;
702 }
703
704 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
705 // float.
706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
708     return CN;
709
710   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711     BitVector UndefElements;
712     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
713
714     // BuildVectors can truncate their operands. Ignore that case here.
715     // FIXME: We blindly ignore splats which include undef which is overly
716     // pessimistic.
717     if (CN && UndefElements.none() &&
718         CN->getValueType(0) == N.getValueType().getScalarType())
719       return CN;
720   }
721
722   return nullptr;
723 }
724
725 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
726                                     SDValue N0, SDValue N1) {
727   EVT VT = N0.getValueType();
728   if (N0.getOpcode() == Opc) {
729     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733         if (!OpNode.getNode())
734           return SDValue();
735         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
736       }
737       if (N0.hasOneUse()) {
738         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
739         // use
740         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741         if (!OpNode.getNode())
742           return SDValue();
743         AddToWorklist(OpNode.getNode());
744         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
745       }
746     }
747   }
748
749   if (N1.getOpcode() == Opc) {
750     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754         if (!OpNode.getNode())
755           return SDValue();
756         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
757       }
758       if (N1.hasOneUse()) {
759         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
760         // use
761         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762         if (!OpNode.getNode())
763           return SDValue();
764         AddToWorklist(OpNode.getNode());
765         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
766       }
767     }
768   }
769
770   return SDValue();
771 }
772
773 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
774                                bool AddTo) {
775   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
776   ++NodesCombined;
777   DEBUG(dbgs() << "\nReplacing.1 ";
778         N->dump(&DAG);
779         dbgs() << "\nWith: ";
780         To[0].getNode()->dump(&DAG);
781         dbgs() << " and " << NumTo-1 << " other values\n";
782         for (unsigned i = 0, e = NumTo; i != e; ++i)
783           assert((!To[i].getNode() ||
784                   N->getValueType(i) == To[i].getValueType()) &&
785                  "Cannot combine value to value of different type!"));
786   WorklistRemover DeadNodes(*this);
787   DAG.ReplaceAllUsesWith(N, To);
788   if (AddTo) {
789     // Push the new nodes and any users onto the worklist
790     for (unsigned i = 0, e = NumTo; i != e; ++i) {
791       if (To[i].getNode()) {
792         AddToWorklist(To[i].getNode());
793         AddUsersToWorklist(To[i].getNode());
794       }
795     }
796   }
797
798   // Finally, if the node is now dead, remove it from the graph.  The node
799   // may not be dead if the replacement process recursively simplified to
800   // something else needing this node.
801   if (N->use_empty())
802     deleteAndRecombine(N);
803   return SDValue(N, 0);
804 }
805
806 void DAGCombiner::
807 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
808   // Replace all uses.  If any nodes become isomorphic to other nodes and
809   // are deleted, make sure to remove them from our worklist.
810   WorklistRemover DeadNodes(*this);
811   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
812
813   // Push the new node and any (possibly new) users onto the worklist.
814   AddToWorklist(TLO.New.getNode());
815   AddUsersToWorklist(TLO.New.getNode());
816
817   // Finally, if the node is now dead, remove it from the graph.  The node
818   // may not be dead if the replacement process recursively simplified to
819   // something else needing this node.
820   if (TLO.Old.getNode()->use_empty())
821     deleteAndRecombine(TLO.Old.getNode());
822 }
823
824 /// SimplifyDemandedBits - Check the specified integer node value to see if
825 /// it can be simplified or if things it uses can be simplified by bit
826 /// propagation.  If so, return true.
827 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
828   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
829   APInt KnownZero, KnownOne;
830   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
831     return false;
832
833   // Revisit the node.
834   AddToWorklist(Op.getNode());
835
836   // Replace the old value with the new one.
837   ++NodesCombined;
838   DEBUG(dbgs() << "\nReplacing.2 ";
839         TLO.Old.getNode()->dump(&DAG);
840         dbgs() << "\nWith: ";
841         TLO.New.getNode()->dump(&DAG);
842         dbgs() << '\n');
843
844   CommitTargetLoweringOpt(TLO);
845   return true;
846 }
847
848 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
849   SDLoc dl(Load);
850   EVT VT = Load->getValueType(0);
851   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
852
853   DEBUG(dbgs() << "\nReplacing.9 ";
854         Load->dump(&DAG);
855         dbgs() << "\nWith: ";
856         Trunc.getNode()->dump(&DAG);
857         dbgs() << '\n');
858   WorklistRemover DeadNodes(*this);
859   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
860   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
861   deleteAndRecombine(Load);
862   AddToWorklist(Trunc.getNode());
863 }
864
865 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
866   Replace = false;
867   SDLoc dl(Op);
868   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
869     EVT MemVT = LD->getMemoryVT();
870     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
871       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
872                                                   : ISD::EXTLOAD)
873       : LD->getExtensionType();
874     Replace = true;
875     return DAG.getExtLoad(ExtType, dl, PVT,
876                           LD->getChain(), LD->getBasePtr(),
877                           MemVT, LD->getMemOperand());
878   }
879
880   unsigned Opc = Op.getOpcode();
881   switch (Opc) {
882   default: break;
883   case ISD::AssertSext:
884     return DAG.getNode(ISD::AssertSext, dl, PVT,
885                        SExtPromoteOperand(Op.getOperand(0), PVT),
886                        Op.getOperand(1));
887   case ISD::AssertZext:
888     return DAG.getNode(ISD::AssertZext, dl, PVT,
889                        ZExtPromoteOperand(Op.getOperand(0), PVT),
890                        Op.getOperand(1));
891   case ISD::Constant: {
892     unsigned ExtOpc =
893       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
894     return DAG.getNode(ExtOpc, dl, PVT, Op);
895   }
896   }
897
898   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
899     return SDValue();
900   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
901 }
902
903 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
904   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
905     return SDValue();
906   EVT OldVT = Op.getValueType();
907   SDLoc dl(Op);
908   bool Replace = false;
909   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
910   if (!NewOp.getNode())
911     return SDValue();
912   AddToWorklist(NewOp.getNode());
913
914   if (Replace)
915     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
916   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
917                      DAG.getValueType(OldVT));
918 }
919
920 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
921   EVT OldVT = Op.getValueType();
922   SDLoc dl(Op);
923   bool Replace = false;
924   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
925   if (!NewOp.getNode())
926     return SDValue();
927   AddToWorklist(NewOp.getNode());
928
929   if (Replace)
930     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
931   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
932 }
933
934 /// PromoteIntBinOp - Promote the specified integer binary operation if the
935 /// target indicates it is beneficial. e.g. On x86, it's usually better to
936 /// promote i16 operations to i32 since i16 instructions are longer.
937 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
938   if (!LegalOperations)
939     return SDValue();
940
941   EVT VT = Op.getValueType();
942   if (VT.isVector() || !VT.isInteger())
943     return SDValue();
944
945   // If operation type is 'undesirable', e.g. i16 on x86, consider
946   // promoting it.
947   unsigned Opc = Op.getOpcode();
948   if (TLI.isTypeDesirableForOp(Opc, VT))
949     return SDValue();
950
951   EVT PVT = VT;
952   // Consult target whether it is a good idea to promote this operation and
953   // what's the right type to promote it to.
954   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
955     assert(PVT != VT && "Don't know what type to promote to!");
956
957     bool Replace0 = false;
958     SDValue N0 = Op.getOperand(0);
959     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
960     if (!NN0.getNode())
961       return SDValue();
962
963     bool Replace1 = false;
964     SDValue N1 = Op.getOperand(1);
965     SDValue NN1;
966     if (N0 == N1)
967       NN1 = NN0;
968     else {
969       NN1 = PromoteOperand(N1, PVT, Replace1);
970       if (!NN1.getNode())
971         return SDValue();
972     }
973
974     AddToWorklist(NN0.getNode());
975     if (NN1.getNode())
976       AddToWorklist(NN1.getNode());
977
978     if (Replace0)
979       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
980     if (Replace1)
981       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
982
983     DEBUG(dbgs() << "\nPromoting ";
984           Op.getNode()->dump(&DAG));
985     SDLoc dl(Op);
986     return DAG.getNode(ISD::TRUNCATE, dl, VT,
987                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
988   }
989   return SDValue();
990 }
991
992 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
993 /// target indicates it is beneficial. e.g. On x86, it's usually better to
994 /// promote i16 operations to i32 since i16 instructions are longer.
995 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
996   if (!LegalOperations)
997     return SDValue();
998
999   EVT VT = Op.getValueType();
1000   if (VT.isVector() || !VT.isInteger())
1001     return SDValue();
1002
1003   // If operation type is 'undesirable', e.g. i16 on x86, consider
1004   // promoting it.
1005   unsigned Opc = Op.getOpcode();
1006   if (TLI.isTypeDesirableForOp(Opc, VT))
1007     return SDValue();
1008
1009   EVT PVT = VT;
1010   // Consult target whether it is a good idea to promote this operation and
1011   // what's the right type to promote it to.
1012   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1013     assert(PVT != VT && "Don't know what type to promote to!");
1014
1015     bool Replace = false;
1016     SDValue N0 = Op.getOperand(0);
1017     if (Opc == ISD::SRA)
1018       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1019     else if (Opc == ISD::SRL)
1020       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1021     else
1022       N0 = PromoteOperand(N0, PVT, Replace);
1023     if (!N0.getNode())
1024       return SDValue();
1025
1026     AddToWorklist(N0.getNode());
1027     if (Replace)
1028       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1029
1030     DEBUG(dbgs() << "\nPromoting ";
1031           Op.getNode()->dump(&DAG));
1032     SDLoc dl(Op);
1033     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1034                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1035   }
1036   return SDValue();
1037 }
1038
1039 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1040   if (!LegalOperations)
1041     return SDValue();
1042
1043   EVT VT = Op.getValueType();
1044   if (VT.isVector() || !VT.isInteger())
1045     return SDValue();
1046
1047   // If operation type is 'undesirable', e.g. i16 on x86, consider
1048   // promoting it.
1049   unsigned Opc = Op.getOpcode();
1050   if (TLI.isTypeDesirableForOp(Opc, VT))
1051     return SDValue();
1052
1053   EVT PVT = VT;
1054   // Consult target whether it is a good idea to promote this operation and
1055   // what's the right type to promote it to.
1056   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1057     assert(PVT != VT && "Don't know what type to promote to!");
1058     // fold (aext (aext x)) -> (aext x)
1059     // fold (aext (zext x)) -> (zext x)
1060     // fold (aext (sext x)) -> (sext x)
1061     DEBUG(dbgs() << "\nPromoting ";
1062           Op.getNode()->dump(&DAG));
1063     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1064   }
1065   return SDValue();
1066 }
1067
1068 bool DAGCombiner::PromoteLoad(SDValue Op) {
1069   if (!LegalOperations)
1070     return false;
1071
1072   EVT VT = Op.getValueType();
1073   if (VT.isVector() || !VT.isInteger())
1074     return false;
1075
1076   // If operation type is 'undesirable', e.g. i16 on x86, consider
1077   // promoting it.
1078   unsigned Opc = Op.getOpcode();
1079   if (TLI.isTypeDesirableForOp(Opc, VT))
1080     return false;
1081
1082   EVT PVT = VT;
1083   // Consult target whether it is a good idea to promote this operation and
1084   // what's the right type to promote it to.
1085   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1086     assert(PVT != VT && "Don't know what type to promote to!");
1087
1088     SDLoc dl(Op);
1089     SDNode *N = Op.getNode();
1090     LoadSDNode *LD = cast<LoadSDNode>(N);
1091     EVT MemVT = LD->getMemoryVT();
1092     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1093       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1094                                                   : ISD::EXTLOAD)
1095       : LD->getExtensionType();
1096     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1097                                    LD->getChain(), LD->getBasePtr(),
1098                                    MemVT, LD->getMemOperand());
1099     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1100
1101     DEBUG(dbgs() << "\nPromoting ";
1102           N->dump(&DAG);
1103           dbgs() << "\nTo: ";
1104           Result.getNode()->dump(&DAG);
1105           dbgs() << '\n');
1106     WorklistRemover DeadNodes(*this);
1107     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1108     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1109     deleteAndRecombine(N);
1110     AddToWorklist(Result.getNode());
1111     return true;
1112   }
1113   return false;
1114 }
1115
1116 /// \brief Recursively delete a node which has no uses and any operands for
1117 /// which it is the only use.
1118 ///
1119 /// Note that this both deletes the nodes and removes them from the worklist.
1120 /// It also adds any nodes who have had a user deleted to the worklist as they
1121 /// may now have only one use and subject to other combines.
1122 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1123   if (!N->use_empty())
1124     return false;
1125
1126   SmallSetVector<SDNode *, 16> Nodes;
1127   Nodes.insert(N);
1128   do {
1129     N = Nodes.pop_back_val();
1130     if (!N)
1131       continue;
1132
1133     if (N->use_empty()) {
1134       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1135         Nodes.insert(N->getOperand(i).getNode());
1136
1137       removeFromWorklist(N);
1138       DAG.DeleteNode(N);
1139     } else {
1140       AddToWorklist(N);
1141     }
1142   } while (!Nodes.empty());
1143   return true;
1144 }
1145
1146 //===----------------------------------------------------------------------===//
1147 //  Main DAG Combiner implementation
1148 //===----------------------------------------------------------------------===//
1149
1150 void DAGCombiner::Run(CombineLevel AtLevel) {
1151   // set the instance variables, so that the various visit routines may use it.
1152   Level = AtLevel;
1153   LegalOperations = Level >= AfterLegalizeVectorOps;
1154   LegalTypes = Level >= AfterLegalizeTypes;
1155
1156   // Add all the dag nodes to the worklist.
1157   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1158        E = DAG.allnodes_end(); I != E; ++I)
1159     AddToWorklist(I);
1160
1161   // Create a dummy node (which is not added to allnodes), that adds a reference
1162   // to the root node, preventing it from being deleted, and tracking any
1163   // changes of the root.
1164   HandleSDNode Dummy(DAG.getRoot());
1165
1166   // while the worklist isn't empty, find a node and
1167   // try and combine it.
1168   while (!WorklistMap.empty()) {
1169     SDNode *N;
1170     // The Worklist holds the SDNodes in order, but it may contain null entries.
1171     do {
1172       N = Worklist.pop_back_val();
1173     } while (!N);
1174
1175     bool GoodWorklistEntry = WorklistMap.erase(N);
1176     (void)GoodWorklistEntry;
1177     assert(GoodWorklistEntry &&
1178            "Found a worklist entry without a corresponding map entry!");
1179
1180     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1181     // N is deleted from the DAG, since they too may now be dead or may have a
1182     // reduced number of uses, allowing other xforms.
1183     if (recursivelyDeleteUnusedNodes(N))
1184       continue;
1185
1186     WorklistRemover DeadNodes(*this);
1187
1188     // If this combine is running after legalizing the DAG, re-legalize any
1189     // nodes pulled off the worklist.
1190     if (Level == AfterLegalizeDAG) {
1191       SmallSetVector<SDNode *, 16> UpdatedNodes;
1192       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1193
1194       for (SDNode *LN : UpdatedNodes) {
1195         AddToWorklist(LN);
1196         AddUsersToWorklist(LN);
1197       }
1198       if (!NIsValid)
1199         continue;
1200     }
1201
1202     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1203
1204     // Add any operands of the new node which have not yet been combined to the
1205     // worklist as well. Because the worklist uniques things already, this
1206     // won't repeatedly process the same operand.
1207     CombinedNodes.insert(N);
1208     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1209       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1210         AddToWorklist(N->getOperand(i).getNode());
1211
1212     SDValue RV = combine(N);
1213
1214     if (!RV.getNode())
1215       continue;
1216
1217     ++NodesCombined;
1218
1219     // If we get back the same node we passed in, rather than a new node or
1220     // zero, we know that the node must have defined multiple values and
1221     // CombineTo was used.  Since CombineTo takes care of the worklist
1222     // mechanics for us, we have no work to do in this case.
1223     if (RV.getNode() == N)
1224       continue;
1225
1226     assert(N->getOpcode() != ISD::DELETED_NODE &&
1227            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1228            "Node was deleted but visit returned new node!");
1229
1230     DEBUG(dbgs() << " ... into: ";
1231           RV.getNode()->dump(&DAG));
1232
1233     // Transfer debug value.
1234     DAG.TransferDbgValues(SDValue(N, 0), RV);
1235     if (N->getNumValues() == RV.getNode()->getNumValues())
1236       DAG.ReplaceAllUsesWith(N, RV.getNode());
1237     else {
1238       assert(N->getValueType(0) == RV.getValueType() &&
1239              N->getNumValues() == 1 && "Type mismatch");
1240       SDValue OpV = RV;
1241       DAG.ReplaceAllUsesWith(N, &OpV);
1242     }
1243
1244     // Push the new node and any users onto the worklist
1245     AddToWorklist(RV.getNode());
1246     AddUsersToWorklist(RV.getNode());
1247
1248     // Finally, if the node is now dead, remove it from the graph.  The node
1249     // may not be dead if the replacement process recursively simplified to
1250     // something else needing this node. This will also take care of adding any
1251     // operands which have lost a user to the worklist.
1252     recursivelyDeleteUnusedNodes(N);
1253   }
1254
1255   // If the root changed (e.g. it was a dead load, update the root).
1256   DAG.setRoot(Dummy.getValue());
1257   DAG.RemoveDeadNodes();
1258 }
1259
1260 SDValue DAGCombiner::visit(SDNode *N) {
1261   switch (N->getOpcode()) {
1262   default: break;
1263   case ISD::TokenFactor:        return visitTokenFactor(N);
1264   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1265   case ISD::ADD:                return visitADD(N);
1266   case ISD::SUB:                return visitSUB(N);
1267   case ISD::ADDC:               return visitADDC(N);
1268   case ISD::SUBC:               return visitSUBC(N);
1269   case ISD::ADDE:               return visitADDE(N);
1270   case ISD::SUBE:               return visitSUBE(N);
1271   case ISD::MUL:                return visitMUL(N);
1272   case ISD::SDIV:               return visitSDIV(N);
1273   case ISD::UDIV:               return visitUDIV(N);
1274   case ISD::SREM:               return visitSREM(N);
1275   case ISD::UREM:               return visitUREM(N);
1276   case ISD::MULHU:              return visitMULHU(N);
1277   case ISD::MULHS:              return visitMULHS(N);
1278   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1279   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1280   case ISD::SMULO:              return visitSMULO(N);
1281   case ISD::UMULO:              return visitUMULO(N);
1282   case ISD::SDIVREM:            return visitSDIVREM(N);
1283   case ISD::UDIVREM:            return visitUDIVREM(N);
1284   case ISD::AND:                return visitAND(N);
1285   case ISD::OR:                 return visitOR(N);
1286   case ISD::XOR:                return visitXOR(N);
1287   case ISD::SHL:                return visitSHL(N);
1288   case ISD::SRA:                return visitSRA(N);
1289   case ISD::SRL:                return visitSRL(N);
1290   case ISD::ROTR:
1291   case ISD::ROTL:               return visitRotate(N);
1292   case ISD::CTLZ:               return visitCTLZ(N);
1293   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1294   case ISD::CTTZ:               return visitCTTZ(N);
1295   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1296   case ISD::CTPOP:              return visitCTPOP(N);
1297   case ISD::SELECT:             return visitSELECT(N);
1298   case ISD::VSELECT:            return visitVSELECT(N);
1299   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1300   case ISD::SETCC:              return visitSETCC(N);
1301   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1302   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1303   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1304   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1305   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1306   case ISD::BITCAST:            return visitBITCAST(N);
1307   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1308   case ISD::FADD:               return visitFADD(N);
1309   case ISD::FSUB:               return visitFSUB(N);
1310   case ISD::FMUL:               return visitFMUL(N);
1311   case ISD::FMA:                return visitFMA(N);
1312   case ISD::FDIV:               return visitFDIV(N);
1313   case ISD::FREM:               return visitFREM(N);
1314   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1315   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1316   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1317   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1318   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1319   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1320   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1321   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1322   case ISD::FNEG:               return visitFNEG(N);
1323   case ISD::FABS:               return visitFABS(N);
1324   case ISD::FFLOOR:             return visitFFLOOR(N);
1325   case ISD::FCEIL:              return visitFCEIL(N);
1326   case ISD::FTRUNC:             return visitFTRUNC(N);
1327   case ISD::BRCOND:             return visitBRCOND(N);
1328   case ISD::BR_CC:              return visitBR_CC(N);
1329   case ISD::LOAD:               return visitLOAD(N);
1330   case ISD::STORE:              return visitSTORE(N);
1331   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1332   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1333   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1334   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1335   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1336   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1337   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1338   }
1339   return SDValue();
1340 }
1341
1342 SDValue DAGCombiner::combine(SDNode *N) {
1343   SDValue RV = visit(N);
1344
1345   // If nothing happened, try a target-specific DAG combine.
1346   if (!RV.getNode()) {
1347     assert(N->getOpcode() != ISD::DELETED_NODE &&
1348            "Node was deleted but visit returned NULL!");
1349
1350     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1351         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1352
1353       // Expose the DAG combiner to the target combiner impls.
1354       TargetLowering::DAGCombinerInfo
1355         DagCombineInfo(DAG, Level, false, this);
1356
1357       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1358     }
1359   }
1360
1361   // If nothing happened still, try promoting the operation.
1362   if (!RV.getNode()) {
1363     switch (N->getOpcode()) {
1364     default: break;
1365     case ISD::ADD:
1366     case ISD::SUB:
1367     case ISD::MUL:
1368     case ISD::AND:
1369     case ISD::OR:
1370     case ISD::XOR:
1371       RV = PromoteIntBinOp(SDValue(N, 0));
1372       break;
1373     case ISD::SHL:
1374     case ISD::SRA:
1375     case ISD::SRL:
1376       RV = PromoteIntShiftOp(SDValue(N, 0));
1377       break;
1378     case ISD::SIGN_EXTEND:
1379     case ISD::ZERO_EXTEND:
1380     case ISD::ANY_EXTEND:
1381       RV = PromoteExtend(SDValue(N, 0));
1382       break;
1383     case ISD::LOAD:
1384       if (PromoteLoad(SDValue(N, 0)))
1385         RV = SDValue(N, 0);
1386       break;
1387     }
1388   }
1389
1390   // If N is a commutative binary node, try commuting it to enable more
1391   // sdisel CSE.
1392   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1393       N->getNumValues() == 1) {
1394     SDValue N0 = N->getOperand(0);
1395     SDValue N1 = N->getOperand(1);
1396
1397     // Constant operands are canonicalized to RHS.
1398     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1399       SDValue Ops[] = {N1, N0};
1400       SDNode *CSENode;
1401       if (const BinaryWithFlagsSDNode *BinNode =
1402               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1403         CSENode = DAG.getNodeIfExists(
1404             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1405             BinNode->hasNoSignedWrap(), BinNode->isExact());
1406       } else {
1407         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1408       }
1409       if (CSENode)
1410         return SDValue(CSENode, 0);
1411     }
1412   }
1413
1414   return RV;
1415 }
1416
1417 /// getInputChainForNode - Given a node, return its input chain if it has one,
1418 /// otherwise return a null sd operand.
1419 static SDValue getInputChainForNode(SDNode *N) {
1420   if (unsigned NumOps = N->getNumOperands()) {
1421     if (N->getOperand(0).getValueType() == MVT::Other)
1422       return N->getOperand(0);
1423     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1424       return N->getOperand(NumOps-1);
1425     for (unsigned i = 1; i < NumOps-1; ++i)
1426       if (N->getOperand(i).getValueType() == MVT::Other)
1427         return N->getOperand(i);
1428   }
1429   return SDValue();
1430 }
1431
1432 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1433   // If N has two operands, where one has an input chain equal to the other,
1434   // the 'other' chain is redundant.
1435   if (N->getNumOperands() == 2) {
1436     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1437       return N->getOperand(0);
1438     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1439       return N->getOperand(1);
1440   }
1441
1442   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1443   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1444   SmallPtrSet<SDNode*, 16> SeenOps;
1445   bool Changed = false;             // If we should replace this token factor.
1446
1447   // Start out with this token factor.
1448   TFs.push_back(N);
1449
1450   // Iterate through token factors.  The TFs grows when new token factors are
1451   // encountered.
1452   for (unsigned i = 0; i < TFs.size(); ++i) {
1453     SDNode *TF = TFs[i];
1454
1455     // Check each of the operands.
1456     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1457       SDValue Op = TF->getOperand(i);
1458
1459       switch (Op.getOpcode()) {
1460       case ISD::EntryToken:
1461         // Entry tokens don't need to be added to the list. They are
1462         // rededundant.
1463         Changed = true;
1464         break;
1465
1466       case ISD::TokenFactor:
1467         if (Op.hasOneUse() &&
1468             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1469           // Queue up for processing.
1470           TFs.push_back(Op.getNode());
1471           // Clean up in case the token factor is removed.
1472           AddToWorklist(Op.getNode());
1473           Changed = true;
1474           break;
1475         }
1476         // Fall thru
1477
1478       default:
1479         // Only add if it isn't already in the list.
1480         if (SeenOps.insert(Op.getNode()))
1481           Ops.push_back(Op);
1482         else
1483           Changed = true;
1484         break;
1485       }
1486     }
1487   }
1488
1489   SDValue Result;
1490
1491   // If we've change things around then replace token factor.
1492   if (Changed) {
1493     if (Ops.empty()) {
1494       // The entry token is the only possible outcome.
1495       Result = DAG.getEntryNode();
1496     } else {
1497       // New and improved token factor.
1498       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1499     }
1500
1501     // Don't add users to work list.
1502     return CombineTo(N, Result, false);
1503   }
1504
1505   return Result;
1506 }
1507
1508 /// MERGE_VALUES can always be eliminated.
1509 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1510   WorklistRemover DeadNodes(*this);
1511   // Replacing results may cause a different MERGE_VALUES to suddenly
1512   // be CSE'd with N, and carry its uses with it. Iterate until no
1513   // uses remain, to ensure that the node can be safely deleted.
1514   // First add the users of this node to the work list so that they
1515   // can be tried again once they have new operands.
1516   AddUsersToWorklist(N);
1517   do {
1518     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1519       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1520   } while (!N->use_empty());
1521   deleteAndRecombine(N);
1522   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1523 }
1524
1525 static
1526 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1527                               SelectionDAG &DAG) {
1528   EVT VT = N0.getValueType();
1529   SDValue N00 = N0.getOperand(0);
1530   SDValue N01 = N0.getOperand(1);
1531   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1532
1533   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1534       isa<ConstantSDNode>(N00.getOperand(1))) {
1535     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1536     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1537                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1538                                  N00.getOperand(0), N01),
1539                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1540                                  N00.getOperand(1), N01));
1541     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1542   }
1543
1544   return SDValue();
1545 }
1546
1547 SDValue DAGCombiner::visitADD(SDNode *N) {
1548   SDValue N0 = N->getOperand(0);
1549   SDValue N1 = N->getOperand(1);
1550   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1551   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1552   EVT VT = N0.getValueType();
1553
1554   // fold vector ops
1555   if (VT.isVector()) {
1556     SDValue FoldedVOp = SimplifyVBinOp(N);
1557     if (FoldedVOp.getNode()) return FoldedVOp;
1558
1559     // fold (add x, 0) -> x, vector edition
1560     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1561       return N0;
1562     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1563       return N1;
1564   }
1565
1566   // fold (add x, undef) -> undef
1567   if (N0.getOpcode() == ISD::UNDEF)
1568     return N0;
1569   if (N1.getOpcode() == ISD::UNDEF)
1570     return N1;
1571   // fold (add c1, c2) -> c1+c2
1572   if (N0C && N1C)
1573     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1574   // canonicalize constant to RHS
1575   if (N0C && !N1C)
1576     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1577   // fold (add x, 0) -> x
1578   if (N1C && N1C->isNullValue())
1579     return N0;
1580   // fold (add Sym, c) -> Sym+c
1581   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1582     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1583         GA->getOpcode() == ISD::GlobalAddress)
1584       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1585                                   GA->getOffset() +
1586                                     (uint64_t)N1C->getSExtValue());
1587   // fold ((c1-A)+c2) -> (c1+c2)-A
1588   if (N1C && N0.getOpcode() == ISD::SUB)
1589     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1590       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1591                          DAG.getConstant(N1C->getAPIntValue()+
1592                                          N0C->getAPIntValue(), VT),
1593                          N0.getOperand(1));
1594   // reassociate add
1595   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1596   if (RADD.getNode())
1597     return RADD;
1598   // fold ((0-A) + B) -> B-A
1599   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1600       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1601     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1602   // fold (A + (0-B)) -> A-B
1603   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1604       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1605     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1606   // fold (A+(B-A)) -> B
1607   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1608     return N1.getOperand(0);
1609   // fold ((B-A)+A) -> B
1610   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1611     return N0.getOperand(0);
1612   // fold (A+(B-(A+C))) to (B-C)
1613   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1614       N0 == N1.getOperand(1).getOperand(0))
1615     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1616                        N1.getOperand(1).getOperand(1));
1617   // fold (A+(B-(C+A))) to (B-C)
1618   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1619       N0 == N1.getOperand(1).getOperand(1))
1620     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1621                        N1.getOperand(1).getOperand(0));
1622   // fold (A+((B-A)+or-C)) to (B+or-C)
1623   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1624       N1.getOperand(0).getOpcode() == ISD::SUB &&
1625       N0 == N1.getOperand(0).getOperand(1))
1626     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1627                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1628
1629   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1630   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1631     SDValue N00 = N0.getOperand(0);
1632     SDValue N01 = N0.getOperand(1);
1633     SDValue N10 = N1.getOperand(0);
1634     SDValue N11 = N1.getOperand(1);
1635
1636     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1637       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1638                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1639                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1640   }
1641
1642   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1643     return SDValue(N, 0);
1644
1645   // fold (a+b) -> (a|b) iff a and b share no bits.
1646   if (VT.isInteger() && !VT.isVector()) {
1647     APInt LHSZero, LHSOne;
1648     APInt RHSZero, RHSOne;
1649     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1650
1651     if (LHSZero.getBoolValue()) {
1652       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1653
1654       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1655       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1656       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1657         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1658           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1659       }
1660     }
1661   }
1662
1663   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1664   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1665     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1666     if (Result.getNode()) return Result;
1667   }
1668   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1669     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1670     if (Result.getNode()) return Result;
1671   }
1672
1673   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1674   if (N1.getOpcode() == ISD::SHL &&
1675       N1.getOperand(0).getOpcode() == ISD::SUB)
1676     if (ConstantSDNode *C =
1677           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1678       if (C->getAPIntValue() == 0)
1679         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1680                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1681                                        N1.getOperand(0).getOperand(1),
1682                                        N1.getOperand(1)));
1683   if (N0.getOpcode() == ISD::SHL &&
1684       N0.getOperand(0).getOpcode() == ISD::SUB)
1685     if (ConstantSDNode *C =
1686           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1687       if (C->getAPIntValue() == 0)
1688         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1689                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1690                                        N0.getOperand(0).getOperand(1),
1691                                        N0.getOperand(1)));
1692
1693   if (N1.getOpcode() == ISD::AND) {
1694     SDValue AndOp0 = N1.getOperand(0);
1695     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1696     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1697     unsigned DestBits = VT.getScalarType().getSizeInBits();
1698
1699     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1700     // and similar xforms where the inner op is either ~0 or 0.
1701     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1702       SDLoc DL(N);
1703       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1704     }
1705   }
1706
1707   // add (sext i1), X -> sub X, (zext i1)
1708   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1709       N0.getOperand(0).getValueType() == MVT::i1 &&
1710       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1711     SDLoc DL(N);
1712     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1713     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1714   }
1715
1716   return SDValue();
1717 }
1718
1719 SDValue DAGCombiner::visitADDC(SDNode *N) {
1720   SDValue N0 = N->getOperand(0);
1721   SDValue N1 = N->getOperand(1);
1722   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724   EVT VT = N0.getValueType();
1725
1726   // If the flag result is dead, turn this into an ADD.
1727   if (!N->hasAnyUseOfValue(1))
1728     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1729                      DAG.getNode(ISD::CARRY_FALSE,
1730                                  SDLoc(N), MVT::Glue));
1731
1732   // canonicalize constant to RHS.
1733   if (N0C && !N1C)
1734     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1735
1736   // fold (addc x, 0) -> x + no carry out
1737   if (N1C && N1C->isNullValue())
1738     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1739                                         SDLoc(N), MVT::Glue));
1740
1741   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1742   APInt LHSZero, LHSOne;
1743   APInt RHSZero, RHSOne;
1744   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745
1746   if (LHSZero.getBoolValue()) {
1747     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748
1749     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1752       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1753                        DAG.getNode(ISD::CARRY_FALSE,
1754                                    SDLoc(N), MVT::Glue));
1755   }
1756
1757   return SDValue();
1758 }
1759
1760 SDValue DAGCombiner::visitADDE(SDNode *N) {
1761   SDValue N0 = N->getOperand(0);
1762   SDValue N1 = N->getOperand(1);
1763   SDValue CarryIn = N->getOperand(2);
1764   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766
1767   // canonicalize constant to RHS
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1770                        N1, N0, CarryIn);
1771
1772   // fold (adde x, y, false) -> (addc x, y)
1773   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1774     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1775
1776   return SDValue();
1777 }
1778
1779 // Since it may not be valid to emit a fold to zero for vector initializers
1780 // check if we can before folding.
1781 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1782                              SelectionDAG &DAG,
1783                              bool LegalOperations, bool LegalTypes) {
1784   if (!VT.isVector())
1785     return DAG.getConstant(0, VT);
1786   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1787     return DAG.getConstant(0, VT);
1788   return SDValue();
1789 }
1790
1791 SDValue DAGCombiner::visitSUB(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1796   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1797     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1798   EVT VT = N0.getValueType();
1799
1800   // fold vector ops
1801   if (VT.isVector()) {
1802     SDValue FoldedVOp = SimplifyVBinOp(N);
1803     if (FoldedVOp.getNode()) return FoldedVOp;
1804
1805     // fold (sub x, 0) -> x, vector edition
1806     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1807       return N0;
1808   }
1809
1810   // fold (sub x, x) -> 0
1811   // FIXME: Refactor this and xor and other similar operations together.
1812   if (N0 == N1)
1813     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1814   // fold (sub c1, c2) -> c1-c2
1815   if (N0C && N1C)
1816     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1817   // fold (sub x, c) -> (add x, -c)
1818   if (N1C)
1819     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1820                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1821   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1822   if (N0C && N0C->isAllOnesValue())
1823     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1824   // fold A-(A-B) -> B
1825   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1826     return N1.getOperand(1);
1827   // fold (A+B)-A -> B
1828   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1829     return N0.getOperand(1);
1830   // fold (A+B)-B -> A
1831   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1832     return N0.getOperand(0);
1833   // fold C2-(A+C1) -> (C2-C1)-A
1834   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1835     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1836                                    VT);
1837     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1838                        N1.getOperand(0));
1839   }
1840   // fold ((A+(B+or-C))-B) -> A+or-C
1841   if (N0.getOpcode() == ISD::ADD &&
1842       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1843        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1844       N0.getOperand(1).getOperand(0) == N1)
1845     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1846                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1847   // fold ((A+(C+B))-B) -> A+C
1848   if (N0.getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOpcode() == ISD::ADD &&
1850       N0.getOperand(1).getOperand(1) == N1)
1851     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1852                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1853   // fold ((A-(B-C))-C) -> A-B
1854   if (N0.getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOpcode() == ISD::SUB &&
1856       N0.getOperand(1).getOperand(1) == N1)
1857     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1858                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1859
1860   // If either operand of a sub is undef, the result is undef
1861   if (N0.getOpcode() == ISD::UNDEF)
1862     return N0;
1863   if (N1.getOpcode() == ISD::UNDEF)
1864     return N1;
1865
1866   // If the relocation model supports it, consider symbol offsets.
1867   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1868     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1869       // fold (sub Sym, c) -> Sym-c
1870       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1871         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1872                                     GA->getOffset() -
1873                                       (uint64_t)N1C->getSExtValue());
1874       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1875       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1876         if (GA->getGlobal() == GB->getGlobal())
1877           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1878                                  VT);
1879     }
1880
1881   return SDValue();
1882 }
1883
1884 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1885   SDValue N0 = N->getOperand(0);
1886   SDValue N1 = N->getOperand(1);
1887   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1888   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1889   EVT VT = N0.getValueType();
1890
1891   // If the flag result is dead, turn this into an SUB.
1892   if (!N->hasAnyUseOfValue(1))
1893     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1894                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1895                                  MVT::Glue));
1896
1897   // fold (subc x, x) -> 0 + no borrow
1898   if (N0 == N1)
1899     return CombineTo(N, DAG.getConstant(0, VT),
1900                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1901                                  MVT::Glue));
1902
1903   // fold (subc x, 0) -> x + no borrow
1904   if (N1C && N1C->isNullValue())
1905     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1906                                         MVT::Glue));
1907
1908   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1909   if (N0C && N0C->isAllOnesValue())
1910     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1911                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1912                                  MVT::Glue));
1913
1914   return SDValue();
1915 }
1916
1917 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1918   SDValue N0 = N->getOperand(0);
1919   SDValue N1 = N->getOperand(1);
1920   SDValue CarryIn = N->getOperand(2);
1921
1922   // fold (sube x, y, false) -> (subc x, y)
1923   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1924     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1925
1926   return SDValue();
1927 }
1928
1929 SDValue DAGCombiner::visitMUL(SDNode *N) {
1930   SDValue N0 = N->getOperand(0);
1931   SDValue N1 = N->getOperand(1);
1932   EVT VT = N0.getValueType();
1933
1934   // fold (mul x, undef) -> 0
1935   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1936     return DAG.getConstant(0, VT);
1937
1938   bool N0IsConst = false;
1939   bool N1IsConst = false;
1940   APInt ConstValue0, ConstValue1;
1941   // fold vector ops
1942   if (VT.isVector()) {
1943     SDValue FoldedVOp = SimplifyVBinOp(N);
1944     if (FoldedVOp.getNode()) return FoldedVOp;
1945
1946     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1947     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1948   } else {
1949     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1950     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1951                             : APInt();
1952     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1953     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1954                             : APInt();
1955   }
1956
1957   // fold (mul c1, c2) -> c1*c2
1958   if (N0IsConst && N1IsConst)
1959     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1960
1961   // canonicalize constant to RHS
1962   if (N0IsConst && !N1IsConst)
1963     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1964   // fold (mul x, 0) -> 0
1965   if (N1IsConst && ConstValue1 == 0)
1966     return N1;
1967   // We require a splat of the entire scalar bit width for non-contiguous
1968   // bit patterns.
1969   bool IsFullSplat =
1970     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1971   // fold (mul x, 1) -> x
1972   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1973     return N0;
1974   // fold (mul x, -1) -> 0-x
1975   if (N1IsConst && ConstValue1.isAllOnesValue())
1976     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1977                        DAG.getConstant(0, VT), N0);
1978   // fold (mul x, (1 << c)) -> x << c
1979   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1980     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1981                        DAG.getConstant(ConstValue1.logBase2(),
1982                                        getShiftAmountTy(N0.getValueType())));
1983   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1984   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1985     unsigned Log2Val = (-ConstValue1).logBase2();
1986     // FIXME: If the input is something that is easily negated (e.g. a
1987     // single-use add), we should put the negate there.
1988     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1989                        DAG.getConstant(0, VT),
1990                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1991                             DAG.getConstant(Log2Val,
1992                                       getShiftAmountTy(N0.getValueType()))));
1993   }
1994
1995   APInt Val;
1996   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1997   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1998       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1999                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2000     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2001                              N1, N0.getOperand(1));
2002     AddToWorklist(C3.getNode());
2003     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2004                        N0.getOperand(0), C3);
2005   }
2006
2007   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2008   // use.
2009   {
2010     SDValue Sh(nullptr,0), Y(nullptr,0);
2011     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2012     if (N0.getOpcode() == ISD::SHL &&
2013         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2014                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2015         N0.getNode()->hasOneUse()) {
2016       Sh = N0; Y = N1;
2017     } else if (N1.getOpcode() == ISD::SHL &&
2018                isa<ConstantSDNode>(N1.getOperand(1)) &&
2019                N1.getNode()->hasOneUse()) {
2020       Sh = N1; Y = N0;
2021     }
2022
2023     if (Sh.getNode()) {
2024       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2025                                 Sh.getOperand(0), Y);
2026       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2027                          Mul, Sh.getOperand(1));
2028     }
2029   }
2030
2031   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2032   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2033       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2034                      isa<ConstantSDNode>(N0.getOperand(1))))
2035     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2036                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2037                                    N0.getOperand(0), N1),
2038                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2039                                    N0.getOperand(1), N1));
2040
2041   // reassociate mul
2042   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2043   if (RMUL.getNode())
2044     return RMUL;
2045
2046   return SDValue();
2047 }
2048
2049 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2050   SDValue N0 = N->getOperand(0);
2051   SDValue N1 = N->getOperand(1);
2052   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2053   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2054   EVT VT = N->getValueType(0);
2055
2056   // fold vector ops
2057   if (VT.isVector()) {
2058     SDValue FoldedVOp = SimplifyVBinOp(N);
2059     if (FoldedVOp.getNode()) return FoldedVOp;
2060   }
2061
2062   // fold (sdiv c1, c2) -> c1/c2
2063   if (N0C && N1C && !N1C->isNullValue())
2064     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2065   // fold (sdiv X, 1) -> X
2066   if (N1C && N1C->getAPIntValue() == 1LL)
2067     return N0;
2068   // fold (sdiv X, -1) -> 0-X
2069   if (N1C && N1C->isAllOnesValue())
2070     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2071                        DAG.getConstant(0, VT), N0);
2072   // If we know the sign bits of both operands are zero, strength reduce to a
2073   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2074   if (!VT.isVector()) {
2075     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2076       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2077                          N0, N1);
2078   }
2079
2080   // fold (sdiv X, pow2) -> simple ops after legalize
2081   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2082                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2083     // If dividing by powers of two is cheap, then don't perform the following
2084     // fold.
2085     if (TLI.isPow2SDivCheap())
2086       return SDValue();
2087
2088     // Target-specific implementation of sdiv x, pow2.
2089     SDValue Res = BuildSDIVPow2(N);
2090     if (Res.getNode())
2091       return Res;
2092
2093     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2094
2095     // Splat the sign bit into the register
2096     SDValue SGN =
2097         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2098                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2099                                     getShiftAmountTy(N0.getValueType())));
2100     AddToWorklist(SGN.getNode());
2101
2102     // Add (N0 < 0) ? abs2 - 1 : 0;
2103     SDValue SRL =
2104         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2105                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2106                                     getShiftAmountTy(SGN.getValueType())));
2107     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2108     AddToWorklist(SRL.getNode());
2109     AddToWorklist(ADD.getNode());    // Divide by pow2
2110     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2111                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2112
2113     // If we're dividing by a positive value, we're done.  Otherwise, we must
2114     // negate the result.
2115     if (N1C->getAPIntValue().isNonNegative())
2116       return SRA;
2117
2118     AddToWorklist(SRA.getNode());
2119     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2120   }
2121
2122   // if integer divide is expensive and we satisfy the requirements, emit an
2123   // alternate sequence.
2124   if (N1C && !TLI.isIntDivCheap()) {
2125     SDValue Op = BuildSDIV(N);
2126     if (Op.getNode()) return Op;
2127   }
2128
2129   // undef / X -> 0
2130   if (N0.getOpcode() == ISD::UNDEF)
2131     return DAG.getConstant(0, VT);
2132   // X / undef -> undef
2133   if (N1.getOpcode() == ISD::UNDEF)
2134     return N1;
2135
2136   return SDValue();
2137 }
2138
2139 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2140   SDValue N0 = N->getOperand(0);
2141   SDValue N1 = N->getOperand(1);
2142   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2143   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2144   EVT VT = N->getValueType(0);
2145
2146   // fold vector ops
2147   if (VT.isVector()) {
2148     SDValue FoldedVOp = SimplifyVBinOp(N);
2149     if (FoldedVOp.getNode()) return FoldedVOp;
2150   }
2151
2152   // fold (udiv c1, c2) -> c1/c2
2153   if (N0C && N1C && !N1C->isNullValue())
2154     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2155   // fold (udiv x, (1 << c)) -> x >>u c
2156   if (N1C && N1C->getAPIntValue().isPowerOf2())
2157     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2158                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2159                                        getShiftAmountTy(N0.getValueType())));
2160   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2161   if (N1.getOpcode() == ISD::SHL) {
2162     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2163       if (SHC->getAPIntValue().isPowerOf2()) {
2164         EVT ADDVT = N1.getOperand(1).getValueType();
2165         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2166                                   N1.getOperand(1),
2167                                   DAG.getConstant(SHC->getAPIntValue()
2168                                                                   .logBase2(),
2169                                                   ADDVT));
2170         AddToWorklist(Add.getNode());
2171         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2172       }
2173     }
2174   }
2175   // fold (udiv x, c) -> alternate
2176   if (N1C && !TLI.isIntDivCheap()) {
2177     SDValue Op = BuildUDIV(N);
2178     if (Op.getNode()) return Op;
2179   }
2180
2181   // undef / X -> 0
2182   if (N0.getOpcode() == ISD::UNDEF)
2183     return DAG.getConstant(0, VT);
2184   // X / undef -> undef
2185   if (N1.getOpcode() == ISD::UNDEF)
2186     return N1;
2187
2188   return SDValue();
2189 }
2190
2191 SDValue DAGCombiner::visitSREM(SDNode *N) {
2192   SDValue N0 = N->getOperand(0);
2193   SDValue N1 = N->getOperand(1);
2194   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2195   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2196   EVT VT = N->getValueType(0);
2197
2198   // fold (srem c1, c2) -> c1%c2
2199   if (N0C && N1C && !N1C->isNullValue())
2200     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2201   // If we know the sign bits of both operands are zero, strength reduce to a
2202   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2203   if (!VT.isVector()) {
2204     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2205       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2206   }
2207
2208   // If X/C can be simplified by the division-by-constant logic, lower
2209   // X%C to the equivalent of X-X/C*C.
2210   if (N1C && !N1C->isNullValue()) {
2211     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2212     AddToWorklist(Div.getNode());
2213     SDValue OptimizedDiv = combine(Div.getNode());
2214     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2215       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2216                                 OptimizedDiv, N1);
2217       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2218       AddToWorklist(Mul.getNode());
2219       return Sub;
2220     }
2221   }
2222
2223   // undef % X -> 0
2224   if (N0.getOpcode() == ISD::UNDEF)
2225     return DAG.getConstant(0, VT);
2226   // X % undef -> undef
2227   if (N1.getOpcode() == ISD::UNDEF)
2228     return N1;
2229
2230   return SDValue();
2231 }
2232
2233 SDValue DAGCombiner::visitUREM(SDNode *N) {
2234   SDValue N0 = N->getOperand(0);
2235   SDValue N1 = N->getOperand(1);
2236   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2237   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2238   EVT VT = N->getValueType(0);
2239
2240   // fold (urem c1, c2) -> c1%c2
2241   if (N0C && N1C && !N1C->isNullValue())
2242     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2243   // fold (urem x, pow2) -> (and x, pow2-1)
2244   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2245     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2246                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2247   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2248   if (N1.getOpcode() == ISD::SHL) {
2249     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2250       if (SHC->getAPIntValue().isPowerOf2()) {
2251         SDValue Add =
2252           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2253                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2254                                  VT));
2255         AddToWorklist(Add.getNode());
2256         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2257       }
2258     }
2259   }
2260
2261   // If X/C can be simplified by the division-by-constant logic, lower
2262   // X%C to the equivalent of X-X/C*C.
2263   if (N1C && !N1C->isNullValue()) {
2264     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2265     AddToWorklist(Div.getNode());
2266     SDValue OptimizedDiv = combine(Div.getNode());
2267     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2268       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2269                                 OptimizedDiv, N1);
2270       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2271       AddToWorklist(Mul.getNode());
2272       return Sub;
2273     }
2274   }
2275
2276   // undef % X -> 0
2277   if (N0.getOpcode() == ISD::UNDEF)
2278     return DAG.getConstant(0, VT);
2279   // X % undef -> undef
2280   if (N1.getOpcode() == ISD::UNDEF)
2281     return N1;
2282
2283   return SDValue();
2284 }
2285
2286 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2287   SDValue N0 = N->getOperand(0);
2288   SDValue N1 = N->getOperand(1);
2289   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2290   EVT VT = N->getValueType(0);
2291   SDLoc DL(N);
2292
2293   // fold (mulhs x, 0) -> 0
2294   if (N1C && N1C->isNullValue())
2295     return N1;
2296   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2297   if (N1C && N1C->getAPIntValue() == 1)
2298     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2299                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2300                                        getShiftAmountTy(N0.getValueType())));
2301   // fold (mulhs x, undef) -> 0
2302   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2303     return DAG.getConstant(0, VT);
2304
2305   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2306   // plus a shift.
2307   if (VT.isSimple() && !VT.isVector()) {
2308     MVT Simple = VT.getSimpleVT();
2309     unsigned SimpleSize = Simple.getSizeInBits();
2310     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2313       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2314       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2315       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2316             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2317       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2318     }
2319   }
2320
2321   return SDValue();
2322 }
2323
2324 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2325   SDValue N0 = N->getOperand(0);
2326   SDValue N1 = N->getOperand(1);
2327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2328   EVT VT = N->getValueType(0);
2329   SDLoc DL(N);
2330
2331   // fold (mulhu x, 0) -> 0
2332   if (N1C && N1C->isNullValue())
2333     return N1;
2334   // fold (mulhu x, 1) -> 0
2335   if (N1C && N1C->getAPIntValue() == 1)
2336     return DAG.getConstant(0, N0.getValueType());
2337   // fold (mulhu x, undef) -> 0
2338   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2339     return DAG.getConstant(0, VT);
2340
2341   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2342   // plus a shift.
2343   if (VT.isSimple() && !VT.isVector()) {
2344     MVT Simple = VT.getSimpleVT();
2345     unsigned SimpleSize = Simple.getSizeInBits();
2346     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2347     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2348       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2349       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2350       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2351       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2352             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2353       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2354     }
2355   }
2356
2357   return SDValue();
2358 }
2359
2360 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2361 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2362 /// that are being performed. Return true if a simplification was made.
2363 ///
2364 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2365                                                 unsigned HiOp) {
2366   // If the high half is not needed, just compute the low half.
2367   bool HiExists = N->hasAnyUseOfValue(1);
2368   if (!HiExists &&
2369       (!LegalOperations ||
2370        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2371     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2372     return CombineTo(N, Res, Res);
2373   }
2374
2375   // If the low half is not needed, just compute the high half.
2376   bool LoExists = N->hasAnyUseOfValue(0);
2377   if (!LoExists &&
2378       (!LegalOperations ||
2379        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2380     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2381     return CombineTo(N, Res, Res);
2382   }
2383
2384   // If both halves are used, return as it is.
2385   if (LoExists && HiExists)
2386     return SDValue();
2387
2388   // If the two computed results can be simplified separately, separate them.
2389   if (LoExists) {
2390     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2391     AddToWorklist(Lo.getNode());
2392     SDValue LoOpt = combine(Lo.getNode());
2393     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2394         (!LegalOperations ||
2395          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2396       return CombineTo(N, LoOpt, LoOpt);
2397   }
2398
2399   if (HiExists) {
2400     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2401     AddToWorklist(Hi.getNode());
2402     SDValue HiOpt = combine(Hi.getNode());
2403     if (HiOpt.getNode() && HiOpt != Hi &&
2404         (!LegalOperations ||
2405          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2406       return CombineTo(N, HiOpt, HiOpt);
2407   }
2408
2409   return SDValue();
2410 }
2411
2412 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2413   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2414   if (Res.getNode()) return Res;
2415
2416   EVT VT = N->getValueType(0);
2417   SDLoc DL(N);
2418
2419   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2420   // plus a shift.
2421   if (VT.isSimple() && !VT.isVector()) {
2422     MVT Simple = VT.getSimpleVT();
2423     unsigned SimpleSize = Simple.getSizeInBits();
2424     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2425     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2426       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2427       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2428       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2429       // Compute the high part as N1.
2430       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2431             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2432       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2433       // Compute the low part as N0.
2434       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2435       return CombineTo(N, Lo, Hi);
2436     }
2437   }
2438
2439   return SDValue();
2440 }
2441
2442 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2443   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2444   if (Res.getNode()) return Res;
2445
2446   EVT VT = N->getValueType(0);
2447   SDLoc DL(N);
2448
2449   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2450   // plus a shift.
2451   if (VT.isSimple() && !VT.isVector()) {
2452     MVT Simple = VT.getSimpleVT();
2453     unsigned SimpleSize = Simple.getSizeInBits();
2454     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2455     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2456       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2457       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2458       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2459       // Compute the high part as N1.
2460       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2461             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2462       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2463       // Compute the low part as N0.
2464       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2465       return CombineTo(N, Lo, Hi);
2466     }
2467   }
2468
2469   return SDValue();
2470 }
2471
2472 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2473   // (smulo x, 2) -> (saddo x, x)
2474   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2475     if (C2->getAPIntValue() == 2)
2476       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2477                          N->getOperand(0), N->getOperand(0));
2478
2479   return SDValue();
2480 }
2481
2482 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2483   // (umulo x, 2) -> (uaddo x, x)
2484   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2485     if (C2->getAPIntValue() == 2)
2486       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2487                          N->getOperand(0), N->getOperand(0));
2488
2489   return SDValue();
2490 }
2491
2492 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2493   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2494   if (Res.getNode()) return Res;
2495
2496   return SDValue();
2497 }
2498
2499 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2500   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2501   if (Res.getNode()) return Res;
2502
2503   return SDValue();
2504 }
2505
2506 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2507 /// two operands of the same opcode, try to simplify it.
2508 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2509   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2510   EVT VT = N0.getValueType();
2511   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2512
2513   // Bail early if none of these transforms apply.
2514   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2515
2516   // For each of OP in AND/OR/XOR:
2517   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2518   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2519   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2520   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2521   //
2522   // do not sink logical op inside of a vector extend, since it may combine
2523   // into a vsetcc.
2524   EVT Op0VT = N0.getOperand(0).getValueType();
2525   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2526        N0.getOpcode() == ISD::SIGN_EXTEND ||
2527        // Avoid infinite looping with PromoteIntBinOp.
2528        (N0.getOpcode() == ISD::ANY_EXTEND &&
2529         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2530        (N0.getOpcode() == ISD::TRUNCATE &&
2531         (!TLI.isZExtFree(VT, Op0VT) ||
2532          !TLI.isTruncateFree(Op0VT, VT)) &&
2533         TLI.isTypeLegal(Op0VT))) &&
2534       !VT.isVector() &&
2535       Op0VT == N1.getOperand(0).getValueType() &&
2536       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2537     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2538                                  N0.getOperand(0).getValueType(),
2539                                  N0.getOperand(0), N1.getOperand(0));
2540     AddToWorklist(ORNode.getNode());
2541     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2542   }
2543
2544   // For each of OP in SHL/SRL/SRA/AND...
2545   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2546   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2547   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2548   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2549        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2550       N0.getOperand(1) == N1.getOperand(1)) {
2551     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2552                                  N0.getOperand(0).getValueType(),
2553                                  N0.getOperand(0), N1.getOperand(0));
2554     AddToWorklist(ORNode.getNode());
2555     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2556                        ORNode, N0.getOperand(1));
2557   }
2558
2559   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2560   // Only perform this optimization after type legalization and before
2561   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2562   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2563   // we don't want to undo this promotion.
2564   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2565   // on scalars.
2566   if ((N0.getOpcode() == ISD::BITCAST ||
2567        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2568       Level == AfterLegalizeTypes) {
2569     SDValue In0 = N0.getOperand(0);
2570     SDValue In1 = N1.getOperand(0);
2571     EVT In0Ty = In0.getValueType();
2572     EVT In1Ty = In1.getValueType();
2573     SDLoc DL(N);
2574     // If both incoming values are integers, and the original types are the
2575     // same.
2576     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2577       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2578       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2579       AddToWorklist(Op.getNode());
2580       return BC;
2581     }
2582   }
2583
2584   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2585   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2586   // If both shuffles use the same mask, and both shuffle within a single
2587   // vector, then it is worthwhile to move the swizzle after the operation.
2588   // The type-legalizer generates this pattern when loading illegal
2589   // vector types from memory. In many cases this allows additional shuffle
2590   // optimizations.
2591   // There are other cases where moving the shuffle after the xor/and/or
2592   // is profitable even if shuffles don't perform a swizzle.
2593   // If both shuffles use the same mask, and both shuffles have the same first
2594   // or second operand, then it might still be profitable to move the shuffle
2595   // after the xor/and/or operation.
2596   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2597     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2598     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2599
2600     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2601            "Inputs to shuffles are not the same type");
2602
2603     // Check that both shuffles use the same mask. The masks are known to be of
2604     // the same length because the result vector type is the same.
2605     // Check also that shuffles have only one use to avoid introducing extra
2606     // instructions.
2607     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2608         SVN0->getMask().equals(SVN1->getMask())) {
2609       SDValue ShOp = N0->getOperand(1);
2610
2611       // Don't try to fold this node if it requires introducing a
2612       // build vector of all zeros that might be illegal at this stage.
2613       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2614         if (!LegalTypes)
2615           ShOp = DAG.getConstant(0, VT);
2616         else
2617           ShOp = SDValue();
2618       }
2619
2620       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2621       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2622       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2623       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2624         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2625                                       N0->getOperand(0), N1->getOperand(0));
2626         AddToWorklist(NewNode.getNode());
2627         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2628                                     &SVN0->getMask()[0]);
2629       }
2630
2631       // Don't try to fold this node if it requires introducing a
2632       // build vector of all zeros that might be illegal at this stage.
2633       ShOp = N0->getOperand(0);
2634       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2635         if (!LegalTypes)
2636           ShOp = DAG.getConstant(0, VT);
2637         else
2638           ShOp = SDValue();
2639       }
2640
2641       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2642       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2643       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2644       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2645         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2646                                       N0->getOperand(1), N1->getOperand(1));
2647         AddToWorklist(NewNode.getNode());
2648         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2649                                     &SVN0->getMask()[0]);
2650       }
2651     }
2652   }
2653
2654   return SDValue();
2655 }
2656
2657 SDValue DAGCombiner::visitAND(SDNode *N) {
2658   SDValue N0 = N->getOperand(0);
2659   SDValue N1 = N->getOperand(1);
2660   SDValue LL, LR, RL, RR, CC0, CC1;
2661   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2662   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2663   EVT VT = N1.getValueType();
2664   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2665
2666   // fold vector ops
2667   if (VT.isVector()) {
2668     SDValue FoldedVOp = SimplifyVBinOp(N);
2669     if (FoldedVOp.getNode()) return FoldedVOp;
2670
2671     // fold (and x, 0) -> 0, vector edition
2672     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2673       return N0;
2674     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2675       return N1;
2676
2677     // fold (and x, -1) -> x, vector edition
2678     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2679       return N1;
2680     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2681       return N0;
2682   }
2683
2684   // fold (and x, undef) -> 0
2685   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2686     return DAG.getConstant(0, VT);
2687   // fold (and c1, c2) -> c1&c2
2688   if (N0C && N1C)
2689     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2690   // canonicalize constant to RHS
2691   if (N0C && !N1C)
2692     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2693   // fold (and x, -1) -> x
2694   if (N1C && N1C->isAllOnesValue())
2695     return N0;
2696   // if (and x, c) is known to be zero, return 0
2697   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2698                                    APInt::getAllOnesValue(BitWidth)))
2699     return DAG.getConstant(0, VT);
2700   // reassociate and
2701   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2702   if (RAND.getNode())
2703     return RAND;
2704   // fold (and (or x, C), D) -> D if (C & D) == D
2705   if (N1C && N0.getOpcode() == ISD::OR)
2706     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2707       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2708         return N1;
2709   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2710   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2711     SDValue N0Op0 = N0.getOperand(0);
2712     APInt Mask = ~N1C->getAPIntValue();
2713     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2714     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2715       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2716                                  N0.getValueType(), N0Op0);
2717
2718       // Replace uses of the AND with uses of the Zero extend node.
2719       CombineTo(N, Zext);
2720
2721       // We actually want to replace all uses of the any_extend with the
2722       // zero_extend, to avoid duplicating things.  This will later cause this
2723       // AND to be folded.
2724       CombineTo(N0.getNode(), Zext);
2725       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2726     }
2727   }
2728   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2729   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2730   // already be zero by virtue of the width of the base type of the load.
2731   //
2732   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2733   // more cases.
2734   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2735        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2736       N0.getOpcode() == ISD::LOAD) {
2737     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2738                                          N0 : N0.getOperand(0) );
2739
2740     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2741     // This can be a pure constant or a vector splat, in which case we treat the
2742     // vector as a scalar and use the splat value.
2743     APInt Constant = APInt::getNullValue(1);
2744     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2745       Constant = C->getAPIntValue();
2746     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2747       APInt SplatValue, SplatUndef;
2748       unsigned SplatBitSize;
2749       bool HasAnyUndefs;
2750       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2751                                              SplatBitSize, HasAnyUndefs);
2752       if (IsSplat) {
2753         // Undef bits can contribute to a possible optimisation if set, so
2754         // set them.
2755         SplatValue |= SplatUndef;
2756
2757         // The splat value may be something like "0x00FFFFFF", which means 0 for
2758         // the first vector value and FF for the rest, repeating. We need a mask
2759         // that will apply equally to all members of the vector, so AND all the
2760         // lanes of the constant together.
2761         EVT VT = Vector->getValueType(0);
2762         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2763
2764         // If the splat value has been compressed to a bitlength lower
2765         // than the size of the vector lane, we need to re-expand it to
2766         // the lane size.
2767         if (BitWidth > SplatBitSize)
2768           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2769                SplatBitSize < BitWidth;
2770                SplatBitSize = SplatBitSize * 2)
2771             SplatValue |= SplatValue.shl(SplatBitSize);
2772
2773         Constant = APInt::getAllOnesValue(BitWidth);
2774         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2775           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2776       }
2777     }
2778
2779     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2780     // actually legal and isn't going to get expanded, else this is a false
2781     // optimisation.
2782     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2783                                                     Load->getMemoryVT());
2784
2785     // Resize the constant to the same size as the original memory access before
2786     // extension. If it is still the AllOnesValue then this AND is completely
2787     // unneeded.
2788     Constant =
2789       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2790
2791     bool B;
2792     switch (Load->getExtensionType()) {
2793     default: B = false; break;
2794     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2795     case ISD::ZEXTLOAD:
2796     case ISD::NON_EXTLOAD: B = true; break;
2797     }
2798
2799     if (B && Constant.isAllOnesValue()) {
2800       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2801       // preserve semantics once we get rid of the AND.
2802       SDValue NewLoad(Load, 0);
2803       if (Load->getExtensionType() == ISD::EXTLOAD) {
2804         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2805                               Load->getValueType(0), SDLoc(Load),
2806                               Load->getChain(), Load->getBasePtr(),
2807                               Load->getOffset(), Load->getMemoryVT(),
2808                               Load->getMemOperand());
2809         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2810         if (Load->getNumValues() == 3) {
2811           // PRE/POST_INC loads have 3 values.
2812           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2813                            NewLoad.getValue(2) };
2814           CombineTo(Load, To, 3, true);
2815         } else {
2816           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2817         }
2818       }
2819
2820       // Fold the AND away, taking care not to fold to the old load node if we
2821       // replaced it.
2822       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2823
2824       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2825     }
2826   }
2827   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2828   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2829     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2830     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2831
2832     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2833         LL.getValueType().isInteger()) {
2834       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2835       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2836         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2837                                      LR.getValueType(), LL, RL);
2838         AddToWorklist(ORNode.getNode());
2839         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2840       }
2841       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2842       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2843         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2844                                       LR.getValueType(), LL, RL);
2845         AddToWorklist(ANDNode.getNode());
2846         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2847       }
2848       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2849       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2850         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2851                                      LR.getValueType(), LL, RL);
2852         AddToWorklist(ORNode.getNode());
2853         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2854       }
2855     }
2856     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2857     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2858         Op0 == Op1 && LL.getValueType().isInteger() &&
2859       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2860                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2861                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2862                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2863       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2864                                     LL, DAG.getConstant(1, LL.getValueType()));
2865       AddToWorklist(ADDNode.getNode());
2866       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2867                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2868     }
2869     // canonicalize equivalent to ll == rl
2870     if (LL == RR && LR == RL) {
2871       Op1 = ISD::getSetCCSwappedOperands(Op1);
2872       std::swap(RL, RR);
2873     }
2874     if (LL == RL && LR == RR) {
2875       bool isInteger = LL.getValueType().isInteger();
2876       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2877       if (Result != ISD::SETCC_INVALID &&
2878           (!LegalOperations ||
2879            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2880             TLI.isOperationLegal(ISD::SETCC,
2881                             getSetCCResultType(N0.getSimpleValueType())))))
2882         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2883                             LL, LR, Result);
2884     }
2885   }
2886
2887   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2888   if (N0.getOpcode() == N1.getOpcode()) {
2889     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2890     if (Tmp.getNode()) return Tmp;
2891   }
2892
2893   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2894   // fold (and (sra)) -> (and (srl)) when possible.
2895   if (!VT.isVector() &&
2896       SimplifyDemandedBits(SDValue(N, 0)))
2897     return SDValue(N, 0);
2898
2899   // fold (zext_inreg (extload x)) -> (zextload x)
2900   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2901     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2902     EVT MemVT = LN0->getMemoryVT();
2903     // If we zero all the possible extended bits, then we can turn this into
2904     // a zextload if we are running before legalize or the operation is legal.
2905     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2906     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2907                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2908         ((!LegalOperations && !LN0->isVolatile()) ||
2909          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2910       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2911                                        LN0->getChain(), LN0->getBasePtr(),
2912                                        MemVT, LN0->getMemOperand());
2913       AddToWorklist(N);
2914       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2915       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2916     }
2917   }
2918   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2919   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2920       N0.hasOneUse()) {
2921     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2922     EVT MemVT = LN0->getMemoryVT();
2923     // If we zero all the possible extended bits, then we can turn this into
2924     // a zextload if we are running before legalize or the operation is legal.
2925     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2926     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2927                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2928         ((!LegalOperations && !LN0->isVolatile()) ||
2929          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2930       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2931                                        LN0->getChain(), LN0->getBasePtr(),
2932                                        MemVT, LN0->getMemOperand());
2933       AddToWorklist(N);
2934       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2935       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2936     }
2937   }
2938
2939   // fold (and (load x), 255) -> (zextload x, i8)
2940   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2941   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2942   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2943               (N0.getOpcode() == ISD::ANY_EXTEND &&
2944                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2945     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2946     LoadSDNode *LN0 = HasAnyExt
2947       ? cast<LoadSDNode>(N0.getOperand(0))
2948       : cast<LoadSDNode>(N0);
2949     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2950         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2951       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2952       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2953         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2954         EVT LoadedVT = LN0->getMemoryVT();
2955
2956         if (ExtVT == LoadedVT &&
2957             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2958           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2959
2960           SDValue NewLoad =
2961             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2962                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2963                            LN0->getMemOperand());
2964           AddToWorklist(N);
2965           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2966           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2967         }
2968
2969         // Do not change the width of a volatile load.
2970         // Do not generate loads of non-round integer types since these can
2971         // be expensive (and would be wrong if the type is not byte sized).
2972         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2973             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2974           EVT PtrType = LN0->getOperand(1).getValueType();
2975
2976           unsigned Alignment = LN0->getAlignment();
2977           SDValue NewPtr = LN0->getBasePtr();
2978
2979           // For big endian targets, we need to add an offset to the pointer
2980           // to load the correct bytes.  For little endian systems, we merely
2981           // need to read fewer bytes from the same pointer.
2982           if (TLI.isBigEndian()) {
2983             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2984             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2985             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2986             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2987                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2988             Alignment = MinAlign(Alignment, PtrOff);
2989           }
2990
2991           AddToWorklist(NewPtr.getNode());
2992
2993           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2994           SDValue Load =
2995             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2996                            LN0->getChain(), NewPtr,
2997                            LN0->getPointerInfo(),
2998                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2999                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3000           AddToWorklist(N);
3001           CombineTo(LN0, Load, Load.getValue(1));
3002           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3003         }
3004       }
3005     }
3006   }
3007
3008   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3009       VT.getSizeInBits() <= 64) {
3010     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3011       APInt ADDC = ADDI->getAPIntValue();
3012       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3013         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3014         // immediate for an add, but it is legal if its top c2 bits are set,
3015         // transform the ADD so the immediate doesn't need to be materialized
3016         // in a register.
3017         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3018           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3019                                              SRLI->getZExtValue());
3020           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3021             ADDC |= Mask;
3022             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3023               SDValue NewAdd =
3024                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3025                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3026               CombineTo(N0.getNode(), NewAdd);
3027               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3028             }
3029           }
3030         }
3031       }
3032     }
3033   }
3034
3035   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3036   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3037     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3038                                        N0.getOperand(1), false);
3039     if (BSwap.getNode())
3040       return BSwap;
3041   }
3042
3043   return SDValue();
3044 }
3045
3046 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3047 ///
3048 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3049                                         bool DemandHighBits) {
3050   if (!LegalOperations)
3051     return SDValue();
3052
3053   EVT VT = N->getValueType(0);
3054   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3055     return SDValue();
3056   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3057     return SDValue();
3058
3059   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3060   bool LookPassAnd0 = false;
3061   bool LookPassAnd1 = false;
3062   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3063       std::swap(N0, N1);
3064   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3065       std::swap(N0, N1);
3066   if (N0.getOpcode() == ISD::AND) {
3067     if (!N0.getNode()->hasOneUse())
3068       return SDValue();
3069     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3070     if (!N01C || N01C->getZExtValue() != 0xFF00)
3071       return SDValue();
3072     N0 = N0.getOperand(0);
3073     LookPassAnd0 = true;
3074   }
3075
3076   if (N1.getOpcode() == ISD::AND) {
3077     if (!N1.getNode()->hasOneUse())
3078       return SDValue();
3079     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3080     if (!N11C || N11C->getZExtValue() != 0xFF)
3081       return SDValue();
3082     N1 = N1.getOperand(0);
3083     LookPassAnd1 = true;
3084   }
3085
3086   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3087     std::swap(N0, N1);
3088   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3089     return SDValue();
3090   if (!N0.getNode()->hasOneUse() ||
3091       !N1.getNode()->hasOneUse())
3092     return SDValue();
3093
3094   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3095   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3096   if (!N01C || !N11C)
3097     return SDValue();
3098   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3099     return SDValue();
3100
3101   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3102   SDValue N00 = N0->getOperand(0);
3103   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3104     if (!N00.getNode()->hasOneUse())
3105       return SDValue();
3106     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3107     if (!N001C || N001C->getZExtValue() != 0xFF)
3108       return SDValue();
3109     N00 = N00.getOperand(0);
3110     LookPassAnd0 = true;
3111   }
3112
3113   SDValue N10 = N1->getOperand(0);
3114   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3115     if (!N10.getNode()->hasOneUse())
3116       return SDValue();
3117     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3118     if (!N101C || N101C->getZExtValue() != 0xFF00)
3119       return SDValue();
3120     N10 = N10.getOperand(0);
3121     LookPassAnd1 = true;
3122   }
3123
3124   if (N00 != N10)
3125     return SDValue();
3126
3127   // Make sure everything beyond the low halfword gets set to zero since the SRL
3128   // 16 will clear the top bits.
3129   unsigned OpSizeInBits = VT.getSizeInBits();
3130   if (DemandHighBits && OpSizeInBits > 16) {
3131     // If the left-shift isn't masked out then the only way this is a bswap is
3132     // if all bits beyond the low 8 are 0. In that case the entire pattern
3133     // reduces to a left shift anyway: leave it for other parts of the combiner.
3134     if (!LookPassAnd0)
3135       return SDValue();
3136
3137     // However, if the right shift isn't masked out then it might be because
3138     // it's not needed. See if we can spot that too.
3139     if (!LookPassAnd1 &&
3140         !DAG.MaskedValueIsZero(
3141             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3142       return SDValue();
3143   }
3144
3145   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3146   if (OpSizeInBits > 16)
3147     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3148                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3149   return Res;
3150 }
3151
3152 /// isBSwapHWordElement - Return true if the specified node is an element
3153 /// that makes up a 32-bit packed halfword byteswap. i.e.
3154 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3155 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3156   if (!N.getNode()->hasOneUse())
3157     return false;
3158
3159   unsigned Opc = N.getOpcode();
3160   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3161     return false;
3162
3163   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3164   if (!N1C)
3165     return false;
3166
3167   unsigned Num;
3168   switch (N1C->getZExtValue()) {
3169   default:
3170     return false;
3171   case 0xFF:       Num = 0; break;
3172   case 0xFF00:     Num = 1; break;
3173   case 0xFF0000:   Num = 2; break;
3174   case 0xFF000000: Num = 3; break;
3175   }
3176
3177   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3178   SDValue N0 = N.getOperand(0);
3179   if (Opc == ISD::AND) {
3180     if (Num == 0 || Num == 2) {
3181       // (x >> 8) & 0xff
3182       // (x >> 8) & 0xff0000
3183       if (N0.getOpcode() != ISD::SRL)
3184         return false;
3185       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3186       if (!C || C->getZExtValue() != 8)
3187         return false;
3188     } else {
3189       // (x << 8) & 0xff00
3190       // (x << 8) & 0xff000000
3191       if (N0.getOpcode() != ISD::SHL)
3192         return false;
3193       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3194       if (!C || C->getZExtValue() != 8)
3195         return false;
3196     }
3197   } else if (Opc == ISD::SHL) {
3198     // (x & 0xff) << 8
3199     // (x & 0xff0000) << 8
3200     if (Num != 0 && Num != 2)
3201       return false;
3202     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3203     if (!C || C->getZExtValue() != 8)
3204       return false;
3205   } else { // Opc == ISD::SRL
3206     // (x & 0xff00) >> 8
3207     // (x & 0xff000000) >> 8
3208     if (Num != 1 && Num != 3)
3209       return false;
3210     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3211     if (!C || C->getZExtValue() != 8)
3212       return false;
3213   }
3214
3215   if (Parts[Num])
3216     return false;
3217
3218   Parts[Num] = N0.getOperand(0).getNode();
3219   return true;
3220 }
3221
3222 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3223 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3224 /// => (rotl (bswap x), 16)
3225 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3226   if (!LegalOperations)
3227     return SDValue();
3228
3229   EVT VT = N->getValueType(0);
3230   if (VT != MVT::i32)
3231     return SDValue();
3232   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3233     return SDValue();
3234
3235   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3236   // Look for either
3237   // (or (or (and), (and)), (or (and), (and)))
3238   // (or (or (or (and), (and)), (and)), (and))
3239   if (N0.getOpcode() != ISD::OR)
3240     return SDValue();
3241   SDValue N00 = N0.getOperand(0);
3242   SDValue N01 = N0.getOperand(1);
3243
3244   if (N1.getOpcode() == ISD::OR &&
3245       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3246     // (or (or (and), (and)), (or (and), (and)))
3247     SDValue N000 = N00.getOperand(0);
3248     if (!isBSwapHWordElement(N000, Parts))
3249       return SDValue();
3250
3251     SDValue N001 = N00.getOperand(1);
3252     if (!isBSwapHWordElement(N001, Parts))
3253       return SDValue();
3254     SDValue N010 = N01.getOperand(0);
3255     if (!isBSwapHWordElement(N010, Parts))
3256       return SDValue();
3257     SDValue N011 = N01.getOperand(1);
3258     if (!isBSwapHWordElement(N011, Parts))
3259       return SDValue();
3260   } else {
3261     // (or (or (or (and), (and)), (and)), (and))
3262     if (!isBSwapHWordElement(N1, Parts))
3263       return SDValue();
3264     if (!isBSwapHWordElement(N01, Parts))
3265       return SDValue();
3266     if (N00.getOpcode() != ISD::OR)
3267       return SDValue();
3268     SDValue N000 = N00.getOperand(0);
3269     if (!isBSwapHWordElement(N000, Parts))
3270       return SDValue();
3271     SDValue N001 = N00.getOperand(1);
3272     if (!isBSwapHWordElement(N001, Parts))
3273       return SDValue();
3274   }
3275
3276   // Make sure the parts are all coming from the same node.
3277   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3278     return SDValue();
3279
3280   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3281                               SDValue(Parts[0],0));
3282
3283   // Result of the bswap should be rotated by 16. If it's not legal, then
3284   // do  (x << 16) | (x >> 16).
3285   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3286   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3287     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3288   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3289     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3290   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3291                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3292                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3293 }
3294
3295 SDValue DAGCombiner::visitOR(SDNode *N) {
3296   SDValue N0 = N->getOperand(0);
3297   SDValue N1 = N->getOperand(1);
3298   SDValue LL, LR, RL, RR, CC0, CC1;
3299   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3300   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3301   EVT VT = N1.getValueType();
3302
3303   // fold vector ops
3304   if (VT.isVector()) {
3305     SDValue FoldedVOp = SimplifyVBinOp(N);
3306     if (FoldedVOp.getNode()) return FoldedVOp;
3307
3308     // fold (or x, 0) -> x, vector edition
3309     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3310       return N1;
3311     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3312       return N0;
3313
3314     // fold (or x, -1) -> -1, vector edition
3315     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3316       return N0;
3317     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3318       return N1;
3319
3320     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3321     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3322     // Do this only if the resulting shuffle is legal.
3323     if (isa<ShuffleVectorSDNode>(N0) &&
3324         isa<ShuffleVectorSDNode>(N1) &&
3325         // Avoid folding a node with illegal type.
3326         TLI.isTypeLegal(VT) &&
3327         N0->getOperand(1) == N1->getOperand(1) &&
3328         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3329       bool CanFold = true;
3330       unsigned NumElts = VT.getVectorNumElements();
3331       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3332       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3333       // We construct two shuffle masks:
3334       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3335       // and N1 as the second operand.
3336       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3337       // and N0 as the second operand.
3338       // We do this because OR is commutable and therefore there might be
3339       // two ways to fold this node into a shuffle.
3340       SmallVector<int,4> Mask1;
3341       SmallVector<int,4> Mask2;
3342
3343       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3344         int M0 = SV0->getMaskElt(i);
3345         int M1 = SV1->getMaskElt(i);
3346
3347         // Both shuffle indexes are undef. Propagate Undef.
3348         if (M0 < 0 && M1 < 0) {
3349           Mask1.push_back(M0);
3350           Mask2.push_back(M0);
3351           continue;
3352         }
3353
3354         if (M0 < 0 || M1 < 0 ||
3355             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3356             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3357           CanFold = false;
3358           break;
3359         }
3360
3361         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3362         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3363       }
3364
3365       if (CanFold) {
3366         // Fold this sequence only if the resulting shuffle is 'legal'.
3367         if (TLI.isShuffleMaskLegal(Mask1, VT))
3368           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3369                                       N1->getOperand(0), &Mask1[0]);
3370         if (TLI.isShuffleMaskLegal(Mask2, VT))
3371           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3372                                       N0->getOperand(0), &Mask2[0]);
3373       }
3374     }
3375   }
3376
3377   // fold (or x, undef) -> -1
3378   if (!LegalOperations &&
3379       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3380     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3381     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3382   }
3383   // fold (or c1, c2) -> c1|c2
3384   if (N0C && N1C)
3385     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3386   // canonicalize constant to RHS
3387   if (N0C && !N1C)
3388     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3389   // fold (or x, 0) -> x
3390   if (N1C && N1C->isNullValue())
3391     return N0;
3392   // fold (or x, -1) -> -1
3393   if (N1C && N1C->isAllOnesValue())
3394     return N1;
3395   // fold (or x, c) -> c iff (x & ~c) == 0
3396   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3397     return N1;
3398
3399   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3400   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3401   if (BSwap.getNode())
3402     return BSwap;
3403   BSwap = MatchBSwapHWordLow(N, N0, N1);
3404   if (BSwap.getNode())
3405     return BSwap;
3406
3407   // reassociate or
3408   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3409   if (ROR.getNode())
3410     return ROR;
3411   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3412   // iff (c1 & c2) == 0.
3413   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3414              isa<ConstantSDNode>(N0.getOperand(1))) {
3415     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3416     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3417       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3418       if (!COR.getNode())
3419         return SDValue();
3420       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3421                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3422                                      N0.getOperand(0), N1), COR);
3423     }
3424   }
3425   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3426   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3427     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3428     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3429
3430     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3431         LL.getValueType().isInteger()) {
3432       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3433       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3434       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3435           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3436         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3437                                      LR.getValueType(), LL, RL);
3438         AddToWorklist(ORNode.getNode());
3439         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3440       }
3441       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3442       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3443       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3444           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3445         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3446                                       LR.getValueType(), LL, RL);
3447         AddToWorklist(ANDNode.getNode());
3448         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3449       }
3450     }
3451     // canonicalize equivalent to ll == rl
3452     if (LL == RR && LR == RL) {
3453       Op1 = ISD::getSetCCSwappedOperands(Op1);
3454       std::swap(RL, RR);
3455     }
3456     if (LL == RL && LR == RR) {
3457       bool isInteger = LL.getValueType().isInteger();
3458       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3459       if (Result != ISD::SETCC_INVALID &&
3460           (!LegalOperations ||
3461            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3462             TLI.isOperationLegal(ISD::SETCC,
3463               getSetCCResultType(N0.getValueType())))))
3464         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3465                             LL, LR, Result);
3466     }
3467   }
3468
3469   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3470   if (N0.getOpcode() == N1.getOpcode()) {
3471     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3472     if (Tmp.getNode()) return Tmp;
3473   }
3474
3475   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3476   if (N0.getOpcode() == ISD::AND &&
3477       N1.getOpcode() == ISD::AND &&
3478       N0.getOperand(1).getOpcode() == ISD::Constant &&
3479       N1.getOperand(1).getOpcode() == ISD::Constant &&
3480       // Don't increase # computations.
3481       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3482     // We can only do this xform if we know that bits from X that are set in C2
3483     // but not in C1 are already zero.  Likewise for Y.
3484     const APInt &LHSMask =
3485       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3486     const APInt &RHSMask =
3487       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3488
3489     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3490         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3491       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3492                               N0.getOperand(0), N1.getOperand(0));
3493       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3494                          DAG.getConstant(LHSMask | RHSMask, VT));
3495     }
3496   }
3497
3498   // See if this is some rotate idiom.
3499   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3500     return SDValue(Rot, 0);
3501
3502   // Simplify the operands using demanded-bits information.
3503   if (!VT.isVector() &&
3504       SimplifyDemandedBits(SDValue(N, 0)))
3505     return SDValue(N, 0);
3506
3507   return SDValue();
3508 }
3509
3510 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3511 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3512   if (Op.getOpcode() == ISD::AND) {
3513     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3514       Mask = Op.getOperand(1);
3515       Op = Op.getOperand(0);
3516     } else {
3517       return false;
3518     }
3519   }
3520
3521   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3522     Shift = Op;
3523     return true;
3524   }
3525
3526   return false;
3527 }
3528
3529 // Return true if we can prove that, whenever Neg and Pos are both in the
3530 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3531 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3532 //
3533 //     (or (shift1 X, Neg), (shift2 X, Pos))
3534 //
3535 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3536 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3537 // to consider shift amounts with defined behavior.
3538 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3539   // If OpSize is a power of 2 then:
3540   //
3541   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3542   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3543   //
3544   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3545   // for the stronger condition:
3546   //
3547   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3548   //
3549   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3550   // we can just replace Neg with Neg' for the rest of the function.
3551   //
3552   // In other cases we check for the even stronger condition:
3553   //
3554   //     Neg == OpSize - Pos                                    [B]
3555   //
3556   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3557   // behavior if Pos == 0 (and consequently Neg == OpSize).
3558   //
3559   // We could actually use [A] whenever OpSize is a power of 2, but the
3560   // only extra cases that it would match are those uninteresting ones
3561   // where Neg and Pos are never in range at the same time.  E.g. for
3562   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3563   // as well as (sub 32, Pos), but:
3564   //
3565   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3566   //
3567   // always invokes undefined behavior for 32-bit X.
3568   //
3569   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3570   unsigned MaskLoBits = 0;
3571   if (Neg.getOpcode() == ISD::AND &&
3572       isPowerOf2_64(OpSize) &&
3573       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3574       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3575     Neg = Neg.getOperand(0);
3576     MaskLoBits = Log2_64(OpSize);
3577   }
3578
3579   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3580   if (Neg.getOpcode() != ISD::SUB)
3581     return 0;
3582   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3583   if (!NegC)
3584     return 0;
3585   SDValue NegOp1 = Neg.getOperand(1);
3586
3587   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3588   // Pos'.  The truncation is redundant for the purpose of the equality.
3589   if (MaskLoBits &&
3590       Pos.getOpcode() == ISD::AND &&
3591       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3592       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3593     Pos = Pos.getOperand(0);
3594
3595   // The condition we need is now:
3596   //
3597   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3598   //
3599   // If NegOp1 == Pos then we need:
3600   //
3601   //              OpSize & Mask == NegC & Mask
3602   //
3603   // (because "x & Mask" is a truncation and distributes through subtraction).
3604   APInt Width;
3605   if (Pos == NegOp1)
3606     Width = NegC->getAPIntValue();
3607   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3608   // Then the condition we want to prove becomes:
3609   //
3610   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3611   //
3612   // which, again because "x & Mask" is a truncation, becomes:
3613   //
3614   //                NegC & Mask == (OpSize - PosC) & Mask
3615   //              OpSize & Mask == (NegC + PosC) & Mask
3616   else if (Pos.getOpcode() == ISD::ADD &&
3617            Pos.getOperand(0) == NegOp1 &&
3618            Pos.getOperand(1).getOpcode() == ISD::Constant)
3619     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3620              NegC->getAPIntValue());
3621   else
3622     return false;
3623
3624   // Now we just need to check that OpSize & Mask == Width & Mask.
3625   if (MaskLoBits)
3626     // Opsize & Mask is 0 since Mask is Opsize - 1.
3627     return Width.getLoBits(MaskLoBits) == 0;
3628   return Width == OpSize;
3629 }
3630
3631 // A subroutine of MatchRotate used once we have found an OR of two opposite
3632 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3633 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3634 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3635 // Neg with outer conversions stripped away.
3636 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3637                                        SDValue Neg, SDValue InnerPos,
3638                                        SDValue InnerNeg, unsigned PosOpcode,
3639                                        unsigned NegOpcode, SDLoc DL) {
3640   // fold (or (shl x, (*ext y)),
3641   //          (srl x, (*ext (sub 32, y)))) ->
3642   //   (rotl x, y) or (rotr x, (sub 32, y))
3643   //
3644   // fold (or (shl x, (*ext (sub 32, y))),
3645   //          (srl x, (*ext y))) ->
3646   //   (rotr x, y) or (rotl x, (sub 32, y))
3647   EVT VT = Shifted.getValueType();
3648   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3649     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3650     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3651                        HasPos ? Pos : Neg).getNode();
3652   }
3653
3654   return nullptr;
3655 }
3656
3657 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3658 // idioms for rotate, and if the target supports rotation instructions, generate
3659 // a rot[lr].
3660 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3661   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3662   EVT VT = LHS.getValueType();
3663   if (!TLI.isTypeLegal(VT)) return nullptr;
3664
3665   // The target must have at least one rotate flavor.
3666   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3667   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3668   if (!HasROTL && !HasROTR) return nullptr;
3669
3670   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3671   SDValue LHSShift;   // The shift.
3672   SDValue LHSMask;    // AND value if any.
3673   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3674     return nullptr; // Not part of a rotate.
3675
3676   SDValue RHSShift;   // The shift.
3677   SDValue RHSMask;    // AND value if any.
3678   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3679     return nullptr; // Not part of a rotate.
3680
3681   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3682     return nullptr;   // Not shifting the same value.
3683
3684   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3685     return nullptr;   // Shifts must disagree.
3686
3687   // Canonicalize shl to left side in a shl/srl pair.
3688   if (RHSShift.getOpcode() == ISD::SHL) {
3689     std::swap(LHS, RHS);
3690     std::swap(LHSShift, RHSShift);
3691     std::swap(LHSMask , RHSMask );
3692   }
3693
3694   unsigned OpSizeInBits = VT.getSizeInBits();
3695   SDValue LHSShiftArg = LHSShift.getOperand(0);
3696   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3697   SDValue RHSShiftArg = RHSShift.getOperand(0);
3698   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3699
3700   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3701   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3702   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3703       RHSShiftAmt.getOpcode() == ISD::Constant) {
3704     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3705     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3706     if ((LShVal + RShVal) != OpSizeInBits)
3707       return nullptr;
3708
3709     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3710                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3711
3712     // If there is an AND of either shifted operand, apply it to the result.
3713     if (LHSMask.getNode() || RHSMask.getNode()) {
3714       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3715
3716       if (LHSMask.getNode()) {
3717         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3718         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3719       }
3720       if (RHSMask.getNode()) {
3721         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3722         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3723       }
3724
3725       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3726     }
3727
3728     return Rot.getNode();
3729   }
3730
3731   // If there is a mask here, and we have a variable shift, we can't be sure
3732   // that we're masking out the right stuff.
3733   if (LHSMask.getNode() || RHSMask.getNode())
3734     return nullptr;
3735
3736   // If the shift amount is sign/zext/any-extended just peel it off.
3737   SDValue LExtOp0 = LHSShiftAmt;
3738   SDValue RExtOp0 = RHSShiftAmt;
3739   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3740        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3741        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3742        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3743       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3744        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3745        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3746        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3747     LExtOp0 = LHSShiftAmt.getOperand(0);
3748     RExtOp0 = RHSShiftAmt.getOperand(0);
3749   }
3750
3751   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3752                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3753   if (TryL)
3754     return TryL;
3755
3756   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3757                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3758   if (TryR)
3759     return TryR;
3760
3761   return nullptr;
3762 }
3763
3764 SDValue DAGCombiner::visitXOR(SDNode *N) {
3765   SDValue N0 = N->getOperand(0);
3766   SDValue N1 = N->getOperand(1);
3767   SDValue LHS, RHS, CC;
3768   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3769   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3770   EVT VT = N0.getValueType();
3771
3772   // fold vector ops
3773   if (VT.isVector()) {
3774     SDValue FoldedVOp = SimplifyVBinOp(N);
3775     if (FoldedVOp.getNode()) return FoldedVOp;
3776
3777     // fold (xor x, 0) -> x, vector edition
3778     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3779       return N1;
3780     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3781       return N0;
3782   }
3783
3784   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3785   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3786     return DAG.getConstant(0, VT);
3787   // fold (xor x, undef) -> undef
3788   if (N0.getOpcode() == ISD::UNDEF)
3789     return N0;
3790   if (N1.getOpcode() == ISD::UNDEF)
3791     return N1;
3792   // fold (xor c1, c2) -> c1^c2
3793   if (N0C && N1C)
3794     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3795   // canonicalize constant to RHS
3796   if (N0C && !N1C)
3797     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3798   // fold (xor x, 0) -> x
3799   if (N1C && N1C->isNullValue())
3800     return N0;
3801   // reassociate xor
3802   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3803   if (RXOR.getNode())
3804     return RXOR;
3805
3806   // fold !(x cc y) -> (x !cc y)
3807   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3808     bool isInt = LHS.getValueType().isInteger();
3809     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3810                                                isInt);
3811
3812     if (!LegalOperations ||
3813         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3814       switch (N0.getOpcode()) {
3815       default:
3816         llvm_unreachable("Unhandled SetCC Equivalent!");
3817       case ISD::SETCC:
3818         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3819       case ISD::SELECT_CC:
3820         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3821                                N0.getOperand(3), NotCC);
3822       }
3823     }
3824   }
3825
3826   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3827   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3828       N0.getNode()->hasOneUse() &&
3829       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3830     SDValue V = N0.getOperand(0);
3831     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3832                     DAG.getConstant(1, V.getValueType()));
3833     AddToWorklist(V.getNode());
3834     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3835   }
3836
3837   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3838   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3839       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3840     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3841     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3842       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3843       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3844       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3845       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3846       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3847     }
3848   }
3849   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3850   if (N1C && N1C->isAllOnesValue() &&
3851       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3852     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3853     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3854       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3855       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3856       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3857       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3858       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3859     }
3860   }
3861   // fold (xor (and x, y), y) -> (and (not x), y)
3862   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3863       N0->getOperand(1) == N1) {
3864     SDValue X = N0->getOperand(0);
3865     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3866     AddToWorklist(NotX.getNode());
3867     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3868   }
3869   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3870   if (N1C && N0.getOpcode() == ISD::XOR) {
3871     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3872     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3873     if (N00C)
3874       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3875                          DAG.getConstant(N1C->getAPIntValue() ^
3876                                          N00C->getAPIntValue(), VT));
3877     if (N01C)
3878       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3879                          DAG.getConstant(N1C->getAPIntValue() ^
3880                                          N01C->getAPIntValue(), VT));
3881   }
3882   // fold (xor x, x) -> 0
3883   if (N0 == N1)
3884     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3885
3886   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3887   if (N0.getOpcode() == N1.getOpcode()) {
3888     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3889     if (Tmp.getNode()) return Tmp;
3890   }
3891
3892   // Simplify the expression using non-local knowledge.
3893   if (!VT.isVector() &&
3894       SimplifyDemandedBits(SDValue(N, 0)))
3895     return SDValue(N, 0);
3896
3897   return SDValue();
3898 }
3899
3900 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3901 /// the shift amount is a constant.
3902 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3903   // We can't and shouldn't fold opaque constants.
3904   if (Amt->isOpaque())
3905     return SDValue();
3906
3907   SDNode *LHS = N->getOperand(0).getNode();
3908   if (!LHS->hasOneUse()) return SDValue();
3909
3910   // We want to pull some binops through shifts, so that we have (and (shift))
3911   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3912   // thing happens with address calculations, so it's important to canonicalize
3913   // it.
3914   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3915
3916   switch (LHS->getOpcode()) {
3917   default: return SDValue();
3918   case ISD::OR:
3919   case ISD::XOR:
3920     HighBitSet = false; // We can only transform sra if the high bit is clear.
3921     break;
3922   case ISD::AND:
3923     HighBitSet = true;  // We can only transform sra if the high bit is set.
3924     break;
3925   case ISD::ADD:
3926     if (N->getOpcode() != ISD::SHL)
3927       return SDValue(); // only shl(add) not sr[al](add).
3928     HighBitSet = false; // We can only transform sra if the high bit is clear.
3929     break;
3930   }
3931
3932   // We require the RHS of the binop to be a constant and not opaque as well.
3933   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3934   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3935
3936   // FIXME: disable this unless the input to the binop is a shift by a constant.
3937   // If it is not a shift, it pessimizes some common cases like:
3938   //
3939   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3940   //    int bar(int *X, int i) { return X[i & 255]; }
3941   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3942   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3943        BinOpLHSVal->getOpcode() != ISD::SRA &&
3944        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3945       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3946     return SDValue();
3947
3948   EVT VT = N->getValueType(0);
3949
3950   // If this is a signed shift right, and the high bit is modified by the
3951   // logical operation, do not perform the transformation. The highBitSet
3952   // boolean indicates the value of the high bit of the constant which would
3953   // cause it to be modified for this operation.
3954   if (N->getOpcode() == ISD::SRA) {
3955     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3956     if (BinOpRHSSignSet != HighBitSet)
3957       return SDValue();
3958   }
3959
3960   if (!TLI.isDesirableToCommuteWithShift(LHS))
3961     return SDValue();
3962
3963   // Fold the constants, shifting the binop RHS by the shift amount.
3964   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3965                                N->getValueType(0),
3966                                LHS->getOperand(1), N->getOperand(1));
3967   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3968
3969   // Create the new shift.
3970   SDValue NewShift = DAG.getNode(N->getOpcode(),
3971                                  SDLoc(LHS->getOperand(0)),
3972                                  VT, LHS->getOperand(0), N->getOperand(1));
3973
3974   // Create the new binop.
3975   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3976 }
3977
3978 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3979   assert(N->getOpcode() == ISD::TRUNCATE);
3980   assert(N->getOperand(0).getOpcode() == ISD::AND);
3981
3982   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3983   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3984     SDValue N01 = N->getOperand(0).getOperand(1);
3985
3986     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3987       EVT TruncVT = N->getValueType(0);
3988       SDValue N00 = N->getOperand(0).getOperand(0);
3989       APInt TruncC = N01C->getAPIntValue();
3990       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3991
3992       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3993                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3994                          DAG.getConstant(TruncC, TruncVT));
3995     }
3996   }
3997
3998   return SDValue();
3999 }
4000
4001 SDValue DAGCombiner::visitRotate(SDNode *N) {
4002   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4003   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4004       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4005     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4006     if (NewOp1.getNode())
4007       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4008                          N->getOperand(0), NewOp1);
4009   }
4010   return SDValue();
4011 }
4012
4013 SDValue DAGCombiner::visitSHL(SDNode *N) {
4014   SDValue N0 = N->getOperand(0);
4015   SDValue N1 = N->getOperand(1);
4016   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4017   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4018   EVT VT = N0.getValueType();
4019   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4020
4021   // fold vector ops
4022   if (VT.isVector()) {
4023     SDValue FoldedVOp = SimplifyVBinOp(N);
4024     if (FoldedVOp.getNode()) return FoldedVOp;
4025
4026     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4027     // If setcc produces all-one true value then:
4028     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4029     if (N1CV && N1CV->isConstant()) {
4030       if (N0.getOpcode() == ISD::AND) {
4031         SDValue N00 = N0->getOperand(0);
4032         SDValue N01 = N0->getOperand(1);
4033         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4034
4035         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4036             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4037                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4038           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4039           if (C.getNode())
4040             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4041         }
4042       } else {
4043         N1C = isConstOrConstSplat(N1);
4044       }
4045     }
4046   }
4047
4048   // fold (shl c1, c2) -> c1<<c2
4049   if (N0C && N1C)
4050     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4051   // fold (shl 0, x) -> 0
4052   if (N0C && N0C->isNullValue())
4053     return N0;
4054   // fold (shl x, c >= size(x)) -> undef
4055   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4056     return DAG.getUNDEF(VT);
4057   // fold (shl x, 0) -> x
4058   if (N1C && N1C->isNullValue())
4059     return N0;
4060   // fold (shl undef, x) -> 0
4061   if (N0.getOpcode() == ISD::UNDEF)
4062     return DAG.getConstant(0, VT);
4063   // if (shl x, c) is known to be zero, return 0
4064   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4065                             APInt::getAllOnesValue(OpSizeInBits)))
4066     return DAG.getConstant(0, VT);
4067   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4068   if (N1.getOpcode() == ISD::TRUNCATE &&
4069       N1.getOperand(0).getOpcode() == ISD::AND) {
4070     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4071     if (NewOp1.getNode())
4072       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4073   }
4074
4075   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4076     return SDValue(N, 0);
4077
4078   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4079   if (N1C && N0.getOpcode() == ISD::SHL) {
4080     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4081       uint64_t c1 = N0C1->getZExtValue();
4082       uint64_t c2 = N1C->getZExtValue();
4083       if (c1 + c2 >= OpSizeInBits)
4084         return DAG.getConstant(0, VT);
4085       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4086                          DAG.getConstant(c1 + c2, N1.getValueType()));
4087     }
4088   }
4089
4090   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4091   // For this to be valid, the second form must not preserve any of the bits
4092   // that are shifted out by the inner shift in the first form.  This means
4093   // the outer shift size must be >= the number of bits added by the ext.
4094   // As a corollary, we don't care what kind of ext it is.
4095   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4096               N0.getOpcode() == ISD::ANY_EXTEND ||
4097               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4098       N0.getOperand(0).getOpcode() == ISD::SHL) {
4099     SDValue N0Op0 = N0.getOperand(0);
4100     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4101       uint64_t c1 = N0Op0C1->getZExtValue();
4102       uint64_t c2 = N1C->getZExtValue();
4103       EVT InnerShiftVT = N0Op0.getValueType();
4104       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4105       if (c2 >= OpSizeInBits - InnerShiftSize) {
4106         if (c1 + c2 >= OpSizeInBits)
4107           return DAG.getConstant(0, VT);
4108         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4109                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4110                                        N0Op0->getOperand(0)),
4111                            DAG.getConstant(c1 + c2, N1.getValueType()));
4112       }
4113     }
4114   }
4115
4116   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4117   // Only fold this if the inner zext has no other uses to avoid increasing
4118   // the total number of instructions.
4119   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4120       N0.getOperand(0).getOpcode() == ISD::SRL) {
4121     SDValue N0Op0 = N0.getOperand(0);
4122     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4123       uint64_t c1 = N0Op0C1->getZExtValue();
4124       if (c1 < VT.getScalarSizeInBits()) {
4125         uint64_t c2 = N1C->getZExtValue();
4126         if (c1 == c2) {
4127           SDValue NewOp0 = N0.getOperand(0);
4128           EVT CountVT = NewOp0.getOperand(1).getValueType();
4129           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4130                                        NewOp0, DAG.getConstant(c2, CountVT));
4131           AddToWorklist(NewSHL.getNode());
4132           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4133         }
4134       }
4135     }
4136   }
4137
4138   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4139   //                               (and (srl x, (sub c1, c2), MASK)
4140   // Only fold this if the inner shift has no other uses -- if it does, folding
4141   // this will increase the total number of instructions.
4142   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4143     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4144       uint64_t c1 = N0C1->getZExtValue();
4145       if (c1 < OpSizeInBits) {
4146         uint64_t c2 = N1C->getZExtValue();
4147         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4148         SDValue Shift;
4149         if (c2 > c1) {
4150           Mask = Mask.shl(c2 - c1);
4151           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4152                               DAG.getConstant(c2 - c1, N1.getValueType()));
4153         } else {
4154           Mask = Mask.lshr(c1 - c2);
4155           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4156                               DAG.getConstant(c1 - c2, N1.getValueType()));
4157         }
4158         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4159                            DAG.getConstant(Mask, VT));
4160       }
4161     }
4162   }
4163   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4164   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4165     unsigned BitSize = VT.getScalarSizeInBits();
4166     SDValue HiBitsMask =
4167       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4168                                             BitSize - N1C->getZExtValue()), VT);
4169     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4170                        HiBitsMask);
4171   }
4172
4173   if (N1C) {
4174     SDValue NewSHL = visitShiftByConstant(N, N1C);
4175     if (NewSHL.getNode())
4176       return NewSHL;
4177   }
4178
4179   return SDValue();
4180 }
4181
4182 SDValue DAGCombiner::visitSRA(SDNode *N) {
4183   SDValue N0 = N->getOperand(0);
4184   SDValue N1 = N->getOperand(1);
4185   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4186   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4187   EVT VT = N0.getValueType();
4188   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4189
4190   // fold vector ops
4191   if (VT.isVector()) {
4192     SDValue FoldedVOp = SimplifyVBinOp(N);
4193     if (FoldedVOp.getNode()) return FoldedVOp;
4194
4195     N1C = isConstOrConstSplat(N1);
4196   }
4197
4198   // fold (sra c1, c2) -> (sra c1, c2)
4199   if (N0C && N1C)
4200     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4201   // fold (sra 0, x) -> 0
4202   if (N0C && N0C->isNullValue())
4203     return N0;
4204   // fold (sra -1, x) -> -1
4205   if (N0C && N0C->isAllOnesValue())
4206     return N0;
4207   // fold (sra x, (setge c, size(x))) -> undef
4208   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4209     return DAG.getUNDEF(VT);
4210   // fold (sra x, 0) -> x
4211   if (N1C && N1C->isNullValue())
4212     return N0;
4213   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4214   // sext_inreg.
4215   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4216     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4217     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4218     if (VT.isVector())
4219       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4220                                ExtVT, VT.getVectorNumElements());
4221     if ((!LegalOperations ||
4222          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4223       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4224                          N0.getOperand(0), DAG.getValueType(ExtVT));
4225   }
4226
4227   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4228   if (N1C && N0.getOpcode() == ISD::SRA) {
4229     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4230       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4231       if (Sum >= OpSizeInBits)
4232         Sum = OpSizeInBits - 1;
4233       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4234                          DAG.getConstant(Sum, N1.getValueType()));
4235     }
4236   }
4237
4238   // fold (sra (shl X, m), (sub result_size, n))
4239   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4240   // result_size - n != m.
4241   // If truncate is free for the target sext(shl) is likely to result in better
4242   // code.
4243   if (N0.getOpcode() == ISD::SHL && N1C) {
4244     // Get the two constanst of the shifts, CN0 = m, CN = n.
4245     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4246     if (N01C) {
4247       LLVMContext &Ctx = *DAG.getContext();
4248       // Determine what the truncate's result bitsize and type would be.
4249       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4250
4251       if (VT.isVector())
4252         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4253
4254       // Determine the residual right-shift amount.
4255       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4256
4257       // If the shift is not a no-op (in which case this should be just a sign
4258       // extend already), the truncated to type is legal, sign_extend is legal
4259       // on that type, and the truncate to that type is both legal and free,
4260       // perform the transform.
4261       if ((ShiftAmt > 0) &&
4262           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4263           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4264           TLI.isTruncateFree(VT, TruncVT)) {
4265
4266           SDValue Amt = DAG.getConstant(ShiftAmt,
4267               getShiftAmountTy(N0.getOperand(0).getValueType()));
4268           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4269                                       N0.getOperand(0), Amt);
4270           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4271                                       Shift);
4272           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4273                              N->getValueType(0), Trunc);
4274       }
4275     }
4276   }
4277
4278   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4279   if (N1.getOpcode() == ISD::TRUNCATE &&
4280       N1.getOperand(0).getOpcode() == ISD::AND) {
4281     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4282     if (NewOp1.getNode())
4283       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4284   }
4285
4286   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4287   //      if c1 is equal to the number of bits the trunc removes
4288   if (N0.getOpcode() == ISD::TRUNCATE &&
4289       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4290        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4291       N0.getOperand(0).hasOneUse() &&
4292       N0.getOperand(0).getOperand(1).hasOneUse() &&
4293       N1C) {
4294     SDValue N0Op0 = N0.getOperand(0);
4295     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4296       unsigned LargeShiftVal = LargeShift->getZExtValue();
4297       EVT LargeVT = N0Op0.getValueType();
4298
4299       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4300         SDValue Amt =
4301           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4302                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4303         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4304                                   N0Op0.getOperand(0), Amt);
4305         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4306       }
4307     }
4308   }
4309
4310   // Simplify, based on bits shifted out of the LHS.
4311   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4312     return SDValue(N, 0);
4313
4314
4315   // If the sign bit is known to be zero, switch this to a SRL.
4316   if (DAG.SignBitIsZero(N0))
4317     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4318
4319   if (N1C) {
4320     SDValue NewSRA = visitShiftByConstant(N, N1C);
4321     if (NewSRA.getNode())
4322       return NewSRA;
4323   }
4324
4325   return SDValue();
4326 }
4327
4328 SDValue DAGCombiner::visitSRL(SDNode *N) {
4329   SDValue N0 = N->getOperand(0);
4330   SDValue N1 = N->getOperand(1);
4331   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4332   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4333   EVT VT = N0.getValueType();
4334   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4335
4336   // fold vector ops
4337   if (VT.isVector()) {
4338     SDValue FoldedVOp = SimplifyVBinOp(N);
4339     if (FoldedVOp.getNode()) return FoldedVOp;
4340
4341     N1C = isConstOrConstSplat(N1);
4342   }
4343
4344   // fold (srl c1, c2) -> c1 >>u c2
4345   if (N0C && N1C)
4346     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4347   // fold (srl 0, x) -> 0
4348   if (N0C && N0C->isNullValue())
4349     return N0;
4350   // fold (srl x, c >= size(x)) -> undef
4351   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4352     return DAG.getUNDEF(VT);
4353   // fold (srl x, 0) -> x
4354   if (N1C && N1C->isNullValue())
4355     return N0;
4356   // if (srl x, c) is known to be zero, return 0
4357   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4358                                    APInt::getAllOnesValue(OpSizeInBits)))
4359     return DAG.getConstant(0, VT);
4360
4361   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4362   if (N1C && N0.getOpcode() == ISD::SRL) {
4363     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4364       uint64_t c1 = N01C->getZExtValue();
4365       uint64_t c2 = N1C->getZExtValue();
4366       if (c1 + c2 >= OpSizeInBits)
4367         return DAG.getConstant(0, VT);
4368       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4369                          DAG.getConstant(c1 + c2, N1.getValueType()));
4370     }
4371   }
4372
4373   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4374   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4375       N0.getOperand(0).getOpcode() == ISD::SRL &&
4376       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4377     uint64_t c1 =
4378       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4379     uint64_t c2 = N1C->getZExtValue();
4380     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4381     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4382     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4383     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4384     if (c1 + OpSizeInBits == InnerShiftSize) {
4385       if (c1 + c2 >= InnerShiftSize)
4386         return DAG.getConstant(0, VT);
4387       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4388                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4389                                      N0.getOperand(0)->getOperand(0),
4390                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4391     }
4392   }
4393
4394   // fold (srl (shl x, c), c) -> (and x, cst2)
4395   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4396     unsigned BitSize = N0.getScalarValueSizeInBits();
4397     if (BitSize <= 64) {
4398       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4399       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4400                          DAG.getConstant(~0ULL >> ShAmt, VT));
4401     }
4402   }
4403
4404   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4405   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4406     // Shifting in all undef bits?
4407     EVT SmallVT = N0.getOperand(0).getValueType();
4408     unsigned BitSize = SmallVT.getScalarSizeInBits();
4409     if (N1C->getZExtValue() >= BitSize)
4410       return DAG.getUNDEF(VT);
4411
4412     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4413       uint64_t ShiftAmt = N1C->getZExtValue();
4414       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4415                                        N0.getOperand(0),
4416                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4417       AddToWorklist(SmallShift.getNode());
4418       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4419       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4420                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4421                          DAG.getConstant(Mask, VT));
4422     }
4423   }
4424
4425   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4426   // bit, which is unmodified by sra.
4427   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4428     if (N0.getOpcode() == ISD::SRA)
4429       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4430   }
4431
4432   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4433   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4434       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4435     APInt KnownZero, KnownOne;
4436     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4437
4438     // If any of the input bits are KnownOne, then the input couldn't be all
4439     // zeros, thus the result of the srl will always be zero.
4440     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4441
4442     // If all of the bits input the to ctlz node are known to be zero, then
4443     // the result of the ctlz is "32" and the result of the shift is one.
4444     APInt UnknownBits = ~KnownZero;
4445     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4446
4447     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4448     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4449       // Okay, we know that only that the single bit specified by UnknownBits
4450       // could be set on input to the CTLZ node. If this bit is set, the SRL
4451       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4452       // to an SRL/XOR pair, which is likely to simplify more.
4453       unsigned ShAmt = UnknownBits.countTrailingZeros();
4454       SDValue Op = N0.getOperand(0);
4455
4456       if (ShAmt) {
4457         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4458                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4459         AddToWorklist(Op.getNode());
4460       }
4461
4462       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4463                          Op, DAG.getConstant(1, VT));
4464     }
4465   }
4466
4467   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4468   if (N1.getOpcode() == ISD::TRUNCATE &&
4469       N1.getOperand(0).getOpcode() == ISD::AND) {
4470     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4471     if (NewOp1.getNode())
4472       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4473   }
4474
4475   // fold operands of srl based on knowledge that the low bits are not
4476   // demanded.
4477   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4478     return SDValue(N, 0);
4479
4480   if (N1C) {
4481     SDValue NewSRL = visitShiftByConstant(N, N1C);
4482     if (NewSRL.getNode())
4483       return NewSRL;
4484   }
4485
4486   // Attempt to convert a srl of a load into a narrower zero-extending load.
4487   SDValue NarrowLoad = ReduceLoadWidth(N);
4488   if (NarrowLoad.getNode())
4489     return NarrowLoad;
4490
4491   // Here is a common situation. We want to optimize:
4492   //
4493   //   %a = ...
4494   //   %b = and i32 %a, 2
4495   //   %c = srl i32 %b, 1
4496   //   brcond i32 %c ...
4497   //
4498   // into
4499   //
4500   //   %a = ...
4501   //   %b = and %a, 2
4502   //   %c = setcc eq %b, 0
4503   //   brcond %c ...
4504   //
4505   // However when after the source operand of SRL is optimized into AND, the SRL
4506   // itself may not be optimized further. Look for it and add the BRCOND into
4507   // the worklist.
4508   if (N->hasOneUse()) {
4509     SDNode *Use = *N->use_begin();
4510     if (Use->getOpcode() == ISD::BRCOND)
4511       AddToWorklist(Use);
4512     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4513       // Also look pass the truncate.
4514       Use = *Use->use_begin();
4515       if (Use->getOpcode() == ISD::BRCOND)
4516         AddToWorklist(Use);
4517     }
4518   }
4519
4520   return SDValue();
4521 }
4522
4523 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4524   SDValue N0 = N->getOperand(0);
4525   EVT VT = N->getValueType(0);
4526
4527   // fold (ctlz c1) -> c2
4528   if (isa<ConstantSDNode>(N0))
4529     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4530   return SDValue();
4531 }
4532
4533 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4534   SDValue N0 = N->getOperand(0);
4535   EVT VT = N->getValueType(0);
4536
4537   // fold (ctlz_zero_undef c1) -> c2
4538   if (isa<ConstantSDNode>(N0))
4539     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4540   return SDValue();
4541 }
4542
4543 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4544   SDValue N0 = N->getOperand(0);
4545   EVT VT = N->getValueType(0);
4546
4547   // fold (cttz c1) -> c2
4548   if (isa<ConstantSDNode>(N0))
4549     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4550   return SDValue();
4551 }
4552
4553 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4554   SDValue N0 = N->getOperand(0);
4555   EVT VT = N->getValueType(0);
4556
4557   // fold (cttz_zero_undef c1) -> c2
4558   if (isa<ConstantSDNode>(N0))
4559     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4560   return SDValue();
4561 }
4562
4563 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4564   SDValue N0 = N->getOperand(0);
4565   EVT VT = N->getValueType(0);
4566
4567   // fold (ctpop c1) -> c2
4568   if (isa<ConstantSDNode>(N0))
4569     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4570   return SDValue();
4571 }
4572
4573 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4574   SDValue N0 = N->getOperand(0);
4575   SDValue N1 = N->getOperand(1);
4576   SDValue N2 = N->getOperand(2);
4577   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4578   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4579   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4580   EVT VT = N->getValueType(0);
4581   EVT VT0 = N0.getValueType();
4582
4583   // fold (select C, X, X) -> X
4584   if (N1 == N2)
4585     return N1;
4586   // fold (select true, X, Y) -> X
4587   if (N0C && !N0C->isNullValue())
4588     return N1;
4589   // fold (select false, X, Y) -> Y
4590   if (N0C && N0C->isNullValue())
4591     return N2;
4592   // fold (select C, 1, X) -> (or C, X)
4593   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4594     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4595   // fold (select C, 0, 1) -> (xor C, 1)
4596   // We can't do this reliably if integer based booleans have different contents
4597   // to floating point based booleans. This is because we can't tell whether we
4598   // have an integer-based boolean or a floating-point-based boolean unless we
4599   // can find the SETCC that produced it and inspect its operands. This is
4600   // fairly easy if C is the SETCC node, but it can potentially be
4601   // undiscoverable (or not reasonably discoverable). For example, it could be
4602   // in another basic block or it could require searching a complicated
4603   // expression.
4604   if (VT.isInteger() &&
4605       (VT0 == MVT::i1 || (VT0.isInteger() &&
4606                           TLI.getBooleanContents(false, false) ==
4607                               TLI.getBooleanContents(false, true) &&
4608                           TLI.getBooleanContents(false, false) ==
4609                               TargetLowering::ZeroOrOneBooleanContent)) &&
4610       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4611     SDValue XORNode;
4612     if (VT == VT0)
4613       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4614                          N0, DAG.getConstant(1, VT0));
4615     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4616                           N0, DAG.getConstant(1, VT0));
4617     AddToWorklist(XORNode.getNode());
4618     if (VT.bitsGT(VT0))
4619       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4620     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4621   }
4622   // fold (select C, 0, X) -> (and (not C), X)
4623   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4624     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4625     AddToWorklist(NOTNode.getNode());
4626     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4627   }
4628   // fold (select C, X, 1) -> (or (not C), X)
4629   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4630     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4631     AddToWorklist(NOTNode.getNode());
4632     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4633   }
4634   // fold (select C, X, 0) -> (and C, X)
4635   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4636     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4637   // fold (select X, X, Y) -> (or X, Y)
4638   // fold (select X, 1, Y) -> (or X, Y)
4639   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4640     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4641   // fold (select X, Y, X) -> (and X, Y)
4642   // fold (select X, Y, 0) -> (and X, Y)
4643   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4644     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4645
4646   // If we can fold this based on the true/false value, do so.
4647   if (SimplifySelectOps(N, N1, N2))
4648     return SDValue(N, 0);  // Don't revisit N.
4649
4650   // fold selects based on a setcc into other things, such as min/max/abs
4651   if (N0.getOpcode() == ISD::SETCC) {
4652     if ((!LegalOperations &&
4653          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4654         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4655       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4656                          N0.getOperand(0), N0.getOperand(1),
4657                          N1, N2, N0.getOperand(2));
4658     return SimplifySelect(SDLoc(N), N0, N1, N2);
4659   }
4660
4661   return SDValue();
4662 }
4663
4664 static
4665 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4666   SDLoc DL(N);
4667   EVT LoVT, HiVT;
4668   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4669
4670   // Split the inputs.
4671   SDValue Lo, Hi, LL, LH, RL, RH;
4672   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4673   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4674
4675   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4676   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4677
4678   return std::make_pair(Lo, Hi);
4679 }
4680
4681 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4682 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4683 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4684   SDLoc dl(N);
4685   SDValue Cond = N->getOperand(0);
4686   SDValue LHS = N->getOperand(1);
4687   SDValue RHS = N->getOperand(2);
4688   EVT VT = N->getValueType(0);
4689   int NumElems = VT.getVectorNumElements();
4690   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4692          Cond.getOpcode() == ISD::BUILD_VECTOR);
4693
4694   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4695   // binary ones here.
4696   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4697     return SDValue();
4698
4699   // We're sure we have an even number of elements due to the
4700   // concat_vectors we have as arguments to vselect.
4701   // Skip BV elements until we find one that's not an UNDEF
4702   // After we find an UNDEF element, keep looping until we get to half the
4703   // length of the BV and see if all the non-undef nodes are the same.
4704   ConstantSDNode *BottomHalf = nullptr;
4705   for (int i = 0; i < NumElems / 2; ++i) {
4706     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4707       continue;
4708
4709     if (BottomHalf == nullptr)
4710       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4711     else if (Cond->getOperand(i).getNode() != BottomHalf)
4712       return SDValue();
4713   }
4714
4715   // Do the same for the second half of the BuildVector
4716   ConstantSDNode *TopHalf = nullptr;
4717   for (int i = NumElems / 2; i < NumElems; ++i) {
4718     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4719       continue;
4720
4721     if (TopHalf == nullptr)
4722       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4723     else if (Cond->getOperand(i).getNode() != TopHalf)
4724       return SDValue();
4725   }
4726
4727   assert(TopHalf && BottomHalf &&
4728          "One half of the selector was all UNDEFs and the other was all the "
4729          "same value. This should have been addressed before this function.");
4730   return DAG.getNode(
4731       ISD::CONCAT_VECTORS, dl, VT,
4732       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4733       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4734 }
4735
4736 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4737   SDValue N0 = N->getOperand(0);
4738   SDValue N1 = N->getOperand(1);
4739   SDValue N2 = N->getOperand(2);
4740   SDLoc DL(N);
4741
4742   // Canonicalize integer abs.
4743   // vselect (setg[te] X,  0),  X, -X ->
4744   // vselect (setgt    X, -1),  X, -X ->
4745   // vselect (setl[te] X,  0), -X,  X ->
4746   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4747   if (N0.getOpcode() == ISD::SETCC) {
4748     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4749     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4750     bool isAbs = false;
4751     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4752
4753     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4754          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4755         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4756       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4757     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4758              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4759       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4760
4761     if (isAbs) {
4762       EVT VT = LHS.getValueType();
4763       SDValue Shift = DAG.getNode(
4764           ISD::SRA, DL, VT, LHS,
4765           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4766       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4767       AddToWorklist(Shift.getNode());
4768       AddToWorklist(Add.getNode());
4769       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4770     }
4771   }
4772
4773   // If the VSELECT result requires splitting and the mask is provided by a
4774   // SETCC, then split both nodes and its operands before legalization. This
4775   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4776   // and enables future optimizations (e.g. min/max pattern matching on X86).
4777   if (N0.getOpcode() == ISD::SETCC) {
4778     EVT VT = N->getValueType(0);
4779
4780     // Check if any splitting is required.
4781     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4782         TargetLowering::TypeSplitVector)
4783       return SDValue();
4784
4785     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4786     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4787     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4788     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4789
4790     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4791     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4792
4793     // Add the new VSELECT nodes to the work list in case they need to be split
4794     // again.
4795     AddToWorklist(Lo.getNode());
4796     AddToWorklist(Hi.getNode());
4797
4798     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4799   }
4800
4801   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4802   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4803     return N1;
4804   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4805   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4806     return N2;
4807
4808   // The ConvertSelectToConcatVector function is assuming both the above
4809   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4810   // and addressed.
4811   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4812       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4813       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4814     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4815     if (CV.getNode())
4816       return CV;
4817   }
4818
4819   return SDValue();
4820 }
4821
4822 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4823   SDValue N0 = N->getOperand(0);
4824   SDValue N1 = N->getOperand(1);
4825   SDValue N2 = N->getOperand(2);
4826   SDValue N3 = N->getOperand(3);
4827   SDValue N4 = N->getOperand(4);
4828   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4829
4830   // fold select_cc lhs, rhs, x, x, cc -> x
4831   if (N2 == N3)
4832     return N2;
4833
4834   // Determine if the condition we're dealing with is constant
4835   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4836                               N0, N1, CC, SDLoc(N), false);
4837   if (SCC.getNode()) {
4838     AddToWorklist(SCC.getNode());
4839
4840     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4841       if (!SCCC->isNullValue())
4842         return N2;    // cond always true -> true val
4843       else
4844         return N3;    // cond always false -> false val
4845     }
4846
4847     // Fold to a simpler select_cc
4848     if (SCC.getOpcode() == ISD::SETCC)
4849       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4850                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4851                          SCC.getOperand(2));
4852   }
4853
4854   // If we can fold this based on the true/false value, do so.
4855   if (SimplifySelectOps(N, N2, N3))
4856     return SDValue(N, 0);  // Don't revisit N.
4857
4858   // fold select_cc into other things, such as min/max/abs
4859   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4860 }
4861
4862 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4863   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4864                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4865                        SDLoc(N));
4866 }
4867
4868 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4869 // dag node into a ConstantSDNode or a build_vector of constants.
4870 // This function is called by the DAGCombiner when visiting sext/zext/aext
4871 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4872 // Vector extends are not folded if operations are legal; this is to
4873 // avoid introducing illegal build_vector dag nodes.
4874 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4875                                          SelectionDAG &DAG, bool LegalTypes,
4876                                          bool LegalOperations) {
4877   unsigned Opcode = N->getOpcode();
4878   SDValue N0 = N->getOperand(0);
4879   EVT VT = N->getValueType(0);
4880
4881   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4882          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4883
4884   // fold (sext c1) -> c1
4885   // fold (zext c1) -> c1
4886   // fold (aext c1) -> c1
4887   if (isa<ConstantSDNode>(N0))
4888     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4889
4890   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4891   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4892   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4893   EVT SVT = VT.getScalarType();
4894   if (!(VT.isVector() &&
4895       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4896       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4897     return nullptr;
4898
4899   // We can fold this node into a build_vector.
4900   unsigned VTBits = SVT.getSizeInBits();
4901   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4902   unsigned ShAmt = VTBits - EVTBits;
4903   SmallVector<SDValue, 8> Elts;
4904   unsigned NumElts = N0->getNumOperands();
4905   SDLoc DL(N);
4906
4907   for (unsigned i=0; i != NumElts; ++i) {
4908     SDValue Op = N0->getOperand(i);
4909     if (Op->getOpcode() == ISD::UNDEF) {
4910       Elts.push_back(DAG.getUNDEF(SVT));
4911       continue;
4912     }
4913
4914     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4915     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4916     if (Opcode == ISD::SIGN_EXTEND)
4917       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4918                                      SVT));
4919     else
4920       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4921                                      SVT));
4922   }
4923
4924   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4925 }
4926
4927 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4928 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4929 // transformation. Returns true if extension are possible and the above
4930 // mentioned transformation is profitable.
4931 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4932                                     unsigned ExtOpc,
4933                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4934                                     const TargetLowering &TLI) {
4935   bool HasCopyToRegUses = false;
4936   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4937   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4938                             UE = N0.getNode()->use_end();
4939        UI != UE; ++UI) {
4940     SDNode *User = *UI;
4941     if (User == N)
4942       continue;
4943     if (UI.getUse().getResNo() != N0.getResNo())
4944       continue;
4945     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4946     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4947       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4948       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4949         // Sign bits will be lost after a zext.
4950         return false;
4951       bool Add = false;
4952       for (unsigned i = 0; i != 2; ++i) {
4953         SDValue UseOp = User->getOperand(i);
4954         if (UseOp == N0)
4955           continue;
4956         if (!isa<ConstantSDNode>(UseOp))
4957           return false;
4958         Add = true;
4959       }
4960       if (Add)
4961         ExtendNodes.push_back(User);
4962       continue;
4963     }
4964     // If truncates aren't free and there are users we can't
4965     // extend, it isn't worthwhile.
4966     if (!isTruncFree)
4967       return false;
4968     // Remember if this value is live-out.
4969     if (User->getOpcode() == ISD::CopyToReg)
4970       HasCopyToRegUses = true;
4971   }
4972
4973   if (HasCopyToRegUses) {
4974     bool BothLiveOut = false;
4975     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4976          UI != UE; ++UI) {
4977       SDUse &Use = UI.getUse();
4978       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4979         BothLiveOut = true;
4980         break;
4981       }
4982     }
4983     if (BothLiveOut)
4984       // Both unextended and extended values are live out. There had better be
4985       // a good reason for the transformation.
4986       return ExtendNodes.size();
4987   }
4988   return true;
4989 }
4990
4991 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4992                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4993                                   ISD::NodeType ExtType) {
4994   // Extend SetCC uses if necessary.
4995   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4996     SDNode *SetCC = SetCCs[i];
4997     SmallVector<SDValue, 4> Ops;
4998
4999     for (unsigned j = 0; j != 2; ++j) {
5000       SDValue SOp = SetCC->getOperand(j);
5001       if (SOp == Trunc)
5002         Ops.push_back(ExtLoad);
5003       else
5004         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5005     }
5006
5007     Ops.push_back(SetCC->getOperand(2));
5008     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5009   }
5010 }
5011
5012 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5013   SDValue N0 = N->getOperand(0);
5014   EVT VT = N->getValueType(0);
5015
5016   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5017                                               LegalOperations))
5018     return SDValue(Res, 0);
5019
5020   // fold (sext (sext x)) -> (sext x)
5021   // fold (sext (aext x)) -> (sext x)
5022   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5023     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5024                        N0.getOperand(0));
5025
5026   if (N0.getOpcode() == ISD::TRUNCATE) {
5027     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5028     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5029     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5030     if (NarrowLoad.getNode()) {
5031       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5032       if (NarrowLoad.getNode() != N0.getNode()) {
5033         CombineTo(N0.getNode(), NarrowLoad);
5034         // CombineTo deleted the truncate, if needed, but not what's under it.
5035         AddToWorklist(oye);
5036       }
5037       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5038     }
5039
5040     // See if the value being truncated is already sign extended.  If so, just
5041     // eliminate the trunc/sext pair.
5042     SDValue Op = N0.getOperand(0);
5043     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5044     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5045     unsigned DestBits = VT.getScalarType().getSizeInBits();
5046     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5047
5048     if (OpBits == DestBits) {
5049       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5050       // bits, it is already ready.
5051       if (NumSignBits > DestBits-MidBits)
5052         return Op;
5053     } else if (OpBits < DestBits) {
5054       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5055       // bits, just sext from i32.
5056       if (NumSignBits > OpBits-MidBits)
5057         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5058     } else {
5059       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5060       // bits, just truncate to i32.
5061       if (NumSignBits > OpBits-MidBits)
5062         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5063     }
5064
5065     // fold (sext (truncate x)) -> (sextinreg x).
5066     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5067                                                  N0.getValueType())) {
5068       if (OpBits < DestBits)
5069         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5070       else if (OpBits > DestBits)
5071         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5072       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5073                          DAG.getValueType(N0.getValueType()));
5074     }
5075   }
5076
5077   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5078   // None of the supported targets knows how to perform load and sign extend
5079   // on vectors in one instruction.  We only perform this transformation on
5080   // scalars.
5081   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5082       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5083       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5084        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5085     bool DoXform = true;
5086     SmallVector<SDNode*, 4> SetCCs;
5087     if (!N0.hasOneUse())
5088       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5089     if (DoXform) {
5090       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5091       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5092                                        LN0->getChain(),
5093                                        LN0->getBasePtr(), N0.getValueType(),
5094                                        LN0->getMemOperand());
5095       CombineTo(N, ExtLoad);
5096       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5097                                   N0.getValueType(), ExtLoad);
5098       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5099       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5100                       ISD::SIGN_EXTEND);
5101       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5102     }
5103   }
5104
5105   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5106   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5107   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5108       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5109     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5110     EVT MemVT = LN0->getMemoryVT();
5111     if ((!LegalOperations && !LN0->isVolatile()) ||
5112         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5113       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5114                                        LN0->getChain(),
5115                                        LN0->getBasePtr(), MemVT,
5116                                        LN0->getMemOperand());
5117       CombineTo(N, ExtLoad);
5118       CombineTo(N0.getNode(),
5119                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5120                             N0.getValueType(), ExtLoad),
5121                 ExtLoad.getValue(1));
5122       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5123     }
5124   }
5125
5126   // fold (sext (and/or/xor (load x), cst)) ->
5127   //      (and/or/xor (sextload x), (sext cst))
5128   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5129        N0.getOpcode() == ISD::XOR) &&
5130       isa<LoadSDNode>(N0.getOperand(0)) &&
5131       N0.getOperand(1).getOpcode() == ISD::Constant &&
5132       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5133       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5134     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5135     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5136       bool DoXform = true;
5137       SmallVector<SDNode*, 4> SetCCs;
5138       if (!N0.hasOneUse())
5139         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5140                                           SetCCs, TLI);
5141       if (DoXform) {
5142         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5143                                          LN0->getChain(), LN0->getBasePtr(),
5144                                          LN0->getMemoryVT(),
5145                                          LN0->getMemOperand());
5146         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5147         Mask = Mask.sext(VT.getSizeInBits());
5148         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5149                                   ExtLoad, DAG.getConstant(Mask, VT));
5150         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5151                                     SDLoc(N0.getOperand(0)),
5152                                     N0.getOperand(0).getValueType(), ExtLoad);
5153         CombineTo(N, And);
5154         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5155         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5156                         ISD::SIGN_EXTEND);
5157         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5158       }
5159     }
5160   }
5161
5162   if (N0.getOpcode() == ISD::SETCC) {
5163     EVT N0VT = N0.getOperand(0).getValueType();
5164     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5165     // Only do this before legalize for now.
5166     if (VT.isVector() && !LegalOperations &&
5167         TLI.getBooleanContents(N0VT) ==
5168             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5169       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5170       // of the same size as the compared operands. Only optimize sext(setcc())
5171       // if this is the case.
5172       EVT SVT = getSetCCResultType(N0VT);
5173
5174       // We know that the # elements of the results is the same as the
5175       // # elements of the compare (and the # elements of the compare result
5176       // for that matter).  Check to see that they are the same size.  If so,
5177       // we know that the element size of the sext'd result matches the
5178       // element size of the compare operands.
5179       if (VT.getSizeInBits() == SVT.getSizeInBits())
5180         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5181                              N0.getOperand(1),
5182                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5183
5184       // If the desired elements are smaller or larger than the source
5185       // elements we can use a matching integer vector type and then
5186       // truncate/sign extend
5187       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5188       if (SVT == MatchingVectorType) {
5189         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5190                                N0.getOperand(0), N0.getOperand(1),
5191                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5192         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5193       }
5194     }
5195
5196     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5197     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5198     SDValue NegOne =
5199       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5200     SDValue SCC =
5201       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5202                        NegOne, DAG.getConstant(0, VT),
5203                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5204     if (SCC.getNode()) return SCC;
5205
5206     if (!VT.isVector()) {
5207       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5208       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5209         SDLoc DL(N);
5210         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5211         SDValue SetCC = DAG.getSetCC(DL,
5212                                      SetCCVT,
5213                                      N0.getOperand(0), N0.getOperand(1), CC);
5214         EVT SelectVT = getSetCCResultType(VT);
5215         return DAG.getSelect(DL, VT,
5216                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5217                              NegOne, DAG.getConstant(0, VT));
5218
5219       }
5220     }
5221   }
5222
5223   // fold (sext x) -> (zext x) if the sign bit is known zero.
5224   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5225       DAG.SignBitIsZero(N0))
5226     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5227
5228   return SDValue();
5229 }
5230
5231 // isTruncateOf - If N is a truncate of some other value, return true, record
5232 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5233 // This function computes KnownZero to avoid a duplicated call to
5234 // computeKnownBits in the caller.
5235 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5236                          APInt &KnownZero) {
5237   APInt KnownOne;
5238   if (N->getOpcode() == ISD::TRUNCATE) {
5239     Op = N->getOperand(0);
5240     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5241     return true;
5242   }
5243
5244   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5245       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5246     return false;
5247
5248   SDValue Op0 = N->getOperand(0);
5249   SDValue Op1 = N->getOperand(1);
5250   assert(Op0.getValueType() == Op1.getValueType());
5251
5252   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5253   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5254   if (COp0 && COp0->isNullValue())
5255     Op = Op1;
5256   else if (COp1 && COp1->isNullValue())
5257     Op = Op0;
5258   else
5259     return false;
5260
5261   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5262
5263   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5264     return false;
5265
5266   return true;
5267 }
5268
5269 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5270   SDValue N0 = N->getOperand(0);
5271   EVT VT = N->getValueType(0);
5272
5273   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5274                                               LegalOperations))
5275     return SDValue(Res, 0);
5276
5277   // fold (zext (zext x)) -> (zext x)
5278   // fold (zext (aext x)) -> (zext x)
5279   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5280     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5281                        N0.getOperand(0));
5282
5283   // fold (zext (truncate x)) -> (zext x) or
5284   //      (zext (truncate x)) -> (truncate x)
5285   // This is valid when the truncated bits of x are already zero.
5286   // FIXME: We should extend this to work for vectors too.
5287   SDValue Op;
5288   APInt KnownZero;
5289   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5290     APInt TruncatedBits =
5291       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5292       APInt(Op.getValueSizeInBits(), 0) :
5293       APInt::getBitsSet(Op.getValueSizeInBits(),
5294                         N0.getValueSizeInBits(),
5295                         std::min(Op.getValueSizeInBits(),
5296                                  VT.getSizeInBits()));
5297     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5298       if (VT.bitsGT(Op.getValueType()))
5299         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5300       if (VT.bitsLT(Op.getValueType()))
5301         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5302
5303       return Op;
5304     }
5305   }
5306
5307   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5308   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5309   if (N0.getOpcode() == ISD::TRUNCATE) {
5310     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5311     if (NarrowLoad.getNode()) {
5312       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5313       if (NarrowLoad.getNode() != N0.getNode()) {
5314         CombineTo(N0.getNode(), NarrowLoad);
5315         // CombineTo deleted the truncate, if needed, but not what's under it.
5316         AddToWorklist(oye);
5317       }
5318       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5319     }
5320   }
5321
5322   // fold (zext (truncate x)) -> (and x, mask)
5323   if (N0.getOpcode() == ISD::TRUNCATE &&
5324       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5325
5326     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5327     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5328     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5329     if (NarrowLoad.getNode()) {
5330       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5331       if (NarrowLoad.getNode() != N0.getNode()) {
5332         CombineTo(N0.getNode(), NarrowLoad);
5333         // CombineTo deleted the truncate, if needed, but not what's under it.
5334         AddToWorklist(oye);
5335       }
5336       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5337     }
5338
5339     SDValue Op = N0.getOperand(0);
5340     if (Op.getValueType().bitsLT(VT)) {
5341       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5342       AddToWorklist(Op.getNode());
5343     } else if (Op.getValueType().bitsGT(VT)) {
5344       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5345       AddToWorklist(Op.getNode());
5346     }
5347     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5348                                   N0.getValueType().getScalarType());
5349   }
5350
5351   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5352   // if either of the casts is not free.
5353   if (N0.getOpcode() == ISD::AND &&
5354       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5355       N0.getOperand(1).getOpcode() == ISD::Constant &&
5356       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5357                            N0.getValueType()) ||
5358        !TLI.isZExtFree(N0.getValueType(), VT))) {
5359     SDValue X = N0.getOperand(0).getOperand(0);
5360     if (X.getValueType().bitsLT(VT)) {
5361       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5362     } else if (X.getValueType().bitsGT(VT)) {
5363       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5364     }
5365     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5366     Mask = Mask.zext(VT.getSizeInBits());
5367     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5368                        X, DAG.getConstant(Mask, VT));
5369   }
5370
5371   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5372   // None of the supported targets knows how to perform load and vector_zext
5373   // on vectors in one instruction.  We only perform this transformation on
5374   // scalars.
5375   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5376       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5377       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5378        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5379     bool DoXform = true;
5380     SmallVector<SDNode*, 4> SetCCs;
5381     if (!N0.hasOneUse())
5382       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5383     if (DoXform) {
5384       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5385       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5386                                        LN0->getChain(),
5387                                        LN0->getBasePtr(), N0.getValueType(),
5388                                        LN0->getMemOperand());
5389       CombineTo(N, ExtLoad);
5390       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5391                                   N0.getValueType(), ExtLoad);
5392       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5393
5394       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5395                       ISD::ZERO_EXTEND);
5396       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5397     }
5398   }
5399
5400   // fold (zext (and/or/xor (load x), cst)) ->
5401   //      (and/or/xor (zextload x), (zext cst))
5402   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5403        N0.getOpcode() == ISD::XOR) &&
5404       isa<LoadSDNode>(N0.getOperand(0)) &&
5405       N0.getOperand(1).getOpcode() == ISD::Constant &&
5406       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5407       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5408     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5409     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5410       bool DoXform = true;
5411       SmallVector<SDNode*, 4> SetCCs;
5412       if (!N0.hasOneUse())
5413         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5414                                           SetCCs, TLI);
5415       if (DoXform) {
5416         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5417                                          LN0->getChain(), LN0->getBasePtr(),
5418                                          LN0->getMemoryVT(),
5419                                          LN0->getMemOperand());
5420         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5421         Mask = Mask.zext(VT.getSizeInBits());
5422         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5423                                   ExtLoad, DAG.getConstant(Mask, VT));
5424         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5425                                     SDLoc(N0.getOperand(0)),
5426                                     N0.getOperand(0).getValueType(), ExtLoad);
5427         CombineTo(N, And);
5428         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5429         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5430                         ISD::ZERO_EXTEND);
5431         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5432       }
5433     }
5434   }
5435
5436   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5437   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5438   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5439       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5440     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5441     EVT MemVT = LN0->getMemoryVT();
5442     if ((!LegalOperations && !LN0->isVolatile()) ||
5443         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5444       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5445                                        LN0->getChain(),
5446                                        LN0->getBasePtr(), MemVT,
5447                                        LN0->getMemOperand());
5448       CombineTo(N, ExtLoad);
5449       CombineTo(N0.getNode(),
5450                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5451                             ExtLoad),
5452                 ExtLoad.getValue(1));
5453       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5454     }
5455   }
5456
5457   if (N0.getOpcode() == ISD::SETCC) {
5458     if (!LegalOperations && VT.isVector() &&
5459         N0.getValueType().getVectorElementType() == MVT::i1) {
5460       EVT N0VT = N0.getOperand(0).getValueType();
5461       if (getSetCCResultType(N0VT) == N0.getValueType())
5462         return SDValue();
5463
5464       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5465       // Only do this before legalize for now.
5466       EVT EltVT = VT.getVectorElementType();
5467       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5468                                     DAG.getConstant(1, EltVT));
5469       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5470         // We know that the # elements of the results is the same as the
5471         // # elements of the compare (and the # elements of the compare result
5472         // for that matter).  Check to see that they are the same size.  If so,
5473         // we know that the element size of the sext'd result matches the
5474         // element size of the compare operands.
5475         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5476                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5477                                          N0.getOperand(1),
5478                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5479                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5480                                        OneOps));
5481
5482       // If the desired elements are smaller or larger than the source
5483       // elements we can use a matching integer vector type and then
5484       // truncate/sign extend
5485       EVT MatchingElementType =
5486         EVT::getIntegerVT(*DAG.getContext(),
5487                           N0VT.getScalarType().getSizeInBits());
5488       EVT MatchingVectorType =
5489         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5490                          N0VT.getVectorNumElements());
5491       SDValue VsetCC =
5492         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5493                       N0.getOperand(1),
5494                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5495       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5496                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5497                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5498     }
5499
5500     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5501     SDValue SCC =
5502       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5503                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5504                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5505     if (SCC.getNode()) return SCC;
5506   }
5507
5508   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5509   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5510       isa<ConstantSDNode>(N0.getOperand(1)) &&
5511       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5512       N0.hasOneUse()) {
5513     SDValue ShAmt = N0.getOperand(1);
5514     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5515     if (N0.getOpcode() == ISD::SHL) {
5516       SDValue InnerZExt = N0.getOperand(0);
5517       // If the original shl may be shifting out bits, do not perform this
5518       // transformation.
5519       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5520         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5521       if (ShAmtVal > KnownZeroBits)
5522         return SDValue();
5523     }
5524
5525     SDLoc DL(N);
5526
5527     // Ensure that the shift amount is wide enough for the shifted value.
5528     if (VT.getSizeInBits() >= 256)
5529       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5530
5531     return DAG.getNode(N0.getOpcode(), DL, VT,
5532                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5533                        ShAmt);
5534   }
5535
5536   return SDValue();
5537 }
5538
5539 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5540   SDValue N0 = N->getOperand(0);
5541   EVT VT = N->getValueType(0);
5542
5543   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5544                                               LegalOperations))
5545     return SDValue(Res, 0);
5546
5547   // fold (aext (aext x)) -> (aext x)
5548   // fold (aext (zext x)) -> (zext x)
5549   // fold (aext (sext x)) -> (sext x)
5550   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5551       N0.getOpcode() == ISD::ZERO_EXTEND ||
5552       N0.getOpcode() == ISD::SIGN_EXTEND)
5553     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5554
5555   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5556   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5557   if (N0.getOpcode() == ISD::TRUNCATE) {
5558     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5559     if (NarrowLoad.getNode()) {
5560       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5561       if (NarrowLoad.getNode() != N0.getNode()) {
5562         CombineTo(N0.getNode(), NarrowLoad);
5563         // CombineTo deleted the truncate, if needed, but not what's under it.
5564         AddToWorklist(oye);
5565       }
5566       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5567     }
5568   }
5569
5570   // fold (aext (truncate x))
5571   if (N0.getOpcode() == ISD::TRUNCATE) {
5572     SDValue TruncOp = N0.getOperand(0);
5573     if (TruncOp.getValueType() == VT)
5574       return TruncOp; // x iff x size == zext size.
5575     if (TruncOp.getValueType().bitsGT(VT))
5576       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5577     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5578   }
5579
5580   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5581   // if the trunc is not free.
5582   if (N0.getOpcode() == ISD::AND &&
5583       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5584       N0.getOperand(1).getOpcode() == ISD::Constant &&
5585       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5586                           N0.getValueType())) {
5587     SDValue X = N0.getOperand(0).getOperand(0);
5588     if (X.getValueType().bitsLT(VT)) {
5589       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5590     } else if (X.getValueType().bitsGT(VT)) {
5591       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5592     }
5593     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5594     Mask = Mask.zext(VT.getSizeInBits());
5595     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5596                        X, DAG.getConstant(Mask, VT));
5597   }
5598
5599   // fold (aext (load x)) -> (aext (truncate (extload x)))
5600   // None of the supported targets knows how to perform load and any_ext
5601   // on vectors in one instruction.  We only perform this transformation on
5602   // scalars.
5603   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5604       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5605       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5606     bool DoXform = true;
5607     SmallVector<SDNode*, 4> SetCCs;
5608     if (!N0.hasOneUse())
5609       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5610     if (DoXform) {
5611       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5612       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5613                                        LN0->getChain(),
5614                                        LN0->getBasePtr(), N0.getValueType(),
5615                                        LN0->getMemOperand());
5616       CombineTo(N, ExtLoad);
5617       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5618                                   N0.getValueType(), ExtLoad);
5619       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5620       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5621                       ISD::ANY_EXTEND);
5622       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5623     }
5624   }
5625
5626   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5627   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5628   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5629   if (N0.getOpcode() == ISD::LOAD &&
5630       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5631       N0.hasOneUse()) {
5632     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5633     ISD::LoadExtType ExtType = LN0->getExtensionType();
5634     EVT MemVT = LN0->getMemoryVT();
5635     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5636       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5637                                        VT, LN0->getChain(), LN0->getBasePtr(),
5638                                        MemVT, LN0->getMemOperand());
5639       CombineTo(N, ExtLoad);
5640       CombineTo(N0.getNode(),
5641                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5642                             N0.getValueType(), ExtLoad),
5643                 ExtLoad.getValue(1));
5644       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5645     }
5646   }
5647
5648   if (N0.getOpcode() == ISD::SETCC) {
5649     // For vectors:
5650     // aext(setcc) -> vsetcc
5651     // aext(setcc) -> truncate(vsetcc)
5652     // aext(setcc) -> aext(vsetcc)
5653     // Only do this before legalize for now.
5654     if (VT.isVector() && !LegalOperations) {
5655       EVT N0VT = N0.getOperand(0).getValueType();
5656         // We know that the # elements of the results is the same as the
5657         // # elements of the compare (and the # elements of the compare result
5658         // for that matter).  Check to see that they are the same size.  If so,
5659         // we know that the element size of the sext'd result matches the
5660         // element size of the compare operands.
5661       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5662         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5663                              N0.getOperand(1),
5664                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5665       // If the desired elements are smaller or larger than the source
5666       // elements we can use a matching integer vector type and then
5667       // truncate/any extend
5668       else {
5669         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5670         SDValue VsetCC =
5671           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5672                         N0.getOperand(1),
5673                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5674         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5675       }
5676     }
5677
5678     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5679     SDValue SCC =
5680       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5681                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5682                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5683     if (SCC.getNode())
5684       return SCC;
5685   }
5686
5687   return SDValue();
5688 }
5689
5690 /// GetDemandedBits - See if the specified operand can be simplified with the
5691 /// knowledge that only the bits specified by Mask are used.  If so, return the
5692 /// simpler operand, otherwise return a null SDValue.
5693 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5694   switch (V.getOpcode()) {
5695   default: break;
5696   case ISD::Constant: {
5697     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5698     assert(CV && "Const value should be ConstSDNode.");
5699     const APInt &CVal = CV->getAPIntValue();
5700     APInt NewVal = CVal & Mask;
5701     if (NewVal != CVal)
5702       return DAG.getConstant(NewVal, V.getValueType());
5703     break;
5704   }
5705   case ISD::OR:
5706   case ISD::XOR:
5707     // If the LHS or RHS don't contribute bits to the or, drop them.
5708     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5709       return V.getOperand(1);
5710     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5711       return V.getOperand(0);
5712     break;
5713   case ISD::SRL:
5714     // Only look at single-use SRLs.
5715     if (!V.getNode()->hasOneUse())
5716       break;
5717     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5718       // See if we can recursively simplify the LHS.
5719       unsigned Amt = RHSC->getZExtValue();
5720
5721       // Watch out for shift count overflow though.
5722       if (Amt >= Mask.getBitWidth()) break;
5723       APInt NewMask = Mask << Amt;
5724       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5725       if (SimplifyLHS.getNode())
5726         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5727                            SimplifyLHS, V.getOperand(1));
5728     }
5729   }
5730   return SDValue();
5731 }
5732
5733 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5734 /// bits and then truncated to a narrower type and where N is a multiple
5735 /// of number of bits of the narrower type, transform it to a narrower load
5736 /// from address + N / num of bits of new type. If the result is to be
5737 /// extended, also fold the extension to form a extending load.
5738 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5739   unsigned Opc = N->getOpcode();
5740
5741   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5742   SDValue N0 = N->getOperand(0);
5743   EVT VT = N->getValueType(0);
5744   EVT ExtVT = VT;
5745
5746   // This transformation isn't valid for vector loads.
5747   if (VT.isVector())
5748     return SDValue();
5749
5750   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5751   // extended to VT.
5752   if (Opc == ISD::SIGN_EXTEND_INREG) {
5753     ExtType = ISD::SEXTLOAD;
5754     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5755   } else if (Opc == ISD::SRL) {
5756     // Another special-case: SRL is basically zero-extending a narrower value.
5757     ExtType = ISD::ZEXTLOAD;
5758     N0 = SDValue(N, 0);
5759     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5760     if (!N01) return SDValue();
5761     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5762                               VT.getSizeInBits() - N01->getZExtValue());
5763   }
5764   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5765     return SDValue();
5766
5767   unsigned EVTBits = ExtVT.getSizeInBits();
5768
5769   // Do not generate loads of non-round integer types since these can
5770   // be expensive (and would be wrong if the type is not byte sized).
5771   if (!ExtVT.isRound())
5772     return SDValue();
5773
5774   unsigned ShAmt = 0;
5775   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5776     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5777       ShAmt = N01->getZExtValue();
5778       // Is the shift amount a multiple of size of VT?
5779       if ((ShAmt & (EVTBits-1)) == 0) {
5780         N0 = N0.getOperand(0);
5781         // Is the load width a multiple of size of VT?
5782         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5783           return SDValue();
5784       }
5785
5786       // At this point, we must have a load or else we can't do the transform.
5787       if (!isa<LoadSDNode>(N0)) return SDValue();
5788
5789       // Because a SRL must be assumed to *need* to zero-extend the high bits
5790       // (as opposed to anyext the high bits), we can't combine the zextload
5791       // lowering of SRL and an sextload.
5792       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5793         return SDValue();
5794
5795       // If the shift amount is larger than the input type then we're not
5796       // accessing any of the loaded bytes.  If the load was a zextload/extload
5797       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5798       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5799         return SDValue();
5800     }
5801   }
5802
5803   // If the load is shifted left (and the result isn't shifted back right),
5804   // we can fold the truncate through the shift.
5805   unsigned ShLeftAmt = 0;
5806   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5807       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5808     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5809       ShLeftAmt = N01->getZExtValue();
5810       N0 = N0.getOperand(0);
5811     }
5812   }
5813
5814   // If we haven't found a load, we can't narrow it.  Don't transform one with
5815   // multiple uses, this would require adding a new load.
5816   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5817     return SDValue();
5818
5819   // Don't change the width of a volatile load.
5820   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5821   if (LN0->isVolatile())
5822     return SDValue();
5823
5824   // Verify that we are actually reducing a load width here.
5825   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5826     return SDValue();
5827
5828   // For the transform to be legal, the load must produce only two values
5829   // (the value loaded and the chain).  Don't transform a pre-increment
5830   // load, for example, which produces an extra value.  Otherwise the
5831   // transformation is not equivalent, and the downstream logic to replace
5832   // uses gets things wrong.
5833   if (LN0->getNumValues() > 2)
5834     return SDValue();
5835
5836   // If the load that we're shrinking is an extload and we're not just
5837   // discarding the extension we can't simply shrink the load. Bail.
5838   // TODO: It would be possible to merge the extensions in some cases.
5839   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5840       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5841     return SDValue();
5842
5843   EVT PtrType = N0.getOperand(1).getValueType();
5844
5845   if (PtrType == MVT::Untyped || PtrType.isExtended())
5846     // It's not possible to generate a constant of extended or untyped type.
5847     return SDValue();
5848
5849   // For big endian targets, we need to adjust the offset to the pointer to
5850   // load the correct bytes.
5851   if (TLI.isBigEndian()) {
5852     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5853     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5854     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5855   }
5856
5857   uint64_t PtrOff = ShAmt / 8;
5858   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5859   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5860                                PtrType, LN0->getBasePtr(),
5861                                DAG.getConstant(PtrOff, PtrType));
5862   AddToWorklist(NewPtr.getNode());
5863
5864   SDValue Load;
5865   if (ExtType == ISD::NON_EXTLOAD)
5866     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5867                         LN0->getPointerInfo().getWithOffset(PtrOff),
5868                         LN0->isVolatile(), LN0->isNonTemporal(),
5869                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5870   else
5871     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5872                           LN0->getPointerInfo().getWithOffset(PtrOff),
5873                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5874                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5875
5876   // Replace the old load's chain with the new load's chain.
5877   WorklistRemover DeadNodes(*this);
5878   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5879
5880   // Shift the result left, if we've swallowed a left shift.
5881   SDValue Result = Load;
5882   if (ShLeftAmt != 0) {
5883     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5884     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5885       ShImmTy = VT;
5886     // If the shift amount is as large as the result size (but, presumably,
5887     // no larger than the source) then the useful bits of the result are
5888     // zero; we can't simply return the shortened shift, because the result
5889     // of that operation is undefined.
5890     if (ShLeftAmt >= VT.getSizeInBits())
5891       Result = DAG.getConstant(0, VT);
5892     else
5893       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5894                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5895   }
5896
5897   // Return the new loaded value.
5898   return Result;
5899 }
5900
5901 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5902   SDValue N0 = N->getOperand(0);
5903   SDValue N1 = N->getOperand(1);
5904   EVT VT = N->getValueType(0);
5905   EVT EVT = cast<VTSDNode>(N1)->getVT();
5906   unsigned VTBits = VT.getScalarType().getSizeInBits();
5907   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5908
5909   // fold (sext_in_reg c1) -> c1
5910   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5911     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5912
5913   // If the input is already sign extended, just drop the extension.
5914   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5915     return N0;
5916
5917   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5918   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5919       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5920     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5921                        N0.getOperand(0), N1);
5922
5923   // fold (sext_in_reg (sext x)) -> (sext x)
5924   // fold (sext_in_reg (aext x)) -> (sext x)
5925   // if x is small enough.
5926   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5927     SDValue N00 = N0.getOperand(0);
5928     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5929         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5930       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5931   }
5932
5933   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5934   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5935     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5936
5937   // fold operands of sext_in_reg based on knowledge that the top bits are not
5938   // demanded.
5939   if (SimplifyDemandedBits(SDValue(N, 0)))
5940     return SDValue(N, 0);
5941
5942   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5943   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5944   SDValue NarrowLoad = ReduceLoadWidth(N);
5945   if (NarrowLoad.getNode())
5946     return NarrowLoad;
5947
5948   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5949   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5950   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5951   if (N0.getOpcode() == ISD::SRL) {
5952     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5953       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5954         // We can turn this into an SRA iff the input to the SRL is already sign
5955         // extended enough.
5956         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5957         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5958           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5959                              N0.getOperand(0), N0.getOperand(1));
5960       }
5961   }
5962
5963   // fold (sext_inreg (extload x)) -> (sextload x)
5964   if (ISD::isEXTLoad(N0.getNode()) &&
5965       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5966       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5967       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5968        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5969     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5970     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5971                                      LN0->getChain(),
5972                                      LN0->getBasePtr(), EVT,
5973                                      LN0->getMemOperand());
5974     CombineTo(N, ExtLoad);
5975     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5976     AddToWorklist(ExtLoad.getNode());
5977     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5978   }
5979   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5980   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5981       N0.hasOneUse() &&
5982       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5983       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5984        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5985     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5986     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5987                                      LN0->getChain(),
5988                                      LN0->getBasePtr(), EVT,
5989                                      LN0->getMemOperand());
5990     CombineTo(N, ExtLoad);
5991     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5992     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5993   }
5994
5995   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5996   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5997     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5998                                        N0.getOperand(1), false);
5999     if (BSwap.getNode())
6000       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6001                          BSwap, N1);
6002   }
6003
6004   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6005   // into a build_vector.
6006   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6007     SmallVector<SDValue, 8> Elts;
6008     unsigned NumElts = N0->getNumOperands();
6009     unsigned ShAmt = VTBits - EVTBits;
6010
6011     for (unsigned i = 0; i != NumElts; ++i) {
6012       SDValue Op = N0->getOperand(i);
6013       if (Op->getOpcode() == ISD::UNDEF) {
6014         Elts.push_back(Op);
6015         continue;
6016       }
6017
6018       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6019       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6020       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6021                                      Op.getValueType()));
6022     }
6023
6024     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6025   }
6026
6027   return SDValue();
6028 }
6029
6030 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6031   SDValue N0 = N->getOperand(0);
6032   EVT VT = N->getValueType(0);
6033   bool isLE = TLI.isLittleEndian();
6034
6035   // noop truncate
6036   if (N0.getValueType() == N->getValueType(0))
6037     return N0;
6038   // fold (truncate c1) -> c1
6039   if (isa<ConstantSDNode>(N0))
6040     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6041   // fold (truncate (truncate x)) -> (truncate x)
6042   if (N0.getOpcode() == ISD::TRUNCATE)
6043     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6044   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6045   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6046       N0.getOpcode() == ISD::SIGN_EXTEND ||
6047       N0.getOpcode() == ISD::ANY_EXTEND) {
6048     if (N0.getOperand(0).getValueType().bitsLT(VT))
6049       // if the source is smaller than the dest, we still need an extend
6050       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6051                          N0.getOperand(0));
6052     if (N0.getOperand(0).getValueType().bitsGT(VT))
6053       // if the source is larger than the dest, than we just need the truncate
6054       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6055     // if the source and dest are the same type, we can drop both the extend
6056     // and the truncate.
6057     return N0.getOperand(0);
6058   }
6059
6060   // Fold extract-and-trunc into a narrow extract. For example:
6061   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6062   //   i32 y = TRUNCATE(i64 x)
6063   //        -- becomes --
6064   //   v16i8 b = BITCAST (v2i64 val)
6065   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6066   //
6067   // Note: We only run this optimization after type legalization (which often
6068   // creates this pattern) and before operation legalization after which
6069   // we need to be more careful about the vector instructions that we generate.
6070   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6071       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6072
6073     EVT VecTy = N0.getOperand(0).getValueType();
6074     EVT ExTy = N0.getValueType();
6075     EVT TrTy = N->getValueType(0);
6076
6077     unsigned NumElem = VecTy.getVectorNumElements();
6078     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6079
6080     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6081     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6082
6083     SDValue EltNo = N0->getOperand(1);
6084     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6085       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6086       EVT IndexTy = TLI.getVectorIdxTy();
6087       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6088
6089       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6090                               NVT, N0.getOperand(0));
6091
6092       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6093                          SDLoc(N), TrTy, V,
6094                          DAG.getConstant(Index, IndexTy));
6095     }
6096   }
6097
6098   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6099   if (N0.getOpcode() == ISD::SELECT) {
6100     EVT SrcVT = N0.getValueType();
6101     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6102         TLI.isTruncateFree(SrcVT, VT)) {
6103       SDLoc SL(N0);
6104       SDValue Cond = N0.getOperand(0);
6105       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6106       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6107       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6108     }
6109   }
6110
6111   // Fold a series of buildvector, bitcast, and truncate if possible.
6112   // For example fold
6113   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6114   //   (2xi32 (buildvector x, y)).
6115   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6116       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6117       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6118       N0.getOperand(0).hasOneUse()) {
6119
6120     SDValue BuildVect = N0.getOperand(0);
6121     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6122     EVT TruncVecEltTy = VT.getVectorElementType();
6123
6124     // Check that the element types match.
6125     if (BuildVectEltTy == TruncVecEltTy) {
6126       // Now we only need to compute the offset of the truncated elements.
6127       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6128       unsigned TruncVecNumElts = VT.getVectorNumElements();
6129       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6130
6131       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6132              "Invalid number of elements");
6133
6134       SmallVector<SDValue, 8> Opnds;
6135       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6136         Opnds.push_back(BuildVect.getOperand(i));
6137
6138       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6139     }
6140   }
6141
6142   // See if we can simplify the input to this truncate through knowledge that
6143   // only the low bits are being used.
6144   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6145   // Currently we only perform this optimization on scalars because vectors
6146   // may have different active low bits.
6147   if (!VT.isVector()) {
6148     SDValue Shorter =
6149       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6150                                                VT.getSizeInBits()));
6151     if (Shorter.getNode())
6152       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6153   }
6154   // fold (truncate (load x)) -> (smaller load x)
6155   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6156   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6157     SDValue Reduced = ReduceLoadWidth(N);
6158     if (Reduced.getNode())
6159       return Reduced;
6160     // Handle the case where the load remains an extending load even
6161     // after truncation.
6162     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6163       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6164       if (!LN0->isVolatile() &&
6165           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6166         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6167                                          VT, LN0->getChain(), LN0->getBasePtr(),
6168                                          LN0->getMemoryVT(),
6169                                          LN0->getMemOperand());
6170         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6171         return NewLoad;
6172       }
6173     }
6174   }
6175   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6176   // where ... are all 'undef'.
6177   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6178     SmallVector<EVT, 8> VTs;
6179     SDValue V;
6180     unsigned Idx = 0;
6181     unsigned NumDefs = 0;
6182
6183     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6184       SDValue X = N0.getOperand(i);
6185       if (X.getOpcode() != ISD::UNDEF) {
6186         V = X;
6187         Idx = i;
6188         NumDefs++;
6189       }
6190       // Stop if more than one members are non-undef.
6191       if (NumDefs > 1)
6192         break;
6193       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6194                                      VT.getVectorElementType(),
6195                                      X.getValueType().getVectorNumElements()));
6196     }
6197
6198     if (NumDefs == 0)
6199       return DAG.getUNDEF(VT);
6200
6201     if (NumDefs == 1) {
6202       assert(V.getNode() && "The single defined operand is empty!");
6203       SmallVector<SDValue, 8> Opnds;
6204       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6205         if (i != Idx) {
6206           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6207           continue;
6208         }
6209         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6210         AddToWorklist(NV.getNode());
6211         Opnds.push_back(NV);
6212       }
6213       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6214     }
6215   }
6216
6217   // Simplify the operands using demanded-bits information.
6218   if (!VT.isVector() &&
6219       SimplifyDemandedBits(SDValue(N, 0)))
6220     return SDValue(N, 0);
6221
6222   return SDValue();
6223 }
6224
6225 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6226   SDValue Elt = N->getOperand(i);
6227   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6228     return Elt.getNode();
6229   return Elt.getOperand(Elt.getResNo()).getNode();
6230 }
6231
6232 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6233 /// if load locations are consecutive.
6234 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6235   assert(N->getOpcode() == ISD::BUILD_PAIR);
6236
6237   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6238   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6239   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6240       LD1->getAddressSpace() != LD2->getAddressSpace())
6241     return SDValue();
6242   EVT LD1VT = LD1->getValueType(0);
6243
6244   if (ISD::isNON_EXTLoad(LD2) &&
6245       LD2->hasOneUse() &&
6246       // If both are volatile this would reduce the number of volatile loads.
6247       // If one is volatile it might be ok, but play conservative and bail out.
6248       !LD1->isVolatile() &&
6249       !LD2->isVolatile() &&
6250       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6251     unsigned Align = LD1->getAlignment();
6252     unsigned NewAlign = TLI.getDataLayout()->
6253       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6254
6255     if (NewAlign <= Align &&
6256         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6257       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6258                          LD1->getBasePtr(), LD1->getPointerInfo(),
6259                          false, false, false, Align);
6260   }
6261
6262   return SDValue();
6263 }
6264
6265 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6266   SDValue N0 = N->getOperand(0);
6267   EVT VT = N->getValueType(0);
6268
6269   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6270   // Only do this before legalize, since afterward the target may be depending
6271   // on the bitconvert.
6272   // First check to see if this is all constant.
6273   if (!LegalTypes &&
6274       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6275       VT.isVector()) {
6276     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6277
6278     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6279     assert(!DestEltVT.isVector() &&
6280            "Element type of vector ValueType must not be vector!");
6281     if (isSimple)
6282       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6283   }
6284
6285   // If the input is a constant, let getNode fold it.
6286   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6287     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6288     if (Res.getNode() != N) {
6289       if (!LegalOperations ||
6290           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6291         return Res;
6292
6293       // Folding it resulted in an illegal node, and it's too late to
6294       // do that. Clean up the old node and forego the transformation.
6295       // Ideally this won't happen very often, because instcombine
6296       // and the earlier dagcombine runs (where illegal nodes are
6297       // permitted) should have folded most of them already.
6298       deleteAndRecombine(Res.getNode());
6299     }
6300   }
6301
6302   // (conv (conv x, t1), t2) -> (conv x, t2)
6303   if (N0.getOpcode() == ISD::BITCAST)
6304     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6305                        N0.getOperand(0));
6306
6307   // fold (conv (load x)) -> (load (conv*)x)
6308   // If the resultant load doesn't need a higher alignment than the original!
6309   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6310       // Do not change the width of a volatile load.
6311       !cast<LoadSDNode>(N0)->isVolatile() &&
6312       // Do not remove the cast if the types differ in endian layout.
6313       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6314       TLI.hasBigEndianPartOrdering(VT) &&
6315       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6316       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6317     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6318     unsigned Align = TLI.getDataLayout()->
6319       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6320     unsigned OrigAlign = LN0->getAlignment();
6321
6322     if (Align <= OrigAlign) {
6323       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6324                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6325                                  LN0->isVolatile(), LN0->isNonTemporal(),
6326                                  LN0->isInvariant(), OrigAlign,
6327                                  LN0->getAAInfo());
6328       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6329       return Load;
6330     }
6331   }
6332
6333   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6334   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6335   // This often reduces constant pool loads.
6336   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6337        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6338       N0.getNode()->hasOneUse() && VT.isInteger() &&
6339       !VT.isVector() && !N0.getValueType().isVector()) {
6340     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6341                                   N0.getOperand(0));
6342     AddToWorklist(NewConv.getNode());
6343
6344     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6345     if (N0.getOpcode() == ISD::FNEG)
6346       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6347                          NewConv, DAG.getConstant(SignBit, VT));
6348     assert(N0.getOpcode() == ISD::FABS);
6349     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6350                        NewConv, DAG.getConstant(~SignBit, VT));
6351   }
6352
6353   // fold (bitconvert (fcopysign cst, x)) ->
6354   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6355   // Note that we don't handle (copysign x, cst) because this can always be
6356   // folded to an fneg or fabs.
6357   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6358       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6359       VT.isInteger() && !VT.isVector()) {
6360     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6361     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6362     if (isTypeLegal(IntXVT)) {
6363       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6364                               IntXVT, N0.getOperand(1));
6365       AddToWorklist(X.getNode());
6366
6367       // If X has a different width than the result/lhs, sext it or truncate it.
6368       unsigned VTWidth = VT.getSizeInBits();
6369       if (OrigXWidth < VTWidth) {
6370         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6371         AddToWorklist(X.getNode());
6372       } else if (OrigXWidth > VTWidth) {
6373         // To get the sign bit in the right place, we have to shift it right
6374         // before truncating.
6375         X = DAG.getNode(ISD::SRL, SDLoc(X),
6376                         X.getValueType(), X,
6377                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6378         AddToWorklist(X.getNode());
6379         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6380         AddToWorklist(X.getNode());
6381       }
6382
6383       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6384       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6385                       X, DAG.getConstant(SignBit, VT));
6386       AddToWorklist(X.getNode());
6387
6388       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6389                                 VT, N0.getOperand(0));
6390       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6391                         Cst, DAG.getConstant(~SignBit, VT));
6392       AddToWorklist(Cst.getNode());
6393
6394       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6395     }
6396   }
6397
6398   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6399   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6400     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6401     if (CombineLD.getNode())
6402       return CombineLD;
6403   }
6404
6405   return SDValue();
6406 }
6407
6408 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6409   EVT VT = N->getValueType(0);
6410   return CombineConsecutiveLoads(N, VT);
6411 }
6412
6413 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6414 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6415 /// destination element value type.
6416 SDValue DAGCombiner::
6417 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6418   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6419
6420   // If this is already the right type, we're done.
6421   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6422
6423   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6424   unsigned DstBitSize = DstEltVT.getSizeInBits();
6425
6426   // If this is a conversion of N elements of one type to N elements of another
6427   // type, convert each element.  This handles FP<->INT cases.
6428   if (SrcBitSize == DstBitSize) {
6429     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6430                               BV->getValueType(0).getVectorNumElements());
6431
6432     // Due to the FP element handling below calling this routine recursively,
6433     // we can end up with a scalar-to-vector node here.
6434     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6435       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6436                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6437                                      DstEltVT, BV->getOperand(0)));
6438
6439     SmallVector<SDValue, 8> Ops;
6440     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6441       SDValue Op = BV->getOperand(i);
6442       // If the vector element type is not legal, the BUILD_VECTOR operands
6443       // are promoted and implicitly truncated.  Make that explicit here.
6444       if (Op.getValueType() != SrcEltVT)
6445         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6446       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6447                                 DstEltVT, Op));
6448       AddToWorklist(Ops.back().getNode());
6449     }
6450     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6451   }
6452
6453   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6454   // handle annoying details of growing/shrinking FP values, we convert them to
6455   // int first.
6456   if (SrcEltVT.isFloatingPoint()) {
6457     // Convert the input float vector to a int vector where the elements are the
6458     // same sizes.
6459     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6460     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6461     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6462     SrcEltVT = IntVT;
6463   }
6464
6465   // Now we know the input is an integer vector.  If the output is a FP type,
6466   // convert to integer first, then to FP of the right size.
6467   if (DstEltVT.isFloatingPoint()) {
6468     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6469     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6470     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6471
6472     // Next, convert to FP elements of the same size.
6473     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6474   }
6475
6476   // Okay, we know the src/dst types are both integers of differing types.
6477   // Handling growing first.
6478   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6479   if (SrcBitSize < DstBitSize) {
6480     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6481
6482     SmallVector<SDValue, 8> Ops;
6483     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6484          i += NumInputsPerOutput) {
6485       bool isLE = TLI.isLittleEndian();
6486       APInt NewBits = APInt(DstBitSize, 0);
6487       bool EltIsUndef = true;
6488       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6489         // Shift the previously computed bits over.
6490         NewBits <<= SrcBitSize;
6491         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6492         if (Op.getOpcode() == ISD::UNDEF) continue;
6493         EltIsUndef = false;
6494
6495         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6496                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6497       }
6498
6499       if (EltIsUndef)
6500         Ops.push_back(DAG.getUNDEF(DstEltVT));
6501       else
6502         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6503     }
6504
6505     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6506     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6507   }
6508
6509   // Finally, this must be the case where we are shrinking elements: each input
6510   // turns into multiple outputs.
6511   bool isS2V = ISD::isScalarToVector(BV);
6512   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6513   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6514                             NumOutputsPerInput*BV->getNumOperands());
6515   SmallVector<SDValue, 8> Ops;
6516
6517   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6518     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6519       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6520         Ops.push_back(DAG.getUNDEF(DstEltVT));
6521       continue;
6522     }
6523
6524     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6525                   getAPIntValue().zextOrTrunc(SrcBitSize);
6526
6527     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6528       APInt ThisVal = OpVal.trunc(DstBitSize);
6529       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6530       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6531         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6532         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6533                            Ops[0]);
6534       OpVal = OpVal.lshr(DstBitSize);
6535     }
6536
6537     // For big endian targets, swap the order of the pieces of each element.
6538     if (TLI.isBigEndian())
6539       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6540   }
6541
6542   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6543 }
6544
6545 SDValue DAGCombiner::visitFADD(SDNode *N) {
6546   SDValue N0 = N->getOperand(0);
6547   SDValue N1 = N->getOperand(1);
6548   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6549   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6550   EVT VT = N->getValueType(0);
6551
6552   // fold vector ops
6553   if (VT.isVector()) {
6554     SDValue FoldedVOp = SimplifyVBinOp(N);
6555     if (FoldedVOp.getNode()) return FoldedVOp;
6556   }
6557
6558   // fold (fadd c1, c2) -> c1 + c2
6559   if (N0CFP && N1CFP)
6560     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6561   // canonicalize constant to RHS
6562   if (N0CFP && !N1CFP)
6563     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6564   // fold (fadd A, 0) -> A
6565   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6566       N1CFP->getValueAPF().isZero())
6567     return N0;
6568   // fold (fadd A, (fneg B)) -> (fsub A, B)
6569   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6570     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6571     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6572                        GetNegatedExpression(N1, DAG, LegalOperations));
6573   // fold (fadd (fneg A), B) -> (fsub B, A)
6574   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6575     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6576     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6577                        GetNegatedExpression(N0, DAG, LegalOperations));
6578
6579   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6580   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6581       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6582       isa<ConstantFPSDNode>(N0.getOperand(1)))
6583     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6584                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6585                                    N0.getOperand(1), N1));
6586
6587   // No FP constant should be created after legalization as Instruction
6588   // Selection pass has hard time in dealing with FP constant.
6589   //
6590   // We don't need test this condition for transformation like following, as
6591   // the DAG being transformed implies it is legal to take FP constant as
6592   // operand.
6593   //
6594   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6595   //
6596   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6597
6598   // If allow, fold (fadd (fneg x), x) -> 0.0
6599   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6600       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6601     return DAG.getConstantFP(0.0, VT);
6602
6603     // If allow, fold (fadd x, (fneg x)) -> 0.0
6604   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6605       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6606     return DAG.getConstantFP(0.0, VT);
6607
6608   // In unsafe math mode, we can fold chains of FADD's of the same value
6609   // into multiplications.  This transform is not safe in general because
6610   // we are reducing the number of rounding steps.
6611   if (DAG.getTarget().Options.UnsafeFPMath &&
6612       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6613       !N0CFP && !N1CFP) {
6614     if (N0.getOpcode() == ISD::FMUL) {
6615       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6616       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6617
6618       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6619       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6620         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6621                                      SDValue(CFP00, 0),
6622                                      DAG.getConstantFP(1.0, VT));
6623         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6624                            N1, NewCFP);
6625       }
6626
6627       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6628       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6629         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6630                                      SDValue(CFP01, 0),
6631                                      DAG.getConstantFP(1.0, VT));
6632         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6633                            N1, NewCFP);
6634       }
6635
6636       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6637       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6638           N1.getOperand(0) == N1.getOperand(1) &&
6639           N0.getOperand(1) == N1.getOperand(0)) {
6640         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6641                                      SDValue(CFP00, 0),
6642                                      DAG.getConstantFP(2.0, VT));
6643         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6644                            N0.getOperand(1), NewCFP);
6645       }
6646
6647       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6648       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6649           N1.getOperand(0) == N1.getOperand(1) &&
6650           N0.getOperand(0) == N1.getOperand(0)) {
6651         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6652                                      SDValue(CFP01, 0),
6653                                      DAG.getConstantFP(2.0, VT));
6654         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6655                            N0.getOperand(0), NewCFP);
6656       }
6657     }
6658
6659     if (N1.getOpcode() == ISD::FMUL) {
6660       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6661       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6662
6663       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6664       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6665         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6666                                      SDValue(CFP10, 0),
6667                                      DAG.getConstantFP(1.0, VT));
6668         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6669                            N0, NewCFP);
6670       }
6671
6672       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6673       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6674         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6675                                      SDValue(CFP11, 0),
6676                                      DAG.getConstantFP(1.0, VT));
6677         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6678                            N0, NewCFP);
6679       }
6680
6681
6682       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6683       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6684           N0.getOperand(0) == N0.getOperand(1) &&
6685           N1.getOperand(1) == N0.getOperand(0)) {
6686         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6687                                      SDValue(CFP10, 0),
6688                                      DAG.getConstantFP(2.0, VT));
6689         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6690                            N1.getOperand(1), NewCFP);
6691       }
6692
6693       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6694       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6695           N0.getOperand(0) == N0.getOperand(1) &&
6696           N1.getOperand(0) == N0.getOperand(0)) {
6697         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6698                                      SDValue(CFP11, 0),
6699                                      DAG.getConstantFP(2.0, VT));
6700         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6701                            N1.getOperand(0), NewCFP);
6702       }
6703     }
6704
6705     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6706       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6707       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6708       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6709           (N0.getOperand(0) == N1))
6710         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6711                            N1, DAG.getConstantFP(3.0, VT));
6712     }
6713
6714     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6715       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6716       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6717       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6718           N1.getOperand(0) == N0)
6719         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6720                            N0, DAG.getConstantFP(3.0, VT));
6721     }
6722
6723     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6724     if (AllowNewFpConst &&
6725         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6726         N0.getOperand(0) == N0.getOperand(1) &&
6727         N1.getOperand(0) == N1.getOperand(1) &&
6728         N0.getOperand(0) == N1.getOperand(0))
6729       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6730                          N0.getOperand(0),
6731                          DAG.getConstantFP(4.0, VT));
6732   }
6733
6734   // FADD -> FMA combines:
6735   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6736        DAG.getTarget().Options.UnsafeFPMath) &&
6737       DAG.getTarget()
6738           .getSubtargetImpl()
6739           ->getTargetLowering()
6740           ->isFMAFasterThanFMulAndFAdd(VT) &&
6741       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6742
6743     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6744     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6745       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6746                          N0.getOperand(0), N0.getOperand(1), N1);
6747
6748     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6749     // Note: Commutes FADD operands.
6750     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6751       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6752                          N1.getOperand(0), N1.getOperand(1), N0);
6753   }
6754
6755   return SDValue();
6756 }
6757
6758 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6759   SDValue N0 = N->getOperand(0);
6760   SDValue N1 = N->getOperand(1);
6761   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6762   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6763   EVT VT = N->getValueType(0);
6764   SDLoc dl(N);
6765
6766   // fold vector ops
6767   if (VT.isVector()) {
6768     SDValue FoldedVOp = SimplifyVBinOp(N);
6769     if (FoldedVOp.getNode()) return FoldedVOp;
6770   }
6771
6772   // fold (fsub c1, c2) -> c1-c2
6773   if (N0CFP && N1CFP)
6774     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6775   // fold (fsub A, 0) -> A
6776   if (DAG.getTarget().Options.UnsafeFPMath &&
6777       N1CFP && N1CFP->getValueAPF().isZero())
6778     return N0;
6779   // fold (fsub 0, B) -> -B
6780   if (DAG.getTarget().Options.UnsafeFPMath &&
6781       N0CFP && N0CFP->getValueAPF().isZero()) {
6782     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6783       return GetNegatedExpression(N1, DAG, LegalOperations);
6784     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6785       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6786   }
6787   // fold (fsub A, (fneg B)) -> (fadd A, B)
6788   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6789     return DAG.getNode(ISD::FADD, dl, VT, N0,
6790                        GetNegatedExpression(N1, DAG, LegalOperations));
6791
6792   // If 'unsafe math' is enabled, fold
6793   //    (fsub x, x) -> 0.0 &
6794   //    (fsub x, (fadd x, y)) -> (fneg y) &
6795   //    (fsub x, (fadd y, x)) -> (fneg y)
6796   if (DAG.getTarget().Options.UnsafeFPMath) {
6797     if (N0 == N1)
6798       return DAG.getConstantFP(0.0f, VT);
6799
6800     if (N1.getOpcode() == ISD::FADD) {
6801       SDValue N10 = N1->getOperand(0);
6802       SDValue N11 = N1->getOperand(1);
6803
6804       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6805                                           &DAG.getTarget().Options))
6806         return GetNegatedExpression(N11, DAG, LegalOperations);
6807
6808       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6809                                           &DAG.getTarget().Options))
6810         return GetNegatedExpression(N10, DAG, LegalOperations);
6811     }
6812   }
6813
6814   // FSUB -> FMA combines:
6815   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6816        DAG.getTarget().Options.UnsafeFPMath) &&
6817       DAG.getTarget()
6818           .getSubtargetImpl()
6819           ->getTargetLowering()
6820           ->isFMAFasterThanFMulAndFAdd(VT) &&
6821       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6822
6823     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6824     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6825       return DAG.getNode(ISD::FMA, dl, VT,
6826                          N0.getOperand(0), N0.getOperand(1),
6827                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6828
6829     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6830     // Note: Commutes FSUB operands.
6831     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6832       return DAG.getNode(ISD::FMA, dl, VT,
6833                          DAG.getNode(ISD::FNEG, dl, VT,
6834                          N1.getOperand(0)),
6835                          N1.getOperand(1), N0);
6836
6837     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6838     if (N0.getOpcode() == ISD::FNEG &&
6839         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6840         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6841       SDValue N00 = N0.getOperand(0).getOperand(0);
6842       SDValue N01 = N0.getOperand(0).getOperand(1);
6843       return DAG.getNode(ISD::FMA, dl, VT,
6844                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6845                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6846     }
6847   }
6848
6849   return SDValue();
6850 }
6851
6852 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6853   SDValue N0 = N->getOperand(0);
6854   SDValue N1 = N->getOperand(1);
6855   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6856   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6857   EVT VT = N->getValueType(0);
6858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6859
6860   // fold vector ops
6861   if (VT.isVector()) {
6862     SDValue FoldedVOp = SimplifyVBinOp(N);
6863     if (FoldedVOp.getNode()) return FoldedVOp;
6864   }
6865
6866   // fold (fmul c1, c2) -> c1*c2
6867   if (N0CFP && N1CFP)
6868     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6869   // canonicalize constant to RHS
6870   if (N0CFP && !N1CFP)
6871     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6872   // fold (fmul A, 0) -> 0
6873   if (DAG.getTarget().Options.UnsafeFPMath &&
6874       N1CFP && N1CFP->getValueAPF().isZero())
6875     return N1;
6876   // fold (fmul A, 1.0) -> A
6877   if (N1CFP && N1CFP->isExactlyValue(1.0))
6878     return N0;
6879
6880   // fold (fmul X, 2.0) -> (fadd X, X)
6881   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6882     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6883   // fold (fmul X, -1.0) -> (fneg X)
6884   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6885     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6886       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6887
6888   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6889   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6890                                        &DAG.getTarget().Options)) {
6891     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6892                                          &DAG.getTarget().Options)) {
6893       // Both can be negated for free, check to see if at least one is cheaper
6894       // negated.
6895       if (LHSNeg == 2 || RHSNeg == 2)
6896         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6897                            GetNegatedExpression(N0, DAG, LegalOperations),
6898                            GetNegatedExpression(N1, DAG, LegalOperations));
6899     }
6900   }
6901
6902   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6903   if (DAG.getTarget().Options.UnsafeFPMath &&
6904       N1CFP && N0.getOpcode() == ISD::FMUL &&
6905       N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6906     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6907                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6908                                    N0.getOperand(1), N1));
6909   }
6910
6911   return SDValue();
6912 }
6913
6914 SDValue DAGCombiner::visitFMA(SDNode *N) {
6915   SDValue N0 = N->getOperand(0);
6916   SDValue N1 = N->getOperand(1);
6917   SDValue N2 = N->getOperand(2);
6918   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6919   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6920   EVT VT = N->getValueType(0);
6921   SDLoc dl(N);
6922
6923
6924   // Constant fold FMA.
6925   if (isa<ConstantFPSDNode>(N0) &&
6926       isa<ConstantFPSDNode>(N1) &&
6927       isa<ConstantFPSDNode>(N2)) {
6928     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6929   }
6930
6931   if (DAG.getTarget().Options.UnsafeFPMath) {
6932     if (N0CFP && N0CFP->isZero())
6933       return N2;
6934     if (N1CFP && N1CFP->isZero())
6935       return N2;
6936   }
6937   if (N0CFP && N0CFP->isExactlyValue(1.0))
6938     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6939   if (N1CFP && N1CFP->isExactlyValue(1.0))
6940     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6941
6942   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6943   if (N0CFP && !N1CFP)
6944     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6945
6946   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6947   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6948       N2.getOpcode() == ISD::FMUL &&
6949       N0 == N2.getOperand(0) &&
6950       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6951     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6952                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6953   }
6954
6955
6956   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6957   if (DAG.getTarget().Options.UnsafeFPMath &&
6958       N0.getOpcode() == ISD::FMUL && N1CFP &&
6959       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6960     return DAG.getNode(ISD::FMA, dl, VT,
6961                        N0.getOperand(0),
6962                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6963                        N2);
6964   }
6965
6966   // (fma x, 1, y) -> (fadd x, y)
6967   // (fma x, -1, y) -> (fadd (fneg x), y)
6968   if (N1CFP) {
6969     if (N1CFP->isExactlyValue(1.0))
6970       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6971
6972     if (N1CFP->isExactlyValue(-1.0) &&
6973         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6974       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6975       AddToWorklist(RHSNeg.getNode());
6976       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6977     }
6978   }
6979
6980   // (fma x, c, x) -> (fmul x, (c+1))
6981   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6982     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6983                        DAG.getNode(ISD::FADD, dl, VT,
6984                                    N1, DAG.getConstantFP(1.0, VT)));
6985
6986   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6987   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6988       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6989     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6990                        DAG.getNode(ISD::FADD, dl, VT,
6991                                    N1, DAG.getConstantFP(-1.0, VT)));
6992
6993
6994   return SDValue();
6995 }
6996
6997 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6998   SDValue N0 = N->getOperand(0);
6999   SDValue N1 = N->getOperand(1);
7000   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7001   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7002   EVT VT = N->getValueType(0);
7003   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7004
7005   // fold vector ops
7006   if (VT.isVector()) {
7007     SDValue FoldedVOp = SimplifyVBinOp(N);
7008     if (FoldedVOp.getNode()) return FoldedVOp;
7009   }
7010
7011   // fold (fdiv c1, c2) -> c1/c2
7012   if (N0CFP && N1CFP)
7013     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7014
7015   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7016   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
7017     // Compute the reciprocal 1.0 / c2.
7018     APFloat N1APF = N1CFP->getValueAPF();
7019     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7020     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7021     // Only do the transform if the reciprocal is a legal fp immediate that
7022     // isn't too nasty (eg NaN, denormal, ...).
7023     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7024         (!LegalOperations ||
7025          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7026          // backend)... we should handle this gracefully after Legalize.
7027          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7028          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7029          TLI.isFPImmLegal(Recip, VT)))
7030       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7031                          DAG.getConstantFP(Recip, VT));
7032   }
7033
7034   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7035   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7036                                        &DAG.getTarget().Options)) {
7037     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7038                                          &DAG.getTarget().Options)) {
7039       // Both can be negated for free, check to see if at least one is cheaper
7040       // negated.
7041       if (LHSNeg == 2 || RHSNeg == 2)
7042         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7043                            GetNegatedExpression(N0, DAG, LegalOperations),
7044                            GetNegatedExpression(N1, DAG, LegalOperations));
7045     }
7046   }
7047
7048   return SDValue();
7049 }
7050
7051 SDValue DAGCombiner::visitFREM(SDNode *N) {
7052   SDValue N0 = N->getOperand(0);
7053   SDValue N1 = N->getOperand(1);
7054   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7055   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7056   EVT VT = N->getValueType(0);
7057
7058   // fold (frem c1, c2) -> fmod(c1,c2)
7059   if (N0CFP && N1CFP)
7060     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7061
7062   return SDValue();
7063 }
7064
7065 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7066   SDValue N0 = N->getOperand(0);
7067   SDValue N1 = N->getOperand(1);
7068   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7069   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7070   EVT VT = N->getValueType(0);
7071
7072   if (N0CFP && N1CFP)  // Constant fold
7073     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7074
7075   if (N1CFP) {
7076     const APFloat& V = N1CFP->getValueAPF();
7077     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7078     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7079     if (!V.isNegative()) {
7080       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7081         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7082     } else {
7083       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7084         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7085                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7086     }
7087   }
7088
7089   // copysign(fabs(x), y) -> copysign(x, y)
7090   // copysign(fneg(x), y) -> copysign(x, y)
7091   // copysign(copysign(x,z), y) -> copysign(x, y)
7092   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7093       N0.getOpcode() == ISD::FCOPYSIGN)
7094     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7095                        N0.getOperand(0), N1);
7096
7097   // copysign(x, abs(y)) -> abs(x)
7098   if (N1.getOpcode() == ISD::FABS)
7099     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7100
7101   // copysign(x, copysign(y,z)) -> copysign(x, z)
7102   if (N1.getOpcode() == ISD::FCOPYSIGN)
7103     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7104                        N0, N1.getOperand(1));
7105
7106   // copysign(x, fp_extend(y)) -> copysign(x, y)
7107   // copysign(x, fp_round(y)) -> copysign(x, y)
7108   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7109     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7110                        N0, N1.getOperand(0));
7111
7112   return SDValue();
7113 }
7114
7115 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7116   SDValue N0 = N->getOperand(0);
7117   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7118   EVT VT = N->getValueType(0);
7119   EVT OpVT = N0.getValueType();
7120
7121   // fold (sint_to_fp c1) -> c1fp
7122   if (N0C &&
7123       // ...but only if the target supports immediate floating-point values
7124       (!LegalOperations ||
7125        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7126     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7127
7128   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7129   // but UINT_TO_FP is legal on this target, try to convert.
7130   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7131       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7132     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7133     if (DAG.SignBitIsZero(N0))
7134       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7135   }
7136
7137   // The next optimizations are desirable only if SELECT_CC can be lowered.
7138   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7139     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7140     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7141         !VT.isVector() &&
7142         (!LegalOperations ||
7143          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7144       SDValue Ops[] =
7145         { N0.getOperand(0), N0.getOperand(1),
7146           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7147           N0.getOperand(2) };
7148       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7149     }
7150
7151     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7152     //      (select_cc x, y, 1.0, 0.0,, cc)
7153     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7154         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7155         (!LegalOperations ||
7156          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7157       SDValue Ops[] =
7158         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7159           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7160           N0.getOperand(0).getOperand(2) };
7161       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7162     }
7163   }
7164
7165   return SDValue();
7166 }
7167
7168 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7169   SDValue N0 = N->getOperand(0);
7170   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7171   EVT VT = N->getValueType(0);
7172   EVT OpVT = N0.getValueType();
7173
7174   // fold (uint_to_fp c1) -> c1fp
7175   if (N0C &&
7176       // ...but only if the target supports immediate floating-point values
7177       (!LegalOperations ||
7178        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7179     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7180
7181   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7182   // but SINT_TO_FP is legal on this target, try to convert.
7183   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7184       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7185     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7186     if (DAG.SignBitIsZero(N0))
7187       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7188   }
7189
7190   // The next optimizations are desirable only if SELECT_CC can be lowered.
7191   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7192     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7193
7194     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7195         (!LegalOperations ||
7196          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7197       SDValue Ops[] =
7198         { N0.getOperand(0), N0.getOperand(1),
7199           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7200           N0.getOperand(2) };
7201       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7202     }
7203   }
7204
7205   return SDValue();
7206 }
7207
7208 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7209   SDValue N0 = N->getOperand(0);
7210   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7211   EVT VT = N->getValueType(0);
7212
7213   // fold (fp_to_sint c1fp) -> c1
7214   if (N0CFP)
7215     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7216
7217   return SDValue();
7218 }
7219
7220 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7221   SDValue N0 = N->getOperand(0);
7222   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7223   EVT VT = N->getValueType(0);
7224
7225   // fold (fp_to_uint c1fp) -> c1
7226   if (N0CFP)
7227     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7228
7229   return SDValue();
7230 }
7231
7232 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7233   SDValue N0 = N->getOperand(0);
7234   SDValue N1 = N->getOperand(1);
7235   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7236   EVT VT = N->getValueType(0);
7237
7238   // fold (fp_round c1fp) -> c1fp
7239   if (N0CFP)
7240     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7241
7242   // fold (fp_round (fp_extend x)) -> x
7243   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7244     return N0.getOperand(0);
7245
7246   // fold (fp_round (fp_round x)) -> (fp_round x)
7247   if (N0.getOpcode() == ISD::FP_ROUND) {
7248     // This is a value preserving truncation if both round's are.
7249     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7250                    N0.getNode()->getConstantOperandVal(1) == 1;
7251     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7252                        DAG.getIntPtrConstant(IsTrunc));
7253   }
7254
7255   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7256   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7257     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7258                               N0.getOperand(0), N1);
7259     AddToWorklist(Tmp.getNode());
7260     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7261                        Tmp, N0.getOperand(1));
7262   }
7263
7264   return SDValue();
7265 }
7266
7267 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7268   SDValue N0 = N->getOperand(0);
7269   EVT VT = N->getValueType(0);
7270   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7271   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7272
7273   // fold (fp_round_inreg c1fp) -> c1fp
7274   if (N0CFP && isTypeLegal(EVT)) {
7275     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7276     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7277   }
7278
7279   return SDValue();
7280 }
7281
7282 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7283   SDValue N0 = N->getOperand(0);
7284   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7285   EVT VT = N->getValueType(0);
7286
7287   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7288   if (N->hasOneUse() &&
7289       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7290     return SDValue();
7291
7292   // fold (fp_extend c1fp) -> c1fp
7293   if (N0CFP)
7294     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7295
7296   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7297   // value of X.
7298   if (N0.getOpcode() == ISD::FP_ROUND
7299       && N0.getNode()->getConstantOperandVal(1) == 1) {
7300     SDValue In = N0.getOperand(0);
7301     if (In.getValueType() == VT) return In;
7302     if (VT.bitsLT(In.getValueType()))
7303       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7304                          In, N0.getOperand(1));
7305     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7306   }
7307
7308   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7309   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7310        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7311     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7312     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7313                                      LN0->getChain(),
7314                                      LN0->getBasePtr(), N0.getValueType(),
7315                                      LN0->getMemOperand());
7316     CombineTo(N, ExtLoad);
7317     CombineTo(N0.getNode(),
7318               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7319                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7320               ExtLoad.getValue(1));
7321     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7322   }
7323
7324   return SDValue();
7325 }
7326
7327 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7328   SDValue N0 = N->getOperand(0);
7329   EVT VT = N->getValueType(0);
7330
7331   // Constant fold FNEG.
7332   if (isa<ConstantFPSDNode>(N0))
7333     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7334
7335   if (VT.isVector()) {
7336     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7337     if (FoldedVOp.getNode()) return FoldedVOp;
7338   }
7339
7340   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7341                          &DAG.getTarget().Options))
7342     return GetNegatedExpression(N0, DAG, LegalOperations);
7343
7344   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7345   // constant pool values.
7346   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7347       N0.getNode()->hasOneUse()) {
7348     SDValue Int = N0.getOperand(0);
7349     EVT IntVT = Int.getValueType();
7350     if (IntVT.isInteger() && !IntVT.isVector()) {
7351       APInt SignMask;
7352       if (N0.getValueType().isVector()) {
7353         // For a vector, get a mask such as 0x80... per scalar element
7354         // and splat it.
7355         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7356         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7357       } else {
7358         // For a scalar, just generate 0x80...
7359         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7360       }
7361       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7362                         DAG.getConstant(SignMask, IntVT));
7363       AddToWorklist(Int.getNode());
7364       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7365     }
7366   }
7367
7368   // (fneg (fmul c, x)) -> (fmul -c, x)
7369   if (N0.getOpcode() == ISD::FMUL) {
7370     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7371     if (CFP1) {
7372       APFloat CVal = CFP1->getValueAPF();
7373       CVal.changeSign();
7374       if (Level >= AfterLegalizeDAG &&
7375           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7376            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7377         return DAG.getNode(
7378             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7379             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7380     }
7381   }
7382
7383   return SDValue();
7384 }
7385
7386 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7387   SDValue N0 = N->getOperand(0);
7388   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7389   EVT VT = N->getValueType(0);
7390
7391   // fold (fceil c1) -> fceil(c1)
7392   if (N0CFP)
7393     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7394
7395   return SDValue();
7396 }
7397
7398 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7399   SDValue N0 = N->getOperand(0);
7400   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7401   EVT VT = N->getValueType(0);
7402
7403   // fold (ftrunc c1) -> ftrunc(c1)
7404   if (N0CFP)
7405     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7406
7407   return SDValue();
7408 }
7409
7410 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7411   SDValue N0 = N->getOperand(0);
7412   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7413   EVT VT = N->getValueType(0);
7414
7415   // fold (ffloor c1) -> ffloor(c1)
7416   if (N0CFP)
7417     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7418
7419   return SDValue();
7420 }
7421
7422 SDValue DAGCombiner::visitFABS(SDNode *N) {
7423   SDValue N0 = N->getOperand(0);
7424   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7425   EVT VT = N->getValueType(0);
7426
7427   if (VT.isVector()) {
7428     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7429     if (FoldedVOp.getNode()) return FoldedVOp;
7430   }
7431
7432   // fold (fabs c1) -> fabs(c1)
7433   if (N0CFP)
7434     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7435   // fold (fabs (fabs x)) -> (fabs x)
7436   if (N0.getOpcode() == ISD::FABS)
7437     return N->getOperand(0);
7438   // fold (fabs (fneg x)) -> (fabs x)
7439   // fold (fabs (fcopysign x, y)) -> (fabs x)
7440   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7441     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7442
7443   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7444   // constant pool values.
7445   if (!TLI.isFAbsFree(VT) &&
7446       N0.getOpcode() == ISD::BITCAST &&
7447       N0.getNode()->hasOneUse()) {
7448     SDValue Int = N0.getOperand(0);
7449     EVT IntVT = Int.getValueType();
7450     if (IntVT.isInteger() && !IntVT.isVector()) {
7451       APInt SignMask;
7452       if (N0.getValueType().isVector()) {
7453         // For a vector, get a mask such as 0x7f... per scalar element
7454         // and splat it.
7455         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7456         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7457       } else {
7458         // For a scalar, just generate 0x7f...
7459         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7460       }
7461       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7462                         DAG.getConstant(SignMask, IntVT));
7463       AddToWorklist(Int.getNode());
7464       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7465     }
7466   }
7467
7468   return SDValue();
7469 }
7470
7471 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7472   SDValue Chain = N->getOperand(0);
7473   SDValue N1 = N->getOperand(1);
7474   SDValue N2 = N->getOperand(2);
7475
7476   // If N is a constant we could fold this into a fallthrough or unconditional
7477   // branch. However that doesn't happen very often in normal code, because
7478   // Instcombine/SimplifyCFG should have handled the available opportunities.
7479   // If we did this folding here, it would be necessary to update the
7480   // MachineBasicBlock CFG, which is awkward.
7481
7482   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7483   // on the target.
7484   if (N1.getOpcode() == ISD::SETCC &&
7485       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7486                                    N1.getOperand(0).getValueType())) {
7487     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7488                        Chain, N1.getOperand(2),
7489                        N1.getOperand(0), N1.getOperand(1), N2);
7490   }
7491
7492   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7493       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7494        (N1.getOperand(0).hasOneUse() &&
7495         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7496     SDNode *Trunc = nullptr;
7497     if (N1.getOpcode() == ISD::TRUNCATE) {
7498       // Look pass the truncate.
7499       Trunc = N1.getNode();
7500       N1 = N1.getOperand(0);
7501     }
7502
7503     // Match this pattern so that we can generate simpler code:
7504     //
7505     //   %a = ...
7506     //   %b = and i32 %a, 2
7507     //   %c = srl i32 %b, 1
7508     //   brcond i32 %c ...
7509     //
7510     // into
7511     //
7512     //   %a = ...
7513     //   %b = and i32 %a, 2
7514     //   %c = setcc eq %b, 0
7515     //   brcond %c ...
7516     //
7517     // This applies only when the AND constant value has one bit set and the
7518     // SRL constant is equal to the log2 of the AND constant. The back-end is
7519     // smart enough to convert the result into a TEST/JMP sequence.
7520     SDValue Op0 = N1.getOperand(0);
7521     SDValue Op1 = N1.getOperand(1);
7522
7523     if (Op0.getOpcode() == ISD::AND &&
7524         Op1.getOpcode() == ISD::Constant) {
7525       SDValue AndOp1 = Op0.getOperand(1);
7526
7527       if (AndOp1.getOpcode() == ISD::Constant) {
7528         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7529
7530         if (AndConst.isPowerOf2() &&
7531             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7532           SDValue SetCC =
7533             DAG.getSetCC(SDLoc(N),
7534                          getSetCCResultType(Op0.getValueType()),
7535                          Op0, DAG.getConstant(0, Op0.getValueType()),
7536                          ISD::SETNE);
7537
7538           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7539                                           MVT::Other, Chain, SetCC, N2);
7540           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7541           // will convert it back to (X & C1) >> C2.
7542           CombineTo(N, NewBRCond, false);
7543           // Truncate is dead.
7544           if (Trunc)
7545             deleteAndRecombine(Trunc);
7546           // Replace the uses of SRL with SETCC
7547           WorklistRemover DeadNodes(*this);
7548           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7549           deleteAndRecombine(N1.getNode());
7550           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7551         }
7552       }
7553     }
7554
7555     if (Trunc)
7556       // Restore N1 if the above transformation doesn't match.
7557       N1 = N->getOperand(1);
7558   }
7559
7560   // Transform br(xor(x, y)) -> br(x != y)
7561   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7562   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7563     SDNode *TheXor = N1.getNode();
7564     SDValue Op0 = TheXor->getOperand(0);
7565     SDValue Op1 = TheXor->getOperand(1);
7566     if (Op0.getOpcode() == Op1.getOpcode()) {
7567       // Avoid missing important xor optimizations.
7568       SDValue Tmp = visitXOR(TheXor);
7569       if (Tmp.getNode()) {
7570         if (Tmp.getNode() != TheXor) {
7571           DEBUG(dbgs() << "\nReplacing.8 ";
7572                 TheXor->dump(&DAG);
7573                 dbgs() << "\nWith: ";
7574                 Tmp.getNode()->dump(&DAG);
7575                 dbgs() << '\n');
7576           WorklistRemover DeadNodes(*this);
7577           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7578           deleteAndRecombine(TheXor);
7579           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7580                              MVT::Other, Chain, Tmp, N2);
7581         }
7582
7583         // visitXOR has changed XOR's operands or replaced the XOR completely,
7584         // bail out.
7585         return SDValue(N, 0);
7586       }
7587     }
7588
7589     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7590       bool Equal = false;
7591       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7592         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7593             Op0.getOpcode() == ISD::XOR) {
7594           TheXor = Op0.getNode();
7595           Equal = true;
7596         }
7597
7598       EVT SetCCVT = N1.getValueType();
7599       if (LegalTypes)
7600         SetCCVT = getSetCCResultType(SetCCVT);
7601       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7602                                    SetCCVT,
7603                                    Op0, Op1,
7604                                    Equal ? ISD::SETEQ : ISD::SETNE);
7605       // Replace the uses of XOR with SETCC
7606       WorklistRemover DeadNodes(*this);
7607       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7608       deleteAndRecombine(N1.getNode());
7609       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7610                          MVT::Other, Chain, SetCC, N2);
7611     }
7612   }
7613
7614   return SDValue();
7615 }
7616
7617 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7618 //
7619 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7620   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7621   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7622
7623   // If N is a constant we could fold this into a fallthrough or unconditional
7624   // branch. However that doesn't happen very often in normal code, because
7625   // Instcombine/SimplifyCFG should have handled the available opportunities.
7626   // If we did this folding here, it would be necessary to update the
7627   // MachineBasicBlock CFG, which is awkward.
7628
7629   // Use SimplifySetCC to simplify SETCC's.
7630   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7631                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7632                                false);
7633   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7634
7635   // fold to a simpler setcc
7636   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7637     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7638                        N->getOperand(0), Simp.getOperand(2),
7639                        Simp.getOperand(0), Simp.getOperand(1),
7640                        N->getOperand(4));
7641
7642   return SDValue();
7643 }
7644
7645 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7646 /// uses N as its base pointer and that N may be folded in the load / store
7647 /// addressing mode.
7648 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7649                                     SelectionDAG &DAG,
7650                                     const TargetLowering &TLI) {
7651   EVT VT;
7652   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7653     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7654       return false;
7655     VT = Use->getValueType(0);
7656   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7657     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7658       return false;
7659     VT = ST->getValue().getValueType();
7660   } else
7661     return false;
7662
7663   TargetLowering::AddrMode AM;
7664   if (N->getOpcode() == ISD::ADD) {
7665     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7666     if (Offset)
7667       // [reg +/- imm]
7668       AM.BaseOffs = Offset->getSExtValue();
7669     else
7670       // [reg +/- reg]
7671       AM.Scale = 1;
7672   } else if (N->getOpcode() == ISD::SUB) {
7673     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7674     if (Offset)
7675       // [reg +/- imm]
7676       AM.BaseOffs = -Offset->getSExtValue();
7677     else
7678       // [reg +/- reg]
7679       AM.Scale = 1;
7680   } else
7681     return false;
7682
7683   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7684 }
7685
7686 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7687 /// pre-indexed load / store when the base pointer is an add or subtract
7688 /// and it has other uses besides the load / store. After the
7689 /// transformation, the new indexed load / store has effectively folded
7690 /// the add / subtract in and all of its other uses are redirected to the
7691 /// new load / store.
7692 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7693   if (Level < AfterLegalizeDAG)
7694     return false;
7695
7696   bool isLoad = true;
7697   SDValue Ptr;
7698   EVT VT;
7699   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7700     if (LD->isIndexed())
7701       return false;
7702     VT = LD->getMemoryVT();
7703     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7704         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7705       return false;
7706     Ptr = LD->getBasePtr();
7707   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7708     if (ST->isIndexed())
7709       return false;
7710     VT = ST->getMemoryVT();
7711     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7712         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7713       return false;
7714     Ptr = ST->getBasePtr();
7715     isLoad = false;
7716   } else {
7717     return false;
7718   }
7719
7720   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7721   // out.  There is no reason to make this a preinc/predec.
7722   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7723       Ptr.getNode()->hasOneUse())
7724     return false;
7725
7726   // Ask the target to do addressing mode selection.
7727   SDValue BasePtr;
7728   SDValue Offset;
7729   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7730   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7731     return false;
7732
7733   // Backends without true r+i pre-indexed forms may need to pass a
7734   // constant base with a variable offset so that constant coercion
7735   // will work with the patterns in canonical form.
7736   bool Swapped = false;
7737   if (isa<ConstantSDNode>(BasePtr)) {
7738     std::swap(BasePtr, Offset);
7739     Swapped = true;
7740   }
7741
7742   // Don't create a indexed load / store with zero offset.
7743   if (isa<ConstantSDNode>(Offset) &&
7744       cast<ConstantSDNode>(Offset)->isNullValue())
7745     return false;
7746
7747   // Try turning it into a pre-indexed load / store except when:
7748   // 1) The new base ptr is a frame index.
7749   // 2) If N is a store and the new base ptr is either the same as or is a
7750   //    predecessor of the value being stored.
7751   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7752   //    that would create a cycle.
7753   // 4) All uses are load / store ops that use it as old base ptr.
7754
7755   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7756   // (plus the implicit offset) to a register to preinc anyway.
7757   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7758     return false;
7759
7760   // Check #2.
7761   if (!isLoad) {
7762     SDValue Val = cast<StoreSDNode>(N)->getValue();
7763     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7764       return false;
7765   }
7766
7767   // If the offset is a constant, there may be other adds of constants that
7768   // can be folded with this one. We should do this to avoid having to keep
7769   // a copy of the original base pointer.
7770   SmallVector<SDNode *, 16> OtherUses;
7771   if (isa<ConstantSDNode>(Offset))
7772     for (SDNode *Use : BasePtr.getNode()->uses()) {
7773       if (Use == Ptr.getNode())
7774         continue;
7775
7776       if (Use->isPredecessorOf(N))
7777         continue;
7778
7779       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7780         OtherUses.clear();
7781         break;
7782       }
7783
7784       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7785       if (Op1.getNode() == BasePtr.getNode())
7786         std::swap(Op0, Op1);
7787       assert(Op0.getNode() == BasePtr.getNode() &&
7788              "Use of ADD/SUB but not an operand");
7789
7790       if (!isa<ConstantSDNode>(Op1)) {
7791         OtherUses.clear();
7792         break;
7793       }
7794
7795       // FIXME: In some cases, we can be smarter about this.
7796       if (Op1.getValueType() != Offset.getValueType()) {
7797         OtherUses.clear();
7798         break;
7799       }
7800
7801       OtherUses.push_back(Use);
7802     }
7803
7804   if (Swapped)
7805     std::swap(BasePtr, Offset);
7806
7807   // Now check for #3 and #4.
7808   bool RealUse = false;
7809
7810   // Caches for hasPredecessorHelper
7811   SmallPtrSet<const SDNode *, 32> Visited;
7812   SmallVector<const SDNode *, 16> Worklist;
7813
7814   for (SDNode *Use : Ptr.getNode()->uses()) {
7815     if (Use == N)
7816       continue;
7817     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7818       return false;
7819
7820     // If Ptr may be folded in addressing mode of other use, then it's
7821     // not profitable to do this transformation.
7822     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7823       RealUse = true;
7824   }
7825
7826   if (!RealUse)
7827     return false;
7828
7829   SDValue Result;
7830   if (isLoad)
7831     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7832                                 BasePtr, Offset, AM);
7833   else
7834     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7835                                  BasePtr, Offset, AM);
7836   ++PreIndexedNodes;
7837   ++NodesCombined;
7838   DEBUG(dbgs() << "\nReplacing.4 ";
7839         N->dump(&DAG);
7840         dbgs() << "\nWith: ";
7841         Result.getNode()->dump(&DAG);
7842         dbgs() << '\n');
7843   WorklistRemover DeadNodes(*this);
7844   if (isLoad) {
7845     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7846     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7847   } else {
7848     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7849   }
7850
7851   // Finally, since the node is now dead, remove it from the graph.
7852   deleteAndRecombine(N);
7853
7854   if (Swapped)
7855     std::swap(BasePtr, Offset);
7856
7857   // Replace other uses of BasePtr that can be updated to use Ptr
7858   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7859     unsigned OffsetIdx = 1;
7860     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7861       OffsetIdx = 0;
7862     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7863            BasePtr.getNode() && "Expected BasePtr operand");
7864
7865     // We need to replace ptr0 in the following expression:
7866     //   x0 * offset0 + y0 * ptr0 = t0
7867     // knowing that
7868     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7869     //
7870     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7871     // indexed load/store and the expresion that needs to be re-written.
7872     //
7873     // Therefore, we have:
7874     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7875
7876     ConstantSDNode *CN =
7877       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7878     int X0, X1, Y0, Y1;
7879     APInt Offset0 = CN->getAPIntValue();
7880     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7881
7882     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7883     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7884     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7885     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7886
7887     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7888
7889     APInt CNV = Offset0;
7890     if (X0 < 0) CNV = -CNV;
7891     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7892     else CNV = CNV - Offset1;
7893
7894     // We can now generate the new expression.
7895     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7896     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7897
7898     SDValue NewUse = DAG.getNode(Opcode,
7899                                  SDLoc(OtherUses[i]),
7900                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7901     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7902     deleteAndRecombine(OtherUses[i]);
7903   }
7904
7905   // Replace the uses of Ptr with uses of the updated base value.
7906   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7907   deleteAndRecombine(Ptr.getNode());
7908
7909   return true;
7910 }
7911
7912 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7913 /// add / sub of the base pointer node into a post-indexed load / store.
7914 /// The transformation folded the add / subtract into the new indexed
7915 /// load / store effectively and all of its uses are redirected to the
7916 /// new load / store.
7917 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7918   if (Level < AfterLegalizeDAG)
7919     return false;
7920
7921   bool isLoad = true;
7922   SDValue Ptr;
7923   EVT VT;
7924   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7925     if (LD->isIndexed())
7926       return false;
7927     VT = LD->getMemoryVT();
7928     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7929         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7930       return false;
7931     Ptr = LD->getBasePtr();
7932   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7933     if (ST->isIndexed())
7934       return false;
7935     VT = ST->getMemoryVT();
7936     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7937         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7938       return false;
7939     Ptr = ST->getBasePtr();
7940     isLoad = false;
7941   } else {
7942     return false;
7943   }
7944
7945   if (Ptr.getNode()->hasOneUse())
7946     return false;
7947
7948   for (SDNode *Op : Ptr.getNode()->uses()) {
7949     if (Op == N ||
7950         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7951       continue;
7952
7953     SDValue BasePtr;
7954     SDValue Offset;
7955     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7956     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7957       // Don't create a indexed load / store with zero offset.
7958       if (isa<ConstantSDNode>(Offset) &&
7959           cast<ConstantSDNode>(Offset)->isNullValue())
7960         continue;
7961
7962       // Try turning it into a post-indexed load / store except when
7963       // 1) All uses are load / store ops that use it as base ptr (and
7964       //    it may be folded as addressing mmode).
7965       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7966       //    nor a successor of N. Otherwise, if Op is folded that would
7967       //    create a cycle.
7968
7969       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7970         continue;
7971
7972       // Check for #1.
7973       bool TryNext = false;
7974       for (SDNode *Use : BasePtr.getNode()->uses()) {
7975         if (Use == Ptr.getNode())
7976           continue;
7977
7978         // If all the uses are load / store addresses, then don't do the
7979         // transformation.
7980         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7981           bool RealUse = false;
7982           for (SDNode *UseUse : Use->uses()) {
7983             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7984               RealUse = true;
7985           }
7986
7987           if (!RealUse) {
7988             TryNext = true;
7989             break;
7990           }
7991         }
7992       }
7993
7994       if (TryNext)
7995         continue;
7996
7997       // Check for #2
7998       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7999         SDValue Result = isLoad
8000           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8001                                BasePtr, Offset, AM)
8002           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8003                                 BasePtr, Offset, AM);
8004         ++PostIndexedNodes;
8005         ++NodesCombined;
8006         DEBUG(dbgs() << "\nReplacing.5 ";
8007               N->dump(&DAG);
8008               dbgs() << "\nWith: ";
8009               Result.getNode()->dump(&DAG);
8010               dbgs() << '\n');
8011         WorklistRemover DeadNodes(*this);
8012         if (isLoad) {
8013           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8014           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8015         } else {
8016           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8017         }
8018
8019         // Finally, since the node is now dead, remove it from the graph.
8020         deleteAndRecombine(N);
8021
8022         // Replace the uses of Use with uses of the updated base value.
8023         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8024                                       Result.getValue(isLoad ? 1 : 0));
8025         deleteAndRecombine(Op);
8026         return true;
8027       }
8028     }
8029   }
8030
8031   return false;
8032 }
8033
8034 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8035   LoadSDNode *LD  = cast<LoadSDNode>(N);
8036   SDValue Chain = LD->getChain();
8037   SDValue Ptr   = LD->getBasePtr();
8038
8039   // If load is not volatile and there are no uses of the loaded value (and
8040   // the updated indexed value in case of indexed loads), change uses of the
8041   // chain value into uses of the chain input (i.e. delete the dead load).
8042   if (!LD->isVolatile()) {
8043     if (N->getValueType(1) == MVT::Other) {
8044       // Unindexed loads.
8045       if (!N->hasAnyUseOfValue(0)) {
8046         // It's not safe to use the two value CombineTo variant here. e.g.
8047         // v1, chain2 = load chain1, loc
8048         // v2, chain3 = load chain2, loc
8049         // v3         = add v2, c
8050         // Now we replace use of chain2 with chain1.  This makes the second load
8051         // isomorphic to the one we are deleting, and thus makes this load live.
8052         DEBUG(dbgs() << "\nReplacing.6 ";
8053               N->dump(&DAG);
8054               dbgs() << "\nWith chain: ";
8055               Chain.getNode()->dump(&DAG);
8056               dbgs() << "\n");
8057         WorklistRemover DeadNodes(*this);
8058         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8059
8060         if (N->use_empty())
8061           deleteAndRecombine(N);
8062
8063         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8064       }
8065     } else {
8066       // Indexed loads.
8067       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8068       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8069         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8070         DEBUG(dbgs() << "\nReplacing.7 ";
8071               N->dump(&DAG);
8072               dbgs() << "\nWith: ";
8073               Undef.getNode()->dump(&DAG);
8074               dbgs() << " and 2 other values\n");
8075         WorklistRemover DeadNodes(*this);
8076         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8077         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8078                                       DAG.getUNDEF(N->getValueType(1)));
8079         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8080         deleteAndRecombine(N);
8081         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8082       }
8083     }
8084   }
8085
8086   // If this load is directly stored, replace the load value with the stored
8087   // value.
8088   // TODO: Handle store large -> read small portion.
8089   // TODO: Handle TRUNCSTORE/LOADEXT
8090   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8091     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8092       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8093       if (PrevST->getBasePtr() == Ptr &&
8094           PrevST->getValue().getValueType() == N->getValueType(0))
8095       return CombineTo(N, Chain.getOperand(1), Chain);
8096     }
8097   }
8098
8099   // Try to infer better alignment information than the load already has.
8100   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8101     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8102       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8103         SDValue NewLoad =
8104                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8105                               LD->getValueType(0),
8106                               Chain, Ptr, LD->getPointerInfo(),
8107                               LD->getMemoryVT(),
8108                               LD->isVolatile(), LD->isNonTemporal(),
8109                               LD->isInvariant(), Align, LD->getAAInfo());
8110         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8111       }
8112     }
8113   }
8114
8115   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8116     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8117 #ifndef NDEBUG
8118   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8119       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8120     UseAA = false;
8121 #endif
8122   if (UseAA && LD->isUnindexed()) {
8123     // Walk up chain skipping non-aliasing memory nodes.
8124     SDValue BetterChain = FindBetterChain(N, Chain);
8125
8126     // If there is a better chain.
8127     if (Chain != BetterChain) {
8128       SDValue ReplLoad;
8129
8130       // Replace the chain to void dependency.
8131       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8132         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8133                                BetterChain, Ptr, LD->getMemOperand());
8134       } else {
8135         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8136                                   LD->getValueType(0),
8137                                   BetterChain, Ptr, LD->getMemoryVT(),
8138                                   LD->getMemOperand());
8139       }
8140
8141       // Create token factor to keep old chain connected.
8142       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8143                                   MVT::Other, Chain, ReplLoad.getValue(1));
8144
8145       // Make sure the new and old chains are cleaned up.
8146       AddToWorklist(Token.getNode());
8147
8148       // Replace uses with load result and token factor. Don't add users
8149       // to work list.
8150       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8151     }
8152   }
8153
8154   // Try transforming N to an indexed load.
8155   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8156     return SDValue(N, 0);
8157
8158   // Try to slice up N to more direct loads if the slices are mapped to
8159   // different register banks or pairing can take place.
8160   if (SliceUpLoad(N))
8161     return SDValue(N, 0);
8162
8163   return SDValue();
8164 }
8165
8166 namespace {
8167 /// \brief Helper structure used to slice a load in smaller loads.
8168 /// Basically a slice is obtained from the following sequence:
8169 /// Origin = load Ty1, Base
8170 /// Shift = srl Ty1 Origin, CstTy Amount
8171 /// Inst = trunc Shift to Ty2
8172 ///
8173 /// Then, it will be rewriten into:
8174 /// Slice = load SliceTy, Base + SliceOffset
8175 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8176 ///
8177 /// SliceTy is deduced from the number of bits that are actually used to
8178 /// build Inst.
8179 struct LoadedSlice {
8180   /// \brief Helper structure used to compute the cost of a slice.
8181   struct Cost {
8182     /// Are we optimizing for code size.
8183     bool ForCodeSize;
8184     /// Various cost.
8185     unsigned Loads;
8186     unsigned Truncates;
8187     unsigned CrossRegisterBanksCopies;
8188     unsigned ZExts;
8189     unsigned Shift;
8190
8191     Cost(bool ForCodeSize = false)
8192         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8193           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8194
8195     /// \brief Get the cost of one isolated slice.
8196     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8197         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8198           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8199       EVT TruncType = LS.Inst->getValueType(0);
8200       EVT LoadedType = LS.getLoadedType();
8201       if (TruncType != LoadedType &&
8202           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8203         ZExts = 1;
8204     }
8205
8206     /// \brief Account for slicing gain in the current cost.
8207     /// Slicing provide a few gains like removing a shift or a
8208     /// truncate. This method allows to grow the cost of the original
8209     /// load with the gain from this slice.
8210     void addSliceGain(const LoadedSlice &LS) {
8211       // Each slice saves a truncate.
8212       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8213       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8214                               LS.Inst->getOperand(0).getValueType()))
8215         ++Truncates;
8216       // If there is a shift amount, this slice gets rid of it.
8217       if (LS.Shift)
8218         ++Shift;
8219       // If this slice can merge a cross register bank copy, account for it.
8220       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8221         ++CrossRegisterBanksCopies;
8222     }
8223
8224     Cost &operator+=(const Cost &RHS) {
8225       Loads += RHS.Loads;
8226       Truncates += RHS.Truncates;
8227       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8228       ZExts += RHS.ZExts;
8229       Shift += RHS.Shift;
8230       return *this;
8231     }
8232
8233     bool operator==(const Cost &RHS) const {
8234       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8235              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8236              ZExts == RHS.ZExts && Shift == RHS.Shift;
8237     }
8238
8239     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8240
8241     bool operator<(const Cost &RHS) const {
8242       // Assume cross register banks copies are as expensive as loads.
8243       // FIXME: Do we want some more target hooks?
8244       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8245       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8246       // Unless we are optimizing for code size, consider the
8247       // expensive operation first.
8248       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8249         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8250       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8251              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8252     }
8253
8254     bool operator>(const Cost &RHS) const { return RHS < *this; }
8255
8256     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8257
8258     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8259   };
8260   // The last instruction that represent the slice. This should be a
8261   // truncate instruction.
8262   SDNode *Inst;
8263   // The original load instruction.
8264   LoadSDNode *Origin;
8265   // The right shift amount in bits from the original load.
8266   unsigned Shift;
8267   // The DAG from which Origin came from.
8268   // This is used to get some contextual information about legal types, etc.
8269   SelectionDAG *DAG;
8270
8271   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8272               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8273       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8274
8275   LoadedSlice(const LoadedSlice &LS)
8276       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8277
8278   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8279   /// \return Result is \p BitWidth and has used bits set to 1 and
8280   ///         not used bits set to 0.
8281   APInt getUsedBits() const {
8282     // Reproduce the trunc(lshr) sequence:
8283     // - Start from the truncated value.
8284     // - Zero extend to the desired bit width.
8285     // - Shift left.
8286     assert(Origin && "No original load to compare against.");
8287     unsigned BitWidth = Origin->getValueSizeInBits(0);
8288     assert(Inst && "This slice is not bound to an instruction");
8289     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8290            "Extracted slice is bigger than the whole type!");
8291     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8292     UsedBits.setAllBits();
8293     UsedBits = UsedBits.zext(BitWidth);
8294     UsedBits <<= Shift;
8295     return UsedBits;
8296   }
8297
8298   /// \brief Get the size of the slice to be loaded in bytes.
8299   unsigned getLoadedSize() const {
8300     unsigned SliceSize = getUsedBits().countPopulation();
8301     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8302     return SliceSize / 8;
8303   }
8304
8305   /// \brief Get the type that will be loaded for this slice.
8306   /// Note: This may not be the final type for the slice.
8307   EVT getLoadedType() const {
8308     assert(DAG && "Missing context");
8309     LLVMContext &Ctxt = *DAG->getContext();
8310     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8311   }
8312
8313   /// \brief Get the alignment of the load used for this slice.
8314   unsigned getAlignment() const {
8315     unsigned Alignment = Origin->getAlignment();
8316     unsigned Offset = getOffsetFromBase();
8317     if (Offset != 0)
8318       Alignment = MinAlign(Alignment, Alignment + Offset);
8319     return Alignment;
8320   }
8321
8322   /// \brief Check if this slice can be rewritten with legal operations.
8323   bool isLegal() const {
8324     // An invalid slice is not legal.
8325     if (!Origin || !Inst || !DAG)
8326       return false;
8327
8328     // Offsets are for indexed load only, we do not handle that.
8329     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8330       return false;
8331
8332     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8333
8334     // Check that the type is legal.
8335     EVT SliceType = getLoadedType();
8336     if (!TLI.isTypeLegal(SliceType))
8337       return false;
8338
8339     // Check that the load is legal for this type.
8340     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8341       return false;
8342
8343     // Check that the offset can be computed.
8344     // 1. Check its type.
8345     EVT PtrType = Origin->getBasePtr().getValueType();
8346     if (PtrType == MVT::Untyped || PtrType.isExtended())
8347       return false;
8348
8349     // 2. Check that it fits in the immediate.
8350     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8351       return false;
8352
8353     // 3. Check that the computation is legal.
8354     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8355       return false;
8356
8357     // Check that the zext is legal if it needs one.
8358     EVT TruncateType = Inst->getValueType(0);
8359     if (TruncateType != SliceType &&
8360         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8361       return false;
8362
8363     return true;
8364   }
8365
8366   /// \brief Get the offset in bytes of this slice in the original chunk of
8367   /// bits.
8368   /// \pre DAG != nullptr.
8369   uint64_t getOffsetFromBase() const {
8370     assert(DAG && "Missing context.");
8371     bool IsBigEndian =
8372         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8373     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8374     uint64_t Offset = Shift / 8;
8375     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8376     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8377            "The size of the original loaded type is not a multiple of a"
8378            " byte.");
8379     // If Offset is bigger than TySizeInBytes, it means we are loading all
8380     // zeros. This should have been optimized before in the process.
8381     assert(TySizeInBytes > Offset &&
8382            "Invalid shift amount for given loaded size");
8383     if (IsBigEndian)
8384       Offset = TySizeInBytes - Offset - getLoadedSize();
8385     return Offset;
8386   }
8387
8388   /// \brief Generate the sequence of instructions to load the slice
8389   /// represented by this object and redirect the uses of this slice to
8390   /// this new sequence of instructions.
8391   /// \pre this->Inst && this->Origin are valid Instructions and this
8392   /// object passed the legal check: LoadedSlice::isLegal returned true.
8393   /// \return The last instruction of the sequence used to load the slice.
8394   SDValue loadSlice() const {
8395     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8396     const SDValue &OldBaseAddr = Origin->getBasePtr();
8397     SDValue BaseAddr = OldBaseAddr;
8398     // Get the offset in that chunk of bytes w.r.t. the endianess.
8399     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8400     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8401     if (Offset) {
8402       // BaseAddr = BaseAddr + Offset.
8403       EVT ArithType = BaseAddr.getValueType();
8404       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8405                               DAG->getConstant(Offset, ArithType));
8406     }
8407
8408     // Create the type of the loaded slice according to its size.
8409     EVT SliceType = getLoadedType();
8410
8411     // Create the load for the slice.
8412     SDValue LastInst = DAG->getLoad(
8413         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8414         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8415         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8416     // If the final type is not the same as the loaded type, this means that
8417     // we have to pad with zero. Create a zero extend for that.
8418     EVT FinalType = Inst->getValueType(0);
8419     if (SliceType != FinalType)
8420       LastInst =
8421           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8422     return LastInst;
8423   }
8424
8425   /// \brief Check if this slice can be merged with an expensive cross register
8426   /// bank copy. E.g.,
8427   /// i = load i32
8428   /// f = bitcast i32 i to float
8429   bool canMergeExpensiveCrossRegisterBankCopy() const {
8430     if (!Inst || !Inst->hasOneUse())
8431       return false;
8432     SDNode *Use = *Inst->use_begin();
8433     if (Use->getOpcode() != ISD::BITCAST)
8434       return false;
8435     assert(DAG && "Missing context");
8436     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8437     EVT ResVT = Use->getValueType(0);
8438     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8439     const TargetRegisterClass *ArgRC =
8440         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8441     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8442       return false;
8443
8444     // At this point, we know that we perform a cross-register-bank copy.
8445     // Check if it is expensive.
8446     const TargetRegisterInfo *TRI =
8447         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8448     // Assume bitcasts are cheap, unless both register classes do not
8449     // explicitly share a common sub class.
8450     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8451       return false;
8452
8453     // Check if it will be merged with the load.
8454     // 1. Check the alignment constraint.
8455     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8456         ResVT.getTypeForEVT(*DAG->getContext()));
8457
8458     if (RequiredAlignment > getAlignment())
8459       return false;
8460
8461     // 2. Check that the load is a legal operation for that type.
8462     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8463       return false;
8464
8465     // 3. Check that we do not have a zext in the way.
8466     if (Inst->getValueType(0) != getLoadedType())
8467       return false;
8468
8469     return true;
8470   }
8471 };
8472 }
8473
8474 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8475 /// \p UsedBits looks like 0..0 1..1 0..0.
8476 static bool areUsedBitsDense(const APInt &UsedBits) {
8477   // If all the bits are one, this is dense!
8478   if (UsedBits.isAllOnesValue())
8479     return true;
8480
8481   // Get rid of the unused bits on the right.
8482   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8483   // Get rid of the unused bits on the left.
8484   if (NarrowedUsedBits.countLeadingZeros())
8485     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8486   // Check that the chunk of bits is completely used.
8487   return NarrowedUsedBits.isAllOnesValue();
8488 }
8489
8490 /// \brief Check whether or not \p First and \p Second are next to each other
8491 /// in memory. This means that there is no hole between the bits loaded
8492 /// by \p First and the bits loaded by \p Second.
8493 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8494                                      const LoadedSlice &Second) {
8495   assert(First.Origin == Second.Origin && First.Origin &&
8496          "Unable to match different memory origins.");
8497   APInt UsedBits = First.getUsedBits();
8498   assert((UsedBits & Second.getUsedBits()) == 0 &&
8499          "Slices are not supposed to overlap.");
8500   UsedBits |= Second.getUsedBits();
8501   return areUsedBitsDense(UsedBits);
8502 }
8503
8504 /// \brief Adjust the \p GlobalLSCost according to the target
8505 /// paring capabilities and the layout of the slices.
8506 /// \pre \p GlobalLSCost should account for at least as many loads as
8507 /// there is in the slices in \p LoadedSlices.
8508 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8509                                  LoadedSlice::Cost &GlobalLSCost) {
8510   unsigned NumberOfSlices = LoadedSlices.size();
8511   // If there is less than 2 elements, no pairing is possible.
8512   if (NumberOfSlices < 2)
8513     return;
8514
8515   // Sort the slices so that elements that are likely to be next to each
8516   // other in memory are next to each other in the list.
8517   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8518             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8519     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8520     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8521   });
8522   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8523   // First (resp. Second) is the first (resp. Second) potentially candidate
8524   // to be placed in a paired load.
8525   const LoadedSlice *First = nullptr;
8526   const LoadedSlice *Second = nullptr;
8527   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8528                 // Set the beginning of the pair.
8529                                                            First = Second) {
8530
8531     Second = &LoadedSlices[CurrSlice];
8532
8533     // If First is NULL, it means we start a new pair.
8534     // Get to the next slice.
8535     if (!First)
8536       continue;
8537
8538     EVT LoadedType = First->getLoadedType();
8539
8540     // If the types of the slices are different, we cannot pair them.
8541     if (LoadedType != Second->getLoadedType())
8542       continue;
8543
8544     // Check if the target supplies paired loads for this type.
8545     unsigned RequiredAlignment = 0;
8546     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8547       // move to the next pair, this type is hopeless.
8548       Second = nullptr;
8549       continue;
8550     }
8551     // Check if we meet the alignment requirement.
8552     if (RequiredAlignment > First->getAlignment())
8553       continue;
8554
8555     // Check that both loads are next to each other in memory.
8556     if (!areSlicesNextToEachOther(*First, *Second))
8557       continue;
8558
8559     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8560     --GlobalLSCost.Loads;
8561     // Move to the next pair.
8562     Second = nullptr;
8563   }
8564 }
8565
8566 /// \brief Check the profitability of all involved LoadedSlice.
8567 /// Currently, it is considered profitable if there is exactly two
8568 /// involved slices (1) which are (2) next to each other in memory, and
8569 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8570 ///
8571 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8572 /// the elements themselves.
8573 ///
8574 /// FIXME: When the cost model will be mature enough, we can relax
8575 /// constraints (1) and (2).
8576 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8577                                 const APInt &UsedBits, bool ForCodeSize) {
8578   unsigned NumberOfSlices = LoadedSlices.size();
8579   if (StressLoadSlicing)
8580     return NumberOfSlices > 1;
8581
8582   // Check (1).
8583   if (NumberOfSlices != 2)
8584     return false;
8585
8586   // Check (2).
8587   if (!areUsedBitsDense(UsedBits))
8588     return false;
8589
8590   // Check (3).
8591   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8592   // The original code has one big load.
8593   OrigCost.Loads = 1;
8594   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8595     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8596     // Accumulate the cost of all the slices.
8597     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8598     GlobalSlicingCost += SliceCost;
8599
8600     // Account as cost in the original configuration the gain obtained
8601     // with the current slices.
8602     OrigCost.addSliceGain(LS);
8603   }
8604
8605   // If the target supports paired load, adjust the cost accordingly.
8606   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8607   return OrigCost > GlobalSlicingCost;
8608 }
8609
8610 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8611 /// operations, split it in the various pieces being extracted.
8612 ///
8613 /// This sort of thing is introduced by SROA.
8614 /// This slicing takes care not to insert overlapping loads.
8615 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8616 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8617   if (Level < AfterLegalizeDAG)
8618     return false;
8619
8620   LoadSDNode *LD = cast<LoadSDNode>(N);
8621   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8622       !LD->getValueType(0).isInteger())
8623     return false;
8624
8625   // Keep track of already used bits to detect overlapping values.
8626   // In that case, we will just abort the transformation.
8627   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8628
8629   SmallVector<LoadedSlice, 4> LoadedSlices;
8630
8631   // Check if this load is used as several smaller chunks of bits.
8632   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8633   // of computation for each trunc.
8634   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8635        UI != UIEnd; ++UI) {
8636     // Skip the uses of the chain.
8637     if (UI.getUse().getResNo() != 0)
8638       continue;
8639
8640     SDNode *User = *UI;
8641     unsigned Shift = 0;
8642
8643     // Check if this is a trunc(lshr).
8644     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8645         isa<ConstantSDNode>(User->getOperand(1))) {
8646       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8647       User = *User->use_begin();
8648     }
8649
8650     // At this point, User is a Truncate, iff we encountered, trunc or
8651     // trunc(lshr).
8652     if (User->getOpcode() != ISD::TRUNCATE)
8653       return false;
8654
8655     // The width of the type must be a power of 2 and greater than 8-bits.
8656     // Otherwise the load cannot be represented in LLVM IR.
8657     // Moreover, if we shifted with a non-8-bits multiple, the slice
8658     // will be across several bytes. We do not support that.
8659     unsigned Width = User->getValueSizeInBits(0);
8660     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8661       return 0;
8662
8663     // Build the slice for this chain of computations.
8664     LoadedSlice LS(User, LD, Shift, &DAG);
8665     APInt CurrentUsedBits = LS.getUsedBits();
8666
8667     // Check if this slice overlaps with another.
8668     if ((CurrentUsedBits & UsedBits) != 0)
8669       return false;
8670     // Update the bits used globally.
8671     UsedBits |= CurrentUsedBits;
8672
8673     // Check if the new slice would be legal.
8674     if (!LS.isLegal())
8675       return false;
8676
8677     // Record the slice.
8678     LoadedSlices.push_back(LS);
8679   }
8680
8681   // Abort slicing if it does not seem to be profitable.
8682   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8683     return false;
8684
8685   ++SlicedLoads;
8686
8687   // Rewrite each chain to use an independent load.
8688   // By construction, each chain can be represented by a unique load.
8689
8690   // Prepare the argument for the new token factor for all the slices.
8691   SmallVector<SDValue, 8> ArgChains;
8692   for (SmallVectorImpl<LoadedSlice>::const_iterator
8693            LSIt = LoadedSlices.begin(),
8694            LSItEnd = LoadedSlices.end();
8695        LSIt != LSItEnd; ++LSIt) {
8696     SDValue SliceInst = LSIt->loadSlice();
8697     CombineTo(LSIt->Inst, SliceInst, true);
8698     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8699       SliceInst = SliceInst.getOperand(0);
8700     assert(SliceInst->getOpcode() == ISD::LOAD &&
8701            "It takes more than a zext to get to the loaded slice!!");
8702     ArgChains.push_back(SliceInst.getValue(1));
8703   }
8704
8705   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8706                               ArgChains);
8707   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8708   return true;
8709 }
8710
8711 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8712 /// load is having specific bytes cleared out.  If so, return the byte size
8713 /// being masked out and the shift amount.
8714 static std::pair<unsigned, unsigned>
8715 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8716   std::pair<unsigned, unsigned> Result(0, 0);
8717
8718   // Check for the structure we're looking for.
8719   if (V->getOpcode() != ISD::AND ||
8720       !isa<ConstantSDNode>(V->getOperand(1)) ||
8721       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8722     return Result;
8723
8724   // Check the chain and pointer.
8725   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8726   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8727
8728   // The store should be chained directly to the load or be an operand of a
8729   // tokenfactor.
8730   if (LD == Chain.getNode())
8731     ; // ok.
8732   else if (Chain->getOpcode() != ISD::TokenFactor)
8733     return Result; // Fail.
8734   else {
8735     bool isOk = false;
8736     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8737       if (Chain->getOperand(i).getNode() == LD) {
8738         isOk = true;
8739         break;
8740       }
8741     if (!isOk) return Result;
8742   }
8743
8744   // This only handles simple types.
8745   if (V.getValueType() != MVT::i16 &&
8746       V.getValueType() != MVT::i32 &&
8747       V.getValueType() != MVT::i64)
8748     return Result;
8749
8750   // Check the constant mask.  Invert it so that the bits being masked out are
8751   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8752   // follow the sign bit for uniformity.
8753   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8754   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8755   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8756   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8757   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8758   if (NotMaskLZ == 64) return Result;  // All zero mask.
8759
8760   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8761   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8762     return Result;
8763
8764   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8765   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8766     NotMaskLZ -= 64-V.getValueSizeInBits();
8767
8768   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8769   switch (MaskedBytes) {
8770   case 1:
8771   case 2:
8772   case 4: break;
8773   default: return Result; // All one mask, or 5-byte mask.
8774   }
8775
8776   // Verify that the first bit starts at a multiple of mask so that the access
8777   // is aligned the same as the access width.
8778   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8779
8780   Result.first = MaskedBytes;
8781   Result.second = NotMaskTZ/8;
8782   return Result;
8783 }
8784
8785
8786 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8787 /// provides a value as specified by MaskInfo.  If so, replace the specified
8788 /// store with a narrower store of truncated IVal.
8789 static SDNode *
8790 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8791                                 SDValue IVal, StoreSDNode *St,
8792                                 DAGCombiner *DC) {
8793   unsigned NumBytes = MaskInfo.first;
8794   unsigned ByteShift = MaskInfo.second;
8795   SelectionDAG &DAG = DC->getDAG();
8796
8797   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8798   // that uses this.  If not, this is not a replacement.
8799   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8800                                   ByteShift*8, (ByteShift+NumBytes)*8);
8801   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8802
8803   // Check that it is legal on the target to do this.  It is legal if the new
8804   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8805   // legalization.
8806   MVT VT = MVT::getIntegerVT(NumBytes*8);
8807   if (!DC->isTypeLegal(VT))
8808     return nullptr;
8809
8810   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8811   // shifted by ByteShift and truncated down to NumBytes.
8812   if (ByteShift)
8813     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8814                        DAG.getConstant(ByteShift*8,
8815                                     DC->getShiftAmountTy(IVal.getValueType())));
8816
8817   // Figure out the offset for the store and the alignment of the access.
8818   unsigned StOffset;
8819   unsigned NewAlign = St->getAlignment();
8820
8821   if (DAG.getTargetLoweringInfo().isLittleEndian())
8822     StOffset = ByteShift;
8823   else
8824     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8825
8826   SDValue Ptr = St->getBasePtr();
8827   if (StOffset) {
8828     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8829                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8830     NewAlign = MinAlign(NewAlign, StOffset);
8831   }
8832
8833   // Truncate down to the new size.
8834   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8835
8836   ++OpsNarrowed;
8837   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8838                       St->getPointerInfo().getWithOffset(StOffset),
8839                       false, false, NewAlign).getNode();
8840 }
8841
8842
8843 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8844 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8845 /// of the loaded bits, try narrowing the load and store if it would end up
8846 /// being a win for performance or code size.
8847 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8848   StoreSDNode *ST  = cast<StoreSDNode>(N);
8849   if (ST->isVolatile())
8850     return SDValue();
8851
8852   SDValue Chain = ST->getChain();
8853   SDValue Value = ST->getValue();
8854   SDValue Ptr   = ST->getBasePtr();
8855   EVT VT = Value.getValueType();
8856
8857   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8858     return SDValue();
8859
8860   unsigned Opc = Value.getOpcode();
8861
8862   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8863   // is a byte mask indicating a consecutive number of bytes, check to see if
8864   // Y is known to provide just those bytes.  If so, we try to replace the
8865   // load + replace + store sequence with a single (narrower) store, which makes
8866   // the load dead.
8867   if (Opc == ISD::OR) {
8868     std::pair<unsigned, unsigned> MaskedLoad;
8869     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8870     if (MaskedLoad.first)
8871       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8872                                                   Value.getOperand(1), ST,this))
8873         return SDValue(NewST, 0);
8874
8875     // Or is commutative, so try swapping X and Y.
8876     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8877     if (MaskedLoad.first)
8878       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8879                                                   Value.getOperand(0), ST,this))
8880         return SDValue(NewST, 0);
8881   }
8882
8883   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8884       Value.getOperand(1).getOpcode() != ISD::Constant)
8885     return SDValue();
8886
8887   SDValue N0 = Value.getOperand(0);
8888   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8889       Chain == SDValue(N0.getNode(), 1)) {
8890     LoadSDNode *LD = cast<LoadSDNode>(N0);
8891     if (LD->getBasePtr() != Ptr ||
8892         LD->getPointerInfo().getAddrSpace() !=
8893         ST->getPointerInfo().getAddrSpace())
8894       return SDValue();
8895
8896     // Find the type to narrow it the load / op / store to.
8897     SDValue N1 = Value.getOperand(1);
8898     unsigned BitWidth = N1.getValueSizeInBits();
8899     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8900     if (Opc == ISD::AND)
8901       Imm ^= APInt::getAllOnesValue(BitWidth);
8902     if (Imm == 0 || Imm.isAllOnesValue())
8903       return SDValue();
8904     unsigned ShAmt = Imm.countTrailingZeros();
8905     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8906     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8907     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8908     while (NewBW < BitWidth &&
8909            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8910              TLI.isNarrowingProfitable(VT, NewVT))) {
8911       NewBW = NextPowerOf2(NewBW);
8912       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8913     }
8914     if (NewBW >= BitWidth)
8915       return SDValue();
8916
8917     // If the lsb changed does not start at the type bitwidth boundary,
8918     // start at the previous one.
8919     if (ShAmt % NewBW)
8920       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8921     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8922                                    std::min(BitWidth, ShAmt + NewBW));
8923     if ((Imm & Mask) == Imm) {
8924       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8925       if (Opc == ISD::AND)
8926         NewImm ^= APInt::getAllOnesValue(NewBW);
8927       uint64_t PtrOff = ShAmt / 8;
8928       // For big endian targets, we need to adjust the offset to the pointer to
8929       // load the correct bytes.
8930       if (TLI.isBigEndian())
8931         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8932
8933       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8934       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8935       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8936         return SDValue();
8937
8938       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8939                                    Ptr.getValueType(), Ptr,
8940                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8941       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8942                                   LD->getChain(), NewPtr,
8943                                   LD->getPointerInfo().getWithOffset(PtrOff),
8944                                   LD->isVolatile(), LD->isNonTemporal(),
8945                                   LD->isInvariant(), NewAlign,
8946                                   LD->getAAInfo());
8947       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8948                                    DAG.getConstant(NewImm, NewVT));
8949       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8950                                    NewVal, NewPtr,
8951                                    ST->getPointerInfo().getWithOffset(PtrOff),
8952                                    false, false, NewAlign);
8953
8954       AddToWorklist(NewPtr.getNode());
8955       AddToWorklist(NewLD.getNode());
8956       AddToWorklist(NewVal.getNode());
8957       WorklistRemover DeadNodes(*this);
8958       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8959       ++OpsNarrowed;
8960       return NewST;
8961     }
8962   }
8963
8964   return SDValue();
8965 }
8966
8967 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8968 /// if the load value isn't used by any other operations, then consider
8969 /// transforming the pair to integer load / store operations if the target
8970 /// deems the transformation profitable.
8971 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8972   StoreSDNode *ST  = cast<StoreSDNode>(N);
8973   SDValue Chain = ST->getChain();
8974   SDValue Value = ST->getValue();
8975   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8976       Value.hasOneUse() &&
8977       Chain == SDValue(Value.getNode(), 1)) {
8978     LoadSDNode *LD = cast<LoadSDNode>(Value);
8979     EVT VT = LD->getMemoryVT();
8980     if (!VT.isFloatingPoint() ||
8981         VT != ST->getMemoryVT() ||
8982         LD->isNonTemporal() ||
8983         ST->isNonTemporal() ||
8984         LD->getPointerInfo().getAddrSpace() != 0 ||
8985         ST->getPointerInfo().getAddrSpace() != 0)
8986       return SDValue();
8987
8988     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8989     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8990         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8991         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8992         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8993       return SDValue();
8994
8995     unsigned LDAlign = LD->getAlignment();
8996     unsigned STAlign = ST->getAlignment();
8997     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8998     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8999     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9000       return SDValue();
9001
9002     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9003                                 LD->getChain(), LD->getBasePtr(),
9004                                 LD->getPointerInfo(),
9005                                 false, false, false, LDAlign);
9006
9007     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9008                                  NewLD, ST->getBasePtr(),
9009                                  ST->getPointerInfo(),
9010                                  false, false, STAlign);
9011
9012     AddToWorklist(NewLD.getNode());
9013     AddToWorklist(NewST.getNode());
9014     WorklistRemover DeadNodes(*this);
9015     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9016     ++LdStFP2Int;
9017     return NewST;
9018   }
9019
9020   return SDValue();
9021 }
9022
9023 /// Helper struct to parse and store a memory address as base + index + offset.
9024 /// We ignore sign extensions when it is safe to do so.
9025 /// The following two expressions are not equivalent. To differentiate we need
9026 /// to store whether there was a sign extension involved in the index
9027 /// computation.
9028 ///  (load (i64 add (i64 copyfromreg %c)
9029 ///                 (i64 signextend (add (i8 load %index)
9030 ///                                      (i8 1))))
9031 /// vs
9032 ///
9033 /// (load (i64 add (i64 copyfromreg %c)
9034 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9035 ///                                         (i32 1)))))
9036 struct BaseIndexOffset {
9037   SDValue Base;
9038   SDValue Index;
9039   int64_t Offset;
9040   bool IsIndexSignExt;
9041
9042   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9043
9044   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9045                   bool IsIndexSignExt) :
9046     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9047
9048   bool equalBaseIndex(const BaseIndexOffset &Other) {
9049     return Other.Base == Base && Other.Index == Index &&
9050       Other.IsIndexSignExt == IsIndexSignExt;
9051   }
9052
9053   /// Parses tree in Ptr for base, index, offset addresses.
9054   static BaseIndexOffset match(SDValue Ptr) {
9055     bool IsIndexSignExt = false;
9056
9057     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9058     // instruction, then it could be just the BASE or everything else we don't
9059     // know how to handle. Just use Ptr as BASE and give up.
9060     if (Ptr->getOpcode() != ISD::ADD)
9061       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9062
9063     // We know that we have at least an ADD instruction. Try to pattern match
9064     // the simple case of BASE + OFFSET.
9065     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9066       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9067       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9068                               IsIndexSignExt);
9069     }
9070
9071     // Inside a loop the current BASE pointer is calculated using an ADD and a
9072     // MUL instruction. In this case Ptr is the actual BASE pointer.
9073     // (i64 add (i64 %array_ptr)
9074     //          (i64 mul (i64 %induction_var)
9075     //                   (i64 %element_size)))
9076     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9077       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9078
9079     // Look at Base + Index + Offset cases.
9080     SDValue Base = Ptr->getOperand(0);
9081     SDValue IndexOffset = Ptr->getOperand(1);
9082
9083     // Skip signextends.
9084     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9085       IndexOffset = IndexOffset->getOperand(0);
9086       IsIndexSignExt = true;
9087     }
9088
9089     // Either the case of Base + Index (no offset) or something else.
9090     if (IndexOffset->getOpcode() != ISD::ADD)
9091       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9092
9093     // Now we have the case of Base + Index + offset.
9094     SDValue Index = IndexOffset->getOperand(0);
9095     SDValue Offset = IndexOffset->getOperand(1);
9096
9097     if (!isa<ConstantSDNode>(Offset))
9098       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9099
9100     // Ignore signextends.
9101     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9102       Index = Index->getOperand(0);
9103       IsIndexSignExt = true;
9104     } else IsIndexSignExt = false;
9105
9106     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9107     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9108   }
9109 };
9110
9111 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9112 /// is located in a sequence of memory operations connected by a chain.
9113 struct MemOpLink {
9114   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9115     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9116   // Ptr to the mem node.
9117   LSBaseSDNode *MemNode;
9118   // Offset from the base ptr.
9119   int64_t OffsetFromBase;
9120   // What is the sequence number of this mem node.
9121   // Lowest mem operand in the DAG starts at zero.
9122   unsigned SequenceNum;
9123 };
9124
9125 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9126   EVT MemVT = St->getMemoryVT();
9127   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9128   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9129     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9130
9131   // Don't merge vectors into wider inputs.
9132   if (MemVT.isVector() || !MemVT.isSimple())
9133     return false;
9134
9135   // Perform an early exit check. Do not bother looking at stored values that
9136   // are not constants or loads.
9137   SDValue StoredVal = St->getValue();
9138   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9139   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9140       !IsLoadSrc)
9141     return false;
9142
9143   // Only look at ends of store sequences.
9144   SDValue Chain = SDValue(St, 0);
9145   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9146     return false;
9147
9148   // This holds the base pointer, index, and the offset in bytes from the base
9149   // pointer.
9150   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9151
9152   // We must have a base and an offset.
9153   if (!BasePtr.Base.getNode())
9154     return false;
9155
9156   // Do not handle stores to undef base pointers.
9157   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9158     return false;
9159
9160   // Save the LoadSDNodes that we find in the chain.
9161   // We need to make sure that these nodes do not interfere with
9162   // any of the store nodes.
9163   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9164
9165   // Save the StoreSDNodes that we find in the chain.
9166   SmallVector<MemOpLink, 8> StoreNodes;
9167
9168   // Walk up the chain and look for nodes with offsets from the same
9169   // base pointer. Stop when reaching an instruction with a different kind
9170   // or instruction which has a different base pointer.
9171   unsigned Seq = 0;
9172   StoreSDNode *Index = St;
9173   while (Index) {
9174     // If the chain has more than one use, then we can't reorder the mem ops.
9175     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9176       break;
9177
9178     // Find the base pointer and offset for this memory node.
9179     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9180
9181     // Check that the base pointer is the same as the original one.
9182     if (!Ptr.equalBaseIndex(BasePtr))
9183       break;
9184
9185     // Check that the alignment is the same.
9186     if (Index->getAlignment() != St->getAlignment())
9187       break;
9188
9189     // The memory operands must not be volatile.
9190     if (Index->isVolatile() || Index->isIndexed())
9191       break;
9192
9193     // No truncation.
9194     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9195       if (St->isTruncatingStore())
9196         break;
9197
9198     // The stored memory type must be the same.
9199     if (Index->getMemoryVT() != MemVT)
9200       break;
9201
9202     // We do not allow unaligned stores because we want to prevent overriding
9203     // stores.
9204     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9205       break;
9206
9207     // We found a potential memory operand to merge.
9208     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9209
9210     // Find the next memory operand in the chain. If the next operand in the
9211     // chain is a store then move up and continue the scan with the next
9212     // memory operand. If the next operand is a load save it and use alias
9213     // information to check if it interferes with anything.
9214     SDNode *NextInChain = Index->getChain().getNode();
9215     while (1) {
9216       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9217         // We found a store node. Use it for the next iteration.
9218         Index = STn;
9219         break;
9220       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9221         if (Ldn->isVolatile()) {
9222           Index = nullptr;
9223           break;
9224         }
9225
9226         // Save the load node for later. Continue the scan.
9227         AliasLoadNodes.push_back(Ldn);
9228         NextInChain = Ldn->getChain().getNode();
9229         continue;
9230       } else {
9231         Index = nullptr;
9232         break;
9233       }
9234     }
9235   }
9236
9237   // Check if there is anything to merge.
9238   if (StoreNodes.size() < 2)
9239     return false;
9240
9241   // Sort the memory operands according to their distance from the base pointer.
9242   std::sort(StoreNodes.begin(), StoreNodes.end(),
9243             [](MemOpLink LHS, MemOpLink RHS) {
9244     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9245            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9246             LHS.SequenceNum > RHS.SequenceNum);
9247   });
9248
9249   // Scan the memory operations on the chain and find the first non-consecutive
9250   // store memory address.
9251   unsigned LastConsecutiveStore = 0;
9252   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9253   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9254
9255     // Check that the addresses are consecutive starting from the second
9256     // element in the list of stores.
9257     if (i > 0) {
9258       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9259       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9260         break;
9261     }
9262
9263     bool Alias = false;
9264     // Check if this store interferes with any of the loads that we found.
9265     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9266       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9267         Alias = true;
9268         break;
9269       }
9270     // We found a load that alias with this store. Stop the sequence.
9271     if (Alias)
9272       break;
9273
9274     // Mark this node as useful.
9275     LastConsecutiveStore = i;
9276   }
9277
9278   // The node with the lowest store address.
9279   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9280
9281   // Store the constants into memory as one consecutive store.
9282   if (!IsLoadSrc) {
9283     unsigned LastLegalType = 0;
9284     unsigned LastLegalVectorType = 0;
9285     bool NonZero = false;
9286     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9287       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9288       SDValue StoredVal = St->getValue();
9289
9290       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9291         NonZero |= !C->isNullValue();
9292       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9293         NonZero |= !C->getConstantFPValue()->isNullValue();
9294       } else {
9295         // Non-constant.
9296         break;
9297       }
9298
9299       // Find a legal type for the constant store.
9300       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9301       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9302       if (TLI.isTypeLegal(StoreTy))
9303         LastLegalType = i+1;
9304       // Or check whether a truncstore is legal.
9305       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9306                TargetLowering::TypePromoteInteger) {
9307         EVT LegalizedStoredValueTy =
9308           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9309         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9310           LastLegalType = i+1;
9311       }
9312
9313       // Find a legal type for the vector store.
9314       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9315       if (TLI.isTypeLegal(Ty))
9316         LastLegalVectorType = i + 1;
9317     }
9318
9319     // We only use vectors if the constant is known to be zero and the
9320     // function is not marked with the noimplicitfloat attribute.
9321     if (NonZero || NoVectors)
9322       LastLegalVectorType = 0;
9323
9324     // Check if we found a legal integer type to store.
9325     if (LastLegalType == 0 && LastLegalVectorType == 0)
9326       return false;
9327
9328     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9329     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9330
9331     // Make sure we have something to merge.
9332     if (NumElem < 2)
9333       return false;
9334
9335     unsigned EarliestNodeUsed = 0;
9336     for (unsigned i=0; i < NumElem; ++i) {
9337       // Find a chain for the new wide-store operand. Notice that some
9338       // of the store nodes that we found may not be selected for inclusion
9339       // in the wide store. The chain we use needs to be the chain of the
9340       // earliest store node which is *used* and replaced by the wide store.
9341       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9342         EarliestNodeUsed = i;
9343     }
9344
9345     // The earliest Node in the DAG.
9346     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9347     SDLoc DL(StoreNodes[0].MemNode);
9348
9349     SDValue StoredVal;
9350     if (UseVector) {
9351       // Find a legal type for the vector store.
9352       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9353       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9354       StoredVal = DAG.getConstant(0, Ty);
9355     } else {
9356       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9357       APInt StoreInt(StoreBW, 0);
9358
9359       // Construct a single integer constant which is made of the smaller
9360       // constant inputs.
9361       bool IsLE = TLI.isLittleEndian();
9362       for (unsigned i = 0; i < NumElem ; ++i) {
9363         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9364         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9365         SDValue Val = St->getValue();
9366         StoreInt<<=ElementSizeBytes*8;
9367         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9368           StoreInt|=C->getAPIntValue().zext(StoreBW);
9369         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9370           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9371         } else {
9372           assert(false && "Invalid constant element type");
9373         }
9374       }
9375
9376       // Create the new Load and Store operations.
9377       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9378       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9379     }
9380
9381     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9382                                     FirstInChain->getBasePtr(),
9383                                     FirstInChain->getPointerInfo(),
9384                                     false, false,
9385                                     FirstInChain->getAlignment());
9386
9387     // Replace the first store with the new store
9388     CombineTo(EarliestOp, NewStore);
9389     // Erase all other stores.
9390     for (unsigned i = 0; i < NumElem ; ++i) {
9391       if (StoreNodes[i].MemNode == EarliestOp)
9392         continue;
9393       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9394       // ReplaceAllUsesWith will replace all uses that existed when it was
9395       // called, but graph optimizations may cause new ones to appear. For
9396       // example, the case in pr14333 looks like
9397       //
9398       //  St's chain -> St -> another store -> X
9399       //
9400       // And the only difference from St to the other store is the chain.
9401       // When we change it's chain to be St's chain they become identical,
9402       // get CSEed and the net result is that X is now a use of St.
9403       // Since we know that St is redundant, just iterate.
9404       while (!St->use_empty())
9405         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9406       deleteAndRecombine(St);
9407     }
9408
9409     return true;
9410   }
9411
9412   // Below we handle the case of multiple consecutive stores that
9413   // come from multiple consecutive loads. We merge them into a single
9414   // wide load and a single wide store.
9415
9416   // Look for load nodes which are used by the stored values.
9417   SmallVector<MemOpLink, 8> LoadNodes;
9418
9419   // Find acceptable loads. Loads need to have the same chain (token factor),
9420   // must not be zext, volatile, indexed, and they must be consecutive.
9421   BaseIndexOffset LdBasePtr;
9422   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9423     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9424     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9425     if (!Ld) break;
9426
9427     // Loads must only have one use.
9428     if (!Ld->hasNUsesOfValue(1, 0))
9429       break;
9430
9431     // Check that the alignment is the same as the stores.
9432     if (Ld->getAlignment() != St->getAlignment())
9433       break;
9434
9435     // The memory operands must not be volatile.
9436     if (Ld->isVolatile() || Ld->isIndexed())
9437       break;
9438
9439     // We do not accept ext loads.
9440     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9441       break;
9442
9443     // The stored memory type must be the same.
9444     if (Ld->getMemoryVT() != MemVT)
9445       break;
9446
9447     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9448     // If this is not the first ptr that we check.
9449     if (LdBasePtr.Base.getNode()) {
9450       // The base ptr must be the same.
9451       if (!LdPtr.equalBaseIndex(LdBasePtr))
9452         break;
9453     } else {
9454       // Check that all other base pointers are the same as this one.
9455       LdBasePtr = LdPtr;
9456     }
9457
9458     // We found a potential memory operand to merge.
9459     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9460   }
9461
9462   if (LoadNodes.size() < 2)
9463     return false;
9464
9465   // If we have load/store pair instructions and we only have two values,
9466   // don't bother.
9467   unsigned RequiredAlignment;
9468   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9469       St->getAlignment() >= RequiredAlignment)
9470     return false;
9471
9472   // Scan the memory operations on the chain and find the first non-consecutive
9473   // load memory address. These variables hold the index in the store node
9474   // array.
9475   unsigned LastConsecutiveLoad = 0;
9476   // This variable refers to the size and not index in the array.
9477   unsigned LastLegalVectorType = 0;
9478   unsigned LastLegalIntegerType = 0;
9479   StartAddress = LoadNodes[0].OffsetFromBase;
9480   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9481   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9482     // All loads much share the same chain.
9483     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9484       break;
9485
9486     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9487     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9488       break;
9489     LastConsecutiveLoad = i;
9490
9491     // Find a legal type for the vector store.
9492     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9493     if (TLI.isTypeLegal(StoreTy))
9494       LastLegalVectorType = i + 1;
9495
9496     // Find a legal type for the integer store.
9497     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9498     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9499     if (TLI.isTypeLegal(StoreTy))
9500       LastLegalIntegerType = i + 1;
9501     // Or check whether a truncstore and extload is legal.
9502     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9503              TargetLowering::TypePromoteInteger) {
9504       EVT LegalizedStoredValueTy =
9505         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9506       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9507           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9508           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9509           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9510         LastLegalIntegerType = i+1;
9511     }
9512   }
9513
9514   // Only use vector types if the vector type is larger than the integer type.
9515   // If they are the same, use integers.
9516   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9517   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9518
9519   // We add +1 here because the LastXXX variables refer to location while
9520   // the NumElem refers to array/index size.
9521   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9522   NumElem = std::min(LastLegalType, NumElem);
9523
9524   if (NumElem < 2)
9525     return false;
9526
9527   // The earliest Node in the DAG.
9528   unsigned EarliestNodeUsed = 0;
9529   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9530   for (unsigned i=1; i<NumElem; ++i) {
9531     // Find a chain for the new wide-store operand. Notice that some
9532     // of the store nodes that we found may not be selected for inclusion
9533     // in the wide store. The chain we use needs to be the chain of the
9534     // earliest store node which is *used* and replaced by the wide store.
9535     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9536       EarliestNodeUsed = i;
9537   }
9538
9539   // Find if it is better to use vectors or integers to load and store
9540   // to memory.
9541   EVT JointMemOpVT;
9542   if (UseVectorTy) {
9543     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9544   } else {
9545     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9546     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9547   }
9548
9549   SDLoc LoadDL(LoadNodes[0].MemNode);
9550   SDLoc StoreDL(StoreNodes[0].MemNode);
9551
9552   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9553   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9554                                 FirstLoad->getChain(),
9555                                 FirstLoad->getBasePtr(),
9556                                 FirstLoad->getPointerInfo(),
9557                                 false, false, false,
9558                                 FirstLoad->getAlignment());
9559
9560   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9561                                   FirstInChain->getBasePtr(),
9562                                   FirstInChain->getPointerInfo(), false, false,
9563                                   FirstInChain->getAlignment());
9564
9565   // Replace one of the loads with the new load.
9566   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9567   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9568                                 SDValue(NewLoad.getNode(), 1));
9569
9570   // Remove the rest of the load chains.
9571   for (unsigned i = 1; i < NumElem ; ++i) {
9572     // Replace all chain users of the old load nodes with the chain of the new
9573     // load node.
9574     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9575     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9576   }
9577
9578   // Replace the first store with the new store.
9579   CombineTo(EarliestOp, NewStore);
9580   // Erase all other stores.
9581   for (unsigned i = 0; i < NumElem ; ++i) {
9582     // Remove all Store nodes.
9583     if (StoreNodes[i].MemNode == EarliestOp)
9584       continue;
9585     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9586     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9587     deleteAndRecombine(St);
9588   }
9589
9590   return true;
9591 }
9592
9593 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9594   StoreSDNode *ST  = cast<StoreSDNode>(N);
9595   SDValue Chain = ST->getChain();
9596   SDValue Value = ST->getValue();
9597   SDValue Ptr   = ST->getBasePtr();
9598
9599   // If this is a store of a bit convert, store the input value if the
9600   // resultant store does not need a higher alignment than the original.
9601   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9602       ST->isUnindexed()) {
9603     unsigned OrigAlign = ST->getAlignment();
9604     EVT SVT = Value.getOperand(0).getValueType();
9605     unsigned Align = TLI.getDataLayout()->
9606       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9607     if (Align <= OrigAlign &&
9608         ((!LegalOperations && !ST->isVolatile()) ||
9609          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9610       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9611                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9612                           ST->isNonTemporal(), OrigAlign,
9613                           ST->getAAInfo());
9614   }
9615
9616   // Turn 'store undef, Ptr' -> nothing.
9617   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9618     return Chain;
9619
9620   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9621   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9622     // NOTE: If the original store is volatile, this transform must not increase
9623     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9624     // processor operation but an i64 (which is not legal) requires two.  So the
9625     // transform should not be done in this case.
9626     if (Value.getOpcode() != ISD::TargetConstantFP) {
9627       SDValue Tmp;
9628       switch (CFP->getSimpleValueType(0).SimpleTy) {
9629       default: llvm_unreachable("Unknown FP type");
9630       case MVT::f16:    // We don't do this for these yet.
9631       case MVT::f80:
9632       case MVT::f128:
9633       case MVT::ppcf128:
9634         break;
9635       case MVT::f32:
9636         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9637             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9638           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9639                               bitcastToAPInt().getZExtValue(), MVT::i32);
9640           return DAG.getStore(Chain, SDLoc(N), Tmp,
9641                               Ptr, ST->getMemOperand());
9642         }
9643         break;
9644       case MVT::f64:
9645         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9646              !ST->isVolatile()) ||
9647             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9648           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9649                                 getZExtValue(), MVT::i64);
9650           return DAG.getStore(Chain, SDLoc(N), Tmp,
9651                               Ptr, ST->getMemOperand());
9652         }
9653
9654         if (!ST->isVolatile() &&
9655             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9656           // Many FP stores are not made apparent until after legalize, e.g. for
9657           // argument passing.  Since this is so common, custom legalize the
9658           // 64-bit integer store into two 32-bit stores.
9659           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9660           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9661           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9662           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9663
9664           unsigned Alignment = ST->getAlignment();
9665           bool isVolatile = ST->isVolatile();
9666           bool isNonTemporal = ST->isNonTemporal();
9667           AAMDNodes AAInfo = ST->getAAInfo();
9668
9669           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9670                                      Ptr, ST->getPointerInfo(),
9671                                      isVolatile, isNonTemporal,
9672                                      ST->getAlignment(), AAInfo);
9673           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9674                             DAG.getConstant(4, Ptr.getValueType()));
9675           Alignment = MinAlign(Alignment, 4U);
9676           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9677                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9678                                      isVolatile, isNonTemporal,
9679                                      Alignment, AAInfo);
9680           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9681                              St0, St1);
9682         }
9683
9684         break;
9685       }
9686     }
9687   }
9688
9689   // Try to infer better alignment information than the store already has.
9690   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9691     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9692       if (Align > ST->getAlignment())
9693         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9694                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9695                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9696                                  ST->getAAInfo());
9697     }
9698   }
9699
9700   // Try transforming a pair floating point load / store ops to integer
9701   // load / store ops.
9702   SDValue NewST = TransformFPLoadStorePair(N);
9703   if (NewST.getNode())
9704     return NewST;
9705
9706   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9707     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9708 #ifndef NDEBUG
9709   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9710       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9711     UseAA = false;
9712 #endif
9713   if (UseAA && ST->isUnindexed()) {
9714     // Walk up chain skipping non-aliasing memory nodes.
9715     SDValue BetterChain = FindBetterChain(N, Chain);
9716
9717     // If there is a better chain.
9718     if (Chain != BetterChain) {
9719       SDValue ReplStore;
9720
9721       // Replace the chain to avoid dependency.
9722       if (ST->isTruncatingStore()) {
9723         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9724                                       ST->getMemoryVT(), ST->getMemOperand());
9725       } else {
9726         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9727                                  ST->getMemOperand());
9728       }
9729
9730       // Create token to keep both nodes around.
9731       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9732                                   MVT::Other, Chain, ReplStore);
9733
9734       // Make sure the new and old chains are cleaned up.
9735       AddToWorklist(Token.getNode());
9736
9737       // Don't add users to work list.
9738       return CombineTo(N, Token, false);
9739     }
9740   }
9741
9742   // Try transforming N to an indexed store.
9743   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9744     return SDValue(N, 0);
9745
9746   // FIXME: is there such a thing as a truncating indexed store?
9747   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9748       Value.getValueType().isInteger()) {
9749     // See if we can simplify the input to this truncstore with knowledge that
9750     // only the low bits are being used.  For example:
9751     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9752     SDValue Shorter =
9753       GetDemandedBits(Value,
9754                       APInt::getLowBitsSet(
9755                         Value.getValueType().getScalarType().getSizeInBits(),
9756                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9757     AddToWorklist(Value.getNode());
9758     if (Shorter.getNode())
9759       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9760                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9761
9762     // Otherwise, see if we can simplify the operation with
9763     // SimplifyDemandedBits, which only works if the value has a single use.
9764     if (SimplifyDemandedBits(Value,
9765                         APInt::getLowBitsSet(
9766                           Value.getValueType().getScalarType().getSizeInBits(),
9767                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9768       return SDValue(N, 0);
9769   }
9770
9771   // If this is a load followed by a store to the same location, then the store
9772   // is dead/noop.
9773   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9774     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9775         ST->isUnindexed() && !ST->isVolatile() &&
9776         // There can't be any side effects between the load and store, such as
9777         // a call or store.
9778         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9779       // The store is dead, remove it.
9780       return Chain;
9781     }
9782   }
9783
9784   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9785   // truncating store.  We can do this even if this is already a truncstore.
9786   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9787       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9788       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9789                             ST->getMemoryVT())) {
9790     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9791                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9792   }
9793
9794   // Only perform this optimization before the types are legal, because we
9795   // don't want to perform this optimization on every DAGCombine invocation.
9796   if (!LegalTypes) {
9797     bool EverChanged = false;
9798
9799     do {
9800       // There can be multiple store sequences on the same chain.
9801       // Keep trying to merge store sequences until we are unable to do so
9802       // or until we merge the last store on the chain.
9803       bool Changed = MergeConsecutiveStores(ST);
9804       EverChanged |= Changed;
9805       if (!Changed) break;
9806     } while (ST->getOpcode() != ISD::DELETED_NODE);
9807
9808     if (EverChanged)
9809       return SDValue(N, 0);
9810   }
9811
9812   return ReduceLoadOpStoreWidth(N);
9813 }
9814
9815 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9816   SDValue InVec = N->getOperand(0);
9817   SDValue InVal = N->getOperand(1);
9818   SDValue EltNo = N->getOperand(2);
9819   SDLoc dl(N);
9820
9821   // If the inserted element is an UNDEF, just use the input vector.
9822   if (InVal.getOpcode() == ISD::UNDEF)
9823     return InVec;
9824
9825   EVT VT = InVec.getValueType();
9826
9827   // If we can't generate a legal BUILD_VECTOR, exit
9828   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9829     return SDValue();
9830
9831   // Check that we know which element is being inserted
9832   if (!isa<ConstantSDNode>(EltNo))
9833     return SDValue();
9834   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9835
9836   // Canonicalize insert_vector_elt dag nodes.
9837   // Example:
9838   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9839   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9840   //
9841   // Do this only if the child insert_vector node has one use; also
9842   // do this only if indices are both constants and Idx1 < Idx0.
9843   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9844       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9845     unsigned OtherElt =
9846       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9847     if (Elt < OtherElt) {
9848       // Swap nodes.
9849       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9850                                   InVec.getOperand(0), InVal, EltNo);
9851       AddToWorklist(NewOp.getNode());
9852       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9853                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9854     }
9855   }
9856
9857   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9858   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9859   // vector elements.
9860   SmallVector<SDValue, 8> Ops;
9861   // Do not combine these two vectors if the output vector will not replace
9862   // the input vector.
9863   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9864     Ops.append(InVec.getNode()->op_begin(),
9865                InVec.getNode()->op_end());
9866   } else if (InVec.getOpcode() == ISD::UNDEF) {
9867     unsigned NElts = VT.getVectorNumElements();
9868     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9869   } else {
9870     return SDValue();
9871   }
9872
9873   // Insert the element
9874   if (Elt < Ops.size()) {
9875     // All the operands of BUILD_VECTOR must have the same type;
9876     // we enforce that here.
9877     EVT OpVT = Ops[0].getValueType();
9878     if (InVal.getValueType() != OpVT)
9879       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9880                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9881                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9882     Ops[Elt] = InVal;
9883   }
9884
9885   // Return the new vector
9886   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9887 }
9888
9889 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9890     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9891   EVT ResultVT = EVE->getValueType(0);
9892   EVT VecEltVT = InVecVT.getVectorElementType();
9893   unsigned Align = OriginalLoad->getAlignment();
9894   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9895       VecEltVT.getTypeForEVT(*DAG.getContext()));
9896
9897   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9898     return SDValue();
9899
9900   Align = NewAlign;
9901
9902   SDValue NewPtr = OriginalLoad->getBasePtr();
9903   SDValue Offset;
9904   EVT PtrType = NewPtr.getValueType();
9905   MachinePointerInfo MPI;
9906   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9907     int Elt = ConstEltNo->getZExtValue();
9908     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9909     if (TLI.isBigEndian())
9910       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9911     Offset = DAG.getConstant(PtrOff, PtrType);
9912     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9913   } else {
9914     Offset = DAG.getNode(
9915         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9916         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9917     if (TLI.isBigEndian())
9918       Offset = DAG.getNode(
9919           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9920           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9921     MPI = OriginalLoad->getPointerInfo();
9922   }
9923   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9924
9925   // The replacement we need to do here is a little tricky: we need to
9926   // replace an extractelement of a load with a load.
9927   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9928   // Note that this replacement assumes that the extractvalue is the only
9929   // use of the load; that's okay because we don't want to perform this
9930   // transformation in other cases anyway.
9931   SDValue Load;
9932   SDValue Chain;
9933   if (ResultVT.bitsGT(VecEltVT)) {
9934     // If the result type of vextract is wider than the load, then issue an
9935     // extending load instead.
9936     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9937                                    ? ISD::ZEXTLOAD
9938                                    : ISD::EXTLOAD;
9939     Load = DAG.getExtLoad(
9940         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9941         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9942         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9943     Chain = Load.getValue(1);
9944   } else {
9945     Load = DAG.getLoad(
9946         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9947         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9948         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9949     Chain = Load.getValue(1);
9950     if (ResultVT.bitsLT(VecEltVT))
9951       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9952     else
9953       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9954   }
9955   WorklistRemover DeadNodes(*this);
9956   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9957   SDValue To[] = { Load, Chain };
9958   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9959   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9960   // worklist explicitly as well.
9961   AddToWorklist(Load.getNode());
9962   AddUsersToWorklist(Load.getNode()); // Add users too
9963   // Make sure to revisit this node to clean it up; it will usually be dead.
9964   AddToWorklist(EVE);
9965   ++OpsNarrowed;
9966   return SDValue(EVE, 0);
9967 }
9968
9969 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9970   // (vextract (scalar_to_vector val, 0) -> val
9971   SDValue InVec = N->getOperand(0);
9972   EVT VT = InVec.getValueType();
9973   EVT NVT = N->getValueType(0);
9974
9975   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9976     // Check if the result type doesn't match the inserted element type. A
9977     // SCALAR_TO_VECTOR may truncate the inserted element and the
9978     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9979     SDValue InOp = InVec.getOperand(0);
9980     if (InOp.getValueType() != NVT) {
9981       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9982       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9983     }
9984     return InOp;
9985   }
9986
9987   SDValue EltNo = N->getOperand(1);
9988   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9989
9990   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9991   // We only perform this optimization before the op legalization phase because
9992   // we may introduce new vector instructions which are not backed by TD
9993   // patterns. For example on AVX, extracting elements from a wide vector
9994   // without using extract_subvector. However, if we can find an underlying
9995   // scalar value, then we can always use that.
9996   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9997       && ConstEltNo) {
9998     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9999     int NumElem = VT.getVectorNumElements();
10000     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10001     // Find the new index to extract from.
10002     int OrigElt = SVOp->getMaskElt(Elt);
10003
10004     // Extracting an undef index is undef.
10005     if (OrigElt == -1)
10006       return DAG.getUNDEF(NVT);
10007
10008     // Select the right vector half to extract from.
10009     SDValue SVInVec;
10010     if (OrigElt < NumElem) {
10011       SVInVec = InVec->getOperand(0);
10012     } else {
10013       SVInVec = InVec->getOperand(1);
10014       OrigElt -= NumElem;
10015     }
10016
10017     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10018       SDValue InOp = SVInVec.getOperand(OrigElt);
10019       if (InOp.getValueType() != NVT) {
10020         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10021         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10022       }
10023
10024       return InOp;
10025     }
10026
10027     // FIXME: We should handle recursing on other vector shuffles and
10028     // scalar_to_vector here as well.
10029
10030     if (!LegalOperations) {
10031       EVT IndexTy = TLI.getVectorIdxTy();
10032       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10033                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10034     }
10035   }
10036
10037   bool BCNumEltsChanged = false;
10038   EVT ExtVT = VT.getVectorElementType();
10039   EVT LVT = ExtVT;
10040
10041   // If the result of load has to be truncated, then it's not necessarily
10042   // profitable.
10043   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10044     return SDValue();
10045
10046   if (InVec.getOpcode() == ISD::BITCAST) {
10047     // Don't duplicate a load with other uses.
10048     if (!InVec.hasOneUse())
10049       return SDValue();
10050
10051     EVT BCVT = InVec.getOperand(0).getValueType();
10052     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10053       return SDValue();
10054     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10055       BCNumEltsChanged = true;
10056     InVec = InVec.getOperand(0);
10057     ExtVT = BCVT.getVectorElementType();
10058   }
10059
10060   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10061   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10062       ISD::isNormalLoad(InVec.getNode()) &&
10063       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10064     SDValue Index = N->getOperand(1);
10065     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10066       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10067                                                            OrigLoad);
10068   }
10069
10070   // Perform only after legalization to ensure build_vector / vector_shuffle
10071   // optimizations have already been done.
10072   if (!LegalOperations) return SDValue();
10073
10074   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10075   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10076   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10077
10078   if (ConstEltNo) {
10079     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10080
10081     LoadSDNode *LN0 = nullptr;
10082     const ShuffleVectorSDNode *SVN = nullptr;
10083     if (ISD::isNormalLoad(InVec.getNode())) {
10084       LN0 = cast<LoadSDNode>(InVec);
10085     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10086                InVec.getOperand(0).getValueType() == ExtVT &&
10087                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10088       // Don't duplicate a load with other uses.
10089       if (!InVec.hasOneUse())
10090         return SDValue();
10091
10092       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10093     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10094       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10095       // =>
10096       // (load $addr+1*size)
10097
10098       // Don't duplicate a load with other uses.
10099       if (!InVec.hasOneUse())
10100         return SDValue();
10101
10102       // If the bit convert changed the number of elements, it is unsafe
10103       // to examine the mask.
10104       if (BCNumEltsChanged)
10105         return SDValue();
10106
10107       // Select the input vector, guarding against out of range extract vector.
10108       unsigned NumElems = VT.getVectorNumElements();
10109       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10110       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10111
10112       if (InVec.getOpcode() == ISD::BITCAST) {
10113         // Don't duplicate a load with other uses.
10114         if (!InVec.hasOneUse())
10115           return SDValue();
10116
10117         InVec = InVec.getOperand(0);
10118       }
10119       if (ISD::isNormalLoad(InVec.getNode())) {
10120         LN0 = cast<LoadSDNode>(InVec);
10121         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10122         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10123       }
10124     }
10125
10126     // Make sure we found a non-volatile load and the extractelement is
10127     // the only use.
10128     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10129       return SDValue();
10130
10131     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10132     if (Elt == -1)
10133       return DAG.getUNDEF(LVT);
10134
10135     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10136   }
10137
10138   return SDValue();
10139 }
10140
10141 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10142 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10143   // We perform this optimization post type-legalization because
10144   // the type-legalizer often scalarizes integer-promoted vectors.
10145   // Performing this optimization before may create bit-casts which
10146   // will be type-legalized to complex code sequences.
10147   // We perform this optimization only before the operation legalizer because we
10148   // may introduce illegal operations.
10149   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10150     return SDValue();
10151
10152   unsigned NumInScalars = N->getNumOperands();
10153   SDLoc dl(N);
10154   EVT VT = N->getValueType(0);
10155
10156   // Check to see if this is a BUILD_VECTOR of a bunch of values
10157   // which come from any_extend or zero_extend nodes. If so, we can create
10158   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10159   // optimizations. We do not handle sign-extend because we can't fill the sign
10160   // using shuffles.
10161   EVT SourceType = MVT::Other;
10162   bool AllAnyExt = true;
10163
10164   for (unsigned i = 0; i != NumInScalars; ++i) {
10165     SDValue In = N->getOperand(i);
10166     // Ignore undef inputs.
10167     if (In.getOpcode() == ISD::UNDEF) continue;
10168
10169     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10170     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10171
10172     // Abort if the element is not an extension.
10173     if (!ZeroExt && !AnyExt) {
10174       SourceType = MVT::Other;
10175       break;
10176     }
10177
10178     // The input is a ZeroExt or AnyExt. Check the original type.
10179     EVT InTy = In.getOperand(0).getValueType();
10180
10181     // Check that all of the widened source types are the same.
10182     if (SourceType == MVT::Other)
10183       // First time.
10184       SourceType = InTy;
10185     else if (InTy != SourceType) {
10186       // Multiple income types. Abort.
10187       SourceType = MVT::Other;
10188       break;
10189     }
10190
10191     // Check if all of the extends are ANY_EXTENDs.
10192     AllAnyExt &= AnyExt;
10193   }
10194
10195   // In order to have valid types, all of the inputs must be extended from the
10196   // same source type and all of the inputs must be any or zero extend.
10197   // Scalar sizes must be a power of two.
10198   EVT OutScalarTy = VT.getScalarType();
10199   bool ValidTypes = SourceType != MVT::Other &&
10200                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10201                  isPowerOf2_32(SourceType.getSizeInBits());
10202
10203   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10204   // turn into a single shuffle instruction.
10205   if (!ValidTypes)
10206     return SDValue();
10207
10208   bool isLE = TLI.isLittleEndian();
10209   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10210   assert(ElemRatio > 1 && "Invalid element size ratio");
10211   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10212                                DAG.getConstant(0, SourceType);
10213
10214   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10215   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10216
10217   // Populate the new build_vector
10218   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10219     SDValue Cast = N->getOperand(i);
10220     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10221             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10222             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10223     SDValue In;
10224     if (Cast.getOpcode() == ISD::UNDEF)
10225       In = DAG.getUNDEF(SourceType);
10226     else
10227       In = Cast->getOperand(0);
10228     unsigned Index = isLE ? (i * ElemRatio) :
10229                             (i * ElemRatio + (ElemRatio - 1));
10230
10231     assert(Index < Ops.size() && "Invalid index");
10232     Ops[Index] = In;
10233   }
10234
10235   // The type of the new BUILD_VECTOR node.
10236   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10237   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10238          "Invalid vector size");
10239   // Check if the new vector type is legal.
10240   if (!isTypeLegal(VecVT)) return SDValue();
10241
10242   // Make the new BUILD_VECTOR.
10243   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10244
10245   // The new BUILD_VECTOR node has the potential to be further optimized.
10246   AddToWorklist(BV.getNode());
10247   // Bitcast to the desired type.
10248   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10249 }
10250
10251 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10252   EVT VT = N->getValueType(0);
10253
10254   unsigned NumInScalars = N->getNumOperands();
10255   SDLoc dl(N);
10256
10257   EVT SrcVT = MVT::Other;
10258   unsigned Opcode = ISD::DELETED_NODE;
10259   unsigned NumDefs = 0;
10260
10261   for (unsigned i = 0; i != NumInScalars; ++i) {
10262     SDValue In = N->getOperand(i);
10263     unsigned Opc = In.getOpcode();
10264
10265     if (Opc == ISD::UNDEF)
10266       continue;
10267
10268     // If all scalar values are floats and converted from integers.
10269     if (Opcode == ISD::DELETED_NODE &&
10270         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10271       Opcode = Opc;
10272     }
10273
10274     if (Opc != Opcode)
10275       return SDValue();
10276
10277     EVT InVT = In.getOperand(0).getValueType();
10278
10279     // If all scalar values are typed differently, bail out. It's chosen to
10280     // simplify BUILD_VECTOR of integer types.
10281     if (SrcVT == MVT::Other)
10282       SrcVT = InVT;
10283     if (SrcVT != InVT)
10284       return SDValue();
10285     NumDefs++;
10286   }
10287
10288   // If the vector has just one element defined, it's not worth to fold it into
10289   // a vectorized one.
10290   if (NumDefs < 2)
10291     return SDValue();
10292
10293   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10294          && "Should only handle conversion from integer to float.");
10295   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10296
10297   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10298
10299   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10300     return SDValue();
10301
10302   SmallVector<SDValue, 8> Opnds;
10303   for (unsigned i = 0; i != NumInScalars; ++i) {
10304     SDValue In = N->getOperand(i);
10305
10306     if (In.getOpcode() == ISD::UNDEF)
10307       Opnds.push_back(DAG.getUNDEF(SrcVT));
10308     else
10309       Opnds.push_back(In.getOperand(0));
10310   }
10311   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10312   AddToWorklist(BV.getNode());
10313
10314   return DAG.getNode(Opcode, dl, VT, BV);
10315 }
10316
10317 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10318   unsigned NumInScalars = N->getNumOperands();
10319   SDLoc dl(N);
10320   EVT VT = N->getValueType(0);
10321
10322   // A vector built entirely of undefs is undef.
10323   if (ISD::allOperandsUndef(N))
10324     return DAG.getUNDEF(VT);
10325
10326   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10327   if (V.getNode())
10328     return V;
10329
10330   V = reduceBuildVecConvertToConvertBuildVec(N);
10331   if (V.getNode())
10332     return V;
10333
10334   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10335   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10336   // at most two distinct vectors, turn this into a shuffle node.
10337
10338   // May only combine to shuffle after legalize if shuffle is legal.
10339   if (LegalOperations &&
10340       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10341     return SDValue();
10342
10343   SDValue VecIn1, VecIn2;
10344   for (unsigned i = 0; i != NumInScalars; ++i) {
10345     // Ignore undef inputs.
10346     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10347
10348     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10349     // constant index, bail out.
10350     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10351         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10352       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10353       break;
10354     }
10355
10356     // We allow up to two distinct input vectors.
10357     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10358     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10359       continue;
10360
10361     if (!VecIn1.getNode()) {
10362       VecIn1 = ExtractedFromVec;
10363     } else if (!VecIn2.getNode()) {
10364       VecIn2 = ExtractedFromVec;
10365     } else {
10366       // Too many inputs.
10367       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10368       break;
10369     }
10370   }
10371
10372   // If everything is good, we can make a shuffle operation.
10373   if (VecIn1.getNode()) {
10374     SmallVector<int, 8> Mask;
10375     for (unsigned i = 0; i != NumInScalars; ++i) {
10376       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10377         Mask.push_back(-1);
10378         continue;
10379       }
10380
10381       // If extracting from the first vector, just use the index directly.
10382       SDValue Extract = N->getOperand(i);
10383       SDValue ExtVal = Extract.getOperand(1);
10384       if (Extract.getOperand(0) == VecIn1) {
10385         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10386         if (ExtIndex > VT.getVectorNumElements())
10387           return SDValue();
10388
10389         Mask.push_back(ExtIndex);
10390         continue;
10391       }
10392
10393       // Otherwise, use InIdx + VecSize
10394       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10395       Mask.push_back(Idx+NumInScalars);
10396     }
10397
10398     // We can't generate a shuffle node with mismatched input and output types.
10399     // Attempt to transform a single input vector to the correct type.
10400     if ((VT != VecIn1.getValueType())) {
10401       // We don't support shuffeling between TWO values of different types.
10402       if (VecIn2.getNode())
10403         return SDValue();
10404
10405       // We only support widening of vectors which are half the size of the
10406       // output registers. For example XMM->YMM widening on X86 with AVX.
10407       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10408         return SDValue();
10409
10410       // If the input vector type has a different base type to the output
10411       // vector type, bail out.
10412       if (VecIn1.getValueType().getVectorElementType() !=
10413           VT.getVectorElementType())
10414         return SDValue();
10415
10416       // Widen the input vector by adding undef values.
10417       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10418                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10419     }
10420
10421     // If VecIn2 is unused then change it to undef.
10422     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10423
10424     // Check that we were able to transform all incoming values to the same
10425     // type.
10426     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10427         VecIn1.getValueType() != VT)
10428           return SDValue();
10429
10430     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10431     if (!isTypeLegal(VT))
10432       return SDValue();
10433
10434     // Return the new VECTOR_SHUFFLE node.
10435     SDValue Ops[2];
10436     Ops[0] = VecIn1;
10437     Ops[1] = VecIn2;
10438     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10439   }
10440
10441   return SDValue();
10442 }
10443
10444 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10445   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10446   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10447   // inputs come from at most two distinct vectors, turn this into a shuffle
10448   // node.
10449
10450   // If we only have one input vector, we don't need to do any concatenation.
10451   if (N->getNumOperands() == 1)
10452     return N->getOperand(0);
10453
10454   // Check if all of the operands are undefs.
10455   EVT VT = N->getValueType(0);
10456   if (ISD::allOperandsUndef(N))
10457     return DAG.getUNDEF(VT);
10458
10459   // Optimize concat_vectors where one of the vectors is undef.
10460   if (N->getNumOperands() == 2 &&
10461       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10462     SDValue In = N->getOperand(0);
10463     assert(In.getValueType().isVector() && "Must concat vectors");
10464
10465     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10466     if (In->getOpcode() == ISD::BITCAST &&
10467         !In->getOperand(0)->getValueType(0).isVector()) {
10468       SDValue Scalar = In->getOperand(0);
10469       EVT SclTy = Scalar->getValueType(0);
10470
10471       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10472         return SDValue();
10473
10474       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10475                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10476       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10477         return SDValue();
10478
10479       SDLoc dl = SDLoc(N);
10480       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10481       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10482     }
10483   }
10484
10485   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10486   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10487   if (N->getNumOperands() == 2 &&
10488       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10489       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10490     EVT VT = N->getValueType(0);
10491     SDValue N0 = N->getOperand(0);
10492     SDValue N1 = N->getOperand(1);
10493     SmallVector<SDValue, 8> Opnds;
10494     unsigned BuildVecNumElts =  N0.getNumOperands();
10495
10496     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10497     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10498     if (SclTy0.isFloatingPoint()) {
10499       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10500         Opnds.push_back(N0.getOperand(i));
10501       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10502         Opnds.push_back(N1.getOperand(i));
10503     } else {
10504       // If BUILD_VECTOR are from built from integer, they may have different
10505       // operand types. Get the smaller type and truncate all operands to it.
10506       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10507       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10508         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10509                         N0.getOperand(i)));
10510       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10511         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10512                         N1.getOperand(i)));
10513     }
10514
10515     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10516   }
10517
10518   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10519   // nodes often generate nop CONCAT_VECTOR nodes.
10520   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10521   // place the incoming vectors at the exact same location.
10522   SDValue SingleSource = SDValue();
10523   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10524
10525   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10526     SDValue Op = N->getOperand(i);
10527
10528     if (Op.getOpcode() == ISD::UNDEF)
10529       continue;
10530
10531     // Check if this is the identity extract:
10532     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10533       return SDValue();
10534
10535     // Find the single incoming vector for the extract_subvector.
10536     if (SingleSource.getNode()) {
10537       if (Op.getOperand(0) != SingleSource)
10538         return SDValue();
10539     } else {
10540       SingleSource = Op.getOperand(0);
10541
10542       // Check the source type is the same as the type of the result.
10543       // If not, this concat may extend the vector, so we can not
10544       // optimize it away.
10545       if (SingleSource.getValueType() != N->getValueType(0))
10546         return SDValue();
10547     }
10548
10549     unsigned IdentityIndex = i * PartNumElem;
10550     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10551     // The extract index must be constant.
10552     if (!CS)
10553       return SDValue();
10554
10555     // Check that we are reading from the identity index.
10556     if (CS->getZExtValue() != IdentityIndex)
10557       return SDValue();
10558   }
10559
10560   if (SingleSource.getNode())
10561     return SingleSource;
10562
10563   return SDValue();
10564 }
10565
10566 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10567   EVT NVT = N->getValueType(0);
10568   SDValue V = N->getOperand(0);
10569
10570   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10571     // Combine:
10572     //    (extract_subvec (concat V1, V2, ...), i)
10573     // Into:
10574     //    Vi if possible
10575     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10576     // type.
10577     if (V->getOperand(0).getValueType() != NVT)
10578       return SDValue();
10579     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10580     unsigned NumElems = NVT.getVectorNumElements();
10581     assert((Idx % NumElems) == 0 &&
10582            "IDX in concat is not a multiple of the result vector length.");
10583     return V->getOperand(Idx / NumElems);
10584   }
10585
10586   // Skip bitcasting
10587   if (V->getOpcode() == ISD::BITCAST)
10588     V = V.getOperand(0);
10589
10590   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10591     SDLoc dl(N);
10592     // Handle only simple case where vector being inserted and vector
10593     // being extracted are of same type, and are half size of larger vectors.
10594     EVT BigVT = V->getOperand(0).getValueType();
10595     EVT SmallVT = V->getOperand(1).getValueType();
10596     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10597       return SDValue();
10598
10599     // Only handle cases where both indexes are constants with the same type.
10600     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10601     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10602
10603     if (InsIdx && ExtIdx &&
10604         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10605         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10606       // Combine:
10607       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10608       // Into:
10609       //    indices are equal or bit offsets are equal => V1
10610       //    otherwise => (extract_subvec V1, ExtIdx)
10611       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10612           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10613         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10614       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10615                          DAG.getNode(ISD::BITCAST, dl,
10616                                      N->getOperand(0).getValueType(),
10617                                      V->getOperand(0)), N->getOperand(1));
10618     }
10619   }
10620
10621   return SDValue();
10622 }
10623
10624 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10625 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10626   EVT VT = N->getValueType(0);
10627   unsigned NumElts = VT.getVectorNumElements();
10628
10629   SDValue N0 = N->getOperand(0);
10630   SDValue N1 = N->getOperand(1);
10631   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10632
10633   SmallVector<SDValue, 4> Ops;
10634   EVT ConcatVT = N0.getOperand(0).getValueType();
10635   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10636   unsigned NumConcats = NumElts / NumElemsPerConcat;
10637
10638   // Look at every vector that's inserted. We're looking for exact
10639   // subvector-sized copies from a concatenated vector
10640   for (unsigned I = 0; I != NumConcats; ++I) {
10641     // Make sure we're dealing with a copy.
10642     unsigned Begin = I * NumElemsPerConcat;
10643     bool AllUndef = true, NoUndef = true;
10644     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10645       if (SVN->getMaskElt(J) >= 0)
10646         AllUndef = false;
10647       else
10648         NoUndef = false;
10649     }
10650
10651     if (NoUndef) {
10652       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10653         return SDValue();
10654
10655       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10656         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10657           return SDValue();
10658
10659       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10660       if (FirstElt < N0.getNumOperands())
10661         Ops.push_back(N0.getOperand(FirstElt));
10662       else
10663         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10664
10665     } else if (AllUndef) {
10666       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10667     } else { // Mixed with general masks and undefs, can't do optimization.
10668       return SDValue();
10669     }
10670   }
10671
10672   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10673 }
10674
10675 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10676   EVT VT = N->getValueType(0);
10677   unsigned NumElts = VT.getVectorNumElements();
10678
10679   SDValue N0 = N->getOperand(0);
10680   SDValue N1 = N->getOperand(1);
10681
10682   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10683
10684   // Canonicalize shuffle undef, undef -> undef
10685   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10686     return DAG.getUNDEF(VT);
10687
10688   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10689
10690   // Canonicalize shuffle v, v -> v, undef
10691   if (N0 == N1) {
10692     SmallVector<int, 8> NewMask;
10693     for (unsigned i = 0; i != NumElts; ++i) {
10694       int Idx = SVN->getMaskElt(i);
10695       if (Idx >= (int)NumElts) Idx -= NumElts;
10696       NewMask.push_back(Idx);
10697     }
10698     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10699                                 &NewMask[0]);
10700   }
10701
10702   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10703   if (N0.getOpcode() == ISD::UNDEF) {
10704     SmallVector<int, 8> NewMask;
10705     for (unsigned i = 0; i != NumElts; ++i) {
10706       int Idx = SVN->getMaskElt(i);
10707       if (Idx >= 0) {
10708         if (Idx >= (int)NumElts)
10709           Idx -= NumElts;
10710         else
10711           Idx = -1; // remove reference to lhs
10712       }
10713       NewMask.push_back(Idx);
10714     }
10715     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10716                                 &NewMask[0]);
10717   }
10718
10719   // Remove references to rhs if it is undef
10720   if (N1.getOpcode() == ISD::UNDEF) {
10721     bool Changed = false;
10722     SmallVector<int, 8> NewMask;
10723     for (unsigned i = 0; i != NumElts; ++i) {
10724       int Idx = SVN->getMaskElt(i);
10725       if (Idx >= (int)NumElts) {
10726         Idx = -1;
10727         Changed = true;
10728       }
10729       NewMask.push_back(Idx);
10730     }
10731     if (Changed)
10732       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10733   }
10734
10735   // If it is a splat, check if the argument vector is another splat or a
10736   // build_vector with all scalar elements the same.
10737   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10738     SDNode *V = N0.getNode();
10739
10740     // If this is a bit convert that changes the element type of the vector but
10741     // not the number of vector elements, look through it.  Be careful not to
10742     // look though conversions that change things like v4f32 to v2f64.
10743     if (V->getOpcode() == ISD::BITCAST) {
10744       SDValue ConvInput = V->getOperand(0);
10745       if (ConvInput.getValueType().isVector() &&
10746           ConvInput.getValueType().getVectorNumElements() == NumElts)
10747         V = ConvInput.getNode();
10748     }
10749
10750     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10751       assert(V->getNumOperands() == NumElts &&
10752              "BUILD_VECTOR has wrong number of operands");
10753       SDValue Base;
10754       bool AllSame = true;
10755       for (unsigned i = 0; i != NumElts; ++i) {
10756         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10757           Base = V->getOperand(i);
10758           break;
10759         }
10760       }
10761       // Splat of <u, u, u, u>, return <u, u, u, u>
10762       if (!Base.getNode())
10763         return N0;
10764       for (unsigned i = 0; i != NumElts; ++i) {
10765         if (V->getOperand(i) != Base) {
10766           AllSame = false;
10767           break;
10768         }
10769       }
10770       // Splat of <x, x, x, x>, return <x, x, x, x>
10771       if (AllSame)
10772         return N0;
10773     }
10774   }
10775
10776   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10777       Level < AfterLegalizeVectorOps &&
10778       (N1.getOpcode() == ISD::UNDEF ||
10779       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10780        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10781     SDValue V = partitionShuffleOfConcats(N, DAG);
10782
10783     if (V.getNode())
10784       return V;
10785   }
10786
10787   // If this shuffle node is simply a swizzle of another shuffle node,
10788   // then try to simplify it.
10789   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10790       N1.getOpcode() == ISD::UNDEF) {
10791
10792     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10793
10794     // The incoming shuffle must be of the same type as the result of the
10795     // current shuffle.
10796     assert(OtherSV->getOperand(0).getValueType() == VT &&
10797            "Shuffle types don't match");
10798
10799     SmallVector<int, 4> Mask;
10800     // Compute the combined shuffle mask.
10801     for (unsigned i = 0; i != NumElts; ++i) {
10802       int Idx = SVN->getMaskElt(i);
10803       assert(Idx < (int)NumElts && "Index references undef operand");
10804       // Next, this index comes from the first value, which is the incoming
10805       // shuffle. Adopt the incoming index.
10806       if (Idx >= 0)
10807         Idx = OtherSV->getMaskElt(Idx);
10808       Mask.push_back(Idx);
10809     }
10810
10811     // Check if all indices in Mask are Undef. In case, propagate Undef.
10812     bool isUndefMask = true;
10813     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10814       isUndefMask &= Mask[i] < 0;
10815
10816     if (isUndefMask)
10817       return DAG.getUNDEF(VT);
10818     
10819     bool CommuteOperands = false;
10820     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10821       // To be valid, the combine shuffle mask should only reference elements
10822       // from one of the two vectors in input to the inner shufflevector.
10823       bool IsValidMask = true;
10824       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10825         // See if the combined mask only reference undefs or elements coming
10826         // from the first shufflevector operand.
10827         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10828
10829       if (!IsValidMask) {
10830         IsValidMask = true;
10831         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10832           // Check that all the elements come from the second shuffle operand.
10833           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10834         CommuteOperands = IsValidMask;
10835       }
10836
10837       // Early exit if the combined shuffle mask is not valid.
10838       if (!IsValidMask)
10839         return SDValue();
10840     }
10841
10842     // See if this pair of shuffles can be safely folded according to either
10843     // of the following rules:
10844     //   shuffle(shuffle(x, y), undef) -> x
10845     //   shuffle(shuffle(x, undef), undef) -> x
10846     //   shuffle(shuffle(x, y), undef) -> y
10847     bool IsIdentityMask = true;
10848     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10849     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10850       // Skip Undefs.
10851       if (Mask[i] < 0)
10852         continue;
10853
10854       // The combined shuffle must map each index to itself.
10855       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10856     }
10857     
10858     if (IsIdentityMask) {
10859       if (CommuteOperands)
10860         // optimize shuffle(shuffle(x, y), undef) -> y.
10861         return OtherSV->getOperand(1);
10862       
10863       // optimize shuffle(shuffle(x, undef), undef) -> x
10864       // optimize shuffle(shuffle(x, y), undef) -> x
10865       return OtherSV->getOperand(0);
10866     }
10867
10868     // It may still be beneficial to combine the two shuffles if the
10869     // resulting shuffle is legal.
10870     if (TLI.isTypeLegal(VT)) {
10871       if (!CommuteOperands) {
10872         if (TLI.isShuffleMaskLegal(Mask, VT))
10873           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10874           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10875           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10876                                       &Mask[0]);
10877       } else {
10878         // Compute the commuted shuffle mask.
10879         for (unsigned i = 0; i != NumElts; ++i) {
10880           int idx = Mask[i];
10881           if (idx < 0)
10882             continue;
10883           else if (idx < (int)NumElts)
10884             Mask[i] = idx + NumElts;
10885           else
10886             Mask[i] = idx - NumElts;
10887         }
10888
10889         if (TLI.isShuffleMaskLegal(Mask, VT))
10890           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10891           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10892                                       &Mask[0]);
10893       }
10894     }
10895   }
10896
10897   // Canonicalize shuffles according to rules:
10898   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10899   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10900   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10901   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10902       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10903       TLI.isTypeLegal(VT)) {
10904     // The incoming shuffle must be of the same type as the result of the
10905     // current shuffle.
10906     assert(N1->getOperand(0).getValueType() == VT &&
10907            "Shuffle types don't match");
10908
10909     SDValue SV0 = N1->getOperand(0);
10910     SDValue SV1 = N1->getOperand(1);
10911     bool HasSameOp0 = N0 == SV0;
10912     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10913     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10914       // Commute the operands of this shuffle so that next rule
10915       // will trigger.
10916       return DAG.getCommutedVectorShuffle(*SVN);
10917   }
10918
10919   // Try to fold according to rules:
10920   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10921   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10922   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10923   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10924   // Don't try to fold shuffles with illegal type.
10925   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10926       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10927     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10928
10929     // The incoming shuffle must be of the same type as the result of the
10930     // current shuffle.
10931     assert(OtherSV->getOperand(0).getValueType() == VT &&
10932            "Shuffle types don't match");
10933
10934     SDValue SV0 = OtherSV->getOperand(0);
10935     SDValue SV1 = OtherSV->getOperand(1);
10936     bool HasSameOp0 = N1 == SV0;
10937     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10938     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10939       // Early exit.
10940       return SDValue();
10941
10942     SmallVector<int, 4> Mask;
10943     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10944     // operand, and SV1 as the second operand.
10945     for (unsigned i = 0; i != NumElts; ++i) {
10946       int Idx = SVN->getMaskElt(i);
10947       if (Idx < 0) {
10948         // Propagate Undef.
10949         Mask.push_back(Idx);
10950         continue;
10951       }
10952
10953       if (Idx < (int)NumElts) {
10954         Idx = OtherSV->getMaskElt(Idx);
10955         if (IsSV1Undef && Idx >= (int) NumElts)
10956           Idx = -1;  // Propagate Undef.
10957       } else
10958         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10959
10960       Mask.push_back(Idx);
10961     }
10962
10963     // Check if all indices in Mask are Undef. In case, propagate Undef.
10964     bool isUndefMask = true;
10965     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10966       isUndefMask &= Mask[i] < 0;
10967
10968     if (isUndefMask)
10969       return DAG.getUNDEF(VT);
10970
10971     // Avoid introducing shuffles with illegal mask.
10972     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10973       if (IsSV1Undef)
10974         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10975         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10976         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10977       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10978     }
10979   }
10980
10981   return SDValue();
10982 }
10983
10984 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10985   SDValue N0 = N->getOperand(0);
10986   SDValue N2 = N->getOperand(2);
10987
10988   // If the input vector is a concatenation, and the insert replaces
10989   // one of the halves, we can optimize into a single concat_vectors.
10990   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10991       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10992     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10993     EVT VT = N->getValueType(0);
10994
10995     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10996     // (concat_vectors Z, Y)
10997     if (InsIdx == 0)
10998       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10999                          N->getOperand(1), N0.getOperand(1));
11000
11001     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11002     // (concat_vectors X, Z)
11003     if (InsIdx == VT.getVectorNumElements()/2)
11004       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11005                          N0.getOperand(0), N->getOperand(1));
11006   }
11007
11008   return SDValue();
11009 }
11010
11011 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
11012 /// an AND to a vector_shuffle with the destination vector and a zero vector.
11013 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11014 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11015 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11016   EVT VT = N->getValueType(0);
11017   SDLoc dl(N);
11018   SDValue LHS = N->getOperand(0);
11019   SDValue RHS = N->getOperand(1);
11020   if (N->getOpcode() == ISD::AND) {
11021     if (RHS.getOpcode() == ISD::BITCAST)
11022       RHS = RHS.getOperand(0);
11023     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11024       SmallVector<int, 8> Indices;
11025       unsigned NumElts = RHS.getNumOperands();
11026       for (unsigned i = 0; i != NumElts; ++i) {
11027         SDValue Elt = RHS.getOperand(i);
11028         if (!isa<ConstantSDNode>(Elt))
11029           return SDValue();
11030
11031         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11032           Indices.push_back(i);
11033         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11034           Indices.push_back(NumElts);
11035         else
11036           return SDValue();
11037       }
11038
11039       // Let's see if the target supports this vector_shuffle.
11040       EVT RVT = RHS.getValueType();
11041       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11042         return SDValue();
11043
11044       // Return the new VECTOR_SHUFFLE node.
11045       EVT EltVT = RVT.getVectorElementType();
11046       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11047                                      DAG.getConstant(0, EltVT));
11048       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11049       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11050       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11051       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11052     }
11053   }
11054
11055   return SDValue();
11056 }
11057
11058 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
11059 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11060   assert(N->getValueType(0).isVector() &&
11061          "SimplifyVBinOp only works on vectors!");
11062
11063   SDValue LHS = N->getOperand(0);
11064   SDValue RHS = N->getOperand(1);
11065   SDValue Shuffle = XformToShuffleWithZero(N);
11066   if (Shuffle.getNode()) return Shuffle;
11067
11068   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11069   // this operation.
11070   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11071       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11072     // Check if both vectors are constants. If not bail out.
11073     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11074           cast<BuildVectorSDNode>(RHS)->isConstant()))
11075       return SDValue();
11076
11077     SmallVector<SDValue, 8> Ops;
11078     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11079       SDValue LHSOp = LHS.getOperand(i);
11080       SDValue RHSOp = RHS.getOperand(i);
11081
11082       // Can't fold divide by zero.
11083       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11084           N->getOpcode() == ISD::FDIV) {
11085         if ((RHSOp.getOpcode() == ISD::Constant &&
11086              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11087             (RHSOp.getOpcode() == ISD::ConstantFP &&
11088              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11089           break;
11090       }
11091
11092       EVT VT = LHSOp.getValueType();
11093       EVT RVT = RHSOp.getValueType();
11094       if (RVT != VT) {
11095         // Integer BUILD_VECTOR operands may have types larger than the element
11096         // size (e.g., when the element type is not legal).  Prior to type
11097         // legalization, the types may not match between the two BUILD_VECTORS.
11098         // Truncate one of the operands to make them match.
11099         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11100           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11101         } else {
11102           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11103           VT = RVT;
11104         }
11105       }
11106       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11107                                    LHSOp, RHSOp);
11108       if (FoldOp.getOpcode() != ISD::UNDEF &&
11109           FoldOp.getOpcode() != ISD::Constant &&
11110           FoldOp.getOpcode() != ISD::ConstantFP)
11111         break;
11112       Ops.push_back(FoldOp);
11113       AddToWorklist(FoldOp.getNode());
11114     }
11115
11116     if (Ops.size() == LHS.getNumOperands())
11117       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11118   }
11119
11120   // Type legalization might introduce new shuffles in the DAG.
11121   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11122   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11123   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11124       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11125       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11126       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11127     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11128     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11129
11130     if (SVN0->getMask().equals(SVN1->getMask())) {
11131       EVT VT = N->getValueType(0);
11132       SDValue UndefVector = LHS.getOperand(1);
11133       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11134                                      LHS.getOperand(0), RHS.getOperand(0));
11135       AddUsersToWorklist(N);
11136       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11137                                   &SVN0->getMask()[0]);
11138     }
11139   }
11140
11141   return SDValue();
11142 }
11143
11144 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11145 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11146   assert(N->getValueType(0).isVector() &&
11147          "SimplifyVUnaryOp only works on vectors!");
11148
11149   SDValue N0 = N->getOperand(0);
11150
11151   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11152     return SDValue();
11153
11154   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11155   SmallVector<SDValue, 8> Ops;
11156   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11157     SDValue Op = N0.getOperand(i);
11158     if (Op.getOpcode() != ISD::UNDEF &&
11159         Op.getOpcode() != ISD::ConstantFP)
11160       break;
11161     EVT EltVT = Op.getValueType();
11162     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11163     if (FoldOp.getOpcode() != ISD::UNDEF &&
11164         FoldOp.getOpcode() != ISD::ConstantFP)
11165       break;
11166     Ops.push_back(FoldOp);
11167     AddToWorklist(FoldOp.getNode());
11168   }
11169
11170   if (Ops.size() != N0.getNumOperands())
11171     return SDValue();
11172
11173   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11174 }
11175
11176 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11177                                     SDValue N1, SDValue N2){
11178   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11179
11180   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11181                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11182
11183   // If we got a simplified select_cc node back from SimplifySelectCC, then
11184   // break it down into a new SETCC node, and a new SELECT node, and then return
11185   // the SELECT node, since we were called with a SELECT node.
11186   if (SCC.getNode()) {
11187     // Check to see if we got a select_cc back (to turn into setcc/select).
11188     // Otherwise, just return whatever node we got back, like fabs.
11189     if (SCC.getOpcode() == ISD::SELECT_CC) {
11190       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11191                                   N0.getValueType(),
11192                                   SCC.getOperand(0), SCC.getOperand(1),
11193                                   SCC.getOperand(4));
11194       AddToWorklist(SETCC.getNode());
11195       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11196                            SCC.getOperand(2), SCC.getOperand(3));
11197     }
11198
11199     return SCC;
11200   }
11201   return SDValue();
11202 }
11203
11204 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11205 /// are the two values being selected between, see if we can simplify the
11206 /// select.  Callers of this should assume that TheSelect is deleted if this
11207 /// returns true.  As such, they should return the appropriate thing (e.g. the
11208 /// node) back to the top-level of the DAG combiner loop to avoid it being
11209 /// looked at.
11210 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11211                                     SDValue RHS) {
11212
11213   // Cannot simplify select with vector condition
11214   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11215
11216   // If this is a select from two identical things, try to pull the operation
11217   // through the select.
11218   if (LHS.getOpcode() != RHS.getOpcode() ||
11219       !LHS.hasOneUse() || !RHS.hasOneUse())
11220     return false;
11221
11222   // If this is a load and the token chain is identical, replace the select
11223   // of two loads with a load through a select of the address to load from.
11224   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11225   // constants have been dropped into the constant pool.
11226   if (LHS.getOpcode() == ISD::LOAD) {
11227     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11228     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11229
11230     // Token chains must be identical.
11231     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11232         // Do not let this transformation reduce the number of volatile loads.
11233         LLD->isVolatile() || RLD->isVolatile() ||
11234         // If this is an EXTLOAD, the VT's must match.
11235         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11236         // If this is an EXTLOAD, the kind of extension must match.
11237         (LLD->getExtensionType() != RLD->getExtensionType() &&
11238          // The only exception is if one of the extensions is anyext.
11239          LLD->getExtensionType() != ISD::EXTLOAD &&
11240          RLD->getExtensionType() != ISD::EXTLOAD) ||
11241         // FIXME: this discards src value information.  This is
11242         // over-conservative. It would be beneficial to be able to remember
11243         // both potential memory locations.  Since we are discarding
11244         // src value info, don't do the transformation if the memory
11245         // locations are not in the default address space.
11246         LLD->getPointerInfo().getAddrSpace() != 0 ||
11247         RLD->getPointerInfo().getAddrSpace() != 0 ||
11248         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11249                                       LLD->getBasePtr().getValueType()))
11250       return false;
11251
11252     // Check that the select condition doesn't reach either load.  If so,
11253     // folding this will induce a cycle into the DAG.  If not, this is safe to
11254     // xform, so create a select of the addresses.
11255     SDValue Addr;
11256     if (TheSelect->getOpcode() == ISD::SELECT) {
11257       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11258       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11259           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11260         return false;
11261       // The loads must not depend on one another.
11262       if (LLD->isPredecessorOf(RLD) ||
11263           RLD->isPredecessorOf(LLD))
11264         return false;
11265       Addr = DAG.getSelect(SDLoc(TheSelect),
11266                            LLD->getBasePtr().getValueType(),
11267                            TheSelect->getOperand(0), LLD->getBasePtr(),
11268                            RLD->getBasePtr());
11269     } else {  // Otherwise SELECT_CC
11270       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11271       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11272
11273       if ((LLD->hasAnyUseOfValue(1) &&
11274            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11275           (RLD->hasAnyUseOfValue(1) &&
11276            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11277         return false;
11278
11279       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11280                          LLD->getBasePtr().getValueType(),
11281                          TheSelect->getOperand(0),
11282                          TheSelect->getOperand(1),
11283                          LLD->getBasePtr(), RLD->getBasePtr(),
11284                          TheSelect->getOperand(4));
11285     }
11286
11287     SDValue Load;
11288     // It is safe to replace the two loads if they have different alignments,
11289     // but the new load must be the minimum (most restrictive) alignment of the
11290     // inputs.
11291     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11292     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11293     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11294       Load = DAG.getLoad(TheSelect->getValueType(0),
11295                          SDLoc(TheSelect),
11296                          // FIXME: Discards pointer and AA info.
11297                          LLD->getChain(), Addr, MachinePointerInfo(),
11298                          LLD->isVolatile(), LLD->isNonTemporal(),
11299                          isInvariant, Alignment);
11300     } else {
11301       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11302                             RLD->getExtensionType() : LLD->getExtensionType(),
11303                             SDLoc(TheSelect),
11304                             TheSelect->getValueType(0),
11305                             // FIXME: Discards pointer and AA info.
11306                             LLD->getChain(), Addr, MachinePointerInfo(),
11307                             LLD->getMemoryVT(), LLD->isVolatile(),
11308                             LLD->isNonTemporal(), isInvariant, Alignment);
11309     }
11310
11311     // Users of the select now use the result of the load.
11312     CombineTo(TheSelect, Load);
11313
11314     // Users of the old loads now use the new load's chain.  We know the
11315     // old-load value is dead now.
11316     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11317     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11318     return true;
11319   }
11320
11321   return false;
11322 }
11323
11324 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11325 /// where 'cond' is the comparison specified by CC.
11326 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11327                                       SDValue N2, SDValue N3,
11328                                       ISD::CondCode CC, bool NotExtCompare) {
11329   // (x ? y : y) -> y.
11330   if (N2 == N3) return N2;
11331
11332   EVT VT = N2.getValueType();
11333   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11334   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11335   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11336
11337   // Determine if the condition we're dealing with is constant
11338   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11339                               N0, N1, CC, DL, false);
11340   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11341   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11342
11343   // fold select_cc true, x, y -> x
11344   if (SCCC && !SCCC->isNullValue())
11345     return N2;
11346   // fold select_cc false, x, y -> y
11347   if (SCCC && SCCC->isNullValue())
11348     return N3;
11349
11350   // Check to see if we can simplify the select into an fabs node
11351   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11352     // Allow either -0.0 or 0.0
11353     if (CFP->getValueAPF().isZero()) {
11354       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11355       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11356           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11357           N2 == N3.getOperand(0))
11358         return DAG.getNode(ISD::FABS, DL, VT, N0);
11359
11360       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11361       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11362           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11363           N2.getOperand(0) == N3)
11364         return DAG.getNode(ISD::FABS, DL, VT, N3);
11365     }
11366   }
11367
11368   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11369   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11370   // in it.  This is a win when the constant is not otherwise available because
11371   // it replaces two constant pool loads with one.  We only do this if the FP
11372   // type is known to be legal, because if it isn't, then we are before legalize
11373   // types an we want the other legalization to happen first (e.g. to avoid
11374   // messing with soft float) and if the ConstantFP is not legal, because if
11375   // it is legal, we may not need to store the FP constant in a constant pool.
11376   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11377     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11378       if (TLI.isTypeLegal(N2.getValueType()) &&
11379           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11380                TargetLowering::Legal &&
11381            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11382            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11383           // If both constants have multiple uses, then we won't need to do an
11384           // extra load, they are likely around in registers for other users.
11385           (TV->hasOneUse() || FV->hasOneUse())) {
11386         Constant *Elts[] = {
11387           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11388           const_cast<ConstantFP*>(TV->getConstantFPValue())
11389         };
11390         Type *FPTy = Elts[0]->getType();
11391         const DataLayout &TD = *TLI.getDataLayout();
11392
11393         // Create a ConstantArray of the two constants.
11394         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11395         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11396                                             TD.getPrefTypeAlignment(FPTy));
11397         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11398
11399         // Get the offsets to the 0 and 1 element of the array so that we can
11400         // select between them.
11401         SDValue Zero = DAG.getIntPtrConstant(0);
11402         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11403         SDValue One = DAG.getIntPtrConstant(EltSize);
11404
11405         SDValue Cond = DAG.getSetCC(DL,
11406                                     getSetCCResultType(N0.getValueType()),
11407                                     N0, N1, CC);
11408         AddToWorklist(Cond.getNode());
11409         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11410                                           Cond, One, Zero);
11411         AddToWorklist(CstOffset.getNode());
11412         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11413                             CstOffset);
11414         AddToWorklist(CPIdx.getNode());
11415         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11416                            MachinePointerInfo::getConstantPool(), false,
11417                            false, false, Alignment);
11418
11419       }
11420     }
11421
11422   // Check to see if we can perform the "gzip trick", transforming
11423   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11424   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11425       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11426        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11427     EVT XType = N0.getValueType();
11428     EVT AType = N2.getValueType();
11429     if (XType.bitsGE(AType)) {
11430       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11431       // single-bit constant.
11432       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11433         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11434         ShCtV = XType.getSizeInBits()-ShCtV-1;
11435         SDValue ShCt = DAG.getConstant(ShCtV,
11436                                        getShiftAmountTy(N0.getValueType()));
11437         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11438                                     XType, N0, ShCt);
11439         AddToWorklist(Shift.getNode());
11440
11441         if (XType.bitsGT(AType)) {
11442           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11443           AddToWorklist(Shift.getNode());
11444         }
11445
11446         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11447       }
11448
11449       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11450                                   XType, N0,
11451                                   DAG.getConstant(XType.getSizeInBits()-1,
11452                                          getShiftAmountTy(N0.getValueType())));
11453       AddToWorklist(Shift.getNode());
11454
11455       if (XType.bitsGT(AType)) {
11456         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11457         AddToWorklist(Shift.getNode());
11458       }
11459
11460       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11461     }
11462   }
11463
11464   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11465   // where y is has a single bit set.
11466   // A plaintext description would be, we can turn the SELECT_CC into an AND
11467   // when the condition can be materialized as an all-ones register.  Any
11468   // single bit-test can be materialized as an all-ones register with
11469   // shift-left and shift-right-arith.
11470   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11471       N0->getValueType(0) == VT &&
11472       N1C && N1C->isNullValue() &&
11473       N2C && N2C->isNullValue()) {
11474     SDValue AndLHS = N0->getOperand(0);
11475     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11476     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11477       // Shift the tested bit over the sign bit.
11478       APInt AndMask = ConstAndRHS->getAPIntValue();
11479       SDValue ShlAmt =
11480         DAG.getConstant(AndMask.countLeadingZeros(),
11481                         getShiftAmountTy(AndLHS.getValueType()));
11482       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11483
11484       // Now arithmetic right shift it all the way over, so the result is either
11485       // all-ones, or zero.
11486       SDValue ShrAmt =
11487         DAG.getConstant(AndMask.getBitWidth()-1,
11488                         getShiftAmountTy(Shl.getValueType()));
11489       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11490
11491       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11492     }
11493   }
11494
11495   // fold select C, 16, 0 -> shl C, 4
11496   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11497       TLI.getBooleanContents(N0.getValueType()) ==
11498           TargetLowering::ZeroOrOneBooleanContent) {
11499
11500     // If the caller doesn't want us to simplify this into a zext of a compare,
11501     // don't do it.
11502     if (NotExtCompare && N2C->getAPIntValue() == 1)
11503       return SDValue();
11504
11505     // Get a SetCC of the condition
11506     // NOTE: Don't create a SETCC if it's not legal on this target.
11507     if (!LegalOperations ||
11508         TLI.isOperationLegal(ISD::SETCC,
11509           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11510       SDValue Temp, SCC;
11511       // cast from setcc result type to select result type
11512       if (LegalTypes) {
11513         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11514                             N0, N1, CC);
11515         if (N2.getValueType().bitsLT(SCC.getValueType()))
11516           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11517                                         N2.getValueType());
11518         else
11519           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11520                              N2.getValueType(), SCC);
11521       } else {
11522         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11523         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11524                            N2.getValueType(), SCC);
11525       }
11526
11527       AddToWorklist(SCC.getNode());
11528       AddToWorklist(Temp.getNode());
11529
11530       if (N2C->getAPIntValue() == 1)
11531         return Temp;
11532
11533       // shl setcc result by log2 n2c
11534       return DAG.getNode(
11535           ISD::SHL, DL, N2.getValueType(), Temp,
11536           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11537                           getShiftAmountTy(Temp.getValueType())));
11538     }
11539   }
11540
11541   // Check to see if this is the equivalent of setcc
11542   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11543   // otherwise, go ahead with the folds.
11544   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11545     EVT XType = N0.getValueType();
11546     if (!LegalOperations ||
11547         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11548       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11549       if (Res.getValueType() != VT)
11550         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11551       return Res;
11552     }
11553
11554     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11555     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11556         (!LegalOperations ||
11557          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11558       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11559       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11560                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11561                                        getShiftAmountTy(Ctlz.getValueType())));
11562     }
11563     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11564     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11565       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11566                                   XType, DAG.getConstant(0, XType), N0);
11567       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11568       return DAG.getNode(ISD::SRL, DL, XType,
11569                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11570                          DAG.getConstant(XType.getSizeInBits()-1,
11571                                          getShiftAmountTy(XType)));
11572     }
11573     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11574     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11575       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11576                                  DAG.getConstant(XType.getSizeInBits()-1,
11577                                          getShiftAmountTy(N0.getValueType())));
11578       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11579     }
11580   }
11581
11582   // Check to see if this is an integer abs.
11583   // select_cc setg[te] X,  0,  X, -X ->
11584   // select_cc setgt    X, -1,  X, -X ->
11585   // select_cc setl[te] X,  0, -X,  X ->
11586   // select_cc setlt    X,  1, -X,  X ->
11587   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11588   if (N1C) {
11589     ConstantSDNode *SubC = nullptr;
11590     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11591          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11592         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11593       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11594     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11595               (N1C->isOne() && CC == ISD::SETLT)) &&
11596              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11597       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11598
11599     EVT XType = N0.getValueType();
11600     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11601       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11602                                   N0,
11603                                   DAG.getConstant(XType.getSizeInBits()-1,
11604                                          getShiftAmountTy(N0.getValueType())));
11605       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11606                                 XType, N0, Shift);
11607       AddToWorklist(Shift.getNode());
11608       AddToWorklist(Add.getNode());
11609       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11610     }
11611   }
11612
11613   return SDValue();
11614 }
11615
11616 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11617 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11618                                    SDValue N1, ISD::CondCode Cond,
11619                                    SDLoc DL, bool foldBooleans) {
11620   TargetLowering::DAGCombinerInfo
11621     DagCombineInfo(DAG, Level, false, this);
11622   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11623 }
11624
11625 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11626 /// a DAG expression to select that will generate the same value by multiplying
11627 /// by a magic number.  See:
11628 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11629 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11630   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11631   if (!C)
11632     return SDValue();
11633
11634   // Avoid division by zero.
11635   if (!C->getAPIntValue())
11636     return SDValue();
11637
11638   std::vector<SDNode*> Built;
11639   SDValue S =
11640       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11641
11642   for (SDNode *N : Built)
11643     AddToWorklist(N);
11644   return S;
11645 }
11646
11647 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11648 /// power of 2, return a DAG expression to select that will generate the same
11649 /// value by right shifting.
11650 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11651   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11652   if (!C)
11653     return SDValue();
11654
11655   // Avoid division by zero.
11656   if (!C->getAPIntValue())
11657     return SDValue();
11658
11659   std::vector<SDNode *> Built;
11660   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11661
11662   for (SDNode *N : Built)
11663     AddToWorklist(N);
11664   return S;
11665 }
11666
11667 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11668 /// return a DAG expression to select that will generate the same value by
11669 /// multiplying by a magic number.  See:
11670 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11671 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11672   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11673   if (!C)
11674     return SDValue();
11675
11676   // Avoid division by zero.
11677   if (!C->getAPIntValue())
11678     return SDValue();
11679
11680   std::vector<SDNode*> Built;
11681   SDValue S =
11682       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11683
11684   for (SDNode *N : Built)
11685     AddToWorklist(N);
11686   return S;
11687 }
11688
11689 /// FindBaseOffset - Return true if base is a frame index, which is known not
11690 // to alias with anything but itself.  Provides base object and offset as
11691 // results.
11692 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11693                            const GlobalValue *&GV, const void *&CV) {
11694   // Assume it is a primitive operation.
11695   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11696
11697   // If it's an adding a simple constant then integrate the offset.
11698   if (Base.getOpcode() == ISD::ADD) {
11699     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11700       Base = Base.getOperand(0);
11701       Offset += C->getZExtValue();
11702     }
11703   }
11704
11705   // Return the underlying GlobalValue, and update the Offset.  Return false
11706   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11707   // by multiple nodes with different offsets.
11708   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11709     GV = G->getGlobal();
11710     Offset += G->getOffset();
11711     return false;
11712   }
11713
11714   // Return the underlying Constant value, and update the Offset.  Return false
11715   // for ConstantSDNodes since the same constant pool entry may be represented
11716   // by multiple nodes with different offsets.
11717   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11718     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11719                                          : (const void *)C->getConstVal();
11720     Offset += C->getOffset();
11721     return false;
11722   }
11723   // If it's any of the following then it can't alias with anything but itself.
11724   return isa<FrameIndexSDNode>(Base);
11725 }
11726
11727 /// isAlias - Return true if there is any possibility that the two addresses
11728 /// overlap.
11729 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11730   // If they are the same then they must be aliases.
11731   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11732
11733   // If they are both volatile then they cannot be reordered.
11734   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11735
11736   // Gather base node and offset information.
11737   SDValue Base1, Base2;
11738   int64_t Offset1, Offset2;
11739   const GlobalValue *GV1, *GV2;
11740   const void *CV1, *CV2;
11741   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11742                                       Base1, Offset1, GV1, CV1);
11743   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11744                                       Base2, Offset2, GV2, CV2);
11745
11746   // If they have a same base address then check to see if they overlap.
11747   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11748     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11749              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11750
11751   // It is possible for different frame indices to alias each other, mostly
11752   // when tail call optimization reuses return address slots for arguments.
11753   // To catch this case, look up the actual index of frame indices to compute
11754   // the real alias relationship.
11755   if (isFrameIndex1 && isFrameIndex2) {
11756     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11757     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11758     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11759     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11760              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11761   }
11762
11763   // Otherwise, if we know what the bases are, and they aren't identical, then
11764   // we know they cannot alias.
11765   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11766     return false;
11767
11768   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11769   // compared to the size and offset of the access, we may be able to prove they
11770   // do not alias.  This check is conservative for now to catch cases created by
11771   // splitting vector types.
11772   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11773       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11774       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11775        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11776       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11777     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11778     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11779
11780     // There is no overlap between these relatively aligned accesses of similar
11781     // size, return no alias.
11782     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11783         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11784       return false;
11785   }
11786
11787   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11788     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11789 #ifndef NDEBUG
11790   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11791       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11792     UseAA = false;
11793 #endif
11794   if (UseAA &&
11795       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11796     // Use alias analysis information.
11797     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11798                                  Op1->getSrcValueOffset());
11799     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11800         Op0->getSrcValueOffset() - MinOffset;
11801     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11802         Op1->getSrcValueOffset() - MinOffset;
11803     AliasAnalysis::AliasResult AAResult =
11804         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11805                                          Overlap1,
11806                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11807                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11808                                          Overlap2,
11809                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11810     if (AAResult == AliasAnalysis::NoAlias)
11811       return false;
11812   }
11813
11814   // Otherwise we have to assume they alias.
11815   return true;
11816 }
11817
11818 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11819 /// looking for aliasing nodes and adding them to the Aliases vector.
11820 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11821                                    SmallVectorImpl<SDValue> &Aliases) {
11822   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11823   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11824
11825   // Get alias information for node.
11826   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11827
11828   // Starting off.
11829   Chains.push_back(OriginalChain);
11830   unsigned Depth = 0;
11831
11832   // Look at each chain and determine if it is an alias.  If so, add it to the
11833   // aliases list.  If not, then continue up the chain looking for the next
11834   // candidate.
11835   while (!Chains.empty()) {
11836     SDValue Chain = Chains.back();
11837     Chains.pop_back();
11838
11839     // For TokenFactor nodes, look at each operand and only continue up the
11840     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11841     // find more and revert to original chain since the xform is unlikely to be
11842     // profitable.
11843     //
11844     // FIXME: The depth check could be made to return the last non-aliasing
11845     // chain we found before we hit a tokenfactor rather than the original
11846     // chain.
11847     if (Depth > 6 || Aliases.size() == 2) {
11848       Aliases.clear();
11849       Aliases.push_back(OriginalChain);
11850       return;
11851     }
11852
11853     // Don't bother if we've been before.
11854     if (!Visited.insert(Chain.getNode()))
11855       continue;
11856
11857     switch (Chain.getOpcode()) {
11858     case ISD::EntryToken:
11859       // Entry token is ideal chain operand, but handled in FindBetterChain.
11860       break;
11861
11862     case ISD::LOAD:
11863     case ISD::STORE: {
11864       // Get alias information for Chain.
11865       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11866           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11867
11868       // If chain is alias then stop here.
11869       if (!(IsLoad && IsOpLoad) &&
11870           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11871         Aliases.push_back(Chain);
11872       } else {
11873         // Look further up the chain.
11874         Chains.push_back(Chain.getOperand(0));
11875         ++Depth;
11876       }
11877       break;
11878     }
11879
11880     case ISD::TokenFactor:
11881       // We have to check each of the operands of the token factor for "small"
11882       // token factors, so we queue them up.  Adding the operands to the queue
11883       // (stack) in reverse order maintains the original order and increases the
11884       // likelihood that getNode will find a matching token factor (CSE.)
11885       if (Chain.getNumOperands() > 16) {
11886         Aliases.push_back(Chain);
11887         break;
11888       }
11889       for (unsigned n = Chain.getNumOperands(); n;)
11890         Chains.push_back(Chain.getOperand(--n));
11891       ++Depth;
11892       break;
11893
11894     default:
11895       // For all other instructions we will just have to take what we can get.
11896       Aliases.push_back(Chain);
11897       break;
11898     }
11899   }
11900
11901   // We need to be careful here to also search for aliases through the
11902   // value operand of a store, etc. Consider the following situation:
11903   //   Token1 = ...
11904   //   L1 = load Token1, %52
11905   //   S1 = store Token1, L1, %51
11906   //   L2 = load Token1, %52+8
11907   //   S2 = store Token1, L2, %51+8
11908   //   Token2 = Token(S1, S2)
11909   //   L3 = load Token2, %53
11910   //   S3 = store Token2, L3, %52
11911   //   L4 = load Token2, %53+8
11912   //   S4 = store Token2, L4, %52+8
11913   // If we search for aliases of S3 (which loads address %52), and we look
11914   // only through the chain, then we'll miss the trivial dependence on L1
11915   // (which also loads from %52). We then might change all loads and
11916   // stores to use Token1 as their chain operand, which could result in
11917   // copying %53 into %52 before copying %52 into %51 (which should
11918   // happen first).
11919   //
11920   // The problem is, however, that searching for such data dependencies
11921   // can become expensive, and the cost is not directly related to the
11922   // chain depth. Instead, we'll rule out such configurations here by
11923   // insisting that we've visited all chain users (except for users
11924   // of the original chain, which is not necessary). When doing this,
11925   // we need to look through nodes we don't care about (otherwise, things
11926   // like register copies will interfere with trivial cases).
11927
11928   SmallVector<const SDNode *, 16> Worklist;
11929   for (const SDNode *N : Visited)
11930     if (N != OriginalChain.getNode())
11931       Worklist.push_back(N);
11932
11933   while (!Worklist.empty()) {
11934     const SDNode *M = Worklist.pop_back_val();
11935
11936     // We have already visited M, and want to make sure we've visited any uses
11937     // of M that we care about. For uses that we've not visisted, and don't
11938     // care about, queue them to the worklist.
11939
11940     for (SDNode::use_iterator UI = M->use_begin(),
11941          UIE = M->use_end(); UI != UIE; ++UI)
11942       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11943         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11944           // We've not visited this use, and we care about it (it could have an
11945           // ordering dependency with the original node).
11946           Aliases.clear();
11947           Aliases.push_back(OriginalChain);
11948           return;
11949         }
11950
11951         // We've not visited this use, but we don't care about it. Mark it as
11952         // visited and enqueue it to the worklist.
11953         Worklist.push_back(*UI);
11954       }
11955   }
11956 }
11957
11958 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11959 /// for a better chain (aliasing node.)
11960 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11961   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11962
11963   // Accumulate all the aliases to this node.
11964   GatherAllAliases(N, OldChain, Aliases);
11965
11966   // If no operands then chain to entry token.
11967   if (Aliases.size() == 0)
11968     return DAG.getEntryNode();
11969
11970   // If a single operand then chain to it.  We don't need to revisit it.
11971   if (Aliases.size() == 1)
11972     return Aliases[0];
11973
11974   // Construct a custom tailored token factor.
11975   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11976 }
11977
11978 // SelectionDAG::Combine - This is the entry point for the file.
11979 //
11980 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11981                            CodeGenOpt::Level OptLevel) {
11982   /// run - This is the main entry point to this class.
11983   ///
11984   DAGCombiner(*this, AA, OptLevel).Run(Level);
11985 }