Match the InstCombine form of rotates by X+C
[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 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.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 STATISTIC(NodesCombined   , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
49
50 namespace {
51   static cl::opt<bool>
52     CombinerAA("combiner-alias-analysis", cl::Hidden,
53                cl::desc("Turn on alias analysis during testing"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Include global information in alias analysis"));
58
59   /// Hidden option to stress test load slicing, i.e., when this option
60   /// is enabled, load slicing bypasses most of its profitability guards.
61   static cl::opt<bool>
62   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63                     cl::desc("Bypass the profitability model of load "
64                              "slicing"),
65                     cl::init(false));
66
67 //------------------------------ DAGCombiner ---------------------------------//
68
69   class DAGCombiner {
70     SelectionDAG &DAG;
71     const TargetLowering &TLI;
72     CombineLevel Level;
73     CodeGenOpt::Level OptLevel;
74     bool LegalOperations;
75     bool LegalTypes;
76     bool ForCodeSize;
77
78     // Worklist of all of the nodes that need to be simplified.
79     //
80     // This has the semantics that when adding to the worklist,
81     // the item added must be next to be processed. It should
82     // also only appear once. The naive approach to this takes
83     // linear time.
84     //
85     // To reduce the insert/remove time to logarithmic, we use
86     // a set and a vector to maintain our worklist.
87     //
88     // The set contains the items on the worklist, but does not
89     // maintain the order they should be visited.
90     //
91     // The vector maintains the order nodes should be visited, but may
92     // contain duplicate or removed nodes. When choosing a node to
93     // visit, we pop off the order stack until we find an item that is
94     // also in the contents set. All operations are O(log N).
95     SmallPtrSet<SDNode*, 64> WorkListContents;
96     SmallVector<SDNode*, 64> WorkListOrder;
97
98     // AA - Used for DAG load/store alias analysis.
99     AliasAnalysis &AA;
100
101     /// AddUsersToWorkList - When an instruction is simplified, add all users of
102     /// the instruction to the work lists because they might get more simplified
103     /// now.
104     ///
105     void AddUsersToWorkList(SDNode *N) {
106       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
107            UI != UE; ++UI)
108         AddToWorkList(*UI);
109     }
110
111     /// visit - call the node-specific routine that knows how to fold each
112     /// particular type of node.
113     SDValue visit(SDNode *N);
114
115   public:
116     /// AddToWorkList - Add to the work list making sure its instance is at the
117     /// back (next to be processed.)
118     void AddToWorkList(SDNode *N) {
119       WorkListContents.insert(N);
120       WorkListOrder.push_back(N);
121     }
122
123     /// removeFromWorkList - remove all instances of N from the worklist.
124     ///
125     void removeFromWorkList(SDNode *N) {
126       WorkListContents.erase(N);
127     }
128
129     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
130                       bool AddTo = true);
131
132     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
133       return CombineTo(N, &Res, 1, AddTo);
134     }
135
136     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
137                       bool AddTo = true) {
138       SDValue To[] = { Res0, Res1 };
139       return CombineTo(N, To, 2, AddTo);
140     }
141
142     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
143
144   private:
145
146     /// SimplifyDemandedBits - Check the specified integer node value to see if
147     /// it can be simplified or if things it uses can be simplified by bit
148     /// propagation.  If so, return true.
149     bool SimplifyDemandedBits(SDValue Op) {
150       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151       APInt Demanded = APInt::getAllOnesValue(BitWidth);
152       return SimplifyDemandedBits(Op, Demanded);
153     }
154
155     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
156
157     bool CombineToPreIndexedLoadStore(SDNode *N);
158     bool CombineToPostIndexedLoadStore(SDNode *N);
159     bool SliceUpLoad(SDNode *N);
160
161     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
165     SDValue PromoteIntBinOp(SDValue Op);
166     SDValue PromoteIntShiftOp(SDValue Op);
167     SDValue PromoteExtend(SDValue Op);
168     bool PromoteLoad(SDValue Op);
169
170     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
171                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
172                          ISD::NodeType ExtType);
173
174     /// combine - call the node-specific routine that knows how to fold each
175     /// particular type of node. If that doesn't do anything, try the
176     /// target-specific DAG combines.
177     SDValue combine(SDNode *N);
178
179     // Visitation implementation - Implement dag node combining for different
180     // node types.  The semantics are as follows:
181     // Return Value:
182     //   SDValue.getNode() == 0 - No change was made
183     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
184     //   otherwise              - N should be replaced by the returned Operand.
185     //
186     SDValue visitTokenFactor(SDNode *N);
187     SDValue visitMERGE_VALUES(SDNode *N);
188     SDValue visitADD(SDNode *N);
189     SDValue visitSUB(SDNode *N);
190     SDValue visitADDC(SDNode *N);
191     SDValue visitSUBC(SDNode *N);
192     SDValue visitADDE(SDNode *N);
193     SDValue visitSUBE(SDNode *N);
194     SDValue visitMUL(SDNode *N);
195     SDValue visitSDIV(SDNode *N);
196     SDValue visitUDIV(SDNode *N);
197     SDValue visitSREM(SDNode *N);
198     SDValue visitUREM(SDNode *N);
199     SDValue visitMULHU(SDNode *N);
200     SDValue visitMULHS(SDNode *N);
201     SDValue visitSMUL_LOHI(SDNode *N);
202     SDValue visitUMUL_LOHI(SDNode *N);
203     SDValue visitSMULO(SDNode *N);
204     SDValue visitUMULO(SDNode *N);
205     SDValue visitSDIVREM(SDNode *N);
206     SDValue visitUDIVREM(SDNode *N);
207     SDValue visitAND(SDNode *N);
208     SDValue visitOR(SDNode *N);
209     SDValue visitXOR(SDNode *N);
210     SDValue SimplifyVBinOp(SDNode *N);
211     SDValue SimplifyVUnaryOp(SDNode *N);
212     SDValue visitSHL(SDNode *N);
213     SDValue visitSRA(SDNode *N);
214     SDValue visitSRL(SDNode *N);
215     SDValue visitCTLZ(SDNode *N);
216     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
217     SDValue visitCTTZ(SDNode *N);
218     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
219     SDValue visitCTPOP(SDNode *N);
220     SDValue visitSELECT(SDNode *N);
221     SDValue visitVSELECT(SDNode *N);
222     SDValue visitSELECT_CC(SDNode *N);
223     SDValue visitSETCC(SDNode *N);
224     SDValue visitSIGN_EXTEND(SDNode *N);
225     SDValue visitZERO_EXTEND(SDNode *N);
226     SDValue visitANY_EXTEND(SDNode *N);
227     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228     SDValue visitTRUNCATE(SDNode *N);
229     SDValue visitBITCAST(SDNode *N);
230     SDValue visitBUILD_PAIR(SDNode *N);
231     SDValue visitFADD(SDNode *N);
232     SDValue visitFSUB(SDNode *N);
233     SDValue visitFMUL(SDNode *N);
234     SDValue visitFMA(SDNode *N);
235     SDValue visitFDIV(SDNode *N);
236     SDValue visitFREM(SDNode *N);
237     SDValue visitFCOPYSIGN(SDNode *N);
238     SDValue visitSINT_TO_FP(SDNode *N);
239     SDValue visitUINT_TO_FP(SDNode *N);
240     SDValue visitFP_TO_SINT(SDNode *N);
241     SDValue visitFP_TO_UINT(SDNode *N);
242     SDValue visitFP_ROUND(SDNode *N);
243     SDValue visitFP_ROUND_INREG(SDNode *N);
244     SDValue visitFP_EXTEND(SDNode *N);
245     SDValue visitFNEG(SDNode *N);
246     SDValue visitFABS(SDNode *N);
247     SDValue visitFCEIL(SDNode *N);
248     SDValue visitFTRUNC(SDNode *N);
249     SDValue visitFFLOOR(SDNode *N);
250     SDValue visitBRCOND(SDNode *N);
251     SDValue visitBR_CC(SDNode *N);
252     SDValue visitLOAD(SDNode *N);
253     SDValue visitSTORE(SDNode *N);
254     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256     SDValue visitBUILD_VECTOR(SDNode *N);
257     SDValue visitCONCAT_VECTORS(SDNode *N);
258     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
259     SDValue visitVECTOR_SHUFFLE(SDNode *N);
260
261     SDValue XformToShuffleWithZero(SDNode *N);
262     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
263
264     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
265
266     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
268     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
270                              SDValue N3, ISD::CondCode CC,
271                              bool NotExtCompare = false);
272     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
273                           SDLoc DL, bool foldBooleans = true);
274     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
275                                          unsigned HiOp);
276     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
277     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
278     SDValue BuildSDIV(SDNode *N);
279     SDValue BuildUDIV(SDNode *N);
280     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281                                bool DemandHighBits = true);
282     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
283     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
284                               SDValue InnerPos, SDValue InnerNeg,
285                               unsigned PosOpcode, unsigned NegOpcode,
286                               SDLoc DL);
287     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
288     SDValue ReduceLoadWidth(SDNode *N);
289     SDValue ReduceLoadOpStoreWidth(SDNode *N);
290     SDValue TransformFPLoadStorePair(SDNode *N);
291     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
292     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
293
294     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
295
296     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
297     /// looking for aliasing nodes and adding them to the Aliases vector.
298     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
299                           SmallVectorImpl<SDValue> &Aliases);
300
301     /// isAlias - Return true if there is any possibility that the two addresses
302     /// overlap.
303     bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
304                  const Value *SrcValue1, int SrcValueOffset1,
305                  unsigned SrcValueAlign1,
306                  const MDNode *TBAAInfo1,
307                  SDValue Ptr2, int64_t Size2, bool IsVolatile2,
308                  const Value *SrcValue2, int SrcValueOffset2,
309                  unsigned SrcValueAlign2,
310                  const MDNode *TBAAInfo2) const;
311
312     /// isAlias - Return true if there is any possibility that the two addresses
313     /// overlap.
314     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
315
316     /// FindAliasInfo - Extracts the relevant alias information from the memory
317     /// node.  Returns true if the operand was a load.
318     bool FindAliasInfo(SDNode *N,
319                        SDValue &Ptr, int64_t &Size, bool &IsVolatile,
320                        const Value *&SrcValue, int &SrcValueOffset,
321                        unsigned &SrcValueAlignment,
322                        const MDNode *&TBAAInfo) const;
323
324     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
325     /// looking for a better chain (aliasing node.)
326     SDValue FindBetterChain(SDNode *N, SDValue Chain);
327
328     /// Merge consecutive store operations into a wide store.
329     /// This optimization uses wide integers or vectors when possible.
330     /// \return True if some memory operations were changed.
331     bool MergeConsecutiveStores(StoreSDNode *N);
332
333   public:
334     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
335         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
336           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
337       AttributeSet FnAttrs =
338           DAG.getMachineFunction().getFunction()->getAttributes();
339       ForCodeSize =
340           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
341                                Attribute::OptimizeForSize) ||
342           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
343     }
344
345     /// Run - runs the dag combiner on all nodes in the work list
346     void Run(CombineLevel AtLevel);
347
348     SelectionDAG &getDAG() const { return DAG; }
349
350     /// getShiftAmountTy - Returns a type large enough to hold any valid
351     /// shift amount - before type legalization these can be huge.
352     EVT getShiftAmountTy(EVT LHSTy) {
353       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
354       if (LHSTy.isVector())
355         return LHSTy;
356       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
357                         : TLI.getPointerTy();
358     }
359
360     /// isTypeLegal - This method returns true if we are running before type
361     /// legalization or if the specified VT is legal.
362     bool isTypeLegal(const EVT &VT) {
363       if (!LegalTypes) return true;
364       return TLI.isTypeLegal(VT);
365     }
366
367     /// getSetCCResultType - Convenience wrapper around
368     /// TargetLowering::getSetCCResultType
369     EVT getSetCCResultType(EVT VT) const {
370       return TLI.getSetCCResultType(*DAG.getContext(), VT);
371     }
372   };
373 }
374
375
376 namespace {
377 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
378 /// nodes from the worklist.
379 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
380   DAGCombiner &DC;
381 public:
382   explicit WorkListRemover(DAGCombiner &dc)
383     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
384
385   virtual void NodeDeleted(SDNode *N, SDNode *E) {
386     DC.removeFromWorkList(N);
387   }
388 };
389 }
390
391 //===----------------------------------------------------------------------===//
392 //  TargetLowering::DAGCombinerInfo implementation
393 //===----------------------------------------------------------------------===//
394
395 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
396   ((DAGCombiner*)DC)->AddToWorkList(N);
397 }
398
399 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
400   ((DAGCombiner*)DC)->removeFromWorkList(N);
401 }
402
403 SDValue TargetLowering::DAGCombinerInfo::
404 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
405   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
406 }
407
408 SDValue TargetLowering::DAGCombinerInfo::
409 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
410   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
411 }
412
413
414 SDValue TargetLowering::DAGCombinerInfo::
415 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
416   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
417 }
418
419 void TargetLowering::DAGCombinerInfo::
420 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
421   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
422 }
423
424 //===----------------------------------------------------------------------===//
425 // Helper Functions
426 //===----------------------------------------------------------------------===//
427
428 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
429 /// specified expression for the same cost as the expression itself, or 2 if we
430 /// can compute the negated form more cheaply than the expression itself.
431 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
432                                const TargetLowering &TLI,
433                                const TargetOptions *Options,
434                                unsigned Depth = 0) {
435   // fneg is removable even if it has multiple uses.
436   if (Op.getOpcode() == ISD::FNEG) return 2;
437
438   // Don't allow anything with multiple uses.
439   if (!Op.hasOneUse()) return 0;
440
441   // Don't recurse exponentially.
442   if (Depth > 6) return 0;
443
444   switch (Op.getOpcode()) {
445   default: return false;
446   case ISD::ConstantFP:
447     // Don't invert constant FP values after legalize.  The negated constant
448     // isn't necessarily legal.
449     return LegalOperations ? 0 : 1;
450   case ISD::FADD:
451     // FIXME: determine better conditions for this xform.
452     if (!Options->UnsafeFPMath) return 0;
453
454     // After operation legalization, it might not be legal to create new FSUBs.
455     if (LegalOperations &&
456         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
457       return 0;
458
459     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
460     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
461                                     Options, Depth + 1))
462       return V;
463     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
464     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
465                               Depth + 1);
466   case ISD::FSUB:
467     // We can't turn -(A-B) into B-A when we honor signed zeros.
468     if (!Options->UnsafeFPMath) return 0;
469
470     // fold (fneg (fsub A, B)) -> (fsub B, A)
471     return 1;
472
473   case ISD::FMUL:
474   case ISD::FDIV:
475     if (Options->HonorSignDependentRoundingFPMath()) return 0;
476
477     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
478     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
479                                     Options, Depth + 1))
480       return V;
481
482     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
483                               Depth + 1);
484
485   case ISD::FP_EXTEND:
486   case ISD::FP_ROUND:
487   case ISD::FSIN:
488     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
489                               Depth + 1);
490   }
491 }
492
493 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
494 /// returns the newly negated expression.
495 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
496                                     bool LegalOperations, unsigned Depth = 0) {
497   // fneg is removable even if it has multiple uses.
498   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
499
500   // Don't allow anything with multiple uses.
501   assert(Op.hasOneUse() && "Unknown reuse!");
502
503   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
504   switch (Op.getOpcode()) {
505   default: llvm_unreachable("Unknown code");
506   case ISD::ConstantFP: {
507     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
508     V.changeSign();
509     return DAG.getConstantFP(V, Op.getValueType());
510   }
511   case ISD::FADD:
512     // FIXME: determine better conditions for this xform.
513     assert(DAG.getTarget().Options.UnsafeFPMath);
514
515     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
516     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
517                            DAG.getTargetLoweringInfo(),
518                            &DAG.getTarget().Options, Depth+1))
519       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
520                          GetNegatedExpression(Op.getOperand(0), DAG,
521                                               LegalOperations, Depth+1),
522                          Op.getOperand(1));
523     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
525                        GetNegatedExpression(Op.getOperand(1), DAG,
526                                             LegalOperations, Depth+1),
527                        Op.getOperand(0));
528   case ISD::FSUB:
529     // We can't turn -(A-B) into B-A when we honor signed zeros.
530     assert(DAG.getTarget().Options.UnsafeFPMath);
531
532     // fold (fneg (fsub 0, B)) -> B
533     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
534       if (N0CFP->getValueAPF().isZero())
535         return Op.getOperand(1);
536
537     // fold (fneg (fsub A, B)) -> (fsub B, A)
538     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
539                        Op.getOperand(1), Op.getOperand(0));
540
541   case ISD::FMUL:
542   case ISD::FDIV:
543     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
544
545     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
546     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
547                            DAG.getTargetLoweringInfo(),
548                            &DAG.getTarget().Options, Depth+1))
549       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
550                          GetNegatedExpression(Op.getOperand(0), DAG,
551                                               LegalOperations, Depth+1),
552                          Op.getOperand(1));
553
554     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
555     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
556                        Op.getOperand(0),
557                        GetNegatedExpression(Op.getOperand(1), DAG,
558                                             LegalOperations, Depth+1));
559
560   case ISD::FP_EXTEND:
561   case ISD::FSIN:
562     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563                        GetNegatedExpression(Op.getOperand(0), DAG,
564                                             LegalOperations, Depth+1));
565   case ISD::FP_ROUND:
566       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
567                          GetNegatedExpression(Op.getOperand(0), DAG,
568                                               LegalOperations, Depth+1),
569                          Op.getOperand(1));
570   }
571 }
572
573
574 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
575 // that selects between the values 1 and 0, making it equivalent to a setcc.
576 // Also, set the incoming LHS, RHS, and CC references to the appropriate
577 // nodes based on the type of node we are checking.  This simplifies life a
578 // bit for the callers.
579 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
580                               SDValue &CC) {
581   if (N.getOpcode() == ISD::SETCC) {
582     LHS = N.getOperand(0);
583     RHS = N.getOperand(1);
584     CC  = N.getOperand(2);
585     return true;
586   }
587   if (N.getOpcode() == ISD::SELECT_CC &&
588       N.getOperand(2).getOpcode() == ISD::Constant &&
589       N.getOperand(3).getOpcode() == ISD::Constant &&
590       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
591       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
592     LHS = N.getOperand(0);
593     RHS = N.getOperand(1);
594     CC  = N.getOperand(4);
595     return true;
596   }
597   return false;
598 }
599
600 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
601 // one use.  If this is true, it allows the users to invert the operation for
602 // free when it is profitable to do so.
603 static bool isOneUseSetCC(SDValue N) {
604   SDValue N0, N1, N2;
605   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
606     return true;
607   return false;
608 }
609
610 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
611                                     SDValue N0, SDValue N1) {
612   EVT VT = N0.getValueType();
613   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
614     if (isa<ConstantSDNode>(N1)) {
615       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
616       SDValue OpNode =
617         DAG.FoldConstantArithmetic(Opc, VT,
618                                    cast<ConstantSDNode>(N0.getOperand(1)),
619                                    cast<ConstantSDNode>(N1));
620       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
621     }
622     if (N0.hasOneUse()) {
623       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
624       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
625                                    N0.getOperand(0), N1);
626       AddToWorkList(OpNode.getNode());
627       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
628     }
629   }
630
631   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
632     if (isa<ConstantSDNode>(N0)) {
633       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
634       SDValue OpNode =
635         DAG.FoldConstantArithmetic(Opc, VT,
636                                    cast<ConstantSDNode>(N1.getOperand(1)),
637                                    cast<ConstantSDNode>(N0));
638       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
639     }
640     if (N1.hasOneUse()) {
641       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
642       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
643                                    N1.getOperand(0), N0);
644       AddToWorkList(OpNode.getNode());
645       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
646     }
647   }
648
649   return SDValue();
650 }
651
652 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
653                                bool AddTo) {
654   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
655   ++NodesCombined;
656   DEBUG(dbgs() << "\nReplacing.1 ";
657         N->dump(&DAG);
658         dbgs() << "\nWith: ";
659         To[0].getNode()->dump(&DAG);
660         dbgs() << " and " << NumTo-1 << " other values\n";
661         for (unsigned i = 0, e = NumTo; i != e; ++i)
662           assert((!To[i].getNode() ||
663                   N->getValueType(i) == To[i].getValueType()) &&
664                  "Cannot combine value to value of different type!"));
665   WorkListRemover DeadNodes(*this);
666   DAG.ReplaceAllUsesWith(N, To);
667   if (AddTo) {
668     // Push the new nodes and any users onto the worklist
669     for (unsigned i = 0, e = NumTo; i != e; ++i) {
670       if (To[i].getNode()) {
671         AddToWorkList(To[i].getNode());
672         AddUsersToWorkList(To[i].getNode());
673       }
674     }
675   }
676
677   // Finally, if the node is now dead, remove it from the graph.  The node
678   // may not be dead if the replacement process recursively simplified to
679   // something else needing this node.
680   if (N->use_empty()) {
681     // Nodes can be reintroduced into the worklist.  Make sure we do not
682     // process a node that has been replaced.
683     removeFromWorkList(N);
684
685     // Finally, since the node is now dead, remove it from the graph.
686     DAG.DeleteNode(N);
687   }
688   return SDValue(N, 0);
689 }
690
691 void DAGCombiner::
692 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
693   // Replace all uses.  If any nodes become isomorphic to other nodes and
694   // are deleted, make sure to remove them from our worklist.
695   WorkListRemover DeadNodes(*this);
696   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
697
698   // Push the new node and any (possibly new) users onto the worklist.
699   AddToWorkList(TLO.New.getNode());
700   AddUsersToWorkList(TLO.New.getNode());
701
702   // Finally, if the node is now dead, remove it from the graph.  The node
703   // may not be dead if the replacement process recursively simplified to
704   // something else needing this node.
705   if (TLO.Old.getNode()->use_empty()) {
706     removeFromWorkList(TLO.Old.getNode());
707
708     // If the operands of this node are only used by the node, they will now
709     // be dead.  Make sure to visit them first to delete dead nodes early.
710     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
711       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
712         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
713
714     DAG.DeleteNode(TLO.Old.getNode());
715   }
716 }
717
718 /// SimplifyDemandedBits - Check the specified integer node value to see if
719 /// it can be simplified or if things it uses can be simplified by bit
720 /// propagation.  If so, return true.
721 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
722   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
723   APInt KnownZero, KnownOne;
724   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
725     return false;
726
727   // Revisit the node.
728   AddToWorkList(Op.getNode());
729
730   // Replace the old value with the new one.
731   ++NodesCombined;
732   DEBUG(dbgs() << "\nReplacing.2 ";
733         TLO.Old.getNode()->dump(&DAG);
734         dbgs() << "\nWith: ";
735         TLO.New.getNode()->dump(&DAG);
736         dbgs() << '\n');
737
738   CommitTargetLoweringOpt(TLO);
739   return true;
740 }
741
742 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
743   SDLoc dl(Load);
744   EVT VT = Load->getValueType(0);
745   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
746
747   DEBUG(dbgs() << "\nReplacing.9 ";
748         Load->dump(&DAG);
749         dbgs() << "\nWith: ";
750         Trunc.getNode()->dump(&DAG);
751         dbgs() << '\n');
752   WorkListRemover DeadNodes(*this);
753   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
754   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
755   removeFromWorkList(Load);
756   DAG.DeleteNode(Load);
757   AddToWorkList(Trunc.getNode());
758 }
759
760 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
761   Replace = false;
762   SDLoc dl(Op);
763   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
764     EVT MemVT = LD->getMemoryVT();
765     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
766       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
767                                                   : ISD::EXTLOAD)
768       : LD->getExtensionType();
769     Replace = true;
770     return DAG.getExtLoad(ExtType, dl, PVT,
771                           LD->getChain(), LD->getBasePtr(),
772                           MemVT, LD->getMemOperand());
773   }
774
775   unsigned Opc = Op.getOpcode();
776   switch (Opc) {
777   default: break;
778   case ISD::AssertSext:
779     return DAG.getNode(ISD::AssertSext, dl, PVT,
780                        SExtPromoteOperand(Op.getOperand(0), PVT),
781                        Op.getOperand(1));
782   case ISD::AssertZext:
783     return DAG.getNode(ISD::AssertZext, dl, PVT,
784                        ZExtPromoteOperand(Op.getOperand(0), PVT),
785                        Op.getOperand(1));
786   case ISD::Constant: {
787     unsigned ExtOpc =
788       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
789     return DAG.getNode(ExtOpc, dl, PVT, Op);
790   }
791   }
792
793   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
794     return SDValue();
795   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
796 }
797
798 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
799   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
800     return SDValue();
801   EVT OldVT = Op.getValueType();
802   SDLoc dl(Op);
803   bool Replace = false;
804   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
805   if (NewOp.getNode() == 0)
806     return SDValue();
807   AddToWorkList(NewOp.getNode());
808
809   if (Replace)
810     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
811   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
812                      DAG.getValueType(OldVT));
813 }
814
815 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
816   EVT OldVT = Op.getValueType();
817   SDLoc dl(Op);
818   bool Replace = false;
819   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
820   if (NewOp.getNode() == 0)
821     return SDValue();
822   AddToWorkList(NewOp.getNode());
823
824   if (Replace)
825     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
826   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
827 }
828
829 /// PromoteIntBinOp - Promote the specified integer binary operation if the
830 /// target indicates it is beneficial. e.g. On x86, it's usually better to
831 /// promote i16 operations to i32 since i16 instructions are longer.
832 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
833   if (!LegalOperations)
834     return SDValue();
835
836   EVT VT = Op.getValueType();
837   if (VT.isVector() || !VT.isInteger())
838     return SDValue();
839
840   // If operation type is 'undesirable', e.g. i16 on x86, consider
841   // promoting it.
842   unsigned Opc = Op.getOpcode();
843   if (TLI.isTypeDesirableForOp(Opc, VT))
844     return SDValue();
845
846   EVT PVT = VT;
847   // Consult target whether it is a good idea to promote this operation and
848   // what's the right type to promote it to.
849   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
850     assert(PVT != VT && "Don't know what type to promote to!");
851
852     bool Replace0 = false;
853     SDValue N0 = Op.getOperand(0);
854     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
855     if (NN0.getNode() == 0)
856       return SDValue();
857
858     bool Replace1 = false;
859     SDValue N1 = Op.getOperand(1);
860     SDValue NN1;
861     if (N0 == N1)
862       NN1 = NN0;
863     else {
864       NN1 = PromoteOperand(N1, PVT, Replace1);
865       if (NN1.getNode() == 0)
866         return SDValue();
867     }
868
869     AddToWorkList(NN0.getNode());
870     if (NN1.getNode())
871       AddToWorkList(NN1.getNode());
872
873     if (Replace0)
874       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
875     if (Replace1)
876       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
877
878     DEBUG(dbgs() << "\nPromoting ";
879           Op.getNode()->dump(&DAG));
880     SDLoc dl(Op);
881     return DAG.getNode(ISD::TRUNCATE, dl, VT,
882                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
883   }
884   return SDValue();
885 }
886
887 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
888 /// target indicates it is beneficial. e.g. On x86, it's usually better to
889 /// promote i16 operations to i32 since i16 instructions are longer.
890 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
891   if (!LegalOperations)
892     return SDValue();
893
894   EVT VT = Op.getValueType();
895   if (VT.isVector() || !VT.isInteger())
896     return SDValue();
897
898   // If operation type is 'undesirable', e.g. i16 on x86, consider
899   // promoting it.
900   unsigned Opc = Op.getOpcode();
901   if (TLI.isTypeDesirableForOp(Opc, VT))
902     return SDValue();
903
904   EVT PVT = VT;
905   // Consult target whether it is a good idea to promote this operation and
906   // what's the right type to promote it to.
907   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
908     assert(PVT != VT && "Don't know what type to promote to!");
909
910     bool Replace = false;
911     SDValue N0 = Op.getOperand(0);
912     if (Opc == ISD::SRA)
913       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
914     else if (Opc == ISD::SRL)
915       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
916     else
917       N0 = PromoteOperand(N0, PVT, Replace);
918     if (N0.getNode() == 0)
919       return SDValue();
920
921     AddToWorkList(N0.getNode());
922     if (Replace)
923       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
924
925     DEBUG(dbgs() << "\nPromoting ";
926           Op.getNode()->dump(&DAG));
927     SDLoc dl(Op);
928     return DAG.getNode(ISD::TRUNCATE, dl, VT,
929                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
930   }
931   return SDValue();
932 }
933
934 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
935   if (!LegalOperations)
936     return SDValue();
937
938   EVT VT = Op.getValueType();
939   if (VT.isVector() || !VT.isInteger())
940     return SDValue();
941
942   // If operation type is 'undesirable', e.g. i16 on x86, consider
943   // promoting it.
944   unsigned Opc = Op.getOpcode();
945   if (TLI.isTypeDesirableForOp(Opc, VT))
946     return SDValue();
947
948   EVT PVT = VT;
949   // Consult target whether it is a good idea to promote this operation and
950   // what's the right type to promote it to.
951   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
952     assert(PVT != VT && "Don't know what type to promote to!");
953     // fold (aext (aext x)) -> (aext x)
954     // fold (aext (zext x)) -> (zext x)
955     // fold (aext (sext x)) -> (sext x)
956     DEBUG(dbgs() << "\nPromoting ";
957           Op.getNode()->dump(&DAG));
958     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
959   }
960   return SDValue();
961 }
962
963 bool DAGCombiner::PromoteLoad(SDValue Op) {
964   if (!LegalOperations)
965     return false;
966
967   EVT VT = Op.getValueType();
968   if (VT.isVector() || !VT.isInteger())
969     return false;
970
971   // If operation type is 'undesirable', e.g. i16 on x86, consider
972   // promoting it.
973   unsigned Opc = Op.getOpcode();
974   if (TLI.isTypeDesirableForOp(Opc, VT))
975     return false;
976
977   EVT PVT = VT;
978   // Consult target whether it is a good idea to promote this operation and
979   // what's the right type to promote it to.
980   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
981     assert(PVT != VT && "Don't know what type to promote to!");
982
983     SDLoc dl(Op);
984     SDNode *N = Op.getNode();
985     LoadSDNode *LD = cast<LoadSDNode>(N);
986     EVT MemVT = LD->getMemoryVT();
987     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
988       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
989                                                   : ISD::EXTLOAD)
990       : LD->getExtensionType();
991     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
992                                    LD->getChain(), LD->getBasePtr(),
993                                    MemVT, LD->getMemOperand());
994     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
995
996     DEBUG(dbgs() << "\nPromoting ";
997           N->dump(&DAG);
998           dbgs() << "\nTo: ";
999           Result.getNode()->dump(&DAG);
1000           dbgs() << '\n');
1001     WorkListRemover DeadNodes(*this);
1002     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1003     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1004     removeFromWorkList(N);
1005     DAG.DeleteNode(N);
1006     AddToWorkList(Result.getNode());
1007     return true;
1008   }
1009   return false;
1010 }
1011
1012
1013 //===----------------------------------------------------------------------===//
1014 //  Main DAG Combiner implementation
1015 //===----------------------------------------------------------------------===//
1016
1017 void DAGCombiner::Run(CombineLevel AtLevel) {
1018   // set the instance variables, so that the various visit routines may use it.
1019   Level = AtLevel;
1020   LegalOperations = Level >= AfterLegalizeVectorOps;
1021   LegalTypes = Level >= AfterLegalizeTypes;
1022
1023   // Add all the dag nodes to the worklist.
1024   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1025        E = DAG.allnodes_end(); I != E; ++I)
1026     AddToWorkList(I);
1027
1028   // Create a dummy node (which is not added to allnodes), that adds a reference
1029   // to the root node, preventing it from being deleted, and tracking any
1030   // changes of the root.
1031   HandleSDNode Dummy(DAG.getRoot());
1032
1033   // The root of the dag may dangle to deleted nodes until the dag combiner is
1034   // done.  Set it to null to avoid confusion.
1035   DAG.setRoot(SDValue());
1036
1037   // while the worklist isn't empty, find a node and
1038   // try and combine it.
1039   while (!WorkListContents.empty()) {
1040     SDNode *N;
1041     // The WorkListOrder holds the SDNodes in order, but it may contain
1042     // duplicates.
1043     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1044     // worklist *should* contain, and check the node we want to visit is should
1045     // actually be visited.
1046     do {
1047       N = WorkListOrder.pop_back_val();
1048     } while (!WorkListContents.erase(N));
1049
1050     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1051     // N is deleted from the DAG, since they too may now be dead or may have a
1052     // reduced number of uses, allowing other xforms.
1053     if (N->use_empty() && N != &Dummy) {
1054       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1055         AddToWorkList(N->getOperand(i).getNode());
1056
1057       DAG.DeleteNode(N);
1058       continue;
1059     }
1060
1061     SDValue RV = combine(N);
1062
1063     if (RV.getNode() == 0)
1064       continue;
1065
1066     ++NodesCombined;
1067
1068     // If we get back the same node we passed in, rather than a new node or
1069     // zero, we know that the node must have defined multiple values and
1070     // CombineTo was used.  Since CombineTo takes care of the worklist
1071     // mechanics for us, we have no work to do in this case.
1072     if (RV.getNode() == N)
1073       continue;
1074
1075     assert(N->getOpcode() != ISD::DELETED_NODE &&
1076            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1077            "Node was deleted but visit returned new node!");
1078
1079     DEBUG(dbgs() << "\nReplacing.3 ";
1080           N->dump(&DAG);
1081           dbgs() << "\nWith: ";
1082           RV.getNode()->dump(&DAG);
1083           dbgs() << '\n');
1084
1085     // Transfer debug value.
1086     DAG.TransferDbgValues(SDValue(N, 0), RV);
1087     WorkListRemover DeadNodes(*this);
1088     if (N->getNumValues() == RV.getNode()->getNumValues())
1089       DAG.ReplaceAllUsesWith(N, RV.getNode());
1090     else {
1091       assert(N->getValueType(0) == RV.getValueType() &&
1092              N->getNumValues() == 1 && "Type mismatch");
1093       SDValue OpV = RV;
1094       DAG.ReplaceAllUsesWith(N, &OpV);
1095     }
1096
1097     // Push the new node and any users onto the worklist
1098     AddToWorkList(RV.getNode());
1099     AddUsersToWorkList(RV.getNode());
1100
1101     // Add any uses of the old node to the worklist in case this node is the
1102     // last one that uses them.  They may become dead after this node is
1103     // deleted.
1104     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1105       AddToWorkList(N->getOperand(i).getNode());
1106
1107     // Finally, if the node is now dead, remove it from the graph.  The node
1108     // may not be dead if the replacement process recursively simplified to
1109     // something else needing this node.
1110     if (N->use_empty()) {
1111       // Nodes can be reintroduced into the worklist.  Make sure we do not
1112       // process a node that has been replaced.
1113       removeFromWorkList(N);
1114
1115       // Finally, since the node is now dead, remove it from the graph.
1116       DAG.DeleteNode(N);
1117     }
1118   }
1119
1120   // If the root changed (e.g. it was a dead load, update the root).
1121   DAG.setRoot(Dummy.getValue());
1122   DAG.RemoveDeadNodes();
1123 }
1124
1125 SDValue DAGCombiner::visit(SDNode *N) {
1126   switch (N->getOpcode()) {
1127   default: break;
1128   case ISD::TokenFactor:        return visitTokenFactor(N);
1129   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1130   case ISD::ADD:                return visitADD(N);
1131   case ISD::SUB:                return visitSUB(N);
1132   case ISD::ADDC:               return visitADDC(N);
1133   case ISD::SUBC:               return visitSUBC(N);
1134   case ISD::ADDE:               return visitADDE(N);
1135   case ISD::SUBE:               return visitSUBE(N);
1136   case ISD::MUL:                return visitMUL(N);
1137   case ISD::SDIV:               return visitSDIV(N);
1138   case ISD::UDIV:               return visitUDIV(N);
1139   case ISD::SREM:               return visitSREM(N);
1140   case ISD::UREM:               return visitUREM(N);
1141   case ISD::MULHU:              return visitMULHU(N);
1142   case ISD::MULHS:              return visitMULHS(N);
1143   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1144   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1145   case ISD::SMULO:              return visitSMULO(N);
1146   case ISD::UMULO:              return visitUMULO(N);
1147   case ISD::SDIVREM:            return visitSDIVREM(N);
1148   case ISD::UDIVREM:            return visitUDIVREM(N);
1149   case ISD::AND:                return visitAND(N);
1150   case ISD::OR:                 return visitOR(N);
1151   case ISD::XOR:                return visitXOR(N);
1152   case ISD::SHL:                return visitSHL(N);
1153   case ISD::SRA:                return visitSRA(N);
1154   case ISD::SRL:                return visitSRL(N);
1155   case ISD::CTLZ:               return visitCTLZ(N);
1156   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1157   case ISD::CTTZ:               return visitCTTZ(N);
1158   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1159   case ISD::CTPOP:              return visitCTPOP(N);
1160   case ISD::SELECT:             return visitSELECT(N);
1161   case ISD::VSELECT:            return visitVSELECT(N);
1162   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1163   case ISD::SETCC:              return visitSETCC(N);
1164   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1165   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1166   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1167   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1168   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1169   case ISD::BITCAST:            return visitBITCAST(N);
1170   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1171   case ISD::FADD:               return visitFADD(N);
1172   case ISD::FSUB:               return visitFSUB(N);
1173   case ISD::FMUL:               return visitFMUL(N);
1174   case ISD::FMA:                return visitFMA(N);
1175   case ISD::FDIV:               return visitFDIV(N);
1176   case ISD::FREM:               return visitFREM(N);
1177   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1178   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1179   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1180   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1181   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1182   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1183   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1184   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1185   case ISD::FNEG:               return visitFNEG(N);
1186   case ISD::FABS:               return visitFABS(N);
1187   case ISD::FFLOOR:             return visitFFLOOR(N);
1188   case ISD::FCEIL:              return visitFCEIL(N);
1189   case ISD::FTRUNC:             return visitFTRUNC(N);
1190   case ISD::BRCOND:             return visitBRCOND(N);
1191   case ISD::BR_CC:              return visitBR_CC(N);
1192   case ISD::LOAD:               return visitLOAD(N);
1193   case ISD::STORE:              return visitSTORE(N);
1194   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1195   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1196   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1197   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1198   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1199   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1200   }
1201   return SDValue();
1202 }
1203
1204 SDValue DAGCombiner::combine(SDNode *N) {
1205   SDValue RV = visit(N);
1206
1207   // If nothing happened, try a target-specific DAG combine.
1208   if (RV.getNode() == 0) {
1209     assert(N->getOpcode() != ISD::DELETED_NODE &&
1210            "Node was deleted but visit returned NULL!");
1211
1212     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1213         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1214
1215       // Expose the DAG combiner to the target combiner impls.
1216       TargetLowering::DAGCombinerInfo
1217         DagCombineInfo(DAG, Level, false, this);
1218
1219       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1220     }
1221   }
1222
1223   // If nothing happened still, try promoting the operation.
1224   if (RV.getNode() == 0) {
1225     switch (N->getOpcode()) {
1226     default: break;
1227     case ISD::ADD:
1228     case ISD::SUB:
1229     case ISD::MUL:
1230     case ISD::AND:
1231     case ISD::OR:
1232     case ISD::XOR:
1233       RV = PromoteIntBinOp(SDValue(N, 0));
1234       break;
1235     case ISD::SHL:
1236     case ISD::SRA:
1237     case ISD::SRL:
1238       RV = PromoteIntShiftOp(SDValue(N, 0));
1239       break;
1240     case ISD::SIGN_EXTEND:
1241     case ISD::ZERO_EXTEND:
1242     case ISD::ANY_EXTEND:
1243       RV = PromoteExtend(SDValue(N, 0));
1244       break;
1245     case ISD::LOAD:
1246       if (PromoteLoad(SDValue(N, 0)))
1247         RV = SDValue(N, 0);
1248       break;
1249     }
1250   }
1251
1252   // If N is a commutative binary node, try commuting it to enable more
1253   // sdisel CSE.
1254   if (RV.getNode() == 0 &&
1255       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1256       N->getNumValues() == 1) {
1257     SDValue N0 = N->getOperand(0);
1258     SDValue N1 = N->getOperand(1);
1259
1260     // Constant operands are canonicalized to RHS.
1261     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1262       SDValue Ops[] = { N1, N0 };
1263       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1264                                             Ops, 2);
1265       if (CSENode)
1266         return SDValue(CSENode, 0);
1267     }
1268   }
1269
1270   return RV;
1271 }
1272
1273 /// getInputChainForNode - Given a node, return its input chain if it has one,
1274 /// otherwise return a null sd operand.
1275 static SDValue getInputChainForNode(SDNode *N) {
1276   if (unsigned NumOps = N->getNumOperands()) {
1277     if (N->getOperand(0).getValueType() == MVT::Other)
1278       return N->getOperand(0);
1279     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1280       return N->getOperand(NumOps-1);
1281     for (unsigned i = 1; i < NumOps-1; ++i)
1282       if (N->getOperand(i).getValueType() == MVT::Other)
1283         return N->getOperand(i);
1284   }
1285   return SDValue();
1286 }
1287
1288 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1289   // If N has two operands, where one has an input chain equal to the other,
1290   // the 'other' chain is redundant.
1291   if (N->getNumOperands() == 2) {
1292     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1293       return N->getOperand(0);
1294     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1295       return N->getOperand(1);
1296   }
1297
1298   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1299   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1300   SmallPtrSet<SDNode*, 16> SeenOps;
1301   bool Changed = false;             // If we should replace this token factor.
1302
1303   // Start out with this token factor.
1304   TFs.push_back(N);
1305
1306   // Iterate through token factors.  The TFs grows when new token factors are
1307   // encountered.
1308   for (unsigned i = 0; i < TFs.size(); ++i) {
1309     SDNode *TF = TFs[i];
1310
1311     // Check each of the operands.
1312     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1313       SDValue Op = TF->getOperand(i);
1314
1315       switch (Op.getOpcode()) {
1316       case ISD::EntryToken:
1317         // Entry tokens don't need to be added to the list. They are
1318         // rededundant.
1319         Changed = true;
1320         break;
1321
1322       case ISD::TokenFactor:
1323         if (Op.hasOneUse() &&
1324             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1325           // Queue up for processing.
1326           TFs.push_back(Op.getNode());
1327           // Clean up in case the token factor is removed.
1328           AddToWorkList(Op.getNode());
1329           Changed = true;
1330           break;
1331         }
1332         // Fall thru
1333
1334       default:
1335         // Only add if it isn't already in the list.
1336         if (SeenOps.insert(Op.getNode()))
1337           Ops.push_back(Op);
1338         else
1339           Changed = true;
1340         break;
1341       }
1342     }
1343   }
1344
1345   SDValue Result;
1346
1347   // If we've change things around then replace token factor.
1348   if (Changed) {
1349     if (Ops.empty()) {
1350       // The entry token is the only possible outcome.
1351       Result = DAG.getEntryNode();
1352     } else {
1353       // New and improved token factor.
1354       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1355                            MVT::Other, &Ops[0], Ops.size());
1356     }
1357
1358     // Don't add users to work list.
1359     return CombineTo(N, Result, false);
1360   }
1361
1362   return Result;
1363 }
1364
1365 /// MERGE_VALUES can always be eliminated.
1366 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1367   WorkListRemover DeadNodes(*this);
1368   // Replacing results may cause a different MERGE_VALUES to suddenly
1369   // be CSE'd with N, and carry its uses with it. Iterate until no
1370   // uses remain, to ensure that the node can be safely deleted.
1371   // First add the users of this node to the work list so that they
1372   // can be tried again once they have new operands.
1373   AddUsersToWorkList(N);
1374   do {
1375     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1376       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1377   } while (!N->use_empty());
1378   removeFromWorkList(N);
1379   DAG.DeleteNode(N);
1380   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1381 }
1382
1383 static
1384 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1385                               SelectionDAG &DAG) {
1386   EVT VT = N0.getValueType();
1387   SDValue N00 = N0.getOperand(0);
1388   SDValue N01 = N0.getOperand(1);
1389   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1390
1391   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1392       isa<ConstantSDNode>(N00.getOperand(1))) {
1393     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1394     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1395                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1396                                  N00.getOperand(0), N01),
1397                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1398                                  N00.getOperand(1), N01));
1399     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1400   }
1401
1402   return SDValue();
1403 }
1404
1405 SDValue DAGCombiner::visitADD(SDNode *N) {
1406   SDValue N0 = N->getOperand(0);
1407   SDValue N1 = N->getOperand(1);
1408   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1409   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1410   EVT VT = N0.getValueType();
1411
1412   // fold vector ops
1413   if (VT.isVector()) {
1414     SDValue FoldedVOp = SimplifyVBinOp(N);
1415     if (FoldedVOp.getNode()) return FoldedVOp;
1416
1417     // fold (add x, 0) -> x, vector edition
1418     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1419       return N0;
1420     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1421       return N1;
1422   }
1423
1424   // fold (add x, undef) -> undef
1425   if (N0.getOpcode() == ISD::UNDEF)
1426     return N0;
1427   if (N1.getOpcode() == ISD::UNDEF)
1428     return N1;
1429   // fold (add c1, c2) -> c1+c2
1430   if (N0C && N1C)
1431     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1432   // canonicalize constant to RHS
1433   if (N0C && !N1C)
1434     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1435   // fold (add x, 0) -> x
1436   if (N1C && N1C->isNullValue())
1437     return N0;
1438   // fold (add Sym, c) -> Sym+c
1439   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1440     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1441         GA->getOpcode() == ISD::GlobalAddress)
1442       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1443                                   GA->getOffset() +
1444                                     (uint64_t)N1C->getSExtValue());
1445   // fold ((c1-A)+c2) -> (c1+c2)-A
1446   if (N1C && N0.getOpcode() == ISD::SUB)
1447     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1448       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1449                          DAG.getConstant(N1C->getAPIntValue()+
1450                                          N0C->getAPIntValue(), VT),
1451                          N0.getOperand(1));
1452   // reassociate add
1453   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1454   if (RADD.getNode() != 0)
1455     return RADD;
1456   // fold ((0-A) + B) -> B-A
1457   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1458       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1459     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1460   // fold (A + (0-B)) -> A-B
1461   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1462       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1463     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1464   // fold (A+(B-A)) -> B
1465   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1466     return N1.getOperand(0);
1467   // fold ((B-A)+A) -> B
1468   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1469     return N0.getOperand(0);
1470   // fold (A+(B-(A+C))) to (B-C)
1471   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1472       N0 == N1.getOperand(1).getOperand(0))
1473     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1474                        N1.getOperand(1).getOperand(1));
1475   // fold (A+(B-(C+A))) to (B-C)
1476   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1477       N0 == N1.getOperand(1).getOperand(1))
1478     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1479                        N1.getOperand(1).getOperand(0));
1480   // fold (A+((B-A)+or-C)) to (B+or-C)
1481   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1482       N1.getOperand(0).getOpcode() == ISD::SUB &&
1483       N0 == N1.getOperand(0).getOperand(1))
1484     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1485                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1486
1487   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1488   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1489     SDValue N00 = N0.getOperand(0);
1490     SDValue N01 = N0.getOperand(1);
1491     SDValue N10 = N1.getOperand(0);
1492     SDValue N11 = N1.getOperand(1);
1493
1494     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1495       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1496                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1497                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1498   }
1499
1500   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1501     return SDValue(N, 0);
1502
1503   // fold (a+b) -> (a|b) iff a and b share no bits.
1504   if (VT.isInteger() && !VT.isVector()) {
1505     APInt LHSZero, LHSOne;
1506     APInt RHSZero, RHSOne;
1507     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1508
1509     if (LHSZero.getBoolValue()) {
1510       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1511
1512       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1513       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1514       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1515         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1516     }
1517   }
1518
1519   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1520   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1521     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1522     if (Result.getNode()) return Result;
1523   }
1524   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1525     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1526     if (Result.getNode()) return Result;
1527   }
1528
1529   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1530   if (N1.getOpcode() == ISD::SHL &&
1531       N1.getOperand(0).getOpcode() == ISD::SUB)
1532     if (ConstantSDNode *C =
1533           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1534       if (C->getAPIntValue() == 0)
1535         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1536                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1537                                        N1.getOperand(0).getOperand(1),
1538                                        N1.getOperand(1)));
1539   if (N0.getOpcode() == ISD::SHL &&
1540       N0.getOperand(0).getOpcode() == ISD::SUB)
1541     if (ConstantSDNode *C =
1542           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1543       if (C->getAPIntValue() == 0)
1544         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1545                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1546                                        N0.getOperand(0).getOperand(1),
1547                                        N0.getOperand(1)));
1548
1549   if (N1.getOpcode() == ISD::AND) {
1550     SDValue AndOp0 = N1.getOperand(0);
1551     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1552     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1553     unsigned DestBits = VT.getScalarType().getSizeInBits();
1554
1555     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1556     // and similar xforms where the inner op is either ~0 or 0.
1557     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1558       SDLoc DL(N);
1559       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1560     }
1561   }
1562
1563   // add (sext i1), X -> sub X, (zext i1)
1564   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1565       N0.getOperand(0).getValueType() == MVT::i1 &&
1566       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1567     SDLoc DL(N);
1568     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1569     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1570   }
1571
1572   return SDValue();
1573 }
1574
1575 SDValue DAGCombiner::visitADDC(SDNode *N) {
1576   SDValue N0 = N->getOperand(0);
1577   SDValue N1 = N->getOperand(1);
1578   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1579   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1580   EVT VT = N0.getValueType();
1581
1582   // If the flag result is dead, turn this into an ADD.
1583   if (!N->hasAnyUseOfValue(1))
1584     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1585                      DAG.getNode(ISD::CARRY_FALSE,
1586                                  SDLoc(N), MVT::Glue));
1587
1588   // canonicalize constant to RHS.
1589   if (N0C && !N1C)
1590     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1591
1592   // fold (addc x, 0) -> x + no carry out
1593   if (N1C && N1C->isNullValue())
1594     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1595                                         SDLoc(N), MVT::Glue));
1596
1597   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1598   APInt LHSZero, LHSOne;
1599   APInt RHSZero, RHSOne;
1600   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1601
1602   if (LHSZero.getBoolValue()) {
1603     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1604
1605     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1606     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1607     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1608       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1609                        DAG.getNode(ISD::CARRY_FALSE,
1610                                    SDLoc(N), MVT::Glue));
1611   }
1612
1613   return SDValue();
1614 }
1615
1616 SDValue DAGCombiner::visitADDE(SDNode *N) {
1617   SDValue N0 = N->getOperand(0);
1618   SDValue N1 = N->getOperand(1);
1619   SDValue CarryIn = N->getOperand(2);
1620   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1621   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1622
1623   // canonicalize constant to RHS
1624   if (N0C && !N1C)
1625     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1626                        N1, N0, CarryIn);
1627
1628   // fold (adde x, y, false) -> (addc x, y)
1629   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1630     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1631
1632   return SDValue();
1633 }
1634
1635 // Since it may not be valid to emit a fold to zero for vector initializers
1636 // check if we can before folding.
1637 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1638                              SelectionDAG &DAG,
1639                              bool LegalOperations, bool LegalTypes) {
1640   if (!VT.isVector())
1641     return DAG.getConstant(0, VT);
1642   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1643     return DAG.getConstant(0, VT);
1644   return SDValue();
1645 }
1646
1647 SDValue DAGCombiner::visitSUB(SDNode *N) {
1648   SDValue N0 = N->getOperand(0);
1649   SDValue N1 = N->getOperand(1);
1650   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1651   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1652   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1653     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1654   EVT VT = N0.getValueType();
1655
1656   // fold vector ops
1657   if (VT.isVector()) {
1658     SDValue FoldedVOp = SimplifyVBinOp(N);
1659     if (FoldedVOp.getNode()) return FoldedVOp;
1660
1661     // fold (sub x, 0) -> x, vector edition
1662     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1663       return N0;
1664   }
1665
1666   // fold (sub x, x) -> 0
1667   // FIXME: Refactor this and xor and other similar operations together.
1668   if (N0 == N1)
1669     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1670   // fold (sub c1, c2) -> c1-c2
1671   if (N0C && N1C)
1672     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1673   // fold (sub x, c) -> (add x, -c)
1674   if (N1C)
1675     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1676                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1677   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1678   if (N0C && N0C->isAllOnesValue())
1679     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1680   // fold A-(A-B) -> B
1681   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1682     return N1.getOperand(1);
1683   // fold (A+B)-A -> B
1684   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1685     return N0.getOperand(1);
1686   // fold (A+B)-B -> A
1687   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1688     return N0.getOperand(0);
1689   // fold C2-(A+C1) -> (C2-C1)-A
1690   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1691     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1692                                    VT);
1693     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1694                        N1.getOperand(0));
1695   }
1696   // fold ((A+(B+or-C))-B) -> A+or-C
1697   if (N0.getOpcode() == ISD::ADD &&
1698       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1699        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1700       N0.getOperand(1).getOperand(0) == N1)
1701     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1702                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1703   // fold ((A+(C+B))-B) -> A+C
1704   if (N0.getOpcode() == ISD::ADD &&
1705       N0.getOperand(1).getOpcode() == ISD::ADD &&
1706       N0.getOperand(1).getOperand(1) == N1)
1707     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1708                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1709   // fold ((A-(B-C))-C) -> A-B
1710   if (N0.getOpcode() == ISD::SUB &&
1711       N0.getOperand(1).getOpcode() == ISD::SUB &&
1712       N0.getOperand(1).getOperand(1) == N1)
1713     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1714                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1715
1716   // If either operand of a sub is undef, the result is undef
1717   if (N0.getOpcode() == ISD::UNDEF)
1718     return N0;
1719   if (N1.getOpcode() == ISD::UNDEF)
1720     return N1;
1721
1722   // If the relocation model supports it, consider symbol offsets.
1723   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1724     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1725       // fold (sub Sym, c) -> Sym-c
1726       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1727         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1728                                     GA->getOffset() -
1729                                       (uint64_t)N1C->getSExtValue());
1730       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1731       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1732         if (GA->getGlobal() == GB->getGlobal())
1733           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1734                                  VT);
1735     }
1736
1737   return SDValue();
1738 }
1739
1740 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1741   SDValue N0 = N->getOperand(0);
1742   SDValue N1 = N->getOperand(1);
1743   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1745   EVT VT = N0.getValueType();
1746
1747   // If the flag result is dead, turn this into an SUB.
1748   if (!N->hasAnyUseOfValue(1))
1749     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1750                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1751                                  MVT::Glue));
1752
1753   // fold (subc x, x) -> 0 + no borrow
1754   if (N0 == N1)
1755     return CombineTo(N, DAG.getConstant(0, VT),
1756                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1757                                  MVT::Glue));
1758
1759   // fold (subc x, 0) -> x + no borrow
1760   if (N1C && N1C->isNullValue())
1761     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1762                                         MVT::Glue));
1763
1764   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1765   if (N0C && N0C->isAllOnesValue())
1766     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1767                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1768                                  MVT::Glue));
1769
1770   return SDValue();
1771 }
1772
1773 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1774   SDValue N0 = N->getOperand(0);
1775   SDValue N1 = N->getOperand(1);
1776   SDValue CarryIn = N->getOperand(2);
1777
1778   // fold (sube x, y, false) -> (subc x, y)
1779   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1780     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1781
1782   return SDValue();
1783 }
1784
1785 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1786 /// elements are all the same constant or undefined.
1787 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1788   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1789   if (!C)
1790     return false;
1791
1792   APInt SplatUndef;
1793   unsigned SplatBitSize;
1794   bool HasAnyUndefs;
1795   EVT EltVT = N->getValueType(0).getVectorElementType();
1796   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1797                              HasAnyUndefs) &&
1798           EltVT.getSizeInBits() >= SplatBitSize);
1799 }
1800
1801 SDValue DAGCombiner::visitMUL(SDNode *N) {
1802   SDValue N0 = N->getOperand(0);
1803   SDValue N1 = N->getOperand(1);
1804   EVT VT = N0.getValueType();
1805
1806   // fold (mul x, undef) -> 0
1807   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1808     return DAG.getConstant(0, VT);
1809
1810   bool N0IsConst = false;
1811   bool N1IsConst = false;
1812   APInt ConstValue0, ConstValue1;
1813   // fold vector ops
1814   if (VT.isVector()) {
1815     SDValue FoldedVOp = SimplifyVBinOp(N);
1816     if (FoldedVOp.getNode()) return FoldedVOp;
1817
1818     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1819     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1820   } else {
1821     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1822     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1823                             : APInt();
1824     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1825     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1826                             : APInt();
1827   }
1828
1829   // fold (mul c1, c2) -> c1*c2
1830   if (N0IsConst && N1IsConst)
1831     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1832
1833   // canonicalize constant to RHS
1834   if (N0IsConst && !N1IsConst)
1835     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1836   // fold (mul x, 0) -> 0
1837   if (N1IsConst && ConstValue1 == 0)
1838     return N1;
1839   // We require a splat of the entire scalar bit width for non-contiguous
1840   // bit patterns.
1841   bool IsFullSplat =
1842     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1843   // fold (mul x, 1) -> x
1844   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1845     return N0;
1846   // fold (mul x, -1) -> 0-x
1847   if (N1IsConst && ConstValue1.isAllOnesValue())
1848     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849                        DAG.getConstant(0, VT), N0);
1850   // fold (mul x, (1 << c)) -> x << c
1851   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1852     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1853                        DAG.getConstant(ConstValue1.logBase2(),
1854                                        getShiftAmountTy(N0.getValueType())));
1855   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1856   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1857     unsigned Log2Val = (-ConstValue1).logBase2();
1858     // FIXME: If the input is something that is easily negated (e.g. a
1859     // single-use add), we should put the negate there.
1860     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1861                        DAG.getConstant(0, VT),
1862                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1863                             DAG.getConstant(Log2Val,
1864                                       getShiftAmountTy(N0.getValueType()))));
1865   }
1866
1867   APInt Val;
1868   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1869   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1870       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1871                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1872     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1873                              N1, N0.getOperand(1));
1874     AddToWorkList(C3.getNode());
1875     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1876                        N0.getOperand(0), C3);
1877   }
1878
1879   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1880   // use.
1881   {
1882     SDValue Sh(0,0), Y(0,0);
1883     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1884     if (N0.getOpcode() == ISD::SHL &&
1885         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1886                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1887         N0.getNode()->hasOneUse()) {
1888       Sh = N0; Y = N1;
1889     } else if (N1.getOpcode() == ISD::SHL &&
1890                isa<ConstantSDNode>(N1.getOperand(1)) &&
1891                N1.getNode()->hasOneUse()) {
1892       Sh = N1; Y = N0;
1893     }
1894
1895     if (Sh.getNode()) {
1896       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1897                                 Sh.getOperand(0), Y);
1898       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1899                          Mul, Sh.getOperand(1));
1900     }
1901   }
1902
1903   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1904   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1905       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1906                      isa<ConstantSDNode>(N0.getOperand(1))))
1907     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1908                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1909                                    N0.getOperand(0), N1),
1910                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1911                                    N0.getOperand(1), N1));
1912
1913   // reassociate mul
1914   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1915   if (RMUL.getNode() != 0)
1916     return RMUL;
1917
1918   return SDValue();
1919 }
1920
1921 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1922   SDValue N0 = N->getOperand(0);
1923   SDValue N1 = N->getOperand(1);
1924   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1925   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1926   EVT VT = N->getValueType(0);
1927
1928   // fold vector ops
1929   if (VT.isVector()) {
1930     SDValue FoldedVOp = SimplifyVBinOp(N);
1931     if (FoldedVOp.getNode()) return FoldedVOp;
1932   }
1933
1934   // fold (sdiv c1, c2) -> c1/c2
1935   if (N0C && N1C && !N1C->isNullValue())
1936     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1937   // fold (sdiv X, 1) -> X
1938   if (N1C && N1C->getAPIntValue() == 1LL)
1939     return N0;
1940   // fold (sdiv X, -1) -> 0-X
1941   if (N1C && N1C->isAllOnesValue())
1942     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1943                        DAG.getConstant(0, VT), N0);
1944   // If we know the sign bits of both operands are zero, strength reduce to a
1945   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1946   if (!VT.isVector()) {
1947     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1948       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1949                          N0, N1);
1950   }
1951   // fold (sdiv X, pow2) -> simple ops after legalize
1952   if (N1C && !N1C->isNullValue() &&
1953       (N1C->getAPIntValue().isPowerOf2() ||
1954        (-N1C->getAPIntValue()).isPowerOf2())) {
1955     // If dividing by powers of two is cheap, then don't perform the following
1956     // fold.
1957     if (TLI.isPow2DivCheap())
1958       return SDValue();
1959
1960     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1961
1962     // Splat the sign bit into the register
1963     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1964                               DAG.getConstant(VT.getSizeInBits()-1,
1965                                        getShiftAmountTy(N0.getValueType())));
1966     AddToWorkList(SGN.getNode());
1967
1968     // Add (N0 < 0) ? abs2 - 1 : 0;
1969     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1970                               DAG.getConstant(VT.getSizeInBits() - lg2,
1971                                        getShiftAmountTy(SGN.getValueType())));
1972     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1973     AddToWorkList(SRL.getNode());
1974     AddToWorkList(ADD.getNode());    // Divide by pow2
1975     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1976                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1977
1978     // If we're dividing by a positive value, we're done.  Otherwise, we must
1979     // negate the result.
1980     if (N1C->getAPIntValue().isNonNegative())
1981       return SRA;
1982
1983     AddToWorkList(SRA.getNode());
1984     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1985                        DAG.getConstant(0, VT), SRA);
1986   }
1987
1988   // if integer divide is expensive and we satisfy the requirements, emit an
1989   // alternate sequence.
1990   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1991     SDValue Op = BuildSDIV(N);
1992     if (Op.getNode()) return Op;
1993   }
1994
1995   // undef / X -> 0
1996   if (N0.getOpcode() == ISD::UNDEF)
1997     return DAG.getConstant(0, VT);
1998   // X / undef -> undef
1999   if (N1.getOpcode() == ISD::UNDEF)
2000     return N1;
2001
2002   return SDValue();
2003 }
2004
2005 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2006   SDValue N0 = N->getOperand(0);
2007   SDValue N1 = N->getOperand(1);
2008   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2009   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2010   EVT VT = N->getValueType(0);
2011
2012   // fold vector ops
2013   if (VT.isVector()) {
2014     SDValue FoldedVOp = SimplifyVBinOp(N);
2015     if (FoldedVOp.getNode()) return FoldedVOp;
2016   }
2017
2018   // fold (udiv c1, c2) -> c1/c2
2019   if (N0C && N1C && !N1C->isNullValue())
2020     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2021   // fold (udiv x, (1 << c)) -> x >>u c
2022   if (N1C && N1C->getAPIntValue().isPowerOf2())
2023     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2024                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2025                                        getShiftAmountTy(N0.getValueType())));
2026   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2027   if (N1.getOpcode() == ISD::SHL) {
2028     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2029       if (SHC->getAPIntValue().isPowerOf2()) {
2030         EVT ADDVT = N1.getOperand(1).getValueType();
2031         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2032                                   N1.getOperand(1),
2033                                   DAG.getConstant(SHC->getAPIntValue()
2034                                                                   .logBase2(),
2035                                                   ADDVT));
2036         AddToWorkList(Add.getNode());
2037         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2038       }
2039     }
2040   }
2041   // fold (udiv x, c) -> alternate
2042   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2043     SDValue Op = BuildUDIV(N);
2044     if (Op.getNode()) return Op;
2045   }
2046
2047   // undef / X -> 0
2048   if (N0.getOpcode() == ISD::UNDEF)
2049     return DAG.getConstant(0, VT);
2050   // X / undef -> undef
2051   if (N1.getOpcode() == ISD::UNDEF)
2052     return N1;
2053
2054   return SDValue();
2055 }
2056
2057 SDValue DAGCombiner::visitSREM(SDNode *N) {
2058   SDValue N0 = N->getOperand(0);
2059   SDValue N1 = N->getOperand(1);
2060   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2061   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2062   EVT VT = N->getValueType(0);
2063
2064   // fold (srem c1, c2) -> c1%c2
2065   if (N0C && N1C && !N1C->isNullValue())
2066     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2067   // If we know the sign bits of both operands are zero, strength reduce to a
2068   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2069   if (!VT.isVector()) {
2070     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2071       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2072   }
2073
2074   // If X/C can be simplified by the division-by-constant logic, lower
2075   // X%C to the equivalent of X-X/C*C.
2076   if (N1C && !N1C->isNullValue()) {
2077     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2078     AddToWorkList(Div.getNode());
2079     SDValue OptimizedDiv = combine(Div.getNode());
2080     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2081       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2082                                 OptimizedDiv, N1);
2083       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2084       AddToWorkList(Mul.getNode());
2085       return Sub;
2086     }
2087   }
2088
2089   // undef % X -> 0
2090   if (N0.getOpcode() == ISD::UNDEF)
2091     return DAG.getConstant(0, VT);
2092   // X % undef -> undef
2093   if (N1.getOpcode() == ISD::UNDEF)
2094     return N1;
2095
2096   return SDValue();
2097 }
2098
2099 SDValue DAGCombiner::visitUREM(SDNode *N) {
2100   SDValue N0 = N->getOperand(0);
2101   SDValue N1 = N->getOperand(1);
2102   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2103   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2104   EVT VT = N->getValueType(0);
2105
2106   // fold (urem c1, c2) -> c1%c2
2107   if (N0C && N1C && !N1C->isNullValue())
2108     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2109   // fold (urem x, pow2) -> (and x, pow2-1)
2110   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2111     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2112                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2113   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2114   if (N1.getOpcode() == ISD::SHL) {
2115     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2116       if (SHC->getAPIntValue().isPowerOf2()) {
2117         SDValue Add =
2118           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2119                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2120                                  VT));
2121         AddToWorkList(Add.getNode());
2122         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2123       }
2124     }
2125   }
2126
2127   // If X/C can be simplified by the division-by-constant logic, lower
2128   // X%C to the equivalent of X-X/C*C.
2129   if (N1C && !N1C->isNullValue()) {
2130     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2131     AddToWorkList(Div.getNode());
2132     SDValue OptimizedDiv = combine(Div.getNode());
2133     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2134       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2135                                 OptimizedDiv, N1);
2136       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2137       AddToWorkList(Mul.getNode());
2138       return Sub;
2139     }
2140   }
2141
2142   // undef % X -> 0
2143   if (N0.getOpcode() == ISD::UNDEF)
2144     return DAG.getConstant(0, VT);
2145   // X % undef -> undef
2146   if (N1.getOpcode() == ISD::UNDEF)
2147     return N1;
2148
2149   return SDValue();
2150 }
2151
2152 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2153   SDValue N0 = N->getOperand(0);
2154   SDValue N1 = N->getOperand(1);
2155   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2156   EVT VT = N->getValueType(0);
2157   SDLoc DL(N);
2158
2159   // fold (mulhs x, 0) -> 0
2160   if (N1C && N1C->isNullValue())
2161     return N1;
2162   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2163   if (N1C && N1C->getAPIntValue() == 1)
2164     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2165                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2166                                        getShiftAmountTy(N0.getValueType())));
2167   // fold (mulhs x, undef) -> 0
2168   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2169     return DAG.getConstant(0, VT);
2170
2171   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2172   // plus a shift.
2173   if (VT.isSimple() && !VT.isVector()) {
2174     MVT Simple = VT.getSimpleVT();
2175     unsigned SimpleSize = Simple.getSizeInBits();
2176     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2177     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2178       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2179       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2180       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2181       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2182             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2183       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2184     }
2185   }
2186
2187   return SDValue();
2188 }
2189
2190 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2191   SDValue N0 = N->getOperand(0);
2192   SDValue N1 = N->getOperand(1);
2193   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2194   EVT VT = N->getValueType(0);
2195   SDLoc DL(N);
2196
2197   // fold (mulhu x, 0) -> 0
2198   if (N1C && N1C->isNullValue())
2199     return N1;
2200   // fold (mulhu x, 1) -> 0
2201   if (N1C && N1C->getAPIntValue() == 1)
2202     return DAG.getConstant(0, N0.getValueType());
2203   // fold (mulhu x, undef) -> 0
2204   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2205     return DAG.getConstant(0, VT);
2206
2207   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2208   // plus a shift.
2209   if (VT.isSimple() && !VT.isVector()) {
2210     MVT Simple = VT.getSimpleVT();
2211     unsigned SimpleSize = Simple.getSizeInBits();
2212     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2213     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2214       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2215       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2216       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2217       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2218             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2219       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2220     }
2221   }
2222
2223   return SDValue();
2224 }
2225
2226 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2227 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2228 /// that are being performed. Return true if a simplification was made.
2229 ///
2230 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2231                                                 unsigned HiOp) {
2232   // If the high half is not needed, just compute the low half.
2233   bool HiExists = N->hasAnyUseOfValue(1);
2234   if (!HiExists &&
2235       (!LegalOperations ||
2236        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2237     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2238                               N->op_begin(), N->getNumOperands());
2239     return CombineTo(N, Res, Res);
2240   }
2241
2242   // If the low half is not needed, just compute the high half.
2243   bool LoExists = N->hasAnyUseOfValue(0);
2244   if (!LoExists &&
2245       (!LegalOperations ||
2246        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2247     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2248                               N->op_begin(), N->getNumOperands());
2249     return CombineTo(N, Res, Res);
2250   }
2251
2252   // If both halves are used, return as it is.
2253   if (LoExists && HiExists)
2254     return SDValue();
2255
2256   // If the two computed results can be simplified separately, separate them.
2257   if (LoExists) {
2258     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2259                              N->op_begin(), N->getNumOperands());
2260     AddToWorkList(Lo.getNode());
2261     SDValue LoOpt = combine(Lo.getNode());
2262     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2263         (!LegalOperations ||
2264          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2265       return CombineTo(N, LoOpt, LoOpt);
2266   }
2267
2268   if (HiExists) {
2269     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2270                              N->op_begin(), N->getNumOperands());
2271     AddToWorkList(Hi.getNode());
2272     SDValue HiOpt = combine(Hi.getNode());
2273     if (HiOpt.getNode() && HiOpt != Hi &&
2274         (!LegalOperations ||
2275          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2276       return CombineTo(N, HiOpt, HiOpt);
2277   }
2278
2279   return SDValue();
2280 }
2281
2282 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2283   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2284   if (Res.getNode()) return Res;
2285
2286   EVT VT = N->getValueType(0);
2287   SDLoc DL(N);
2288
2289   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2290   // plus a shift.
2291   if (VT.isSimple() && !VT.isVector()) {
2292     MVT Simple = VT.getSimpleVT();
2293     unsigned SimpleSize = Simple.getSizeInBits();
2294     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2295     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2296       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2297       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2298       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2299       // Compute the high part as N1.
2300       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2301             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2302       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2303       // Compute the low part as N0.
2304       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2305       return CombineTo(N, Lo, Hi);
2306     }
2307   }
2308
2309   return SDValue();
2310 }
2311
2312 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2313   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2314   if (Res.getNode()) return Res;
2315
2316   EVT VT = N->getValueType(0);
2317   SDLoc DL(N);
2318
2319   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2320   // plus a shift.
2321   if (VT.isSimple() && !VT.isVector()) {
2322     MVT Simple = VT.getSimpleVT();
2323     unsigned SimpleSize = Simple.getSizeInBits();
2324     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2325     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2326       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2327       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2328       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2329       // Compute the high part as N1.
2330       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2331             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2332       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2333       // Compute the low part as N0.
2334       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2335       return CombineTo(N, Lo, Hi);
2336     }
2337   }
2338
2339   return SDValue();
2340 }
2341
2342 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2343   // (smulo x, 2) -> (saddo x, x)
2344   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2345     if (C2->getAPIntValue() == 2)
2346       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2347                          N->getOperand(0), N->getOperand(0));
2348
2349   return SDValue();
2350 }
2351
2352 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2353   // (umulo x, 2) -> (uaddo x, x)
2354   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2355     if (C2->getAPIntValue() == 2)
2356       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2357                          N->getOperand(0), N->getOperand(0));
2358
2359   return SDValue();
2360 }
2361
2362 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2363   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2364   if (Res.getNode()) return Res;
2365
2366   return SDValue();
2367 }
2368
2369 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2370   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2371   if (Res.getNode()) return Res;
2372
2373   return SDValue();
2374 }
2375
2376 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2377 /// two operands of the same opcode, try to simplify it.
2378 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2379   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2380   EVT VT = N0.getValueType();
2381   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2382
2383   // Bail early if none of these transforms apply.
2384   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2385
2386   // For each of OP in AND/OR/XOR:
2387   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2388   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2389   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2390   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2391   //
2392   // do not sink logical op inside of a vector extend, since it may combine
2393   // into a vsetcc.
2394   EVT Op0VT = N0.getOperand(0).getValueType();
2395   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2396        N0.getOpcode() == ISD::SIGN_EXTEND ||
2397        // Avoid infinite looping with PromoteIntBinOp.
2398        (N0.getOpcode() == ISD::ANY_EXTEND &&
2399         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2400        (N0.getOpcode() == ISD::TRUNCATE &&
2401         (!TLI.isZExtFree(VT, Op0VT) ||
2402          !TLI.isTruncateFree(Op0VT, VT)) &&
2403         TLI.isTypeLegal(Op0VT))) &&
2404       !VT.isVector() &&
2405       Op0VT == N1.getOperand(0).getValueType() &&
2406       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2407     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2408                                  N0.getOperand(0).getValueType(),
2409                                  N0.getOperand(0), N1.getOperand(0));
2410     AddToWorkList(ORNode.getNode());
2411     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2412   }
2413
2414   // For each of OP in SHL/SRL/SRA/AND...
2415   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2416   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2417   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2418   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2419        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2420       N0.getOperand(1) == N1.getOperand(1)) {
2421     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2422                                  N0.getOperand(0).getValueType(),
2423                                  N0.getOperand(0), N1.getOperand(0));
2424     AddToWorkList(ORNode.getNode());
2425     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2426                        ORNode, N0.getOperand(1));
2427   }
2428
2429   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2430   // Only perform this optimization after type legalization and before
2431   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2432   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2433   // we don't want to undo this promotion.
2434   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2435   // on scalars.
2436   if ((N0.getOpcode() == ISD::BITCAST ||
2437        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2438       Level == AfterLegalizeTypes) {
2439     SDValue In0 = N0.getOperand(0);
2440     SDValue In1 = N1.getOperand(0);
2441     EVT In0Ty = In0.getValueType();
2442     EVT In1Ty = In1.getValueType();
2443     SDLoc DL(N);
2444     // If both incoming values are integers, and the original types are the
2445     // same.
2446     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2447       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2448       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2449       AddToWorkList(Op.getNode());
2450       return BC;
2451     }
2452   }
2453
2454   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2455   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2456   // If both shuffles use the same mask, and both shuffle within a single
2457   // vector, then it is worthwhile to move the swizzle after the operation.
2458   // The type-legalizer generates this pattern when loading illegal
2459   // vector types from memory. In many cases this allows additional shuffle
2460   // optimizations.
2461   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2462       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2463       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2464     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2465     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2466
2467     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2468            "Inputs to shuffles are not the same type");
2469
2470     unsigned NumElts = VT.getVectorNumElements();
2471
2472     // Check that both shuffles use the same mask. The masks are known to be of
2473     // the same length because the result vector type is the same.
2474     bool SameMask = true;
2475     for (unsigned i = 0; i != NumElts; ++i) {
2476       int Idx0 = SVN0->getMaskElt(i);
2477       int Idx1 = SVN1->getMaskElt(i);
2478       if (Idx0 != Idx1) {
2479         SameMask = false;
2480         break;
2481       }
2482     }
2483
2484     if (SameMask) {
2485       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2486                                N0.getOperand(0), N1.getOperand(0));
2487       AddToWorkList(Op.getNode());
2488       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2489                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2490     }
2491   }
2492
2493   return SDValue();
2494 }
2495
2496 SDValue DAGCombiner::visitAND(SDNode *N) {
2497   SDValue N0 = N->getOperand(0);
2498   SDValue N1 = N->getOperand(1);
2499   SDValue LL, LR, RL, RR, CC0, CC1;
2500   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2501   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2502   EVT VT = N1.getValueType();
2503   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2504
2505   // fold vector ops
2506   if (VT.isVector()) {
2507     SDValue FoldedVOp = SimplifyVBinOp(N);
2508     if (FoldedVOp.getNode()) return FoldedVOp;
2509
2510     // fold (and x, 0) -> 0, vector edition
2511     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2512       return N0;
2513     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2514       return N1;
2515
2516     // fold (and x, -1) -> x, vector edition
2517     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2518       return N1;
2519     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2520       return N0;
2521   }
2522
2523   // fold (and x, undef) -> 0
2524   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2525     return DAG.getConstant(0, VT);
2526   // fold (and c1, c2) -> c1&c2
2527   if (N0C && N1C)
2528     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2529   // canonicalize constant to RHS
2530   if (N0C && !N1C)
2531     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2532   // fold (and x, -1) -> x
2533   if (N1C && N1C->isAllOnesValue())
2534     return N0;
2535   // if (and x, c) is known to be zero, return 0
2536   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2537                                    APInt::getAllOnesValue(BitWidth)))
2538     return DAG.getConstant(0, VT);
2539   // reassociate and
2540   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2541   if (RAND.getNode() != 0)
2542     return RAND;
2543   // fold (and (or x, C), D) -> D if (C & D) == D
2544   if (N1C && N0.getOpcode() == ISD::OR)
2545     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2546       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2547         return N1;
2548   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2549   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2550     SDValue N0Op0 = N0.getOperand(0);
2551     APInt Mask = ~N1C->getAPIntValue();
2552     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2553     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2554       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2555                                  N0.getValueType(), N0Op0);
2556
2557       // Replace uses of the AND with uses of the Zero extend node.
2558       CombineTo(N, Zext);
2559
2560       // We actually want to replace all uses of the any_extend with the
2561       // zero_extend, to avoid duplicating things.  This will later cause this
2562       // AND to be folded.
2563       CombineTo(N0.getNode(), Zext);
2564       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2565     }
2566   }
2567   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2568   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2569   // already be zero by virtue of the width of the base type of the load.
2570   //
2571   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2572   // more cases.
2573   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2574        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2575       N0.getOpcode() == ISD::LOAD) {
2576     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2577                                          N0 : N0.getOperand(0) );
2578
2579     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2580     // This can be a pure constant or a vector splat, in which case we treat the
2581     // vector as a scalar and use the splat value.
2582     APInt Constant = APInt::getNullValue(1);
2583     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2584       Constant = C->getAPIntValue();
2585     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2586       APInt SplatValue, SplatUndef;
2587       unsigned SplatBitSize;
2588       bool HasAnyUndefs;
2589       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2590                                              SplatBitSize, HasAnyUndefs);
2591       if (IsSplat) {
2592         // Undef bits can contribute to a possible optimisation if set, so
2593         // set them.
2594         SplatValue |= SplatUndef;
2595
2596         // The splat value may be something like "0x00FFFFFF", which means 0 for
2597         // the first vector value and FF for the rest, repeating. We need a mask
2598         // that will apply equally to all members of the vector, so AND all the
2599         // lanes of the constant together.
2600         EVT VT = Vector->getValueType(0);
2601         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2602
2603         // If the splat value has been compressed to a bitlength lower
2604         // than the size of the vector lane, we need to re-expand it to
2605         // the lane size.
2606         if (BitWidth > SplatBitSize)
2607           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2608                SplatBitSize < BitWidth;
2609                SplatBitSize = SplatBitSize * 2)
2610             SplatValue |= SplatValue.shl(SplatBitSize);
2611
2612         Constant = APInt::getAllOnesValue(BitWidth);
2613         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2614           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2615       }
2616     }
2617
2618     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2619     // actually legal and isn't going to get expanded, else this is a false
2620     // optimisation.
2621     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2622                                                     Load->getMemoryVT());
2623
2624     // Resize the constant to the same size as the original memory access before
2625     // extension. If it is still the AllOnesValue then this AND is completely
2626     // unneeded.
2627     Constant =
2628       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2629
2630     bool B;
2631     switch (Load->getExtensionType()) {
2632     default: B = false; break;
2633     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2634     case ISD::ZEXTLOAD:
2635     case ISD::NON_EXTLOAD: B = true; break;
2636     }
2637
2638     if (B && Constant.isAllOnesValue()) {
2639       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2640       // preserve semantics once we get rid of the AND.
2641       SDValue NewLoad(Load, 0);
2642       if (Load->getExtensionType() == ISD::EXTLOAD) {
2643         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2644                               Load->getValueType(0), SDLoc(Load),
2645                               Load->getChain(), Load->getBasePtr(),
2646                               Load->getOffset(), Load->getMemoryVT(),
2647                               Load->getMemOperand());
2648         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2649         if (Load->getNumValues() == 3) {
2650           // PRE/POST_INC loads have 3 values.
2651           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2652                            NewLoad.getValue(2) };
2653           CombineTo(Load, To, 3, true);
2654         } else {
2655           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2656         }
2657       }
2658
2659       // Fold the AND away, taking care not to fold to the old load node if we
2660       // replaced it.
2661       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2662
2663       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2664     }
2665   }
2666   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2667   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2668     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2669     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2670
2671     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2672         LL.getValueType().isInteger()) {
2673       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2674       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2675         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2676                                      LR.getValueType(), LL, RL);
2677         AddToWorkList(ORNode.getNode());
2678         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2679       }
2680       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2681       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2682         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2683                                       LR.getValueType(), LL, RL);
2684         AddToWorkList(ANDNode.getNode());
2685         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2686       }
2687       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2688       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2689         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2690                                      LR.getValueType(), LL, RL);
2691         AddToWorkList(ORNode.getNode());
2692         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2693       }
2694     }
2695     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2696     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2697         Op0 == Op1 && LL.getValueType().isInteger() &&
2698       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2699                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2700                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2701                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2702       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2703                                     LL, DAG.getConstant(1, LL.getValueType()));
2704       AddToWorkList(ADDNode.getNode());
2705       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2706                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2707     }
2708     // canonicalize equivalent to ll == rl
2709     if (LL == RR && LR == RL) {
2710       Op1 = ISD::getSetCCSwappedOperands(Op1);
2711       std::swap(RL, RR);
2712     }
2713     if (LL == RL && LR == RR) {
2714       bool isInteger = LL.getValueType().isInteger();
2715       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2716       if (Result != ISD::SETCC_INVALID &&
2717           (!LegalOperations ||
2718            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2719             TLI.isOperationLegal(ISD::SETCC,
2720                             getSetCCResultType(N0.getSimpleValueType())))))
2721         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2722                             LL, LR, Result);
2723     }
2724   }
2725
2726   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2727   if (N0.getOpcode() == N1.getOpcode()) {
2728     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2729     if (Tmp.getNode()) return Tmp;
2730   }
2731
2732   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2733   // fold (and (sra)) -> (and (srl)) when possible.
2734   if (!VT.isVector() &&
2735       SimplifyDemandedBits(SDValue(N, 0)))
2736     return SDValue(N, 0);
2737
2738   // fold (zext_inreg (extload x)) -> (zextload x)
2739   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2740     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2741     EVT MemVT = LN0->getMemoryVT();
2742     // If we zero all the possible extended bits, then we can turn this into
2743     // a zextload if we are running before legalize or the operation is legal.
2744     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2745     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2746                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2747         ((!LegalOperations && !LN0->isVolatile()) ||
2748          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2749       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2750                                        LN0->getChain(), LN0->getBasePtr(),
2751                                        MemVT, LN0->getMemOperand());
2752       AddToWorkList(N);
2753       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2754       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2755     }
2756   }
2757   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2758   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2759       N0.hasOneUse()) {
2760     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2761     EVT MemVT = LN0->getMemoryVT();
2762     // If we zero all the possible extended bits, then we can turn this into
2763     // a zextload if we are running before legalize or the operation is legal.
2764     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2765     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2766                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2767         ((!LegalOperations && !LN0->isVolatile()) ||
2768          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2769       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2770                                        LN0->getChain(), LN0->getBasePtr(),
2771                                        MemVT, LN0->getMemOperand());
2772       AddToWorkList(N);
2773       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2774       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2775     }
2776   }
2777
2778   // fold (and (load x), 255) -> (zextload x, i8)
2779   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2780   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2781   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2782               (N0.getOpcode() == ISD::ANY_EXTEND &&
2783                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2784     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2785     LoadSDNode *LN0 = HasAnyExt
2786       ? cast<LoadSDNode>(N0.getOperand(0))
2787       : cast<LoadSDNode>(N0);
2788     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2789         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2790       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2791       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2792         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2793         EVT LoadedVT = LN0->getMemoryVT();
2794
2795         if (ExtVT == LoadedVT &&
2796             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2797           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2798
2799           SDValue NewLoad =
2800             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2801                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2802                            LN0->getMemOperand());
2803           AddToWorkList(N);
2804           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2805           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2806         }
2807
2808         // Do not change the width of a volatile load.
2809         // Do not generate loads of non-round integer types since these can
2810         // be expensive (and would be wrong if the type is not byte sized).
2811         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2812             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813           EVT PtrType = LN0->getOperand(1).getValueType();
2814
2815           unsigned Alignment = LN0->getAlignment();
2816           SDValue NewPtr = LN0->getBasePtr();
2817
2818           // For big endian targets, we need to add an offset to the pointer
2819           // to load the correct bytes.  For little endian systems, we merely
2820           // need to read fewer bytes from the same pointer.
2821           if (TLI.isBigEndian()) {
2822             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2823             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2824             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2825             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2826                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2827             Alignment = MinAlign(Alignment, PtrOff);
2828           }
2829
2830           AddToWorkList(NewPtr.getNode());
2831
2832           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2833           SDValue Load =
2834             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2835                            LN0->getChain(), NewPtr,
2836                            LN0->getPointerInfo(),
2837                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2838                            Alignment, LN0->getTBAAInfo());
2839           AddToWorkList(N);
2840           CombineTo(LN0, Load, Load.getValue(1));
2841           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2842         }
2843       }
2844     }
2845   }
2846
2847   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2848       VT.getSizeInBits() <= 64) {
2849     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2850       APInt ADDC = ADDI->getAPIntValue();
2851       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2852         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2853         // immediate for an add, but it is legal if its top c2 bits are set,
2854         // transform the ADD so the immediate doesn't need to be materialized
2855         // in a register.
2856         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2857           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2858                                              SRLI->getZExtValue());
2859           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2860             ADDC |= Mask;
2861             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2862               SDValue NewAdd =
2863                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2864                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2865               CombineTo(N0.getNode(), NewAdd);
2866               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2867             }
2868           }
2869         }
2870       }
2871     }
2872   }
2873
2874   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2875   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2876     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2877                                        N0.getOperand(1), false);
2878     if (BSwap.getNode())
2879       return BSwap;
2880   }
2881
2882   return SDValue();
2883 }
2884
2885 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2886 ///
2887 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2888                                         bool DemandHighBits) {
2889   if (!LegalOperations)
2890     return SDValue();
2891
2892   EVT VT = N->getValueType(0);
2893   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2894     return SDValue();
2895   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2896     return SDValue();
2897
2898   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2899   bool LookPassAnd0 = false;
2900   bool LookPassAnd1 = false;
2901   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2902       std::swap(N0, N1);
2903   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2904       std::swap(N0, N1);
2905   if (N0.getOpcode() == ISD::AND) {
2906     if (!N0.getNode()->hasOneUse())
2907       return SDValue();
2908     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2909     if (!N01C || N01C->getZExtValue() != 0xFF00)
2910       return SDValue();
2911     N0 = N0.getOperand(0);
2912     LookPassAnd0 = true;
2913   }
2914
2915   if (N1.getOpcode() == ISD::AND) {
2916     if (!N1.getNode()->hasOneUse())
2917       return SDValue();
2918     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2919     if (!N11C || N11C->getZExtValue() != 0xFF)
2920       return SDValue();
2921     N1 = N1.getOperand(0);
2922     LookPassAnd1 = true;
2923   }
2924
2925   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2926     std::swap(N0, N1);
2927   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2928     return SDValue();
2929   if (!N0.getNode()->hasOneUse() ||
2930       !N1.getNode()->hasOneUse())
2931     return SDValue();
2932
2933   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2934   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2935   if (!N01C || !N11C)
2936     return SDValue();
2937   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2938     return SDValue();
2939
2940   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2941   SDValue N00 = N0->getOperand(0);
2942   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2943     if (!N00.getNode()->hasOneUse())
2944       return SDValue();
2945     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2946     if (!N001C || N001C->getZExtValue() != 0xFF)
2947       return SDValue();
2948     N00 = N00.getOperand(0);
2949     LookPassAnd0 = true;
2950   }
2951
2952   SDValue N10 = N1->getOperand(0);
2953   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2954     if (!N10.getNode()->hasOneUse())
2955       return SDValue();
2956     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2957     if (!N101C || N101C->getZExtValue() != 0xFF00)
2958       return SDValue();
2959     N10 = N10.getOperand(0);
2960     LookPassAnd1 = true;
2961   }
2962
2963   if (N00 != N10)
2964     return SDValue();
2965
2966   // Make sure everything beyond the low halfword gets set to zero since the SRL
2967   // 16 will clear the top bits.
2968   unsigned OpSizeInBits = VT.getSizeInBits();
2969   if (DemandHighBits && OpSizeInBits > 16) {
2970     // If the left-shift isn't masked out then the only way this is a bswap is
2971     // if all bits beyond the low 8 are 0. In that case the entire pattern
2972     // reduces to a left shift anyway: leave it for other parts of the combiner.
2973     if (!LookPassAnd0)
2974       return SDValue();
2975
2976     // However, if the right shift isn't masked out then it might be because
2977     // it's not needed. See if we can spot that too.
2978     if (!LookPassAnd1 &&
2979         !DAG.MaskedValueIsZero(
2980             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2981       return SDValue();
2982   }
2983
2984   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2985   if (OpSizeInBits > 16)
2986     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2987                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2988   return Res;
2989 }
2990
2991 /// isBSwapHWordElement - Return true if the specified node is an element
2992 /// that makes up a 32-bit packed halfword byteswap. i.e.
2993 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2994 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2995   if (!N.getNode()->hasOneUse())
2996     return false;
2997
2998   unsigned Opc = N.getOpcode();
2999   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3000     return false;
3001
3002   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3003   if (!N1C)
3004     return false;
3005
3006   unsigned Num;
3007   switch (N1C->getZExtValue()) {
3008   default:
3009     return false;
3010   case 0xFF:       Num = 0; break;
3011   case 0xFF00:     Num = 1; break;
3012   case 0xFF0000:   Num = 2; break;
3013   case 0xFF000000: Num = 3; break;
3014   }
3015
3016   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3017   SDValue N0 = N.getOperand(0);
3018   if (Opc == ISD::AND) {
3019     if (Num == 0 || Num == 2) {
3020       // (x >> 8) & 0xff
3021       // (x >> 8) & 0xff0000
3022       if (N0.getOpcode() != ISD::SRL)
3023         return false;
3024       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3025       if (!C || C->getZExtValue() != 8)
3026         return false;
3027     } else {
3028       // (x << 8) & 0xff00
3029       // (x << 8) & 0xff000000
3030       if (N0.getOpcode() != ISD::SHL)
3031         return false;
3032       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3033       if (!C || C->getZExtValue() != 8)
3034         return false;
3035     }
3036   } else if (Opc == ISD::SHL) {
3037     // (x & 0xff) << 8
3038     // (x & 0xff0000) << 8
3039     if (Num != 0 && Num != 2)
3040       return false;
3041     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3042     if (!C || C->getZExtValue() != 8)
3043       return false;
3044   } else { // Opc == ISD::SRL
3045     // (x & 0xff00) >> 8
3046     // (x & 0xff000000) >> 8
3047     if (Num != 1 && Num != 3)
3048       return false;
3049     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3050     if (!C || C->getZExtValue() != 8)
3051       return false;
3052   }
3053
3054   if (Parts[Num])
3055     return false;
3056
3057   Parts[Num] = N0.getOperand(0).getNode();
3058   return true;
3059 }
3060
3061 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3062 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3063 /// => (rotl (bswap x), 16)
3064 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3065   if (!LegalOperations)
3066     return SDValue();
3067
3068   EVT VT = N->getValueType(0);
3069   if (VT != MVT::i32)
3070     return SDValue();
3071   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3072     return SDValue();
3073
3074   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3075   // Look for either
3076   // (or (or (and), (and)), (or (and), (and)))
3077   // (or (or (or (and), (and)), (and)), (and))
3078   if (N0.getOpcode() != ISD::OR)
3079     return SDValue();
3080   SDValue N00 = N0.getOperand(0);
3081   SDValue N01 = N0.getOperand(1);
3082
3083   if (N1.getOpcode() == ISD::OR &&
3084       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3085     // (or (or (and), (and)), (or (and), (and)))
3086     SDValue N000 = N00.getOperand(0);
3087     if (!isBSwapHWordElement(N000, Parts))
3088       return SDValue();
3089
3090     SDValue N001 = N00.getOperand(1);
3091     if (!isBSwapHWordElement(N001, Parts))
3092       return SDValue();
3093     SDValue N010 = N01.getOperand(0);
3094     if (!isBSwapHWordElement(N010, Parts))
3095       return SDValue();
3096     SDValue N011 = N01.getOperand(1);
3097     if (!isBSwapHWordElement(N011, Parts))
3098       return SDValue();
3099   } else {
3100     // (or (or (or (and), (and)), (and)), (and))
3101     if (!isBSwapHWordElement(N1, Parts))
3102       return SDValue();
3103     if (!isBSwapHWordElement(N01, Parts))
3104       return SDValue();
3105     if (N00.getOpcode() != ISD::OR)
3106       return SDValue();
3107     SDValue N000 = N00.getOperand(0);
3108     if (!isBSwapHWordElement(N000, Parts))
3109       return SDValue();
3110     SDValue N001 = N00.getOperand(1);
3111     if (!isBSwapHWordElement(N001, Parts))
3112       return SDValue();
3113   }
3114
3115   // Make sure the parts are all coming from the same node.
3116   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3117     return SDValue();
3118
3119   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3120                               SDValue(Parts[0],0));
3121
3122   // Result of the bswap should be rotated by 16. If it's not legal, then
3123   // do  (x << 16) | (x >> 16).
3124   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3125   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3126     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3127   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3128     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3129   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3130                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3131                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3132 }
3133
3134 SDValue DAGCombiner::visitOR(SDNode *N) {
3135   SDValue N0 = N->getOperand(0);
3136   SDValue N1 = N->getOperand(1);
3137   SDValue LL, LR, RL, RR, CC0, CC1;
3138   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3139   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3140   EVT VT = N1.getValueType();
3141
3142   // fold vector ops
3143   if (VT.isVector()) {
3144     SDValue FoldedVOp = SimplifyVBinOp(N);
3145     if (FoldedVOp.getNode()) return FoldedVOp;
3146
3147     // fold (or x, 0) -> x, vector edition
3148     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3149       return N1;
3150     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3151       return N0;
3152
3153     // fold (or x, -1) -> -1, vector edition
3154     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3155       return N0;
3156     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3157       return N1;
3158   }
3159
3160   // fold (or x, undef) -> -1
3161   if (!LegalOperations &&
3162       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3163     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3164     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3165   }
3166   // fold (or c1, c2) -> c1|c2
3167   if (N0C && N1C)
3168     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3169   // canonicalize constant to RHS
3170   if (N0C && !N1C)
3171     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3172   // fold (or x, 0) -> x
3173   if (N1C && N1C->isNullValue())
3174     return N0;
3175   // fold (or x, -1) -> -1
3176   if (N1C && N1C->isAllOnesValue())
3177     return N1;
3178   // fold (or x, c) -> c iff (x & ~c) == 0
3179   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3180     return N1;
3181
3182   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3183   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3184   if (BSwap.getNode() != 0)
3185     return BSwap;
3186   BSwap = MatchBSwapHWordLow(N, N0, N1);
3187   if (BSwap.getNode() != 0)
3188     return BSwap;
3189
3190   // reassociate or
3191   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3192   if (ROR.getNode() != 0)
3193     return ROR;
3194   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3195   // iff (c1 & c2) == 0.
3196   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3197              isa<ConstantSDNode>(N0.getOperand(1))) {
3198     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3199     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3200       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3201                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3202                                      N0.getOperand(0), N1),
3203                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3204   }
3205   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3206   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3207     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3208     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3209
3210     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3211         LL.getValueType().isInteger()) {
3212       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3213       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3214       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3215           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3216         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3217                                      LR.getValueType(), LL, RL);
3218         AddToWorkList(ORNode.getNode());
3219         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3220       }
3221       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3222       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3223       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3224           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3225         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3226                                       LR.getValueType(), LL, RL);
3227         AddToWorkList(ANDNode.getNode());
3228         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3229       }
3230     }
3231     // canonicalize equivalent to ll == rl
3232     if (LL == RR && LR == RL) {
3233       Op1 = ISD::getSetCCSwappedOperands(Op1);
3234       std::swap(RL, RR);
3235     }
3236     if (LL == RL && LR == RR) {
3237       bool isInteger = LL.getValueType().isInteger();
3238       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3239       if (Result != ISD::SETCC_INVALID &&
3240           (!LegalOperations ||
3241            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3242             TLI.isOperationLegal(ISD::SETCC,
3243               getSetCCResultType(N0.getValueType())))))
3244         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3245                             LL, LR, Result);
3246     }
3247   }
3248
3249   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3250   if (N0.getOpcode() == N1.getOpcode()) {
3251     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3252     if (Tmp.getNode()) return Tmp;
3253   }
3254
3255   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3256   if (N0.getOpcode() == ISD::AND &&
3257       N1.getOpcode() == ISD::AND &&
3258       N0.getOperand(1).getOpcode() == ISD::Constant &&
3259       N1.getOperand(1).getOpcode() == ISD::Constant &&
3260       // Don't increase # computations.
3261       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3262     // We can only do this xform if we know that bits from X that are set in C2
3263     // but not in C1 are already zero.  Likewise for Y.
3264     const APInt &LHSMask =
3265       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3266     const APInt &RHSMask =
3267       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3268
3269     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3270         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3271       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3272                               N0.getOperand(0), N1.getOperand(0));
3273       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3274                          DAG.getConstant(LHSMask | RHSMask, VT));
3275     }
3276   }
3277
3278   // See if this is some rotate idiom.
3279   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3280     return SDValue(Rot, 0);
3281
3282   // Simplify the operands using demanded-bits information.
3283   if (!VT.isVector() &&
3284       SimplifyDemandedBits(SDValue(N, 0)))
3285     return SDValue(N, 0);
3286
3287   return SDValue();
3288 }
3289
3290 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3291 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3292   if (Op.getOpcode() == ISD::AND) {
3293     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3294       Mask = Op.getOperand(1);
3295       Op = Op.getOperand(0);
3296     } else {
3297       return false;
3298     }
3299   }
3300
3301   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3302     Shift = Op;
3303     return true;
3304   }
3305
3306   return false;
3307 }
3308
3309 // Return true if we can prove that Neg == OpSize - Pos.  This means that
3310 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3311 //
3312 //     (or (shift1 X, Neg), (shift2 X, Pos))
3313 //
3314 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3315 // shift1 by Neg.  Note that the (or ...) then invokes undefined behavior
3316 // if Pos == 0 (and consequently Neg == OpSize).
3317 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3318   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3319   if (Neg.getOpcode() != ISD::SUB)
3320     return 0;
3321   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3322   if (!NegC)
3323     return 0;
3324   SDValue NegOp1 = Neg.getOperand(1);
3325
3326   // The condition we need to prove is now NegC - NegOp1 == OpSize - Pos.
3327   // Check whether the terms match directly.
3328   if (Pos == NegOp1)
3329     return NegC->getAPIntValue() == OpSize;
3330
3331   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3332   // Then the condition we want to prove becomes:
3333   //   NegC - NegOp1 == OpSize - (NegOp1 + PosC)
3334   //            NegC == OpSize - PosC
3335   //
3336   // Because NegC and PosC are APInts, this is easier to test as:
3337   //          OpSize == NegC + PosC
3338   if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3339     ConstantSDNode *PosC = dyn_cast<ConstantSDNode>(Pos.getOperand(1));
3340     return PosC && OpSize == NegC->getAPIntValue() + PosC->getAPIntValue();
3341   }
3342
3343   return false;
3344 }
3345
3346 // A subroutine of MatchRotate used once we have found an OR of two opposite
3347 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3348 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3349 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3350 // Neg with outer conversions stripped away.
3351 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3352                                        SDValue Neg, SDValue InnerPos,
3353                                        SDValue InnerNeg, unsigned PosOpcode,
3354                                        unsigned NegOpcode, SDLoc DL) {
3355   // fold (or (shl x, (*ext y)),
3356   //          (srl x, (*ext (sub 32, y)))) ->
3357   //   (rotl x, y) or (rotr x, (sub 32, y))
3358   //
3359   // fold (or (shl x, (*ext (sub 32, y))),
3360   //          (srl x, (*ext y))) ->
3361   //   (rotr x, y) or (rotl x, (sub 32, y))
3362   EVT VT = Shifted.getValueType();
3363   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3364     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3365     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3366                        HasPos ? Pos : Neg).getNode();
3367   }
3368
3369   // fold (or (shl (*ext x), (*ext y)),
3370   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3371   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3372   //
3373   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3374   //          (srl (*ext x), (*ext y))) ->
3375   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3376   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3377       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3378     SDValue InnerShifted = Shifted.getOperand(0);
3379     EVT InnerVT = InnerShifted.getValueType();
3380     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3381     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3382       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3383         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3384                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3385         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3386       }
3387     }
3388   }
3389
3390   return 0;
3391 }
3392
3393 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3394 // idioms for rotate, and if the target supports rotation instructions, generate
3395 // a rot[lr].
3396 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3397   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3398   EVT VT = LHS.getValueType();
3399   if (!TLI.isTypeLegal(VT)) return 0;
3400
3401   // The target must have at least one rotate flavor.
3402   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3403   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3404   if (!HasROTL && !HasROTR) return 0;
3405
3406   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3407   SDValue LHSShift;   // The shift.
3408   SDValue LHSMask;    // AND value if any.
3409   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3410     return 0; // Not part of a rotate.
3411
3412   SDValue RHSShift;   // The shift.
3413   SDValue RHSMask;    // AND value if any.
3414   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3415     return 0; // Not part of a rotate.
3416
3417   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3418     return 0;   // Not shifting the same value.
3419
3420   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3421     return 0;   // Shifts must disagree.
3422
3423   // Canonicalize shl to left side in a shl/srl pair.
3424   if (RHSShift.getOpcode() == ISD::SHL) {
3425     std::swap(LHS, RHS);
3426     std::swap(LHSShift, RHSShift);
3427     std::swap(LHSMask , RHSMask );
3428   }
3429
3430   unsigned OpSizeInBits = VT.getSizeInBits();
3431   SDValue LHSShiftArg = LHSShift.getOperand(0);
3432   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3433   SDValue RHSShiftArg = RHSShift.getOperand(0);
3434   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3435
3436   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3437   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3438   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3439       RHSShiftAmt.getOpcode() == ISD::Constant) {
3440     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3441     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3442     if ((LShVal + RShVal) != OpSizeInBits)
3443       return 0;
3444
3445     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3446                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3447
3448     // If there is an AND of either shifted operand, apply it to the result.
3449     if (LHSMask.getNode() || RHSMask.getNode()) {
3450       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3451
3452       if (LHSMask.getNode()) {
3453         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3454         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3455       }
3456       if (RHSMask.getNode()) {
3457         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3458         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3459       }
3460
3461       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3462     }
3463
3464     return Rot.getNode();
3465   }
3466
3467   // If there is a mask here, and we have a variable shift, we can't be sure
3468   // that we're masking out the right stuff.
3469   if (LHSMask.getNode() || RHSMask.getNode())
3470     return 0;
3471
3472   // If the shift amount is sign/zext/any-extended just peel it off.
3473   SDValue LExtOp0 = LHSShiftAmt;
3474   SDValue RExtOp0 = RHSShiftAmt;
3475   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3476        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3477        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3478        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3479       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3480        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3481        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3482        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3483     LExtOp0 = LHSShiftAmt.getOperand(0);
3484     RExtOp0 = RHSShiftAmt.getOperand(0);
3485   }
3486
3487   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3488                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3489   if (TryL)
3490     return TryL;
3491
3492   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3493                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3494   if (TryR)
3495     return TryR;
3496
3497   return 0;
3498 }
3499
3500 SDValue DAGCombiner::visitXOR(SDNode *N) {
3501   SDValue N0 = N->getOperand(0);
3502   SDValue N1 = N->getOperand(1);
3503   SDValue LHS, RHS, CC;
3504   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3505   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3506   EVT VT = N0.getValueType();
3507
3508   // fold vector ops
3509   if (VT.isVector()) {
3510     SDValue FoldedVOp = SimplifyVBinOp(N);
3511     if (FoldedVOp.getNode()) return FoldedVOp;
3512
3513     // fold (xor x, 0) -> x, vector edition
3514     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3515       return N1;
3516     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3517       return N0;
3518   }
3519
3520   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3521   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3522     return DAG.getConstant(0, VT);
3523   // fold (xor x, undef) -> undef
3524   if (N0.getOpcode() == ISD::UNDEF)
3525     return N0;
3526   if (N1.getOpcode() == ISD::UNDEF)
3527     return N1;
3528   // fold (xor c1, c2) -> c1^c2
3529   if (N0C && N1C)
3530     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3531   // canonicalize constant to RHS
3532   if (N0C && !N1C)
3533     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3534   // fold (xor x, 0) -> x
3535   if (N1C && N1C->isNullValue())
3536     return N0;
3537   // reassociate xor
3538   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3539   if (RXOR.getNode() != 0)
3540     return RXOR;
3541
3542   // fold !(x cc y) -> (x !cc y)
3543   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3544     bool isInt = LHS.getValueType().isInteger();
3545     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3546                                                isInt);
3547
3548     if (!LegalOperations ||
3549         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3550       switch (N0.getOpcode()) {
3551       default:
3552         llvm_unreachable("Unhandled SetCC Equivalent!");
3553       case ISD::SETCC:
3554         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3555       case ISD::SELECT_CC:
3556         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3557                                N0.getOperand(3), NotCC);
3558       }
3559     }
3560   }
3561
3562   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3563   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3564       N0.getNode()->hasOneUse() &&
3565       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3566     SDValue V = N0.getOperand(0);
3567     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3568                     DAG.getConstant(1, V.getValueType()));
3569     AddToWorkList(V.getNode());
3570     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3571   }
3572
3573   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3574   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3575       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3576     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3577     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3578       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3579       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3580       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3581       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3582       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3583     }
3584   }
3585   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3586   if (N1C && N1C->isAllOnesValue() &&
3587       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3588     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3589     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3590       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3591       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3592       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3593       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3594       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3595     }
3596   }
3597   // fold (xor (and x, y), y) -> (and (not x), y)
3598   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3599       N0->getOperand(1) == N1) {
3600     SDValue X = N0->getOperand(0);
3601     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3602     AddToWorkList(NotX.getNode());
3603     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3604   }
3605   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3606   if (N1C && N0.getOpcode() == ISD::XOR) {
3607     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3608     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3609     if (N00C)
3610       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3611                          DAG.getConstant(N1C->getAPIntValue() ^
3612                                          N00C->getAPIntValue(), VT));
3613     if (N01C)
3614       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3615                          DAG.getConstant(N1C->getAPIntValue() ^
3616                                          N01C->getAPIntValue(), VT));
3617   }
3618   // fold (xor x, x) -> 0
3619   if (N0 == N1)
3620     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3621
3622   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3623   if (N0.getOpcode() == N1.getOpcode()) {
3624     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3625     if (Tmp.getNode()) return Tmp;
3626   }
3627
3628   // Simplify the expression using non-local knowledge.
3629   if (!VT.isVector() &&
3630       SimplifyDemandedBits(SDValue(N, 0)))
3631     return SDValue(N, 0);
3632
3633   return SDValue();
3634 }
3635
3636 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3637 /// the shift amount is a constant.
3638 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3639   SDNode *LHS = N->getOperand(0).getNode();
3640   if (!LHS->hasOneUse()) return SDValue();
3641
3642   // We want to pull some binops through shifts, so that we have (and (shift))
3643   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3644   // thing happens with address calculations, so it's important to canonicalize
3645   // it.
3646   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3647
3648   switch (LHS->getOpcode()) {
3649   default: return SDValue();
3650   case ISD::OR:
3651   case ISD::XOR:
3652     HighBitSet = false; // We can only transform sra if the high bit is clear.
3653     break;
3654   case ISD::AND:
3655     HighBitSet = true;  // We can only transform sra if the high bit is set.
3656     break;
3657   case ISD::ADD:
3658     if (N->getOpcode() != ISD::SHL)
3659       return SDValue(); // only shl(add) not sr[al](add).
3660     HighBitSet = false; // We can only transform sra if the high bit is clear.
3661     break;
3662   }
3663
3664   // We require the RHS of the binop to be a constant as well.
3665   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3666   if (!BinOpCst) return SDValue();
3667
3668   // FIXME: disable this unless the input to the binop is a shift by a constant.
3669   // If it is not a shift, it pessimizes some common cases like:
3670   //
3671   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3672   //    int bar(int *X, int i) { return X[i & 255]; }
3673   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3674   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3675        BinOpLHSVal->getOpcode() != ISD::SRA &&
3676        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3677       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3678     return SDValue();
3679
3680   EVT VT = N->getValueType(0);
3681
3682   // If this is a signed shift right, and the high bit is modified by the
3683   // logical operation, do not perform the transformation. The highBitSet
3684   // boolean indicates the value of the high bit of the constant which would
3685   // cause it to be modified for this operation.
3686   if (N->getOpcode() == ISD::SRA) {
3687     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3688     if (BinOpRHSSignSet != HighBitSet)
3689       return SDValue();
3690   }
3691
3692   // Fold the constants, shifting the binop RHS by the shift amount.
3693   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3694                                N->getValueType(0),
3695                                LHS->getOperand(1), N->getOperand(1));
3696
3697   // Create the new shift.
3698   SDValue NewShift = DAG.getNode(N->getOpcode(),
3699                                  SDLoc(LHS->getOperand(0)),
3700                                  VT, LHS->getOperand(0), N->getOperand(1));
3701
3702   // Create the new binop.
3703   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3704 }
3705
3706 SDValue DAGCombiner::visitSHL(SDNode *N) {
3707   SDValue N0 = N->getOperand(0);
3708   SDValue N1 = N->getOperand(1);
3709   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3710   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3711   EVT VT = N0.getValueType();
3712   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3713
3714   // fold vector ops
3715   if (VT.isVector()) {
3716     SDValue FoldedVOp = SimplifyVBinOp(N);
3717     if (FoldedVOp.getNode()) return FoldedVOp;
3718   }
3719
3720   // fold (shl c1, c2) -> c1<<c2
3721   if (N0C && N1C)
3722     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3723   // fold (shl 0, x) -> 0
3724   if (N0C && N0C->isNullValue())
3725     return N0;
3726   // fold (shl x, c >= size(x)) -> undef
3727   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3728     return DAG.getUNDEF(VT);
3729   // fold (shl x, 0) -> x
3730   if (N1C && N1C->isNullValue())
3731     return N0;
3732   // fold (shl undef, x) -> 0
3733   if (N0.getOpcode() == ISD::UNDEF)
3734     return DAG.getConstant(0, VT);
3735   // if (shl x, c) is known to be zero, return 0
3736   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3737                             APInt::getAllOnesValue(OpSizeInBits)))
3738     return DAG.getConstant(0, VT);
3739   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3740   if (N1.getOpcode() == ISD::TRUNCATE &&
3741       N1.getOperand(0).getOpcode() == ISD::AND &&
3742       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3743     SDValue N101 = N1.getOperand(0).getOperand(1);
3744     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3745       EVT TruncVT = N1.getValueType();
3746       SDValue N100 = N1.getOperand(0).getOperand(0);
3747       APInt TruncC = N101C->getAPIntValue();
3748       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3749       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3750                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3751                                      DAG.getNode(ISD::TRUNCATE,
3752                                                  SDLoc(N),
3753                                                  TruncVT, N100),
3754                                      DAG.getConstant(TruncC, TruncVT)));
3755     }
3756   }
3757
3758   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3759     return SDValue(N, 0);
3760
3761   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3762   if (N1C && N0.getOpcode() == ISD::SHL &&
3763       N0.getOperand(1).getOpcode() == ISD::Constant) {
3764     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3765     uint64_t c2 = N1C->getZExtValue();
3766     if (c1 + c2 >= OpSizeInBits)
3767       return DAG.getConstant(0, VT);
3768     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3769                        DAG.getConstant(c1 + c2, N1.getValueType()));
3770   }
3771
3772   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3773   // For this to be valid, the second form must not preserve any of the bits
3774   // that are shifted out by the inner shift in the first form.  This means
3775   // the outer shift size must be >= the number of bits added by the ext.
3776   // As a corollary, we don't care what kind of ext it is.
3777   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3778               N0.getOpcode() == ISD::ANY_EXTEND ||
3779               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3780       N0.getOperand(0).getOpcode() == ISD::SHL &&
3781       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3782     uint64_t c1 =
3783       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3784     uint64_t c2 = N1C->getZExtValue();
3785     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3786     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3787     if (c2 >= OpSizeInBits - InnerShiftSize) {
3788       if (c1 + c2 >= OpSizeInBits)
3789         return DAG.getConstant(0, VT);
3790       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3791                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3792                                      N0.getOperand(0)->getOperand(0)),
3793                          DAG.getConstant(c1 + c2, N1.getValueType()));
3794     }
3795   }
3796
3797   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3798   // Only fold this if the inner zext has no other uses to avoid increasing
3799   // the total number of instructions.
3800   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3801       N0.getOperand(0).getOpcode() == ISD::SRL &&
3802       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3803     uint64_t c1 =
3804       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3805     if (c1 < VT.getSizeInBits()) {
3806       uint64_t c2 = N1C->getZExtValue();
3807       if (c1 == c2) {
3808         SDValue NewOp0 = N0.getOperand(0);
3809         EVT CountVT = NewOp0.getOperand(1).getValueType();
3810         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3811                                      NewOp0, DAG.getConstant(c2, CountVT));
3812         AddToWorkList(NewSHL.getNode());
3813         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3814       }
3815     }
3816   }
3817
3818   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3819   //                               (and (srl x, (sub c1, c2), MASK)
3820   // Only fold this if the inner shift has no other uses -- if it does, folding
3821   // this will increase the total number of instructions.
3822   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3823       N0.getOperand(1).getOpcode() == ISD::Constant) {
3824     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3825     if (c1 < VT.getSizeInBits()) {
3826       uint64_t c2 = N1C->getZExtValue();
3827       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3828                                          VT.getSizeInBits() - c1);
3829       SDValue Shift;
3830       if (c2 > c1) {
3831         Mask = Mask.shl(c2-c1);
3832         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3833                             DAG.getConstant(c2-c1, N1.getValueType()));
3834       } else {
3835         Mask = Mask.lshr(c1-c2);
3836         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3837                             DAG.getConstant(c1-c2, N1.getValueType()));
3838       }
3839       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3840                          DAG.getConstant(Mask, VT));
3841     }
3842   }
3843   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3844   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3845     SDValue HiBitsMask =
3846       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3847                                             VT.getSizeInBits() -
3848                                               N1C->getZExtValue()),
3849                       VT);
3850     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3851                        HiBitsMask);
3852   }
3853
3854   if (N1C) {
3855     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3856     if (NewSHL.getNode())
3857       return NewSHL;
3858   }
3859
3860   return SDValue();
3861 }
3862
3863 SDValue DAGCombiner::visitSRA(SDNode *N) {
3864   SDValue N0 = N->getOperand(0);
3865   SDValue N1 = N->getOperand(1);
3866   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3867   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3868   EVT VT = N0.getValueType();
3869   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3870
3871   // fold vector ops
3872   if (VT.isVector()) {
3873     SDValue FoldedVOp = SimplifyVBinOp(N);
3874     if (FoldedVOp.getNode()) return FoldedVOp;
3875   }
3876
3877   // fold (sra c1, c2) -> (sra c1, c2)
3878   if (N0C && N1C)
3879     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3880   // fold (sra 0, x) -> 0
3881   if (N0C && N0C->isNullValue())
3882     return N0;
3883   // fold (sra -1, x) -> -1
3884   if (N0C && N0C->isAllOnesValue())
3885     return N0;
3886   // fold (sra x, (setge c, size(x))) -> undef
3887   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3888     return DAG.getUNDEF(VT);
3889   // fold (sra x, 0) -> x
3890   if (N1C && N1C->isNullValue())
3891     return N0;
3892   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3893   // sext_inreg.
3894   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3895     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3896     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3897     if (VT.isVector())
3898       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3899                                ExtVT, VT.getVectorNumElements());
3900     if ((!LegalOperations ||
3901          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3902       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3903                          N0.getOperand(0), DAG.getValueType(ExtVT));
3904   }
3905
3906   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3907   if (N1C && N0.getOpcode() == ISD::SRA) {
3908     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3909       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3910       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3911       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3912                          DAG.getConstant(Sum, N1C->getValueType(0)));
3913     }
3914   }
3915
3916   // fold (sra (shl X, m), (sub result_size, n))
3917   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3918   // result_size - n != m.
3919   // If truncate is free for the target sext(shl) is likely to result in better
3920   // code.
3921   if (N0.getOpcode() == ISD::SHL) {
3922     // Get the two constanst of the shifts, CN0 = m, CN = n.
3923     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3924     if (N01C && N1C) {
3925       // Determine what the truncate's result bitsize and type would be.
3926       EVT TruncVT =
3927         EVT::getIntegerVT(*DAG.getContext(),
3928                           OpSizeInBits - N1C->getZExtValue());
3929       // Determine the residual right-shift amount.
3930       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3931
3932       // If the shift is not a no-op (in which case this should be just a sign
3933       // extend already), the truncated to type is legal, sign_extend is legal
3934       // on that type, and the truncate to that type is both legal and free,
3935       // perform the transform.
3936       if ((ShiftAmt > 0) &&
3937           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3938           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3939           TLI.isTruncateFree(VT, TruncVT)) {
3940
3941           SDValue Amt = DAG.getConstant(ShiftAmt,
3942               getShiftAmountTy(N0.getOperand(0).getValueType()));
3943           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3944                                       N0.getOperand(0), Amt);
3945           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3946                                       Shift);
3947           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3948                              N->getValueType(0), Trunc);
3949       }
3950     }
3951   }
3952
3953   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3954   if (N1.getOpcode() == ISD::TRUNCATE &&
3955       N1.getOperand(0).getOpcode() == ISD::AND &&
3956       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3957     SDValue N101 = N1.getOperand(0).getOperand(1);
3958     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3959       EVT TruncVT = N1.getValueType();
3960       SDValue N100 = N1.getOperand(0).getOperand(0);
3961       APInt TruncC = N101C->getAPIntValue();
3962       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3963       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3964                          DAG.getNode(ISD::AND, SDLoc(N),
3965                                      TruncVT,
3966                                      DAG.getNode(ISD::TRUNCATE,
3967                                                  SDLoc(N),
3968                                                  TruncVT, N100),
3969                                      DAG.getConstant(TruncC, TruncVT)));
3970     }
3971   }
3972
3973   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3974   //      if c1 is equal to the number of bits the trunc removes
3975   if (N0.getOpcode() == ISD::TRUNCATE &&
3976       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3977        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3978       N0.getOperand(0).hasOneUse() &&
3979       N0.getOperand(0).getOperand(1).hasOneUse() &&
3980       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3981     EVT LargeVT = N0.getOperand(0).getValueType();
3982     ConstantSDNode *LargeShiftAmt =
3983       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3984
3985     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3986         LargeShiftAmt->getZExtValue()) {
3987       SDValue Amt =
3988         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3989               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3990       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3991                                 N0.getOperand(0).getOperand(0), Amt);
3992       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3993     }
3994   }
3995
3996   // Simplify, based on bits shifted out of the LHS.
3997   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3998     return SDValue(N, 0);
3999
4000
4001   // If the sign bit is known to be zero, switch this to a SRL.
4002   if (DAG.SignBitIsZero(N0))
4003     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4004
4005   if (N1C) {
4006     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4007     if (NewSRA.getNode())
4008       return NewSRA;
4009   }
4010
4011   return SDValue();
4012 }
4013
4014 SDValue DAGCombiner::visitSRL(SDNode *N) {
4015   SDValue N0 = N->getOperand(0);
4016   SDValue N1 = N->getOperand(1);
4017   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4018   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4019   EVT VT = N0.getValueType();
4020   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4021
4022   // fold vector ops
4023   if (VT.isVector()) {
4024     SDValue FoldedVOp = SimplifyVBinOp(N);
4025     if (FoldedVOp.getNode()) return FoldedVOp;
4026   }
4027
4028   // fold (srl c1, c2) -> c1 >>u c2
4029   if (N0C && N1C)
4030     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4031   // fold (srl 0, x) -> 0
4032   if (N0C && N0C->isNullValue())
4033     return N0;
4034   // fold (srl x, c >= size(x)) -> undef
4035   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4036     return DAG.getUNDEF(VT);
4037   // fold (srl x, 0) -> x
4038   if (N1C && N1C->isNullValue())
4039     return N0;
4040   // if (srl x, c) is known to be zero, return 0
4041   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4042                                    APInt::getAllOnesValue(OpSizeInBits)))
4043     return DAG.getConstant(0, VT);
4044
4045   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4046   if (N1C && N0.getOpcode() == ISD::SRL &&
4047       N0.getOperand(1).getOpcode() == ISD::Constant) {
4048     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4049     uint64_t c2 = N1C->getZExtValue();
4050     if (c1 + c2 >= OpSizeInBits)
4051       return DAG.getConstant(0, VT);
4052     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4053                        DAG.getConstant(c1 + c2, N1.getValueType()));
4054   }
4055
4056   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4057   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4058       N0.getOperand(0).getOpcode() == ISD::SRL &&
4059       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4060     uint64_t c1 =
4061       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4062     uint64_t c2 = N1C->getZExtValue();
4063     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4064     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4065     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4066     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4067     if (c1 + OpSizeInBits == InnerShiftSize) {
4068       if (c1 + c2 >= InnerShiftSize)
4069         return DAG.getConstant(0, VT);
4070       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4071                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4072                                      N0.getOperand(0)->getOperand(0),
4073                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4074     }
4075   }
4076
4077   // fold (srl (shl x, c), c) -> (and x, cst2)
4078   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4079       N0.getValueSizeInBits() <= 64) {
4080     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4081     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4082                        DAG.getConstant(~0ULL >> ShAmt, VT));
4083   }
4084
4085   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4086   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4087     // Shifting in all undef bits?
4088     EVT SmallVT = N0.getOperand(0).getValueType();
4089     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4090       return DAG.getUNDEF(VT);
4091
4092     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4093       uint64_t ShiftAmt = N1C->getZExtValue();
4094       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4095                                        N0.getOperand(0),
4096                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4097       AddToWorkList(SmallShift.getNode());
4098       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4099       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4100                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4101                          DAG.getConstant(Mask, VT));
4102     }
4103   }
4104
4105   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4106   // bit, which is unmodified by sra.
4107   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4108     if (N0.getOpcode() == ISD::SRA)
4109       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4110   }
4111
4112   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4113   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4114       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4115     APInt KnownZero, KnownOne;
4116     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4117
4118     // If any of the input bits are KnownOne, then the input couldn't be all
4119     // zeros, thus the result of the srl will always be zero.
4120     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4121
4122     // If all of the bits input the to ctlz node are known to be zero, then
4123     // the result of the ctlz is "32" and the result of the shift is one.
4124     APInt UnknownBits = ~KnownZero;
4125     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4126
4127     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4128     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4129       // Okay, we know that only that the single bit specified by UnknownBits
4130       // could be set on input to the CTLZ node. If this bit is set, the SRL
4131       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4132       // to an SRL/XOR pair, which is likely to simplify more.
4133       unsigned ShAmt = UnknownBits.countTrailingZeros();
4134       SDValue Op = N0.getOperand(0);
4135
4136       if (ShAmt) {
4137         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4138                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4139         AddToWorkList(Op.getNode());
4140       }
4141
4142       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4143                          Op, DAG.getConstant(1, VT));
4144     }
4145   }
4146
4147   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4148   if (N1.getOpcode() == ISD::TRUNCATE &&
4149       N1.getOperand(0).getOpcode() == ISD::AND &&
4150       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4151     SDValue N101 = N1.getOperand(0).getOperand(1);
4152     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4153       EVT TruncVT = N1.getValueType();
4154       SDValue N100 = N1.getOperand(0).getOperand(0);
4155       APInt TruncC = N101C->getAPIntValue();
4156       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4157       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4158                          DAG.getNode(ISD::AND, SDLoc(N),
4159                                      TruncVT,
4160                                      DAG.getNode(ISD::TRUNCATE,
4161                                                  SDLoc(N),
4162                                                  TruncVT, N100),
4163                                      DAG.getConstant(TruncC, TruncVT)));
4164     }
4165   }
4166
4167   // fold operands of srl based on knowledge that the low bits are not
4168   // demanded.
4169   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4170     return SDValue(N, 0);
4171
4172   if (N1C) {
4173     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4174     if (NewSRL.getNode())
4175       return NewSRL;
4176   }
4177
4178   // Attempt to convert a srl of a load into a narrower zero-extending load.
4179   SDValue NarrowLoad = ReduceLoadWidth(N);
4180   if (NarrowLoad.getNode())
4181     return NarrowLoad;
4182
4183   // Here is a common situation. We want to optimize:
4184   //
4185   //   %a = ...
4186   //   %b = and i32 %a, 2
4187   //   %c = srl i32 %b, 1
4188   //   brcond i32 %c ...
4189   //
4190   // into
4191   //
4192   //   %a = ...
4193   //   %b = and %a, 2
4194   //   %c = setcc eq %b, 0
4195   //   brcond %c ...
4196   //
4197   // However when after the source operand of SRL is optimized into AND, the SRL
4198   // itself may not be optimized further. Look for it and add the BRCOND into
4199   // the worklist.
4200   if (N->hasOneUse()) {
4201     SDNode *Use = *N->use_begin();
4202     if (Use->getOpcode() == ISD::BRCOND)
4203       AddToWorkList(Use);
4204     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4205       // Also look pass the truncate.
4206       Use = *Use->use_begin();
4207       if (Use->getOpcode() == ISD::BRCOND)
4208         AddToWorkList(Use);
4209     }
4210   }
4211
4212   return SDValue();
4213 }
4214
4215 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4216   SDValue N0 = N->getOperand(0);
4217   EVT VT = N->getValueType(0);
4218
4219   // fold (ctlz c1) -> c2
4220   if (isa<ConstantSDNode>(N0))
4221     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4222   return SDValue();
4223 }
4224
4225 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4226   SDValue N0 = N->getOperand(0);
4227   EVT VT = N->getValueType(0);
4228
4229   // fold (ctlz_zero_undef c1) -> c2
4230   if (isa<ConstantSDNode>(N0))
4231     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4232   return SDValue();
4233 }
4234
4235 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4236   SDValue N0 = N->getOperand(0);
4237   EVT VT = N->getValueType(0);
4238
4239   // fold (cttz c1) -> c2
4240   if (isa<ConstantSDNode>(N0))
4241     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4242   return SDValue();
4243 }
4244
4245 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4246   SDValue N0 = N->getOperand(0);
4247   EVT VT = N->getValueType(0);
4248
4249   // fold (cttz_zero_undef c1) -> c2
4250   if (isa<ConstantSDNode>(N0))
4251     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4252   return SDValue();
4253 }
4254
4255 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4256   SDValue N0 = N->getOperand(0);
4257   EVT VT = N->getValueType(0);
4258
4259   // fold (ctpop c1) -> c2
4260   if (isa<ConstantSDNode>(N0))
4261     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4262   return SDValue();
4263 }
4264
4265 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4266   SDValue N0 = N->getOperand(0);
4267   SDValue N1 = N->getOperand(1);
4268   SDValue N2 = N->getOperand(2);
4269   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4270   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4271   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4272   EVT VT = N->getValueType(0);
4273   EVT VT0 = N0.getValueType();
4274
4275   // fold (select C, X, X) -> X
4276   if (N1 == N2)
4277     return N1;
4278   // fold (select true, X, Y) -> X
4279   if (N0C && !N0C->isNullValue())
4280     return N1;
4281   // fold (select false, X, Y) -> Y
4282   if (N0C && N0C->isNullValue())
4283     return N2;
4284   // fold (select C, 1, X) -> (or C, X)
4285   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4286     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4287   // fold (select C, 0, 1) -> (xor C, 1)
4288   if (VT.isInteger() &&
4289       (VT0 == MVT::i1 ||
4290        (VT0.isInteger() &&
4291         TLI.getBooleanContents(false) ==
4292         TargetLowering::ZeroOrOneBooleanContent)) &&
4293       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4294     SDValue XORNode;
4295     if (VT == VT0)
4296       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4297                          N0, DAG.getConstant(1, VT0));
4298     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4299                           N0, DAG.getConstant(1, VT0));
4300     AddToWorkList(XORNode.getNode());
4301     if (VT.bitsGT(VT0))
4302       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4303     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4304   }
4305   // fold (select C, 0, X) -> (and (not C), X)
4306   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4307     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4308     AddToWorkList(NOTNode.getNode());
4309     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4310   }
4311   // fold (select C, X, 1) -> (or (not C), X)
4312   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4313     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4314     AddToWorkList(NOTNode.getNode());
4315     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4316   }
4317   // fold (select C, X, 0) -> (and C, X)
4318   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4319     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4320   // fold (select X, X, Y) -> (or X, Y)
4321   // fold (select X, 1, Y) -> (or X, Y)
4322   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4323     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4324   // fold (select X, Y, X) -> (and X, Y)
4325   // fold (select X, Y, 0) -> (and X, Y)
4326   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4327     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4328
4329   // If we can fold this based on the true/false value, do so.
4330   if (SimplifySelectOps(N, N1, N2))
4331     return SDValue(N, 0);  // Don't revisit N.
4332
4333   // fold selects based on a setcc into other things, such as min/max/abs
4334   if (N0.getOpcode() == ISD::SETCC) {
4335     // FIXME:
4336     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4337     // having to say they don't support SELECT_CC on every type the DAG knows
4338     // about, since there is no way to mark an opcode illegal at all value types
4339     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4340         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4341       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4342                          N0.getOperand(0), N0.getOperand(1),
4343                          N1, N2, N0.getOperand(2));
4344     return SimplifySelect(SDLoc(N), N0, N1, N2);
4345   }
4346
4347   return SDValue();
4348 }
4349
4350 static
4351 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4352   SDLoc DL(N);
4353   EVT LoVT, HiVT;
4354   llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4355
4356   // Split the inputs.
4357   SDValue Lo, Hi, LL, LH, RL, RH;
4358   llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4359   llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4360
4361   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4362   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4363
4364   return std::make_pair(Lo, Hi);
4365 }
4366
4367 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4368   SDValue N0 = N->getOperand(0);
4369   SDValue N1 = N->getOperand(1);
4370   SDValue N2 = N->getOperand(2);
4371   SDLoc DL(N);
4372
4373   // Canonicalize integer abs.
4374   // vselect (setg[te] X,  0),  X, -X ->
4375   // vselect (setgt    X, -1),  X, -X ->
4376   // vselect (setl[te] X,  0), -X,  X ->
4377   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4378   if (N0.getOpcode() == ISD::SETCC) {
4379     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4380     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4381     bool isAbs = false;
4382     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4383
4384     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4385          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4386         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4387       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4388     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4389              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4390       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4391
4392     if (isAbs) {
4393       EVT VT = LHS.getValueType();
4394       SDValue Shift = DAG.getNode(
4395           ISD::SRA, DL, VT, LHS,
4396           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4397       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4398       AddToWorkList(Shift.getNode());
4399       AddToWorkList(Add.getNode());
4400       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4401     }
4402   }
4403
4404   // If the VSELECT result requires splitting and the mask is provided by a
4405   // SETCC, then split both nodes and its operands before legalization. This
4406   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4407   // and enables future optimizations (e.g. min/max pattern matching on X86).
4408   if (N0.getOpcode() == ISD::SETCC) {
4409     EVT VT = N->getValueType(0);
4410
4411     // Check if any splitting is required.
4412     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4413         TargetLowering::TypeSplitVector)
4414       return SDValue();
4415
4416     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4417     llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4418     llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4419     llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4420
4421     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4422     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4423
4424     // Add the new VSELECT nodes to the work list in case they need to be split
4425     // again.
4426     AddToWorkList(Lo.getNode());
4427     AddToWorkList(Hi.getNode());
4428
4429     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4430   }
4431
4432   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4433   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4434     return N1;
4435   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4436   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4437     return N2;
4438
4439   return SDValue();
4440 }
4441
4442 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4443   SDValue N0 = N->getOperand(0);
4444   SDValue N1 = N->getOperand(1);
4445   SDValue N2 = N->getOperand(2);
4446   SDValue N3 = N->getOperand(3);
4447   SDValue N4 = N->getOperand(4);
4448   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4449
4450   // fold select_cc lhs, rhs, x, x, cc -> x
4451   if (N2 == N3)
4452     return N2;
4453
4454   // Determine if the condition we're dealing with is constant
4455   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4456                               N0, N1, CC, SDLoc(N), false);
4457   if (SCC.getNode()) {
4458     AddToWorkList(SCC.getNode());
4459
4460     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4461       if (!SCCC->isNullValue())
4462         return N2;    // cond always true -> true val
4463       else
4464         return N3;    // cond always false -> false val
4465     }
4466
4467     // Fold to a simpler select_cc
4468     if (SCC.getOpcode() == ISD::SETCC)
4469       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4470                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4471                          SCC.getOperand(2));
4472   }
4473
4474   // If we can fold this based on the true/false value, do so.
4475   if (SimplifySelectOps(N, N2, N3))
4476     return SDValue(N, 0);  // Don't revisit N.
4477
4478   // fold select_cc into other things, such as min/max/abs
4479   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4480 }
4481
4482 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4483   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4484                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4485                        SDLoc(N));
4486 }
4487
4488 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4489 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4490 // transformation. Returns true if extension are possible and the above
4491 // mentioned transformation is profitable.
4492 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4493                                     unsigned ExtOpc,
4494                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4495                                     const TargetLowering &TLI) {
4496   bool HasCopyToRegUses = false;
4497   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4498   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4499                             UE = N0.getNode()->use_end();
4500        UI != UE; ++UI) {
4501     SDNode *User = *UI;
4502     if (User == N)
4503       continue;
4504     if (UI.getUse().getResNo() != N0.getResNo())
4505       continue;
4506     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4507     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4508       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4509       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4510         // Sign bits will be lost after a zext.
4511         return false;
4512       bool Add = false;
4513       for (unsigned i = 0; i != 2; ++i) {
4514         SDValue UseOp = User->getOperand(i);
4515         if (UseOp == N0)
4516           continue;
4517         if (!isa<ConstantSDNode>(UseOp))
4518           return false;
4519         Add = true;
4520       }
4521       if (Add)
4522         ExtendNodes.push_back(User);
4523       continue;
4524     }
4525     // If truncates aren't free and there are users we can't
4526     // extend, it isn't worthwhile.
4527     if (!isTruncFree)
4528       return false;
4529     // Remember if this value is live-out.
4530     if (User->getOpcode() == ISD::CopyToReg)
4531       HasCopyToRegUses = true;
4532   }
4533
4534   if (HasCopyToRegUses) {
4535     bool BothLiveOut = false;
4536     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4537          UI != UE; ++UI) {
4538       SDUse &Use = UI.getUse();
4539       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4540         BothLiveOut = true;
4541         break;
4542       }
4543     }
4544     if (BothLiveOut)
4545       // Both unextended and extended values are live out. There had better be
4546       // a good reason for the transformation.
4547       return ExtendNodes.size();
4548   }
4549   return true;
4550 }
4551
4552 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4553                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4554                                   ISD::NodeType ExtType) {
4555   // Extend SetCC uses if necessary.
4556   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4557     SDNode *SetCC = SetCCs[i];
4558     SmallVector<SDValue, 4> Ops;
4559
4560     for (unsigned j = 0; j != 2; ++j) {
4561       SDValue SOp = SetCC->getOperand(j);
4562       if (SOp == Trunc)
4563         Ops.push_back(ExtLoad);
4564       else
4565         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4566     }
4567
4568     Ops.push_back(SetCC->getOperand(2));
4569     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4570                                  &Ops[0], Ops.size()));
4571   }
4572 }
4573
4574 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4575   SDValue N0 = N->getOperand(0);
4576   EVT VT = N->getValueType(0);
4577
4578   // fold (sext c1) -> c1
4579   if (isa<ConstantSDNode>(N0))
4580     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4581
4582   // fold (sext (sext x)) -> (sext x)
4583   // fold (sext (aext x)) -> (sext x)
4584   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4585     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4586                        N0.getOperand(0));
4587
4588   if (N0.getOpcode() == ISD::TRUNCATE) {
4589     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4590     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4591     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4592     if (NarrowLoad.getNode()) {
4593       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4594       if (NarrowLoad.getNode() != N0.getNode()) {
4595         CombineTo(N0.getNode(), NarrowLoad);
4596         // CombineTo deleted the truncate, if needed, but not what's under it.
4597         AddToWorkList(oye);
4598       }
4599       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4600     }
4601
4602     // See if the value being truncated is already sign extended.  If so, just
4603     // eliminate the trunc/sext pair.
4604     SDValue Op = N0.getOperand(0);
4605     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4606     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4607     unsigned DestBits = VT.getScalarType().getSizeInBits();
4608     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4609
4610     if (OpBits == DestBits) {
4611       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4612       // bits, it is already ready.
4613       if (NumSignBits > DestBits-MidBits)
4614         return Op;
4615     } else if (OpBits < DestBits) {
4616       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4617       // bits, just sext from i32.
4618       if (NumSignBits > OpBits-MidBits)
4619         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4620     } else {
4621       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4622       // bits, just truncate to i32.
4623       if (NumSignBits > OpBits-MidBits)
4624         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4625     }
4626
4627     // fold (sext (truncate x)) -> (sextinreg x).
4628     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4629                                                  N0.getValueType())) {
4630       if (OpBits < DestBits)
4631         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4632       else if (OpBits > DestBits)
4633         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4634       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4635                          DAG.getValueType(N0.getValueType()));
4636     }
4637   }
4638
4639   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4640   // None of the supported targets knows how to perform load and sign extend
4641   // on vectors in one instruction.  We only perform this transformation on
4642   // scalars.
4643   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4644       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4645        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4646     bool DoXform = true;
4647     SmallVector<SDNode*, 4> SetCCs;
4648     if (!N0.hasOneUse())
4649       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4650     if (DoXform) {
4651       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4652       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4653                                        LN0->getChain(),
4654                                        LN0->getBasePtr(), N0.getValueType(),
4655                                        LN0->getMemOperand());
4656       CombineTo(N, ExtLoad);
4657       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4658                                   N0.getValueType(), ExtLoad);
4659       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4660       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4661                       ISD::SIGN_EXTEND);
4662       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4663     }
4664   }
4665
4666   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4667   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4668   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4669       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4670     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4671     EVT MemVT = LN0->getMemoryVT();
4672     if ((!LegalOperations && !LN0->isVolatile()) ||
4673         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4674       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4675                                        LN0->getChain(),
4676                                        LN0->getBasePtr(), MemVT,
4677                                        LN0->getMemOperand());
4678       CombineTo(N, ExtLoad);
4679       CombineTo(N0.getNode(),
4680                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4681                             N0.getValueType(), ExtLoad),
4682                 ExtLoad.getValue(1));
4683       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4684     }
4685   }
4686
4687   // fold (sext (and/or/xor (load x), cst)) ->
4688   //      (and/or/xor (sextload x), (sext cst))
4689   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4690        N0.getOpcode() == ISD::XOR) &&
4691       isa<LoadSDNode>(N0.getOperand(0)) &&
4692       N0.getOperand(1).getOpcode() == ISD::Constant &&
4693       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4694       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4695     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4696     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4697       bool DoXform = true;
4698       SmallVector<SDNode*, 4> SetCCs;
4699       if (!N0.hasOneUse())
4700         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4701                                           SetCCs, TLI);
4702       if (DoXform) {
4703         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4704                                          LN0->getChain(), LN0->getBasePtr(),
4705                                          LN0->getMemoryVT(),
4706                                          LN0->getMemOperand());
4707         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4708         Mask = Mask.sext(VT.getSizeInBits());
4709         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4710                                   ExtLoad, DAG.getConstant(Mask, VT));
4711         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4712                                     SDLoc(N0.getOperand(0)),
4713                                     N0.getOperand(0).getValueType(), ExtLoad);
4714         CombineTo(N, And);
4715         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4716         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4717                         ISD::SIGN_EXTEND);
4718         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4719       }
4720     }
4721   }
4722
4723   if (N0.getOpcode() == ISD::SETCC) {
4724     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4725     // Only do this before legalize for now.
4726     if (VT.isVector() && !LegalOperations &&
4727         TLI.getBooleanContents(true) ==
4728           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4729       EVT N0VT = N0.getOperand(0).getValueType();
4730       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4731       // of the same size as the compared operands. Only optimize sext(setcc())
4732       // if this is the case.
4733       EVT SVT = getSetCCResultType(N0VT);
4734
4735       // We know that the # elements of the results is the same as the
4736       // # elements of the compare (and the # elements of the compare result
4737       // for that matter).  Check to see that they are the same size.  If so,
4738       // we know that the element size of the sext'd result matches the
4739       // element size of the compare operands.
4740       if (VT.getSizeInBits() == SVT.getSizeInBits())
4741         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4742                              N0.getOperand(1),
4743                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4744
4745       // If the desired elements are smaller or larger than the source
4746       // elements we can use a matching integer vector type and then
4747       // truncate/sign extend
4748       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4749       if (SVT == MatchingVectorType) {
4750         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4751                                N0.getOperand(0), N0.getOperand(1),
4752                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4753         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4754       }
4755     }
4756
4757     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4758     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4759     SDValue NegOne =
4760       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4761     SDValue SCC =
4762       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4763                        NegOne, DAG.getConstant(0, VT),
4764                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4765     if (SCC.getNode()) return SCC;
4766     if (!VT.isVector() &&
4767         (!LegalOperations ||
4768          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4769       return DAG.getSelect(SDLoc(N), VT,
4770                            DAG.getSetCC(SDLoc(N),
4771                            getSetCCResultType(VT),
4772                            N0.getOperand(0), N0.getOperand(1),
4773                            cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4774                            NegOne, DAG.getConstant(0, VT));
4775     }
4776   }
4777
4778   // fold (sext x) -> (zext x) if the sign bit is known zero.
4779   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4780       DAG.SignBitIsZero(N0))
4781     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4782
4783   return SDValue();
4784 }
4785
4786 // isTruncateOf - If N is a truncate of some other value, return true, record
4787 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4788 // This function computes KnownZero to avoid a duplicated call to
4789 // ComputeMaskedBits in the caller.
4790 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4791                          APInt &KnownZero) {
4792   APInt KnownOne;
4793   if (N->getOpcode() == ISD::TRUNCATE) {
4794     Op = N->getOperand(0);
4795     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4796     return true;
4797   }
4798
4799   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4800       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4801     return false;
4802
4803   SDValue Op0 = N->getOperand(0);
4804   SDValue Op1 = N->getOperand(1);
4805   assert(Op0.getValueType() == Op1.getValueType());
4806
4807   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4808   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4809   if (COp0 && COp0->isNullValue())
4810     Op = Op1;
4811   else if (COp1 && COp1->isNullValue())
4812     Op = Op0;
4813   else
4814     return false;
4815
4816   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4817
4818   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4819     return false;
4820
4821   return true;
4822 }
4823
4824 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4825   SDValue N0 = N->getOperand(0);
4826   EVT VT = N->getValueType(0);
4827
4828   // fold (zext c1) -> c1
4829   if (isa<ConstantSDNode>(N0))
4830     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4831   // fold (zext (zext x)) -> (zext x)
4832   // fold (zext (aext x)) -> (zext x)
4833   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4834     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4835                        N0.getOperand(0));
4836
4837   // fold (zext (truncate x)) -> (zext x) or
4838   //      (zext (truncate x)) -> (truncate x)
4839   // This is valid when the truncated bits of x are already zero.
4840   // FIXME: We should extend this to work for vectors too.
4841   SDValue Op;
4842   APInt KnownZero;
4843   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4844     APInt TruncatedBits =
4845       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4846       APInt(Op.getValueSizeInBits(), 0) :
4847       APInt::getBitsSet(Op.getValueSizeInBits(),
4848                         N0.getValueSizeInBits(),
4849                         std::min(Op.getValueSizeInBits(),
4850                                  VT.getSizeInBits()));
4851     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4852       if (VT.bitsGT(Op.getValueType()))
4853         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4854       if (VT.bitsLT(Op.getValueType()))
4855         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4856
4857       return Op;
4858     }
4859   }
4860
4861   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4862   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4863   if (N0.getOpcode() == ISD::TRUNCATE) {
4864     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4865     if (NarrowLoad.getNode()) {
4866       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4867       if (NarrowLoad.getNode() != N0.getNode()) {
4868         CombineTo(N0.getNode(), NarrowLoad);
4869         // CombineTo deleted the truncate, if needed, but not what's under it.
4870         AddToWorkList(oye);
4871       }
4872       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4873     }
4874   }
4875
4876   // fold (zext (truncate x)) -> (and x, mask)
4877   if (N0.getOpcode() == ISD::TRUNCATE &&
4878       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4879
4880     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4881     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4882     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4883     if (NarrowLoad.getNode()) {
4884       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4885       if (NarrowLoad.getNode() != N0.getNode()) {
4886         CombineTo(N0.getNode(), NarrowLoad);
4887         // CombineTo deleted the truncate, if needed, but not what's under it.
4888         AddToWorkList(oye);
4889       }
4890       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4891     }
4892
4893     SDValue Op = N0.getOperand(0);
4894     if (Op.getValueType().bitsLT(VT)) {
4895       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4896       AddToWorkList(Op.getNode());
4897     } else if (Op.getValueType().bitsGT(VT)) {
4898       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4899       AddToWorkList(Op.getNode());
4900     }
4901     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4902                                   N0.getValueType().getScalarType());
4903   }
4904
4905   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4906   // if either of the casts is not free.
4907   if (N0.getOpcode() == ISD::AND &&
4908       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4909       N0.getOperand(1).getOpcode() == ISD::Constant &&
4910       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4911                            N0.getValueType()) ||
4912        !TLI.isZExtFree(N0.getValueType(), VT))) {
4913     SDValue X = N0.getOperand(0).getOperand(0);
4914     if (X.getValueType().bitsLT(VT)) {
4915       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4916     } else if (X.getValueType().bitsGT(VT)) {
4917       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4918     }
4919     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4920     Mask = Mask.zext(VT.getSizeInBits());
4921     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4922                        X, DAG.getConstant(Mask, VT));
4923   }
4924
4925   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4926   // None of the supported targets knows how to perform load and vector_zext
4927   // on vectors in one instruction.  We only perform this transformation on
4928   // scalars.
4929   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4930       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4931        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4932     bool DoXform = true;
4933     SmallVector<SDNode*, 4> SetCCs;
4934     if (!N0.hasOneUse())
4935       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4936     if (DoXform) {
4937       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4938       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4939                                        LN0->getChain(),
4940                                        LN0->getBasePtr(), N0.getValueType(),
4941                                        LN0->getMemOperand());
4942       CombineTo(N, ExtLoad);
4943       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4944                                   N0.getValueType(), ExtLoad);
4945       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4946
4947       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4948                       ISD::ZERO_EXTEND);
4949       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4950     }
4951   }
4952
4953   // fold (zext (and/or/xor (load x), cst)) ->
4954   //      (and/or/xor (zextload x), (zext cst))
4955   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4956        N0.getOpcode() == ISD::XOR) &&
4957       isa<LoadSDNode>(N0.getOperand(0)) &&
4958       N0.getOperand(1).getOpcode() == ISD::Constant &&
4959       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4960       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4961     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4962     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4963       bool DoXform = true;
4964       SmallVector<SDNode*, 4> SetCCs;
4965       if (!N0.hasOneUse())
4966         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4967                                           SetCCs, TLI);
4968       if (DoXform) {
4969         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4970                                          LN0->getChain(), LN0->getBasePtr(),
4971                                          LN0->getMemoryVT(),
4972                                          LN0->getMemOperand());
4973         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4974         Mask = Mask.zext(VT.getSizeInBits());
4975         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4976                                   ExtLoad, DAG.getConstant(Mask, VT));
4977         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4978                                     SDLoc(N0.getOperand(0)),
4979                                     N0.getOperand(0).getValueType(), ExtLoad);
4980         CombineTo(N, And);
4981         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4982         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4983                         ISD::ZERO_EXTEND);
4984         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4985       }
4986     }
4987   }
4988
4989   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4990   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4991   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4992       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4993     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4994     EVT MemVT = LN0->getMemoryVT();
4995     if ((!LegalOperations && !LN0->isVolatile()) ||
4996         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4997       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4998                                        LN0->getChain(),
4999                                        LN0->getBasePtr(), MemVT,
5000                                        LN0->getMemOperand());
5001       CombineTo(N, ExtLoad);
5002       CombineTo(N0.getNode(),
5003                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5004                             ExtLoad),
5005                 ExtLoad.getValue(1));
5006       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5007     }
5008   }
5009
5010   if (N0.getOpcode() == ISD::SETCC) {
5011     if (!LegalOperations && VT.isVector() &&
5012         N0.getValueType().getVectorElementType() == MVT::i1) {
5013       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5014       // Only do this before legalize for now.
5015       EVT N0VT = N0.getOperand(0).getValueType();
5016       EVT EltVT = VT.getVectorElementType();
5017       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5018                                     DAG.getConstant(1, EltVT));
5019       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5020         // We know that the # elements of the results is the same as the
5021         // # elements of the compare (and the # elements of the compare result
5022         // for that matter).  Check to see that they are the same size.  If so,
5023         // we know that the element size of the sext'd result matches the
5024         // element size of the compare operands.
5025         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5026                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5027                                          N0.getOperand(1),
5028                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5029                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5030                                        &OneOps[0], OneOps.size()));
5031
5032       // If the desired elements are smaller or larger than the source
5033       // elements we can use a matching integer vector type and then
5034       // truncate/sign extend
5035       EVT MatchingElementType =
5036         EVT::getIntegerVT(*DAG.getContext(),
5037                           N0VT.getScalarType().getSizeInBits());
5038       EVT MatchingVectorType =
5039         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5040                          N0VT.getVectorNumElements());
5041       SDValue VsetCC =
5042         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5043                       N0.getOperand(1),
5044                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5045       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5046                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5047                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5048                                      &OneOps[0], OneOps.size()));
5049     }
5050
5051     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5052     SDValue SCC =
5053       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5054                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5055                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5056     if (SCC.getNode()) return SCC;
5057   }
5058
5059   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5060   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5061       isa<ConstantSDNode>(N0.getOperand(1)) &&
5062       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5063       N0.hasOneUse()) {
5064     SDValue ShAmt = N0.getOperand(1);
5065     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5066     if (N0.getOpcode() == ISD::SHL) {
5067       SDValue InnerZExt = N0.getOperand(0);
5068       // If the original shl may be shifting out bits, do not perform this
5069       // transformation.
5070       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5071         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5072       if (ShAmtVal > KnownZeroBits)
5073         return SDValue();
5074     }
5075
5076     SDLoc DL(N);
5077
5078     // Ensure that the shift amount is wide enough for the shifted value.
5079     if (VT.getSizeInBits() >= 256)
5080       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5081
5082     return DAG.getNode(N0.getOpcode(), DL, VT,
5083                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5084                        ShAmt);
5085   }
5086
5087   return SDValue();
5088 }
5089
5090 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5091   SDValue N0 = N->getOperand(0);
5092   EVT VT = N->getValueType(0);
5093
5094   // fold (aext c1) -> c1
5095   if (isa<ConstantSDNode>(N0))
5096     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5097   // fold (aext (aext x)) -> (aext x)
5098   // fold (aext (zext x)) -> (zext x)
5099   // fold (aext (sext x)) -> (sext x)
5100   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5101       N0.getOpcode() == ISD::ZERO_EXTEND ||
5102       N0.getOpcode() == ISD::SIGN_EXTEND)
5103     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5104
5105   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5106   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5107   if (N0.getOpcode() == ISD::TRUNCATE) {
5108     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5109     if (NarrowLoad.getNode()) {
5110       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5111       if (NarrowLoad.getNode() != N0.getNode()) {
5112         CombineTo(N0.getNode(), NarrowLoad);
5113         // CombineTo deleted the truncate, if needed, but not what's under it.
5114         AddToWorkList(oye);
5115       }
5116       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5117     }
5118   }
5119
5120   // fold (aext (truncate x))
5121   if (N0.getOpcode() == ISD::TRUNCATE) {
5122     SDValue TruncOp = N0.getOperand(0);
5123     if (TruncOp.getValueType() == VT)
5124       return TruncOp; // x iff x size == zext size.
5125     if (TruncOp.getValueType().bitsGT(VT))
5126       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5127     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5128   }
5129
5130   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5131   // if the trunc is not free.
5132   if (N0.getOpcode() == ISD::AND &&
5133       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5134       N0.getOperand(1).getOpcode() == ISD::Constant &&
5135       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5136                           N0.getValueType())) {
5137     SDValue X = N0.getOperand(0).getOperand(0);
5138     if (X.getValueType().bitsLT(VT)) {
5139       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5140     } else if (X.getValueType().bitsGT(VT)) {
5141       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5142     }
5143     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5144     Mask = Mask.zext(VT.getSizeInBits());
5145     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5146                        X, DAG.getConstant(Mask, VT));
5147   }
5148
5149   // fold (aext (load x)) -> (aext (truncate (extload x)))
5150   // None of the supported targets knows how to perform load and any_ext
5151   // on vectors in one instruction.  We only perform this transformation on
5152   // scalars.
5153   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5154       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5155        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5156     bool DoXform = true;
5157     SmallVector<SDNode*, 4> SetCCs;
5158     if (!N0.hasOneUse())
5159       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5160     if (DoXform) {
5161       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5162       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5163                                        LN0->getChain(),
5164                                        LN0->getBasePtr(), N0.getValueType(),
5165                                        LN0->getMemOperand());
5166       CombineTo(N, ExtLoad);
5167       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5168                                   N0.getValueType(), ExtLoad);
5169       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5170       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5171                       ISD::ANY_EXTEND);
5172       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5173     }
5174   }
5175
5176   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5177   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5178   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5179   if (N0.getOpcode() == ISD::LOAD &&
5180       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5181       N0.hasOneUse()) {
5182     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5183     EVT MemVT = LN0->getMemoryVT();
5184     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5185                                      VT, LN0->getChain(), LN0->getBasePtr(),
5186                                      MemVT, LN0->getMemOperand());
5187     CombineTo(N, ExtLoad);
5188     CombineTo(N0.getNode(),
5189               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5190                           N0.getValueType(), ExtLoad),
5191               ExtLoad.getValue(1));
5192     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5193   }
5194
5195   if (N0.getOpcode() == ISD::SETCC) {
5196     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5197     // Only do this before legalize for now.
5198     if (VT.isVector() && !LegalOperations) {
5199       EVT N0VT = N0.getOperand(0).getValueType();
5200         // We know that the # elements of the results is the same as the
5201         // # elements of the compare (and the # elements of the compare result
5202         // for that matter).  Check to see that they are the same size.  If so,
5203         // we know that the element size of the sext'd result matches the
5204         // element size of the compare operands.
5205       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5206         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5207                              N0.getOperand(1),
5208                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5209       // If the desired elements are smaller or larger than the source
5210       // elements we can use a matching integer vector type and then
5211       // truncate/sign extend
5212       else {
5213         EVT MatchingElementType =
5214           EVT::getIntegerVT(*DAG.getContext(),
5215                             N0VT.getScalarType().getSizeInBits());
5216         EVT MatchingVectorType =
5217           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5218                            N0VT.getVectorNumElements());
5219         SDValue VsetCC =
5220           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5221                         N0.getOperand(1),
5222                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5223         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5224       }
5225     }
5226
5227     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5228     SDValue SCC =
5229       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5230                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5231                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5232     if (SCC.getNode())
5233       return SCC;
5234   }
5235
5236   return SDValue();
5237 }
5238
5239 /// GetDemandedBits - See if the specified operand can be simplified with the
5240 /// knowledge that only the bits specified by Mask are used.  If so, return the
5241 /// simpler operand, otherwise return a null SDValue.
5242 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5243   switch (V.getOpcode()) {
5244   default: break;
5245   case ISD::Constant: {
5246     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5247     assert(CV != 0 && "Const value should be ConstSDNode.");
5248     const APInt &CVal = CV->getAPIntValue();
5249     APInt NewVal = CVal & Mask;
5250     if (NewVal != CVal)
5251       return DAG.getConstant(NewVal, V.getValueType());
5252     break;
5253   }
5254   case ISD::OR:
5255   case ISD::XOR:
5256     // If the LHS or RHS don't contribute bits to the or, drop them.
5257     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5258       return V.getOperand(1);
5259     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5260       return V.getOperand(0);
5261     break;
5262   case ISD::SRL:
5263     // Only look at single-use SRLs.
5264     if (!V.getNode()->hasOneUse())
5265       break;
5266     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5267       // See if we can recursively simplify the LHS.
5268       unsigned Amt = RHSC->getZExtValue();
5269
5270       // Watch out for shift count overflow though.
5271       if (Amt >= Mask.getBitWidth()) break;
5272       APInt NewMask = Mask << Amt;
5273       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5274       if (SimplifyLHS.getNode())
5275         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5276                            SimplifyLHS, V.getOperand(1));
5277     }
5278   }
5279   return SDValue();
5280 }
5281
5282 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5283 /// bits and then truncated to a narrower type and where N is a multiple
5284 /// of number of bits of the narrower type, transform it to a narrower load
5285 /// from address + N / num of bits of new type. If the result is to be
5286 /// extended, also fold the extension to form a extending load.
5287 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5288   unsigned Opc = N->getOpcode();
5289
5290   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5291   SDValue N0 = N->getOperand(0);
5292   EVT VT = N->getValueType(0);
5293   EVT ExtVT = VT;
5294
5295   // This transformation isn't valid for vector loads.
5296   if (VT.isVector())
5297     return SDValue();
5298
5299   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5300   // extended to VT.
5301   if (Opc == ISD::SIGN_EXTEND_INREG) {
5302     ExtType = ISD::SEXTLOAD;
5303     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5304   } else if (Opc == ISD::SRL) {
5305     // Another special-case: SRL is basically zero-extending a narrower value.
5306     ExtType = ISD::ZEXTLOAD;
5307     N0 = SDValue(N, 0);
5308     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5309     if (!N01) return SDValue();
5310     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5311                               VT.getSizeInBits() - N01->getZExtValue());
5312   }
5313   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5314     return SDValue();
5315
5316   unsigned EVTBits = ExtVT.getSizeInBits();
5317
5318   // Do not generate loads of non-round integer types since these can
5319   // be expensive (and would be wrong if the type is not byte sized).
5320   if (!ExtVT.isRound())
5321     return SDValue();
5322
5323   unsigned ShAmt = 0;
5324   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5325     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5326       ShAmt = N01->getZExtValue();
5327       // Is the shift amount a multiple of size of VT?
5328       if ((ShAmt & (EVTBits-1)) == 0) {
5329         N0 = N0.getOperand(0);
5330         // Is the load width a multiple of size of VT?
5331         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5332           return SDValue();
5333       }
5334
5335       // At this point, we must have a load or else we can't do the transform.
5336       if (!isa<LoadSDNode>(N0)) return SDValue();
5337
5338       // Because a SRL must be assumed to *need* to zero-extend the high bits
5339       // (as opposed to anyext the high bits), we can't combine the zextload
5340       // lowering of SRL and an sextload.
5341       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5342         return SDValue();
5343
5344       // If the shift amount is larger than the input type then we're not
5345       // accessing any of the loaded bytes.  If the load was a zextload/extload
5346       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5347       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5348         return SDValue();
5349     }
5350   }
5351
5352   // If the load is shifted left (and the result isn't shifted back right),
5353   // we can fold the truncate through the shift.
5354   unsigned ShLeftAmt = 0;
5355   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5356       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5357     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5358       ShLeftAmt = N01->getZExtValue();
5359       N0 = N0.getOperand(0);
5360     }
5361   }
5362
5363   // If we haven't found a load, we can't narrow it.  Don't transform one with
5364   // multiple uses, this would require adding a new load.
5365   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5366     return SDValue();
5367
5368   // Don't change the width of a volatile load.
5369   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5370   if (LN0->isVolatile())
5371     return SDValue();
5372
5373   // Verify that we are actually reducing a load width here.
5374   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5375     return SDValue();
5376
5377   // For the transform to be legal, the load must produce only two values
5378   // (the value loaded and the chain).  Don't transform a pre-increment
5379   // load, for example, which produces an extra value.  Otherwise the
5380   // transformation is not equivalent, and the downstream logic to replace
5381   // uses gets things wrong.
5382   if (LN0->getNumValues() > 2)
5383     return SDValue();
5384
5385   // If the load that we're shrinking is an extload and we're not just
5386   // discarding the extension we can't simply shrink the load. Bail.
5387   // TODO: It would be possible to merge the extensions in some cases.
5388   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5389       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5390     return SDValue();
5391
5392   EVT PtrType = N0.getOperand(1).getValueType();
5393
5394   if (PtrType == MVT::Untyped || PtrType.isExtended())
5395     // It's not possible to generate a constant of extended or untyped type.
5396     return SDValue();
5397
5398   // For big endian targets, we need to adjust the offset to the pointer to
5399   // load the correct bytes.
5400   if (TLI.isBigEndian()) {
5401     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5402     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5403     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5404   }
5405
5406   uint64_t PtrOff = ShAmt / 8;
5407   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5408   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5409                                PtrType, LN0->getBasePtr(),
5410                                DAG.getConstant(PtrOff, PtrType));
5411   AddToWorkList(NewPtr.getNode());
5412
5413   SDValue Load;
5414   if (ExtType == ISD::NON_EXTLOAD)
5415     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5416                         LN0->getPointerInfo().getWithOffset(PtrOff),
5417                         LN0->isVolatile(), LN0->isNonTemporal(),
5418                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5419   else
5420     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5421                           LN0->getPointerInfo().getWithOffset(PtrOff),
5422                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5423                           NewAlign, LN0->getTBAAInfo());
5424
5425   // Replace the old load's chain with the new load's chain.
5426   WorkListRemover DeadNodes(*this);
5427   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5428
5429   // Shift the result left, if we've swallowed a left shift.
5430   SDValue Result = Load;
5431   if (ShLeftAmt != 0) {
5432     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5433     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5434       ShImmTy = VT;
5435     // If the shift amount is as large as the result size (but, presumably,
5436     // no larger than the source) then the useful bits of the result are
5437     // zero; we can't simply return the shortened shift, because the result
5438     // of that operation is undefined.
5439     if (ShLeftAmt >= VT.getSizeInBits())
5440       Result = DAG.getConstant(0, VT);
5441     else
5442       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5443                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5444   }
5445
5446   // Return the new loaded value.
5447   return Result;
5448 }
5449
5450 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5451   SDValue N0 = N->getOperand(0);
5452   SDValue N1 = N->getOperand(1);
5453   EVT VT = N->getValueType(0);
5454   EVT EVT = cast<VTSDNode>(N1)->getVT();
5455   unsigned VTBits = VT.getScalarType().getSizeInBits();
5456   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5457
5458   // fold (sext_in_reg c1) -> c1
5459   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5460     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5461
5462   // If the input is already sign extended, just drop the extension.
5463   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5464     return N0;
5465
5466   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5467   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5468       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5469     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5470                        N0.getOperand(0), N1);
5471
5472   // fold (sext_in_reg (sext x)) -> (sext x)
5473   // fold (sext_in_reg (aext x)) -> (sext x)
5474   // if x is small enough.
5475   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5476     SDValue N00 = N0.getOperand(0);
5477     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5478         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5479       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5480   }
5481
5482   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5483   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5484     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5485
5486   // fold operands of sext_in_reg based on knowledge that the top bits are not
5487   // demanded.
5488   if (SimplifyDemandedBits(SDValue(N, 0)))
5489     return SDValue(N, 0);
5490
5491   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5492   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5493   SDValue NarrowLoad = ReduceLoadWidth(N);
5494   if (NarrowLoad.getNode())
5495     return NarrowLoad;
5496
5497   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5498   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5499   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5500   if (N0.getOpcode() == ISD::SRL) {
5501     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5502       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5503         // We can turn this into an SRA iff the input to the SRL is already sign
5504         // extended enough.
5505         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5506         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5507           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5508                              N0.getOperand(0), N0.getOperand(1));
5509       }
5510   }
5511
5512   // fold (sext_inreg (extload x)) -> (sextload x)
5513   if (ISD::isEXTLoad(N0.getNode()) &&
5514       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5515       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5516       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5517        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5518     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5519     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5520                                      LN0->getChain(),
5521                                      LN0->getBasePtr(), EVT,
5522                                      LN0->getMemOperand());
5523     CombineTo(N, ExtLoad);
5524     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5525     AddToWorkList(ExtLoad.getNode());
5526     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5527   }
5528   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5529   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5530       N0.hasOneUse() &&
5531       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5532       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5533        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5534     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5535     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5536                                      LN0->getChain(),
5537                                      LN0->getBasePtr(), EVT,
5538                                      LN0->getMemOperand());
5539     CombineTo(N, ExtLoad);
5540     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5541     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5542   }
5543
5544   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5545   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5546     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5547                                        N0.getOperand(1), false);
5548     if (BSwap.getNode() != 0)
5549       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5550                          BSwap, N1);
5551   }
5552
5553   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5554   // into a build_vector.
5555   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5556     SmallVector<SDValue, 8> Elts;
5557     unsigned NumElts = N0->getNumOperands();
5558     unsigned ShAmt = VTBits - EVTBits;
5559
5560     for (unsigned i = 0; i != NumElts; ++i) {
5561       SDValue Op = N0->getOperand(i);
5562       if (Op->getOpcode() == ISD::UNDEF) {
5563         Elts.push_back(Op);
5564         continue;
5565       }
5566
5567       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5568       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5569       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5570                                      Op.getValueType()));
5571     }
5572
5573     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5574   }
5575
5576   return SDValue();
5577 }
5578
5579 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5580   SDValue N0 = N->getOperand(0);
5581   EVT VT = N->getValueType(0);
5582   bool isLE = TLI.isLittleEndian();
5583
5584   // noop truncate
5585   if (N0.getValueType() == N->getValueType(0))
5586     return N0;
5587   // fold (truncate c1) -> c1
5588   if (isa<ConstantSDNode>(N0))
5589     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5590   // fold (truncate (truncate x)) -> (truncate x)
5591   if (N0.getOpcode() == ISD::TRUNCATE)
5592     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5593   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5594   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5595       N0.getOpcode() == ISD::SIGN_EXTEND ||
5596       N0.getOpcode() == ISD::ANY_EXTEND) {
5597     if (N0.getOperand(0).getValueType().bitsLT(VT))
5598       // if the source is smaller than the dest, we still need an extend
5599       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5600                          N0.getOperand(0));
5601     if (N0.getOperand(0).getValueType().bitsGT(VT))
5602       // if the source is larger than the dest, than we just need the truncate
5603       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5604     // if the source and dest are the same type, we can drop both the extend
5605     // and the truncate.
5606     return N0.getOperand(0);
5607   }
5608
5609   // Fold extract-and-trunc into a narrow extract. For example:
5610   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5611   //   i32 y = TRUNCATE(i64 x)
5612   //        -- becomes --
5613   //   v16i8 b = BITCAST (v2i64 val)
5614   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5615   //
5616   // Note: We only run this optimization after type legalization (which often
5617   // creates this pattern) and before operation legalization after which
5618   // we need to be more careful about the vector instructions that we generate.
5619   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5620       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5621
5622     EVT VecTy = N0.getOperand(0).getValueType();
5623     EVT ExTy = N0.getValueType();
5624     EVT TrTy = N->getValueType(0);
5625
5626     unsigned NumElem = VecTy.getVectorNumElements();
5627     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5628
5629     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5630     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5631
5632     SDValue EltNo = N0->getOperand(1);
5633     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5634       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5635       EVT IndexTy = TLI.getVectorIdxTy();
5636       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5637
5638       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5639                               NVT, N0.getOperand(0));
5640
5641       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5642                          SDLoc(N), TrTy, V,
5643                          DAG.getConstant(Index, IndexTy));
5644     }
5645   }
5646
5647   // Fold a series of buildvector, bitcast, and truncate if possible.
5648   // For example fold
5649   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5650   //   (2xi32 (buildvector x, y)).
5651   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5652       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5653       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5654       N0.getOperand(0).hasOneUse()) {
5655
5656     SDValue BuildVect = N0.getOperand(0);
5657     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5658     EVT TruncVecEltTy = VT.getVectorElementType();
5659
5660     // Check that the element types match.
5661     if (BuildVectEltTy == TruncVecEltTy) {
5662       // Now we only need to compute the offset of the truncated elements.
5663       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5664       unsigned TruncVecNumElts = VT.getVectorNumElements();
5665       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5666
5667       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5668              "Invalid number of elements");
5669
5670       SmallVector<SDValue, 8> Opnds;
5671       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5672         Opnds.push_back(BuildVect.getOperand(i));
5673
5674       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5675                          Opnds.size());
5676     }
5677   }
5678
5679   // See if we can simplify the input to this truncate through knowledge that
5680   // only the low bits are being used.
5681   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5682   // Currently we only perform this optimization on scalars because vectors
5683   // may have different active low bits.
5684   if (!VT.isVector()) {
5685     SDValue Shorter =
5686       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5687                                                VT.getSizeInBits()));
5688     if (Shorter.getNode())
5689       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5690   }
5691   // fold (truncate (load x)) -> (smaller load x)
5692   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5693   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5694     SDValue Reduced = ReduceLoadWidth(N);
5695     if (Reduced.getNode())
5696       return Reduced;
5697     // Handle the case where the load remains an extending load even
5698     // after truncation.
5699     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5700       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5701       if (!LN0->isVolatile() &&
5702           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5703         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5704                                          VT, LN0->getChain(), LN0->getBasePtr(),
5705                                          LN0->getMemoryVT(),
5706                                          LN0->getMemOperand());
5707         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5708         return NewLoad;
5709       }
5710     }
5711   }
5712   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5713   // where ... are all 'undef'.
5714   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5715     SmallVector<EVT, 8> VTs;
5716     SDValue V;
5717     unsigned Idx = 0;
5718     unsigned NumDefs = 0;
5719
5720     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5721       SDValue X = N0.getOperand(i);
5722       if (X.getOpcode() != ISD::UNDEF) {
5723         V = X;
5724         Idx = i;
5725         NumDefs++;
5726       }
5727       // Stop if more than one members are non-undef.
5728       if (NumDefs > 1)
5729         break;
5730       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5731                                      VT.getVectorElementType(),
5732                                      X.getValueType().getVectorNumElements()));
5733     }
5734
5735     if (NumDefs == 0)
5736       return DAG.getUNDEF(VT);
5737
5738     if (NumDefs == 1) {
5739       assert(V.getNode() && "The single defined operand is empty!");
5740       SmallVector<SDValue, 8> Opnds;
5741       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5742         if (i != Idx) {
5743           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5744           continue;
5745         }
5746         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5747         AddToWorkList(NV.getNode());
5748         Opnds.push_back(NV);
5749       }
5750       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5751                          &Opnds[0], Opnds.size());
5752     }
5753   }
5754
5755   // Simplify the operands using demanded-bits information.
5756   if (!VT.isVector() &&
5757       SimplifyDemandedBits(SDValue(N, 0)))
5758     return SDValue(N, 0);
5759
5760   return SDValue();
5761 }
5762
5763 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5764   SDValue Elt = N->getOperand(i);
5765   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5766     return Elt.getNode();
5767   return Elt.getOperand(Elt.getResNo()).getNode();
5768 }
5769
5770 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5771 /// if load locations are consecutive.
5772 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5773   assert(N->getOpcode() == ISD::BUILD_PAIR);
5774
5775   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5776   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5777   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5778       LD1->getPointerInfo().getAddrSpace() !=
5779          LD2->getPointerInfo().getAddrSpace())
5780     return SDValue();
5781   EVT LD1VT = LD1->getValueType(0);
5782
5783   if (ISD::isNON_EXTLoad(LD2) &&
5784       LD2->hasOneUse() &&
5785       // If both are volatile this would reduce the number of volatile loads.
5786       // If one is volatile it might be ok, but play conservative and bail out.
5787       !LD1->isVolatile() &&
5788       !LD2->isVolatile() &&
5789       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5790     unsigned Align = LD1->getAlignment();
5791     unsigned NewAlign = TLI.getDataLayout()->
5792       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5793
5794     if (NewAlign <= Align &&
5795         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5796       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5797                          LD1->getBasePtr(), LD1->getPointerInfo(),
5798                          false, false, false, Align);
5799   }
5800
5801   return SDValue();
5802 }
5803
5804 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5805   SDValue N0 = N->getOperand(0);
5806   EVT VT = N->getValueType(0);
5807
5808   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5809   // Only do this before legalize, since afterward the target may be depending
5810   // on the bitconvert.
5811   // First check to see if this is all constant.
5812   if (!LegalTypes &&
5813       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5814       VT.isVector()) {
5815     bool isSimple = true;
5816     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5817       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5818           N0.getOperand(i).getOpcode() != ISD::Constant &&
5819           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5820         isSimple = false;
5821         break;
5822       }
5823
5824     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5825     assert(!DestEltVT.isVector() &&
5826            "Element type of vector ValueType must not be vector!");
5827     if (isSimple)
5828       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5829   }
5830
5831   // If the input is a constant, let getNode fold it.
5832   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5833     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5834     if (Res.getNode() != N) {
5835       if (!LegalOperations ||
5836           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5837         return Res;
5838
5839       // Folding it resulted in an illegal node, and it's too late to
5840       // do that. Clean up the old node and forego the transformation.
5841       // Ideally this won't happen very often, because instcombine
5842       // and the earlier dagcombine runs (where illegal nodes are
5843       // permitted) should have folded most of them already.
5844       DAG.DeleteNode(Res.getNode());
5845     }
5846   }
5847
5848   // (conv (conv x, t1), t2) -> (conv x, t2)
5849   if (N0.getOpcode() == ISD::BITCAST)
5850     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5851                        N0.getOperand(0));
5852
5853   // fold (conv (load x)) -> (load (conv*)x)
5854   // If the resultant load doesn't need a higher alignment than the original!
5855   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5856       // Do not change the width of a volatile load.
5857       !cast<LoadSDNode>(N0)->isVolatile() &&
5858       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5859       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5860     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5861     unsigned Align = TLI.getDataLayout()->
5862       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5863     unsigned OrigAlign = LN0->getAlignment();
5864
5865     if (Align <= OrigAlign) {
5866       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5867                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5868                                  LN0->isVolatile(), LN0->isNonTemporal(),
5869                                  LN0->isInvariant(), OrigAlign,
5870                                  LN0->getTBAAInfo());
5871       AddToWorkList(N);
5872       CombineTo(N0.getNode(),
5873                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5874                             N0.getValueType(), Load),
5875                 Load.getValue(1));
5876       return Load;
5877     }
5878   }
5879
5880   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5881   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5882   // This often reduces constant pool loads.
5883   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5884        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5885       N0.getNode()->hasOneUse() && VT.isInteger() &&
5886       !VT.isVector() && !N0.getValueType().isVector()) {
5887     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5888                                   N0.getOperand(0));
5889     AddToWorkList(NewConv.getNode());
5890
5891     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5892     if (N0.getOpcode() == ISD::FNEG)
5893       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5894                          NewConv, DAG.getConstant(SignBit, VT));
5895     assert(N0.getOpcode() == ISD::FABS);
5896     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5897                        NewConv, DAG.getConstant(~SignBit, VT));
5898   }
5899
5900   // fold (bitconvert (fcopysign cst, x)) ->
5901   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5902   // Note that we don't handle (copysign x, cst) because this can always be
5903   // folded to an fneg or fabs.
5904   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5905       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5906       VT.isInteger() && !VT.isVector()) {
5907     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5908     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5909     if (isTypeLegal(IntXVT)) {
5910       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5911                               IntXVT, N0.getOperand(1));
5912       AddToWorkList(X.getNode());
5913
5914       // If X has a different width than the result/lhs, sext it or truncate it.
5915       unsigned VTWidth = VT.getSizeInBits();
5916       if (OrigXWidth < VTWidth) {
5917         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5918         AddToWorkList(X.getNode());
5919       } else if (OrigXWidth > VTWidth) {
5920         // To get the sign bit in the right place, we have to shift it right
5921         // before truncating.
5922         X = DAG.getNode(ISD::SRL, SDLoc(X),
5923                         X.getValueType(), X,
5924                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5925         AddToWorkList(X.getNode());
5926         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5927         AddToWorkList(X.getNode());
5928       }
5929
5930       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5931       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5932                       X, DAG.getConstant(SignBit, VT));
5933       AddToWorkList(X.getNode());
5934
5935       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5936                                 VT, N0.getOperand(0));
5937       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5938                         Cst, DAG.getConstant(~SignBit, VT));
5939       AddToWorkList(Cst.getNode());
5940
5941       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5942     }
5943   }
5944
5945   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5946   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5947     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5948     if (CombineLD.getNode())
5949       return CombineLD;
5950   }
5951
5952   return SDValue();
5953 }
5954
5955 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5956   EVT VT = N->getValueType(0);
5957   return CombineConsecutiveLoads(N, VT);
5958 }
5959
5960 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5961 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5962 /// destination element value type.
5963 SDValue DAGCombiner::
5964 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5965   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5966
5967   // If this is already the right type, we're done.
5968   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5969
5970   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5971   unsigned DstBitSize = DstEltVT.getSizeInBits();
5972
5973   // If this is a conversion of N elements of one type to N elements of another
5974   // type, convert each element.  This handles FP<->INT cases.
5975   if (SrcBitSize == DstBitSize) {
5976     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5977                               BV->getValueType(0).getVectorNumElements());
5978
5979     // Due to the FP element handling below calling this routine recursively,
5980     // we can end up with a scalar-to-vector node here.
5981     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5982       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5983                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5984                                      DstEltVT, BV->getOperand(0)));
5985
5986     SmallVector<SDValue, 8> Ops;
5987     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5988       SDValue Op = BV->getOperand(i);
5989       // If the vector element type is not legal, the BUILD_VECTOR operands
5990       // are promoted and implicitly truncated.  Make that explicit here.
5991       if (Op.getValueType() != SrcEltVT)
5992         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5993       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5994                                 DstEltVT, Op));
5995       AddToWorkList(Ops.back().getNode());
5996     }
5997     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5998                        &Ops[0], Ops.size());
5999   }
6000
6001   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6002   // handle annoying details of growing/shrinking FP values, we convert them to
6003   // int first.
6004   if (SrcEltVT.isFloatingPoint()) {
6005     // Convert the input float vector to a int vector where the elements are the
6006     // same sizes.
6007     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6008     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6009     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6010     SrcEltVT = IntVT;
6011   }
6012
6013   // Now we know the input is an integer vector.  If the output is a FP type,
6014   // convert to integer first, then to FP of the right size.
6015   if (DstEltVT.isFloatingPoint()) {
6016     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6017     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6018     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6019
6020     // Next, convert to FP elements of the same size.
6021     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6022   }
6023
6024   // Okay, we know the src/dst types are both integers of differing types.
6025   // Handling growing first.
6026   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6027   if (SrcBitSize < DstBitSize) {
6028     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6029
6030     SmallVector<SDValue, 8> Ops;
6031     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6032          i += NumInputsPerOutput) {
6033       bool isLE = TLI.isLittleEndian();
6034       APInt NewBits = APInt(DstBitSize, 0);
6035       bool EltIsUndef = true;
6036       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6037         // Shift the previously computed bits over.
6038         NewBits <<= SrcBitSize;
6039         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6040         if (Op.getOpcode() == ISD::UNDEF) continue;
6041         EltIsUndef = false;
6042
6043         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6044                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6045       }
6046
6047       if (EltIsUndef)
6048         Ops.push_back(DAG.getUNDEF(DstEltVT));
6049       else
6050         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6051     }
6052
6053     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6054     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6055                        &Ops[0], Ops.size());
6056   }
6057
6058   // Finally, this must be the case where we are shrinking elements: each input
6059   // turns into multiple outputs.
6060   bool isS2V = ISD::isScalarToVector(BV);
6061   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6062   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6063                             NumOutputsPerInput*BV->getNumOperands());
6064   SmallVector<SDValue, 8> Ops;
6065
6066   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6067     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6068       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6069         Ops.push_back(DAG.getUNDEF(DstEltVT));
6070       continue;
6071     }
6072
6073     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6074                   getAPIntValue().zextOrTrunc(SrcBitSize);
6075
6076     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6077       APInt ThisVal = OpVal.trunc(DstBitSize);
6078       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6079       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6080         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6081         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6082                            Ops[0]);
6083       OpVal = OpVal.lshr(DstBitSize);
6084     }
6085
6086     // For big endian targets, swap the order of the pieces of each element.
6087     if (TLI.isBigEndian())
6088       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6089   }
6090
6091   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6092                      &Ops[0], Ops.size());
6093 }
6094
6095 SDValue DAGCombiner::visitFADD(SDNode *N) {
6096   SDValue N0 = N->getOperand(0);
6097   SDValue N1 = N->getOperand(1);
6098   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6099   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6100   EVT VT = N->getValueType(0);
6101
6102   // fold vector ops
6103   if (VT.isVector()) {
6104     SDValue FoldedVOp = SimplifyVBinOp(N);
6105     if (FoldedVOp.getNode()) return FoldedVOp;
6106   }
6107
6108   // fold (fadd c1, c2) -> c1 + c2
6109   if (N0CFP && N1CFP)
6110     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6111   // canonicalize constant to RHS
6112   if (N0CFP && !N1CFP)
6113     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6114   // fold (fadd A, 0) -> A
6115   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6116       N1CFP->getValueAPF().isZero())
6117     return N0;
6118   // fold (fadd A, (fneg B)) -> (fsub A, B)
6119   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6120     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6121     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6122                        GetNegatedExpression(N1, DAG, LegalOperations));
6123   // fold (fadd (fneg A), B) -> (fsub B, A)
6124   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6125     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6126     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6127                        GetNegatedExpression(N0, DAG, LegalOperations));
6128
6129   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6130   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6131       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6132       isa<ConstantFPSDNode>(N0.getOperand(1)))
6133     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6134                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6135                                    N0.getOperand(1), N1));
6136
6137   // No FP constant should be created after legalization as Instruction
6138   // Selection pass has hard time in dealing with FP constant.
6139   //
6140   // We don't need test this condition for transformation like following, as
6141   // the DAG being transformed implies it is legal to take FP constant as
6142   // operand.
6143   //
6144   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6145   //
6146   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6147
6148   // If allow, fold (fadd (fneg x), x) -> 0.0
6149   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6150       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6151     return DAG.getConstantFP(0.0, VT);
6152
6153     // If allow, fold (fadd x, (fneg x)) -> 0.0
6154   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6155       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6156     return DAG.getConstantFP(0.0, VT);
6157
6158   // In unsafe math mode, we can fold chains of FADD's of the same value
6159   // into multiplications.  This transform is not safe in general because
6160   // we are reducing the number of rounding steps.
6161   if (DAG.getTarget().Options.UnsafeFPMath &&
6162       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6163       !N0CFP && !N1CFP) {
6164     if (N0.getOpcode() == ISD::FMUL) {
6165       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6166       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6167
6168       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6169       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6170         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6171                                      SDValue(CFP00, 0),
6172                                      DAG.getConstantFP(1.0, VT));
6173         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6174                            N1, NewCFP);
6175       }
6176
6177       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6178       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6179         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6180                                      SDValue(CFP01, 0),
6181                                      DAG.getConstantFP(1.0, VT));
6182         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6183                            N1, NewCFP);
6184       }
6185
6186       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6187       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6188           N1.getOperand(0) == N1.getOperand(1) &&
6189           N0.getOperand(1) == N1.getOperand(0)) {
6190         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6191                                      SDValue(CFP00, 0),
6192                                      DAG.getConstantFP(2.0, VT));
6193         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6194                            N0.getOperand(1), NewCFP);
6195       }
6196
6197       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6198       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6199           N1.getOperand(0) == N1.getOperand(1) &&
6200           N0.getOperand(0) == N1.getOperand(0)) {
6201         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6202                                      SDValue(CFP01, 0),
6203                                      DAG.getConstantFP(2.0, VT));
6204         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6205                            N0.getOperand(0), NewCFP);
6206       }
6207     }
6208
6209     if (N1.getOpcode() == ISD::FMUL) {
6210       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6211       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6212
6213       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6214       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6215         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6216                                      SDValue(CFP10, 0),
6217                                      DAG.getConstantFP(1.0, VT));
6218         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6219                            N0, NewCFP);
6220       }
6221
6222       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6223       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6224         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6225                                      SDValue(CFP11, 0),
6226                                      DAG.getConstantFP(1.0, VT));
6227         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6228                            N0, NewCFP);
6229       }
6230
6231
6232       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6233       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6234           N0.getOperand(0) == N0.getOperand(1) &&
6235           N1.getOperand(1) == N0.getOperand(0)) {
6236         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6237                                      SDValue(CFP10, 0),
6238                                      DAG.getConstantFP(2.0, VT));
6239         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6240                            N1.getOperand(1), NewCFP);
6241       }
6242
6243       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6244       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6245           N0.getOperand(0) == N0.getOperand(1) &&
6246           N1.getOperand(0) == N0.getOperand(0)) {
6247         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6248                                      SDValue(CFP11, 0),
6249                                      DAG.getConstantFP(2.0, VT));
6250         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6251                            N1.getOperand(0), NewCFP);
6252       }
6253     }
6254
6255     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6256       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6257       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6258       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6259           (N0.getOperand(0) == N1))
6260         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6261                            N1, DAG.getConstantFP(3.0, VT));
6262     }
6263
6264     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6265       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6266       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6267       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6268           N1.getOperand(0) == N0)
6269         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6270                            N0, DAG.getConstantFP(3.0, VT));
6271     }
6272
6273     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6274     if (AllowNewFpConst &&
6275         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6276         N0.getOperand(0) == N0.getOperand(1) &&
6277         N1.getOperand(0) == N1.getOperand(1) &&
6278         N0.getOperand(0) == N1.getOperand(0))
6279       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6280                          N0.getOperand(0),
6281                          DAG.getConstantFP(4.0, VT));
6282   }
6283
6284   // FADD -> FMA combines:
6285   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6286        DAG.getTarget().Options.UnsafeFPMath) &&
6287       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6288       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6289
6290     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6291     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6292       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6293                          N0.getOperand(0), N0.getOperand(1), N1);
6294
6295     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6296     // Note: Commutes FADD operands.
6297     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6298       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6299                          N1.getOperand(0), N1.getOperand(1), N0);
6300   }
6301
6302   return SDValue();
6303 }
6304
6305 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6306   SDValue N0 = N->getOperand(0);
6307   SDValue N1 = N->getOperand(1);
6308   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6309   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6310   EVT VT = N->getValueType(0);
6311   SDLoc dl(N);
6312
6313   // fold vector ops
6314   if (VT.isVector()) {
6315     SDValue FoldedVOp = SimplifyVBinOp(N);
6316     if (FoldedVOp.getNode()) return FoldedVOp;
6317   }
6318
6319   // fold (fsub c1, c2) -> c1-c2
6320   if (N0CFP && N1CFP)
6321     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6322   // fold (fsub A, 0) -> A
6323   if (DAG.getTarget().Options.UnsafeFPMath &&
6324       N1CFP && N1CFP->getValueAPF().isZero())
6325     return N0;
6326   // fold (fsub 0, B) -> -B
6327   if (DAG.getTarget().Options.UnsafeFPMath &&
6328       N0CFP && N0CFP->getValueAPF().isZero()) {
6329     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6330       return GetNegatedExpression(N1, DAG, LegalOperations);
6331     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6332       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6333   }
6334   // fold (fsub A, (fneg B)) -> (fadd A, B)
6335   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6336     return DAG.getNode(ISD::FADD, dl, VT, N0,
6337                        GetNegatedExpression(N1, DAG, LegalOperations));
6338
6339   // If 'unsafe math' is enabled, fold
6340   //    (fsub x, x) -> 0.0 &
6341   //    (fsub x, (fadd x, y)) -> (fneg y) &
6342   //    (fsub x, (fadd y, x)) -> (fneg y)
6343   if (DAG.getTarget().Options.UnsafeFPMath) {
6344     if (N0 == N1)
6345       return DAG.getConstantFP(0.0f, VT);
6346
6347     if (N1.getOpcode() == ISD::FADD) {
6348       SDValue N10 = N1->getOperand(0);
6349       SDValue N11 = N1->getOperand(1);
6350
6351       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6352                                           &DAG.getTarget().Options))
6353         return GetNegatedExpression(N11, DAG, LegalOperations);
6354
6355       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6356                                           &DAG.getTarget().Options))
6357         return GetNegatedExpression(N10, DAG, LegalOperations);
6358     }
6359   }
6360
6361   // FSUB -> FMA combines:
6362   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6363        DAG.getTarget().Options.UnsafeFPMath) &&
6364       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6365       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6366
6367     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6368     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6369       return DAG.getNode(ISD::FMA, dl, VT,
6370                          N0.getOperand(0), N0.getOperand(1),
6371                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6372
6373     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6374     // Note: Commutes FSUB operands.
6375     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6376       return DAG.getNode(ISD::FMA, dl, VT,
6377                          DAG.getNode(ISD::FNEG, dl, VT,
6378                          N1.getOperand(0)),
6379                          N1.getOperand(1), N0);
6380
6381     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6382     if (N0.getOpcode() == ISD::FNEG &&
6383         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6384         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6385       SDValue N00 = N0.getOperand(0).getOperand(0);
6386       SDValue N01 = N0.getOperand(0).getOperand(1);
6387       return DAG.getNode(ISD::FMA, dl, VT,
6388                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6389                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6390     }
6391   }
6392
6393   return SDValue();
6394 }
6395
6396 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6397   SDValue N0 = N->getOperand(0);
6398   SDValue N1 = N->getOperand(1);
6399   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6400   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6401   EVT VT = N->getValueType(0);
6402   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6403
6404   // fold vector ops
6405   if (VT.isVector()) {
6406     SDValue FoldedVOp = SimplifyVBinOp(N);
6407     if (FoldedVOp.getNode()) return FoldedVOp;
6408   }
6409
6410   // fold (fmul c1, c2) -> c1*c2
6411   if (N0CFP && N1CFP)
6412     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6413   // canonicalize constant to RHS
6414   if (N0CFP && !N1CFP)
6415     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6416   // fold (fmul A, 0) -> 0
6417   if (DAG.getTarget().Options.UnsafeFPMath &&
6418       N1CFP && N1CFP->getValueAPF().isZero())
6419     return N1;
6420   // fold (fmul A, 0) -> 0, vector edition.
6421   if (DAG.getTarget().Options.UnsafeFPMath &&
6422       ISD::isBuildVectorAllZeros(N1.getNode()))
6423     return N1;
6424   // fold (fmul A, 1.0) -> A
6425   if (N1CFP && N1CFP->isExactlyValue(1.0))
6426     return N0;
6427   // fold (fmul X, 2.0) -> (fadd X, X)
6428   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6429     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6430   // fold (fmul X, -1.0) -> (fneg X)
6431   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6432     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6433       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6434
6435   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6436   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6437                                        &DAG.getTarget().Options)) {
6438     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6439                                          &DAG.getTarget().Options)) {
6440       // Both can be negated for free, check to see if at least one is cheaper
6441       // negated.
6442       if (LHSNeg == 2 || RHSNeg == 2)
6443         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6444                            GetNegatedExpression(N0, DAG, LegalOperations),
6445                            GetNegatedExpression(N1, DAG, LegalOperations));
6446     }
6447   }
6448
6449   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6450   if (DAG.getTarget().Options.UnsafeFPMath &&
6451       N1CFP && N0.getOpcode() == ISD::FMUL &&
6452       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6453     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6454                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6455                                    N0.getOperand(1), N1));
6456
6457   return SDValue();
6458 }
6459
6460 SDValue DAGCombiner::visitFMA(SDNode *N) {
6461   SDValue N0 = N->getOperand(0);
6462   SDValue N1 = N->getOperand(1);
6463   SDValue N2 = N->getOperand(2);
6464   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6465   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6466   EVT VT = N->getValueType(0);
6467   SDLoc dl(N);
6468
6469   if (DAG.getTarget().Options.UnsafeFPMath) {
6470     if (N0CFP && N0CFP->isZero())
6471       return N2;
6472     if (N1CFP && N1CFP->isZero())
6473       return N2;
6474   }
6475   if (N0CFP && N0CFP->isExactlyValue(1.0))
6476     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6477   if (N1CFP && N1CFP->isExactlyValue(1.0))
6478     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6479
6480   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6481   if (N0CFP && !N1CFP)
6482     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6483
6484   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6485   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6486       N2.getOpcode() == ISD::FMUL &&
6487       N0 == N2.getOperand(0) &&
6488       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6489     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6490                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6491   }
6492
6493
6494   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6495   if (DAG.getTarget().Options.UnsafeFPMath &&
6496       N0.getOpcode() == ISD::FMUL && N1CFP &&
6497       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6498     return DAG.getNode(ISD::FMA, dl, VT,
6499                        N0.getOperand(0),
6500                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6501                        N2);
6502   }
6503
6504   // (fma x, 1, y) -> (fadd x, y)
6505   // (fma x, -1, y) -> (fadd (fneg x), y)
6506   if (N1CFP) {
6507     if (N1CFP->isExactlyValue(1.0))
6508       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6509
6510     if (N1CFP->isExactlyValue(-1.0) &&
6511         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6512       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6513       AddToWorkList(RHSNeg.getNode());
6514       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6515     }
6516   }
6517
6518   // (fma x, c, x) -> (fmul x, (c+1))
6519   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6520     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6521                        DAG.getNode(ISD::FADD, dl, VT,
6522                                    N1, DAG.getConstantFP(1.0, VT)));
6523
6524   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6525   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6526       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6527     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6528                        DAG.getNode(ISD::FADD, dl, VT,
6529                                    N1, DAG.getConstantFP(-1.0, VT)));
6530
6531
6532   return SDValue();
6533 }
6534
6535 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6536   SDValue N0 = N->getOperand(0);
6537   SDValue N1 = N->getOperand(1);
6538   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6539   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6540   EVT VT = N->getValueType(0);
6541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6542
6543   // fold vector ops
6544   if (VT.isVector()) {
6545     SDValue FoldedVOp = SimplifyVBinOp(N);
6546     if (FoldedVOp.getNode()) return FoldedVOp;
6547   }
6548
6549   // fold (fdiv c1, c2) -> c1/c2
6550   if (N0CFP && N1CFP)
6551     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6552
6553   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6554   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6555     // Compute the reciprocal 1.0 / c2.
6556     APFloat N1APF = N1CFP->getValueAPF();
6557     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6558     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6559     // Only do the transform if the reciprocal is a legal fp immediate that
6560     // isn't too nasty (eg NaN, denormal, ...).
6561     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6562         (!LegalOperations ||
6563          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6564          // backend)... we should handle this gracefully after Legalize.
6565          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6566          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6567          TLI.isFPImmLegal(Recip, VT)))
6568       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6569                          DAG.getConstantFP(Recip, VT));
6570   }
6571
6572   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6573   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6574                                        &DAG.getTarget().Options)) {
6575     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6576                                          &DAG.getTarget().Options)) {
6577       // Both can be negated for free, check to see if at least one is cheaper
6578       // negated.
6579       if (LHSNeg == 2 || RHSNeg == 2)
6580         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6581                            GetNegatedExpression(N0, DAG, LegalOperations),
6582                            GetNegatedExpression(N1, DAG, LegalOperations));
6583     }
6584   }
6585
6586   return SDValue();
6587 }
6588
6589 SDValue DAGCombiner::visitFREM(SDNode *N) {
6590   SDValue N0 = N->getOperand(0);
6591   SDValue N1 = N->getOperand(1);
6592   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6593   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6594   EVT VT = N->getValueType(0);
6595
6596   // fold (frem c1, c2) -> fmod(c1,c2)
6597   if (N0CFP && N1CFP)
6598     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6599
6600   return SDValue();
6601 }
6602
6603 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6604   SDValue N0 = N->getOperand(0);
6605   SDValue N1 = N->getOperand(1);
6606   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6607   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6608   EVT VT = N->getValueType(0);
6609
6610   if (N0CFP && N1CFP)  // Constant fold
6611     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6612
6613   if (N1CFP) {
6614     const APFloat& V = N1CFP->getValueAPF();
6615     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6616     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6617     if (!V.isNegative()) {
6618       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6619         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6620     } else {
6621       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6622         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6623                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6624     }
6625   }
6626
6627   // copysign(fabs(x), y) -> copysign(x, y)
6628   // copysign(fneg(x), y) -> copysign(x, y)
6629   // copysign(copysign(x,z), y) -> copysign(x, y)
6630   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6631       N0.getOpcode() == ISD::FCOPYSIGN)
6632     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6633                        N0.getOperand(0), N1);
6634
6635   // copysign(x, abs(y)) -> abs(x)
6636   if (N1.getOpcode() == ISD::FABS)
6637     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6638
6639   // copysign(x, copysign(y,z)) -> copysign(x, z)
6640   if (N1.getOpcode() == ISD::FCOPYSIGN)
6641     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6642                        N0, N1.getOperand(1));
6643
6644   // copysign(x, fp_extend(y)) -> copysign(x, y)
6645   // copysign(x, fp_round(y)) -> copysign(x, y)
6646   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6647     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6648                        N0, N1.getOperand(0));
6649
6650   return SDValue();
6651 }
6652
6653 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6654   SDValue N0 = N->getOperand(0);
6655   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6656   EVT VT = N->getValueType(0);
6657   EVT OpVT = N0.getValueType();
6658
6659   // fold (sint_to_fp c1) -> c1fp
6660   if (N0C &&
6661       // ...but only if the target supports immediate floating-point values
6662       (!LegalOperations ||
6663        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6664     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6665
6666   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6667   // but UINT_TO_FP is legal on this target, try to convert.
6668   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6669       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6670     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6671     if (DAG.SignBitIsZero(N0))
6672       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6673   }
6674
6675   // The next optimizations are desireable only if SELECT_CC can be lowered.
6676   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6677   // having to say they don't support SELECT_CC on every type the DAG knows
6678   // about, since there is no way to mark an opcode illegal at all value types
6679   // (See also visitSELECT)
6680   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6681     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6682     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6683         !VT.isVector() &&
6684         (!LegalOperations ||
6685          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6686       SDValue Ops[] =
6687         { N0.getOperand(0), N0.getOperand(1),
6688           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6689           N0.getOperand(2) };
6690       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6691     }
6692
6693     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6694     //      (select_cc x, y, 1.0, 0.0,, cc)
6695     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6696         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6697         (!LegalOperations ||
6698          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6699       SDValue Ops[] =
6700         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6701           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6702           N0.getOperand(0).getOperand(2) };
6703       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6704     }
6705   }
6706
6707   return SDValue();
6708 }
6709
6710 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6711   SDValue N0 = N->getOperand(0);
6712   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6713   EVT VT = N->getValueType(0);
6714   EVT OpVT = N0.getValueType();
6715
6716   // fold (uint_to_fp c1) -> c1fp
6717   if (N0C &&
6718       // ...but only if the target supports immediate floating-point values
6719       (!LegalOperations ||
6720        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6721     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6722
6723   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6724   // but SINT_TO_FP is legal on this target, try to convert.
6725   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6726       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6727     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6728     if (DAG.SignBitIsZero(N0))
6729       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6730   }
6731
6732   // The next optimizations are desireable only if SELECT_CC can be lowered.
6733   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6734   // having to say they don't support SELECT_CC on every type the DAG knows
6735   // about, since there is no way to mark an opcode illegal at all value types
6736   // (See also visitSELECT)
6737   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6738     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6739
6740     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6741         (!LegalOperations ||
6742          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6743       SDValue Ops[] =
6744         { N0.getOperand(0), N0.getOperand(1),
6745           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6746           N0.getOperand(2) };
6747       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6748     }
6749   }
6750
6751   return SDValue();
6752 }
6753
6754 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6755   SDValue N0 = N->getOperand(0);
6756   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6757   EVT VT = N->getValueType(0);
6758
6759   // fold (fp_to_sint c1fp) -> c1
6760   if (N0CFP)
6761     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6762
6763   return SDValue();
6764 }
6765
6766 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6767   SDValue N0 = N->getOperand(0);
6768   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6769   EVT VT = N->getValueType(0);
6770
6771   // fold (fp_to_uint c1fp) -> c1
6772   if (N0CFP)
6773     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6774
6775   return SDValue();
6776 }
6777
6778 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6779   SDValue N0 = N->getOperand(0);
6780   SDValue N1 = N->getOperand(1);
6781   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6782   EVT VT = N->getValueType(0);
6783
6784   // fold (fp_round c1fp) -> c1fp
6785   if (N0CFP)
6786     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6787
6788   // fold (fp_round (fp_extend x)) -> x
6789   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6790     return N0.getOperand(0);
6791
6792   // fold (fp_round (fp_round x)) -> (fp_round x)
6793   if (N0.getOpcode() == ISD::FP_ROUND) {
6794     // This is a value preserving truncation if both round's are.
6795     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6796                    N0.getNode()->getConstantOperandVal(1) == 1;
6797     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6798                        DAG.getIntPtrConstant(IsTrunc));
6799   }
6800
6801   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6802   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6803     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6804                               N0.getOperand(0), N1);
6805     AddToWorkList(Tmp.getNode());
6806     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6807                        Tmp, N0.getOperand(1));
6808   }
6809
6810   return SDValue();
6811 }
6812
6813 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6814   SDValue N0 = N->getOperand(0);
6815   EVT VT = N->getValueType(0);
6816   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6817   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6818
6819   // fold (fp_round_inreg c1fp) -> c1fp
6820   if (N0CFP && isTypeLegal(EVT)) {
6821     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6822     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6823   }
6824
6825   return SDValue();
6826 }
6827
6828 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6829   SDValue N0 = N->getOperand(0);
6830   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6831   EVT VT = N->getValueType(0);
6832
6833   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6834   if (N->hasOneUse() &&
6835       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6836     return SDValue();
6837
6838   // fold (fp_extend c1fp) -> c1fp
6839   if (N0CFP)
6840     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6841
6842   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6843   // value of X.
6844   if (N0.getOpcode() == ISD::FP_ROUND
6845       && N0.getNode()->getConstantOperandVal(1) == 1) {
6846     SDValue In = N0.getOperand(0);
6847     if (In.getValueType() == VT) return In;
6848     if (VT.bitsLT(In.getValueType()))
6849       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6850                          In, N0.getOperand(1));
6851     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6852   }
6853
6854   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6855   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6856       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6857        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6858     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6859     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6860                                      LN0->getChain(),
6861                                      LN0->getBasePtr(), N0.getValueType(),
6862                                      LN0->getMemOperand());
6863     CombineTo(N, ExtLoad);
6864     CombineTo(N0.getNode(),
6865               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6866                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6867               ExtLoad.getValue(1));
6868     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6869   }
6870
6871   return SDValue();
6872 }
6873
6874 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6875   SDValue N0 = N->getOperand(0);
6876   EVT VT = N->getValueType(0);
6877
6878   if (VT.isVector()) {
6879     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6880     if (FoldedVOp.getNode()) return FoldedVOp;
6881   }
6882
6883   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6884                          &DAG.getTarget().Options))
6885     return GetNegatedExpression(N0, DAG, LegalOperations);
6886
6887   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6888   // constant pool values.
6889   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6890       !VT.isVector() &&
6891       N0.getNode()->hasOneUse() &&
6892       N0.getOperand(0).getValueType().isInteger()) {
6893     SDValue Int = N0.getOperand(0);
6894     EVT IntVT = Int.getValueType();
6895     if (IntVT.isInteger() && !IntVT.isVector()) {
6896       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6897               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6898       AddToWorkList(Int.getNode());
6899       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6900                          VT, Int);
6901     }
6902   }
6903
6904   // (fneg (fmul c, x)) -> (fmul -c, x)
6905   if (N0.getOpcode() == ISD::FMUL) {
6906     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6907     if (CFP1)
6908       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6909                          N0.getOperand(0),
6910                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6911                                      N0.getOperand(1)));
6912   }
6913
6914   return SDValue();
6915 }
6916
6917 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6918   SDValue N0 = N->getOperand(0);
6919   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6920   EVT VT = N->getValueType(0);
6921
6922   // fold (fceil c1) -> fceil(c1)
6923   if (N0CFP)
6924     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6925
6926   return SDValue();
6927 }
6928
6929 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6930   SDValue N0 = N->getOperand(0);
6931   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6932   EVT VT = N->getValueType(0);
6933
6934   // fold (ftrunc c1) -> ftrunc(c1)
6935   if (N0CFP)
6936     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6937
6938   return SDValue();
6939 }
6940
6941 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6942   SDValue N0 = N->getOperand(0);
6943   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6944   EVT VT = N->getValueType(0);
6945
6946   // fold (ffloor c1) -> ffloor(c1)
6947   if (N0CFP)
6948     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6949
6950   return SDValue();
6951 }
6952
6953 SDValue DAGCombiner::visitFABS(SDNode *N) {
6954   SDValue N0 = N->getOperand(0);
6955   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6956   EVT VT = N->getValueType(0);
6957
6958   if (VT.isVector()) {
6959     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6960     if (FoldedVOp.getNode()) return FoldedVOp;
6961   }
6962
6963   // fold (fabs c1) -> fabs(c1)
6964   if (N0CFP)
6965     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6966   // fold (fabs (fabs x)) -> (fabs x)
6967   if (N0.getOpcode() == ISD::FABS)
6968     return N->getOperand(0);
6969   // fold (fabs (fneg x)) -> (fabs x)
6970   // fold (fabs (fcopysign x, y)) -> (fabs x)
6971   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6972     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6973
6974   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6975   // constant pool values.
6976   if (!TLI.isFAbsFree(VT) &&
6977       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6978       N0.getOperand(0).getValueType().isInteger() &&
6979       !N0.getOperand(0).getValueType().isVector()) {
6980     SDValue Int = N0.getOperand(0);
6981     EVT IntVT = Int.getValueType();
6982     if (IntVT.isInteger() && !IntVT.isVector()) {
6983       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6984              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6985       AddToWorkList(Int.getNode());
6986       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6987                          N->getValueType(0), Int);
6988     }
6989   }
6990
6991   return SDValue();
6992 }
6993
6994 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6995   SDValue Chain = N->getOperand(0);
6996   SDValue N1 = N->getOperand(1);
6997   SDValue N2 = N->getOperand(2);
6998
6999   // If N is a constant we could fold this into a fallthrough or unconditional
7000   // branch. However that doesn't happen very often in normal code, because
7001   // Instcombine/SimplifyCFG should have handled the available opportunities.
7002   // If we did this folding here, it would be necessary to update the
7003   // MachineBasicBlock CFG, which is awkward.
7004
7005   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7006   // on the target.
7007   if (N1.getOpcode() == ISD::SETCC &&
7008       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7009                                    N1.getOperand(0).getValueType())) {
7010     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7011                        Chain, N1.getOperand(2),
7012                        N1.getOperand(0), N1.getOperand(1), N2);
7013   }
7014
7015   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7016       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7017        (N1.getOperand(0).hasOneUse() &&
7018         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7019     SDNode *Trunc = 0;
7020     if (N1.getOpcode() == ISD::TRUNCATE) {
7021       // Look pass the truncate.
7022       Trunc = N1.getNode();
7023       N1 = N1.getOperand(0);
7024     }
7025
7026     // Match this pattern so that we can generate simpler code:
7027     //
7028     //   %a = ...
7029     //   %b = and i32 %a, 2
7030     //   %c = srl i32 %b, 1
7031     //   brcond i32 %c ...
7032     //
7033     // into
7034     //
7035     //   %a = ...
7036     //   %b = and i32 %a, 2
7037     //   %c = setcc eq %b, 0
7038     //   brcond %c ...
7039     //
7040     // This applies only when the AND constant value has one bit set and the
7041     // SRL constant is equal to the log2 of the AND constant. The back-end is
7042     // smart enough to convert the result into a TEST/JMP sequence.
7043     SDValue Op0 = N1.getOperand(0);
7044     SDValue Op1 = N1.getOperand(1);
7045
7046     if (Op0.getOpcode() == ISD::AND &&
7047         Op1.getOpcode() == ISD::Constant) {
7048       SDValue AndOp1 = Op0.getOperand(1);
7049
7050       if (AndOp1.getOpcode() == ISD::Constant) {
7051         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7052
7053         if (AndConst.isPowerOf2() &&
7054             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7055           SDValue SetCC =
7056             DAG.getSetCC(SDLoc(N),
7057                          getSetCCResultType(Op0.getValueType()),
7058                          Op0, DAG.getConstant(0, Op0.getValueType()),
7059                          ISD::SETNE);
7060
7061           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7062                                           MVT::Other, Chain, SetCC, N2);
7063           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7064           // will convert it back to (X & C1) >> C2.
7065           CombineTo(N, NewBRCond, false);
7066           // Truncate is dead.
7067           if (Trunc) {
7068             removeFromWorkList(Trunc);
7069             DAG.DeleteNode(Trunc);
7070           }
7071           // Replace the uses of SRL with SETCC
7072           WorkListRemover DeadNodes(*this);
7073           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7074           removeFromWorkList(N1.getNode());
7075           DAG.DeleteNode(N1.getNode());
7076           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7077         }
7078       }
7079     }
7080
7081     if (Trunc)
7082       // Restore N1 if the above transformation doesn't match.
7083       N1 = N->getOperand(1);
7084   }
7085
7086   // Transform br(xor(x, y)) -> br(x != y)
7087   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7088   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7089     SDNode *TheXor = N1.getNode();
7090     SDValue Op0 = TheXor->getOperand(0);
7091     SDValue Op1 = TheXor->getOperand(1);
7092     if (Op0.getOpcode() == Op1.getOpcode()) {
7093       // Avoid missing important xor optimizations.
7094       SDValue Tmp = visitXOR(TheXor);
7095       if (Tmp.getNode()) {
7096         if (Tmp.getNode() != TheXor) {
7097           DEBUG(dbgs() << "\nReplacing.8 ";
7098                 TheXor->dump(&DAG);
7099                 dbgs() << "\nWith: ";
7100                 Tmp.getNode()->dump(&DAG);
7101                 dbgs() << '\n');
7102           WorkListRemover DeadNodes(*this);
7103           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7104           removeFromWorkList(TheXor);
7105           DAG.DeleteNode(TheXor);
7106           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7107                              MVT::Other, Chain, Tmp, N2);
7108         }
7109
7110         // visitXOR has changed XOR's operands or replaced the XOR completely,
7111         // bail out.
7112         return SDValue(N, 0);
7113       }
7114     }
7115
7116     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7117       bool Equal = false;
7118       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7119         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7120             Op0.getOpcode() == ISD::XOR) {
7121           TheXor = Op0.getNode();
7122           Equal = true;
7123         }
7124
7125       EVT SetCCVT = N1.getValueType();
7126       if (LegalTypes)
7127         SetCCVT = getSetCCResultType(SetCCVT);
7128       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7129                                    SetCCVT,
7130                                    Op0, Op1,
7131                                    Equal ? ISD::SETEQ : ISD::SETNE);
7132       // Replace the uses of XOR with SETCC
7133       WorkListRemover DeadNodes(*this);
7134       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7135       removeFromWorkList(N1.getNode());
7136       DAG.DeleteNode(N1.getNode());
7137       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7138                          MVT::Other, Chain, SetCC, N2);
7139     }
7140   }
7141
7142   return SDValue();
7143 }
7144
7145 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7146 //
7147 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7148   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7149   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7150
7151   // If N is a constant we could fold this into a fallthrough or unconditional
7152   // branch. However that doesn't happen very often in normal code, because
7153   // Instcombine/SimplifyCFG should have handled the available opportunities.
7154   // If we did this folding here, it would be necessary to update the
7155   // MachineBasicBlock CFG, which is awkward.
7156
7157   // Use SimplifySetCC to simplify SETCC's.
7158   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7159                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7160                                false);
7161   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7162
7163   // fold to a simpler setcc
7164   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7165     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7166                        N->getOperand(0), Simp.getOperand(2),
7167                        Simp.getOperand(0), Simp.getOperand(1),
7168                        N->getOperand(4));
7169
7170   return SDValue();
7171 }
7172
7173 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7174 /// uses N as its base pointer and that N may be folded in the load / store
7175 /// addressing mode.
7176 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7177                                     SelectionDAG &DAG,
7178                                     const TargetLowering &TLI) {
7179   EVT VT;
7180   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7181     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7182       return false;
7183     VT = Use->getValueType(0);
7184   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7185     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7186       return false;
7187     VT = ST->getValue().getValueType();
7188   } else
7189     return false;
7190
7191   TargetLowering::AddrMode AM;
7192   if (N->getOpcode() == ISD::ADD) {
7193     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7194     if (Offset)
7195       // [reg +/- imm]
7196       AM.BaseOffs = Offset->getSExtValue();
7197     else
7198       // [reg +/- reg]
7199       AM.Scale = 1;
7200   } else if (N->getOpcode() == ISD::SUB) {
7201     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7202     if (Offset)
7203       // [reg +/- imm]
7204       AM.BaseOffs = -Offset->getSExtValue();
7205     else
7206       // [reg +/- reg]
7207       AM.Scale = 1;
7208   } else
7209     return false;
7210
7211   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7212 }
7213
7214 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7215 /// pre-indexed load / store when the base pointer is an add or subtract
7216 /// and it has other uses besides the load / store. After the
7217 /// transformation, the new indexed load / store has effectively folded
7218 /// the add / subtract in and all of its other uses are redirected to the
7219 /// new load / store.
7220 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7221   if (Level < AfterLegalizeDAG)
7222     return false;
7223
7224   bool isLoad = true;
7225   SDValue Ptr;
7226   EVT VT;
7227   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7228     if (LD->isIndexed())
7229       return false;
7230     VT = LD->getMemoryVT();
7231     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7232         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7233       return false;
7234     Ptr = LD->getBasePtr();
7235   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7236     if (ST->isIndexed())
7237       return false;
7238     VT = ST->getMemoryVT();
7239     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7240         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7241       return false;
7242     Ptr = ST->getBasePtr();
7243     isLoad = false;
7244   } else {
7245     return false;
7246   }
7247
7248   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7249   // out.  There is no reason to make this a preinc/predec.
7250   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7251       Ptr.getNode()->hasOneUse())
7252     return false;
7253
7254   // Ask the target to do addressing mode selection.
7255   SDValue BasePtr;
7256   SDValue Offset;
7257   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7258   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7259     return false;
7260
7261   // Backends without true r+i pre-indexed forms may need to pass a
7262   // constant base with a variable offset so that constant coercion
7263   // will work with the patterns in canonical form.
7264   bool Swapped = false;
7265   if (isa<ConstantSDNode>(BasePtr)) {
7266     std::swap(BasePtr, Offset);
7267     Swapped = true;
7268   }
7269
7270   // Don't create a indexed load / store with zero offset.
7271   if (isa<ConstantSDNode>(Offset) &&
7272       cast<ConstantSDNode>(Offset)->isNullValue())
7273     return false;
7274
7275   // Try turning it into a pre-indexed load / store except when:
7276   // 1) The new base ptr is a frame index.
7277   // 2) If N is a store and the new base ptr is either the same as or is a
7278   //    predecessor of the value being stored.
7279   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7280   //    that would create a cycle.
7281   // 4) All uses are load / store ops that use it as old base ptr.
7282
7283   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7284   // (plus the implicit offset) to a register to preinc anyway.
7285   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7286     return false;
7287
7288   // Check #2.
7289   if (!isLoad) {
7290     SDValue Val = cast<StoreSDNode>(N)->getValue();
7291     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7292       return false;
7293   }
7294
7295   // If the offset is a constant, there may be other adds of constants that
7296   // can be folded with this one. We should do this to avoid having to keep
7297   // a copy of the original base pointer.
7298   SmallVector<SDNode *, 16> OtherUses;
7299   if (isa<ConstantSDNode>(Offset))
7300     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7301          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7302       SDNode *Use = *I;
7303       if (Use == Ptr.getNode())
7304         continue;
7305
7306       if (Use->isPredecessorOf(N))
7307         continue;
7308
7309       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7310         OtherUses.clear();
7311         break;
7312       }
7313
7314       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7315       if (Op1.getNode() == BasePtr.getNode())
7316         std::swap(Op0, Op1);
7317       assert(Op0.getNode() == BasePtr.getNode() &&
7318              "Use of ADD/SUB but not an operand");
7319
7320       if (!isa<ConstantSDNode>(Op1)) {
7321         OtherUses.clear();
7322         break;
7323       }
7324
7325       // FIXME: In some cases, we can be smarter about this.
7326       if (Op1.getValueType() != Offset.getValueType()) {
7327         OtherUses.clear();
7328         break;
7329       }
7330
7331       OtherUses.push_back(Use);
7332     }
7333
7334   if (Swapped)
7335     std::swap(BasePtr, Offset);
7336
7337   // Now check for #3 and #4.
7338   bool RealUse = false;
7339
7340   // Caches for hasPredecessorHelper
7341   SmallPtrSet<const SDNode *, 32> Visited;
7342   SmallVector<const SDNode *, 16> Worklist;
7343
7344   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7345          E = Ptr.getNode()->use_end(); I != E; ++I) {
7346     SDNode *Use = *I;
7347     if (Use == N)
7348       continue;
7349     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7350       return false;
7351
7352     // If Ptr may be folded in addressing mode of other use, then it's
7353     // not profitable to do this transformation.
7354     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7355       RealUse = true;
7356   }
7357
7358   if (!RealUse)
7359     return false;
7360
7361   SDValue Result;
7362   if (isLoad)
7363     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7364                                 BasePtr, Offset, AM);
7365   else
7366     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7367                                  BasePtr, Offset, AM);
7368   ++PreIndexedNodes;
7369   ++NodesCombined;
7370   DEBUG(dbgs() << "\nReplacing.4 ";
7371         N->dump(&DAG);
7372         dbgs() << "\nWith: ";
7373         Result.getNode()->dump(&DAG);
7374         dbgs() << '\n');
7375   WorkListRemover DeadNodes(*this);
7376   if (isLoad) {
7377     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7378     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7379   } else {
7380     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7381   }
7382
7383   // Finally, since the node is now dead, remove it from the graph.
7384   DAG.DeleteNode(N);
7385
7386   if (Swapped)
7387     std::swap(BasePtr, Offset);
7388
7389   // Replace other uses of BasePtr that can be updated to use Ptr
7390   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7391     unsigned OffsetIdx = 1;
7392     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7393       OffsetIdx = 0;
7394     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7395            BasePtr.getNode() && "Expected BasePtr operand");
7396
7397     // We need to replace ptr0 in the following expression:
7398     //   x0 * offset0 + y0 * ptr0 = t0
7399     // knowing that
7400     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7401     //
7402     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7403     // indexed load/store and the expresion that needs to be re-written.
7404     //
7405     // Therefore, we have:
7406     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7407
7408     ConstantSDNode *CN =
7409       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7410     int X0, X1, Y0, Y1;
7411     APInt Offset0 = CN->getAPIntValue();
7412     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7413
7414     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7415     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7416     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7417     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7418
7419     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7420
7421     APInt CNV = Offset0;
7422     if (X0 < 0) CNV = -CNV;
7423     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7424     else CNV = CNV - Offset1;
7425
7426     // We can now generate the new expression.
7427     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7428     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7429
7430     SDValue NewUse = DAG.getNode(Opcode,
7431                                  SDLoc(OtherUses[i]),
7432                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7433     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7434     removeFromWorkList(OtherUses[i]);
7435     DAG.DeleteNode(OtherUses[i]);
7436   }
7437
7438   // Replace the uses of Ptr with uses of the updated base value.
7439   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7440   removeFromWorkList(Ptr.getNode());
7441   DAG.DeleteNode(Ptr.getNode());
7442
7443   return true;
7444 }
7445
7446 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7447 /// add / sub of the base pointer node into a post-indexed load / store.
7448 /// The transformation folded the add / subtract into the new indexed
7449 /// load / store effectively and all of its uses are redirected to the
7450 /// new load / store.
7451 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7452   if (Level < AfterLegalizeDAG)
7453     return false;
7454
7455   bool isLoad = true;
7456   SDValue Ptr;
7457   EVT VT;
7458   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7459     if (LD->isIndexed())
7460       return false;
7461     VT = LD->getMemoryVT();
7462     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7463         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7464       return false;
7465     Ptr = LD->getBasePtr();
7466   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7467     if (ST->isIndexed())
7468       return false;
7469     VT = ST->getMemoryVT();
7470     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7471         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7472       return false;
7473     Ptr = ST->getBasePtr();
7474     isLoad = false;
7475   } else {
7476     return false;
7477   }
7478
7479   if (Ptr.getNode()->hasOneUse())
7480     return false;
7481
7482   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7483          E = Ptr.getNode()->use_end(); I != E; ++I) {
7484     SDNode *Op = *I;
7485     if (Op == N ||
7486         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7487       continue;
7488
7489     SDValue BasePtr;
7490     SDValue Offset;
7491     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7492     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7493       // Don't create a indexed load / store with zero offset.
7494       if (isa<ConstantSDNode>(Offset) &&
7495           cast<ConstantSDNode>(Offset)->isNullValue())
7496         continue;
7497
7498       // Try turning it into a post-indexed load / store except when
7499       // 1) All uses are load / store ops that use it as base ptr (and
7500       //    it may be folded as addressing mmode).
7501       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7502       //    nor a successor of N. Otherwise, if Op is folded that would
7503       //    create a cycle.
7504
7505       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7506         continue;
7507
7508       // Check for #1.
7509       bool TryNext = false;
7510       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7511              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7512         SDNode *Use = *II;
7513         if (Use == Ptr.getNode())
7514           continue;
7515
7516         // If all the uses are load / store addresses, then don't do the
7517         // transformation.
7518         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7519           bool RealUse = false;
7520           for (SDNode::use_iterator III = Use->use_begin(),
7521                  EEE = Use->use_end(); III != EEE; ++III) {
7522             SDNode *UseUse = *III;
7523             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7524               RealUse = true;
7525           }
7526
7527           if (!RealUse) {
7528             TryNext = true;
7529             break;
7530           }
7531         }
7532       }
7533
7534       if (TryNext)
7535         continue;
7536
7537       // Check for #2
7538       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7539         SDValue Result = isLoad
7540           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7541                                BasePtr, Offset, AM)
7542           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7543                                 BasePtr, Offset, AM);
7544         ++PostIndexedNodes;
7545         ++NodesCombined;
7546         DEBUG(dbgs() << "\nReplacing.5 ";
7547               N->dump(&DAG);
7548               dbgs() << "\nWith: ";
7549               Result.getNode()->dump(&DAG);
7550               dbgs() << '\n');
7551         WorkListRemover DeadNodes(*this);
7552         if (isLoad) {
7553           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7554           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7555         } else {
7556           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7557         }
7558
7559         // Finally, since the node is now dead, remove it from the graph.
7560         DAG.DeleteNode(N);
7561
7562         // Replace the uses of Use with uses of the updated base value.
7563         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7564                                       Result.getValue(isLoad ? 1 : 0));
7565         removeFromWorkList(Op);
7566         DAG.DeleteNode(Op);
7567         return true;
7568       }
7569     }
7570   }
7571
7572   return false;
7573 }
7574
7575 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7576   LoadSDNode *LD  = cast<LoadSDNode>(N);
7577   SDValue Chain = LD->getChain();
7578   SDValue Ptr   = LD->getBasePtr();
7579
7580   // If load is not volatile and there are no uses of the loaded value (and
7581   // the updated indexed value in case of indexed loads), change uses of the
7582   // chain value into uses of the chain input (i.e. delete the dead load).
7583   if (!LD->isVolatile()) {
7584     if (N->getValueType(1) == MVT::Other) {
7585       // Unindexed loads.
7586       if (!N->hasAnyUseOfValue(0)) {
7587         // It's not safe to use the two value CombineTo variant here. e.g.
7588         // v1, chain2 = load chain1, loc
7589         // v2, chain3 = load chain2, loc
7590         // v3         = add v2, c
7591         // Now we replace use of chain2 with chain1.  This makes the second load
7592         // isomorphic to the one we are deleting, and thus makes this load live.
7593         DEBUG(dbgs() << "\nReplacing.6 ";
7594               N->dump(&DAG);
7595               dbgs() << "\nWith chain: ";
7596               Chain.getNode()->dump(&DAG);
7597               dbgs() << "\n");
7598         WorkListRemover DeadNodes(*this);
7599         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7600
7601         if (N->use_empty()) {
7602           removeFromWorkList(N);
7603           DAG.DeleteNode(N);
7604         }
7605
7606         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7607       }
7608     } else {
7609       // Indexed loads.
7610       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7611       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7612         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7613         DEBUG(dbgs() << "\nReplacing.7 ";
7614               N->dump(&DAG);
7615               dbgs() << "\nWith: ";
7616               Undef.getNode()->dump(&DAG);
7617               dbgs() << " and 2 other values\n");
7618         WorkListRemover DeadNodes(*this);
7619         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7620         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7621                                       DAG.getUNDEF(N->getValueType(1)));
7622         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7623         removeFromWorkList(N);
7624         DAG.DeleteNode(N);
7625         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7626       }
7627     }
7628   }
7629
7630   // If this load is directly stored, replace the load value with the stored
7631   // value.
7632   // TODO: Handle store large -> read small portion.
7633   // TODO: Handle TRUNCSTORE/LOADEXT
7634   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7635     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7636       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7637       if (PrevST->getBasePtr() == Ptr &&
7638           PrevST->getValue().getValueType() == N->getValueType(0))
7639       return CombineTo(N, Chain.getOperand(1), Chain);
7640     }
7641   }
7642
7643   // Try to infer better alignment information than the load already has.
7644   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7645     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7646       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7647         SDValue NewLoad =
7648                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7649                               LD->getValueType(0),
7650                               Chain, Ptr, LD->getPointerInfo(),
7651                               LD->getMemoryVT(),
7652                               LD->isVolatile(), LD->isNonTemporal(), Align,
7653                               LD->getTBAAInfo());
7654         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7655       }
7656     }
7657   }
7658
7659   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7660     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7661   if (UseAA) {
7662     // Walk up chain skipping non-aliasing memory nodes.
7663     SDValue BetterChain = FindBetterChain(N, Chain);
7664
7665     // If there is a better chain.
7666     if (Chain != BetterChain) {
7667       SDValue ReplLoad;
7668
7669       // Replace the chain to void dependency.
7670       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7671         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7672                                BetterChain, Ptr, LD->getMemOperand());
7673       } else {
7674         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7675                                   LD->getValueType(0),
7676                                   BetterChain, Ptr, LD->getMemoryVT(),
7677                                   LD->getMemOperand());
7678       }
7679
7680       // Create token factor to keep old chain connected.
7681       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7682                                   MVT::Other, Chain, ReplLoad.getValue(1));
7683
7684       // Make sure the new and old chains are cleaned up.
7685       AddToWorkList(Token.getNode());
7686
7687       // Replace uses with load result and token factor. Don't add users
7688       // to work list.
7689       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7690     }
7691   }
7692
7693   // Try transforming N to an indexed load.
7694   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7695     return SDValue(N, 0);
7696
7697   // Try to slice up N to more direct loads if the slices are mapped to
7698   // different register banks or pairing can take place.
7699   if (SliceUpLoad(N))
7700     return SDValue(N, 0);
7701
7702   return SDValue();
7703 }
7704
7705 namespace {
7706 /// \brief Helper structure used to slice a load in smaller loads.
7707 /// Basically a slice is obtained from the following sequence:
7708 /// Origin = load Ty1, Base
7709 /// Shift = srl Ty1 Origin, CstTy Amount
7710 /// Inst = trunc Shift to Ty2
7711 ///
7712 /// Then, it will be rewriten into:
7713 /// Slice = load SliceTy, Base + SliceOffset
7714 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7715 ///
7716 /// SliceTy is deduced from the number of bits that are actually used to
7717 /// build Inst.
7718 struct LoadedSlice {
7719   /// \brief Helper structure used to compute the cost of a slice.
7720   struct Cost {
7721     /// Are we optimizing for code size.
7722     bool ForCodeSize;
7723     /// Various cost.
7724     unsigned Loads;
7725     unsigned Truncates;
7726     unsigned CrossRegisterBanksCopies;
7727     unsigned ZExts;
7728     unsigned Shift;
7729
7730     Cost(bool ForCodeSize = false)
7731         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7732           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7733
7734     /// \brief Get the cost of one isolated slice.
7735     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7736         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7737           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7738       EVT TruncType = LS.Inst->getValueType(0);
7739       EVT LoadedType = LS.getLoadedType();
7740       if (TruncType != LoadedType &&
7741           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7742         ZExts = 1;
7743     }
7744
7745     /// \brief Account for slicing gain in the current cost.
7746     /// Slicing provide a few gains like removing a shift or a
7747     /// truncate. This method allows to grow the cost of the original
7748     /// load with the gain from this slice.
7749     void addSliceGain(const LoadedSlice &LS) {
7750       // Each slice saves a truncate.
7751       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7752       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7753                               LS.Inst->getOperand(0).getValueType()))
7754         ++Truncates;
7755       // If there is a shift amount, this slice gets rid of it.
7756       if (LS.Shift)
7757         ++Shift;
7758       // If this slice can merge a cross register bank copy, account for it.
7759       if (LS.canMergeExpensiveCrossRegisterBankCopy())
7760         ++CrossRegisterBanksCopies;
7761     }
7762
7763     Cost &operator+=(const Cost &RHS) {
7764       Loads += RHS.Loads;
7765       Truncates += RHS.Truncates;
7766       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7767       ZExts += RHS.ZExts;
7768       Shift += RHS.Shift;
7769       return *this;
7770     }
7771
7772     bool operator==(const Cost &RHS) const {
7773       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7774              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7775              ZExts == RHS.ZExts && Shift == RHS.Shift;
7776     }
7777
7778     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7779
7780     bool operator<(const Cost &RHS) const {
7781       // Assume cross register banks copies are as expensive as loads.
7782       // FIXME: Do we want some more target hooks?
7783       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7784       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7785       // Unless we are optimizing for code size, consider the
7786       // expensive operation first.
7787       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7788         return ExpensiveOpsLHS < ExpensiveOpsRHS;
7789       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7790              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7791     }
7792
7793     bool operator>(const Cost &RHS) const { return RHS < *this; }
7794
7795     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7796
7797     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7798   };
7799   // The last instruction that represent the slice. This should be a
7800   // truncate instruction.
7801   SDNode *Inst;
7802   // The original load instruction.
7803   LoadSDNode *Origin;
7804   // The right shift amount in bits from the original load.
7805   unsigned Shift;
7806   // The DAG from which Origin came from.
7807   // This is used to get some contextual information about legal types, etc.
7808   SelectionDAG *DAG;
7809
7810   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7811               unsigned Shift = 0, SelectionDAG *DAG = NULL)
7812       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7813
7814   LoadedSlice(const LoadedSlice &LS)
7815       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7816
7817   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7818   /// \return Result is \p BitWidth and has used bits set to 1 and
7819   ///         not used bits set to 0.
7820   APInt getUsedBits() const {
7821     // Reproduce the trunc(lshr) sequence:
7822     // - Start from the truncated value.
7823     // - Zero extend to the desired bit width.
7824     // - Shift left.
7825     assert(Origin && "No original load to compare against.");
7826     unsigned BitWidth = Origin->getValueSizeInBits(0);
7827     assert(Inst && "This slice is not bound to an instruction");
7828     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7829            "Extracted slice is bigger than the whole type!");
7830     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7831     UsedBits.setAllBits();
7832     UsedBits = UsedBits.zext(BitWidth);
7833     UsedBits <<= Shift;
7834     return UsedBits;
7835   }
7836
7837   /// \brief Get the size of the slice to be loaded in bytes.
7838   unsigned getLoadedSize() const {
7839     unsigned SliceSize = getUsedBits().countPopulation();
7840     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7841     return SliceSize / 8;
7842   }
7843
7844   /// \brief Get the type that will be loaded for this slice.
7845   /// Note: This may not be the final type for the slice.
7846   EVT getLoadedType() const {
7847     assert(DAG && "Missing context");
7848     LLVMContext &Ctxt = *DAG->getContext();
7849     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7850   }
7851
7852   /// \brief Get the alignment of the load used for this slice.
7853   unsigned getAlignment() const {
7854     unsigned Alignment = Origin->getAlignment();
7855     unsigned Offset = getOffsetFromBase();
7856     if (Offset != 0)
7857       Alignment = MinAlign(Alignment, Alignment + Offset);
7858     return Alignment;
7859   }
7860
7861   /// \brief Check if this slice can be rewritten with legal operations.
7862   bool isLegal() const {
7863     // An invalid slice is not legal.
7864     if (!Origin || !Inst || !DAG)
7865       return false;
7866
7867     // Offsets are for indexed load only, we do not handle that.
7868     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7869       return false;
7870
7871     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7872
7873     // Check that the type is legal.
7874     EVT SliceType = getLoadedType();
7875     if (!TLI.isTypeLegal(SliceType))
7876       return false;
7877
7878     // Check that the load is legal for this type.
7879     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7880       return false;
7881
7882     // Check that the offset can be computed.
7883     // 1. Check its type.
7884     EVT PtrType = Origin->getBasePtr().getValueType();
7885     if (PtrType == MVT::Untyped || PtrType.isExtended())
7886       return false;
7887
7888     // 2. Check that it fits in the immediate.
7889     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7890       return false;
7891
7892     // 3. Check that the computation is legal.
7893     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7894       return false;
7895
7896     // Check that the zext is legal if it needs one.
7897     EVT TruncateType = Inst->getValueType(0);
7898     if (TruncateType != SliceType &&
7899         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7900       return false;
7901
7902     return true;
7903   }
7904
7905   /// \brief Get the offset in bytes of this slice in the original chunk of
7906   /// bits.
7907   /// \pre DAG != NULL.
7908   uint64_t getOffsetFromBase() const {
7909     assert(DAG && "Missing context.");
7910     bool IsBigEndian =
7911         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7912     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7913     uint64_t Offset = Shift / 8;
7914     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7915     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7916            "The size of the original loaded type is not a multiple of a"
7917            " byte.");
7918     // If Offset is bigger than TySizeInBytes, it means we are loading all
7919     // zeros. This should have been optimized before in the process.
7920     assert(TySizeInBytes > Offset &&
7921            "Invalid shift amount for given loaded size");
7922     if (IsBigEndian)
7923       Offset = TySizeInBytes - Offset - getLoadedSize();
7924     return Offset;
7925   }
7926
7927   /// \brief Generate the sequence of instructions to load the slice
7928   /// represented by this object and redirect the uses of this slice to
7929   /// this new sequence of instructions.
7930   /// \pre this->Inst && this->Origin are valid Instructions and this
7931   /// object passed the legal check: LoadedSlice::isLegal returned true.
7932   /// \return The last instruction of the sequence used to load the slice.
7933   SDValue loadSlice() const {
7934     assert(Inst && Origin && "Unable to replace a non-existing slice.");
7935     const SDValue &OldBaseAddr = Origin->getBasePtr();
7936     SDValue BaseAddr = OldBaseAddr;
7937     // Get the offset in that chunk of bytes w.r.t. the endianess.
7938     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7939     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7940     if (Offset) {
7941       // BaseAddr = BaseAddr + Offset.
7942       EVT ArithType = BaseAddr.getValueType();
7943       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7944                               DAG->getConstant(Offset, ArithType));
7945     }
7946
7947     // Create the type of the loaded slice according to its size.
7948     EVT SliceType = getLoadedType();
7949
7950     // Create the load for the slice.
7951     SDValue LastInst = DAG->getLoad(
7952         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7953         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7954         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7955     // If the final type is not the same as the loaded type, this means that
7956     // we have to pad with zero. Create a zero extend for that.
7957     EVT FinalType = Inst->getValueType(0);
7958     if (SliceType != FinalType)
7959       LastInst =
7960           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7961     return LastInst;
7962   }
7963
7964   /// \brief Check if this slice can be merged with an expensive cross register
7965   /// bank copy. E.g.,
7966   /// i = load i32
7967   /// f = bitcast i32 i to float
7968   bool canMergeExpensiveCrossRegisterBankCopy() const {
7969     if (!Inst || !Inst->hasOneUse())
7970       return false;
7971     SDNode *Use = *Inst->use_begin();
7972     if (Use->getOpcode() != ISD::BITCAST)
7973       return false;
7974     assert(DAG && "Missing context");
7975     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7976     EVT ResVT = Use->getValueType(0);
7977     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7978     const TargetRegisterClass *ArgRC =
7979         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7980     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7981       return false;
7982
7983     // At this point, we know that we perform a cross-register-bank copy.
7984     // Check if it is expensive.
7985     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7986     // Assume bitcasts are cheap, unless both register classes do not
7987     // explicitly share a common sub class.
7988     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7989       return false;
7990
7991     // Check if it will be merged with the load.
7992     // 1. Check the alignment constraint.
7993     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7994         ResVT.getTypeForEVT(*DAG->getContext()));
7995
7996     if (RequiredAlignment > getAlignment())
7997       return false;
7998
7999     // 2. Check that the load is a legal operation for that type.
8000     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8001       return false;
8002
8003     // 3. Check that we do not have a zext in the way.
8004     if (Inst->getValueType(0) != getLoadedType())
8005       return false;
8006
8007     return true;
8008   }
8009 };
8010 }
8011
8012 /// \brief Sorts LoadedSlice according to their offset.
8013 struct LoadedSliceSorter {
8014   bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8015     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8016     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8017   }
8018 };
8019
8020 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8021 /// \p UsedBits looks like 0..0 1..1 0..0.
8022 static bool areUsedBitsDense(const APInt &UsedBits) {
8023   // If all the bits are one, this is dense!
8024   if (UsedBits.isAllOnesValue())
8025     return true;
8026
8027   // Get rid of the unused bits on the right.
8028   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8029   // Get rid of the unused bits on the left.
8030   if (NarrowedUsedBits.countLeadingZeros())
8031     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8032   // Check that the chunk of bits is completely used.
8033   return NarrowedUsedBits.isAllOnesValue();
8034 }
8035
8036 /// \brief Check whether or not \p First and \p Second are next to each other
8037 /// in memory. This means that there is no hole between the bits loaded
8038 /// by \p First and the bits loaded by \p Second.
8039 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8040                                      const LoadedSlice &Second) {
8041   assert(First.Origin == Second.Origin && First.Origin &&
8042          "Unable to match different memory origins.");
8043   APInt UsedBits = First.getUsedBits();
8044   assert((UsedBits & Second.getUsedBits()) == 0 &&
8045          "Slices are not supposed to overlap.");
8046   UsedBits |= Second.getUsedBits();
8047   return areUsedBitsDense(UsedBits);
8048 }
8049
8050 /// \brief Adjust the \p GlobalLSCost according to the target
8051 /// paring capabilities and the layout of the slices.
8052 /// \pre \p GlobalLSCost should account for at least as many loads as
8053 /// there is in the slices in \p LoadedSlices.
8054 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8055                                  LoadedSlice::Cost &GlobalLSCost) {
8056   unsigned NumberOfSlices = LoadedSlices.size();
8057   // If there is less than 2 elements, no pairing is possible.
8058   if (NumberOfSlices < 2)
8059     return;
8060
8061   // Sort the slices so that elements that are likely to be next to each
8062   // other in memory are next to each other in the list.
8063   std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8064   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8065   // First (resp. Second) is the first (resp. Second) potentially candidate
8066   // to be placed in a paired load.
8067   const LoadedSlice *First = NULL;
8068   const LoadedSlice *Second = NULL;
8069   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8070                 // Set the beginning of the pair.
8071                                                            First = Second) {
8072
8073     Second = &LoadedSlices[CurrSlice];
8074
8075     // If First is NULL, it means we start a new pair.
8076     // Get to the next slice.
8077     if (!First)
8078       continue;
8079
8080     EVT LoadedType = First->getLoadedType();
8081
8082     // If the types of the slices are different, we cannot pair them.
8083     if (LoadedType != Second->getLoadedType())
8084       continue;
8085
8086     // Check if the target supplies paired loads for this type.
8087     unsigned RequiredAlignment = 0;
8088     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8089       // move to the next pair, this type is hopeless.
8090       Second = NULL;
8091       continue;
8092     }
8093     // Check if we meet the alignment requirement.
8094     if (RequiredAlignment > First->getAlignment())
8095       continue;
8096
8097     // Check that both loads are next to each other in memory.
8098     if (!areSlicesNextToEachOther(*First, *Second))
8099       continue;
8100
8101     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8102     --GlobalLSCost.Loads;
8103     // Move to the next pair.
8104     Second = NULL;
8105   }
8106 }
8107
8108 /// \brief Check the profitability of all involved LoadedSlice.
8109 /// Currently, it is considered profitable if there is exactly two
8110 /// involved slices (1) which are (2) next to each other in memory, and
8111 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8112 ///
8113 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8114 /// the elements themselves.
8115 ///
8116 /// FIXME: When the cost model will be mature enough, we can relax
8117 /// constraints (1) and (2).
8118 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8119                                 const APInt &UsedBits, bool ForCodeSize) {
8120   unsigned NumberOfSlices = LoadedSlices.size();
8121   if (StressLoadSlicing)
8122     return NumberOfSlices > 1;
8123
8124   // Check (1).
8125   if (NumberOfSlices != 2)
8126     return false;
8127
8128   // Check (2).
8129   if (!areUsedBitsDense(UsedBits))
8130     return false;
8131
8132   // Check (3).
8133   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8134   // The original code has one big load.
8135   OrigCost.Loads = 1;
8136   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8137     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8138     // Accumulate the cost of all the slices.
8139     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8140     GlobalSlicingCost += SliceCost;
8141
8142     // Account as cost in the original configuration the gain obtained
8143     // with the current slices.
8144     OrigCost.addSliceGain(LS);
8145   }
8146
8147   // If the target supports paired load, adjust the cost accordingly.
8148   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8149   return OrigCost > GlobalSlicingCost;
8150 }
8151
8152 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8153 /// operations, split it in the various pieces being extracted.
8154 ///
8155 /// This sort of thing is introduced by SROA.
8156 /// This slicing takes care not to insert overlapping loads.
8157 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8158 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8159   if (Level < AfterLegalizeDAG)
8160     return false;
8161
8162   LoadSDNode *LD = cast<LoadSDNode>(N);
8163   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8164       !LD->getValueType(0).isInteger())
8165     return false;
8166
8167   // Keep track of already used bits to detect overlapping values.
8168   // In that case, we will just abort the transformation.
8169   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8170
8171   SmallVector<LoadedSlice, 4> LoadedSlices;
8172
8173   // Check if this load is used as several smaller chunks of bits.
8174   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8175   // of computation for each trunc.
8176   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8177        UI != UIEnd; ++UI) {
8178     // Skip the uses of the chain.
8179     if (UI.getUse().getResNo() != 0)
8180       continue;
8181
8182     SDNode *User = *UI;
8183     unsigned Shift = 0;
8184
8185     // Check if this is a trunc(lshr).
8186     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8187         isa<ConstantSDNode>(User->getOperand(1))) {
8188       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8189       User = *User->use_begin();
8190     }
8191
8192     // At this point, User is a Truncate, iff we encountered, trunc or
8193     // trunc(lshr).
8194     if (User->getOpcode() != ISD::TRUNCATE)
8195       return false;
8196
8197     // The width of the type must be a power of 2 and greater than 8-bits.
8198     // Otherwise the load cannot be represented in LLVM IR.
8199     // Moreover, if we shifted with a non-8-bits multiple, the slice
8200     // will be accross several bytes. We do not support that.
8201     unsigned Width = User->getValueSizeInBits(0);
8202     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8203       return 0;
8204
8205     // Build the slice for this chain of computations.
8206     LoadedSlice LS(User, LD, Shift, &DAG);
8207     APInt CurrentUsedBits = LS.getUsedBits();
8208
8209     // Check if this slice overlaps with another.
8210     if ((CurrentUsedBits & UsedBits) != 0)
8211       return false;
8212     // Update the bits used globally.
8213     UsedBits |= CurrentUsedBits;
8214
8215     // Check if the new slice would be legal.
8216     if (!LS.isLegal())
8217       return false;
8218
8219     // Record the slice.
8220     LoadedSlices.push_back(LS);
8221   }
8222
8223   // Abort slicing if it does not seem to be profitable.
8224   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8225     return false;
8226
8227   ++SlicedLoads;
8228
8229   // Rewrite each chain to use an independent load.
8230   // By construction, each chain can be represented by a unique load.
8231
8232   // Prepare the argument for the new token factor for all the slices.
8233   SmallVector<SDValue, 8> ArgChains;
8234   for (SmallVectorImpl<LoadedSlice>::const_iterator
8235            LSIt = LoadedSlices.begin(),
8236            LSItEnd = LoadedSlices.end();
8237        LSIt != LSItEnd; ++LSIt) {
8238     SDValue SliceInst = LSIt->loadSlice();
8239     CombineTo(LSIt->Inst, SliceInst, true);
8240     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8241       SliceInst = SliceInst.getOperand(0);
8242     assert(SliceInst->getOpcode() == ISD::LOAD &&
8243            "It takes more than a zext to get to the loaded slice!!");
8244     ArgChains.push_back(SliceInst.getValue(1));
8245   }
8246
8247   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8248                               &ArgChains[0], ArgChains.size());
8249   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8250   return true;
8251 }
8252
8253 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8254 /// load is having specific bytes cleared out.  If so, return the byte size
8255 /// being masked out and the shift amount.
8256 static std::pair<unsigned, unsigned>
8257 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8258   std::pair<unsigned, unsigned> Result(0, 0);
8259
8260   // Check for the structure we're looking for.
8261   if (V->getOpcode() != ISD::AND ||
8262       !isa<ConstantSDNode>(V->getOperand(1)) ||
8263       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8264     return Result;
8265
8266   // Check the chain and pointer.
8267   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8268   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8269
8270   // The store should be chained directly to the load or be an operand of a
8271   // tokenfactor.
8272   if (LD == Chain.getNode())
8273     ; // ok.
8274   else if (Chain->getOpcode() != ISD::TokenFactor)
8275     return Result; // Fail.
8276   else {
8277     bool isOk = false;
8278     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8279       if (Chain->getOperand(i).getNode() == LD) {
8280         isOk = true;
8281         break;
8282       }
8283     if (!isOk) return Result;
8284   }
8285
8286   // This only handles simple types.
8287   if (V.getValueType() != MVT::i16 &&
8288       V.getValueType() != MVT::i32 &&
8289       V.getValueType() != MVT::i64)
8290     return Result;
8291
8292   // Check the constant mask.  Invert it so that the bits being masked out are
8293   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8294   // follow the sign bit for uniformity.
8295   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8296   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8297   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8298   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8299   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8300   if (NotMaskLZ == 64) return Result;  // All zero mask.
8301
8302   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8303   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8304     return Result;
8305
8306   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8307   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8308     NotMaskLZ -= 64-V.getValueSizeInBits();
8309
8310   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8311   switch (MaskedBytes) {
8312   case 1:
8313   case 2:
8314   case 4: break;
8315   default: return Result; // All one mask, or 5-byte mask.
8316   }
8317
8318   // Verify that the first bit starts at a multiple of mask so that the access
8319   // is aligned the same as the access width.
8320   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8321
8322   Result.first = MaskedBytes;
8323   Result.second = NotMaskTZ/8;
8324   return Result;
8325 }
8326
8327
8328 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8329 /// provides a value as specified by MaskInfo.  If so, replace the specified
8330 /// store with a narrower store of truncated IVal.
8331 static SDNode *
8332 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8333                                 SDValue IVal, StoreSDNode *St,
8334                                 DAGCombiner *DC) {
8335   unsigned NumBytes = MaskInfo.first;
8336   unsigned ByteShift = MaskInfo.second;
8337   SelectionDAG &DAG = DC->getDAG();
8338
8339   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8340   // that uses this.  If not, this is not a replacement.
8341   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8342                                   ByteShift*8, (ByteShift+NumBytes)*8);
8343   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8344
8345   // Check that it is legal on the target to do this.  It is legal if the new
8346   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8347   // legalization.
8348   MVT VT = MVT::getIntegerVT(NumBytes*8);
8349   if (!DC->isTypeLegal(VT))
8350     return 0;
8351
8352   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8353   // shifted by ByteShift and truncated down to NumBytes.
8354   if (ByteShift)
8355     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8356                        DAG.getConstant(ByteShift*8,
8357                                     DC->getShiftAmountTy(IVal.getValueType())));
8358
8359   // Figure out the offset for the store and the alignment of the access.
8360   unsigned StOffset;
8361   unsigned NewAlign = St->getAlignment();
8362
8363   if (DAG.getTargetLoweringInfo().isLittleEndian())
8364     StOffset = ByteShift;
8365   else
8366     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8367
8368   SDValue Ptr = St->getBasePtr();
8369   if (StOffset) {
8370     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8371                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8372     NewAlign = MinAlign(NewAlign, StOffset);
8373   }
8374
8375   // Truncate down to the new size.
8376   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8377
8378   ++OpsNarrowed;
8379   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8380                       St->getPointerInfo().getWithOffset(StOffset),
8381                       false, false, NewAlign).getNode();
8382 }
8383
8384
8385 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8386 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8387 /// of the loaded bits, try narrowing the load and store if it would end up
8388 /// being a win for performance or code size.
8389 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8390   StoreSDNode *ST  = cast<StoreSDNode>(N);
8391   if (ST->isVolatile())
8392     return SDValue();
8393
8394   SDValue Chain = ST->getChain();
8395   SDValue Value = ST->getValue();
8396   SDValue Ptr   = ST->getBasePtr();
8397   EVT VT = Value.getValueType();
8398
8399   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8400     return SDValue();
8401
8402   unsigned Opc = Value.getOpcode();
8403
8404   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8405   // is a byte mask indicating a consecutive number of bytes, check to see if
8406   // Y is known to provide just those bytes.  If so, we try to replace the
8407   // load + replace + store sequence with a single (narrower) store, which makes
8408   // the load dead.
8409   if (Opc == ISD::OR) {
8410     std::pair<unsigned, unsigned> MaskedLoad;
8411     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8412     if (MaskedLoad.first)
8413       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8414                                                   Value.getOperand(1), ST,this))
8415         return SDValue(NewST, 0);
8416
8417     // Or is commutative, so try swapping X and Y.
8418     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8419     if (MaskedLoad.first)
8420       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8421                                                   Value.getOperand(0), ST,this))
8422         return SDValue(NewST, 0);
8423   }
8424
8425   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8426       Value.getOperand(1).getOpcode() != ISD::Constant)
8427     return SDValue();
8428
8429   SDValue N0 = Value.getOperand(0);
8430   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8431       Chain == SDValue(N0.getNode(), 1)) {
8432     LoadSDNode *LD = cast<LoadSDNode>(N0);
8433     if (LD->getBasePtr() != Ptr ||
8434         LD->getPointerInfo().getAddrSpace() !=
8435         ST->getPointerInfo().getAddrSpace())
8436       return SDValue();
8437
8438     // Find the type to narrow it the load / op / store to.
8439     SDValue N1 = Value.getOperand(1);
8440     unsigned BitWidth = N1.getValueSizeInBits();
8441     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8442     if (Opc == ISD::AND)
8443       Imm ^= APInt::getAllOnesValue(BitWidth);
8444     if (Imm == 0 || Imm.isAllOnesValue())
8445       return SDValue();
8446     unsigned ShAmt = Imm.countTrailingZeros();
8447     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8448     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8449     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8450     while (NewBW < BitWidth &&
8451            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8452              TLI.isNarrowingProfitable(VT, NewVT))) {
8453       NewBW = NextPowerOf2(NewBW);
8454       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8455     }
8456     if (NewBW >= BitWidth)
8457       return SDValue();
8458
8459     // If the lsb changed does not start at the type bitwidth boundary,
8460     // start at the previous one.
8461     if (ShAmt % NewBW)
8462       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8463     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8464                                    std::min(BitWidth, ShAmt + NewBW));
8465     if ((Imm & Mask) == Imm) {
8466       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8467       if (Opc == ISD::AND)
8468         NewImm ^= APInt::getAllOnesValue(NewBW);
8469       uint64_t PtrOff = ShAmt / 8;
8470       // For big endian targets, we need to adjust the offset to the pointer to
8471       // load the correct bytes.
8472       if (TLI.isBigEndian())
8473         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8474
8475       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8476       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8477       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8478         return SDValue();
8479
8480       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8481                                    Ptr.getValueType(), Ptr,
8482                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8483       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8484                                   LD->getChain(), NewPtr,
8485                                   LD->getPointerInfo().getWithOffset(PtrOff),
8486                                   LD->isVolatile(), LD->isNonTemporal(),
8487                                   LD->isInvariant(), NewAlign,
8488                                   LD->getTBAAInfo());
8489       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8490                                    DAG.getConstant(NewImm, NewVT));
8491       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8492                                    NewVal, NewPtr,
8493                                    ST->getPointerInfo().getWithOffset(PtrOff),
8494                                    false, false, NewAlign);
8495
8496       AddToWorkList(NewPtr.getNode());
8497       AddToWorkList(NewLD.getNode());
8498       AddToWorkList(NewVal.getNode());
8499       WorkListRemover DeadNodes(*this);
8500       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8501       ++OpsNarrowed;
8502       return NewST;
8503     }
8504   }
8505
8506   return SDValue();
8507 }
8508
8509 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8510 /// if the load value isn't used by any other operations, then consider
8511 /// transforming the pair to integer load / store operations if the target
8512 /// deems the transformation profitable.
8513 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8514   StoreSDNode *ST  = cast<StoreSDNode>(N);
8515   SDValue Chain = ST->getChain();
8516   SDValue Value = ST->getValue();
8517   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8518       Value.hasOneUse() &&
8519       Chain == SDValue(Value.getNode(), 1)) {
8520     LoadSDNode *LD = cast<LoadSDNode>(Value);
8521     EVT VT = LD->getMemoryVT();
8522     if (!VT.isFloatingPoint() ||
8523         VT != ST->getMemoryVT() ||
8524         LD->isNonTemporal() ||
8525         ST->isNonTemporal() ||
8526         LD->getPointerInfo().getAddrSpace() != 0 ||
8527         ST->getPointerInfo().getAddrSpace() != 0)
8528       return SDValue();
8529
8530     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8531     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8532         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8533         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8534         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8535       return SDValue();
8536
8537     unsigned LDAlign = LD->getAlignment();
8538     unsigned STAlign = ST->getAlignment();
8539     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8540     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8541     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8542       return SDValue();
8543
8544     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8545                                 LD->getChain(), LD->getBasePtr(),
8546                                 LD->getPointerInfo(),
8547                                 false, false, false, LDAlign);
8548
8549     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8550                                  NewLD, ST->getBasePtr(),
8551                                  ST->getPointerInfo(),
8552                                  false, false, STAlign);
8553
8554     AddToWorkList(NewLD.getNode());
8555     AddToWorkList(NewST.getNode());
8556     WorkListRemover DeadNodes(*this);
8557     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8558     ++LdStFP2Int;
8559     return NewST;
8560   }
8561
8562   return SDValue();
8563 }
8564
8565 /// Helper struct to parse and store a memory address as base + index + offset.
8566 /// We ignore sign extensions when it is safe to do so.
8567 /// The following two expressions are not equivalent. To differentiate we need
8568 /// to store whether there was a sign extension involved in the index
8569 /// computation.
8570 ///  (load (i64 add (i64 copyfromreg %c)
8571 ///                 (i64 signextend (add (i8 load %index)
8572 ///                                      (i8 1))))
8573 /// vs
8574 ///
8575 /// (load (i64 add (i64 copyfromreg %c)
8576 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8577 ///                                         (i32 1)))))
8578 struct BaseIndexOffset {
8579   SDValue Base;
8580   SDValue Index;
8581   int64_t Offset;
8582   bool IsIndexSignExt;
8583
8584   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8585
8586   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8587                   bool IsIndexSignExt) :
8588     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8589
8590   bool equalBaseIndex(const BaseIndexOffset &Other) {
8591     return Other.Base == Base && Other.Index == Index &&
8592       Other.IsIndexSignExt == IsIndexSignExt;
8593   }
8594
8595   /// Parses tree in Ptr for base, index, offset addresses.
8596   static BaseIndexOffset match(SDValue Ptr) {
8597     bool IsIndexSignExt = false;
8598
8599     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8600     // instruction, then it could be just the BASE or everything else we don't
8601     // know how to handle. Just use Ptr as BASE and give up.
8602     if (Ptr->getOpcode() != ISD::ADD)
8603       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8604
8605     // We know that we have at least an ADD instruction. Try to pattern match
8606     // the simple case of BASE + OFFSET.
8607     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8608       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8609       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8610                               IsIndexSignExt);
8611     }
8612
8613     // Inside a loop the current BASE pointer is calculated using an ADD and a
8614     // MUL instruction. In this case Ptr is the actual BASE pointer.
8615     // (i64 add (i64 %array_ptr)
8616     //          (i64 mul (i64 %induction_var)
8617     //                   (i64 %element_size)))
8618     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8619       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8620
8621     // Look at Base + Index + Offset cases.
8622     SDValue Base = Ptr->getOperand(0);
8623     SDValue IndexOffset = Ptr->getOperand(1);
8624
8625     // Skip signextends.
8626     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8627       IndexOffset = IndexOffset->getOperand(0);
8628       IsIndexSignExt = true;
8629     }
8630
8631     // Either the case of Base + Index (no offset) or something else.
8632     if (IndexOffset->getOpcode() != ISD::ADD)
8633       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8634
8635     // Now we have the case of Base + Index + offset.
8636     SDValue Index = IndexOffset->getOperand(0);
8637     SDValue Offset = IndexOffset->getOperand(1);
8638
8639     if (!isa<ConstantSDNode>(Offset))
8640       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8641
8642     // Ignore signextends.
8643     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8644       Index = Index->getOperand(0);
8645       IsIndexSignExt = true;
8646     } else IsIndexSignExt = false;
8647
8648     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8649     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8650   }
8651 };
8652
8653 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8654 /// is located in a sequence of memory operations connected by a chain.
8655 struct MemOpLink {
8656   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8657     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8658   // Ptr to the mem node.
8659   LSBaseSDNode *MemNode;
8660   // Offset from the base ptr.
8661   int64_t OffsetFromBase;
8662   // What is the sequence number of this mem node.
8663   // Lowest mem operand in the DAG starts at zero.
8664   unsigned SequenceNum;
8665 };
8666
8667 /// Sorts store nodes in a link according to their offset from a shared
8668 // base ptr.
8669 struct ConsecutiveMemoryChainSorter {
8670   bool operator()(MemOpLink LHS, MemOpLink RHS) {
8671     return LHS.OffsetFromBase < RHS.OffsetFromBase;
8672   }
8673 };
8674
8675 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8676   EVT MemVT = St->getMemoryVT();
8677   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8678   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8679     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8680
8681   // Don't merge vectors into wider inputs.
8682   if (MemVT.isVector() || !MemVT.isSimple())
8683     return false;
8684
8685   // Perform an early exit check. Do not bother looking at stored values that
8686   // are not constants or loads.
8687   SDValue StoredVal = St->getValue();
8688   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8689   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8690       !IsLoadSrc)
8691     return false;
8692
8693   // Only look at ends of store sequences.
8694   SDValue Chain = SDValue(St, 1);
8695   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8696     return false;
8697
8698   // This holds the base pointer, index, and the offset in bytes from the base
8699   // pointer.
8700   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8701
8702   // We must have a base and an offset.
8703   if (!BasePtr.Base.getNode())
8704     return false;
8705
8706   // Do not handle stores to undef base pointers.
8707   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8708     return false;
8709
8710   // Save the LoadSDNodes that we find in the chain.
8711   // We need to make sure that these nodes do not interfere with
8712   // any of the store nodes.
8713   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8714
8715   // Save the StoreSDNodes that we find in the chain.
8716   SmallVector<MemOpLink, 8> StoreNodes;
8717
8718   // Walk up the chain and look for nodes with offsets from the same
8719   // base pointer. Stop when reaching an instruction with a different kind
8720   // or instruction which has a different base pointer.
8721   unsigned Seq = 0;
8722   StoreSDNode *Index = St;
8723   while (Index) {
8724     // If the chain has more than one use, then we can't reorder the mem ops.
8725     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8726       break;
8727
8728     // Find the base pointer and offset for this memory node.
8729     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8730
8731     // Check that the base pointer is the same as the original one.
8732     if (!Ptr.equalBaseIndex(BasePtr))
8733       break;
8734
8735     // Check that the alignment is the same.
8736     if (Index->getAlignment() != St->getAlignment())
8737       break;
8738
8739     // The memory operands must not be volatile.
8740     if (Index->isVolatile() || Index->isIndexed())
8741       break;
8742
8743     // No truncation.
8744     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8745       if (St->isTruncatingStore())
8746         break;
8747
8748     // The stored memory type must be the same.
8749     if (Index->getMemoryVT() != MemVT)
8750       break;
8751
8752     // We do not allow unaligned stores because we want to prevent overriding
8753     // stores.
8754     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8755       break;
8756
8757     // We found a potential memory operand to merge.
8758     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8759
8760     // Find the next memory operand in the chain. If the next operand in the
8761     // chain is a store then move up and continue the scan with the next
8762     // memory operand. If the next operand is a load save it and use alias
8763     // information to check if it interferes with anything.
8764     SDNode *NextInChain = Index->getChain().getNode();
8765     while (1) {
8766       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8767         // We found a store node. Use it for the next iteration.
8768         Index = STn;
8769         break;
8770       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8771         if (Ldn->isVolatile()) {
8772           Index = NULL;
8773           break;
8774         }
8775
8776         // Save the load node for later. Continue the scan.
8777         AliasLoadNodes.push_back(Ldn);
8778         NextInChain = Ldn->getChain().getNode();
8779         continue;
8780       } else {
8781         Index = NULL;
8782         break;
8783       }
8784     }
8785   }
8786
8787   // Check if there is anything to merge.
8788   if (StoreNodes.size() < 2)
8789     return false;
8790
8791   // Sort the memory operands according to their distance from the base pointer.
8792   std::sort(StoreNodes.begin(), StoreNodes.end(),
8793             ConsecutiveMemoryChainSorter());
8794
8795   // Scan the memory operations on the chain and find the first non-consecutive
8796   // store memory address.
8797   unsigned LastConsecutiveStore = 0;
8798   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8799   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8800
8801     // Check that the addresses are consecutive starting from the second
8802     // element in the list of stores.
8803     if (i > 0) {
8804       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8805       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8806         break;
8807     }
8808
8809     bool Alias = false;
8810     // Check if this store interferes with any of the loads that we found.
8811     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8812       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8813         Alias = true;
8814         break;
8815       }
8816     // We found a load that alias with this store. Stop the sequence.
8817     if (Alias)
8818       break;
8819
8820     // Mark this node as useful.
8821     LastConsecutiveStore = i;
8822   }
8823
8824   // The node with the lowest store address.
8825   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8826
8827   // Store the constants into memory as one consecutive store.
8828   if (!IsLoadSrc) {
8829     unsigned LastLegalType = 0;
8830     unsigned LastLegalVectorType = 0;
8831     bool NonZero = false;
8832     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8833       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8834       SDValue StoredVal = St->getValue();
8835
8836       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8837         NonZero |= !C->isNullValue();
8838       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8839         NonZero |= !C->getConstantFPValue()->isNullValue();
8840       } else {
8841         // Non-constant.
8842         break;
8843       }
8844
8845       // Find a legal type for the constant store.
8846       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8847       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8848       if (TLI.isTypeLegal(StoreTy))
8849         LastLegalType = i+1;
8850       // Or check whether a truncstore is legal.
8851       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8852                TargetLowering::TypePromoteInteger) {
8853         EVT LegalizedStoredValueTy =
8854           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8855         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8856           LastLegalType = i+1;
8857       }
8858
8859       // Find a legal type for the vector store.
8860       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8861       if (TLI.isTypeLegal(Ty))
8862         LastLegalVectorType = i + 1;
8863     }
8864
8865     // We only use vectors if the constant is known to be zero and the
8866     // function is not marked with the noimplicitfloat attribute.
8867     if (NonZero || NoVectors)
8868       LastLegalVectorType = 0;
8869
8870     // Check if we found a legal integer type to store.
8871     if (LastLegalType == 0 && LastLegalVectorType == 0)
8872       return false;
8873
8874     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8875     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8876
8877     // Make sure we have something to merge.
8878     if (NumElem < 2)
8879       return false;
8880
8881     unsigned EarliestNodeUsed = 0;
8882     for (unsigned i=0; i < NumElem; ++i) {
8883       // Find a chain for the new wide-store operand. Notice that some
8884       // of the store nodes that we found may not be selected for inclusion
8885       // in the wide store. The chain we use needs to be the chain of the
8886       // earliest store node which is *used* and replaced by the wide store.
8887       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8888         EarliestNodeUsed = i;
8889     }
8890
8891     // The earliest Node in the DAG.
8892     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8893     SDLoc DL(StoreNodes[0].MemNode);
8894
8895     SDValue StoredVal;
8896     if (UseVector) {
8897       // Find a legal type for the vector store.
8898       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8899       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8900       StoredVal = DAG.getConstant(0, Ty);
8901     } else {
8902       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8903       APInt StoreInt(StoreBW, 0);
8904
8905       // Construct a single integer constant which is made of the smaller
8906       // constant inputs.
8907       bool IsLE = TLI.isLittleEndian();
8908       for (unsigned i = 0; i < NumElem ; ++i) {
8909         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8910         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8911         SDValue Val = St->getValue();
8912         StoreInt<<=ElementSizeBytes*8;
8913         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8914           StoreInt|=C->getAPIntValue().zext(StoreBW);
8915         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8916           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8917         } else {
8918           assert(false && "Invalid constant element type");
8919         }
8920       }
8921
8922       // Create the new Load and Store operations.
8923       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8924       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8925     }
8926
8927     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8928                                     FirstInChain->getBasePtr(),
8929                                     FirstInChain->getPointerInfo(),
8930                                     false, false,
8931                                     FirstInChain->getAlignment());
8932
8933     // Replace the first store with the new store
8934     CombineTo(EarliestOp, NewStore);
8935     // Erase all other stores.
8936     for (unsigned i = 0; i < NumElem ; ++i) {
8937       if (StoreNodes[i].MemNode == EarliestOp)
8938         continue;
8939       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8940       // ReplaceAllUsesWith will replace all uses that existed when it was
8941       // called, but graph optimizations may cause new ones to appear. For
8942       // example, the case in pr14333 looks like
8943       //
8944       //  St's chain -> St -> another store -> X
8945       //
8946       // And the only difference from St to the other store is the chain.
8947       // When we change it's chain to be St's chain they become identical,
8948       // get CSEed and the net result is that X is now a use of St.
8949       // Since we know that St is redundant, just iterate.
8950       while (!St->use_empty())
8951         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8952       removeFromWorkList(St);
8953       DAG.DeleteNode(St);
8954     }
8955
8956     return true;
8957   }
8958
8959   // Below we handle the case of multiple consecutive stores that
8960   // come from multiple consecutive loads. We merge them into a single
8961   // wide load and a single wide store.
8962
8963   // Look for load nodes which are used by the stored values.
8964   SmallVector<MemOpLink, 8> LoadNodes;
8965
8966   // Find acceptable loads. Loads need to have the same chain (token factor),
8967   // must not be zext, volatile, indexed, and they must be consecutive.
8968   BaseIndexOffset LdBasePtr;
8969   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8970     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8971     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8972     if (!Ld) break;
8973
8974     // Loads must only have one use.
8975     if (!Ld->hasNUsesOfValue(1, 0))
8976       break;
8977
8978     // Check that the alignment is the same as the stores.
8979     if (Ld->getAlignment() != St->getAlignment())
8980       break;
8981
8982     // The memory operands must not be volatile.
8983     if (Ld->isVolatile() || Ld->isIndexed())
8984       break;
8985
8986     // We do not accept ext loads.
8987     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8988       break;
8989
8990     // The stored memory type must be the same.
8991     if (Ld->getMemoryVT() != MemVT)
8992       break;
8993
8994     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8995     // If this is not the first ptr that we check.
8996     if (LdBasePtr.Base.getNode()) {
8997       // The base ptr must be the same.
8998       if (!LdPtr.equalBaseIndex(LdBasePtr))
8999         break;
9000     } else {
9001       // Check that all other base pointers are the same as this one.
9002       LdBasePtr = LdPtr;
9003     }
9004
9005     // We found a potential memory operand to merge.
9006     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9007   }
9008
9009   if (LoadNodes.size() < 2)
9010     return false;
9011
9012   // Scan the memory operations on the chain and find the first non-consecutive
9013   // load memory address. These variables hold the index in the store node
9014   // array.
9015   unsigned LastConsecutiveLoad = 0;
9016   // This variable refers to the size and not index in the array.
9017   unsigned LastLegalVectorType = 0;
9018   unsigned LastLegalIntegerType = 0;
9019   StartAddress = LoadNodes[0].OffsetFromBase;
9020   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9021   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9022     // All loads much share the same chain.
9023     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9024       break;
9025
9026     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9027     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9028       break;
9029     LastConsecutiveLoad = i;
9030
9031     // Find a legal type for the vector store.
9032     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9033     if (TLI.isTypeLegal(StoreTy))
9034       LastLegalVectorType = i + 1;
9035
9036     // Find a legal type for the integer store.
9037     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9038     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9039     if (TLI.isTypeLegal(StoreTy))
9040       LastLegalIntegerType = i + 1;
9041     // Or check whether a truncstore and extload is legal.
9042     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9043              TargetLowering::TypePromoteInteger) {
9044       EVT LegalizedStoredValueTy =
9045         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9046       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9047           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9048           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9049           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9050         LastLegalIntegerType = i+1;
9051     }
9052   }
9053
9054   // Only use vector types if the vector type is larger than the integer type.
9055   // If they are the same, use integers.
9056   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9057   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9058
9059   // We add +1 here because the LastXXX variables refer to location while
9060   // the NumElem refers to array/index size.
9061   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9062   NumElem = std::min(LastLegalType, NumElem);
9063
9064   if (NumElem < 2)
9065     return false;
9066
9067   // The earliest Node in the DAG.
9068   unsigned EarliestNodeUsed = 0;
9069   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9070   for (unsigned i=1; i<NumElem; ++i) {
9071     // Find a chain for the new wide-store operand. Notice that some
9072     // of the store nodes that we found may not be selected for inclusion
9073     // in the wide store. The chain we use needs to be the chain of the
9074     // earliest store node which is *used* and replaced by the wide store.
9075     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9076       EarliestNodeUsed = i;
9077   }
9078
9079   // Find if it is better to use vectors or integers to load and store
9080   // to memory.
9081   EVT JointMemOpVT;
9082   if (UseVectorTy) {
9083     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9084   } else {
9085     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9086     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9087   }
9088
9089   SDLoc LoadDL(LoadNodes[0].MemNode);
9090   SDLoc StoreDL(StoreNodes[0].MemNode);
9091
9092   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9093   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9094                                 FirstLoad->getChain(),
9095                                 FirstLoad->getBasePtr(),
9096                                 FirstLoad->getPointerInfo(),
9097                                 false, false, false,
9098                                 FirstLoad->getAlignment());
9099
9100   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9101                                   FirstInChain->getBasePtr(),
9102                                   FirstInChain->getPointerInfo(), false, false,
9103                                   FirstInChain->getAlignment());
9104
9105   // Replace one of the loads with the new load.
9106   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9107   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9108                                 SDValue(NewLoad.getNode(), 1));
9109
9110   // Remove the rest of the load chains.
9111   for (unsigned i = 1; i < NumElem ; ++i) {
9112     // Replace all chain users of the old load nodes with the chain of the new
9113     // load node.
9114     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9115     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9116   }
9117
9118   // Replace the first store with the new store.
9119   CombineTo(EarliestOp, NewStore);
9120   // Erase all other stores.
9121   for (unsigned i = 0; i < NumElem ; ++i) {
9122     // Remove all Store nodes.
9123     if (StoreNodes[i].MemNode == EarliestOp)
9124       continue;
9125     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9126     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9127     removeFromWorkList(St);
9128     DAG.DeleteNode(St);
9129   }
9130
9131   return true;
9132 }
9133
9134 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9135   StoreSDNode *ST  = cast<StoreSDNode>(N);
9136   SDValue Chain = ST->getChain();
9137   SDValue Value = ST->getValue();
9138   SDValue Ptr   = ST->getBasePtr();
9139
9140   // If this is a store of a bit convert, store the input value if the
9141   // resultant store does not need a higher alignment than the original.
9142   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9143       ST->isUnindexed()) {
9144     unsigned OrigAlign = ST->getAlignment();
9145     EVT SVT = Value.getOperand(0).getValueType();
9146     unsigned Align = TLI.getDataLayout()->
9147       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9148     if (Align <= OrigAlign &&
9149         ((!LegalOperations && !ST->isVolatile()) ||
9150          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9151       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9152                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9153                           ST->isNonTemporal(), OrigAlign,
9154                           ST->getTBAAInfo());
9155   }
9156
9157   // Turn 'store undef, Ptr' -> nothing.
9158   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9159     return Chain;
9160
9161   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9162   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9163     // NOTE: If the original store is volatile, this transform must not increase
9164     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9165     // processor operation but an i64 (which is not legal) requires two.  So the
9166     // transform should not be done in this case.
9167     if (Value.getOpcode() != ISD::TargetConstantFP) {
9168       SDValue Tmp;
9169       switch (CFP->getSimpleValueType(0).SimpleTy) {
9170       default: llvm_unreachable("Unknown FP type");
9171       case MVT::f16:    // We don't do this for these yet.
9172       case MVT::f80:
9173       case MVT::f128:
9174       case MVT::ppcf128:
9175         break;
9176       case MVT::f32:
9177         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9178             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9179           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9180                               bitcastToAPInt().getZExtValue(), MVT::i32);
9181           return DAG.getStore(Chain, SDLoc(N), Tmp,
9182                               Ptr, ST->getMemOperand());
9183         }
9184         break;
9185       case MVT::f64:
9186         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9187              !ST->isVolatile()) ||
9188             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9189           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9190                                 getZExtValue(), MVT::i64);
9191           return DAG.getStore(Chain, SDLoc(N), Tmp,
9192                               Ptr, ST->getMemOperand());
9193         }
9194
9195         if (!ST->isVolatile() &&
9196             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9197           // Many FP stores are not made apparent until after legalize, e.g. for
9198           // argument passing.  Since this is so common, custom legalize the
9199           // 64-bit integer store into two 32-bit stores.
9200           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9201           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9202           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9203           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9204
9205           unsigned Alignment = ST->getAlignment();
9206           bool isVolatile = ST->isVolatile();
9207           bool isNonTemporal = ST->isNonTemporal();
9208           const MDNode *TBAAInfo = ST->getTBAAInfo();
9209
9210           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9211                                      Ptr, ST->getPointerInfo(),
9212                                      isVolatile, isNonTemporal,
9213                                      ST->getAlignment(), TBAAInfo);
9214           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9215                             DAG.getConstant(4, Ptr.getValueType()));
9216           Alignment = MinAlign(Alignment, 4U);
9217           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9218                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9219                                      isVolatile, isNonTemporal,
9220                                      Alignment, TBAAInfo);
9221           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9222                              St0, St1);
9223         }
9224
9225         break;
9226       }
9227     }
9228   }
9229
9230   // Try to infer better alignment information than the store already has.
9231   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9232     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9233       if (Align > ST->getAlignment())
9234         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9235                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9236                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9237                                  ST->getTBAAInfo());
9238     }
9239   }
9240
9241   // Try transforming a pair floating point load / store ops to integer
9242   // load / store ops.
9243   SDValue NewST = TransformFPLoadStorePair(N);
9244   if (NewST.getNode())
9245     return NewST;
9246
9247   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9248     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9249   if (UseAA) {
9250     // Walk up chain skipping non-aliasing memory nodes.
9251     SDValue BetterChain = FindBetterChain(N, Chain);
9252
9253     // If there is a better chain.
9254     if (Chain != BetterChain) {
9255       SDValue ReplStore;
9256
9257       // Replace the chain to avoid dependency.
9258       if (ST->isTruncatingStore()) {
9259         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9260                                       ST->getMemoryVT(), ST->getMemOperand());
9261       } else {
9262         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9263                                  ST->getMemOperand());
9264       }
9265
9266       // Create token to keep both nodes around.
9267       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9268                                   MVT::Other, Chain, ReplStore);
9269
9270       // Make sure the new and old chains are cleaned up.
9271       AddToWorkList(Token.getNode());
9272
9273       // Don't add users to work list.
9274       return CombineTo(N, Token, false);
9275     }
9276   }
9277
9278   // Try transforming N to an indexed store.
9279   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9280     return SDValue(N, 0);
9281
9282   // FIXME: is there such a thing as a truncating indexed store?
9283   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9284       Value.getValueType().isInteger()) {
9285     // See if we can simplify the input to this truncstore with knowledge that
9286     // only the low bits are being used.  For example:
9287     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9288     SDValue Shorter =
9289       GetDemandedBits(Value,
9290                       APInt::getLowBitsSet(
9291                         Value.getValueType().getScalarType().getSizeInBits(),
9292                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9293     AddToWorkList(Value.getNode());
9294     if (Shorter.getNode())
9295       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9296                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9297
9298     // Otherwise, see if we can simplify the operation with
9299     // SimplifyDemandedBits, which only works if the value has a single use.
9300     if (SimplifyDemandedBits(Value,
9301                         APInt::getLowBitsSet(
9302                           Value.getValueType().getScalarType().getSizeInBits(),
9303                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9304       return SDValue(N, 0);
9305   }
9306
9307   // If this is a load followed by a store to the same location, then the store
9308   // is dead/noop.
9309   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9310     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9311         ST->isUnindexed() && !ST->isVolatile() &&
9312         // There can't be any side effects between the load and store, such as
9313         // a call or store.
9314         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9315       // The store is dead, remove it.
9316       return Chain;
9317     }
9318   }
9319
9320   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9321   // truncating store.  We can do this even if this is already a truncstore.
9322   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9323       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9324       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9325                             ST->getMemoryVT())) {
9326     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9327                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9328   }
9329
9330   // Only perform this optimization before the types are legal, because we
9331   // don't want to perform this optimization on every DAGCombine invocation.
9332   if (!LegalTypes) {
9333     bool EverChanged = false;
9334
9335     do {
9336       // There can be multiple store sequences on the same chain.
9337       // Keep trying to merge store sequences until we are unable to do so
9338       // or until we merge the last store on the chain.
9339       bool Changed = MergeConsecutiveStores(ST);
9340       EverChanged |= Changed;
9341       if (!Changed) break;
9342     } while (ST->getOpcode() != ISD::DELETED_NODE);
9343
9344     if (EverChanged)
9345       return SDValue(N, 0);
9346   }
9347
9348   return ReduceLoadOpStoreWidth(N);
9349 }
9350
9351 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9352   SDValue InVec = N->getOperand(0);
9353   SDValue InVal = N->getOperand(1);
9354   SDValue EltNo = N->getOperand(2);
9355   SDLoc dl(N);
9356
9357   // If the inserted element is an UNDEF, just use the input vector.
9358   if (InVal.getOpcode() == ISD::UNDEF)
9359     return InVec;
9360
9361   EVT VT = InVec.getValueType();
9362
9363   // If we can't generate a legal BUILD_VECTOR, exit
9364   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9365     return SDValue();
9366
9367   // Check that we know which element is being inserted
9368   if (!isa<ConstantSDNode>(EltNo))
9369     return SDValue();
9370   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9371
9372   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9373   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9374   // vector elements.
9375   SmallVector<SDValue, 8> Ops;
9376   // Do not combine these two vectors if the output vector will not replace
9377   // the input vector.
9378   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9379     Ops.append(InVec.getNode()->op_begin(),
9380                InVec.getNode()->op_end());
9381   } else if (InVec.getOpcode() == ISD::UNDEF) {
9382     unsigned NElts = VT.getVectorNumElements();
9383     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9384   } else {
9385     return SDValue();
9386   }
9387
9388   // Insert the element
9389   if (Elt < Ops.size()) {
9390     // All the operands of BUILD_VECTOR must have the same type;
9391     // we enforce that here.
9392     EVT OpVT = Ops[0].getValueType();
9393     if (InVal.getValueType() != OpVT)
9394       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9395                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9396                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9397     Ops[Elt] = InVal;
9398   }
9399
9400   // Return the new vector
9401   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9402                      VT, &Ops[0], Ops.size());
9403 }
9404
9405 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9406   // (vextract (scalar_to_vector val, 0) -> val
9407   SDValue InVec = N->getOperand(0);
9408   EVT VT = InVec.getValueType();
9409   EVT NVT = N->getValueType(0);
9410
9411   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9412     // Check if the result type doesn't match the inserted element type. A
9413     // SCALAR_TO_VECTOR may truncate the inserted element and the
9414     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9415     SDValue InOp = InVec.getOperand(0);
9416     if (InOp.getValueType() != NVT) {
9417       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9418       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9419     }
9420     return InOp;
9421   }
9422
9423   SDValue EltNo = N->getOperand(1);
9424   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9425
9426   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9427   // We only perform this optimization before the op legalization phase because
9428   // we may introduce new vector instructions which are not backed by TD
9429   // patterns. For example on AVX, extracting elements from a wide vector
9430   // without using extract_subvector.
9431   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9432       && ConstEltNo && !LegalOperations) {
9433     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9434     int NumElem = VT.getVectorNumElements();
9435     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9436     // Find the new index to extract from.
9437     int OrigElt = SVOp->getMaskElt(Elt);
9438
9439     // Extracting an undef index is undef.
9440     if (OrigElt == -1)
9441       return DAG.getUNDEF(NVT);
9442
9443     // Select the right vector half to extract from.
9444     if (OrigElt < NumElem) {
9445       InVec = InVec->getOperand(0);
9446     } else {
9447       InVec = InVec->getOperand(1);
9448       OrigElt -= NumElem;
9449     }
9450
9451     EVT IndexTy = TLI.getVectorIdxTy();
9452     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9453                        InVec, DAG.getConstant(OrigElt, IndexTy));
9454   }
9455
9456   // Perform only after legalization to ensure build_vector / vector_shuffle
9457   // optimizations have already been done.
9458   if (!LegalOperations) return SDValue();
9459
9460   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9461   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9462   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9463
9464   if (ConstEltNo) {
9465     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9466     bool NewLoad = false;
9467     bool BCNumEltsChanged = false;
9468     EVT ExtVT = VT.getVectorElementType();
9469     EVT LVT = ExtVT;
9470
9471     // If the result of load has to be truncated, then it's not necessarily
9472     // profitable.
9473     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9474       return SDValue();
9475
9476     if (InVec.getOpcode() == ISD::BITCAST) {
9477       // Don't duplicate a load with other uses.
9478       if (!InVec.hasOneUse())
9479         return SDValue();
9480
9481       EVT BCVT = InVec.getOperand(0).getValueType();
9482       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9483         return SDValue();
9484       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9485         BCNumEltsChanged = true;
9486       InVec = InVec.getOperand(0);
9487       ExtVT = BCVT.getVectorElementType();
9488       NewLoad = true;
9489     }
9490
9491     LoadSDNode *LN0 = NULL;
9492     const ShuffleVectorSDNode *SVN = NULL;
9493     if (ISD::isNormalLoad(InVec.getNode())) {
9494       LN0 = cast<LoadSDNode>(InVec);
9495     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9496                InVec.getOperand(0).getValueType() == ExtVT &&
9497                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9498       // Don't duplicate a load with other uses.
9499       if (!InVec.hasOneUse())
9500         return SDValue();
9501
9502       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9503     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9504       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9505       // =>
9506       // (load $addr+1*size)
9507
9508       // Don't duplicate a load with other uses.
9509       if (!InVec.hasOneUse())
9510         return SDValue();
9511
9512       // If the bit convert changed the number of elements, it is unsafe
9513       // to examine the mask.
9514       if (BCNumEltsChanged)
9515         return SDValue();
9516
9517       // Select the input vector, guarding against out of range extract vector.
9518       unsigned NumElems = VT.getVectorNumElements();
9519       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9520       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9521
9522       if (InVec.getOpcode() == ISD::BITCAST) {
9523         // Don't duplicate a load with other uses.
9524         if (!InVec.hasOneUse())
9525           return SDValue();
9526
9527         InVec = InVec.getOperand(0);
9528       }
9529       if (ISD::isNormalLoad(InVec.getNode())) {
9530         LN0 = cast<LoadSDNode>(InVec);
9531         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9532       }
9533     }
9534
9535     // Make sure we found a non-volatile load and the extractelement is
9536     // the only use.
9537     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9538       return SDValue();
9539
9540     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9541     if (Elt == -1)
9542       return DAG.getUNDEF(LVT);
9543
9544     unsigned Align = LN0->getAlignment();
9545     if (NewLoad) {
9546       // Check the resultant load doesn't need a higher alignment than the
9547       // original load.
9548       unsigned NewAlign =
9549         TLI.getDataLayout()
9550             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9551
9552       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9553         return SDValue();
9554
9555       Align = NewAlign;
9556     }
9557
9558     SDValue NewPtr = LN0->getBasePtr();
9559     unsigned PtrOff = 0;
9560
9561     if (Elt) {
9562       PtrOff = LVT.getSizeInBits() * Elt / 8;
9563       EVT PtrType = NewPtr.getValueType();
9564       if (TLI.isBigEndian())
9565         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9566       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9567                            DAG.getConstant(PtrOff, PtrType));
9568     }
9569
9570     // The replacement we need to do here is a little tricky: we need to
9571     // replace an extractelement of a load with a load.
9572     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9573     // Note that this replacement assumes that the extractvalue is the only
9574     // use of the load; that's okay because we don't want to perform this
9575     // transformation in other cases anyway.
9576     SDValue Load;
9577     SDValue Chain;
9578     if (NVT.bitsGT(LVT)) {
9579       // If the result type of vextract is wider than the load, then issue an
9580       // extending load instead.
9581       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9582         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9583       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9584                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9585                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9586                             Align, LN0->getTBAAInfo());
9587       Chain = Load.getValue(1);
9588     } else {
9589       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9590                          LN0->getPointerInfo().getWithOffset(PtrOff),
9591                          LN0->isVolatile(), LN0->isNonTemporal(),
9592                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9593       Chain = Load.getValue(1);
9594       if (NVT.bitsLT(LVT))
9595         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9596       else
9597         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9598     }
9599     WorkListRemover DeadNodes(*this);
9600     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9601     SDValue To[] = { Load, Chain };
9602     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9603     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9604     // worklist explicitly as well.
9605     AddToWorkList(Load.getNode());
9606     AddUsersToWorkList(Load.getNode()); // Add users too
9607     // Make sure to revisit this node to clean it up; it will usually be dead.
9608     AddToWorkList(N);
9609     return SDValue(N, 0);
9610   }
9611
9612   return SDValue();
9613 }
9614
9615 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9616 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9617   // We perform this optimization post type-legalization because
9618   // the type-legalizer often scalarizes integer-promoted vectors.
9619   // Performing this optimization before may create bit-casts which
9620   // will be type-legalized to complex code sequences.
9621   // We perform this optimization only before the operation legalizer because we
9622   // may introduce illegal operations.
9623   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9624     return SDValue();
9625
9626   unsigned NumInScalars = N->getNumOperands();
9627   SDLoc dl(N);
9628   EVT VT = N->getValueType(0);
9629
9630   // Check to see if this is a BUILD_VECTOR of a bunch of values
9631   // which come from any_extend or zero_extend nodes. If so, we can create
9632   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9633   // optimizations. We do not handle sign-extend because we can't fill the sign
9634   // using shuffles.
9635   EVT SourceType = MVT::Other;
9636   bool AllAnyExt = true;
9637
9638   for (unsigned i = 0; i != NumInScalars; ++i) {
9639     SDValue In = N->getOperand(i);
9640     // Ignore undef inputs.
9641     if (In.getOpcode() == ISD::UNDEF) continue;
9642
9643     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9644     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9645
9646     // Abort if the element is not an extension.
9647     if (!ZeroExt && !AnyExt) {
9648       SourceType = MVT::Other;
9649       break;
9650     }
9651
9652     // The input is a ZeroExt or AnyExt. Check the original type.
9653     EVT InTy = In.getOperand(0).getValueType();
9654
9655     // Check that all of the widened source types are the same.
9656     if (SourceType == MVT::Other)
9657       // First time.
9658       SourceType = InTy;
9659     else if (InTy != SourceType) {
9660       // Multiple income types. Abort.
9661       SourceType = MVT::Other;
9662       break;
9663     }
9664
9665     // Check if all of the extends are ANY_EXTENDs.
9666     AllAnyExt &= AnyExt;
9667   }
9668
9669   // In order to have valid types, all of the inputs must be extended from the
9670   // same source type and all of the inputs must be any or zero extend.
9671   // Scalar sizes must be a power of two.
9672   EVT OutScalarTy = VT.getScalarType();
9673   bool ValidTypes = SourceType != MVT::Other &&
9674                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9675                  isPowerOf2_32(SourceType.getSizeInBits());
9676
9677   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9678   // turn into a single shuffle instruction.
9679   if (!ValidTypes)
9680     return SDValue();
9681
9682   bool isLE = TLI.isLittleEndian();
9683   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9684   assert(ElemRatio > 1 && "Invalid element size ratio");
9685   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9686                                DAG.getConstant(0, SourceType);
9687
9688   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9689   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9690
9691   // Populate the new build_vector
9692   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9693     SDValue Cast = N->getOperand(i);
9694     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9695             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9696             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9697     SDValue In;
9698     if (Cast.getOpcode() == ISD::UNDEF)
9699       In = DAG.getUNDEF(SourceType);
9700     else
9701       In = Cast->getOperand(0);
9702     unsigned Index = isLE ? (i * ElemRatio) :
9703                             (i * ElemRatio + (ElemRatio - 1));
9704
9705     assert(Index < Ops.size() && "Invalid index");
9706     Ops[Index] = In;
9707   }
9708
9709   // The type of the new BUILD_VECTOR node.
9710   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9711   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9712          "Invalid vector size");
9713   // Check if the new vector type is legal.
9714   if (!isTypeLegal(VecVT)) return SDValue();
9715
9716   // Make the new BUILD_VECTOR.
9717   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9718
9719   // The new BUILD_VECTOR node has the potential to be further optimized.
9720   AddToWorkList(BV.getNode());
9721   // Bitcast to the desired type.
9722   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9723 }
9724
9725 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9726   EVT VT = N->getValueType(0);
9727
9728   unsigned NumInScalars = N->getNumOperands();
9729   SDLoc dl(N);
9730
9731   EVT SrcVT = MVT::Other;
9732   unsigned Opcode = ISD::DELETED_NODE;
9733   unsigned NumDefs = 0;
9734
9735   for (unsigned i = 0; i != NumInScalars; ++i) {
9736     SDValue In = N->getOperand(i);
9737     unsigned Opc = In.getOpcode();
9738
9739     if (Opc == ISD::UNDEF)
9740       continue;
9741
9742     // If all scalar values are floats and converted from integers.
9743     if (Opcode == ISD::DELETED_NODE &&
9744         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9745       Opcode = Opc;
9746     }
9747
9748     if (Opc != Opcode)
9749       return SDValue();
9750
9751     EVT InVT = In.getOperand(0).getValueType();
9752
9753     // If all scalar values are typed differently, bail out. It's chosen to
9754     // simplify BUILD_VECTOR of integer types.
9755     if (SrcVT == MVT::Other)
9756       SrcVT = InVT;
9757     if (SrcVT != InVT)
9758       return SDValue();
9759     NumDefs++;
9760   }
9761
9762   // If the vector has just one element defined, it's not worth to fold it into
9763   // a vectorized one.
9764   if (NumDefs < 2)
9765     return SDValue();
9766
9767   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9768          && "Should only handle conversion from integer to float.");
9769   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9770
9771   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9772
9773   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9774     return SDValue();
9775
9776   SmallVector<SDValue, 8> Opnds;
9777   for (unsigned i = 0; i != NumInScalars; ++i) {
9778     SDValue In = N->getOperand(i);
9779
9780     if (In.getOpcode() == ISD::UNDEF)
9781       Opnds.push_back(DAG.getUNDEF(SrcVT));
9782     else
9783       Opnds.push_back(In.getOperand(0));
9784   }
9785   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9786                            &Opnds[0], Opnds.size());
9787   AddToWorkList(BV.getNode());
9788
9789   return DAG.getNode(Opcode, dl, VT, BV);
9790 }
9791
9792 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9793   unsigned NumInScalars = N->getNumOperands();
9794   SDLoc dl(N);
9795   EVT VT = N->getValueType(0);
9796
9797   // A vector built entirely of undefs is undef.
9798   if (ISD::allOperandsUndef(N))
9799     return DAG.getUNDEF(VT);
9800
9801   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9802   if (V.getNode())
9803     return V;
9804
9805   V = reduceBuildVecConvertToConvertBuildVec(N);
9806   if (V.getNode())
9807     return V;
9808
9809   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9810   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9811   // at most two distinct vectors, turn this into a shuffle node.
9812
9813   // May only combine to shuffle after legalize if shuffle is legal.
9814   if (LegalOperations &&
9815       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9816     return SDValue();
9817
9818   SDValue VecIn1, VecIn2;
9819   for (unsigned i = 0; i != NumInScalars; ++i) {
9820     // Ignore undef inputs.
9821     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9822
9823     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9824     // constant index, bail out.
9825     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9826         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9827       VecIn1 = VecIn2 = SDValue(0, 0);
9828       break;
9829     }
9830
9831     // We allow up to two distinct input vectors.
9832     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9833     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9834       continue;
9835
9836     if (VecIn1.getNode() == 0) {
9837       VecIn1 = ExtractedFromVec;
9838     } else if (VecIn2.getNode() == 0) {
9839       VecIn2 = ExtractedFromVec;
9840     } else {
9841       // Too many inputs.
9842       VecIn1 = VecIn2 = SDValue(0, 0);
9843       break;
9844     }
9845   }
9846
9847     // If everything is good, we can make a shuffle operation.
9848   if (VecIn1.getNode()) {
9849     SmallVector<int, 8> Mask;
9850     for (unsigned i = 0; i != NumInScalars; ++i) {
9851       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9852         Mask.push_back(-1);
9853         continue;
9854       }
9855
9856       // If extracting from the first vector, just use the index directly.
9857       SDValue Extract = N->getOperand(i);
9858       SDValue ExtVal = Extract.getOperand(1);
9859       if (Extract.getOperand(0) == VecIn1) {
9860         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9861         if (ExtIndex > VT.getVectorNumElements())
9862           return SDValue();
9863
9864         Mask.push_back(ExtIndex);
9865         continue;
9866       }
9867
9868       // Otherwise, use InIdx + VecSize
9869       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9870       Mask.push_back(Idx+NumInScalars);
9871     }
9872
9873     // We can't generate a shuffle node with mismatched input and output types.
9874     // Attempt to transform a single input vector to the correct type.
9875     if ((VT != VecIn1.getValueType())) {
9876       // We don't support shuffeling between TWO values of different types.
9877       if (VecIn2.getNode() != 0)
9878         return SDValue();
9879
9880       // We only support widening of vectors which are half the size of the
9881       // output registers. For example XMM->YMM widening on X86 with AVX.
9882       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9883         return SDValue();
9884
9885       // If the input vector type has a different base type to the output
9886       // vector type, bail out.
9887       if (VecIn1.getValueType().getVectorElementType() !=
9888           VT.getVectorElementType())
9889         return SDValue();
9890
9891       // Widen the input vector by adding undef values.
9892       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9893                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9894     }
9895
9896     // If VecIn2 is unused then change it to undef.
9897     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9898
9899     // Check that we were able to transform all incoming values to the same
9900     // type.
9901     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9902         VecIn1.getValueType() != VT)
9903           return SDValue();
9904
9905     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9906     if (!isTypeLegal(VT))
9907       return SDValue();
9908
9909     // Return the new VECTOR_SHUFFLE node.
9910     SDValue Ops[2];
9911     Ops[0] = VecIn1;
9912     Ops[1] = VecIn2;
9913     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9914   }
9915
9916   return SDValue();
9917 }
9918
9919 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9920   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9921   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9922   // inputs come from at most two distinct vectors, turn this into a shuffle
9923   // node.
9924
9925   // If we only have one input vector, we don't need to do any concatenation.
9926   if (N->getNumOperands() == 1)
9927     return N->getOperand(0);
9928
9929   // Check if all of the operands are undefs.
9930   EVT VT = N->getValueType(0);
9931   if (ISD::allOperandsUndef(N))
9932     return DAG.getUNDEF(VT);
9933
9934   // Optimize concat_vectors where one of the vectors is undef.
9935   if (N->getNumOperands() == 2 &&
9936       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
9937     SDValue In = N->getOperand(0);
9938     assert(In.getValueType().isVector() && "Must concat vectors");
9939
9940     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
9941     if (In->getOpcode() == ISD::BITCAST &&
9942         !In->getOperand(0)->getValueType(0).isVector()) {
9943       SDValue Scalar = In->getOperand(0);
9944       EVT SclTy = Scalar->getValueType(0);
9945
9946       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
9947         return SDValue();
9948
9949       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
9950                                  VT.getSizeInBits() / SclTy.getSizeInBits());
9951       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
9952         return SDValue();
9953
9954       SDLoc dl = SDLoc(N);
9955       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
9956       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
9957     }
9958   }
9959
9960   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9961   // nodes often generate nop CONCAT_VECTOR nodes.
9962   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9963   // place the incoming vectors at the exact same location.
9964   SDValue SingleSource = SDValue();
9965   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9966
9967   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9968     SDValue Op = N->getOperand(i);
9969
9970     if (Op.getOpcode() == ISD::UNDEF)
9971       continue;
9972
9973     // Check if this is the identity extract:
9974     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9975       return SDValue();
9976
9977     // Find the single incoming vector for the extract_subvector.
9978     if (SingleSource.getNode()) {
9979       if (Op.getOperand(0) != SingleSource)
9980         return SDValue();
9981     } else {
9982       SingleSource = Op.getOperand(0);
9983
9984       // Check the source type is the same as the type of the result.
9985       // If not, this concat may extend the vector, so we can not
9986       // optimize it away.
9987       if (SingleSource.getValueType() != N->getValueType(0))
9988         return SDValue();
9989     }
9990
9991     unsigned IdentityIndex = i * PartNumElem;
9992     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9993     // The extract index must be constant.
9994     if (!CS)
9995       return SDValue();
9996
9997     // Check that we are reading from the identity index.
9998     if (CS->getZExtValue() != IdentityIndex)
9999       return SDValue();
10000   }
10001
10002   if (SingleSource.getNode())
10003     return SingleSource;
10004
10005   return SDValue();
10006 }
10007
10008 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10009   EVT NVT = N->getValueType(0);
10010   SDValue V = N->getOperand(0);
10011
10012   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10013     // Combine:
10014     //    (extract_subvec (concat V1, V2, ...), i)
10015     // Into:
10016     //    Vi if possible
10017     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10018     // type.
10019     if (V->getOperand(0).getValueType() != NVT)
10020       return SDValue();
10021     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10022     unsigned NumElems = NVT.getVectorNumElements();
10023     assert((Idx % NumElems) == 0 &&
10024            "IDX in concat is not a multiple of the result vector length.");
10025     return V->getOperand(Idx / NumElems);
10026   }
10027
10028   // Skip bitcasting
10029   if (V->getOpcode() == ISD::BITCAST)
10030     V = V.getOperand(0);
10031
10032   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10033     SDLoc dl(N);
10034     // Handle only simple case where vector being inserted and vector
10035     // being extracted are of same type, and are half size of larger vectors.
10036     EVT BigVT = V->getOperand(0).getValueType();
10037     EVT SmallVT = V->getOperand(1).getValueType();
10038     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10039       return SDValue();
10040
10041     // Only handle cases where both indexes are constants with the same type.
10042     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10043     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10044
10045     if (InsIdx && ExtIdx &&
10046         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10047         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10048       // Combine:
10049       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10050       // Into:
10051       //    indices are equal or bit offsets are equal => V1
10052       //    otherwise => (extract_subvec V1, ExtIdx)
10053       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10054           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10055         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10056       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10057                          DAG.getNode(ISD::BITCAST, dl,
10058                                      N->getOperand(0).getValueType(),
10059                                      V->getOperand(0)), N->getOperand(1));
10060     }
10061   }
10062
10063   return SDValue();
10064 }
10065
10066 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10067 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10068   EVT VT = N->getValueType(0);
10069   unsigned NumElts = VT.getVectorNumElements();
10070
10071   SDValue N0 = N->getOperand(0);
10072   SDValue N1 = N->getOperand(1);
10073   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10074
10075   SmallVector<SDValue, 4> Ops;
10076   EVT ConcatVT = N0.getOperand(0).getValueType();
10077   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10078   unsigned NumConcats = NumElts / NumElemsPerConcat;
10079
10080   // Look at every vector that's inserted. We're looking for exact
10081   // subvector-sized copies from a concatenated vector
10082   for (unsigned I = 0; I != NumConcats; ++I) {
10083     // Make sure we're dealing with a copy.
10084     unsigned Begin = I * NumElemsPerConcat;
10085     bool AllUndef = true, NoUndef = true;
10086     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10087       if (SVN->getMaskElt(J) >= 0)
10088         AllUndef = false;
10089       else
10090         NoUndef = false;
10091     }
10092
10093     if (NoUndef) {
10094       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10095         return SDValue();
10096
10097       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10098         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10099           return SDValue();
10100
10101       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10102       if (FirstElt < N0.getNumOperands())
10103         Ops.push_back(N0.getOperand(FirstElt));
10104       else
10105         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10106
10107     } else if (AllUndef) {
10108       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10109     } else { // Mixed with general masks and undefs, can't do optimization.
10110       return SDValue();
10111     }
10112   }
10113
10114   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10115                      Ops.size());
10116 }
10117
10118 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10119   EVT VT = N->getValueType(0);
10120   unsigned NumElts = VT.getVectorNumElements();
10121
10122   SDValue N0 = N->getOperand(0);
10123   SDValue N1 = N->getOperand(1);
10124
10125   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10126
10127   // Canonicalize shuffle undef, undef -> undef
10128   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10129     return DAG.getUNDEF(VT);
10130
10131   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10132
10133   // Canonicalize shuffle v, v -> v, undef
10134   if (N0 == N1) {
10135     SmallVector<int, 8> NewMask;
10136     for (unsigned i = 0; i != NumElts; ++i) {
10137       int Idx = SVN->getMaskElt(i);
10138       if (Idx >= (int)NumElts) Idx -= NumElts;
10139       NewMask.push_back(Idx);
10140     }
10141     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10142                                 &NewMask[0]);
10143   }
10144
10145   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10146   if (N0.getOpcode() == ISD::UNDEF) {
10147     SmallVector<int, 8> NewMask;
10148     for (unsigned i = 0; i != NumElts; ++i) {
10149       int Idx = SVN->getMaskElt(i);
10150       if (Idx >= 0) {
10151         if (Idx >= (int)NumElts)
10152           Idx -= NumElts;
10153         else
10154           Idx = -1; // remove reference to lhs
10155       }
10156       NewMask.push_back(Idx);
10157     }
10158     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10159                                 &NewMask[0]);
10160   }
10161
10162   // Remove references to rhs if it is undef
10163   if (N1.getOpcode() == ISD::UNDEF) {
10164     bool Changed = false;
10165     SmallVector<int, 8> NewMask;
10166     for (unsigned i = 0; i != NumElts; ++i) {
10167       int Idx = SVN->getMaskElt(i);
10168       if (Idx >= (int)NumElts) {
10169         Idx = -1;
10170         Changed = true;
10171       }
10172       NewMask.push_back(Idx);
10173     }
10174     if (Changed)
10175       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10176   }
10177
10178   // If it is a splat, check if the argument vector is another splat or a
10179   // build_vector with all scalar elements the same.
10180   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10181     SDNode *V = N0.getNode();
10182
10183     // If this is a bit convert that changes the element type of the vector but
10184     // not the number of vector elements, look through it.  Be careful not to
10185     // look though conversions that change things like v4f32 to v2f64.
10186     if (V->getOpcode() == ISD::BITCAST) {
10187       SDValue ConvInput = V->getOperand(0);
10188       if (ConvInput.getValueType().isVector() &&
10189           ConvInput.getValueType().getVectorNumElements() == NumElts)
10190         V = ConvInput.getNode();
10191     }
10192
10193     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10194       assert(V->getNumOperands() == NumElts &&
10195              "BUILD_VECTOR has wrong number of operands");
10196       SDValue Base;
10197       bool AllSame = true;
10198       for (unsigned i = 0; i != NumElts; ++i) {
10199         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10200           Base = V->getOperand(i);
10201           break;
10202         }
10203       }
10204       // Splat of <u, u, u, u>, return <u, u, u, u>
10205       if (!Base.getNode())
10206         return N0;
10207       for (unsigned i = 0; i != NumElts; ++i) {
10208         if (V->getOperand(i) != Base) {
10209           AllSame = false;
10210           break;
10211         }
10212       }
10213       // Splat of <x, x, x, x>, return <x, x, x, x>
10214       if (AllSame)
10215         return N0;
10216     }
10217   }
10218
10219   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10220       Level < AfterLegalizeVectorOps &&
10221       (N1.getOpcode() == ISD::UNDEF ||
10222       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10223        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10224     SDValue V = partitionShuffleOfConcats(N, DAG);
10225
10226     if (V.getNode())
10227       return V;
10228   }
10229
10230   // If this shuffle node is simply a swizzle of another shuffle node,
10231   // and it reverses the swizzle of the previous shuffle then we can
10232   // optimize shuffle(shuffle(x, undef), undef) -> x.
10233   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10234       N1.getOpcode() == ISD::UNDEF) {
10235
10236     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10237
10238     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10239     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10240       return SDValue();
10241
10242     // The incoming shuffle must be of the same type as the result of the
10243     // current shuffle.
10244     assert(OtherSV->getOperand(0).getValueType() == VT &&
10245            "Shuffle types don't match");
10246
10247     for (unsigned i = 0; i != NumElts; ++i) {
10248       int Idx = SVN->getMaskElt(i);
10249       assert(Idx < (int)NumElts && "Index references undef operand");
10250       // Next, this index comes from the first value, which is the incoming
10251       // shuffle. Adopt the incoming index.
10252       if (Idx >= 0)
10253         Idx = OtherSV->getMaskElt(Idx);
10254
10255       // The combined shuffle must map each index to itself.
10256       if (Idx >= 0 && (unsigned)Idx != i)
10257         return SDValue();
10258     }
10259
10260     return OtherSV->getOperand(0);
10261   }
10262
10263   return SDValue();
10264 }
10265
10266 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10267 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10268 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10269 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10270 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10271   EVT VT = N->getValueType(0);
10272   SDLoc dl(N);
10273   SDValue LHS = N->getOperand(0);
10274   SDValue RHS = N->getOperand(1);
10275   if (N->getOpcode() == ISD::AND) {
10276     if (RHS.getOpcode() == ISD::BITCAST)
10277       RHS = RHS.getOperand(0);
10278     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10279       SmallVector<int, 8> Indices;
10280       unsigned NumElts = RHS.getNumOperands();
10281       for (unsigned i = 0; i != NumElts; ++i) {
10282         SDValue Elt = RHS.getOperand(i);
10283         if (!isa<ConstantSDNode>(Elt))
10284           return SDValue();
10285
10286         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10287           Indices.push_back(i);
10288         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10289           Indices.push_back(NumElts);
10290         else
10291           return SDValue();
10292       }
10293
10294       // Let's see if the target supports this vector_shuffle.
10295       EVT RVT = RHS.getValueType();
10296       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10297         return SDValue();
10298
10299       // Return the new VECTOR_SHUFFLE node.
10300       EVT EltVT = RVT.getVectorElementType();
10301       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10302                                      DAG.getConstant(0, EltVT));
10303       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10304                                  RVT, &ZeroOps[0], ZeroOps.size());
10305       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10306       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10307       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10308     }
10309   }
10310
10311   return SDValue();
10312 }
10313
10314 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10315 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10316   assert(N->getValueType(0).isVector() &&
10317          "SimplifyVBinOp only works on vectors!");
10318
10319   SDValue LHS = N->getOperand(0);
10320   SDValue RHS = N->getOperand(1);
10321   SDValue Shuffle = XformToShuffleWithZero(N);
10322   if (Shuffle.getNode()) return Shuffle;
10323
10324   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10325   // this operation.
10326   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10327       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10328     SmallVector<SDValue, 8> Ops;
10329     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10330       SDValue LHSOp = LHS.getOperand(i);
10331       SDValue RHSOp = RHS.getOperand(i);
10332       // If these two elements can't be folded, bail out.
10333       if ((LHSOp.getOpcode() != ISD::UNDEF &&
10334            LHSOp.getOpcode() != ISD::Constant &&
10335            LHSOp.getOpcode() != ISD::ConstantFP) ||
10336           (RHSOp.getOpcode() != ISD::UNDEF &&
10337            RHSOp.getOpcode() != ISD::Constant &&
10338            RHSOp.getOpcode() != ISD::ConstantFP))
10339         break;
10340
10341       // Can't fold divide by zero.
10342       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10343           N->getOpcode() == ISD::FDIV) {
10344         if ((RHSOp.getOpcode() == ISD::Constant &&
10345              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10346             (RHSOp.getOpcode() == ISD::ConstantFP &&
10347              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10348           break;
10349       }
10350
10351       EVT VT = LHSOp.getValueType();
10352       EVT RVT = RHSOp.getValueType();
10353       if (RVT != VT) {
10354         // Integer BUILD_VECTOR operands may have types larger than the element
10355         // size (e.g., when the element type is not legal).  Prior to type
10356         // legalization, the types may not match between the two BUILD_VECTORS.
10357         // Truncate one of the operands to make them match.
10358         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10359           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10360         } else {
10361           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10362           VT = RVT;
10363         }
10364       }
10365       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10366                                    LHSOp, RHSOp);
10367       if (FoldOp.getOpcode() != ISD::UNDEF &&
10368           FoldOp.getOpcode() != ISD::Constant &&
10369           FoldOp.getOpcode() != ISD::ConstantFP)
10370         break;
10371       Ops.push_back(FoldOp);
10372       AddToWorkList(FoldOp.getNode());
10373     }
10374
10375     if (Ops.size() == LHS.getNumOperands())
10376       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10377                          LHS.getValueType(), &Ops[0], Ops.size());
10378   }
10379
10380   return SDValue();
10381 }
10382
10383 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10384 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10385   assert(N->getValueType(0).isVector() &&
10386          "SimplifyVUnaryOp only works on vectors!");
10387
10388   SDValue N0 = N->getOperand(0);
10389
10390   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10391     return SDValue();
10392
10393   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10394   SmallVector<SDValue, 8> Ops;
10395   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10396     SDValue Op = N0.getOperand(i);
10397     if (Op.getOpcode() != ISD::UNDEF &&
10398         Op.getOpcode() != ISD::ConstantFP)
10399       break;
10400     EVT EltVT = Op.getValueType();
10401     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10402     if (FoldOp.getOpcode() != ISD::UNDEF &&
10403         FoldOp.getOpcode() != ISD::ConstantFP)
10404       break;
10405     Ops.push_back(FoldOp);
10406     AddToWorkList(FoldOp.getNode());
10407   }
10408
10409   if (Ops.size() != N0.getNumOperands())
10410     return SDValue();
10411
10412   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10413                      N0.getValueType(), &Ops[0], Ops.size());
10414 }
10415
10416 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10417                                     SDValue N1, SDValue N2){
10418   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10419
10420   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10421                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10422
10423   // If we got a simplified select_cc node back from SimplifySelectCC, then
10424   // break it down into a new SETCC node, and a new SELECT node, and then return
10425   // the SELECT node, since we were called with a SELECT node.
10426   if (SCC.getNode()) {
10427     // Check to see if we got a select_cc back (to turn into setcc/select).
10428     // Otherwise, just return whatever node we got back, like fabs.
10429     if (SCC.getOpcode() == ISD::SELECT_CC) {
10430       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10431                                   N0.getValueType(),
10432                                   SCC.getOperand(0), SCC.getOperand(1),
10433                                   SCC.getOperand(4));
10434       AddToWorkList(SETCC.getNode());
10435       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10436                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10437     }
10438
10439     return SCC;
10440   }
10441   return SDValue();
10442 }
10443
10444 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10445 /// are the two values being selected between, see if we can simplify the
10446 /// select.  Callers of this should assume that TheSelect is deleted if this
10447 /// returns true.  As such, they should return the appropriate thing (e.g. the
10448 /// node) back to the top-level of the DAG combiner loop to avoid it being
10449 /// looked at.
10450 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10451                                     SDValue RHS) {
10452
10453   // Cannot simplify select with vector condition
10454   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10455
10456   // If this is a select from two identical things, try to pull the operation
10457   // through the select.
10458   if (LHS.getOpcode() != RHS.getOpcode() ||
10459       !LHS.hasOneUse() || !RHS.hasOneUse())
10460     return false;
10461
10462   // If this is a load and the token chain is identical, replace the select
10463   // of two loads with a load through a select of the address to load from.
10464   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10465   // constants have been dropped into the constant pool.
10466   if (LHS.getOpcode() == ISD::LOAD) {
10467     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10468     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10469
10470     // Token chains must be identical.
10471     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10472         // Do not let this transformation reduce the number of volatile loads.
10473         LLD->isVolatile() || RLD->isVolatile() ||
10474         // If this is an EXTLOAD, the VT's must match.
10475         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10476         // If this is an EXTLOAD, the kind of extension must match.
10477         (LLD->getExtensionType() != RLD->getExtensionType() &&
10478          // The only exception is if one of the extensions is anyext.
10479          LLD->getExtensionType() != ISD::EXTLOAD &&
10480          RLD->getExtensionType() != ISD::EXTLOAD) ||
10481         // FIXME: this discards src value information.  This is
10482         // over-conservative. It would be beneficial to be able to remember
10483         // both potential memory locations.  Since we are discarding
10484         // src value info, don't do the transformation if the memory
10485         // locations are not in the default address space.
10486         LLD->getPointerInfo().getAddrSpace() != 0 ||
10487         RLD->getPointerInfo().getAddrSpace() != 0 ||
10488         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10489                                       LLD->getBasePtr().getValueType()))
10490       return false;
10491
10492     // Check that the select condition doesn't reach either load.  If so,
10493     // folding this will induce a cycle into the DAG.  If not, this is safe to
10494     // xform, so create a select of the addresses.
10495     SDValue Addr;
10496     if (TheSelect->getOpcode() == ISD::SELECT) {
10497       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10498       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10499           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10500         return false;
10501       // The loads must not depend on one another.
10502       if (LLD->isPredecessorOf(RLD) ||
10503           RLD->isPredecessorOf(LLD))
10504         return false;
10505       Addr = DAG.getSelect(SDLoc(TheSelect),
10506                            LLD->getBasePtr().getValueType(),
10507                            TheSelect->getOperand(0), LLD->getBasePtr(),
10508                            RLD->getBasePtr());
10509     } else {  // Otherwise SELECT_CC
10510       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10511       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10512
10513       if ((LLD->hasAnyUseOfValue(1) &&
10514            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10515           (RLD->hasAnyUseOfValue(1) &&
10516            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10517         return false;
10518
10519       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10520                          LLD->getBasePtr().getValueType(),
10521                          TheSelect->getOperand(0),
10522                          TheSelect->getOperand(1),
10523                          LLD->getBasePtr(), RLD->getBasePtr(),
10524                          TheSelect->getOperand(4));
10525     }
10526
10527     SDValue Load;
10528     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10529       Load = DAG.getLoad(TheSelect->getValueType(0),
10530                          SDLoc(TheSelect),
10531                          // FIXME: Discards pointer and TBAA info.
10532                          LLD->getChain(), Addr, MachinePointerInfo(),
10533                          LLD->isVolatile(), LLD->isNonTemporal(),
10534                          LLD->isInvariant(), LLD->getAlignment());
10535     } else {
10536       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10537                             RLD->getExtensionType() : LLD->getExtensionType(),
10538                             SDLoc(TheSelect),
10539                             TheSelect->getValueType(0),
10540                             // FIXME: Discards pointer and TBAA info.
10541                             LLD->getChain(), Addr, MachinePointerInfo(),
10542                             LLD->getMemoryVT(), LLD->isVolatile(),
10543                             LLD->isNonTemporal(), LLD->getAlignment());
10544     }
10545
10546     // Users of the select now use the result of the load.
10547     CombineTo(TheSelect, Load);
10548
10549     // Users of the old loads now use the new load's chain.  We know the
10550     // old-load value is dead now.
10551     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10552     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10553     return true;
10554   }
10555
10556   return false;
10557 }
10558
10559 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10560 /// where 'cond' is the comparison specified by CC.
10561 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10562                                       SDValue N2, SDValue N3,
10563                                       ISD::CondCode CC, bool NotExtCompare) {
10564   // (x ? y : y) -> y.
10565   if (N2 == N3) return N2;
10566
10567   EVT VT = N2.getValueType();
10568   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10569   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10570   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10571
10572   // Determine if the condition we're dealing with is constant
10573   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10574                               N0, N1, CC, DL, false);
10575   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10576   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10577
10578   // fold select_cc true, x, y -> x
10579   if (SCCC && !SCCC->isNullValue())
10580     return N2;
10581   // fold select_cc false, x, y -> y
10582   if (SCCC && SCCC->isNullValue())
10583     return N3;
10584
10585   // Check to see if we can simplify the select into an fabs node
10586   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10587     // Allow either -0.0 or 0.0
10588     if (CFP->getValueAPF().isZero()) {
10589       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10590       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10591           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10592           N2 == N3.getOperand(0))
10593         return DAG.getNode(ISD::FABS, DL, VT, N0);
10594
10595       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10596       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10597           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10598           N2.getOperand(0) == N3)
10599         return DAG.getNode(ISD::FABS, DL, VT, N3);
10600     }
10601   }
10602
10603   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10604   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10605   // in it.  This is a win when the constant is not otherwise available because
10606   // it replaces two constant pool loads with one.  We only do this if the FP
10607   // type is known to be legal, because if it isn't, then we are before legalize
10608   // types an we want the other legalization to happen first (e.g. to avoid
10609   // messing with soft float) and if the ConstantFP is not legal, because if
10610   // it is legal, we may not need to store the FP constant in a constant pool.
10611   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10612     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10613       if (TLI.isTypeLegal(N2.getValueType()) &&
10614           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10615            TargetLowering::Legal) &&
10616           // If both constants have multiple uses, then we won't need to do an
10617           // extra load, they are likely around in registers for other users.
10618           (TV->hasOneUse() || FV->hasOneUse())) {
10619         Constant *Elts[] = {
10620           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10621           const_cast<ConstantFP*>(TV->getConstantFPValue())
10622         };
10623         Type *FPTy = Elts[0]->getType();
10624         const DataLayout &TD = *TLI.getDataLayout();
10625
10626         // Create a ConstantArray of the two constants.
10627         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10628         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10629                                             TD.getPrefTypeAlignment(FPTy));
10630         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10631
10632         // Get the offsets to the 0 and 1 element of the array so that we can
10633         // select between them.
10634         SDValue Zero = DAG.getIntPtrConstant(0);
10635         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10636         SDValue One = DAG.getIntPtrConstant(EltSize);
10637
10638         SDValue Cond = DAG.getSetCC(DL,
10639                                     getSetCCResultType(N0.getValueType()),
10640                                     N0, N1, CC);
10641         AddToWorkList(Cond.getNode());
10642         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10643                                           Cond, One, Zero);
10644         AddToWorkList(CstOffset.getNode());
10645         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10646                             CstOffset);
10647         AddToWorkList(CPIdx.getNode());
10648         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10649                            MachinePointerInfo::getConstantPool(), false,
10650                            false, false, Alignment);
10651
10652       }
10653     }
10654
10655   // Check to see if we can perform the "gzip trick", transforming
10656   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10657   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10658       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10659        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10660     EVT XType = N0.getValueType();
10661     EVT AType = N2.getValueType();
10662     if (XType.bitsGE(AType)) {
10663       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10664       // single-bit constant.
10665       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10666         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10667         ShCtV = XType.getSizeInBits()-ShCtV-1;
10668         SDValue ShCt = DAG.getConstant(ShCtV,
10669                                        getShiftAmountTy(N0.getValueType()));
10670         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10671                                     XType, N0, ShCt);
10672         AddToWorkList(Shift.getNode());
10673
10674         if (XType.bitsGT(AType)) {
10675           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10676           AddToWorkList(Shift.getNode());
10677         }
10678
10679         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10680       }
10681
10682       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10683                                   XType, N0,
10684                                   DAG.getConstant(XType.getSizeInBits()-1,
10685                                          getShiftAmountTy(N0.getValueType())));
10686       AddToWorkList(Shift.getNode());
10687
10688       if (XType.bitsGT(AType)) {
10689         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10690         AddToWorkList(Shift.getNode());
10691       }
10692
10693       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10694     }
10695   }
10696
10697   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10698   // where y is has a single bit set.
10699   // A plaintext description would be, we can turn the SELECT_CC into an AND
10700   // when the condition can be materialized as an all-ones register.  Any
10701   // single bit-test can be materialized as an all-ones register with
10702   // shift-left and shift-right-arith.
10703   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10704       N0->getValueType(0) == VT &&
10705       N1C && N1C->isNullValue() &&
10706       N2C && N2C->isNullValue()) {
10707     SDValue AndLHS = N0->getOperand(0);
10708     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10709     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10710       // Shift the tested bit over the sign bit.
10711       APInt AndMask = ConstAndRHS->getAPIntValue();
10712       SDValue ShlAmt =
10713         DAG.getConstant(AndMask.countLeadingZeros(),
10714                         getShiftAmountTy(AndLHS.getValueType()));
10715       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10716
10717       // Now arithmetic right shift it all the way over, so the result is either
10718       // all-ones, or zero.
10719       SDValue ShrAmt =
10720         DAG.getConstant(AndMask.getBitWidth()-1,
10721                         getShiftAmountTy(Shl.getValueType()));
10722       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10723
10724       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10725     }
10726   }
10727
10728   // fold select C, 16, 0 -> shl C, 4
10729   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10730     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10731       TargetLowering::ZeroOrOneBooleanContent) {
10732
10733     // If the caller doesn't want us to simplify this into a zext of a compare,
10734     // don't do it.
10735     if (NotExtCompare && N2C->getAPIntValue() == 1)
10736       return SDValue();
10737
10738     // Get a SetCC of the condition
10739     // NOTE: Don't create a SETCC if it's not legal on this target.
10740     if (!LegalOperations ||
10741         TLI.isOperationLegal(ISD::SETCC,
10742           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10743       SDValue Temp, SCC;
10744       // cast from setcc result type to select result type
10745       if (LegalTypes) {
10746         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10747                             N0, N1, CC);
10748         if (N2.getValueType().bitsLT(SCC.getValueType()))
10749           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10750                                         N2.getValueType());
10751         else
10752           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10753                              N2.getValueType(), SCC);
10754       } else {
10755         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10756         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10757                            N2.getValueType(), SCC);
10758       }
10759
10760       AddToWorkList(SCC.getNode());
10761       AddToWorkList(Temp.getNode());
10762
10763       if (N2C->getAPIntValue() == 1)
10764         return Temp;
10765
10766       // shl setcc result by log2 n2c
10767       return DAG.getNode(
10768           ISD::SHL, DL, N2.getValueType(), Temp,
10769           DAG.getConstant(N2C->getAPIntValue().logBase2(),
10770                           getShiftAmountTy(Temp.getValueType())));
10771     }
10772   }
10773
10774   // Check to see if this is the equivalent of setcc
10775   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10776   // otherwise, go ahead with the folds.
10777   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10778     EVT XType = N0.getValueType();
10779     if (!LegalOperations ||
10780         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10781       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10782       if (Res.getValueType() != VT)
10783         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10784       return Res;
10785     }
10786
10787     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10788     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10789         (!LegalOperations ||
10790          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10791       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10792       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10793                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10794                                        getShiftAmountTy(Ctlz.getValueType())));
10795     }
10796     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10797     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10798       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10799                                   XType, DAG.getConstant(0, XType), N0);
10800       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10801       return DAG.getNode(ISD::SRL, DL, XType,
10802                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10803                          DAG.getConstant(XType.getSizeInBits()-1,
10804                                          getShiftAmountTy(XType)));
10805     }
10806     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10807     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10808       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10809                                  DAG.getConstant(XType.getSizeInBits()-1,
10810                                          getShiftAmountTy(N0.getValueType())));
10811       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10812     }
10813   }
10814
10815   // Check to see if this is an integer abs.
10816   // select_cc setg[te] X,  0,  X, -X ->
10817   // select_cc setgt    X, -1,  X, -X ->
10818   // select_cc setl[te] X,  0, -X,  X ->
10819   // select_cc setlt    X,  1, -X,  X ->
10820   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10821   if (N1C) {
10822     ConstantSDNode *SubC = NULL;
10823     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10824          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10825         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10826       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10827     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10828               (N1C->isOne() && CC == ISD::SETLT)) &&
10829              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10830       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10831
10832     EVT XType = N0.getValueType();
10833     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10834       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10835                                   N0,
10836                                   DAG.getConstant(XType.getSizeInBits()-1,
10837                                          getShiftAmountTy(N0.getValueType())));
10838       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10839                                 XType, N0, Shift);
10840       AddToWorkList(Shift.getNode());
10841       AddToWorkList(Add.getNode());
10842       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10843     }
10844   }
10845
10846   return SDValue();
10847 }
10848
10849 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10850 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10851                                    SDValue N1, ISD::CondCode Cond,
10852                                    SDLoc DL, bool foldBooleans) {
10853   TargetLowering::DAGCombinerInfo
10854     DagCombineInfo(DAG, Level, false, this);
10855   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10856 }
10857
10858 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10859 /// return a DAG expression to select that will generate the same value by
10860 /// multiplying by a magic number.  See:
10861 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10862 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10863   std::vector<SDNode*> Built;
10864   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10865
10866   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10867        ii != ee; ++ii)
10868     AddToWorkList(*ii);
10869   return S;
10870 }
10871
10872 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10873 /// return a DAG expression to select that will generate the same value by
10874 /// multiplying by a magic number.  See:
10875 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10876 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10877   std::vector<SDNode*> Built;
10878   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10879
10880   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10881        ii != ee; ++ii)
10882     AddToWorkList(*ii);
10883   return S;
10884 }
10885
10886 /// FindBaseOffset - Return true if base is a frame index, which is known not
10887 // to alias with anything but itself.  Provides base object and offset as
10888 // results.
10889 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10890                            const GlobalValue *&GV, const void *&CV) {
10891   // Assume it is a primitive operation.
10892   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10893
10894   // If it's an adding a simple constant then integrate the offset.
10895   if (Base.getOpcode() == ISD::ADD) {
10896     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10897       Base = Base.getOperand(0);
10898       Offset += C->getZExtValue();
10899     }
10900   }
10901
10902   // Return the underlying GlobalValue, and update the Offset.  Return false
10903   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10904   // by multiple nodes with different offsets.
10905   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10906     GV = G->getGlobal();
10907     Offset += G->getOffset();
10908     return false;
10909   }
10910
10911   // Return the underlying Constant value, and update the Offset.  Return false
10912   // for ConstantSDNodes since the same constant pool entry may be represented
10913   // by multiple nodes with different offsets.
10914   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10915     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10916                                          : (const void *)C->getConstVal();
10917     Offset += C->getOffset();
10918     return false;
10919   }
10920   // If it's any of the following then it can't alias with anything but itself.
10921   return isa<FrameIndexSDNode>(Base);
10922 }
10923
10924 /// isAlias - Return true if there is any possibility that the two addresses
10925 /// overlap.
10926 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10927                           const Value *SrcValue1, int SrcValueOffset1,
10928                           unsigned SrcValueAlign1,
10929                           const MDNode *TBAAInfo1,
10930                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10931                           const Value *SrcValue2, int SrcValueOffset2,
10932                           unsigned SrcValueAlign2,
10933                           const MDNode *TBAAInfo2) const {
10934   // If they are the same then they must be aliases.
10935   if (Ptr1 == Ptr2) return true;
10936
10937   // If they are both volatile then they cannot be reordered.
10938   if (IsVolatile1 && IsVolatile2) return true;
10939
10940   // Gather base node and offset information.
10941   SDValue Base1, Base2;
10942   int64_t Offset1, Offset2;
10943   const GlobalValue *GV1, *GV2;
10944   const void *CV1, *CV2;
10945   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10946   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10947
10948   // If they have a same base address then check to see if they overlap.
10949   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10950     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10951
10952   // It is possible for different frame indices to alias each other, mostly
10953   // when tail call optimization reuses return address slots for arguments.
10954   // To catch this case, look up the actual index of frame indices to compute
10955   // the real alias relationship.
10956   if (isFrameIndex1 && isFrameIndex2) {
10957     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10958     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10959     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10960     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10961   }
10962
10963   // Otherwise, if we know what the bases are, and they aren't identical, then
10964   // we know they cannot alias.
10965   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10966     return false;
10967
10968   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10969   // compared to the size and offset of the access, we may be able to prove they
10970   // do not alias.  This check is conservative for now to catch cases created by
10971   // splitting vector types.
10972   if ((SrcValueAlign1 == SrcValueAlign2) &&
10973       (SrcValueOffset1 != SrcValueOffset2) &&
10974       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10975     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10976     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10977
10978     // There is no overlap between these relatively aligned accesses of similar
10979     // size, return no alias.
10980     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10981       return false;
10982   }
10983
10984   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10985     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10986   if (UseAA && SrcValue1 && SrcValue2) {
10987     // Use alias analysis information.
10988     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10989     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10990     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10991     AliasAnalysis::AliasResult AAResult =
10992       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10993                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10994     if (AAResult == AliasAnalysis::NoAlias)
10995       return false;
10996   }
10997
10998   // Otherwise we have to assume they alias.
10999   return true;
11000 }
11001
11002 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11003   SDValue Ptr0, Ptr1;
11004   int64_t Size0, Size1;
11005   bool IsVolatile0, IsVolatile1;
11006   const Value *SrcValue0, *SrcValue1;
11007   int SrcValueOffset0, SrcValueOffset1;
11008   unsigned SrcValueAlign0, SrcValueAlign1;
11009   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11010   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11011                 SrcValueAlign0, SrcTBAAInfo0);
11012   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11013                 SrcValueAlign1, SrcTBAAInfo1);
11014   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11015                  SrcValueAlign0, SrcTBAAInfo0,
11016                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11017                  SrcValueAlign1, SrcTBAAInfo1);
11018 }
11019
11020 /// FindAliasInfo - Extracts the relevant alias information from the memory
11021 /// node.  Returns true if the operand was a nonvolatile load.
11022 bool DAGCombiner::FindAliasInfo(SDNode *N,
11023                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11024                                 const Value *&SrcValue,
11025                                 int &SrcValueOffset,
11026                                 unsigned &SrcValueAlign,
11027                                 const MDNode *&TBAAInfo) const {
11028   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11029
11030   Ptr = LS->getBasePtr();
11031   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11032   IsVolatile = LS->isVolatile();
11033   SrcValue = LS->getSrcValue();
11034   SrcValueOffset = LS->getSrcValueOffset();
11035   SrcValueAlign = LS->getOriginalAlignment();
11036   TBAAInfo = LS->getTBAAInfo();
11037   return isa<LoadSDNode>(LS) && !IsVolatile;
11038 }
11039
11040 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11041 /// looking for aliasing nodes and adding them to the Aliases vector.
11042 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11043                                    SmallVectorImpl<SDValue> &Aliases) {
11044   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11045   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11046
11047   // Get alias information for node.
11048   SDValue Ptr;
11049   int64_t Size;
11050   bool IsVolatile;
11051   const Value *SrcValue;
11052   int SrcValueOffset;
11053   unsigned SrcValueAlign;
11054   const MDNode *SrcTBAAInfo;
11055   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11056                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11057
11058   // Starting off.
11059   Chains.push_back(OriginalChain);
11060   unsigned Depth = 0;
11061
11062   // Look at each chain and determine if it is an alias.  If so, add it to the
11063   // aliases list.  If not, then continue up the chain looking for the next
11064   // candidate.
11065   while (!Chains.empty()) {
11066     SDValue Chain = Chains.back();
11067     Chains.pop_back();
11068
11069     // For TokenFactor nodes, look at each operand and only continue up the
11070     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11071     // find more and revert to original chain since the xform is unlikely to be
11072     // profitable.
11073     //
11074     // FIXME: The depth check could be made to return the last non-aliasing
11075     // chain we found before we hit a tokenfactor rather than the original
11076     // chain.
11077     if (Depth > 6 || Aliases.size() == 2) {
11078       Aliases.clear();
11079       Aliases.push_back(OriginalChain);
11080       break;
11081     }
11082
11083     // Don't bother if we've been before.
11084     if (!Visited.insert(Chain.getNode()))
11085       continue;
11086
11087     switch (Chain.getOpcode()) {
11088     case ISD::EntryToken:
11089       // Entry token is ideal chain operand, but handled in FindBetterChain.
11090       break;
11091
11092     case ISD::LOAD:
11093     case ISD::STORE: {
11094       // Get alias information for Chain.
11095       SDValue OpPtr;
11096       int64_t OpSize;
11097       bool OpIsVolatile;
11098       const Value *OpSrcValue;
11099       int OpSrcValueOffset;
11100       unsigned OpSrcValueAlign;
11101       const MDNode *OpSrcTBAAInfo;
11102       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11103                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11104                                     OpSrcValueAlign,
11105                                     OpSrcTBAAInfo);
11106
11107       // If chain is alias then stop here.
11108       if (!(IsLoad && IsOpLoad) &&
11109           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11110                   SrcValueAlign, SrcTBAAInfo,
11111                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11112                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11113         Aliases.push_back(Chain);
11114       } else {
11115         // Look further up the chain.
11116         Chains.push_back(Chain.getOperand(0));
11117         ++Depth;
11118       }
11119       break;
11120     }
11121
11122     case ISD::TokenFactor:
11123       // We have to check each of the operands of the token factor for "small"
11124       // token factors, so we queue them up.  Adding the operands to the queue
11125       // (stack) in reverse order maintains the original order and increases the
11126       // likelihood that getNode will find a matching token factor (CSE.)
11127       if (Chain.getNumOperands() > 16) {
11128         Aliases.push_back(Chain);
11129         break;
11130       }
11131       for (unsigned n = Chain.getNumOperands(); n;)
11132         Chains.push_back(Chain.getOperand(--n));
11133       ++Depth;
11134       break;
11135
11136     default:
11137       // For all other instructions we will just have to take what we can get.
11138       Aliases.push_back(Chain);
11139       break;
11140     }
11141   }
11142 }
11143
11144 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11145 /// for a better chain (aliasing node.)
11146 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11147   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11148
11149   // Accumulate all the aliases to this node.
11150   GatherAllAliases(N, OldChain, Aliases);
11151
11152   // If no operands then chain to entry token.
11153   if (Aliases.size() == 0)
11154     return DAG.getEntryNode();
11155
11156   // If a single operand then chain to it.  We don't need to revisit it.
11157   if (Aliases.size() == 1)
11158     return Aliases[0];
11159
11160   // Construct a custom tailored token factor.
11161   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11162                      &Aliases[0], Aliases.size());
11163 }
11164
11165 // SelectionDAG::Combine - This is the entry point for the file.
11166 //
11167 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11168                            CodeGenOpt::Level OptLevel) {
11169   /// run - This is the main entry point to this class.
11170   ///
11171   DAGCombiner(*this, AA, OptLevel).Run(Level);
11172 }