Teach DAGCombine to fold fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2...
[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/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 STATISTIC(NodesCombined   , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
45
46 namespace {
47   static cl::opt<bool>
48     CombinerAA("combiner-alias-analysis", cl::Hidden,
49                cl::desc("Turn on alias analysis during testing"));
50
51   static cl::opt<bool>
52     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
53                cl::desc("Include global information in alias analysis"));
54
55 //------------------------------ DAGCombiner ---------------------------------//
56
57   class DAGCombiner {
58     SelectionDAG &DAG;
59     const TargetLowering &TLI;
60     CombineLevel Level;
61     CodeGenOpt::Level OptLevel;
62     bool LegalOperations;
63     bool LegalTypes;
64
65     // Worklist of all of the nodes that need to be simplified.
66     std::vector<SDNode*> WorkList;
67
68     // AA - Used for DAG load/store alias analysis.
69     AliasAnalysis &AA;
70
71     /// AddUsersToWorkList - When an instruction is simplified, add all users of
72     /// the instruction to the work lists because they might get more simplified
73     /// now.
74     ///
75     void AddUsersToWorkList(SDNode *N) {
76       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
77            UI != UE; ++UI)
78         AddToWorkList(*UI);
79     }
80
81     /// visit - call the node-specific routine that knows how to fold each
82     /// particular type of node.
83     SDValue visit(SDNode *N);
84
85   public:
86     /// AddToWorkList - Add to the work list making sure it's instance is at the
87     /// the back (next to be processed.)
88     void AddToWorkList(SDNode *N) {
89       removeFromWorkList(N);
90       WorkList.push_back(N);
91     }
92
93     /// removeFromWorkList - remove all instances of N from the worklist.
94     ///
95     void removeFromWorkList(SDNode *N) {
96       WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
97                      WorkList.end());
98     }
99
100     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
101                       bool AddTo = true);
102
103     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
104       return CombineTo(N, &Res, 1, AddTo);
105     }
106
107     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
108                       bool AddTo = true) {
109       SDValue To[] = { Res0, Res1 };
110       return CombineTo(N, To, 2, AddTo);
111     }
112
113     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
114
115   private:
116
117     /// SimplifyDemandedBits - Check the specified integer node value to see if
118     /// it can be simplified or if things it uses can be simplified by bit
119     /// propagation.  If so, return true.
120     bool SimplifyDemandedBits(SDValue Op) {
121       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
122       APInt Demanded = APInt::getAllOnesValue(BitWidth);
123       return SimplifyDemandedBits(Op, Demanded);
124     }
125
126     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
127
128     bool CombineToPreIndexedLoadStore(SDNode *N);
129     bool CombineToPostIndexedLoadStore(SDNode *N);
130
131     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
132     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
133     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
134     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
135     SDValue PromoteIntBinOp(SDValue Op);
136     SDValue PromoteIntShiftOp(SDValue Op);
137     SDValue PromoteExtend(SDValue Op);
138     bool PromoteLoad(SDValue Op);
139
140     /// combine - call the node-specific routine that knows how to fold each
141     /// particular type of node. If that doesn't do anything, try the
142     /// target-specific DAG combines.
143     SDValue combine(SDNode *N);
144
145     // Visitation implementation - Implement dag node combining for different
146     // node types.  The semantics are as follows:
147     // Return Value:
148     //   SDValue.getNode() == 0 - No change was made
149     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
150     //   otherwise              - N should be replaced by the returned Operand.
151     //
152     SDValue visitTokenFactor(SDNode *N);
153     SDValue visitMERGE_VALUES(SDNode *N);
154     SDValue visitADD(SDNode *N);
155     SDValue visitSUB(SDNode *N);
156     SDValue visitADDC(SDNode *N);
157     SDValue visitADDE(SDNode *N);
158     SDValue visitMUL(SDNode *N);
159     SDValue visitSDIV(SDNode *N);
160     SDValue visitUDIV(SDNode *N);
161     SDValue visitSREM(SDNode *N);
162     SDValue visitUREM(SDNode *N);
163     SDValue visitMULHU(SDNode *N);
164     SDValue visitMULHS(SDNode *N);
165     SDValue visitSMUL_LOHI(SDNode *N);
166     SDValue visitUMUL_LOHI(SDNode *N);
167     SDValue visitSDIVREM(SDNode *N);
168     SDValue visitUDIVREM(SDNode *N);
169     SDValue visitAND(SDNode *N);
170     SDValue visitOR(SDNode *N);
171     SDValue visitXOR(SDNode *N);
172     SDValue SimplifyVBinOp(SDNode *N);
173     SDValue visitSHL(SDNode *N);
174     SDValue visitSRA(SDNode *N);
175     SDValue visitSRL(SDNode *N);
176     SDValue visitCTLZ(SDNode *N);
177     SDValue visitCTTZ(SDNode *N);
178     SDValue visitCTPOP(SDNode *N);
179     SDValue visitSELECT(SDNode *N);
180     SDValue visitSELECT_CC(SDNode *N);
181     SDValue visitSETCC(SDNode *N);
182     SDValue visitSIGN_EXTEND(SDNode *N);
183     SDValue visitZERO_EXTEND(SDNode *N);
184     SDValue visitANY_EXTEND(SDNode *N);
185     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
186     SDValue visitTRUNCATE(SDNode *N);
187     SDValue visitBITCAST(SDNode *N);
188     SDValue visitBUILD_PAIR(SDNode *N);
189     SDValue visitFADD(SDNode *N);
190     SDValue visitFSUB(SDNode *N);
191     SDValue visitFMUL(SDNode *N);
192     SDValue visitFDIV(SDNode *N);
193     SDValue visitFREM(SDNode *N);
194     SDValue visitFCOPYSIGN(SDNode *N);
195     SDValue visitSINT_TO_FP(SDNode *N);
196     SDValue visitUINT_TO_FP(SDNode *N);
197     SDValue visitFP_TO_SINT(SDNode *N);
198     SDValue visitFP_TO_UINT(SDNode *N);
199     SDValue visitFP_ROUND(SDNode *N);
200     SDValue visitFP_ROUND_INREG(SDNode *N);
201     SDValue visitFP_EXTEND(SDNode *N);
202     SDValue visitFNEG(SDNode *N);
203     SDValue visitFABS(SDNode *N);
204     SDValue visitBRCOND(SDNode *N);
205     SDValue visitBR_CC(SDNode *N);
206     SDValue visitLOAD(SDNode *N);
207     SDValue visitSTORE(SDNode *N);
208     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
209     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
210     SDValue visitBUILD_VECTOR(SDNode *N);
211     SDValue visitCONCAT_VECTORS(SDNode *N);
212     SDValue visitVECTOR_SHUFFLE(SDNode *N);
213     SDValue visitMEMBARRIER(SDNode *N);
214
215     SDValue XformToShuffleWithZero(SDNode *N);
216     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
217
218     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
219
220     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
221     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
222     SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
223     SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
224                              SDValue N3, ISD::CondCode CC,
225                              bool NotExtCompare = false);
226     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
227                           DebugLoc DL, bool foldBooleans = true);
228     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
229                                          unsigned HiOp);
230     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
231     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
232     SDValue BuildSDIV(SDNode *N);
233     SDValue BuildUDIV(SDNode *N);
234     SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
235     SDValue ReduceLoadWidth(SDNode *N);
236     SDValue ReduceLoadOpStoreWidth(SDNode *N);
237
238     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
239
240     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
241     /// looking for aliasing nodes and adding them to the Aliases vector.
242     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
243                           SmallVector<SDValue, 8> &Aliases);
244
245     /// isAlias - Return true if there is any possibility that the two addresses
246     /// overlap.
247     bool isAlias(SDValue Ptr1, int64_t Size1,
248                  const Value *SrcValue1, int SrcValueOffset1,
249                  unsigned SrcValueAlign1,
250                  const MDNode *TBAAInfo1,
251                  SDValue Ptr2, int64_t Size2,
252                  const Value *SrcValue2, int SrcValueOffset2,
253                  unsigned SrcValueAlign2,
254                  const MDNode *TBAAInfo2) const;
255
256     /// FindAliasInfo - Extracts the relevant alias information from the memory
257     /// node.  Returns true if the operand was a load.
258     bool FindAliasInfo(SDNode *N,
259                        SDValue &Ptr, int64_t &Size,
260                        const Value *&SrcValue, int &SrcValueOffset,
261                        unsigned &SrcValueAlignment,
262                        const MDNode *&TBAAInfo) const;
263
264     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
265     /// looking for a better chain (aliasing node.)
266     SDValue FindBetterChain(SDNode *N, SDValue Chain);
267
268   public:
269     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
270       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
271         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
272
273     /// Run - runs the dag combiner on all nodes in the work list
274     void Run(CombineLevel AtLevel);
275
276     SelectionDAG &getDAG() const { return DAG; }
277
278     /// getShiftAmountTy - Returns a type large enough to hold any valid
279     /// shift amount - before type legalization these can be huge.
280     EVT getShiftAmountTy() {
281       return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
282     }
283
284     /// isTypeLegal - This method returns true if we are running before type
285     /// legalization or if the specified VT is legal.
286     bool isTypeLegal(const EVT &VT) {
287       if (!LegalTypes) return true;
288       return TLI.isTypeLegal(VT);
289     }
290   };
291 }
292
293
294 namespace {
295 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
296 /// nodes from the worklist.
297 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
298   DAGCombiner &DC;
299 public:
300   explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
301
302   virtual void NodeDeleted(SDNode *N, SDNode *E) {
303     DC.removeFromWorkList(N);
304   }
305
306   virtual void NodeUpdated(SDNode *N) {
307     // Ignore updates.
308   }
309 };
310 }
311
312 //===----------------------------------------------------------------------===//
313 //  TargetLowering::DAGCombinerInfo implementation
314 //===----------------------------------------------------------------------===//
315
316 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
317   ((DAGCombiner*)DC)->AddToWorkList(N);
318 }
319
320 SDValue TargetLowering::DAGCombinerInfo::
321 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
322   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
323 }
324
325 SDValue TargetLowering::DAGCombinerInfo::
326 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
327   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
328 }
329
330
331 SDValue TargetLowering::DAGCombinerInfo::
332 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
333   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
334 }
335
336 void TargetLowering::DAGCombinerInfo::
337 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
338   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
339 }
340
341 //===----------------------------------------------------------------------===//
342 // Helper Functions
343 //===----------------------------------------------------------------------===//
344
345 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
346 /// specified expression for the same cost as the expression itself, or 2 if we
347 /// can compute the negated form more cheaply than the expression itself.
348 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
349                                unsigned Depth = 0) {
350   // No compile time optimizations on this type.
351   if (Op.getValueType() == MVT::ppcf128)
352     return 0;
353
354   // fneg is removable even if it has multiple uses.
355   if (Op.getOpcode() == ISD::FNEG) return 2;
356
357   // Don't allow anything with multiple uses.
358   if (!Op.hasOneUse()) return 0;
359
360   // Don't recurse exponentially.
361   if (Depth > 6) return 0;
362
363   switch (Op.getOpcode()) {
364   default: return false;
365   case ISD::ConstantFP:
366     // Don't invert constant FP values after legalize.  The negated constant
367     // isn't necessarily legal.
368     return LegalOperations ? 0 : 1;
369   case ISD::FADD:
370     // FIXME: determine better conditions for this xform.
371     if (!UnsafeFPMath) return 0;
372
373     // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
374     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
375       return V;
376     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
377     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
378   case ISD::FSUB:
379     // We can't turn -(A-B) into B-A when we honor signed zeros.
380     if (!UnsafeFPMath) return 0;
381
382     // fold (fneg (fsub A, B)) -> (fsub B, A)
383     return 1;
384
385   case ISD::FMUL:
386   case ISD::FDIV:
387     if (HonorSignDependentRoundingFPMath()) return 0;
388
389     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
390     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
391       return V;
392
393     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
394
395   case ISD::FP_EXTEND:
396   case ISD::FP_ROUND:
397   case ISD::FSIN:
398     return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
399   }
400 }
401
402 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
403 /// returns the newly negated expression.
404 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
405                                     bool LegalOperations, unsigned Depth = 0) {
406   // fneg is removable even if it has multiple uses.
407   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
408
409   // Don't allow anything with multiple uses.
410   assert(Op.hasOneUse() && "Unknown reuse!");
411
412   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
413   switch (Op.getOpcode()) {
414   default: llvm_unreachable("Unknown code");
415   case ISD::ConstantFP: {
416     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
417     V.changeSign();
418     return DAG.getConstantFP(V, Op.getValueType());
419   }
420   case ISD::FADD:
421     // FIXME: determine better conditions for this xform.
422     assert(UnsafeFPMath);
423
424     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
425     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
426       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
427                          GetNegatedExpression(Op.getOperand(0), DAG,
428                                               LegalOperations, Depth+1),
429                          Op.getOperand(1));
430     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
431     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
432                        GetNegatedExpression(Op.getOperand(1), DAG,
433                                             LegalOperations, Depth+1),
434                        Op.getOperand(0));
435   case ISD::FSUB:
436     // We can't turn -(A-B) into B-A when we honor signed zeros.
437     assert(UnsafeFPMath);
438
439     // fold (fneg (fsub 0, B)) -> B
440     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
441       if (N0CFP->getValueAPF().isZero())
442         return Op.getOperand(1);
443
444     // fold (fneg (fsub A, B)) -> (fsub B, A)
445     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
446                        Op.getOperand(1), Op.getOperand(0));
447
448   case ISD::FMUL:
449   case ISD::FDIV:
450     assert(!HonorSignDependentRoundingFPMath());
451
452     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
453     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
454       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
455                          GetNegatedExpression(Op.getOperand(0), DAG,
456                                               LegalOperations, Depth+1),
457                          Op.getOperand(1));
458
459     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
460     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
461                        Op.getOperand(0),
462                        GetNegatedExpression(Op.getOperand(1), DAG,
463                                             LegalOperations, Depth+1));
464
465   case ISD::FP_EXTEND:
466   case ISD::FSIN:
467     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
468                        GetNegatedExpression(Op.getOperand(0), DAG,
469                                             LegalOperations, Depth+1));
470   case ISD::FP_ROUND:
471       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
472                          GetNegatedExpression(Op.getOperand(0), DAG,
473                                               LegalOperations, Depth+1),
474                          Op.getOperand(1));
475   }
476 }
477
478
479 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
480 // that selects between the values 1 and 0, making it equivalent to a setcc.
481 // Also, set the incoming LHS, RHS, and CC references to the appropriate
482 // nodes based on the type of node we are checking.  This simplifies life a
483 // bit for the callers.
484 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
485                               SDValue &CC) {
486   if (N.getOpcode() == ISD::SETCC) {
487     LHS = N.getOperand(0);
488     RHS = N.getOperand(1);
489     CC  = N.getOperand(2);
490     return true;
491   }
492   if (N.getOpcode() == ISD::SELECT_CC &&
493       N.getOperand(2).getOpcode() == ISD::Constant &&
494       N.getOperand(3).getOpcode() == ISD::Constant &&
495       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
496       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
497     LHS = N.getOperand(0);
498     RHS = N.getOperand(1);
499     CC  = N.getOperand(4);
500     return true;
501   }
502   return false;
503 }
504
505 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
506 // one use.  If this is true, it allows the users to invert the operation for
507 // free when it is profitable to do so.
508 static bool isOneUseSetCC(SDValue N) {
509   SDValue N0, N1, N2;
510   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
511     return true;
512   return false;
513 }
514
515 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
516                                     SDValue N0, SDValue N1) {
517   EVT VT = N0.getValueType();
518   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
519     if (isa<ConstantSDNode>(N1)) {
520       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
521       SDValue OpNode =
522         DAG.FoldConstantArithmetic(Opc, VT,
523                                    cast<ConstantSDNode>(N0.getOperand(1)),
524                                    cast<ConstantSDNode>(N1));
525       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
526     } else if (N0.hasOneUse()) {
527       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
528       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
529                                    N0.getOperand(0), N1);
530       AddToWorkList(OpNode.getNode());
531       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
532     }
533   }
534
535   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
536     if (isa<ConstantSDNode>(N0)) {
537       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
538       SDValue OpNode =
539         DAG.FoldConstantArithmetic(Opc, VT,
540                                    cast<ConstantSDNode>(N1.getOperand(1)),
541                                    cast<ConstantSDNode>(N0));
542       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
543     } else if (N1.hasOneUse()) {
544       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
545       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
546                                    N1.getOperand(0), N0);
547       AddToWorkList(OpNode.getNode());
548       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
549     }
550   }
551
552   return SDValue();
553 }
554
555 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
556                                bool AddTo) {
557   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
558   ++NodesCombined;
559   DEBUG(dbgs() << "\nReplacing.1 ";
560         N->dump(&DAG);
561         dbgs() << "\nWith: ";
562         To[0].getNode()->dump(&DAG);
563         dbgs() << " and " << NumTo-1 << " other values\n";
564         for (unsigned i = 0, e = NumTo; i != e; ++i)
565           assert((!To[i].getNode() ||
566                   N->getValueType(i) == To[i].getValueType()) &&
567                  "Cannot combine value to value of different type!"));
568   WorkListRemover DeadNodes(*this);
569   DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
570
571   if (AddTo) {
572     // Push the new nodes and any users onto the worklist
573     for (unsigned i = 0, e = NumTo; i != e; ++i) {
574       if (To[i].getNode()) {
575         AddToWorkList(To[i].getNode());
576         AddUsersToWorkList(To[i].getNode());
577       }
578     }
579   }
580
581   // Finally, if the node is now dead, remove it from the graph.  The node
582   // may not be dead if the replacement process recursively simplified to
583   // something else needing this node.
584   if (N->use_empty()) {
585     // Nodes can be reintroduced into the worklist.  Make sure we do not
586     // process a node that has been replaced.
587     removeFromWorkList(N);
588
589     // Finally, since the node is now dead, remove it from the graph.
590     DAG.DeleteNode(N);
591   }
592   return SDValue(N, 0);
593 }
594
595 void DAGCombiner::
596 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
597   // Replace all uses.  If any nodes become isomorphic to other nodes and
598   // are deleted, make sure to remove them from our worklist.
599   WorkListRemover DeadNodes(*this);
600   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
601
602   // Push the new node and any (possibly new) users onto the worklist.
603   AddToWorkList(TLO.New.getNode());
604   AddUsersToWorkList(TLO.New.getNode());
605
606   // Finally, if the node is now dead, remove it from the graph.  The node
607   // may not be dead if the replacement process recursively simplified to
608   // something else needing this node.
609   if (TLO.Old.getNode()->use_empty()) {
610     removeFromWorkList(TLO.Old.getNode());
611
612     // If the operands of this node are only used by the node, they will now
613     // be dead.  Make sure to visit them first to delete dead nodes early.
614     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
615       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
616         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
617
618     DAG.DeleteNode(TLO.Old.getNode());
619   }
620 }
621
622 /// SimplifyDemandedBits - Check the specified integer node value to see if
623 /// it can be simplified or if things it uses can be simplified by bit
624 /// propagation.  If so, return true.
625 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
626   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
627   APInt KnownZero, KnownOne;
628   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
629     return false;
630
631   // Revisit the node.
632   AddToWorkList(Op.getNode());
633
634   // Replace the old value with the new one.
635   ++NodesCombined;
636   DEBUG(dbgs() << "\nReplacing.2 ";
637         TLO.Old.getNode()->dump(&DAG);
638         dbgs() << "\nWith: ";
639         TLO.New.getNode()->dump(&DAG);
640         dbgs() << '\n');
641
642   CommitTargetLoweringOpt(TLO);
643   return true;
644 }
645
646 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
647   DebugLoc dl = Load->getDebugLoc();
648   EVT VT = Load->getValueType(0);
649   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
650
651   DEBUG(dbgs() << "\nReplacing.9 ";
652         Load->dump(&DAG);
653         dbgs() << "\nWith: ";
654         Trunc.getNode()->dump(&DAG);
655         dbgs() << '\n');
656   WorkListRemover DeadNodes(*this);
657   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
658   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
659                                 &DeadNodes);
660   removeFromWorkList(Load);
661   DAG.DeleteNode(Load);
662   AddToWorkList(Trunc.getNode());
663 }
664
665 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
666   Replace = false;
667   DebugLoc dl = Op.getDebugLoc();
668   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
669     EVT MemVT = LD->getMemoryVT();
670     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
671       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 
672                                                   : ISD::EXTLOAD)
673       : LD->getExtensionType();
674     Replace = true;
675     return DAG.getExtLoad(ExtType, PVT, dl,
676                           LD->getChain(), LD->getBasePtr(),
677                           LD->getPointerInfo(),
678                           MemVT, LD->isVolatile(),
679                           LD->isNonTemporal(), LD->getAlignment());
680   }
681
682   unsigned Opc = Op.getOpcode();
683   switch (Opc) {
684   default: break;
685   case ISD::AssertSext:
686     return DAG.getNode(ISD::AssertSext, dl, PVT,
687                        SExtPromoteOperand(Op.getOperand(0), PVT),
688                        Op.getOperand(1));
689   case ISD::AssertZext:
690     return DAG.getNode(ISD::AssertZext, dl, PVT,
691                        ZExtPromoteOperand(Op.getOperand(0), PVT),
692                        Op.getOperand(1));
693   case ISD::Constant: {
694     unsigned ExtOpc =
695       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
696     return DAG.getNode(ExtOpc, dl, PVT, Op);
697   }
698   }
699
700   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
701     return SDValue();
702   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
703 }
704
705 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
706   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
707     return SDValue();
708   EVT OldVT = Op.getValueType();
709   DebugLoc dl = Op.getDebugLoc();
710   bool Replace = false;
711   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
712   if (NewOp.getNode() == 0)
713     return SDValue();
714   AddToWorkList(NewOp.getNode());
715
716   if (Replace)
717     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
718   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
719                      DAG.getValueType(OldVT));
720 }
721
722 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
723   EVT OldVT = Op.getValueType();
724   DebugLoc dl = Op.getDebugLoc();
725   bool Replace = false;
726   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
727   if (NewOp.getNode() == 0)
728     return SDValue();
729   AddToWorkList(NewOp.getNode());
730
731   if (Replace)
732     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
733   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
734 }
735
736 /// PromoteIntBinOp - Promote the specified integer binary operation if the
737 /// target indicates it is beneficial. e.g. On x86, it's usually better to
738 /// promote i16 operations to i32 since i16 instructions are longer.
739 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
740   if (!LegalOperations)
741     return SDValue();
742
743   EVT VT = Op.getValueType();
744   if (VT.isVector() || !VT.isInteger())
745     return SDValue();
746
747   // If operation type is 'undesirable', e.g. i16 on x86, consider
748   // promoting it.
749   unsigned Opc = Op.getOpcode();
750   if (TLI.isTypeDesirableForOp(Opc, VT))
751     return SDValue();
752
753   EVT PVT = VT;
754   // Consult target whether it is a good idea to promote this operation and
755   // what's the right type to promote it to.
756   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
757     assert(PVT != VT && "Don't know what type to promote to!");
758
759     bool Replace0 = false;
760     SDValue N0 = Op.getOperand(0);
761     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
762     if (NN0.getNode() == 0)
763       return SDValue();
764
765     bool Replace1 = false;
766     SDValue N1 = Op.getOperand(1);
767     SDValue NN1;
768     if (N0 == N1)
769       NN1 = NN0;
770     else {
771       NN1 = PromoteOperand(N1, PVT, Replace1);
772       if (NN1.getNode() == 0)
773         return SDValue();
774     }
775
776     AddToWorkList(NN0.getNode());
777     if (NN1.getNode())
778       AddToWorkList(NN1.getNode());
779
780     if (Replace0)
781       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
782     if (Replace1)
783       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
784
785     DEBUG(dbgs() << "\nPromoting ";
786           Op.getNode()->dump(&DAG));
787     DebugLoc dl = Op.getDebugLoc();
788     return DAG.getNode(ISD::TRUNCATE, dl, VT,
789                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
790   }
791   return SDValue();
792 }
793
794 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
795 /// target indicates it is beneficial. e.g. On x86, it's usually better to
796 /// promote i16 operations to i32 since i16 instructions are longer.
797 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
798   if (!LegalOperations)
799     return SDValue();
800
801   EVT VT = Op.getValueType();
802   if (VT.isVector() || !VT.isInteger())
803     return SDValue();
804
805   // If operation type is 'undesirable', e.g. i16 on x86, consider
806   // promoting it.
807   unsigned Opc = Op.getOpcode();
808   if (TLI.isTypeDesirableForOp(Opc, VT))
809     return SDValue();
810
811   EVT PVT = VT;
812   // Consult target whether it is a good idea to promote this operation and
813   // what's the right type to promote it to.
814   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
815     assert(PVT != VT && "Don't know what type to promote to!");
816
817     bool Replace = false;
818     SDValue N0 = Op.getOperand(0);
819     if (Opc == ISD::SRA)
820       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
821     else if (Opc == ISD::SRL)
822       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
823     else
824       N0 = PromoteOperand(N0, PVT, Replace);
825     if (N0.getNode() == 0)
826       return SDValue();
827
828     AddToWorkList(N0.getNode());
829     if (Replace)
830       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
831
832     DEBUG(dbgs() << "\nPromoting ";
833           Op.getNode()->dump(&DAG));
834     DebugLoc dl = Op.getDebugLoc();
835     return DAG.getNode(ISD::TRUNCATE, dl, VT,
836                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
837   }
838   return SDValue();
839 }
840
841 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
842   if (!LegalOperations)
843     return SDValue();
844
845   EVT VT = Op.getValueType();
846   if (VT.isVector() || !VT.isInteger())
847     return SDValue();
848
849   // If operation type is 'undesirable', e.g. i16 on x86, consider
850   // promoting it.
851   unsigned Opc = Op.getOpcode();
852   if (TLI.isTypeDesirableForOp(Opc, VT))
853     return SDValue();
854
855   EVT PVT = VT;
856   // Consult target whether it is a good idea to promote this operation and
857   // what's the right type to promote it to.
858   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
859     assert(PVT != VT && "Don't know what type to promote to!");
860     // fold (aext (aext x)) -> (aext x)
861     // fold (aext (zext x)) -> (zext x)
862     // fold (aext (sext x)) -> (sext x)
863     DEBUG(dbgs() << "\nPromoting ";
864           Op.getNode()->dump(&DAG));
865     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
866   }
867   return SDValue();
868 }
869
870 bool DAGCombiner::PromoteLoad(SDValue Op) {
871   if (!LegalOperations)
872     return false;
873
874   EVT VT = Op.getValueType();
875   if (VT.isVector() || !VT.isInteger())
876     return false;
877
878   // If operation type is 'undesirable', e.g. i16 on x86, consider
879   // promoting it.
880   unsigned Opc = Op.getOpcode();
881   if (TLI.isTypeDesirableForOp(Opc, VT))
882     return false;
883
884   EVT PVT = VT;
885   // Consult target whether it is a good idea to promote this operation and
886   // what's the right type to promote it to.
887   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
888     assert(PVT != VT && "Don't know what type to promote to!");
889
890     DebugLoc dl = Op.getDebugLoc();
891     SDNode *N = Op.getNode();
892     LoadSDNode *LD = cast<LoadSDNode>(N);
893     EVT MemVT = LD->getMemoryVT();
894     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
895       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 
896                                                   : ISD::EXTLOAD)
897       : LD->getExtensionType();
898     SDValue NewLD = DAG.getExtLoad(ExtType, PVT, dl,
899                                    LD->getChain(), LD->getBasePtr(),
900                                    LD->getPointerInfo(),
901                                    MemVT, LD->isVolatile(),
902                                    LD->isNonTemporal(), LD->getAlignment());
903     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
904
905     DEBUG(dbgs() << "\nPromoting ";
906           N->dump(&DAG);
907           dbgs() << "\nTo: ";
908           Result.getNode()->dump(&DAG);
909           dbgs() << '\n');
910     WorkListRemover DeadNodes(*this);
911     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
912     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
913     removeFromWorkList(N);
914     DAG.DeleteNode(N);
915     AddToWorkList(Result.getNode());
916     return true;
917   }
918   return false;
919 }
920
921
922 //===----------------------------------------------------------------------===//
923 //  Main DAG Combiner implementation
924 //===----------------------------------------------------------------------===//
925
926 void DAGCombiner::Run(CombineLevel AtLevel) {
927   // set the instance variables, so that the various visit routines may use it.
928   Level = AtLevel;
929   LegalOperations = Level >= NoIllegalOperations;
930   LegalTypes = Level >= NoIllegalTypes;
931
932   // Add all the dag nodes to the worklist.
933   WorkList.reserve(DAG.allnodes_size());
934   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
935        E = DAG.allnodes_end(); I != E; ++I)
936     WorkList.push_back(I);
937
938   // Create a dummy node (which is not added to allnodes), that adds a reference
939   // to the root node, preventing it from being deleted, and tracking any
940   // changes of the root.
941   HandleSDNode Dummy(DAG.getRoot());
942
943   // The root of the dag may dangle to deleted nodes until the dag combiner is
944   // done.  Set it to null to avoid confusion.
945   DAG.setRoot(SDValue());
946
947   // while the worklist isn't empty, inspect the node on the end of it and
948   // try and combine it.
949   while (!WorkList.empty()) {
950     SDNode *N = WorkList.back();
951     WorkList.pop_back();
952
953     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
954     // N is deleted from the DAG, since they too may now be dead or may have a
955     // reduced number of uses, allowing other xforms.
956     if (N->use_empty() && N != &Dummy) {
957       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
958         AddToWorkList(N->getOperand(i).getNode());
959
960       DAG.DeleteNode(N);
961       continue;
962     }
963
964     SDValue RV = combine(N);
965
966     if (RV.getNode() == 0)
967       continue;
968
969     ++NodesCombined;
970
971     // If we get back the same node we passed in, rather than a new node or
972     // zero, we know that the node must have defined multiple values and
973     // CombineTo was used.  Since CombineTo takes care of the worklist
974     // mechanics for us, we have no work to do in this case.
975     if (RV.getNode() == N)
976       continue;
977
978     assert(N->getOpcode() != ISD::DELETED_NODE &&
979            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
980            "Node was deleted but visit returned new node!");
981
982     DEBUG(dbgs() << "\nReplacing.3 ";
983           N->dump(&DAG);
984           dbgs() << "\nWith: ";
985           RV.getNode()->dump(&DAG);
986           dbgs() << '\n');
987     WorkListRemover DeadNodes(*this);
988     if (N->getNumValues() == RV.getNode()->getNumValues())
989       DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
990     else {
991       assert(N->getValueType(0) == RV.getValueType() &&
992              N->getNumValues() == 1 && "Type mismatch");
993       SDValue OpV = RV;
994       DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
995     }
996
997     // Push the new node and any users onto the worklist
998     AddToWorkList(RV.getNode());
999     AddUsersToWorkList(RV.getNode());
1000
1001     // Add any uses of the old node to the worklist in case this node is the
1002     // last one that uses them.  They may become dead after this node is
1003     // deleted.
1004     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1005       AddToWorkList(N->getOperand(i).getNode());
1006
1007     // Finally, if the node is now dead, remove it from the graph.  The node
1008     // may not be dead if the replacement process recursively simplified to
1009     // something else needing this node.
1010     if (N->use_empty()) {
1011       // Nodes can be reintroduced into the worklist.  Make sure we do not
1012       // process a node that has been replaced.
1013       removeFromWorkList(N);
1014
1015       // Finally, since the node is now dead, remove it from the graph.
1016       DAG.DeleteNode(N);
1017     }
1018   }
1019
1020   // If the root changed (e.g. it was a dead load, update the root).
1021   DAG.setRoot(Dummy.getValue());
1022 }
1023
1024 SDValue DAGCombiner::visit(SDNode *N) {
1025   switch (N->getOpcode()) {
1026   default: break;
1027   case ISD::TokenFactor:        return visitTokenFactor(N);
1028   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1029   case ISD::ADD:                return visitADD(N);
1030   case ISD::SUB:                return visitSUB(N);
1031   case ISD::ADDC:               return visitADDC(N);
1032   case ISD::ADDE:               return visitADDE(N);
1033   case ISD::MUL:                return visitMUL(N);
1034   case ISD::SDIV:               return visitSDIV(N);
1035   case ISD::UDIV:               return visitUDIV(N);
1036   case ISD::SREM:               return visitSREM(N);
1037   case ISD::UREM:               return visitUREM(N);
1038   case ISD::MULHU:              return visitMULHU(N);
1039   case ISD::MULHS:              return visitMULHS(N);
1040   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1041   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1042   case ISD::SDIVREM:            return visitSDIVREM(N);
1043   case ISD::UDIVREM:            return visitUDIVREM(N);
1044   case ISD::AND:                return visitAND(N);
1045   case ISD::OR:                 return visitOR(N);
1046   case ISD::XOR:                return visitXOR(N);
1047   case ISD::SHL:                return visitSHL(N);
1048   case ISD::SRA:                return visitSRA(N);
1049   case ISD::SRL:                return visitSRL(N);
1050   case ISD::CTLZ:               return visitCTLZ(N);
1051   case ISD::CTTZ:               return visitCTTZ(N);
1052   case ISD::CTPOP:              return visitCTPOP(N);
1053   case ISD::SELECT:             return visitSELECT(N);
1054   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1055   case ISD::SETCC:              return visitSETCC(N);
1056   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1057   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1058   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1059   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1060   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1061   case ISD::BITCAST:            return visitBITCAST(N);
1062   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1063   case ISD::FADD:               return visitFADD(N);
1064   case ISD::FSUB:               return visitFSUB(N);
1065   case ISD::FMUL:               return visitFMUL(N);
1066   case ISD::FDIV:               return visitFDIV(N);
1067   case ISD::FREM:               return visitFREM(N);
1068   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1069   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1070   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1071   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1072   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1073   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1074   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1075   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1076   case ISD::FNEG:               return visitFNEG(N);
1077   case ISD::FABS:               return visitFABS(N);
1078   case ISD::BRCOND:             return visitBRCOND(N);
1079   case ISD::BR_CC:              return visitBR_CC(N);
1080   case ISD::LOAD:               return visitLOAD(N);
1081   case ISD::STORE:              return visitSTORE(N);
1082   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1083   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1084   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1085   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1086   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1087   case ISD::MEMBARRIER:         return visitMEMBARRIER(N);
1088   }
1089   return SDValue();
1090 }
1091
1092 SDValue DAGCombiner::combine(SDNode *N) {
1093   SDValue RV = visit(N);
1094
1095   // If nothing happened, try a target-specific DAG combine.
1096   if (RV.getNode() == 0) {
1097     assert(N->getOpcode() != ISD::DELETED_NODE &&
1098            "Node was deleted but visit returned NULL!");
1099
1100     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1101         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1102
1103       // Expose the DAG combiner to the target combiner impls.
1104       TargetLowering::DAGCombinerInfo
1105         DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1106
1107       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1108     }
1109   }
1110
1111   // If nothing happened still, try promoting the operation.
1112   if (RV.getNode() == 0) {
1113     switch (N->getOpcode()) {
1114     default: break;
1115     case ISD::ADD:
1116     case ISD::SUB:
1117     case ISD::MUL:
1118     case ISD::AND:
1119     case ISD::OR:
1120     case ISD::XOR:
1121       RV = PromoteIntBinOp(SDValue(N, 0));
1122       break;
1123     case ISD::SHL:
1124     case ISD::SRA:
1125     case ISD::SRL:
1126       RV = PromoteIntShiftOp(SDValue(N, 0));
1127       break;
1128     case ISD::SIGN_EXTEND:
1129     case ISD::ZERO_EXTEND:
1130     case ISD::ANY_EXTEND:
1131       RV = PromoteExtend(SDValue(N, 0));
1132       break;
1133     case ISD::LOAD:
1134       if (PromoteLoad(SDValue(N, 0)))
1135         RV = SDValue(N, 0);
1136       break;
1137     }
1138   }
1139
1140   // If N is a commutative binary node, try commuting it to enable more
1141   // sdisel CSE.
1142   if (RV.getNode() == 0 &&
1143       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1144       N->getNumValues() == 1) {
1145     SDValue N0 = N->getOperand(0);
1146     SDValue N1 = N->getOperand(1);
1147
1148     // Constant operands are canonicalized to RHS.
1149     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1150       SDValue Ops[] = { N1, N0 };
1151       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1152                                             Ops, 2);
1153       if (CSENode)
1154         return SDValue(CSENode, 0);
1155     }
1156   }
1157
1158   return RV;
1159 }
1160
1161 /// getInputChainForNode - Given a node, return its input chain if it has one,
1162 /// otherwise return a null sd operand.
1163 static SDValue getInputChainForNode(SDNode *N) {
1164   if (unsigned NumOps = N->getNumOperands()) {
1165     if (N->getOperand(0).getValueType() == MVT::Other)
1166       return N->getOperand(0);
1167     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1168       return N->getOperand(NumOps-1);
1169     for (unsigned i = 1; i < NumOps-1; ++i)
1170       if (N->getOperand(i).getValueType() == MVT::Other)
1171         return N->getOperand(i);
1172   }
1173   return SDValue();
1174 }
1175
1176 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1177   // If N has two operands, where one has an input chain equal to the other,
1178   // the 'other' chain is redundant.
1179   if (N->getNumOperands() == 2) {
1180     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1181       return N->getOperand(0);
1182     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1183       return N->getOperand(1);
1184   }
1185
1186   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1187   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1188   SmallPtrSet<SDNode*, 16> SeenOps;
1189   bool Changed = false;             // If we should replace this token factor.
1190
1191   // Start out with this token factor.
1192   TFs.push_back(N);
1193
1194   // Iterate through token factors.  The TFs grows when new token factors are
1195   // encountered.
1196   for (unsigned i = 0; i < TFs.size(); ++i) {
1197     SDNode *TF = TFs[i];
1198
1199     // Check each of the operands.
1200     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1201       SDValue Op = TF->getOperand(i);
1202
1203       switch (Op.getOpcode()) {
1204       case ISD::EntryToken:
1205         // Entry tokens don't need to be added to the list. They are
1206         // rededundant.
1207         Changed = true;
1208         break;
1209
1210       case ISD::TokenFactor:
1211         if (Op.hasOneUse() &&
1212             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1213           // Queue up for processing.
1214           TFs.push_back(Op.getNode());
1215           // Clean up in case the token factor is removed.
1216           AddToWorkList(Op.getNode());
1217           Changed = true;
1218           break;
1219         }
1220         // Fall thru
1221
1222       default:
1223         // Only add if it isn't already in the list.
1224         if (SeenOps.insert(Op.getNode()))
1225           Ops.push_back(Op);
1226         else
1227           Changed = true;
1228         break;
1229       }
1230     }
1231   }
1232
1233   SDValue Result;
1234
1235   // If we've change things around then replace token factor.
1236   if (Changed) {
1237     if (Ops.empty()) {
1238       // The entry token is the only possible outcome.
1239       Result = DAG.getEntryNode();
1240     } else {
1241       // New and improved token factor.
1242       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1243                            MVT::Other, &Ops[0], Ops.size());
1244     }
1245
1246     // Don't add users to work list.
1247     return CombineTo(N, Result, false);
1248   }
1249
1250   return Result;
1251 }
1252
1253 /// MERGE_VALUES can always be eliminated.
1254 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1255   WorkListRemover DeadNodes(*this);
1256   // Replacing results may cause a different MERGE_VALUES to suddenly
1257   // be CSE'd with N, and carry its uses with it. Iterate until no
1258   // uses remain, to ensure that the node can be safely deleted.
1259   do {
1260     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1261       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1262                                     &DeadNodes);
1263   } while (!N->use_empty());
1264   removeFromWorkList(N);
1265   DAG.DeleteNode(N);
1266   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1267 }
1268
1269 static
1270 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1271                               SelectionDAG &DAG) {
1272   EVT VT = N0.getValueType();
1273   SDValue N00 = N0.getOperand(0);
1274   SDValue N01 = N0.getOperand(1);
1275   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1276
1277   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1278       isa<ConstantSDNode>(N00.getOperand(1))) {
1279     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1280     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1281                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1282                                  N00.getOperand(0), N01),
1283                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1284                                  N00.getOperand(1), N01));
1285     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1286   }
1287
1288   return SDValue();
1289 }
1290
1291 SDValue DAGCombiner::visitADD(SDNode *N) {
1292   SDValue N0 = N->getOperand(0);
1293   SDValue N1 = N->getOperand(1);
1294   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1295   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1296   EVT VT = N0.getValueType();
1297
1298   // fold vector ops
1299   if (VT.isVector()) {
1300     SDValue FoldedVOp = SimplifyVBinOp(N);
1301     if (FoldedVOp.getNode()) return FoldedVOp;
1302   }
1303
1304   // fold (add x, undef) -> undef
1305   if (N0.getOpcode() == ISD::UNDEF)
1306     return N0;
1307   if (N1.getOpcode() == ISD::UNDEF)
1308     return N1;
1309   // fold (add c1, c2) -> c1+c2
1310   if (N0C && N1C)
1311     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1312   // canonicalize constant to RHS
1313   if (N0C && !N1C)
1314     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1315   // fold (add x, 0) -> x
1316   if (N1C && N1C->isNullValue())
1317     return N0;
1318   // fold (add Sym, c) -> Sym+c
1319   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1320     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1321         GA->getOpcode() == ISD::GlobalAddress)
1322       return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1323                                   GA->getOffset() +
1324                                     (uint64_t)N1C->getSExtValue());
1325   // fold ((c1-A)+c2) -> (c1+c2)-A
1326   if (N1C && N0.getOpcode() == ISD::SUB)
1327     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1328       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1329                          DAG.getConstant(N1C->getAPIntValue()+
1330                                          N0C->getAPIntValue(), VT),
1331                          N0.getOperand(1));
1332   // reassociate add
1333   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1334   if (RADD.getNode() != 0)
1335     return RADD;
1336   // fold ((0-A) + B) -> B-A
1337   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1338       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1339     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1340   // fold (A + (0-B)) -> A-B
1341   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1342       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1343     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1344   // fold (A+(B-A)) -> B
1345   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1346     return N1.getOperand(0);
1347   // fold ((B-A)+A) -> B
1348   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1349     return N0.getOperand(0);
1350   // fold (A+(B-(A+C))) to (B-C)
1351   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1352       N0 == N1.getOperand(1).getOperand(0))
1353     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1354                        N1.getOperand(1).getOperand(1));
1355   // fold (A+(B-(C+A))) to (B-C)
1356   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1357       N0 == N1.getOperand(1).getOperand(1))
1358     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1359                        N1.getOperand(1).getOperand(0));
1360   // fold (A+((B-A)+or-C)) to (B+or-C)
1361   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1362       N1.getOperand(0).getOpcode() == ISD::SUB &&
1363       N0 == N1.getOperand(0).getOperand(1))
1364     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1365                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1366
1367   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1368   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1369     SDValue N00 = N0.getOperand(0);
1370     SDValue N01 = N0.getOperand(1);
1371     SDValue N10 = N1.getOperand(0);
1372     SDValue N11 = N1.getOperand(1);
1373
1374     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1375       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1376                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1377                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1378   }
1379
1380   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1381     return SDValue(N, 0);
1382
1383   // fold (a+b) -> (a|b) iff a and b share no bits.
1384   if (VT.isInteger() && !VT.isVector()) {
1385     APInt LHSZero, LHSOne;
1386     APInt RHSZero, RHSOne;
1387     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1388     DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1389
1390     if (LHSZero.getBoolValue()) {
1391       DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1392
1393       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1394       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1395       if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1396           (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1397         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1398     }
1399   }
1400
1401   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1402   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1403     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1404     if (Result.getNode()) return Result;
1405   }
1406   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1407     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1408     if (Result.getNode()) return Result;
1409   }
1410
1411   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1412   if (N1.getOpcode() == ISD::SHL &&
1413       N1.getOperand(0).getOpcode() == ISD::SUB)
1414     if (ConstantSDNode *C =
1415           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1416       if (C->getAPIntValue() == 0)
1417         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1418                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1419                                        N1.getOperand(0).getOperand(1),
1420                                        N1.getOperand(1)));
1421   if (N0.getOpcode() == ISD::SHL &&
1422       N0.getOperand(0).getOpcode() == ISD::SUB)
1423     if (ConstantSDNode *C =
1424           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1425       if (C->getAPIntValue() == 0)
1426         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1427                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1428                                        N0.getOperand(0).getOperand(1),
1429                                        N0.getOperand(1)));
1430
1431   if (N1.getOpcode() == ISD::AND) {
1432     SDValue AndOp0 = N1.getOperand(0);
1433     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1434     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1435     unsigned DestBits = VT.getScalarType().getSizeInBits();
1436
1437     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1438     // and similar xforms where the inner op is either ~0 or 0.
1439     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1440       DebugLoc DL = N->getDebugLoc();
1441       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1442     }
1443   }
1444
1445   // add (sext i1), X -> sub X, (zext i1)
1446   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1447       N0.getOperand(0).getValueType() == MVT::i1 &&
1448       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1449     DebugLoc DL = N->getDebugLoc();
1450     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1451     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1452   }
1453
1454   return SDValue();
1455 }
1456
1457 SDValue DAGCombiner::visitADDC(SDNode *N) {
1458   SDValue N0 = N->getOperand(0);
1459   SDValue N1 = N->getOperand(1);
1460   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1461   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1462   EVT VT = N0.getValueType();
1463
1464   // If the flag result is dead, turn this into an ADD.
1465   if (N->hasNUsesOfValue(0, 1))
1466     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1467                      DAG.getNode(ISD::CARRY_FALSE,
1468                                  N->getDebugLoc(), MVT::Glue));
1469
1470   // canonicalize constant to RHS.
1471   if (N0C && !N1C)
1472     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1473
1474   // fold (addc x, 0) -> x + no carry out
1475   if (N1C && N1C->isNullValue())
1476     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1477                                         N->getDebugLoc(), MVT::Glue));
1478
1479   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1480   APInt LHSZero, LHSOne;
1481   APInt RHSZero, RHSOne;
1482   APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1483   DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1484
1485   if (LHSZero.getBoolValue()) {
1486     DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1487
1488     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1489     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1490     if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1491         (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1492       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1493                        DAG.getNode(ISD::CARRY_FALSE,
1494                                    N->getDebugLoc(), MVT::Glue));
1495   }
1496
1497   return SDValue();
1498 }
1499
1500 SDValue DAGCombiner::visitADDE(SDNode *N) {
1501   SDValue N0 = N->getOperand(0);
1502   SDValue N1 = N->getOperand(1);
1503   SDValue CarryIn = N->getOperand(2);
1504   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1505   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1506
1507   // canonicalize constant to RHS
1508   if (N0C && !N1C)
1509     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1510                        N1, N0, CarryIn);
1511
1512   // fold (adde x, y, false) -> (addc x, y)
1513   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1514     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1515
1516   return SDValue();
1517 }
1518
1519 SDValue DAGCombiner::visitSUB(SDNode *N) {
1520   SDValue N0 = N->getOperand(0);
1521   SDValue N1 = N->getOperand(1);
1522   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1523   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1524   EVT VT = N0.getValueType();
1525
1526   // fold vector ops
1527   if (VT.isVector()) {
1528     SDValue FoldedVOp = SimplifyVBinOp(N);
1529     if (FoldedVOp.getNode()) return FoldedVOp;
1530   }
1531
1532   // fold (sub x, x) -> 0
1533   if (N0 == N1)
1534     return DAG.getConstant(0, N->getValueType(0));
1535   // fold (sub c1, c2) -> c1-c2
1536   if (N0C && N1C)
1537     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1538   // fold (sub x, c) -> (add x, -c)
1539   if (N1C)
1540     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1541                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1542   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1543   if (N0C && N0C->isAllOnesValue())
1544     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1545   // fold A-(A-B) -> B
1546   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1547     return N1.getOperand(1);
1548   // fold (A+B)-A -> B
1549   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1550     return N0.getOperand(1);
1551   // fold (A+B)-B -> A
1552   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1553     return N0.getOperand(0);
1554   // fold ((A+(B+or-C))-B) -> A+or-C
1555   if (N0.getOpcode() == ISD::ADD &&
1556       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1557        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1558       N0.getOperand(1).getOperand(0) == N1)
1559     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1560                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1561   // fold ((A+(C+B))-B) -> A+C
1562   if (N0.getOpcode() == ISD::ADD &&
1563       N0.getOperand(1).getOpcode() == ISD::ADD &&
1564       N0.getOperand(1).getOperand(1) == N1)
1565     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1566                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1567   // fold ((A-(B-C))-C) -> A-B
1568   if (N0.getOpcode() == ISD::SUB &&
1569       N0.getOperand(1).getOpcode() == ISD::SUB &&
1570       N0.getOperand(1).getOperand(1) == N1)
1571     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1572                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1573
1574   // If either operand of a sub is undef, the result is undef
1575   if (N0.getOpcode() == ISD::UNDEF)
1576     return N0;
1577   if (N1.getOpcode() == ISD::UNDEF)
1578     return N1;
1579
1580   // If the relocation model supports it, consider symbol offsets.
1581   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1582     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1583       // fold (sub Sym, c) -> Sym-c
1584       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1585         return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1586                                     GA->getOffset() -
1587                                       (uint64_t)N1C->getSExtValue());
1588       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1589       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1590         if (GA->getGlobal() == GB->getGlobal())
1591           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1592                                  VT);
1593     }
1594
1595   return SDValue();
1596 }
1597
1598 SDValue DAGCombiner::visitMUL(SDNode *N) {
1599   SDValue N0 = N->getOperand(0);
1600   SDValue N1 = N->getOperand(1);
1601   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1602   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1603   EVT VT = N0.getValueType();
1604
1605   // fold vector ops
1606   if (VT.isVector()) {
1607     SDValue FoldedVOp = SimplifyVBinOp(N);
1608     if (FoldedVOp.getNode()) return FoldedVOp;
1609   }
1610
1611   // fold (mul x, undef) -> 0
1612   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1613     return DAG.getConstant(0, VT);
1614   // fold (mul c1, c2) -> c1*c2
1615   if (N0C && N1C)
1616     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1617   // canonicalize constant to RHS
1618   if (N0C && !N1C)
1619     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1620   // fold (mul x, 0) -> 0
1621   if (N1C && N1C->isNullValue())
1622     return N1;
1623   // fold (mul x, -1) -> 0-x
1624   if (N1C && N1C->isAllOnesValue())
1625     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1626                        DAG.getConstant(0, VT), N0);
1627   // fold (mul x, (1 << c)) -> x << c
1628   if (N1C && N1C->getAPIntValue().isPowerOf2())
1629     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1630                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1631                                        getShiftAmountTy()));
1632   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1633   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1634     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1635     // FIXME: If the input is something that is easily negated (e.g. a
1636     // single-use add), we should put the negate there.
1637     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1638                        DAG.getConstant(0, VT),
1639                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1640                             DAG.getConstant(Log2Val, getShiftAmountTy())));
1641   }
1642   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1643   if (N1C && N0.getOpcode() == ISD::SHL &&
1644       isa<ConstantSDNode>(N0.getOperand(1))) {
1645     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1646                              N1, N0.getOperand(1));
1647     AddToWorkList(C3.getNode());
1648     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1649                        N0.getOperand(0), C3);
1650   }
1651
1652   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1653   // use.
1654   {
1655     SDValue Sh(0,0), Y(0,0);
1656     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1657     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1658         N0.getNode()->hasOneUse()) {
1659       Sh = N0; Y = N1;
1660     } else if (N1.getOpcode() == ISD::SHL &&
1661                isa<ConstantSDNode>(N1.getOperand(1)) &&
1662                N1.getNode()->hasOneUse()) {
1663       Sh = N1; Y = N0;
1664     }
1665
1666     if (Sh.getNode()) {
1667       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1668                                 Sh.getOperand(0), Y);
1669       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1670                          Mul, Sh.getOperand(1));
1671     }
1672   }
1673
1674   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1675   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1676       isa<ConstantSDNode>(N0.getOperand(1)))
1677     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1678                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1679                                    N0.getOperand(0), N1),
1680                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1681                                    N0.getOperand(1), N1));
1682
1683   // reassociate mul
1684   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1685   if (RMUL.getNode() != 0)
1686     return RMUL;
1687
1688   return SDValue();
1689 }
1690
1691 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1692   SDValue N0 = N->getOperand(0);
1693   SDValue N1 = N->getOperand(1);
1694   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1695   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1696   EVT VT = N->getValueType(0);
1697
1698   // fold vector ops
1699   if (VT.isVector()) {
1700     SDValue FoldedVOp = SimplifyVBinOp(N);
1701     if (FoldedVOp.getNode()) return FoldedVOp;
1702   }
1703
1704   // fold (sdiv c1, c2) -> c1/c2
1705   if (N0C && N1C && !N1C->isNullValue())
1706     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1707   // fold (sdiv X, 1) -> X
1708   if (N1C && N1C->getSExtValue() == 1LL)
1709     return N0;
1710   // fold (sdiv X, -1) -> 0-X
1711   if (N1C && N1C->isAllOnesValue())
1712     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1713                        DAG.getConstant(0, VT), N0);
1714   // If we know the sign bits of both operands are zero, strength reduce to a
1715   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1716   if (!VT.isVector()) {
1717     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1718       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1719                          N0, N1);
1720   }
1721   // fold (sdiv X, pow2) -> simple ops after legalize
1722   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1723       (isPowerOf2_64(N1C->getSExtValue()) ||
1724        isPowerOf2_64(-N1C->getSExtValue()))) {
1725     // If dividing by powers of two is cheap, then don't perform the following
1726     // fold.
1727     if (TLI.isPow2DivCheap())
1728       return SDValue();
1729
1730     int64_t pow2 = N1C->getSExtValue();
1731     int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1732     unsigned lg2 = Log2_64(abs2);
1733
1734     // Splat the sign bit into the register
1735     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1736                               DAG.getConstant(VT.getSizeInBits()-1,
1737                                               getShiftAmountTy()));
1738     AddToWorkList(SGN.getNode());
1739
1740     // Add (N0 < 0) ? abs2 - 1 : 0;
1741     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1742                               DAG.getConstant(VT.getSizeInBits() - lg2,
1743                                               getShiftAmountTy()));
1744     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1745     AddToWorkList(SRL.getNode());
1746     AddToWorkList(ADD.getNode());    // Divide by pow2
1747     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1748                               DAG.getConstant(lg2, getShiftAmountTy()));
1749
1750     // If we're dividing by a positive value, we're done.  Otherwise, we must
1751     // negate the result.
1752     if (pow2 > 0)
1753       return SRA;
1754
1755     AddToWorkList(SRA.getNode());
1756     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1757                        DAG.getConstant(0, VT), SRA);
1758   }
1759
1760   // if integer divide is expensive and we satisfy the requirements, emit an
1761   // alternate sequence.
1762   if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1763       !TLI.isIntDivCheap()) {
1764     SDValue Op = BuildSDIV(N);
1765     if (Op.getNode()) return Op;
1766   }
1767
1768   // undef / X -> 0
1769   if (N0.getOpcode() == ISD::UNDEF)
1770     return DAG.getConstant(0, VT);
1771   // X / undef -> undef
1772   if (N1.getOpcode() == ISD::UNDEF)
1773     return N1;
1774
1775   return SDValue();
1776 }
1777
1778 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1779   SDValue N0 = N->getOperand(0);
1780   SDValue N1 = N->getOperand(1);
1781   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1782   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1783   EVT VT = N->getValueType(0);
1784
1785   // fold vector ops
1786   if (VT.isVector()) {
1787     SDValue FoldedVOp = SimplifyVBinOp(N);
1788     if (FoldedVOp.getNode()) return FoldedVOp;
1789   }
1790
1791   // fold (udiv c1, c2) -> c1/c2
1792   if (N0C && N1C && !N1C->isNullValue())
1793     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1794   // fold (udiv x, (1 << c)) -> x >>u c
1795   if (N1C && N1C->getAPIntValue().isPowerOf2())
1796     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1797                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1798                                        getShiftAmountTy()));
1799   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1800   if (N1.getOpcode() == ISD::SHL) {
1801     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1802       if (SHC->getAPIntValue().isPowerOf2()) {
1803         EVT ADDVT = N1.getOperand(1).getValueType();
1804         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1805                                   N1.getOperand(1),
1806                                   DAG.getConstant(SHC->getAPIntValue()
1807                                                                   .logBase2(),
1808                                                   ADDVT));
1809         AddToWorkList(Add.getNode());
1810         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1811       }
1812     }
1813   }
1814   // fold (udiv x, c) -> alternate
1815   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1816     SDValue Op = BuildUDIV(N);
1817     if (Op.getNode()) return Op;
1818   }
1819
1820   // undef / X -> 0
1821   if (N0.getOpcode() == ISD::UNDEF)
1822     return DAG.getConstant(0, VT);
1823   // X / undef -> undef
1824   if (N1.getOpcode() == ISD::UNDEF)
1825     return N1;
1826
1827   return SDValue();
1828 }
1829
1830 SDValue DAGCombiner::visitSREM(SDNode *N) {
1831   SDValue N0 = N->getOperand(0);
1832   SDValue N1 = N->getOperand(1);
1833   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1834   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1835   EVT VT = N->getValueType(0);
1836
1837   // fold (srem c1, c2) -> c1%c2
1838   if (N0C && N1C && !N1C->isNullValue())
1839     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1840   // If we know the sign bits of both operands are zero, strength reduce to a
1841   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1842   if (!VT.isVector()) {
1843     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1844       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1845   }
1846
1847   // If X/C can be simplified by the division-by-constant logic, lower
1848   // X%C to the equivalent of X-X/C*C.
1849   if (N1C && !N1C->isNullValue()) {
1850     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1851     AddToWorkList(Div.getNode());
1852     SDValue OptimizedDiv = combine(Div.getNode());
1853     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1854       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1855                                 OptimizedDiv, N1);
1856       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1857       AddToWorkList(Mul.getNode());
1858       return Sub;
1859     }
1860   }
1861
1862   // undef % X -> 0
1863   if (N0.getOpcode() == ISD::UNDEF)
1864     return DAG.getConstant(0, VT);
1865   // X % undef -> undef
1866   if (N1.getOpcode() == ISD::UNDEF)
1867     return N1;
1868
1869   return SDValue();
1870 }
1871
1872 SDValue DAGCombiner::visitUREM(SDNode *N) {
1873   SDValue N0 = N->getOperand(0);
1874   SDValue N1 = N->getOperand(1);
1875   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1876   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1877   EVT VT = N->getValueType(0);
1878
1879   // fold (urem c1, c2) -> c1%c2
1880   if (N0C && N1C && !N1C->isNullValue())
1881     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1882   // fold (urem x, pow2) -> (and x, pow2-1)
1883   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1884     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1885                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
1886   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1887   if (N1.getOpcode() == ISD::SHL) {
1888     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1889       if (SHC->getAPIntValue().isPowerOf2()) {
1890         SDValue Add =
1891           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1892                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1893                                  VT));
1894         AddToWorkList(Add.getNode());
1895         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1896       }
1897     }
1898   }
1899
1900   // If X/C can be simplified by the division-by-constant logic, lower
1901   // X%C to the equivalent of X-X/C*C.
1902   if (N1C && !N1C->isNullValue()) {
1903     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1904     AddToWorkList(Div.getNode());
1905     SDValue OptimizedDiv = combine(Div.getNode());
1906     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1907       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1908                                 OptimizedDiv, N1);
1909       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1910       AddToWorkList(Mul.getNode());
1911       return Sub;
1912     }
1913   }
1914
1915   // undef % X -> 0
1916   if (N0.getOpcode() == ISD::UNDEF)
1917     return DAG.getConstant(0, VT);
1918   // X % undef -> undef
1919   if (N1.getOpcode() == ISD::UNDEF)
1920     return N1;
1921
1922   return SDValue();
1923 }
1924
1925 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1926   SDValue N0 = N->getOperand(0);
1927   SDValue N1 = N->getOperand(1);
1928   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1929   EVT VT = N->getValueType(0);
1930   DebugLoc DL = N->getDebugLoc();
1931
1932   // fold (mulhs x, 0) -> 0
1933   if (N1C && N1C->isNullValue())
1934     return N1;
1935   // fold (mulhs x, 1) -> (sra x, size(x)-1)
1936   if (N1C && N1C->getAPIntValue() == 1)
1937     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1938                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1939                                        getShiftAmountTy()));
1940   // fold (mulhs x, undef) -> 0
1941   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1942     return DAG.getConstant(0, VT);
1943
1944   // If the type twice as wide is legal, transform the mulhs to a wider multiply
1945   // plus a shift.
1946   if (VT.isSimple() && !VT.isVector()) {
1947     MVT Simple = VT.getSimpleVT();
1948     unsigned SimpleSize = Simple.getSizeInBits();
1949     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
1950     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
1951       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
1952       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
1953       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
1954       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
1955                        DAG.getConstant(SimpleSize, getShiftAmountTy()));
1956       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
1957     }
1958   }
1959   
1960   return SDValue();
1961 }
1962
1963 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1964   SDValue N0 = N->getOperand(0);
1965   SDValue N1 = N->getOperand(1);
1966   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1967   EVT VT = N->getValueType(0);
1968   DebugLoc DL = N->getDebugLoc();
1969
1970   // fold (mulhu x, 0) -> 0
1971   if (N1C && N1C->isNullValue())
1972     return N1;
1973   // fold (mulhu x, 1) -> 0
1974   if (N1C && N1C->getAPIntValue() == 1)
1975     return DAG.getConstant(0, N0.getValueType());
1976   // fold (mulhu x, undef) -> 0
1977   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1978     return DAG.getConstant(0, VT);
1979
1980   // If the type twice as wide is legal, transform the mulhu to a wider multiply
1981   // plus a shift.
1982   if (VT.isSimple() && !VT.isVector()) {
1983     MVT Simple = VT.getSimpleVT();
1984     unsigned SimpleSize = Simple.getSizeInBits();
1985     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
1986     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
1987       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
1988       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
1989       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
1990       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
1991                        DAG.getConstant(SimpleSize, getShiftAmountTy()));
1992       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
1993     }
1994   }
1995   
1996   return SDValue();
1997 }
1998
1999 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2000 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2001 /// that are being performed. Return true if a simplification was made.
2002 ///
2003 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2004                                                 unsigned HiOp) {
2005   // If the high half is not needed, just compute the low half.
2006   bool HiExists = N->hasAnyUseOfValue(1);
2007   if (!HiExists &&
2008       (!LegalOperations ||
2009        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2010     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2011                               N->op_begin(), N->getNumOperands());
2012     return CombineTo(N, Res, Res);
2013   }
2014
2015   // If the low half is not needed, just compute the high half.
2016   bool LoExists = N->hasAnyUseOfValue(0);
2017   if (!LoExists &&
2018       (!LegalOperations ||
2019        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2020     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2021                               N->op_begin(), N->getNumOperands());
2022     return CombineTo(N, Res, Res);
2023   }
2024
2025   // If both halves are used, return as it is.
2026   if (LoExists && HiExists)
2027     return SDValue();
2028
2029   // If the two computed results can be simplified separately, separate them.
2030   if (LoExists) {
2031     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2032                              N->op_begin(), N->getNumOperands());
2033     AddToWorkList(Lo.getNode());
2034     SDValue LoOpt = combine(Lo.getNode());
2035     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2036         (!LegalOperations ||
2037          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2038       return CombineTo(N, LoOpt, LoOpt);
2039   }
2040
2041   if (HiExists) {
2042     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2043                              N->op_begin(), N->getNumOperands());
2044     AddToWorkList(Hi.getNode());
2045     SDValue HiOpt = combine(Hi.getNode());
2046     if (HiOpt.getNode() && HiOpt != Hi &&
2047         (!LegalOperations ||
2048          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2049       return CombineTo(N, HiOpt, HiOpt);
2050   }
2051
2052   return SDValue();
2053 }
2054
2055 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2056   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2057   if (Res.getNode()) return Res;
2058
2059   EVT VT = N->getValueType(0);
2060   DebugLoc DL = N->getDebugLoc();
2061
2062   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2063   // plus a shift.
2064   if (VT.isSimple() && !VT.isVector()) {
2065     MVT Simple = VT.getSimpleVT();
2066     unsigned SimpleSize = Simple.getSizeInBits();
2067     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2068     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2069       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2070       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2071       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2072       // Compute the high part as N1.
2073       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2074                        DAG.getConstant(SimpleSize, getShiftAmountTy()));
2075       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2076       // Compute the low part as N0.
2077       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2078       return CombineTo(N, Lo, Hi);
2079     }
2080   }
2081   
2082   return SDValue();
2083 }
2084
2085 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2086   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2087   if (Res.getNode()) return Res;
2088
2089   EVT VT = N->getValueType(0);
2090   DebugLoc DL = N->getDebugLoc();
2091   
2092   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2093   // plus a shift.
2094   if (VT.isSimple() && !VT.isVector()) {
2095     MVT Simple = VT.getSimpleVT();
2096     unsigned SimpleSize = Simple.getSizeInBits();
2097     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2098     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2099       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2100       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2101       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2102       // Compute the high part as N1.
2103       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2104                        DAG.getConstant(SimpleSize, getShiftAmountTy()));
2105       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2106       // Compute the low part as N0.
2107       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2108       return CombineTo(N, Lo, Hi);
2109     }
2110   }
2111   
2112   return SDValue();
2113 }
2114
2115 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2116   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2117   if (Res.getNode()) return Res;
2118
2119   return SDValue();
2120 }
2121
2122 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2123   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2124   if (Res.getNode()) return Res;
2125
2126   return SDValue();
2127 }
2128
2129 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2130 /// two operands of the same opcode, try to simplify it.
2131 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2132   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2133   EVT VT = N0.getValueType();
2134   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2135
2136   // Bail early if none of these transforms apply.
2137   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2138
2139   // For each of OP in AND/OR/XOR:
2140   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2141   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2142   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2143   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2144   //
2145   // do not sink logical op inside of a vector extend, since it may combine
2146   // into a vsetcc.
2147   EVT Op0VT = N0.getOperand(0).getValueType();
2148   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2149        N0.getOpcode() == ISD::SIGN_EXTEND ||
2150        // Avoid infinite looping with PromoteIntBinOp.
2151        (N0.getOpcode() == ISD::ANY_EXTEND &&
2152         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2153        (N0.getOpcode() == ISD::TRUNCATE &&
2154         (!TLI.isZExtFree(VT, Op0VT) ||
2155          !TLI.isTruncateFree(Op0VT, VT)) &&
2156         TLI.isTypeLegal(Op0VT))) &&
2157       !VT.isVector() &&
2158       Op0VT == N1.getOperand(0).getValueType() &&
2159       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2160     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2161                                  N0.getOperand(0).getValueType(),
2162                                  N0.getOperand(0), N1.getOperand(0));
2163     AddToWorkList(ORNode.getNode());
2164     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2165   }
2166
2167   // For each of OP in SHL/SRL/SRA/AND...
2168   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2169   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2170   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2171   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2172        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2173       N0.getOperand(1) == N1.getOperand(1)) {
2174     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2175                                  N0.getOperand(0).getValueType(),
2176                                  N0.getOperand(0), N1.getOperand(0));
2177     AddToWorkList(ORNode.getNode());
2178     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2179                        ORNode, N0.getOperand(1));
2180   }
2181
2182   return SDValue();
2183 }
2184
2185 SDValue DAGCombiner::visitAND(SDNode *N) {
2186   SDValue N0 = N->getOperand(0);
2187   SDValue N1 = N->getOperand(1);
2188   SDValue LL, LR, RL, RR, CC0, CC1;
2189   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2190   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2191   EVT VT = N1.getValueType();
2192   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2193
2194   // fold vector ops
2195   if (VT.isVector()) {
2196     SDValue FoldedVOp = SimplifyVBinOp(N);
2197     if (FoldedVOp.getNode()) return FoldedVOp;
2198   }
2199
2200   // fold (and x, undef) -> 0
2201   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2202     return DAG.getConstant(0, VT);
2203   // fold (and c1, c2) -> c1&c2
2204   if (N0C && N1C)
2205     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2206   // canonicalize constant to RHS
2207   if (N0C && !N1C)
2208     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2209   // fold (and x, -1) -> x
2210   if (N1C && N1C->isAllOnesValue())
2211     return N0;
2212   // if (and x, c) is known to be zero, return 0
2213   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2214                                    APInt::getAllOnesValue(BitWidth)))
2215     return DAG.getConstant(0, VT);
2216   // reassociate and
2217   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2218   if (RAND.getNode() != 0)
2219     return RAND;
2220   // fold (and (or x, C), D) -> D if (C & D) == D
2221   if (N1C && N0.getOpcode() == ISD::OR)
2222     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2223       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2224         return N1;
2225   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2226   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2227     SDValue N0Op0 = N0.getOperand(0);
2228     APInt Mask = ~N1C->getAPIntValue();
2229     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2230     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2231       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2232                                  N0.getValueType(), N0Op0);
2233
2234       // Replace uses of the AND with uses of the Zero extend node.
2235       CombineTo(N, Zext);
2236
2237       // We actually want to replace all uses of the any_extend with the
2238       // zero_extend, to avoid duplicating things.  This will later cause this
2239       // AND to be folded.
2240       CombineTo(N0.getNode(), Zext);
2241       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2242     }
2243   }
2244   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2245   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2246     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2247     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2248
2249     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2250         LL.getValueType().isInteger()) {
2251       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2252       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2253         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2254                                      LR.getValueType(), LL, RL);
2255         AddToWorkList(ORNode.getNode());
2256         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2257       }
2258       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2259       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2260         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2261                                       LR.getValueType(), LL, RL);
2262         AddToWorkList(ANDNode.getNode());
2263         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2264       }
2265       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2266       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2267         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2268                                      LR.getValueType(), LL, RL);
2269         AddToWorkList(ORNode.getNode());
2270         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2271       }
2272     }
2273     // canonicalize equivalent to ll == rl
2274     if (LL == RR && LR == RL) {
2275       Op1 = ISD::getSetCCSwappedOperands(Op1);
2276       std::swap(RL, RR);
2277     }
2278     if (LL == RL && LR == RR) {
2279       bool isInteger = LL.getValueType().isInteger();
2280       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2281       if (Result != ISD::SETCC_INVALID &&
2282           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2283         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2284                             LL, LR, Result);
2285     }
2286   }
2287
2288   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2289   if (N0.getOpcode() == N1.getOpcode()) {
2290     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2291     if (Tmp.getNode()) return Tmp;
2292   }
2293
2294   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2295   // fold (and (sra)) -> (and (srl)) when possible.
2296   if (!VT.isVector() &&
2297       SimplifyDemandedBits(SDValue(N, 0)))
2298     return SDValue(N, 0);
2299
2300   // fold (zext_inreg (extload x)) -> (zextload x)
2301   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2302     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2303     EVT MemVT = LN0->getMemoryVT();
2304     // If we zero all the possible extended bits, then we can turn this into
2305     // a zextload if we are running before legalize or the operation is legal.
2306     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2307     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2308                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2309         ((!LegalOperations && !LN0->isVolatile()) ||
2310          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2311       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getDebugLoc(),
2312                                        LN0->getChain(), LN0->getBasePtr(),
2313                                        LN0->getPointerInfo(), MemVT,
2314                                        LN0->isVolatile(), LN0->isNonTemporal(),
2315                                        LN0->getAlignment());
2316       AddToWorkList(N);
2317       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2318       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2319     }
2320   }
2321   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2322   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2323       N0.hasOneUse()) {
2324     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2325     EVT MemVT = LN0->getMemoryVT();
2326     // If we zero all the possible extended bits, then we can turn this into
2327     // a zextload if we are running before legalize or the operation is legal.
2328     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2329     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2330                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2331         ((!LegalOperations && !LN0->isVolatile()) ||
2332          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2333       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getDebugLoc(),
2334                                        LN0->getChain(),
2335                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2336                                        MemVT,
2337                                        LN0->isVolatile(), LN0->isNonTemporal(),
2338                                        LN0->getAlignment());
2339       AddToWorkList(N);
2340       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2341       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2342     }
2343   }
2344
2345   // fold (and (load x), 255) -> (zextload x, i8)
2346   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2347   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2348   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2349               (N0.getOpcode() == ISD::ANY_EXTEND &&
2350                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2351     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2352     LoadSDNode *LN0 = HasAnyExt
2353       ? cast<LoadSDNode>(N0.getOperand(0))
2354       : cast<LoadSDNode>(N0);
2355     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2356         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2357       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2358       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2359         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2360         EVT LoadedVT = LN0->getMemoryVT();
2361
2362         if (ExtVT == LoadedVT &&
2363             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2364           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2365
2366           SDValue NewLoad =
2367             DAG.getExtLoad(ISD::ZEXTLOAD, LoadResultTy, LN0->getDebugLoc(),
2368                            LN0->getChain(), LN0->getBasePtr(),
2369                            LN0->getPointerInfo(),
2370                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2371                            LN0->getAlignment());
2372           AddToWorkList(N);
2373           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2374           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2375         }
2376
2377         // Do not change the width of a volatile load.
2378         // Do not generate loads of non-round integer types since these can
2379         // be expensive (and would be wrong if the type is not byte sized).
2380         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2381             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2382           EVT PtrType = LN0->getOperand(1).getValueType();
2383
2384           unsigned Alignment = LN0->getAlignment();
2385           SDValue NewPtr = LN0->getBasePtr();
2386
2387           // For big endian targets, we need to add an offset to the pointer
2388           // to load the correct bytes.  For little endian systems, we merely
2389           // need to read fewer bytes from the same pointer.
2390           if (TLI.isBigEndian()) {
2391             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2392             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2393             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2394             NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2395                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2396             Alignment = MinAlign(Alignment, PtrOff);
2397           }
2398
2399           AddToWorkList(NewPtr.getNode());
2400
2401           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2402           SDValue Load =
2403             DAG.getExtLoad(ISD::ZEXTLOAD, LoadResultTy, LN0->getDebugLoc(),
2404                            LN0->getChain(), NewPtr,
2405                            LN0->getPointerInfo(),
2406                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2407                            Alignment);
2408           AddToWorkList(N);
2409           CombineTo(LN0, Load, Load.getValue(1));
2410           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2411         }
2412       }
2413     }
2414   }
2415
2416   return SDValue();
2417 }
2418
2419 SDValue DAGCombiner::visitOR(SDNode *N) {
2420   SDValue N0 = N->getOperand(0);
2421   SDValue N1 = N->getOperand(1);
2422   SDValue LL, LR, RL, RR, CC0, CC1;
2423   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2424   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2425   EVT VT = N1.getValueType();
2426
2427   // fold vector ops
2428   if (VT.isVector()) {
2429     SDValue FoldedVOp = SimplifyVBinOp(N);
2430     if (FoldedVOp.getNode()) return FoldedVOp;
2431   }
2432
2433   // fold (or x, undef) -> -1
2434   if (!LegalOperations &&
2435       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2436     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2437     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2438   }
2439   // fold (or c1, c2) -> c1|c2
2440   if (N0C && N1C)
2441     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2442   // canonicalize constant to RHS
2443   if (N0C && !N1C)
2444     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2445   // fold (or x, 0) -> x
2446   if (N1C && N1C->isNullValue())
2447     return N0;
2448   // fold (or x, -1) -> -1
2449   if (N1C && N1C->isAllOnesValue())
2450     return N1;
2451   // fold (or x, c) -> c iff (x & ~c) == 0
2452   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2453     return N1;
2454   // reassociate or
2455   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2456   if (ROR.getNode() != 0)
2457     return ROR;
2458   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2459   // iff (c1 & c2) == 0.
2460   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2461              isa<ConstantSDNode>(N0.getOperand(1))) {
2462     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2463     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2464       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2465                          DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2466                                      N0.getOperand(0), N1),
2467                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2468   }
2469   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2470   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2471     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2472     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2473
2474     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2475         LL.getValueType().isInteger()) {
2476       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2477       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2478       if (cast<ConstantSDNode>(LR)->isNullValue() &&
2479           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2480         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2481                                      LR.getValueType(), LL, RL);
2482         AddToWorkList(ORNode.getNode());
2483         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2484       }
2485       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2486       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
2487       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2488           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2489         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2490                                       LR.getValueType(), LL, RL);
2491         AddToWorkList(ANDNode.getNode());
2492         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2493       }
2494     }
2495     // canonicalize equivalent to ll == rl
2496     if (LL == RR && LR == RL) {
2497       Op1 = ISD::getSetCCSwappedOperands(Op1);
2498       std::swap(RL, RR);
2499     }
2500     if (LL == RL && LR == RR) {
2501       bool isInteger = LL.getValueType().isInteger();
2502       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2503       if (Result != ISD::SETCC_INVALID &&
2504           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2505         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2506                             LL, LR, Result);
2507     }
2508   }
2509
2510   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
2511   if (N0.getOpcode() == N1.getOpcode()) {
2512     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2513     if (Tmp.getNode()) return Tmp;
2514   }
2515
2516   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
2517   if (N0.getOpcode() == ISD::AND &&
2518       N1.getOpcode() == ISD::AND &&
2519       N0.getOperand(1).getOpcode() == ISD::Constant &&
2520       N1.getOperand(1).getOpcode() == ISD::Constant &&
2521       // Don't increase # computations.
2522       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2523     // We can only do this xform if we know that bits from X that are set in C2
2524     // but not in C1 are already zero.  Likewise for Y.
2525     const APInt &LHSMask =
2526       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2527     const APInt &RHSMask =
2528       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2529
2530     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2531         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2532       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2533                               N0.getOperand(0), N1.getOperand(0));
2534       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2535                          DAG.getConstant(LHSMask | RHSMask, VT));
2536     }
2537   }
2538
2539   // See if this is some rotate idiom.
2540   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2541     return SDValue(Rot, 0);
2542
2543   // Simplify the operands using demanded-bits information.
2544   if (!VT.isVector() &&
2545       SimplifyDemandedBits(SDValue(N, 0)))
2546     return SDValue(N, 0);
2547
2548   return SDValue();
2549 }
2550
2551 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2552 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2553   if (Op.getOpcode() == ISD::AND) {
2554     if (isa<ConstantSDNode>(Op.getOperand(1))) {
2555       Mask = Op.getOperand(1);
2556       Op = Op.getOperand(0);
2557     } else {
2558       return false;
2559     }
2560   }
2561
2562   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2563     Shift = Op;
2564     return true;
2565   }
2566
2567   return false;
2568 }
2569
2570 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
2571 // idioms for rotate, and if the target supports rotation instructions, generate
2572 // a rot[lr].
2573 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2574   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
2575   EVT VT = LHS.getValueType();
2576   if (!TLI.isTypeLegal(VT)) return 0;
2577
2578   // The target must have at least one rotate flavor.
2579   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2580   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2581   if (!HasROTL && !HasROTR) return 0;
2582
2583   // Match "(X shl/srl V1) & V2" where V2 may not be present.
2584   SDValue LHSShift;   // The shift.
2585   SDValue LHSMask;    // AND value if any.
2586   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2587     return 0; // Not part of a rotate.
2588
2589   SDValue RHSShift;   // The shift.
2590   SDValue RHSMask;    // AND value if any.
2591   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2592     return 0; // Not part of a rotate.
2593
2594   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2595     return 0;   // Not shifting the same value.
2596
2597   if (LHSShift.getOpcode() == RHSShift.getOpcode())
2598     return 0;   // Shifts must disagree.
2599
2600   // Canonicalize shl to left side in a shl/srl pair.
2601   if (RHSShift.getOpcode() == ISD::SHL) {
2602     std::swap(LHS, RHS);
2603     std::swap(LHSShift, RHSShift);
2604     std::swap(LHSMask , RHSMask );
2605   }
2606
2607   unsigned OpSizeInBits = VT.getSizeInBits();
2608   SDValue LHSShiftArg = LHSShift.getOperand(0);
2609   SDValue LHSShiftAmt = LHSShift.getOperand(1);
2610   SDValue RHSShiftAmt = RHSShift.getOperand(1);
2611
2612   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2613   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2614   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2615       RHSShiftAmt.getOpcode() == ISD::Constant) {
2616     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2617     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2618     if ((LShVal + RShVal) != OpSizeInBits)
2619       return 0;
2620
2621     SDValue Rot;
2622     if (HasROTL)
2623       Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2624     else
2625       Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2626
2627     // If there is an AND of either shifted operand, apply it to the result.
2628     if (LHSMask.getNode() || RHSMask.getNode()) {
2629       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2630
2631       if (LHSMask.getNode()) {
2632         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2633         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2634       }
2635       if (RHSMask.getNode()) {
2636         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2637         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2638       }
2639
2640       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2641     }
2642
2643     return Rot.getNode();
2644   }
2645
2646   // If there is a mask here, and we have a variable shift, we can't be sure
2647   // that we're masking out the right stuff.
2648   if (LHSMask.getNode() || RHSMask.getNode())
2649     return 0;
2650
2651   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2652   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2653   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2654       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2655     if (ConstantSDNode *SUBC =
2656           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2657       if (SUBC->getAPIntValue() == OpSizeInBits) {
2658         if (HasROTL)
2659           return DAG.getNode(ISD::ROTL, DL, VT,
2660                              LHSShiftArg, LHSShiftAmt).getNode();
2661         else
2662           return DAG.getNode(ISD::ROTR, DL, VT,
2663                              LHSShiftArg, RHSShiftAmt).getNode();
2664       }
2665     }
2666   }
2667
2668   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2669   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2670   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2671       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2672     if (ConstantSDNode *SUBC =
2673           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2674       if (SUBC->getAPIntValue() == OpSizeInBits) {
2675         if (HasROTR)
2676           return DAG.getNode(ISD::ROTR, DL, VT,
2677                              LHSShiftArg, RHSShiftAmt).getNode();
2678         else
2679           return DAG.getNode(ISD::ROTL, DL, VT,
2680                              LHSShiftArg, LHSShiftAmt).getNode();
2681       }
2682     }
2683   }
2684
2685   // Look for sign/zext/any-extended or truncate cases:
2686   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2687        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2688        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2689        || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2690       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2691        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2692        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2693        || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2694     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2695     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2696     if (RExtOp0.getOpcode() == ISD::SUB &&
2697         RExtOp0.getOperand(1) == LExtOp0) {
2698       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2699       //   (rotl x, y)
2700       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2701       //   (rotr x, (sub 32, y))
2702       if (ConstantSDNode *SUBC =
2703             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2704         if (SUBC->getAPIntValue() == OpSizeInBits) {
2705           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2706                              LHSShiftArg,
2707                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2708         }
2709       }
2710     } else if (LExtOp0.getOpcode() == ISD::SUB &&
2711                RExtOp0 == LExtOp0.getOperand(1)) {
2712       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2713       //   (rotr x, y)
2714       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2715       //   (rotl x, (sub 32, y))
2716       if (ConstantSDNode *SUBC =
2717             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2718         if (SUBC->getAPIntValue() == OpSizeInBits) {
2719           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2720                              LHSShiftArg,
2721                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2722         }
2723       }
2724     }
2725   }
2726
2727   return 0;
2728 }
2729
2730 SDValue DAGCombiner::visitXOR(SDNode *N) {
2731   SDValue N0 = N->getOperand(0);
2732   SDValue N1 = N->getOperand(1);
2733   SDValue LHS, RHS, CC;
2734   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2735   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2736   EVT VT = N0.getValueType();
2737
2738   // fold vector ops
2739   if (VT.isVector()) {
2740     SDValue FoldedVOp = SimplifyVBinOp(N);
2741     if (FoldedVOp.getNode()) return FoldedVOp;
2742   }
2743
2744   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2745   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2746     return DAG.getConstant(0, VT);
2747   // fold (xor x, undef) -> undef
2748   if (N0.getOpcode() == ISD::UNDEF)
2749     return N0;
2750   if (N1.getOpcode() == ISD::UNDEF)
2751     return N1;
2752   // fold (xor c1, c2) -> c1^c2
2753   if (N0C && N1C)
2754     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2755   // canonicalize constant to RHS
2756   if (N0C && !N1C)
2757     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2758   // fold (xor x, 0) -> x
2759   if (N1C && N1C->isNullValue())
2760     return N0;
2761   // reassociate xor
2762   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2763   if (RXOR.getNode() != 0)
2764     return RXOR;
2765
2766   // fold !(x cc y) -> (x !cc y)
2767   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2768     bool isInt = LHS.getValueType().isInteger();
2769     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2770                                                isInt);
2771
2772     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2773       switch (N0.getOpcode()) {
2774       default:
2775         llvm_unreachable("Unhandled SetCC Equivalent!");
2776       case ISD::SETCC:
2777         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2778       case ISD::SELECT_CC:
2779         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2780                                N0.getOperand(3), NotCC);
2781       }
2782     }
2783   }
2784
2785   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2786   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2787       N0.getNode()->hasOneUse() &&
2788       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2789     SDValue V = N0.getOperand(0);
2790     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2791                     DAG.getConstant(1, V.getValueType()));
2792     AddToWorkList(V.getNode());
2793     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2794   }
2795
2796   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2797   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2798       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2799     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2800     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2801       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2802       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2803       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2804       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2805       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2806     }
2807   }
2808   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2809   if (N1C && N1C->isAllOnesValue() &&
2810       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2811     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2812     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2813       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2814       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2815       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2816       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2817       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2818     }
2819   }
2820   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2821   if (N1C && N0.getOpcode() == ISD::XOR) {
2822     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2823     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2824     if (N00C)
2825       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2826                          DAG.getConstant(N1C->getAPIntValue() ^
2827                                          N00C->getAPIntValue(), VT));
2828     if (N01C)
2829       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2830                          DAG.getConstant(N1C->getAPIntValue() ^
2831                                          N01C->getAPIntValue(), VT));
2832   }
2833   // fold (xor x, x) -> 0
2834   if (N0 == N1) {
2835     if (!VT.isVector()) {
2836       return DAG.getConstant(0, VT);
2837     } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2838       // Produce a vector of zeros.
2839       SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2840       std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2841       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2842                          &Ops[0], Ops.size());
2843     }
2844   }
2845
2846   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
2847   if (N0.getOpcode() == N1.getOpcode()) {
2848     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2849     if (Tmp.getNode()) return Tmp;
2850   }
2851
2852   // Simplify the expression using non-local knowledge.
2853   if (!VT.isVector() &&
2854       SimplifyDemandedBits(SDValue(N, 0)))
2855     return SDValue(N, 0);
2856
2857   return SDValue();
2858 }
2859
2860 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2861 /// the shift amount is a constant.
2862 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2863   SDNode *LHS = N->getOperand(0).getNode();
2864   if (!LHS->hasOneUse()) return SDValue();
2865
2866   // We want to pull some binops through shifts, so that we have (and (shift))
2867   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
2868   // thing happens with address calculations, so it's important to canonicalize
2869   // it.
2870   bool HighBitSet = false;  // Can we transform this if the high bit is set?
2871
2872   switch (LHS->getOpcode()) {
2873   default: return SDValue();
2874   case ISD::OR:
2875   case ISD::XOR:
2876     HighBitSet = false; // We can only transform sra if the high bit is clear.
2877     break;
2878   case ISD::AND:
2879     HighBitSet = true;  // We can only transform sra if the high bit is set.
2880     break;
2881   case ISD::ADD:
2882     if (N->getOpcode() != ISD::SHL)
2883       return SDValue(); // only shl(add) not sr[al](add).
2884     HighBitSet = false; // We can only transform sra if the high bit is clear.
2885     break;
2886   }
2887
2888   // We require the RHS of the binop to be a constant as well.
2889   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2890   if (!BinOpCst) return SDValue();
2891
2892   // FIXME: disable this unless the input to the binop is a shift by a constant.
2893   // If it is not a shift, it pessimizes some common cases like:
2894   //
2895   //    void foo(int *X, int i) { X[i & 1235] = 1; }
2896   //    int bar(int *X, int i) { return X[i & 255]; }
2897   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2898   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2899        BinOpLHSVal->getOpcode() != ISD::SRA &&
2900        BinOpLHSVal->getOpcode() != ISD::SRL) ||
2901       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2902     return SDValue();
2903
2904   EVT VT = N->getValueType(0);
2905
2906   // If this is a signed shift right, and the high bit is modified by the
2907   // logical operation, do not perform the transformation. The highBitSet
2908   // boolean indicates the value of the high bit of the constant which would
2909   // cause it to be modified for this operation.
2910   if (N->getOpcode() == ISD::SRA) {
2911     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2912     if (BinOpRHSSignSet != HighBitSet)
2913       return SDValue();
2914   }
2915
2916   // Fold the constants, shifting the binop RHS by the shift amount.
2917   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2918                                N->getValueType(0),
2919                                LHS->getOperand(1), N->getOperand(1));
2920
2921   // Create the new shift.
2922   SDValue NewShift = DAG.getNode(N->getOpcode(),
2923                                  LHS->getOperand(0).getDebugLoc(),
2924                                  VT, LHS->getOperand(0), N->getOperand(1));
2925
2926   // Create the new binop.
2927   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2928 }
2929
2930 SDValue DAGCombiner::visitSHL(SDNode *N) {
2931   SDValue N0 = N->getOperand(0);
2932   SDValue N1 = N->getOperand(1);
2933   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2934   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2935   EVT VT = N0.getValueType();
2936   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2937
2938   // fold (shl c1, c2) -> c1<<c2
2939   if (N0C && N1C)
2940     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2941   // fold (shl 0, x) -> 0
2942   if (N0C && N0C->isNullValue())
2943     return N0;
2944   // fold (shl x, c >= size(x)) -> undef
2945   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2946     return DAG.getUNDEF(VT);
2947   // fold (shl x, 0) -> x
2948   if (N1C && N1C->isNullValue())
2949     return N0;
2950   // if (shl x, c) is known to be zero, return 0
2951   if (DAG.MaskedValueIsZero(SDValue(N, 0),
2952                             APInt::getAllOnesValue(OpSizeInBits)))
2953     return DAG.getConstant(0, VT);
2954   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2955   if (N1.getOpcode() == ISD::TRUNCATE &&
2956       N1.getOperand(0).getOpcode() == ISD::AND &&
2957       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2958     SDValue N101 = N1.getOperand(0).getOperand(1);
2959     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2960       EVT TruncVT = N1.getValueType();
2961       SDValue N100 = N1.getOperand(0).getOperand(0);
2962       APInt TruncC = N101C->getAPIntValue();
2963       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
2964       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2965                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2966                                      DAG.getNode(ISD::TRUNCATE,
2967                                                  N->getDebugLoc(),
2968                                                  TruncVT, N100),
2969                                      DAG.getConstant(TruncC, TruncVT)));
2970     }
2971   }
2972
2973   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2974     return SDValue(N, 0);
2975
2976   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2977   if (N1C && N0.getOpcode() == ISD::SHL &&
2978       N0.getOperand(1).getOpcode() == ISD::Constant) {
2979     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2980     uint64_t c2 = N1C->getZExtValue();
2981     if (c1 + c2 >= OpSizeInBits)
2982       return DAG.getConstant(0, VT);
2983     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2984                        DAG.getConstant(c1 + c2, N1.getValueType()));
2985   }
2986
2987   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
2988   // For this to be valid, the second form must not preserve any of the bits
2989   // that are shifted out by the inner shift in the first form.  This means
2990   // the outer shift size must be >= the number of bits added by the ext.
2991   // As a corollary, we don't care what kind of ext it is.
2992   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
2993               N0.getOpcode() == ISD::ANY_EXTEND ||
2994               N0.getOpcode() == ISD::SIGN_EXTEND) &&
2995       N0.getOperand(0).getOpcode() == ISD::SHL &&
2996       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
2997     uint64_t c1 = 
2998       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
2999     uint64_t c2 = N1C->getZExtValue();
3000     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3001     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3002     if (c2 >= OpSizeInBits - InnerShiftSize) {
3003       if (c1 + c2 >= OpSizeInBits)
3004         return DAG.getConstant(0, VT);
3005       return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3006                          DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3007                                      N0.getOperand(0)->getOperand(0)),
3008                          DAG.getConstant(c1 + c2, N1.getValueType()));
3009     }
3010   }
3011
3012   // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
3013   //                               (srl (and x, (shl -1, c1)), (sub c1, c2))
3014   if (N1C && N0.getOpcode() == ISD::SRL &&
3015       N0.getOperand(1).getOpcode() == ISD::Constant) {
3016     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3017     if (c1 < VT.getSizeInBits()) {
3018       uint64_t c2 = N1C->getZExtValue();
3019       SDValue HiBitsMask =
3020         DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3021                                               VT.getSizeInBits() - c1),
3022                         VT);
3023       SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
3024                                  N0.getOperand(0),
3025                                  HiBitsMask);
3026       if (c2 > c1)
3027         return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
3028                            DAG.getConstant(c2-c1, N1.getValueType()));
3029       else
3030         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
3031                            DAG.getConstant(c1-c2, N1.getValueType()));
3032     }
3033   }
3034   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3035   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3036     SDValue HiBitsMask =
3037       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3038                                             VT.getSizeInBits() -
3039                                               N1C->getZExtValue()),
3040                       VT);
3041     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3042                        HiBitsMask);
3043   }
3044
3045   if (N1C) {
3046     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3047     if (NewSHL.getNode())
3048       return NewSHL;
3049   }
3050
3051   return SDValue();
3052 }
3053
3054 SDValue DAGCombiner::visitSRA(SDNode *N) {
3055   SDValue N0 = N->getOperand(0);
3056   SDValue N1 = N->getOperand(1);
3057   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3058   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3059   EVT VT = N0.getValueType();
3060   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3061
3062   // fold (sra c1, c2) -> (sra c1, c2)
3063   if (N0C && N1C)
3064     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3065   // fold (sra 0, x) -> 0
3066   if (N0C && N0C->isNullValue())
3067     return N0;
3068   // fold (sra -1, x) -> -1
3069   if (N0C && N0C->isAllOnesValue())
3070     return N0;
3071   // fold (sra x, (setge c, size(x))) -> undef
3072   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3073     return DAG.getUNDEF(VT);
3074   // fold (sra x, 0) -> x
3075   if (N1C && N1C->isNullValue())
3076     return N0;
3077   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3078   // sext_inreg.
3079   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3080     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3081     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3082     if (VT.isVector())
3083       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3084                                ExtVT, VT.getVectorNumElements());
3085     if ((!LegalOperations ||
3086          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3087       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3088                          N0.getOperand(0), DAG.getValueType(ExtVT));
3089   }
3090
3091   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3092   if (N1C && N0.getOpcode() == ISD::SRA) {
3093     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3094       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3095       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3096       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3097                          DAG.getConstant(Sum, N1C->getValueType(0)));
3098     }
3099   }
3100
3101   // fold (sra (shl X, m), (sub result_size, n))
3102   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3103   // result_size - n != m.
3104   // If truncate is free for the target sext(shl) is likely to result in better
3105   // code.
3106   if (N0.getOpcode() == ISD::SHL) {
3107     // Get the two constanst of the shifts, CN0 = m, CN = n.
3108     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3109     if (N01C && N1C) {
3110       // Determine what the truncate's result bitsize and type would be.
3111       EVT TruncVT =
3112         EVT::getIntegerVT(*DAG.getContext(),
3113                           OpSizeInBits - N1C->getZExtValue());
3114       // Determine the residual right-shift amount.
3115       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3116
3117       // If the shift is not a no-op (in which case this should be just a sign
3118       // extend already), the truncated to type is legal, sign_extend is legal
3119       // on that type, and the truncate to that type is both legal and free,
3120       // perform the transform.
3121       if ((ShiftAmt > 0) &&
3122           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3123           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3124           TLI.isTruncateFree(VT, TruncVT)) {
3125
3126           SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
3127           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3128                                       N0.getOperand(0), Amt);
3129           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3130                                       Shift);
3131           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3132                              N->getValueType(0), Trunc);
3133       }
3134     }
3135   }
3136
3137   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3138   if (N1.getOpcode() == ISD::TRUNCATE &&
3139       N1.getOperand(0).getOpcode() == ISD::AND &&
3140       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3141     SDValue N101 = N1.getOperand(0).getOperand(1);
3142     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3143       EVT TruncVT = N1.getValueType();
3144       SDValue N100 = N1.getOperand(0).getOperand(0);
3145       APInt TruncC = N101C->getAPIntValue();
3146       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3147       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3148                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3149                                      TruncVT,
3150                                      DAG.getNode(ISD::TRUNCATE,
3151                                                  N->getDebugLoc(),
3152                                                  TruncVT, N100),
3153                                      DAG.getConstant(TruncC, TruncVT)));
3154     }
3155   }
3156
3157   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3158   //      if c1 is equal to the number of bits the trunc removes
3159   if (N0.getOpcode() == ISD::TRUNCATE &&
3160       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3161        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3162       N0.getOperand(0).hasOneUse() &&
3163       N0.getOperand(0).getOperand(1).hasOneUse() &&
3164       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3165     EVT LargeVT = N0.getOperand(0).getValueType();
3166     ConstantSDNode *LargeShiftAmt =
3167       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3168
3169     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3170         LargeShiftAmt->getZExtValue()) {
3171       SDValue Amt =
3172         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3173                         getShiftAmountTy());
3174       SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3175                                 N0.getOperand(0).getOperand(0), Amt);
3176       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3177     }
3178   }
3179
3180   // Simplify, based on bits shifted out of the LHS.
3181   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3182     return SDValue(N, 0);
3183
3184
3185   // If the sign bit is known to be zero, switch this to a SRL.
3186   if (DAG.SignBitIsZero(N0))
3187     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3188
3189   if (N1C) {
3190     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3191     if (NewSRA.getNode())
3192       return NewSRA;
3193   }
3194
3195   return SDValue();
3196 }
3197
3198 SDValue DAGCombiner::visitSRL(SDNode *N) {
3199   SDValue N0 = N->getOperand(0);
3200   SDValue N1 = N->getOperand(1);
3201   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3202   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3203   EVT VT = N0.getValueType();
3204   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3205
3206   // fold (srl c1, c2) -> c1 >>u c2
3207   if (N0C && N1C)
3208     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3209   // fold (srl 0, x) -> 0
3210   if (N0C && N0C->isNullValue())
3211     return N0;
3212   // fold (srl x, c >= size(x)) -> undef
3213   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3214     return DAG.getUNDEF(VT);
3215   // fold (srl x, 0) -> x
3216   if (N1C && N1C->isNullValue())
3217     return N0;
3218   // if (srl x, c) is known to be zero, return 0
3219   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3220                                    APInt::getAllOnesValue(OpSizeInBits)))
3221     return DAG.getConstant(0, VT);
3222
3223   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3224   if (N1C && N0.getOpcode() == ISD::SRL &&
3225       N0.getOperand(1).getOpcode() == ISD::Constant) {
3226     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3227     uint64_t c2 = N1C->getZExtValue();
3228     if (c1 + c2 >= OpSizeInBits)
3229       return DAG.getConstant(0, VT);
3230     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3231                        DAG.getConstant(c1 + c2, N1.getValueType()));
3232   }
3233
3234   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3235   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3236       N0.getOperand(0).getOpcode() == ISD::SRL &&
3237       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3238     uint64_t c1 = 
3239       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3240     uint64_t c2 = N1C->getZExtValue();
3241     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3242     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3243     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3244     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3245     if (c1 + OpSizeInBits == InnerShiftSize) {
3246       if (c1 + c2 >= InnerShiftSize)
3247         return DAG.getConstant(0, VT);
3248       return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3249                          DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT, 
3250                                      N0.getOperand(0)->getOperand(0),
3251                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3252     }
3253   }
3254
3255   // fold (srl (shl x, c), c) -> (and x, cst2)
3256   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3257       N0.getValueSizeInBits() <= 64) {
3258     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3259     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3260                        DAG.getConstant(~0ULL >> ShAmt, VT));
3261   }
3262
3263
3264   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3265   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3266     // Shifting in all undef bits?
3267     EVT SmallVT = N0.getOperand(0).getValueType();
3268     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3269       return DAG.getUNDEF(VT);
3270
3271     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3272       SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3273                                        N0.getOperand(0), N1);
3274       AddToWorkList(SmallShift.getNode());
3275       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3276     }
3277   }
3278
3279   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3280   // bit, which is unmodified by sra.
3281   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3282     if (N0.getOpcode() == ISD::SRA)
3283       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3284   }
3285
3286   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3287   if (N1C && N0.getOpcode() == ISD::CTLZ &&
3288       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3289     APInt KnownZero, KnownOne;
3290     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3291     DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3292
3293     // If any of the input bits are KnownOne, then the input couldn't be all
3294     // zeros, thus the result of the srl will always be zero.
3295     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3296
3297     // If all of the bits input the to ctlz node are known to be zero, then
3298     // the result of the ctlz is "32" and the result of the shift is one.
3299     APInt UnknownBits = ~KnownZero & Mask;
3300     if (UnknownBits == 0) return DAG.getConstant(1, VT);
3301
3302     // Otherwise, check to see if there is exactly one bit input to the ctlz.
3303     if ((UnknownBits & (UnknownBits - 1)) == 0) {
3304       // Okay, we know that only that the single bit specified by UnknownBits
3305       // could be set on input to the CTLZ node. If this bit is set, the SRL
3306       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3307       // to an SRL/XOR pair, which is likely to simplify more.
3308       unsigned ShAmt = UnknownBits.countTrailingZeros();
3309       SDValue Op = N0.getOperand(0);
3310
3311       if (ShAmt) {
3312         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3313                          DAG.getConstant(ShAmt, getShiftAmountTy()));
3314         AddToWorkList(Op.getNode());
3315       }
3316
3317       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3318                          Op, DAG.getConstant(1, VT));
3319     }
3320   }
3321
3322   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3323   if (N1.getOpcode() == ISD::TRUNCATE &&
3324       N1.getOperand(0).getOpcode() == ISD::AND &&
3325       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3326     SDValue N101 = N1.getOperand(0).getOperand(1);
3327     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3328       EVT TruncVT = N1.getValueType();
3329       SDValue N100 = N1.getOperand(0).getOperand(0);
3330       APInt TruncC = N101C->getAPIntValue();
3331       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3332       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3333                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3334                                      TruncVT,
3335                                      DAG.getNode(ISD::TRUNCATE,
3336                                                  N->getDebugLoc(),
3337                                                  TruncVT, N100),
3338                                      DAG.getConstant(TruncC, TruncVT)));
3339     }
3340   }
3341
3342   // fold operands of srl based on knowledge that the low bits are not
3343   // demanded.
3344   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3345     return SDValue(N, 0);
3346
3347   if (N1C) {
3348     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3349     if (NewSRL.getNode())
3350       return NewSRL;
3351   }
3352
3353   // Attempt to convert a srl of a load into a narrower zero-extending load.
3354   SDValue NarrowLoad = ReduceLoadWidth(N);
3355   if (NarrowLoad.getNode())
3356     return NarrowLoad;
3357
3358   // Here is a common situation. We want to optimize:
3359   //
3360   //   %a = ...
3361   //   %b = and i32 %a, 2
3362   //   %c = srl i32 %b, 1
3363   //   brcond i32 %c ...
3364   //
3365   // into
3366   //
3367   //   %a = ...
3368   //   %b = and %a, 2
3369   //   %c = setcc eq %b, 0
3370   //   brcond %c ...
3371   //
3372   // However when after the source operand of SRL is optimized into AND, the SRL
3373   // itself may not be optimized further. Look for it and add the BRCOND into
3374   // the worklist.
3375   if (N->hasOneUse()) {
3376     SDNode *Use = *N->use_begin();
3377     if (Use->getOpcode() == ISD::BRCOND)
3378       AddToWorkList(Use);
3379     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3380       // Also look pass the truncate.
3381       Use = *Use->use_begin();
3382       if (Use->getOpcode() == ISD::BRCOND)
3383         AddToWorkList(Use);
3384     }
3385   }
3386
3387   return SDValue();
3388 }
3389
3390 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3391   SDValue N0 = N->getOperand(0);
3392   EVT VT = N->getValueType(0);
3393
3394   // fold (ctlz c1) -> c2
3395   if (isa<ConstantSDNode>(N0))
3396     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3397   return SDValue();
3398 }
3399
3400 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3401   SDValue N0 = N->getOperand(0);
3402   EVT VT = N->getValueType(0);
3403
3404   // fold (cttz c1) -> c2
3405   if (isa<ConstantSDNode>(N0))
3406     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3407   return SDValue();
3408 }
3409
3410 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3411   SDValue N0 = N->getOperand(0);
3412   EVT VT = N->getValueType(0);
3413
3414   // fold (ctpop c1) -> c2
3415   if (isa<ConstantSDNode>(N0))
3416     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3417   return SDValue();
3418 }
3419
3420 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3421   SDValue N0 = N->getOperand(0);
3422   SDValue N1 = N->getOperand(1);
3423   SDValue N2 = N->getOperand(2);
3424   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3425   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3426   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3427   EVT VT = N->getValueType(0);
3428   EVT VT0 = N0.getValueType();
3429
3430   // fold (select C, X, X) -> X
3431   if (N1 == N2)
3432     return N1;
3433   // fold (select true, X, Y) -> X
3434   if (N0C && !N0C->isNullValue())
3435     return N1;
3436   // fold (select false, X, Y) -> Y
3437   if (N0C && N0C->isNullValue())
3438     return N2;
3439   // fold (select C, 1, X) -> (or C, X)
3440   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3441     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3442   // fold (select C, 0, 1) -> (xor C, 1)
3443   if (VT.isInteger() &&
3444       (VT0 == MVT::i1 ||
3445        (VT0.isInteger() &&
3446         TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3447       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3448     SDValue XORNode;
3449     if (VT == VT0)
3450       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3451                          N0, DAG.getConstant(1, VT0));
3452     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3453                           N0, DAG.getConstant(1, VT0));
3454     AddToWorkList(XORNode.getNode());
3455     if (VT.bitsGT(VT0))
3456       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3457     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3458   }
3459   // fold (select C, 0, X) -> (and (not C), X)
3460   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3461     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3462     AddToWorkList(NOTNode.getNode());
3463     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3464   }
3465   // fold (select C, X, 1) -> (or (not C), X)
3466   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3467     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3468     AddToWorkList(NOTNode.getNode());
3469     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3470   }
3471   // fold (select C, X, 0) -> (and C, X)
3472   if (VT == MVT::i1 && N2C && N2C->isNullValue())
3473     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3474   // fold (select X, X, Y) -> (or X, Y)
3475   // fold (select X, 1, Y) -> (or X, Y)
3476   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3477     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3478   // fold (select X, Y, X) -> (and X, Y)
3479   // fold (select X, Y, 0) -> (and X, Y)
3480   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3481     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3482
3483   // If we can fold this based on the true/false value, do so.
3484   if (SimplifySelectOps(N, N1, N2))
3485     return SDValue(N, 0);  // Don't revisit N.
3486
3487   // fold selects based on a setcc into other things, such as min/max/abs
3488   if (N0.getOpcode() == ISD::SETCC) {
3489     // FIXME:
3490     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3491     // having to say they don't support SELECT_CC on every type the DAG knows
3492     // about, since there is no way to mark an opcode illegal at all value types
3493     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3494         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3495       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3496                          N0.getOperand(0), N0.getOperand(1),
3497                          N1, N2, N0.getOperand(2));
3498     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3499   }
3500
3501   return SDValue();
3502 }
3503
3504 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3505   SDValue N0 = N->getOperand(0);
3506   SDValue N1 = N->getOperand(1);
3507   SDValue N2 = N->getOperand(2);
3508   SDValue N3 = N->getOperand(3);
3509   SDValue N4 = N->getOperand(4);
3510   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3511
3512   // fold select_cc lhs, rhs, x, x, cc -> x
3513   if (N2 == N3)
3514     return N2;
3515
3516   // Determine if the condition we're dealing with is constant
3517   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3518                               N0, N1, CC, N->getDebugLoc(), false);
3519   if (SCC.getNode()) AddToWorkList(SCC.getNode());
3520
3521   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3522     if (!SCCC->isNullValue())
3523       return N2;    // cond always true -> true val
3524     else
3525       return N3;    // cond always false -> false val
3526   }
3527
3528   // Fold to a simpler select_cc
3529   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3530     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3531                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3532                        SCC.getOperand(2));
3533
3534   // If we can fold this based on the true/false value, do so.
3535   if (SimplifySelectOps(N, N2, N3))
3536     return SDValue(N, 0);  // Don't revisit N.
3537
3538   // fold select_cc into other things, such as min/max/abs
3539   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3540 }
3541
3542 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3543   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3544                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
3545                        N->getDebugLoc());
3546 }
3547
3548 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3549 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3550 // transformation. Returns true if extension are possible and the above
3551 // mentioned transformation is profitable.
3552 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3553                                     unsigned ExtOpc,
3554                                     SmallVector<SDNode*, 4> &ExtendNodes,
3555                                     const TargetLowering &TLI) {
3556   bool HasCopyToRegUses = false;
3557   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3558   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3559                             UE = N0.getNode()->use_end();
3560        UI != UE; ++UI) {
3561     SDNode *User = *UI;
3562     if (User == N)
3563       continue;
3564     if (UI.getUse().getResNo() != N0.getResNo())
3565       continue;
3566     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3567     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3568       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3569       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3570         // Sign bits will be lost after a zext.
3571         return false;
3572       bool Add = false;
3573       for (unsigned i = 0; i != 2; ++i) {
3574         SDValue UseOp = User->getOperand(i);
3575         if (UseOp == N0)
3576           continue;
3577         if (!isa<ConstantSDNode>(UseOp))
3578           return false;
3579         Add = true;
3580       }
3581       if (Add)
3582         ExtendNodes.push_back(User);
3583       continue;
3584     }
3585     // If truncates aren't free and there are users we can't
3586     // extend, it isn't worthwhile.
3587     if (!isTruncFree)
3588       return false;
3589     // Remember if this value is live-out.
3590     if (User->getOpcode() == ISD::CopyToReg)
3591       HasCopyToRegUses = true;
3592   }
3593
3594   if (HasCopyToRegUses) {
3595     bool BothLiveOut = false;
3596     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3597          UI != UE; ++UI) {
3598       SDUse &Use = UI.getUse();
3599       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3600         BothLiveOut = true;
3601         break;
3602       }
3603     }
3604     if (BothLiveOut)
3605       // Both unextended and extended values are live out. There had better be
3606       // a good reason for the transformation.
3607       return ExtendNodes.size();
3608   }
3609   return true;
3610 }
3611
3612 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3613   SDValue N0 = N->getOperand(0);
3614   EVT VT = N->getValueType(0);
3615
3616   // fold (sext c1) -> c1
3617   if (isa<ConstantSDNode>(N0))
3618     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3619
3620   // fold (sext (sext x)) -> (sext x)
3621   // fold (sext (aext x)) -> (sext x)
3622   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3623     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3624                        N0.getOperand(0));
3625
3626   if (N0.getOpcode() == ISD::TRUNCATE) {
3627     // fold (sext (truncate (load x))) -> (sext (smaller load x))
3628     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3629     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3630     if (NarrowLoad.getNode()) {
3631       SDNode* oye = N0.getNode()->getOperand(0).getNode();
3632       if (NarrowLoad.getNode() != N0.getNode()) {
3633         CombineTo(N0.getNode(), NarrowLoad);
3634         // CombineTo deleted the truncate, if needed, but not what's under it.
3635         AddToWorkList(oye);
3636       }
3637       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3638     }
3639
3640     // See if the value being truncated is already sign extended.  If so, just
3641     // eliminate the trunc/sext pair.
3642     SDValue Op = N0.getOperand(0);
3643     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
3644     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
3645     unsigned DestBits = VT.getScalarType().getSizeInBits();
3646     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3647
3648     if (OpBits == DestBits) {
3649       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
3650       // bits, it is already ready.
3651       if (NumSignBits > DestBits-MidBits)
3652         return Op;
3653     } else if (OpBits < DestBits) {
3654       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
3655       // bits, just sext from i32.
3656       if (NumSignBits > OpBits-MidBits)
3657         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3658     } else {
3659       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
3660       // bits, just truncate to i32.
3661       if (NumSignBits > OpBits-MidBits)
3662         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3663     }
3664
3665     // fold (sext (truncate x)) -> (sextinreg x).
3666     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3667                                                  N0.getValueType())) {
3668       if (OpBits < DestBits)
3669         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3670       else if (OpBits > DestBits)
3671         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3672       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3673                          DAG.getValueType(N0.getValueType()));
3674     }
3675   }
3676
3677   // fold (sext (load x)) -> (sext (truncate (sextload x)))
3678   if (ISD::isNON_EXTLoad(N0.getNode()) &&
3679       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3680        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3681     bool DoXform = true;
3682     SmallVector<SDNode*, 4> SetCCs;
3683     if (!N0.hasOneUse())
3684       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3685     if (DoXform) {
3686       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3687       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
3688                                        LN0->getChain(),
3689                                        LN0->getBasePtr(), LN0->getPointerInfo(),
3690                                        N0.getValueType(),
3691                                        LN0->isVolatile(), LN0->isNonTemporal(),
3692                                        LN0->getAlignment());
3693       CombineTo(N, ExtLoad);
3694       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3695                                   N0.getValueType(), ExtLoad);
3696       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3697
3698       // Extend SetCC uses if necessary.
3699       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3700         SDNode *SetCC = SetCCs[i];
3701         SmallVector<SDValue, 4> Ops;
3702
3703         for (unsigned j = 0; j != 2; ++j) {
3704           SDValue SOp = SetCC->getOperand(j);
3705           if (SOp == Trunc)
3706             Ops.push_back(ExtLoad);
3707           else
3708             Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3709                                       N->getDebugLoc(), VT, SOp));
3710         }
3711
3712         Ops.push_back(SetCC->getOperand(2));
3713         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3714                                      SetCC->getValueType(0),
3715                                      &Ops[0], Ops.size()));
3716       }
3717
3718       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3719     }
3720   }
3721
3722   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3723   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3724   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3725       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3726     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3727     EVT MemVT = LN0->getMemoryVT();
3728     if ((!LegalOperations && !LN0->isVolatile()) ||
3729         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3730       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
3731                                        LN0->getChain(),
3732                                        LN0->getBasePtr(), LN0->getPointerInfo(),
3733                                        MemVT,
3734                                        LN0->isVolatile(), LN0->isNonTemporal(),
3735                                        LN0->getAlignment());
3736       CombineTo(N, ExtLoad);
3737       CombineTo(N0.getNode(),
3738                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3739                             N0.getValueType(), ExtLoad),
3740                 ExtLoad.getValue(1));
3741       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3742     }
3743   }
3744
3745   if (N0.getOpcode() == ISD::SETCC) {
3746     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3747     // Only do this before legalize for now.
3748     if (VT.isVector() && !LegalOperations) {
3749       EVT N0VT = N0.getOperand(0).getValueType();
3750         // We know that the # elements of the results is the same as the
3751         // # elements of the compare (and the # elements of the compare result
3752         // for that matter).  Check to see that they are the same size.  If so,
3753         // we know that the element size of the sext'd result matches the
3754         // element size of the compare operands.
3755       if (VT.getSizeInBits() == N0VT.getSizeInBits())
3756         return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3757                              N0.getOperand(1),
3758                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
3759       // If the desired elements are smaller or larger than the source
3760       // elements we can use a matching integer vector type and then
3761       // truncate/sign extend
3762       else {
3763         EVT MatchingElementType =
3764           EVT::getIntegerVT(*DAG.getContext(),
3765                             N0VT.getScalarType().getSizeInBits());
3766         EVT MatchingVectorType =
3767           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3768                            N0VT.getVectorNumElements());
3769         SDValue VsetCC =
3770           DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3771                         N0.getOperand(1),
3772                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
3773         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
3774       }
3775     }
3776
3777     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3778     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3779     SDValue NegOne =
3780       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3781     SDValue SCC =
3782       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3783                        NegOne, DAG.getConstant(0, VT),
3784                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3785     if (SCC.getNode()) return SCC;
3786     if (!LegalOperations ||
3787         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3788       return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3789                          DAG.getSetCC(N->getDebugLoc(),
3790                                       TLI.getSetCCResultType(VT),
3791                                       N0.getOperand(0), N0.getOperand(1),
3792                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3793                          NegOne, DAG.getConstant(0, VT));
3794   }
3795
3796   // fold (sext x) -> (zext x) if the sign bit is known zero.
3797   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3798       DAG.SignBitIsZero(N0))
3799     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3800
3801   return SDValue();
3802 }
3803
3804 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3805   SDValue N0 = N->getOperand(0);
3806   EVT VT = N->getValueType(0);
3807
3808   // fold (zext c1) -> c1
3809   if (isa<ConstantSDNode>(N0))
3810     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3811   // fold (zext (zext x)) -> (zext x)
3812   // fold (zext (aext x)) -> (zext x)
3813   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3814     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3815                        N0.getOperand(0));
3816
3817   // fold (zext (truncate (load x))) -> (zext (smaller load x))
3818   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3819   if (N0.getOpcode() == ISD::TRUNCATE) {
3820     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3821     if (NarrowLoad.getNode()) {
3822       SDNode* oye = N0.getNode()->getOperand(0).getNode();
3823       if (NarrowLoad.getNode() != N0.getNode()) {
3824         CombineTo(N0.getNode(), NarrowLoad);
3825         // CombineTo deleted the truncate, if needed, but not what's under it.
3826         AddToWorkList(oye);
3827       }
3828       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3829     }
3830   }
3831
3832   // fold (zext (truncate x)) -> (and x, mask)
3833   if (N0.getOpcode() == ISD::TRUNCATE &&
3834       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3835
3836     // fold (zext (truncate (load x))) -> (zext (smaller load x))
3837     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
3838     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3839     if (NarrowLoad.getNode()) {
3840       SDNode* oye = N0.getNode()->getOperand(0).getNode();
3841       if (NarrowLoad.getNode() != N0.getNode()) {
3842         CombineTo(N0.getNode(), NarrowLoad);
3843         // CombineTo deleted the truncate, if needed, but not what's under it.
3844         AddToWorkList(oye);
3845       }
3846       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3847     }
3848
3849     SDValue Op = N0.getOperand(0);
3850     if (Op.getValueType().bitsLT(VT)) {
3851       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3852     } else if (Op.getValueType().bitsGT(VT)) {
3853       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3854     }
3855     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3856                                   N0.getValueType().getScalarType());
3857   }
3858
3859   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3860   // if either of the casts is not free.
3861   if (N0.getOpcode() == ISD::AND &&
3862       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3863       N0.getOperand(1).getOpcode() == ISD::Constant &&
3864       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3865                            N0.getValueType()) ||
3866        !TLI.isZExtFree(N0.getValueType(), VT))) {
3867     SDValue X = N0.getOperand(0).getOperand(0);
3868     if (X.getValueType().bitsLT(VT)) {
3869       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3870     } else if (X.getValueType().bitsGT(VT)) {
3871       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3872     }
3873     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3874     Mask = Mask.zext(VT.getSizeInBits());
3875     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3876                        X, DAG.getConstant(Mask, VT));
3877   }
3878
3879   // fold (zext (load x)) -> (zext (truncate (zextload x)))
3880   if (ISD::isNON_EXTLoad(N0.getNode()) &&
3881       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3882        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3883     bool DoXform = true;
3884     SmallVector<SDNode*, 4> SetCCs;
3885     if (!N0.hasOneUse())
3886       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3887     if (DoXform) {
3888       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3889       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N->getDebugLoc(),
3890                                        LN0->getChain(),
3891                                        LN0->getBasePtr(), LN0->getPointerInfo(),
3892                                        N0.getValueType(),
3893                                        LN0->isVolatile(), LN0->isNonTemporal(),
3894                                        LN0->getAlignment());
3895       CombineTo(N, ExtLoad);
3896       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3897                                   N0.getValueType(), ExtLoad);
3898       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3899
3900       // Extend SetCC uses if necessary.
3901       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3902         SDNode *SetCC = SetCCs[i];
3903         SmallVector<SDValue, 4> Ops;
3904
3905         for (unsigned j = 0; j != 2; ++j) {
3906           SDValue SOp = SetCC->getOperand(j);
3907           if (SOp == Trunc)
3908             Ops.push_back(ExtLoad);
3909           else
3910             Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3911                                       N->getDebugLoc(), VT, SOp));
3912         }
3913
3914         Ops.push_back(SetCC->getOperand(2));
3915         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3916                                      SetCC->getValueType(0),
3917                                      &Ops[0], Ops.size()));
3918       }
3919
3920       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3921     }
3922   }
3923
3924   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3925   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3926   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3927       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3928     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3929     EVT MemVT = LN0->getMemoryVT();
3930     if ((!LegalOperations && !LN0->isVolatile()) ||
3931         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3932       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N->getDebugLoc(),
3933                                        LN0->getChain(),
3934                                        LN0->getBasePtr(), LN0->getPointerInfo(),
3935                                        MemVT,
3936                                        LN0->isVolatile(), LN0->isNonTemporal(),
3937                                        LN0->getAlignment());
3938       CombineTo(N, ExtLoad);
3939       CombineTo(N0.getNode(),
3940                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3941                             ExtLoad),
3942                 ExtLoad.getValue(1));
3943       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3944     }
3945   }
3946
3947   if (N0.getOpcode() == ISD::SETCC) {
3948     if (!LegalOperations && VT.isVector()) {
3949       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
3950       // Only do this before legalize for now.
3951       EVT N0VT = N0.getOperand(0).getValueType();
3952       EVT EltVT = VT.getVectorElementType();
3953       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
3954                                     DAG.getConstant(1, EltVT));
3955       if (VT.getSizeInBits() == N0VT.getSizeInBits()) {
3956         // We know that the # elements of the results is the same as the
3957         // # elements of the compare (and the # elements of the compare result
3958         // for that matter).  Check to see that they are the same size.  If so,
3959         // we know that the element size of the sext'd result matches the
3960         // element size of the compare operands.
3961         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3962                            DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3963                                          N0.getOperand(1),
3964                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3965                            DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
3966                                        &OneOps[0], OneOps.size()));
3967       } else {
3968         // If the desired elements are smaller or larger than the source
3969         // elements we can use a matching integer vector type and then
3970         // truncate/sign extend
3971         EVT MatchingElementType =
3972           EVT::getIntegerVT(*DAG.getContext(),
3973                             N0VT.getScalarType().getSizeInBits());
3974         EVT MatchingVectorType =
3975           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3976                            N0VT.getVectorNumElements());
3977         SDValue VsetCC =
3978           DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3979                         N0.getOperand(1),
3980                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
3981         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3982                            DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
3983                            DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
3984                                        &OneOps[0], OneOps.size()));
3985       }
3986     }
3987
3988     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3989     SDValue SCC =
3990       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3991                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3992                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3993     if (SCC.getNode()) return SCC;
3994   }
3995
3996   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3997   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3998       isa<ConstantSDNode>(N0.getOperand(1)) &&
3999       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4000       N0.hasOneUse()) {
4001     if (N0.getOpcode() == ISD::SHL) {
4002       // If the original shl may be shifting out bits, do not perform this
4003       // transformation.
4004       unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4005       unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
4006         N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
4007       if (ShAmt > KnownZeroBits)
4008         return SDValue();
4009     }
4010     DebugLoc dl = N->getDebugLoc();
4011     return DAG.getNode(N0.getOpcode(), dl, VT,
4012                        DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
4013                        DAG.getNode(ISD::ZERO_EXTEND, dl,
4014                                    N0.getOperand(1).getValueType(),
4015                                    N0.getOperand(1)));
4016   }
4017
4018   return SDValue();
4019 }
4020
4021 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4022   SDValue N0 = N->getOperand(0);
4023   EVT VT = N->getValueType(0);
4024
4025   // fold (aext c1) -> c1
4026   if (isa<ConstantSDNode>(N0))
4027     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4028   // fold (aext (aext x)) -> (aext x)
4029   // fold (aext (zext x)) -> (zext x)
4030   // fold (aext (sext x)) -> (sext x)
4031   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4032       N0.getOpcode() == ISD::ZERO_EXTEND ||
4033       N0.getOpcode() == ISD::SIGN_EXTEND)
4034     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4035
4036   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4037   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4038   if (N0.getOpcode() == ISD::TRUNCATE) {
4039     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4040     if (NarrowLoad.getNode()) {
4041       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4042       if (NarrowLoad.getNode() != N0.getNode()) {
4043         CombineTo(N0.getNode(), NarrowLoad);
4044         // CombineTo deleted the truncate, if needed, but not what's under it.
4045         AddToWorkList(oye);
4046       }
4047       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
4048     }
4049   }
4050
4051   // fold (aext (truncate x))
4052   if (N0.getOpcode() == ISD::TRUNCATE) {
4053     SDValue TruncOp = N0.getOperand(0);
4054     if (TruncOp.getValueType() == VT)
4055       return TruncOp; // x iff x size == zext size.
4056     if (TruncOp.getValueType().bitsGT(VT))
4057       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4058     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4059   }
4060
4061   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4062   // if the trunc is not free.
4063   if (N0.getOpcode() == ISD::AND &&
4064       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4065       N0.getOperand(1).getOpcode() == ISD::Constant &&
4066       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4067                           N0.getValueType())) {
4068     SDValue X = N0.getOperand(0).getOperand(0);
4069     if (X.getValueType().bitsLT(VT)) {
4070       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4071     } else if (X.getValueType().bitsGT(VT)) {
4072       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4073     }
4074     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4075     Mask = Mask.zext(VT.getSizeInBits());
4076     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4077                        X, DAG.getConstant(Mask, VT));
4078   }
4079
4080   // fold (aext (load x)) -> (aext (truncate (extload x)))
4081   if (ISD::isNON_EXTLoad(N0.getNode()) &&
4082       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4083        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4084     bool DoXform = true;
4085     SmallVector<SDNode*, 4> SetCCs;
4086     if (!N0.hasOneUse())
4087       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4088     if (DoXform) {
4089       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4090       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
4091                                        LN0->getChain(),
4092                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4093                                        N0.getValueType(),
4094                                        LN0->isVolatile(), LN0->isNonTemporal(),
4095                                        LN0->getAlignment());
4096       CombineTo(N, ExtLoad);
4097       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4098                                   N0.getValueType(), ExtLoad);
4099       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4100
4101       // Extend SetCC uses if necessary.
4102       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4103         SDNode *SetCC = SetCCs[i];
4104         SmallVector<SDValue, 4> Ops;
4105
4106         for (unsigned j = 0; j != 2; ++j) {
4107           SDValue SOp = SetCC->getOperand(j);
4108           if (SOp == Trunc)
4109             Ops.push_back(ExtLoad);
4110           else
4111             Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
4112                                       N->getDebugLoc(), VT, SOp));
4113         }
4114
4115         Ops.push_back(SetCC->getOperand(2));
4116         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
4117                                      SetCC->getValueType(0),
4118                                      &Ops[0], Ops.size()));
4119       }
4120
4121       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4122     }
4123   }
4124
4125   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4126   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4127   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4128   if (N0.getOpcode() == ISD::LOAD &&
4129       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4130       N0.hasOneUse()) {
4131     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4132     EVT MemVT = LN0->getMemoryVT();
4133     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
4134                                      N->getDebugLoc(),
4135                                      LN0->getChain(), LN0->getBasePtr(),
4136                                      LN0->getPointerInfo(), MemVT,
4137                                      LN0->isVolatile(), LN0->isNonTemporal(),
4138                                      LN0->getAlignment());
4139     CombineTo(N, ExtLoad);
4140     CombineTo(N0.getNode(),
4141               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4142                           N0.getValueType(), ExtLoad),
4143               ExtLoad.getValue(1));
4144     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4145   }
4146
4147   if (N0.getOpcode() == ISD::SETCC) {
4148     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4149     // Only do this before legalize for now.
4150     if (VT.isVector() && !LegalOperations) {
4151       EVT N0VT = N0.getOperand(0).getValueType();
4152         // We know that the # elements of the results is the same as the
4153         // # elements of the compare (and the # elements of the compare result
4154         // for that matter).  Check to see that they are the same size.  If so,
4155         // we know that the element size of the sext'd result matches the
4156         // element size of the compare operands.
4157       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4158         return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4159                              N0.getOperand(1),
4160                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4161       // If the desired elements are smaller or larger than the source
4162       // elements we can use a matching integer vector type and then
4163       // truncate/sign extend
4164       else {
4165         EVT MatchingElementType =
4166           EVT::getIntegerVT(*DAG.getContext(),
4167                             N0VT.getScalarType().getSizeInBits());
4168         EVT MatchingVectorType =
4169           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4170                            N0VT.getVectorNumElements());
4171         SDValue VsetCC =
4172           DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4173                         N0.getOperand(1),
4174                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
4175         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4176       }
4177     }
4178
4179     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4180     SDValue SCC =
4181       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4182                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4183                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4184     if (SCC.getNode())
4185       return SCC;
4186   }
4187
4188   return SDValue();
4189 }
4190
4191 /// GetDemandedBits - See if the specified operand can be simplified with the
4192 /// knowledge that only the bits specified by Mask are used.  If so, return the
4193 /// simpler operand, otherwise return a null SDValue.
4194 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4195   switch (V.getOpcode()) {
4196   default: break;
4197   case ISD::OR:
4198   case ISD::XOR:
4199     // If the LHS or RHS don't contribute bits to the or, drop them.
4200     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4201       return V.getOperand(1);
4202     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4203       return V.getOperand(0);
4204     break;
4205   case ISD::SRL:
4206     // Only look at single-use SRLs.
4207     if (!V.getNode()->hasOneUse())
4208       break;
4209     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4210       // See if we can recursively simplify the LHS.
4211       unsigned Amt = RHSC->getZExtValue();
4212
4213       // Watch out for shift count overflow though.
4214       if (Amt >= Mask.getBitWidth()) break;
4215       APInt NewMask = Mask << Amt;
4216       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4217       if (SimplifyLHS.getNode())
4218         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4219                            SimplifyLHS, V.getOperand(1));
4220     }
4221   }
4222   return SDValue();
4223 }
4224
4225 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4226 /// bits and then truncated to a narrower type and where N is a multiple
4227 /// of number of bits of the narrower type, transform it to a narrower load
4228 /// from address + N / num of bits of new type. If the result is to be
4229 /// extended, also fold the extension to form a extending load.
4230 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4231   unsigned Opc = N->getOpcode();
4232
4233   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4234   SDValue N0 = N->getOperand(0);
4235   EVT VT = N->getValueType(0);
4236   EVT ExtVT = VT;
4237
4238   // This transformation isn't valid for vector loads.
4239   if (VT.isVector())
4240     return SDValue();
4241
4242   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4243   // extended to VT.
4244   if (Opc == ISD::SIGN_EXTEND_INREG) {
4245     ExtType = ISD::SEXTLOAD;
4246     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4247     if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
4248       return SDValue();
4249   } else if (Opc == ISD::SRL) {
4250     // Another special-case: SRL is basically zero-extending a narrower value.
4251     ExtType = ISD::ZEXTLOAD;
4252     N0 = SDValue(N, 0);
4253     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4254     if (!N01) return SDValue();
4255     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4256                               VT.getSizeInBits() - N01->getZExtValue());
4257   }
4258
4259   unsigned EVTBits = ExtVT.getSizeInBits();
4260   
4261   // Do not generate loads of non-round integer types since these can
4262   // be expensive (and would be wrong if the type is not byte sized).
4263   if (!ExtVT.isRound())
4264     return SDValue();
4265   
4266   unsigned ShAmt = 0;
4267   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4268     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4269       ShAmt = N01->getZExtValue();
4270       // Is the shift amount a multiple of size of VT?
4271       if ((ShAmt & (EVTBits-1)) == 0) {
4272         N0 = N0.getOperand(0);
4273         // Is the load width a multiple of size of VT?
4274         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4275           return SDValue();
4276       }
4277
4278       // At this point, we must have a load or else we can't do the transform.
4279       if (!isa<LoadSDNode>(N0)) return SDValue();
4280       
4281       // If the shift amount is larger than the input type then we're not
4282       // accessing any of the loaded bytes.  If the load was a zextload/extload
4283       // then the result of the shift+trunc is zero/undef (handled elsewhere).
4284       // If the load was a sextload then the result is a splat of the sign bit
4285       // of the extended byte.  This is not worth optimizing for.
4286       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4287         return SDValue();
4288     }
4289   }
4290
4291   // If the load is shifted left (and the result isn't shifted back right),
4292   // we can fold the truncate through the shift.
4293   unsigned ShLeftAmt = 0;
4294   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4295       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4296     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4297       ShLeftAmt = N01->getZExtValue();
4298       N0 = N0.getOperand(0);
4299     }
4300   }
4301   
4302   // If we haven't found a load, we can't narrow it.  Don't transform one with
4303   // multiple uses, this would require adding a new load.
4304   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
4305       // Don't change the width of a volatile load.
4306       cast<LoadSDNode>(N0)->isVolatile())
4307     return SDValue();
4308   
4309   // Verify that we are actually reducing a load width here.
4310   if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
4311     return SDValue();
4312   
4313   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4314   EVT PtrType = N0.getOperand(1).getValueType();
4315
4316   // For big endian targets, we need to adjust the offset to the pointer to
4317   // load the correct bytes.
4318   if (TLI.isBigEndian()) {
4319     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4320     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4321     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4322   }
4323
4324   uint64_t PtrOff = ShAmt / 8;
4325   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4326   SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4327                                PtrType, LN0->getBasePtr(),
4328                                DAG.getConstant(PtrOff, PtrType));
4329   AddToWorkList(NewPtr.getNode());
4330
4331   SDValue Load;
4332   if (ExtType == ISD::NON_EXTLOAD)
4333     Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4334                         LN0->getPointerInfo().getWithOffset(PtrOff),
4335                         LN0->isVolatile(), LN0->isNonTemporal(), NewAlign);
4336   else
4337     Load = DAG.getExtLoad(ExtType, VT, N0.getDebugLoc(), LN0->getChain(),NewPtr,
4338                           LN0->getPointerInfo().getWithOffset(PtrOff),
4339                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4340                           NewAlign);
4341
4342   // Replace the old load's chain with the new load's chain.
4343   WorkListRemover DeadNodes(*this);
4344   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4345                                 &DeadNodes);
4346
4347   // Shift the result left, if we've swallowed a left shift.
4348   SDValue Result = Load;
4349   if (ShLeftAmt != 0) {
4350     EVT ShImmTy = getShiftAmountTy();
4351     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4352       ShImmTy = VT;
4353     Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4354                          Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4355   }
4356
4357   // Return the new loaded value.
4358   return Result;
4359 }
4360
4361 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4362   SDValue N0 = N->getOperand(0);
4363   SDValue N1 = N->getOperand(1);
4364   EVT VT = N->getValueType(0);
4365   EVT EVT = cast<VTSDNode>(N1)->getVT();
4366   unsigned VTBits = VT.getScalarType().getSizeInBits();
4367   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4368
4369   // fold (sext_in_reg c1) -> c1
4370   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4371     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4372
4373   // If the input is already sign extended, just drop the extension.
4374   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4375     return N0;
4376
4377   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4378   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4379       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4380     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4381                        N0.getOperand(0), N1);
4382   }
4383
4384   // fold (sext_in_reg (sext x)) -> (sext x)
4385   // fold (sext_in_reg (aext x)) -> (sext x)
4386   // if x is small enough.
4387   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4388     SDValue N00 = N0.getOperand(0);
4389     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4390         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4391       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4392   }
4393
4394   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4395   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4396     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4397
4398   // fold operands of sext_in_reg based on knowledge that the top bits are not
4399   // demanded.
4400   if (SimplifyDemandedBits(SDValue(N, 0)))
4401     return SDValue(N, 0);
4402
4403   // fold (sext_in_reg (load x)) -> (smaller sextload x)
4404   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4405   SDValue NarrowLoad = ReduceLoadWidth(N);
4406   if (NarrowLoad.getNode())
4407     return NarrowLoad;
4408
4409   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4410   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4411   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4412   if (N0.getOpcode() == ISD::SRL) {
4413     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4414       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4415         // We can turn this into an SRA iff the input to the SRL is already sign
4416         // extended enough.
4417         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4418         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4419           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4420                              N0.getOperand(0), N0.getOperand(1));
4421       }
4422   }
4423
4424   // fold (sext_inreg (extload x)) -> (sextload x)
4425   if (ISD::isEXTLoad(N0.getNode()) &&
4426       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4427       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4428       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4429        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4430     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4431     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4432                                      LN0->getChain(),
4433                                      LN0->getBasePtr(), LN0->getPointerInfo(),
4434                                      EVT,
4435                                      LN0->isVolatile(), LN0->isNonTemporal(),
4436                                      LN0->getAlignment());
4437     CombineTo(N, ExtLoad);
4438     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4439     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4440   }
4441   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4442   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4443       N0.hasOneUse() &&
4444       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4445       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4446        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4447     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4448     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4449                                      LN0->getChain(),
4450                                      LN0->getBasePtr(), LN0->getPointerInfo(),
4451                                      EVT,
4452                                      LN0->isVolatile(), LN0->isNonTemporal(),
4453                                      LN0->getAlignment());
4454     CombineTo(N, ExtLoad);
4455     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4456     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4457   }
4458   return SDValue();
4459 }
4460
4461 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4462   SDValue N0 = N->getOperand(0);
4463   EVT VT = N->getValueType(0);
4464
4465   // noop truncate
4466   if (N0.getValueType() == N->getValueType(0))
4467     return N0;
4468   // fold (truncate c1) -> c1
4469   if (isa<ConstantSDNode>(N0))
4470     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4471   // fold (truncate (truncate x)) -> (truncate x)
4472   if (N0.getOpcode() == ISD::TRUNCATE)
4473     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4474   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4475   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4476       N0.getOpcode() == ISD::SIGN_EXTEND ||
4477       N0.getOpcode() == ISD::ANY_EXTEND) {
4478     if (N0.getOperand(0).getValueType().bitsLT(VT))
4479       // if the source is smaller than the dest, we still need an extend
4480       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4481                          N0.getOperand(0));
4482     else if (N0.getOperand(0).getValueType().bitsGT(VT))
4483       // if the source is larger than the dest, than we just need the truncate
4484       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4485     else
4486       // if the source and dest are the same type, we can drop both the extend
4487       // and the truncate.
4488       return N0.getOperand(0);
4489   }
4490
4491   // See if we can simplify the input to this truncate through knowledge that
4492   // only the low bits are being used.  For example "trunc (or (shl x, 8), y)"
4493   // -> trunc y
4494   SDValue Shorter =
4495     GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4496                                              VT.getSizeInBits()));
4497   if (Shorter.getNode())
4498     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4499
4500   // fold (truncate (load x)) -> (smaller load x)
4501   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4502   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4503     SDValue Reduced = ReduceLoadWidth(N);
4504     if (Reduced.getNode())
4505       return Reduced;
4506   }
4507
4508   // Simplify the operands using demanded-bits information.
4509   if (!VT.isVector() &&
4510       SimplifyDemandedBits(SDValue(N, 0)))
4511     return SDValue(N, 0);
4512
4513   return SDValue();
4514 }
4515
4516 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4517   SDValue Elt = N->getOperand(i);
4518   if (Elt.getOpcode() != ISD::MERGE_VALUES)
4519     return Elt.getNode();
4520   return Elt.getOperand(Elt.getResNo()).getNode();
4521 }
4522
4523 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4524 /// if load locations are consecutive.
4525 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4526   assert(N->getOpcode() == ISD::BUILD_PAIR);
4527
4528   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4529   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4530   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4531       LD1->getPointerInfo().getAddrSpace() !=
4532          LD2->getPointerInfo().getAddrSpace())
4533     return SDValue();
4534   EVT LD1VT = LD1->getValueType(0);
4535
4536   if (ISD::isNON_EXTLoad(LD2) &&
4537       LD2->hasOneUse() &&
4538       // If both are volatile this would reduce the number of volatile loads.
4539       // If one is volatile it might be ok, but play conservative and bail out.
4540       !LD1->isVolatile() &&
4541       !LD2->isVolatile() &&
4542       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4543     unsigned Align = LD1->getAlignment();
4544     unsigned NewAlign = TLI.getTargetData()->
4545       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4546
4547     if (NewAlign <= Align &&
4548         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4549       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4550                          LD1->getBasePtr(), LD1->getPointerInfo(),
4551                          false, false, Align);
4552   }
4553
4554   return SDValue();
4555 }
4556
4557 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
4558   SDValue N0 = N->getOperand(0);
4559   EVT VT = N->getValueType(0);
4560
4561   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4562   // Only do this before legalize, since afterward the target may be depending
4563   // on the bitconvert.
4564   // First check to see if this is all constant.
4565   if (!LegalTypes &&
4566       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4567       VT.isVector()) {
4568     bool isSimple = true;
4569     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4570       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4571           N0.getOperand(i).getOpcode() != ISD::Constant &&
4572           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4573         isSimple = false;
4574         break;
4575       }
4576
4577     EVT DestEltVT = N->getValueType(0).getVectorElementType();
4578     assert(!DestEltVT.isVector() &&
4579            "Element type of vector ValueType must not be vector!");
4580     if (isSimple)
4581       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4582   }
4583
4584   // If the input is a constant, let getNode fold it.
4585   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4586     SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
4587     if (Res.getNode() != N) {
4588       if (!LegalOperations ||
4589           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4590         return Res;
4591
4592       // Folding it resulted in an illegal node, and it's too late to
4593       // do that. Clean up the old node and forego the transformation.
4594       // Ideally this won't happen very often, because instcombine
4595       // and the earlier dagcombine runs (where illegal nodes are
4596       // permitted) should have folded most of them already.
4597       DAG.DeleteNode(Res.getNode());
4598     }
4599   }
4600
4601   // (conv (conv x, t1), t2) -> (conv x, t2)
4602   if (N0.getOpcode() == ISD::BITCAST)
4603     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
4604                        N0.getOperand(0));
4605
4606   // fold (conv (load x)) -> (load (conv*)x)
4607   // If the resultant load doesn't need a higher alignment than the original!
4608   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4609       // Do not change the width of a volatile load.
4610       !cast<LoadSDNode>(N0)->isVolatile() &&
4611       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4612     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4613     unsigned Align = TLI.getTargetData()->
4614       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4615     unsigned OrigAlign = LN0->getAlignment();
4616
4617     if (Align <= OrigAlign) {
4618       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4619                                  LN0->getBasePtr(), LN0->getPointerInfo(),
4620                                  LN0->isVolatile(), LN0->isNonTemporal(),
4621                                  OrigAlign);
4622       AddToWorkList(N);
4623       CombineTo(N0.getNode(),
4624                 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4625                             N0.getValueType(), Load),
4626                 Load.getValue(1));
4627       return Load;
4628     }
4629   }
4630
4631   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4632   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4633   // This often reduces constant pool loads.
4634   if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4635       N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4636     SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
4637                                   N0.getOperand(0));
4638     AddToWorkList(NewConv.getNode());
4639
4640     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4641     if (N0.getOpcode() == ISD::FNEG)
4642       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4643                          NewConv, DAG.getConstant(SignBit, VT));
4644     assert(N0.getOpcode() == ISD::FABS);
4645     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4646                        NewConv, DAG.getConstant(~SignBit, VT));
4647   }
4648
4649   // fold (bitconvert (fcopysign cst, x)) ->
4650   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
4651   // Note that we don't handle (copysign x, cst) because this can always be
4652   // folded to an fneg or fabs.
4653   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4654       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4655       VT.isInteger() && !VT.isVector()) {
4656     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4657     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4658     if (isTypeLegal(IntXVT)) {
4659       SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4660                               IntXVT, N0.getOperand(1));
4661       AddToWorkList(X.getNode());
4662
4663       // If X has a different width than the result/lhs, sext it or truncate it.
4664       unsigned VTWidth = VT.getSizeInBits();
4665       if (OrigXWidth < VTWidth) {
4666         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4667         AddToWorkList(X.getNode());
4668       } else if (OrigXWidth > VTWidth) {
4669         // To get the sign bit in the right place, we have to shift it right
4670         // before truncating.
4671         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4672                         X.getValueType(), X,
4673                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4674         AddToWorkList(X.getNode());
4675         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4676         AddToWorkList(X.getNode());
4677       }
4678
4679       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4680       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4681                       X, DAG.getConstant(SignBit, VT));
4682       AddToWorkList(X.getNode());
4683
4684       SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4685                                 VT, N0.getOperand(0));
4686       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4687                         Cst, DAG.getConstant(~SignBit, VT));
4688       AddToWorkList(Cst.getNode());
4689
4690       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4691     }
4692   }
4693
4694   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4695   if (N0.getOpcode() == ISD::BUILD_PAIR) {
4696     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4697     if (CombineLD.getNode())
4698       return CombineLD;
4699   }
4700
4701   return SDValue();
4702 }
4703
4704 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4705   EVT VT = N->getValueType(0);
4706   return CombineConsecutiveLoads(N, VT);
4707 }
4708
4709 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
4710 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
4711 /// destination element value type.
4712 SDValue DAGCombiner::
4713 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4714   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4715
4716   // If this is already the right type, we're done.
4717   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4718
4719   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4720   unsigned DstBitSize = DstEltVT.getSizeInBits();
4721
4722   // If this is a conversion of N elements of one type to N elements of another
4723   // type, convert each element.  This handles FP<->INT cases.
4724   if (SrcBitSize == DstBitSize) {
4725     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4726                               BV->getValueType(0).getVectorNumElements());
4727
4728     // Due to the FP element handling below calling this routine recursively,
4729     // we can end up with a scalar-to-vector node here.
4730     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
4731       return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4732                          DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4733                                      DstEltVT, BV->getOperand(0)));
4734
4735     SmallVector<SDValue, 8> Ops;
4736     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4737       SDValue Op = BV->getOperand(i);
4738       // If the vector element type is not legal, the BUILD_VECTOR operands
4739       // are promoted and implicitly truncated.  Make that explicit here.
4740       if (Op.getValueType() != SrcEltVT)
4741         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4742       Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4743                                 DstEltVT, Op));
4744       AddToWorkList(Ops.back().getNode());
4745     }
4746     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4747                        &Ops[0], Ops.size());
4748   }
4749
4750   // Otherwise, we're growing or shrinking the elements.  To avoid having to
4751   // handle annoying details of growing/shrinking FP values, we convert them to
4752   // int first.
4753   if (SrcEltVT.isFloatingPoint()) {
4754     // Convert the input float vector to a int vector where the elements are the
4755     // same sizes.
4756     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4757     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4758     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
4759     SrcEltVT = IntVT;
4760   }
4761
4762   // Now we know the input is an integer vector.  If the output is a FP type,
4763   // convert to integer first, then to FP of the right size.
4764   if (DstEltVT.isFloatingPoint()) {
4765     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4766     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4767     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
4768
4769     // Next, convert to FP elements of the same size.
4770     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
4771   }
4772
4773   // Okay, we know the src/dst types are both integers of differing types.
4774   // Handling growing first.
4775   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4776   if (SrcBitSize < DstBitSize) {
4777     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4778
4779     SmallVector<SDValue, 8> Ops;
4780     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4781          i += NumInputsPerOutput) {
4782       bool isLE = TLI.isLittleEndian();
4783       APInt NewBits = APInt(DstBitSize, 0);
4784       bool EltIsUndef = true;
4785       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4786         // Shift the previously computed bits over.
4787         NewBits <<= SrcBitSize;
4788         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4789         if (Op.getOpcode() == ISD::UNDEF) continue;
4790         EltIsUndef = false;
4791
4792         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
4793                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
4794       }
4795
4796       if (EltIsUndef)
4797         Ops.push_back(DAG.getUNDEF(DstEltVT));
4798       else
4799         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4800     }
4801
4802     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4803     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4804                        &Ops[0], Ops.size());
4805   }
4806
4807   // Finally, this must be the case where we are shrinking elements: each input
4808   // turns into multiple outputs.
4809   bool isS2V = ISD::isScalarToVector(BV);
4810   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4811   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4812                             NumOutputsPerInput*BV->getNumOperands());
4813   SmallVector<SDValue, 8> Ops;
4814
4815   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4816     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4817       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4818         Ops.push_back(DAG.getUNDEF(DstEltVT));
4819       continue;
4820     }
4821
4822     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
4823                   getAPIntValue().zextOrTrunc(SrcBitSize);
4824
4825     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4826       APInt ThisVal = OpVal.trunc(DstBitSize);
4827       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4828       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
4829         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4830         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4831                            Ops[0]);
4832       OpVal = OpVal.lshr(DstBitSize);
4833     }
4834
4835     // For big endian targets, swap the order of the pieces of each element.
4836     if (TLI.isBigEndian())
4837       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4838   }
4839
4840   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4841                      &Ops[0], Ops.size());
4842 }
4843
4844 SDValue DAGCombiner::visitFADD(SDNode *N) {
4845   SDValue N0 = N->getOperand(0);
4846   SDValue N1 = N->getOperand(1);
4847   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4848   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4849   EVT VT = N->getValueType(0);
4850
4851   // fold vector ops
4852   if (VT.isVector()) {
4853     SDValue FoldedVOp = SimplifyVBinOp(N);
4854     if (FoldedVOp.getNode()) return FoldedVOp;
4855   }
4856
4857   // fold (fadd c1, c2) -> (fadd c1, c2)
4858   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4859     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4860   // canonicalize constant to RHS
4861   if (N0CFP && !N1CFP)
4862     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4863   // fold (fadd A, 0) -> A
4864   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4865     return N0;
4866   // fold (fadd A, (fneg B)) -> (fsub A, B)
4867   if (isNegatibleForFree(N1, LegalOperations) == 2)
4868     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4869                        GetNegatedExpression(N1, DAG, LegalOperations));
4870   // fold (fadd (fneg A), B) -> (fsub B, A)
4871   if (isNegatibleForFree(N0, LegalOperations) == 2)
4872     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4873                        GetNegatedExpression(N0, DAG, LegalOperations));
4874
4875   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4876   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4877       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4878     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4879                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4880                                    N0.getOperand(1), N1));
4881
4882   return SDValue();
4883 }
4884
4885 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4886   SDValue N0 = N->getOperand(0);
4887   SDValue N1 = N->getOperand(1);
4888   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4889   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4890   EVT VT = N->getValueType(0);
4891
4892   // fold vector ops
4893   if (VT.isVector()) {
4894     SDValue FoldedVOp = SimplifyVBinOp(N);
4895     if (FoldedVOp.getNode()) return FoldedVOp;
4896   }
4897
4898   // fold (fsub c1, c2) -> c1-c2
4899   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4900     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4901   // fold (fsub A, 0) -> A
4902   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4903     return N0;
4904   // fold (fsub 0, B) -> -B
4905   if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4906     if (isNegatibleForFree(N1, LegalOperations))
4907       return GetNegatedExpression(N1, DAG, LegalOperations);
4908     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4909       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4910   }
4911   // fold (fsub A, (fneg B)) -> (fadd A, B)
4912   if (isNegatibleForFree(N1, LegalOperations))
4913     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4914                        GetNegatedExpression(N1, DAG, LegalOperations));
4915
4916   return SDValue();
4917 }
4918
4919 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4920   SDValue N0 = N->getOperand(0);
4921   SDValue N1 = N->getOperand(1);
4922   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4923   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4924   EVT VT = N->getValueType(0);
4925
4926   // fold vector ops
4927   if (VT.isVector()) {
4928     SDValue FoldedVOp = SimplifyVBinOp(N);
4929     if (FoldedVOp.getNode()) return FoldedVOp;
4930   }
4931
4932   // fold (fmul c1, c2) -> c1*c2
4933   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4934     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4935   // canonicalize constant to RHS
4936   if (N0CFP && !N1CFP)
4937     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4938   // fold (fmul A, 0) -> 0
4939   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4940     return N1;
4941   // fold (fmul A, 0) -> 0, vector edition.
4942   if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4943     return N1;
4944   // fold (fmul X, 2.0) -> (fadd X, X)
4945   if (N1CFP && N1CFP->isExactlyValue(+2.0))
4946     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4947   // fold (fmul X, -1.0) -> (fneg X)
4948   if (N1CFP && N1CFP->isExactlyValue(-1.0))
4949     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4950       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4951
4952   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4953   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4954     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4955       // Both can be negated for free, check to see if at least one is cheaper
4956       // negated.
4957       if (LHSNeg == 2 || RHSNeg == 2)
4958         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4959                            GetNegatedExpression(N0, DAG, LegalOperations),
4960                            GetNegatedExpression(N1, DAG, LegalOperations));
4961     }
4962   }
4963
4964   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4965   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4966       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4967     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4968                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4969                                    N0.getOperand(1), N1));
4970
4971   return SDValue();
4972 }
4973
4974 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4975   SDValue N0 = N->getOperand(0);
4976   SDValue N1 = N->getOperand(1);
4977   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4978   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4979   EVT VT = N->getValueType(0);
4980
4981   // fold vector ops
4982   if (VT.isVector()) {
4983     SDValue FoldedVOp = SimplifyVBinOp(N);
4984     if (FoldedVOp.getNode()) return FoldedVOp;
4985   }
4986
4987   // fold (fdiv c1, c2) -> c1/c2
4988   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4989     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4990
4991
4992   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4993   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4994     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4995       // Both can be negated for free, check to see if at least one is cheaper
4996       // negated.
4997       if (LHSNeg == 2 || RHSNeg == 2)
4998         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4999                            GetNegatedExpression(N0, DAG, LegalOperations),
5000                            GetNegatedExpression(N1, DAG, LegalOperations));
5001     }
5002   }
5003
5004   return SDValue();
5005 }
5006
5007 SDValue DAGCombiner::visitFREM(SDNode *N) {
5008   SDValue N0 = N->getOperand(0);
5009   SDValue N1 = N->getOperand(1);
5010   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5011   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5012   EVT VT = N->getValueType(0);
5013
5014   // fold (frem c1, c2) -> fmod(c1,c2)
5015   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5016     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5017
5018   return SDValue();
5019 }
5020
5021 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5022   SDValue N0 = N->getOperand(0);
5023   SDValue N1 = N->getOperand(1);
5024   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5025   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5026   EVT VT = N->getValueType(0);
5027
5028   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
5029     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5030
5031   if (N1CFP) {
5032     const APFloat& V = N1CFP->getValueAPF();
5033     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
5034     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5035     if (!V.isNegative()) {
5036       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5037         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5038     } else {
5039       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5040         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5041                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5042     }
5043   }
5044
5045   // copysign(fabs(x), y) -> copysign(x, y)
5046   // copysign(fneg(x), y) -> copysign(x, y)
5047   // copysign(copysign(x,z), y) -> copysign(x, y)
5048   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5049       N0.getOpcode() == ISD::FCOPYSIGN)
5050     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5051                        N0.getOperand(0), N1);
5052
5053   // copysign(x, abs(y)) -> abs(x)
5054   if (N1.getOpcode() == ISD::FABS)
5055     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5056
5057   // copysign(x, copysign(y,z)) -> copysign(x, z)
5058   if (N1.getOpcode() == ISD::FCOPYSIGN)
5059     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5060                        N0, N1.getOperand(1));
5061
5062   // copysign(x, fp_extend(y)) -> copysign(x, y)
5063   // copysign(x, fp_round(y)) -> copysign(x, y)
5064   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5065     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5066                        N0, N1.getOperand(0));
5067
5068   return SDValue();
5069 }
5070
5071 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5072   SDValue N0 = N->getOperand(0);
5073   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5074   EVT VT = N->getValueType(0);
5075   EVT OpVT = N0.getValueType();
5076
5077   // fold (sint_to_fp c1) -> c1fp
5078   if (N0C && OpVT != MVT::ppcf128)
5079     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5080
5081   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5082   // but UINT_TO_FP is legal on this target, try to convert.
5083   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5084       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5085     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5086     if (DAG.SignBitIsZero(N0))
5087       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5088   }
5089
5090   return SDValue();
5091 }
5092
5093 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
5094   SDValue N0 = N->getOperand(0);
5095   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5096   EVT VT = N->getValueType(0);
5097   EVT OpVT = N0.getValueType();
5098
5099   // fold (uint_to_fp c1) -> c1fp
5100   if (N0C && OpVT != MVT::ppcf128)
5101     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5102
5103   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
5104   // but SINT_TO_FP is legal on this target, try to convert.
5105   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
5106       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
5107     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
5108     if (DAG.SignBitIsZero(N0))
5109       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5110   }
5111
5112   return SDValue();
5113 }
5114
5115 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
5116   SDValue N0 = N->getOperand(0);
5117   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5118   EVT VT = N->getValueType(0);
5119
5120   // fold (fp_to_sint c1fp) -> c1
5121   if (N0CFP)
5122     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
5123
5124   return SDValue();
5125 }
5126
5127 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
5128   SDValue N0 = N->getOperand(0);
5129   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5130   EVT VT = N->getValueType(0);
5131
5132   // fold (fp_to_uint c1fp) -> c1
5133   if (N0CFP && VT != MVT::ppcf128)
5134     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
5135
5136   return SDValue();
5137 }
5138
5139 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
5140   SDValue N0 = N->getOperand(0);
5141   SDValue N1 = N->getOperand(1);
5142   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5143   EVT VT = N->getValueType(0);
5144
5145   // fold (fp_round c1fp) -> c1fp
5146   if (N0CFP && N0.getValueType() != MVT::ppcf128)
5147     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
5148
5149   // fold (fp_round (fp_extend x)) -> x
5150   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
5151     return N0.getOperand(0);
5152
5153   // fold (fp_round (fp_round x)) -> (fp_round x)
5154   if (N0.getOpcode() == ISD::FP_ROUND) {
5155     // This is a value preserving truncation if both round's are.
5156     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
5157                    N0.getNode()->getConstantOperandVal(1) == 1;
5158     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
5159                        DAG.getIntPtrConstant(IsTrunc));
5160   }
5161
5162   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
5163   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
5164     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
5165                               N0.getOperand(0), N1);
5166     AddToWorkList(Tmp.getNode());
5167     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5168                        Tmp, N0.getOperand(1));
5169   }
5170
5171   return SDValue();
5172 }
5173
5174 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
5175   SDValue N0 = N->getOperand(0);
5176   EVT VT = N->getValueType(0);
5177   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5178   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5179
5180   // fold (fp_round_inreg c1fp) -> c1fp
5181   if (N0CFP && isTypeLegal(EVT)) {
5182     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5183     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5184   }
5185
5186   return SDValue();
5187 }
5188
5189 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5190   SDValue N0 = N->getOperand(0);
5191   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5192   EVT VT = N->getValueType(0);
5193
5194   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5195   if (N->hasOneUse() &&
5196       N->use_begin()->getOpcode() == ISD::FP_ROUND)
5197     return SDValue();
5198
5199   // fold (fp_extend c1fp) -> c1fp
5200   if (N0CFP && VT != MVT::ppcf128)
5201     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5202
5203   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5204   // value of X.
5205   if (N0.getOpcode() == ISD::FP_ROUND
5206       && N0.getNode()->getConstantOperandVal(1) == 1) {
5207     SDValue In = N0.getOperand(0);
5208     if (In.getValueType() == VT) return In;
5209     if (VT.bitsLT(In.getValueType()))
5210       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5211                          In, N0.getOperand(1));
5212     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5213   }
5214
5215   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5216   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5217       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5218        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5219     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5220     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
5221                                      LN0->getChain(),
5222                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5223                                      N0.getValueType(),
5224                                      LN0->isVolatile(), LN0->isNonTemporal(),
5225                                      LN0->getAlignment());
5226     CombineTo(N, ExtLoad);
5227     CombineTo(N0.getNode(),
5228               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5229                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5230               ExtLoad.getValue(1));
5231     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5232   }
5233
5234   return SDValue();
5235 }
5236
5237 SDValue DAGCombiner::visitFNEG(SDNode *N) {
5238   SDValue N0 = N->getOperand(0);
5239   EVT VT = N->getValueType(0);
5240
5241   if (isNegatibleForFree(N0, LegalOperations))
5242     return GetNegatedExpression(N0, DAG, LegalOperations);
5243
5244   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5245   // constant pool values.
5246   if (N0.getOpcode() == ISD::BITCAST &&
5247       !VT.isVector() &&
5248       N0.getNode()->hasOneUse() &&
5249       N0.getOperand(0).getValueType().isInteger()) {
5250     SDValue Int = N0.getOperand(0);
5251     EVT IntVT = Int.getValueType();
5252     if (IntVT.isInteger() && !IntVT.isVector()) {
5253       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5254               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5255       AddToWorkList(Int.getNode());
5256       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5257                          VT, Int);
5258     }
5259   }
5260
5261   return SDValue();
5262 }
5263
5264 SDValue DAGCombiner::visitFABS(SDNode *N) {
5265   SDValue N0 = N->getOperand(0);
5266   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5267   EVT VT = N->getValueType(0);
5268
5269   // fold (fabs c1) -> fabs(c1)
5270   if (N0CFP && VT != MVT::ppcf128)
5271     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5272   // fold (fabs (fabs x)) -> (fabs x)
5273   if (N0.getOpcode() == ISD::FABS)
5274     return N->getOperand(0);
5275   // fold (fabs (fneg x)) -> (fabs x)
5276   // fold (fabs (fcopysign x, y)) -> (fabs x)
5277   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5278     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5279
5280   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5281   // constant pool values.
5282   if (N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
5283       N0.getOperand(0).getValueType().isInteger() &&
5284       !N0.getOperand(0).getValueType().isVector()) {
5285     SDValue Int = N0.getOperand(0);
5286     EVT IntVT = Int.getValueType();
5287     if (IntVT.isInteger() && !IntVT.isVector()) {
5288       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5289              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5290       AddToWorkList(Int.getNode());
5291       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5292                          N->getValueType(0), Int);
5293     }
5294   }
5295
5296   return SDValue();
5297 }
5298
5299 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5300   SDValue Chain = N->getOperand(0);
5301   SDValue N1 = N->getOperand(1);
5302   SDValue N2 = N->getOperand(2);
5303
5304   // If N is a constant we could fold this into a fallthrough or unconditional
5305   // branch. However that doesn't happen very often in normal code, because
5306   // Instcombine/SimplifyCFG should have handled the available opportunities.
5307   // If we did this folding here, it would be necessary to update the
5308   // MachineBasicBlock CFG, which is awkward.
5309
5310   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5311   // on the target.
5312   if (N1.getOpcode() == ISD::SETCC &&
5313       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5314     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5315                        Chain, N1.getOperand(2),
5316                        N1.getOperand(0), N1.getOperand(1), N2);
5317   }
5318
5319   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5320       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5321        (N1.getOperand(0).hasOneUse() &&
5322         N1.getOperand(0).getOpcode() == ISD::SRL))) {
5323     SDNode *Trunc = 0;
5324     if (N1.getOpcode() == ISD::TRUNCATE) {
5325       // Look pass the truncate.
5326       Trunc = N1.getNode();
5327       N1 = N1.getOperand(0);
5328     }
5329
5330     // Match this pattern so that we can generate simpler code:
5331     //
5332     //   %a = ...
5333     //   %b = and i32 %a, 2
5334     //   %c = srl i32 %b, 1
5335     //   brcond i32 %c ...
5336     //
5337     // into
5338     //
5339     //   %a = ...
5340     //   %b = and i32 %a, 2
5341     //   %c = setcc eq %b, 0
5342     //   brcond %c ...
5343     //
5344     // This applies only when the AND constant value has one bit set and the
5345     // SRL constant is equal to the log2 of the AND constant. The back-end is
5346     // smart enough to convert the result into a TEST/JMP sequence.
5347     SDValue Op0 = N1.getOperand(0);
5348     SDValue Op1 = N1.getOperand(1);
5349
5350     if (Op0.getOpcode() == ISD::AND &&
5351         Op1.getOpcode() == ISD::Constant) {
5352       SDValue AndOp1 = Op0.getOperand(1);
5353
5354       if (AndOp1.getOpcode() == ISD::Constant) {
5355         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5356
5357         if (AndConst.isPowerOf2() &&
5358             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5359           SDValue SetCC =
5360             DAG.getSetCC(N->getDebugLoc(),
5361                          TLI.getSetCCResultType(Op0.getValueType()),
5362                          Op0, DAG.getConstant(0, Op0.getValueType()),
5363                          ISD::SETNE);
5364
5365           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5366                                           MVT::Other, Chain, SetCC, N2);
5367           // Don't add the new BRCond into the worklist or else SimplifySelectCC
5368           // will convert it back to (X & C1) >> C2.
5369           CombineTo(N, NewBRCond, false);
5370           // Truncate is dead.
5371           if (Trunc) {
5372             removeFromWorkList(Trunc);
5373             DAG.DeleteNode(Trunc);
5374           }
5375           // Replace the uses of SRL with SETCC
5376           WorkListRemover DeadNodes(*this);
5377           DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5378           removeFromWorkList(N1.getNode());
5379           DAG.DeleteNode(N1.getNode());
5380           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5381         }
5382       }
5383     }
5384
5385     if (Trunc)
5386       // Restore N1 if the above transformation doesn't match.
5387       N1 = N->getOperand(1);
5388   }
5389
5390   // Transform br(xor(x, y)) -> br(x != y)
5391   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5392   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5393     SDNode *TheXor = N1.getNode();
5394     SDValue Op0 = TheXor->getOperand(0);
5395     SDValue Op1 = TheXor->getOperand(1);
5396     if (Op0.getOpcode() == Op1.getOpcode()) {
5397       // Avoid missing important xor optimizations.
5398       SDValue Tmp = visitXOR(TheXor);
5399       if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5400         DEBUG(dbgs() << "\nReplacing.8 ";
5401               TheXor->dump(&DAG);
5402               dbgs() << "\nWith: ";
5403               Tmp.getNode()->dump(&DAG);
5404               dbgs() << '\n');
5405         WorkListRemover DeadNodes(*this);
5406         DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5407         removeFromWorkList(TheXor);
5408         DAG.DeleteNode(TheXor);
5409         return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5410                            MVT::Other, Chain, Tmp, N2);
5411       }
5412     }
5413
5414     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5415       bool Equal = false;
5416       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5417         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5418             Op0.getOpcode() == ISD::XOR) {
5419           TheXor = Op0.getNode();
5420           Equal = true;
5421         }
5422
5423       EVT SetCCVT = N1.getValueType();
5424       if (LegalTypes)
5425         SetCCVT = TLI.getSetCCResultType(SetCCVT);
5426       SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5427                                    SetCCVT,
5428                                    Op0, Op1,
5429                                    Equal ? ISD::SETEQ : ISD::SETNE);
5430       // Replace the uses of XOR with SETCC
5431       WorkListRemover DeadNodes(*this);
5432       DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5433       removeFromWorkList(N1.getNode());
5434       DAG.DeleteNode(N1.getNode());
5435       return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5436                          MVT::Other, Chain, SetCC, N2);
5437     }
5438   }
5439
5440   return SDValue();
5441 }
5442
5443 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5444 //
5445 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5446   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5447   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5448
5449   // If N is a constant we could fold this into a fallthrough or unconditional
5450   // branch. However that doesn't happen very often in normal code, because
5451   // Instcombine/SimplifyCFG should have handled the available opportunities.
5452   // If we did this folding here, it would be necessary to update the
5453   // MachineBasicBlock CFG, which is awkward.
5454
5455   // Use SimplifySetCC to simplify SETCC's.
5456   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5457                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5458                                false);
5459   if (Simp.getNode()) AddToWorkList(Simp.getNode());
5460
5461   // fold to a simpler setcc
5462   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5463     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5464                        N->getOperand(0), Simp.getOperand(2),
5465                        Simp.getOperand(0), Simp.getOperand(1),
5466                        N->getOperand(4));
5467
5468   return SDValue();
5469 }
5470
5471 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5472 /// pre-indexed load / store when the base pointer is an add or subtract
5473 /// and it has other uses besides the load / store. After the
5474 /// transformation, the new indexed load / store has effectively folded
5475 /// the add / subtract in and all of its other uses are redirected to the
5476 /// new load / store.
5477 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5478   if (!LegalOperations)
5479     return false;
5480
5481   bool isLoad = true;
5482   SDValue Ptr;
5483   EVT VT;
5484   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
5485     if (LD->isIndexed())
5486       return false;
5487     VT = LD->getMemoryVT();
5488     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5489         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5490       return false;
5491     Ptr = LD->getBasePtr();
5492   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
5493     if (ST->isIndexed())
5494       return false;
5495     VT = ST->getMemoryVT();
5496     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5497         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5498       return false;
5499     Ptr = ST->getBasePtr();
5500     isLoad = false;
5501   } else {
5502     return false;
5503   }
5504
5505   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5506   // out.  There is no reason to make this a preinc/predec.
5507   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5508       Ptr.getNode()->hasOneUse())
5509     return false;
5510
5511   // Ask the target to do addressing mode selection.
5512   SDValue BasePtr;
5513   SDValue Offset;
5514   ISD::MemIndexedMode AM = ISD::UNINDEXED;
5515   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5516     return false;
5517   // Don't create a indexed load / store with zero offset.
5518   if (isa<ConstantSDNode>(Offset) &&
5519       cast<ConstantSDNode>(Offset)->isNullValue())
5520     return false;
5521
5522   // Try turning it into a pre-indexed load / store except when:
5523   // 1) The new base ptr is a frame index.
5524   // 2) If N is a store and the new base ptr is either the same as or is a
5525   //    predecessor of the value being stored.
5526   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5527   //    that would create a cycle.
5528   // 4) All uses are load / store ops that use it as old base ptr.
5529
5530   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
5531   // (plus the implicit offset) to a register to preinc anyway.
5532   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5533     return false;
5534
5535   // Check #2.
5536   if (!isLoad) {
5537     SDValue Val = cast<StoreSDNode>(N)->getValue();
5538     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5539       return false;
5540   }
5541
5542   // Now check for #3 and #4.
5543   bool RealUse = false;
5544   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5545          E = Ptr.getNode()->use_end(); I != E; ++I) {
5546     SDNode *Use = *I;
5547     if (Use == N)
5548       continue;
5549     if (Use->isPredecessorOf(N))
5550       return false;
5551
5552     if (!((Use->getOpcode() == ISD::LOAD &&
5553            cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5554           (Use->getOpcode() == ISD::STORE &&
5555            cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5556       RealUse = true;
5557   }
5558
5559   if (!RealUse)
5560     return false;
5561
5562   SDValue Result;
5563   if (isLoad)
5564     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5565                                 BasePtr, Offset, AM);
5566   else
5567     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5568                                  BasePtr, Offset, AM);
5569   ++PreIndexedNodes;
5570   ++NodesCombined;
5571   DEBUG(dbgs() << "\nReplacing.4 ";
5572         N->dump(&DAG);
5573         dbgs() << "\nWith: ";
5574         Result.getNode()->dump(&DAG);
5575         dbgs() << '\n');
5576   WorkListRemover DeadNodes(*this);
5577   if (isLoad) {
5578     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5579                                   &DeadNodes);
5580     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5581                                   &DeadNodes);
5582   } else {
5583     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5584                                   &DeadNodes);
5585   }
5586
5587   // Finally, since the node is now dead, remove it from the graph.
5588   DAG.DeleteNode(N);
5589
5590   // Replace the uses of Ptr with uses of the updated base value.
5591   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5592                                 &DeadNodes);
5593   removeFromWorkList(Ptr.getNode());
5594   DAG.DeleteNode(Ptr.getNode());
5595
5596   return true;
5597 }
5598
5599 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5600 /// add / sub of the base pointer node into a post-indexed load / store.
5601 /// The transformation folded the add / subtract into the new indexed
5602 /// load / store effectively and all of its uses are redirected to the
5603 /// new load / store.
5604 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5605   if (!LegalOperations)
5606     return false;
5607
5608   bool isLoad = true;
5609   SDValue Ptr;
5610   EVT VT;
5611   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
5612     if (LD->isIndexed())
5613       return false;
5614     VT = LD->getMemoryVT();
5615     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5616         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5617       return false;
5618     Ptr = LD->getBasePtr();
5619   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
5620     if (ST->isIndexed())
5621       return false;
5622     VT = ST->getMemoryVT();
5623     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5624         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5625       return false;
5626     Ptr = ST->getBasePtr();
5627     isLoad = false;
5628   } else {
5629     return false;
5630   }
5631
5632   if (Ptr.getNode()->hasOneUse())
5633     return false;
5634
5635   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5636          E = Ptr.getNode()->use_end(); I != E; ++I) {
5637     SDNode *Op = *I;
5638     if (Op == N ||
5639         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5640       continue;
5641
5642     SDValue BasePtr;
5643     SDValue Offset;
5644     ISD::MemIndexedMode AM = ISD::UNINDEXED;
5645     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5646       // Don't create a indexed load / store with zero offset.
5647       if (isa<ConstantSDNode>(Offset) &&
5648           cast<ConstantSDNode>(Offset)->isNullValue())
5649         continue;
5650
5651       // Try turning it into a post-indexed load / store except when
5652       // 1) All uses are load / store ops that use it as base ptr.
5653       // 2) Op must be independent of N, i.e. Op is neither a predecessor
5654       //    nor a successor of N. Otherwise, if Op is folded that would
5655       //    create a cycle.
5656
5657       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5658         continue;
5659
5660       // Check for #1.
5661       bool TryNext = false;
5662       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5663              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5664         SDNode *Use = *II;
5665         if (Use == Ptr.getNode())
5666           continue;
5667
5668         // If all the uses are load / store addresses, then don't do the
5669         // transformation.
5670         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5671           bool RealUse = false;
5672           for (SDNode::use_iterator III = Use->use_begin(),
5673                  EEE = Use->use_end(); III != EEE; ++III) {
5674             SDNode *UseUse = *III;
5675             if (!((UseUse->getOpcode() == ISD::LOAD &&
5676                    cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5677                   (UseUse->getOpcode() == ISD::STORE &&
5678                    cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5679               RealUse = true;
5680           }
5681
5682           if (!RealUse) {
5683             TryNext = true;
5684             break;
5685           }
5686         }
5687       }
5688
5689       if (TryNext)
5690         continue;
5691
5692       // Check for #2
5693       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5694         SDValue Result = isLoad
5695           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5696                                BasePtr, Offset, AM)
5697           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5698                                 BasePtr, Offset, AM);
5699         ++PostIndexedNodes;
5700         ++NodesCombined;
5701         DEBUG(dbgs() << "\nReplacing.5 ";
5702               N->dump(&DAG);
5703               dbgs() << "\nWith: ";
5704               Result.getNode()->dump(&DAG);
5705               dbgs() << '\n');
5706         WorkListRemover DeadNodes(*this);
5707         if (isLoad) {
5708           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5709                                         &DeadNodes);
5710           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5711                                         &DeadNodes);
5712         } else {
5713           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5714                                         &DeadNodes);
5715         }
5716
5717         // Finally, since the node is now dead, remove it from the graph.
5718         DAG.DeleteNode(N);
5719
5720         // Replace the uses of Use with uses of the updated base value.
5721         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5722                                       Result.getValue(isLoad ? 1 : 0),
5723                                       &DeadNodes);
5724         removeFromWorkList(Op);
5725         DAG.DeleteNode(Op);
5726         return true;
5727       }
5728     }
5729   }
5730
5731   return false;
5732 }
5733
5734 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5735   LoadSDNode *LD  = cast<LoadSDNode>(N);
5736   SDValue Chain = LD->getChain();
5737   SDValue Ptr   = LD->getBasePtr();
5738
5739   // If load is not volatile and there are no uses of the loaded value (and
5740   // the updated indexed value in case of indexed loads), change uses of the
5741   // chain value into uses of the chain input (i.e. delete the dead load).
5742   if (!LD->isVolatile()) {
5743     if (N->getValueType(1) == MVT::Other) {
5744       // Unindexed loads.
5745       if (N->hasNUsesOfValue(0, 0)) {
5746         // It's not safe to use the two value CombineTo variant here. e.g.
5747         // v1, chain2 = load chain1, loc
5748         // v2, chain3 = load chain2, loc
5749         // v3         = add v2, c
5750         // Now we replace use of chain2 with chain1.  This makes the second load
5751         // isomorphic to the one we are deleting, and thus makes this load live.
5752         DEBUG(dbgs() << "\nReplacing.6 ";
5753               N->dump(&DAG);
5754               dbgs() << "\nWith chain: ";
5755               Chain.getNode()->dump(&DAG);
5756               dbgs() << "\n");
5757         WorkListRemover DeadNodes(*this);
5758         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5759
5760         if (N->use_empty()) {
5761           removeFromWorkList(N);
5762           DAG.DeleteNode(N);
5763         }
5764
5765         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5766       }
5767     } else {
5768       // Indexed loads.
5769       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5770       if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5771         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5772         DEBUG(dbgs() << "\nReplacing.7 ";
5773               N->dump(&DAG);
5774               dbgs() << "\nWith: ";
5775               Undef.getNode()->dump(&DAG);
5776               dbgs() << " and 2 other values\n");
5777         WorkListRemover DeadNodes(*this);
5778         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5779         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5780                                       DAG.getUNDEF(N->getValueType(1)),
5781                                       &DeadNodes);
5782         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5783         removeFromWorkList(N);
5784         DAG.DeleteNode(N);
5785         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5786       }
5787     }
5788   }
5789
5790   // If this load is directly stored, replace the load value with the stored
5791   // value.
5792   // TODO: Handle store large -> read small portion.
5793   // TODO: Handle TRUNCSTORE/LOADEXT
5794   if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5795       !LD->isVolatile()) {
5796     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5797       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5798       if (PrevST->getBasePtr() == Ptr &&
5799           PrevST->getValue().getValueType() == N->getValueType(0))
5800       return CombineTo(N, Chain.getOperand(1), Chain);
5801     }
5802   }
5803
5804   // Try to infer better alignment information than the load already has.
5805   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5806     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5807       if (Align > LD->getAlignment())
5808         return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5809                               N->getDebugLoc(),
5810                               Chain, Ptr, LD->getPointerInfo(),
5811                               LD->getMemoryVT(),
5812                               LD->isVolatile(), LD->isNonTemporal(), Align);
5813     }
5814   }
5815
5816   if (CombinerAA) {
5817     // Walk up chain skipping non-aliasing memory nodes.
5818     SDValue BetterChain = FindBetterChain(N, Chain);
5819
5820     // If there is a better chain.
5821     if (Chain != BetterChain) {
5822       SDValue ReplLoad;
5823
5824       // Replace the chain to void dependency.
5825       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5826         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5827                                BetterChain, Ptr, LD->getPointerInfo(),
5828                                LD->isVolatile(), LD->isNonTemporal(),
5829                                LD->getAlignment());
5830       } else {
5831         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5832                                   LD->getDebugLoc(),
5833                                   BetterChain, Ptr, LD->getPointerInfo(),
5834                                   LD->getMemoryVT(),
5835                                   LD->isVolatile(),
5836                                   LD->isNonTemporal(),
5837                                   LD->getAlignment());
5838       }
5839
5840       // Create token factor to keep old chain connected.
5841       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5842                                   MVT::Other, Chain, ReplLoad.getValue(1));
5843
5844       // Make sure the new and old chains are cleaned up.
5845       AddToWorkList(Token.getNode());
5846
5847       // Replace uses with load result and token factor. Don't add users
5848       // to work list.
5849       return CombineTo(N, ReplLoad.getValue(0), Token, false);
5850     }
5851   }
5852
5853   // Try transforming N to an indexed load.
5854   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5855     return SDValue(N, 0);
5856
5857   return SDValue();
5858 }
5859
5860 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5861 /// load is having specific bytes cleared out.  If so, return the byte size
5862 /// being masked out and the shift amount.
5863 static std::pair<unsigned, unsigned>
5864 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5865   std::pair<unsigned, unsigned> Result(0, 0);
5866
5867   // Check for the structure we're looking for.
5868   if (V->getOpcode() != ISD::AND ||
5869       !isa<ConstantSDNode>(V->getOperand(1)) ||
5870       !ISD::isNormalLoad(V->getOperand(0).getNode()))
5871     return Result;
5872
5873   // Check the chain and pointer.
5874   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5875   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
5876
5877   // The store should be chained directly to the load or be an operand of a
5878   // tokenfactor.
5879   if (LD == Chain.getNode())
5880     ; // ok.
5881   else if (Chain->getOpcode() != ISD::TokenFactor)
5882     return Result; // Fail.
5883   else {
5884     bool isOk = false;
5885     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5886       if (Chain->getOperand(i).getNode() == LD) {
5887         isOk = true;
5888         break;
5889       }
5890     if (!isOk) return Result;
5891   }
5892
5893   // This only handles simple types.
5894   if (V.getValueType() != MVT::i16 &&
5895       V.getValueType() != MVT::i32 &&
5896       V.getValueType() != MVT::i64)
5897     return Result;
5898
5899   // Check the constant mask.  Invert it so that the bits being masked out are
5900   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
5901   // follow the sign bit for uniformity.
5902   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5903   unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5904   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
5905   unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5906   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
5907   if (NotMaskLZ == 64) return Result;  // All zero mask.
5908
5909   // See if we have a continuous run of bits.  If so, we have 0*1+0*
5910   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5911     return Result;
5912
5913   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5914   if (V.getValueType() != MVT::i64 && NotMaskLZ)
5915     NotMaskLZ -= 64-V.getValueSizeInBits();
5916
5917   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5918   switch (MaskedBytes) {
5919   case 1:
5920   case 2:
5921   case 4: break;
5922   default: return Result; // All one mask, or 5-byte mask.
5923   }
5924
5925   // Verify that the first bit starts at a multiple of mask so that the access
5926   // is aligned the same as the access width.
5927   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5928
5929   Result.first = MaskedBytes;
5930   Result.second = NotMaskTZ/8;
5931   return Result;
5932 }
5933
5934
5935 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5936 /// provides a value as specified by MaskInfo.  If so, replace the specified
5937 /// store with a narrower store of truncated IVal.
5938 static SDNode *
5939 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5940                                 SDValue IVal, StoreSDNode *St,
5941                                 DAGCombiner *DC) {
5942   unsigned NumBytes = MaskInfo.first;
5943   unsigned ByteShift = MaskInfo.second;
5944   SelectionDAG &DAG = DC->getDAG();
5945
5946   // Check to see if IVal is all zeros in the part being masked in by the 'or'
5947   // that uses this.  If not, this is not a replacement.
5948   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5949                                   ByteShift*8, (ByteShift+NumBytes)*8);
5950   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5951
5952   // Check that it is legal on the target to do this.  It is legal if the new
5953   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5954   // legalization.
5955   MVT VT = MVT::getIntegerVT(NumBytes*8);
5956   if (!DC->isTypeLegal(VT))
5957     return 0;
5958
5959   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
5960   // shifted by ByteShift and truncated down to NumBytes.
5961   if (ByteShift)
5962     IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5963                        DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5964
5965   // Figure out the offset for the store and the alignment of the access.
5966   unsigned StOffset;
5967   unsigned NewAlign = St->getAlignment();
5968
5969   if (DAG.getTargetLoweringInfo().isLittleEndian())
5970     StOffset = ByteShift;
5971   else
5972     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5973
5974   SDValue Ptr = St->getBasePtr();
5975   if (StOffset) {
5976     Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5977                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5978     NewAlign = MinAlign(NewAlign, StOffset);
5979   }
5980
5981   // Truncate down to the new size.
5982   IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5983
5984   ++OpsNarrowed;
5985   return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
5986                       St->getPointerInfo().getWithOffset(StOffset),
5987                       false, false, NewAlign).getNode();
5988 }
5989
5990
5991 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5992 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5993 /// of the loaded bits, try narrowing the load and store if it would end up
5994 /// being a win for performance or code size.
5995 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5996   StoreSDNode *ST  = cast<StoreSDNode>(N);
5997   if (ST->isVolatile())
5998     return SDValue();
5999
6000   SDValue Chain = ST->getChain();
6001   SDValue Value = ST->getValue();
6002   SDValue Ptr   = ST->getBasePtr();
6003   EVT VT = Value.getValueType();
6004
6005   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6006     return SDValue();
6007
6008   unsigned Opc = Value.getOpcode();
6009
6010   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6011   // is a byte mask indicating a consecutive number of bytes, check to see if
6012   // Y is known to provide just those bytes.  If so, we try to replace the
6013   // load + replace + store sequence with a single (narrower) store, which makes
6014   // the load dead.
6015   if (Opc == ISD::OR) {
6016     std::pair<unsigned, unsigned> MaskedLoad;
6017     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6018     if (MaskedLoad.first)
6019       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6020                                                   Value.getOperand(1), ST,this))
6021         return SDValue(NewST, 0);
6022
6023     // Or is commutative, so try swapping X and Y.
6024     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6025     if (MaskedLoad.first)
6026       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6027                                                   Value.getOperand(0), ST,this))
6028         return SDValue(NewST, 0);
6029   }
6030
6031   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6032       Value.getOperand(1).getOpcode() != ISD::Constant)
6033     return SDValue();
6034
6035   SDValue N0 = Value.getOperand(0);
6036   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6037       Chain == SDValue(N0.getNode(), 1)) {
6038     LoadSDNode *LD = cast<LoadSDNode>(N0);
6039     if (LD->getBasePtr() != Ptr ||
6040         LD->getPointerInfo().getAddrSpace() !=
6041         ST->getPointerInfo().getAddrSpace())
6042       return SDValue();
6043
6044     // Find the type to narrow it the load / op / store to.
6045     SDValue N1 = Value.getOperand(1);
6046     unsigned BitWidth = N1.getValueSizeInBits();
6047     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
6048     if (Opc == ISD::AND)
6049       Imm ^= APInt::getAllOnesValue(BitWidth);
6050     if (Imm == 0 || Imm.isAllOnesValue())
6051       return SDValue();
6052     unsigned ShAmt = Imm.countTrailingZeros();
6053     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
6054     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
6055     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6056     while (NewBW < BitWidth &&
6057            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
6058              TLI.isNarrowingProfitable(VT, NewVT))) {
6059       NewBW = NextPowerOf2(NewBW);
6060       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6061     }
6062     if (NewBW >= BitWidth)
6063       return SDValue();
6064
6065     // If the lsb changed does not start at the type bitwidth boundary,
6066     // start at the previous one.
6067     if (ShAmt % NewBW)
6068       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
6069     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
6070     if ((Imm & Mask) == Imm) {
6071       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
6072       if (Opc == ISD::AND)
6073         NewImm ^= APInt::getAllOnesValue(NewBW);
6074       uint64_t PtrOff = ShAmt / 8;
6075       // For big endian targets, we need to adjust the offset to the pointer to
6076       // load the correct bytes.
6077       if (TLI.isBigEndian())
6078         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
6079
6080       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
6081       const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
6082       if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
6083         return SDValue();
6084
6085       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
6086                                    Ptr.getValueType(), Ptr,
6087                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
6088       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
6089                                   LD->getChain(), NewPtr,
6090                                   LD->getPointerInfo().getWithOffset(PtrOff),
6091                                   LD->isVolatile(), LD->isNonTemporal(),
6092                                   NewAlign);
6093       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
6094                                    DAG.getConstant(NewImm, NewVT));
6095       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
6096                                    NewVal, NewPtr,
6097                                    ST->getPointerInfo().getWithOffset(PtrOff),
6098                                    false, false, NewAlign);
6099
6100       AddToWorkList(NewPtr.getNode());
6101       AddToWorkList(NewLD.getNode());
6102       AddToWorkList(NewVal.getNode());
6103       WorkListRemover DeadNodes(*this);
6104       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
6105                                     &DeadNodes);
6106       ++OpsNarrowed;
6107       return NewST;
6108     }
6109   }
6110
6111   return SDValue();
6112 }
6113
6114 SDValue DAGCombiner::visitSTORE(SDNode *N) {
6115   StoreSDNode *ST  = cast<StoreSDNode>(N);
6116   SDValue Chain = ST->getChain();
6117   SDValue Value = ST->getValue();
6118   SDValue Ptr   = ST->getBasePtr();
6119
6120   // If this is a store of a bit convert, store the input value if the
6121   // resultant store does not need a higher alignment than the original.
6122   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
6123       ST->isUnindexed()) {
6124     unsigned OrigAlign = ST->getAlignment();
6125     EVT SVT = Value.getOperand(0).getValueType();
6126     unsigned Align = TLI.getTargetData()->
6127       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
6128     if (Align <= OrigAlign &&
6129         ((!LegalOperations && !ST->isVolatile()) ||
6130          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
6131       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6132                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
6133                           ST->isNonTemporal(), OrigAlign);
6134   }
6135
6136   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
6137   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
6138     // NOTE: If the original store is volatile, this transform must not increase
6139     // the number of stores.  For example, on x86-32 an f64 can be stored in one
6140     // processor operation but an i64 (which is not legal) requires two.  So the
6141     // transform should not be done in this case.
6142     if (Value.getOpcode() != ISD::TargetConstantFP) {
6143       SDValue Tmp;
6144       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
6145       default: llvm_unreachable("Unknown FP type");
6146       case MVT::f80:    // We don't do this for these yet.
6147       case MVT::f128:
6148       case MVT::ppcf128:
6149         break;
6150       case MVT::f32:
6151         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
6152             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6153           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
6154                               bitcastToAPInt().getZExtValue(), MVT::i32);
6155           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6156                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
6157                               ST->isNonTemporal(), ST->getAlignment());
6158         }
6159         break;
6160       case MVT::f64:
6161         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
6162              !ST->isVolatile()) ||
6163             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
6164           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
6165                                 getZExtValue(), MVT::i64);
6166           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6167                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
6168                               ST->isNonTemporal(), ST->getAlignment());
6169         } else if (!ST->isVolatile() &&
6170                    TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6171           // Many FP stores are not made apparent until after legalize, e.g. for
6172           // argument passing.  Since this is so common, custom legalize the
6173           // 64-bit integer store into two 32-bit stores.
6174           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
6175           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6176           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6177           if (TLI.isBigEndian()) std::swap(Lo, Hi);
6178
6179           unsigned Alignment = ST->getAlignment();
6180           bool isVolatile = ST->isVolatile();
6181           bool isNonTemporal = ST->isNonTemporal();
6182
6183           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6184                                      Ptr, ST->getPointerInfo(),
6185                                      isVolatile, isNonTemporal,
6186                                      ST->getAlignment());
6187           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6188                             DAG.getConstant(4, Ptr.getValueType()));
6189           Alignment = MinAlign(Alignment, 4U);
6190           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6191                                      Ptr, ST->getPointerInfo().getWithOffset(4),
6192                                      isVolatile, isNonTemporal,
6193                                      Alignment);
6194           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6195                              St0, St1);
6196         }
6197
6198         break;
6199       }
6200     }
6201   }
6202
6203   // Try to infer better alignment information than the store already has.
6204   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6205     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6206       if (Align > ST->getAlignment())
6207         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6208                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6209                                  ST->isVolatile(), ST->isNonTemporal(), Align);
6210     }
6211   }
6212
6213   if (CombinerAA) {
6214     // Walk up chain skipping non-aliasing memory nodes.
6215     SDValue BetterChain = FindBetterChain(N, Chain);
6216
6217     // If there is a better chain.
6218     if (Chain != BetterChain) {
6219       SDValue ReplStore;
6220
6221       // Replace the chain to avoid dependency.
6222       if (ST->isTruncatingStore()) {
6223         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6224                                       ST->getPointerInfo(),
6225                                       ST->getMemoryVT(), ST->isVolatile(),
6226                                       ST->isNonTemporal(), ST->getAlignment());
6227       } else {
6228         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6229                                  ST->getPointerInfo(),
6230                                  ST->isVolatile(), ST->isNonTemporal(),
6231                                  ST->getAlignment());
6232       }
6233
6234       // Create token to keep both nodes around.
6235       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6236                                   MVT::Other, Chain, ReplStore);
6237
6238       // Make sure the new and old chains are cleaned up.
6239       AddToWorkList(Token.getNode());
6240
6241       // Don't add users to work list.
6242       return CombineTo(N, Token, false);
6243     }
6244   }
6245
6246   // Try transforming N to an indexed store.
6247   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6248     return SDValue(N, 0);
6249
6250   // FIXME: is there such a thing as a truncating indexed store?
6251   if (ST->isTruncatingStore() && ST->isUnindexed() &&
6252       Value.getValueType().isInteger()) {
6253     // See if we can simplify the input to this truncstore with knowledge that
6254     // only the low bits are being used.  For example:
6255     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
6256     SDValue Shorter =
6257       GetDemandedBits(Value,
6258                       APInt::getLowBitsSet(Value.getValueSizeInBits(),
6259                                            ST->getMemoryVT().getSizeInBits()));
6260     AddToWorkList(Value.getNode());
6261     if (Shorter.getNode())
6262       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6263                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6264                                ST->isVolatile(), ST->isNonTemporal(),
6265                                ST->getAlignment());
6266
6267     // Otherwise, see if we can simplify the operation with
6268     // SimplifyDemandedBits, which only works if the value has a single use.
6269     if (SimplifyDemandedBits(Value,
6270                         APInt::getLowBitsSet(
6271                           Value.getValueType().getScalarType().getSizeInBits(),
6272                           ST->getMemoryVT().getScalarType().getSizeInBits())))
6273       return SDValue(N, 0);
6274   }
6275
6276   // If this is a load followed by a store to the same location, then the store
6277   // is dead/noop.
6278   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6279     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6280         ST->isUnindexed() && !ST->isVolatile() &&
6281         // There can't be any side effects between the load and store, such as
6282         // a call or store.
6283         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6284       // The store is dead, remove it.
6285       return Chain;
6286     }
6287   }
6288
6289   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6290   // truncating store.  We can do this even if this is already a truncstore.
6291   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6292       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6293       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6294                             ST->getMemoryVT())) {
6295     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6296                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6297                              ST->isVolatile(), ST->isNonTemporal(),
6298                              ST->getAlignment());
6299   }
6300
6301   return ReduceLoadOpStoreWidth(N);
6302 }
6303
6304 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6305   SDValue InVec = N->getOperand(0);
6306   SDValue InVal = N->getOperand(1);
6307   SDValue EltNo = N->getOperand(2);
6308
6309   // If the inserted element is an UNDEF, just use the input vector.
6310   if (InVal.getOpcode() == ISD::UNDEF)
6311     return InVec;
6312
6313   // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
6314   // vector with the inserted element.
6315   if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
6316     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6317     SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
6318                                 InVec.getNode()->op_end());
6319     if (Elt < Ops.size())
6320       Ops[Elt] = InVal;
6321     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6322                        InVec.getValueType(), &Ops[0], Ops.size());
6323   }
6324   // If the invec is an UNDEF and if EltNo is a constant, create a new
6325   // BUILD_VECTOR with undef elements and the inserted element.
6326   if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
6327       isa<ConstantSDNode>(EltNo)) {
6328     EVT VT = InVec.getValueType();
6329     EVT EltVT = VT.getVectorElementType();
6330     unsigned NElts = VT.getVectorNumElements();
6331     SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
6332
6333     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6334     if (Elt < Ops.size())
6335       Ops[Elt] = InVal;
6336     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6337                        InVec.getValueType(), &Ops[0], Ops.size());
6338   }
6339   return SDValue();
6340 }
6341
6342 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6343   // (vextract (scalar_to_vector val, 0) -> val
6344   SDValue InVec = N->getOperand(0);
6345
6346  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6347    // Check if the result type doesn't match the inserted element type. A
6348    // SCALAR_TO_VECTOR may truncate the inserted element and the
6349    // EXTRACT_VECTOR_ELT may widen the extracted vector.
6350    SDValue InOp = InVec.getOperand(0);
6351    EVT NVT = N->getValueType(0);
6352    if (InOp.getValueType() != NVT) {
6353      assert(InOp.getValueType().isInteger() && NVT.isInteger());
6354      return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6355    }
6356    return InOp;
6357  }
6358
6359   // Perform only after legalization to ensure build_vector / vector_shuffle
6360   // optimizations have already been done.
6361   if (!LegalOperations) return SDValue();
6362
6363   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6364   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6365   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6366   SDValue EltNo = N->getOperand(1);
6367
6368   if (isa<ConstantSDNode>(EltNo)) {
6369     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6370     bool NewLoad = false;
6371     bool BCNumEltsChanged = false;
6372     EVT VT = InVec.getValueType();
6373     EVT ExtVT = VT.getVectorElementType();
6374     EVT LVT = ExtVT;
6375
6376     if (InVec.getOpcode() == ISD::BITCAST) {
6377       EVT BCVT = InVec.getOperand(0).getValueType();
6378       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6379         return SDValue();
6380       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6381         BCNumEltsChanged = true;
6382       InVec = InVec.getOperand(0);
6383       ExtVT = BCVT.getVectorElementType();
6384       NewLoad = true;
6385     }
6386
6387     LoadSDNode *LN0 = NULL;
6388     const ShuffleVectorSDNode *SVN = NULL;
6389     if (ISD::isNormalLoad(InVec.getNode())) {
6390       LN0 = cast<LoadSDNode>(InVec);
6391     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6392                InVec.getOperand(0).getValueType() == ExtVT &&
6393                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6394       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6395     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6396       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6397       // =>
6398       // (load $addr+1*size)
6399
6400       // If the bit convert changed the number of elements, it is unsafe
6401       // to examine the mask.
6402       if (BCNumEltsChanged)
6403         return SDValue();
6404
6405       // Select the input vector, guarding against out of range extract vector.
6406       unsigned NumElems = VT.getVectorNumElements();
6407       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6408       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6409
6410       if (InVec.getOpcode() == ISD::BITCAST)
6411         InVec = InVec.getOperand(0);
6412       if (ISD::isNormalLoad(InVec.getNode())) {
6413         LN0 = cast<LoadSDNode>(InVec);
6414         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6415       }
6416     }
6417
6418     if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6419       return SDValue();
6420
6421     // If Idx was -1 above, Elt is going to be -1, so just return undef.
6422     if (Elt == -1)
6423       return DAG.getUNDEF(LN0->getBasePtr().getValueType());
6424
6425     unsigned Align = LN0->getAlignment();
6426     if (NewLoad) {
6427       // Check the resultant load doesn't need a higher alignment than the
6428       // original load.
6429       unsigned NewAlign =
6430         TLI.getTargetData()
6431             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6432
6433       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6434         return SDValue();
6435
6436       Align = NewAlign;
6437     }
6438
6439     SDValue NewPtr = LN0->getBasePtr();
6440     unsigned PtrOff = 0;
6441
6442     if (Elt) {
6443       PtrOff = LVT.getSizeInBits() * Elt / 8;
6444       EVT PtrType = NewPtr.getValueType();
6445       if (TLI.isBigEndian())
6446         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6447       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6448                            DAG.getConstant(PtrOff, PtrType));
6449     }
6450
6451     return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6452                        LN0->getPointerInfo().getWithOffset(PtrOff),
6453                        LN0->isVolatile(), LN0->isNonTemporal(), Align);
6454   }
6455
6456   return SDValue();
6457 }
6458
6459 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6460   unsigned NumInScalars = N->getNumOperands();
6461   EVT VT = N->getValueType(0);
6462
6463   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6464   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6465   // at most two distinct vectors, turn this into a shuffle node.
6466   SDValue VecIn1, VecIn2;
6467   for (unsigned i = 0; i != NumInScalars; ++i) {
6468     // Ignore undef inputs.
6469     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6470
6471     // If this input is something other than a EXTRACT_VECTOR_ELT with a
6472     // constant index, bail out.
6473     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6474         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6475       VecIn1 = VecIn2 = SDValue(0, 0);
6476       break;
6477     }
6478
6479     // If the input vector type disagrees with the result of the build_vector,
6480     // we can't make a shuffle.
6481     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6482     if (ExtractedFromVec.getValueType() != VT) {
6483       VecIn1 = VecIn2 = SDValue(0, 0);
6484       break;
6485     }
6486
6487     // Otherwise, remember this.  We allow up to two distinct input vectors.
6488     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6489       continue;
6490
6491     if (VecIn1.getNode() == 0) {
6492       VecIn1 = ExtractedFromVec;
6493     } else if (VecIn2.getNode() == 0) {
6494       VecIn2 = ExtractedFromVec;
6495     } else {
6496       // Too many inputs.
6497       VecIn1 = VecIn2 = SDValue(0, 0);
6498       break;
6499     }
6500   }
6501
6502   // If everything is good, we can make a shuffle operation.
6503   if (VecIn1.getNode()) {
6504     SmallVector<int, 8> Mask;
6505     for (unsigned i = 0; i != NumInScalars; ++i) {
6506       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6507         Mask.push_back(-1);
6508         continue;
6509       }
6510
6511       // If extracting from the first vector, just use the index directly.
6512       SDValue Extract = N->getOperand(i);
6513       SDValue ExtVal = Extract.getOperand(1);
6514       if (Extract.getOperand(0) == VecIn1) {
6515         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6516         if (ExtIndex > VT.getVectorNumElements())
6517           return SDValue();
6518
6519         Mask.push_back(ExtIndex);
6520         continue;
6521       }
6522
6523       // Otherwise, use InIdx + VecSize
6524       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6525       Mask.push_back(Idx+NumInScalars);
6526     }
6527
6528     // Add count and size info.
6529     if (!isTypeLegal(VT))
6530       return SDValue();
6531
6532     // Return the new VECTOR_SHUFFLE node.
6533     SDValue Ops[2];
6534     Ops[0] = VecIn1;
6535     Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6536     return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6537   }
6538
6539   return SDValue();
6540 }
6541
6542 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6543   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6544   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
6545   // inputs come from at most two distinct vectors, turn this into a shuffle
6546   // node.
6547
6548   // If we only have one input vector, we don't need to do any concatenation.
6549   if (N->getNumOperands() == 1)
6550     return N->getOperand(0);
6551
6552   return SDValue();
6553 }
6554
6555 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6556   EVT VT = N->getValueType(0);
6557   unsigned NumElts = VT.getVectorNumElements();
6558
6559   SDValue N0 = N->getOperand(0);
6560
6561   assert(N0.getValueType().getVectorNumElements() == NumElts &&
6562         "Vector shuffle must be normalized in DAG");
6563
6564   // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6565
6566   // If it is a splat, check if the argument vector is another splat or a
6567   // build_vector with all scalar elements the same.
6568   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6569   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
6570     SDNode *V = N0.getNode();
6571
6572     // If this is a bit convert that changes the element type of the vector but
6573     // not the number of vector elements, look through it.  Be careful not to
6574     // look though conversions that change things like v4f32 to v2f64.
6575     if (V->getOpcode() == ISD::BITCAST) {
6576       SDValue ConvInput = V->getOperand(0);
6577       if (ConvInput.getValueType().isVector() &&
6578           ConvInput.getValueType().getVectorNumElements() == NumElts)
6579         V = ConvInput.getNode();
6580     }
6581
6582     if (V->getOpcode() == ISD::BUILD_VECTOR) {
6583       assert(V->getNumOperands() == NumElts &&
6584              "BUILD_VECTOR has wrong number of operands");
6585       SDValue Base;
6586       bool AllSame = true;
6587       for (unsigned i = 0; i != NumElts; ++i) {
6588         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6589           Base = V->getOperand(i);
6590           break;
6591         }
6592       }
6593       // Splat of <u, u, u, u>, return <u, u, u, u>
6594       if (!Base.getNode())
6595         return N0;
6596       for (unsigned i = 0; i != NumElts; ++i) {
6597         if (V->getOperand(i) != Base) {
6598           AllSame = false;
6599           break;
6600         }
6601       }
6602       // Splat of <x, x, x, x>, return <x, x, x, x>
6603       if (AllSame)
6604         return N0;
6605     }
6606   }
6607   return SDValue();
6608 }
6609
6610 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
6611   if (!TLI.getShouldFoldAtomicFences())
6612     return SDValue();
6613
6614   SDValue atomic = N->getOperand(0);
6615   switch (atomic.getOpcode()) {
6616     case ISD::ATOMIC_CMP_SWAP:
6617     case ISD::ATOMIC_SWAP:
6618     case ISD::ATOMIC_LOAD_ADD:
6619     case ISD::ATOMIC_LOAD_SUB:
6620     case ISD::ATOMIC_LOAD_AND:
6621     case ISD::ATOMIC_LOAD_OR:
6622     case ISD::ATOMIC_LOAD_XOR:
6623     case ISD::ATOMIC_LOAD_NAND:
6624     case ISD::ATOMIC_LOAD_MIN:
6625     case ISD::ATOMIC_LOAD_MAX:
6626     case ISD::ATOMIC_LOAD_UMIN:
6627     case ISD::ATOMIC_LOAD_UMAX:
6628       break;
6629     default:
6630       return SDValue();
6631   }
6632
6633   SDValue fence = atomic.getOperand(0);
6634   if (fence.getOpcode() != ISD::MEMBARRIER)
6635     return SDValue();
6636
6637   switch (atomic.getOpcode()) {
6638     case ISD::ATOMIC_CMP_SWAP:
6639       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6640                                     fence.getOperand(0),
6641                                     atomic.getOperand(1), atomic.getOperand(2),
6642                                     atomic.getOperand(3)), atomic.getResNo());
6643     case ISD::ATOMIC_SWAP:
6644     case ISD::ATOMIC_LOAD_ADD:
6645     case ISD::ATOMIC_LOAD_SUB:
6646     case ISD::ATOMIC_LOAD_AND:
6647     case ISD::ATOMIC_LOAD_OR:
6648     case ISD::ATOMIC_LOAD_XOR:
6649     case ISD::ATOMIC_LOAD_NAND:
6650     case ISD::ATOMIC_LOAD_MIN:
6651     case ISD::ATOMIC_LOAD_MAX:
6652     case ISD::ATOMIC_LOAD_UMIN:
6653     case ISD::ATOMIC_LOAD_UMAX:
6654       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6655                                     fence.getOperand(0),
6656                                     atomic.getOperand(1), atomic.getOperand(2)),
6657                      atomic.getResNo());
6658     default:
6659       return SDValue();
6660   }
6661 }
6662
6663 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6664 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6665 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6666 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
6667 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6668   EVT VT = N->getValueType(0);
6669   DebugLoc dl = N->getDebugLoc();
6670   SDValue LHS = N->getOperand(0);
6671   SDValue RHS = N->getOperand(1);
6672   if (N->getOpcode() == ISD::AND) {
6673     if (RHS.getOpcode() == ISD::BITCAST)
6674       RHS = RHS.getOperand(0);
6675     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6676       SmallVector<int, 8> Indices;
6677       unsigned NumElts = RHS.getNumOperands();
6678       for (unsigned i = 0; i != NumElts; ++i) {
6679         SDValue Elt = RHS.getOperand(i);
6680         if (!isa<ConstantSDNode>(Elt))
6681           return SDValue();
6682         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6683           Indices.push_back(i);
6684         else if (cast<ConstantSDNode>(Elt)->isNullValue())
6685           Indices.push_back(NumElts);
6686         else
6687           return SDValue();
6688       }
6689
6690       // Let's see if the target supports this vector_shuffle.
6691       EVT RVT = RHS.getValueType();
6692       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6693         return SDValue();
6694
6695       // Return the new VECTOR_SHUFFLE node.
6696       EVT EltVT = RVT.getVectorElementType();
6697       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6698                                      DAG.getConstant(0, EltVT));
6699       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6700                                  RVT, &ZeroOps[0], ZeroOps.size());
6701       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
6702       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6703       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
6704     }
6705   }
6706
6707   return SDValue();
6708 }
6709
6710 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6711 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6712   // After legalize, the target may be depending on adds and other
6713   // binary ops to provide legal ways to construct constants or other
6714   // things. Simplifying them may result in a loss of legality.
6715   if (LegalOperations) return SDValue();
6716
6717   assert(N->getValueType(0).isVector() &&
6718          "SimplifyVBinOp only works on vectors!");
6719
6720   SDValue LHS = N->getOperand(0);
6721   SDValue RHS = N->getOperand(1);
6722   SDValue Shuffle = XformToShuffleWithZero(N);
6723   if (Shuffle.getNode()) return Shuffle;
6724
6725   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6726   // this operation.
6727   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6728       RHS.getOpcode() == ISD::BUILD_VECTOR) {
6729     SmallVector<SDValue, 8> Ops;
6730     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6731       SDValue LHSOp = LHS.getOperand(i);
6732       SDValue RHSOp = RHS.getOperand(i);
6733       // If these two elements can't be folded, bail out.
6734       if ((LHSOp.getOpcode() != ISD::UNDEF &&
6735            LHSOp.getOpcode() != ISD::Constant &&
6736            LHSOp.getOpcode() != ISD::ConstantFP) ||
6737           (RHSOp.getOpcode() != ISD::UNDEF &&
6738            RHSOp.getOpcode() != ISD::Constant &&
6739            RHSOp.getOpcode() != ISD::ConstantFP))
6740         break;
6741
6742       // Can't fold divide by zero.
6743       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6744           N->getOpcode() == ISD::FDIV) {
6745         if ((RHSOp.getOpcode() == ISD::Constant &&
6746              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6747             (RHSOp.getOpcode() == ISD::ConstantFP &&
6748              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6749           break;
6750       }
6751
6752       EVT VT = LHSOp.getValueType();
6753       assert(RHSOp.getValueType() == VT &&
6754              "SimplifyVBinOp with different BUILD_VECTOR element types");
6755       SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
6756                                    LHSOp, RHSOp);
6757       if (FoldOp.getOpcode() != ISD::UNDEF &&
6758           FoldOp.getOpcode() != ISD::Constant &&
6759           FoldOp.getOpcode() != ISD::ConstantFP)
6760         break;
6761       Ops.push_back(FoldOp);
6762       AddToWorkList(FoldOp.getNode());
6763     }
6764
6765     if (Ops.size() == LHS.getNumOperands())
6766       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6767                          LHS.getValueType(), &Ops[0], Ops.size());
6768   }
6769
6770   return SDValue();
6771 }
6772
6773 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6774                                     SDValue N1, SDValue N2){
6775   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6776
6777   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6778                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
6779
6780   // If we got a simplified select_cc node back from SimplifySelectCC, then
6781   // break it down into a new SETCC node, and a new SELECT node, and then return
6782   // the SELECT node, since we were called with a SELECT node.
6783   if (SCC.getNode()) {
6784     // Check to see if we got a select_cc back (to turn into setcc/select).
6785     // Otherwise, just return whatever node we got back, like fabs.
6786     if (SCC.getOpcode() == ISD::SELECT_CC) {
6787       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6788                                   N0.getValueType(),
6789                                   SCC.getOperand(0), SCC.getOperand(1),
6790                                   SCC.getOperand(4));
6791       AddToWorkList(SETCC.getNode());
6792       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6793                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
6794     }
6795
6796     return SCC;
6797   }
6798   return SDValue();
6799 }
6800
6801 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6802 /// are the two values being selected between, see if we can simplify the
6803 /// select.  Callers of this should assume that TheSelect is deleted if this
6804 /// returns true.  As such, they should return the appropriate thing (e.g. the
6805 /// node) back to the top-level of the DAG combiner loop to avoid it being
6806 /// looked at.
6807 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6808                                     SDValue RHS) {
6809
6810   // If this is a select from two identical things, try to pull the operation
6811   // through the select.
6812   if (LHS.getOpcode() != RHS.getOpcode() ||
6813       !LHS.hasOneUse() || !RHS.hasOneUse())
6814     return false;
6815
6816   // If this is a load and the token chain is identical, replace the select
6817   // of two loads with a load through a select of the address to load from.
6818   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6819   // constants have been dropped into the constant pool.
6820   if (LHS.getOpcode() == ISD::LOAD) {
6821     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6822     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6823
6824     // Token chains must be identical.
6825     if (LHS.getOperand(0) != RHS.getOperand(0) ||
6826         // Do not let this transformation reduce the number of volatile loads.
6827         LLD->isVolatile() || RLD->isVolatile() ||
6828         // If this is an EXTLOAD, the VT's must match.
6829         LLD->getMemoryVT() != RLD->getMemoryVT() ||
6830         // If this is an EXTLOAD, the kind of extension must match.
6831         (LLD->getExtensionType() != RLD->getExtensionType() &&
6832          // The only exception is if one of the extensions is anyext.
6833          LLD->getExtensionType() != ISD::EXTLOAD &&
6834          RLD->getExtensionType() != ISD::EXTLOAD) ||
6835         // FIXME: this discards src value information.  This is
6836         // over-conservative. It would be beneficial to be able to remember
6837         // both potential memory locations.  Since we are discarding
6838         // src value info, don't do the transformation if the memory
6839         // locations are not in the default address space.
6840         LLD->getPointerInfo().getAddrSpace() != 0 ||
6841         RLD->getPointerInfo().getAddrSpace() != 0)
6842       return false;
6843
6844     // Check that the select condition doesn't reach either load.  If so,
6845     // folding this will induce a cycle into the DAG.  If not, this is safe to
6846     // xform, so create a select of the addresses.
6847     SDValue Addr;
6848     if (TheSelect->getOpcode() == ISD::SELECT) {
6849       SDNode *CondNode = TheSelect->getOperand(0).getNode();
6850       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
6851           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
6852         return false;
6853       Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6854                          LLD->getBasePtr().getValueType(),
6855                          TheSelect->getOperand(0), LLD->getBasePtr(),
6856                          RLD->getBasePtr());
6857     } else {  // Otherwise SELECT_CC
6858       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
6859       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
6860
6861       if ((LLD->hasAnyUseOfValue(1) &&
6862            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
6863           (LLD->hasAnyUseOfValue(1) &&
6864            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
6865         return false;
6866
6867       Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6868                          LLD->getBasePtr().getValueType(),
6869                          TheSelect->getOperand(0),
6870                          TheSelect->getOperand(1),
6871                          LLD->getBasePtr(), RLD->getBasePtr(),
6872                          TheSelect->getOperand(4));
6873     }
6874
6875     SDValue Load;
6876     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6877       Load = DAG.getLoad(TheSelect->getValueType(0),
6878                          TheSelect->getDebugLoc(),
6879                          // FIXME: Discards pointer info.
6880                          LLD->getChain(), Addr, MachinePointerInfo(),
6881                          LLD->isVolatile(), LLD->isNonTemporal(),
6882                          LLD->getAlignment());
6883     } else {
6884       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
6885                             RLD->getExtensionType() : LLD->getExtensionType(),
6886                             TheSelect->getValueType(0),
6887                             TheSelect->getDebugLoc(),
6888                             // FIXME: Discards pointer info.
6889                             LLD->getChain(), Addr, MachinePointerInfo(),
6890                             LLD->getMemoryVT(), LLD->isVolatile(),
6891                             LLD->isNonTemporal(), LLD->getAlignment());
6892     }
6893
6894     // Users of the select now use the result of the load.
6895     CombineTo(TheSelect, Load);
6896
6897     // Users of the old loads now use the new load's chain.  We know the
6898     // old-load value is dead now.
6899     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6900     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6901     return true;
6902   }
6903
6904   return false;
6905 }
6906
6907 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6908 /// where 'cond' is the comparison specified by CC.
6909 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6910                                       SDValue N2, SDValue N3,
6911                                       ISD::CondCode CC, bool NotExtCompare) {
6912   // (x ? y : y) -> y.
6913   if (N2 == N3) return N2;
6914
6915   EVT VT = N2.getValueType();
6916   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6917   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6918   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6919
6920   // Determine if the condition we're dealing with is constant
6921   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6922                               N0, N1, CC, DL, false);
6923   if (SCC.getNode()) AddToWorkList(SCC.getNode());
6924   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6925
6926   // fold select_cc true, x, y -> x
6927   if (SCCC && !SCCC->isNullValue())
6928     return N2;
6929   // fold select_cc false, x, y -> y
6930   if (SCCC && SCCC->isNullValue())
6931     return N3;
6932
6933   // Check to see if we can simplify the select into an fabs node
6934   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
6935     // Allow either -0.0 or 0.0
6936     if (CFP->getValueAPF().isZero()) {
6937       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
6938       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
6939           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
6940           N2 == N3.getOperand(0))
6941         return DAG.getNode(ISD::FABS, DL, VT, N0);
6942
6943       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
6944       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
6945           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
6946           N2.getOperand(0) == N3)
6947         return DAG.getNode(ISD::FABS, DL, VT, N3);
6948     }
6949   }
6950
6951   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
6952   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
6953   // in it.  This is a win when the constant is not otherwise available because
6954   // it replaces two constant pool loads with one.  We only do this if the FP
6955   // type is known to be legal, because if it isn't, then we are before legalize
6956   // types an we want the other legalization to happen first (e.g. to avoid
6957   // messing with soft float) and if the ConstantFP is not legal, because if
6958   // it is legal, we may not need to store the FP constant in a constant pool.
6959   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
6960     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
6961       if (TLI.isTypeLegal(N2.getValueType()) &&
6962           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
6963            TargetLowering::Legal) &&
6964           // If both constants have multiple uses, then we won't need to do an
6965           // extra load, they are likely around in registers for other users.
6966           (TV->hasOneUse() || FV->hasOneUse())) {
6967         Constant *Elts[] = {
6968           const_cast<ConstantFP*>(FV->getConstantFPValue()),
6969           const_cast<ConstantFP*>(TV->getConstantFPValue())
6970         };
6971         const Type *FPTy = Elts[0]->getType();
6972         const TargetData &TD = *TLI.getTargetData();
6973
6974         // Create a ConstantArray of the two constants.
6975         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
6976         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
6977                                             TD.getPrefTypeAlignment(FPTy));
6978         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6979
6980         // Get the offsets to the 0 and 1 element of the array so that we can
6981         // select between them.
6982         SDValue Zero = DAG.getIntPtrConstant(0);
6983         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
6984         SDValue One = DAG.getIntPtrConstant(EltSize);
6985
6986         SDValue Cond = DAG.getSetCC(DL,
6987                                     TLI.getSetCCResultType(N0.getValueType()),
6988                                     N0, N1, CC);
6989         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
6990                                         Cond, One, Zero);
6991         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
6992                             CstOffset);
6993         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6994                            MachinePointerInfo::getConstantPool(), false,
6995                            false, Alignment);
6996
6997       }
6998     }
6999
7000   // Check to see if we can perform the "gzip trick", transforming
7001   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
7002   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
7003       N0.getValueType().isInteger() &&
7004       N2.getValueType().isInteger() &&
7005       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
7006        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
7007     EVT XType = N0.getValueType();
7008     EVT AType = N2.getValueType();
7009     if (XType.bitsGE(AType)) {
7010       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
7011       // single-bit constant.
7012       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
7013         unsigned ShCtV = N2C->getAPIntValue().logBase2();
7014         ShCtV = XType.getSizeInBits()-ShCtV-1;
7015         SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
7016         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
7017                                     XType, N0, ShCt);
7018         AddToWorkList(Shift.getNode());
7019
7020         if (XType.bitsGT(AType)) {
7021           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7022           AddToWorkList(Shift.getNode());
7023         }
7024
7025         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7026       }
7027
7028       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
7029                                   XType, N0,
7030                                   DAG.getConstant(XType.getSizeInBits()-1,
7031                                                   getShiftAmountTy()));
7032       AddToWorkList(Shift.getNode());
7033
7034       if (XType.bitsGT(AType)) {
7035         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7036         AddToWorkList(Shift.getNode());
7037       }
7038
7039       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7040     }
7041   }
7042
7043   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
7044   // where y is has a single bit set.
7045   // A plaintext description would be, we can turn the SELECT_CC into an AND
7046   // when the condition can be materialized as an all-ones register.  Any
7047   // single bit-test can be materialized as an all-ones register with
7048   // shift-left and shift-right-arith.
7049   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
7050       N0->getValueType(0) == VT &&
7051       N1C && N1C->isNullValue() &&
7052       N2C && N2C->isNullValue()) {
7053     SDValue AndLHS = N0->getOperand(0);
7054     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7055     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
7056       // Shift the tested bit over the sign bit.
7057       APInt AndMask = ConstAndRHS->getAPIntValue();
7058       SDValue ShlAmt =
7059         DAG.getConstant(AndMask.countLeadingZeros(), getShiftAmountTy());
7060       SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
7061
7062       // Now arithmetic right shift it all the way over, so the result is either
7063       // all-ones, or zero.
7064       SDValue ShrAmt =
7065         DAG.getConstant(AndMask.getBitWidth()-1, getShiftAmountTy());
7066       SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
7067
7068       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
7069     }
7070   }
7071
7072   // fold select C, 16, 0 -> shl C, 4
7073   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
7074       TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
7075
7076     // If the caller doesn't want us to simplify this into a zext of a compare,
7077     // don't do it.
7078     if (NotExtCompare && N2C->getAPIntValue() == 1)
7079       return SDValue();
7080
7081     // Get a SetCC of the condition
7082     // FIXME: Should probably make sure that setcc is legal if we ever have a
7083     // target where it isn't.
7084     SDValue Temp, SCC;
7085     // cast from setcc result type to select result type
7086     if (LegalTypes) {
7087       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
7088                           N0, N1, CC);
7089       if (N2.getValueType().bitsLT(SCC.getValueType()))
7090         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
7091       else
7092         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7093                            N2.getValueType(), SCC);
7094     } else {
7095       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
7096       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7097                          N2.getValueType(), SCC);
7098     }
7099
7100     AddToWorkList(SCC.getNode());
7101     AddToWorkList(Temp.getNode());
7102
7103     if (N2C->getAPIntValue() == 1)
7104       return Temp;
7105
7106     // shl setcc result by log2 n2c
7107     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
7108                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
7109                                        getShiftAmountTy()));
7110   }
7111
7112   // Check to see if this is the equivalent of setcc
7113   // FIXME: Turn all of these into setcc if setcc if setcc is legal
7114   // otherwise, go ahead with the folds.
7115   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
7116     EVT XType = N0.getValueType();
7117     if (!LegalOperations ||
7118         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
7119       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
7120       if (Res.getValueType() != VT)
7121         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
7122       return Res;
7123     }
7124
7125     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
7126     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
7127         (!LegalOperations ||
7128          TLI.isOperationLegal(ISD::CTLZ, XType))) {
7129       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
7130       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
7131                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
7132                                          getShiftAmountTy()));
7133     }
7134     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
7135     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
7136       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
7137                                   XType, DAG.getConstant(0, XType), N0);
7138       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
7139       return DAG.getNode(ISD::SRL, DL, XType,
7140                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
7141                          DAG.getConstant(XType.getSizeInBits()-1,
7142                                          getShiftAmountTy()));
7143     }
7144     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
7145     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
7146       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
7147                                  DAG.getConstant(XType.getSizeInBits()-1,
7148                                                  getShiftAmountTy()));
7149       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
7150     }
7151   }
7152
7153   // Check to see if this is an integer abs.
7154   // select_cc setg[te] X,  0,  X, -X ->
7155   // select_cc setgt    X, -1,  X, -X ->
7156   // select_cc setl[te] X,  0, -X,  X ->
7157   // select_cc setlt    X,  1, -X,  X ->
7158   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7159   if (N1C) {
7160     ConstantSDNode *SubC = NULL;
7161     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7162          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
7163         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
7164       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
7165     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
7166               (N1C->isOne() && CC == ISD::SETLT)) &&
7167              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
7168       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
7169
7170     EVT XType = N0.getValueType();
7171     if (SubC && SubC->isNullValue() && XType.isInteger()) {
7172       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
7173                                   N0,
7174                                   DAG.getConstant(XType.getSizeInBits()-1,
7175                                                   getShiftAmountTy()));
7176       SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7177                                 XType, N0, Shift);
7178       AddToWorkList(Shift.getNode());
7179       AddToWorkList(Add.getNode());
7180       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7181     }
7182   }
7183
7184   return SDValue();
7185 }
7186
7187 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7188 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7189                                    SDValue N1, ISD::CondCode Cond,
7190                                    DebugLoc DL, bool foldBooleans) {
7191   TargetLowering::DAGCombinerInfo
7192     DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7193   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7194 }
7195
7196 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7197 /// return a DAG expression to select that will generate the same value by
7198 /// multiplying by a magic number.  See:
7199 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7200 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7201   std::vector<SDNode*> Built;
7202   SDValue S = TLI.BuildSDIV(N, DAG, &Built);
7203
7204   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7205        ii != ee; ++ii)
7206     AddToWorkList(*ii);
7207   return S;
7208 }
7209
7210 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7211 /// return a DAG expression to select that will generate the same value by
7212 /// multiplying by a magic number.  See:
7213 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7214 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7215   std::vector<SDNode*> Built;
7216   SDValue S = TLI.BuildUDIV(N, DAG, &Built);
7217
7218   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7219        ii != ee; ++ii)
7220     AddToWorkList(*ii);
7221   return S;
7222 }
7223
7224 /// FindBaseOffset - Return true if base is a frame index, which is known not
7225 // to alias with anything but itself.  Provides base object and offset as
7226 // results.
7227 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7228                            const GlobalValue *&GV, void *&CV) {
7229   // Assume it is a primitive operation.
7230   Base = Ptr; Offset = 0; GV = 0; CV = 0;
7231
7232   // If it's an adding a simple constant then integrate the offset.
7233   if (Base.getOpcode() == ISD::ADD) {
7234     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7235       Base = Base.getOperand(0);
7236       Offset += C->getZExtValue();
7237     }
7238   }
7239
7240   // Return the underlying GlobalValue, and update the Offset.  Return false
7241   // for GlobalAddressSDNode since the same GlobalAddress may be represented
7242   // by multiple nodes with different offsets.
7243   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7244     GV = G->getGlobal();
7245     Offset += G->getOffset();
7246     return false;
7247   }
7248
7249   // Return the underlying Constant value, and update the Offset.  Return false
7250   // for ConstantSDNodes since the same constant pool entry may be represented
7251   // by multiple nodes with different offsets.
7252   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7253     CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7254                                          : (void *)C->getConstVal();
7255     Offset += C->getOffset();
7256     return false;
7257   }
7258   // If it's any of the following then it can't alias with anything but itself.
7259   return isa<FrameIndexSDNode>(Base);
7260 }
7261
7262 /// isAlias - Return true if there is any possibility that the two addresses
7263 /// overlap.
7264 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7265                           const Value *SrcValue1, int SrcValueOffset1,
7266                           unsigned SrcValueAlign1,
7267                           const MDNode *TBAAInfo1,
7268                           SDValue Ptr2, int64_t Size2,
7269                           const Value *SrcValue2, int SrcValueOffset2,
7270                           unsigned SrcValueAlign2,
7271                           const MDNode *TBAAInfo2) const {
7272   // If they are the same then they must be aliases.
7273   if (Ptr1 == Ptr2) return true;
7274
7275   // Gather base node and offset information.
7276   SDValue Base1, Base2;
7277   int64_t Offset1, Offset2;
7278   const GlobalValue *GV1, *GV2;
7279   void *CV1, *CV2;
7280   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7281   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7282
7283   // If they have a same base address then check to see if they overlap.
7284   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7285     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7286
7287   // It is possible for different frame indices to alias each other, mostly
7288   // when tail call optimization reuses return address slots for arguments.
7289   // To catch this case, look up the actual index of frame indices to compute
7290   // the real alias relationship.
7291   if (isFrameIndex1 && isFrameIndex2) {
7292     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7293     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7294     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7295     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7296   }
7297
7298   // Otherwise, if we know what the bases are, and they aren't identical, then
7299   // we know they cannot alias.
7300   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7301     return false;
7302
7303   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7304   // compared to the size and offset of the access, we may be able to prove they
7305   // do not alias.  This check is conservative for now to catch cases created by
7306   // splitting vector types.
7307   if ((SrcValueAlign1 == SrcValueAlign2) &&
7308       (SrcValueOffset1 != SrcValueOffset2) &&
7309       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
7310     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
7311     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
7312
7313     // There is no overlap between these relatively aligned accesses of similar
7314     // size, return no alias.
7315     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
7316       return false;
7317   }
7318
7319   if (CombinerGlobalAA) {
7320     // Use alias analysis information.
7321     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
7322     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
7323     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
7324     AliasAnalysis::AliasResult AAResult =
7325       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
7326                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
7327     if (AAResult == AliasAnalysis::NoAlias)
7328       return false;
7329   }
7330
7331   // Otherwise we have to assume they alias.
7332   return true;
7333 }
7334
7335 /// FindAliasInfo - Extracts the relevant alias information from the memory
7336 /// node.  Returns true if the operand was a load.
7337 bool DAGCombiner::FindAliasInfo(SDNode *N,
7338                         SDValue &Ptr, int64_t &Size,
7339                         const Value *&SrcValue,
7340                         int &SrcValueOffset,
7341                         unsigned &SrcValueAlign,
7342                         const MDNode *&TBAAInfo) const {
7343   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7344     Ptr = LD->getBasePtr();
7345     Size = LD->getMemoryVT().getSizeInBits() >> 3;
7346     SrcValue = LD->getSrcValue();
7347     SrcValueOffset = LD->getSrcValueOffset();
7348     SrcValueAlign = LD->getOriginalAlignment();
7349     TBAAInfo = LD->getTBAAInfo();
7350     return true;
7351   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7352     Ptr = ST->getBasePtr();
7353     Size = ST->getMemoryVT().getSizeInBits() >> 3;
7354     SrcValue = ST->getSrcValue();
7355     SrcValueOffset = ST->getSrcValueOffset();
7356     SrcValueAlign = ST->getOriginalAlignment();
7357     TBAAInfo = ST->getTBAAInfo();
7358   } else {
7359     llvm_unreachable("FindAliasInfo expected a memory operand");
7360   }
7361
7362   return false;
7363 }
7364
7365 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
7366 /// looking for aliasing nodes and adding them to the Aliases vector.
7367 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
7368                                    SmallVector<SDValue, 8> &Aliases) {
7369   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
7370   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
7371
7372   // Get alias information for node.
7373   SDValue Ptr;
7374   int64_t Size;
7375   const Value *SrcValue;
7376   int SrcValueOffset;
7377   unsigned SrcValueAlign;
7378   const MDNode *SrcTBAAInfo;
7379   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
7380                               SrcValueAlign, SrcTBAAInfo);
7381
7382   // Starting off.
7383   Chains.push_back(OriginalChain);
7384   unsigned Depth = 0;
7385
7386   // Look at each chain and determine if it is an alias.  If so, add it to the
7387   // aliases list.  If not, then continue up the chain looking for the next
7388   // candidate.
7389   while (!Chains.empty()) {
7390     SDValue Chain = Chains.back();
7391     Chains.pop_back();
7392
7393     // For TokenFactor nodes, look at each operand and only continue up the
7394     // chain until we find two aliases.  If we've seen two aliases, assume we'll
7395     // find more and revert to original chain since the xform is unlikely to be
7396     // profitable.
7397     //
7398     // FIXME: The depth check could be made to return the last non-aliasing
7399     // chain we found before we hit a tokenfactor rather than the original
7400     // chain.
7401     if (Depth > 6 || Aliases.size() == 2) {
7402       Aliases.clear();
7403       Aliases.push_back(OriginalChain);
7404       break;
7405     }
7406
7407     // Don't bother if we've been before.
7408     if (!Visited.insert(Chain.getNode()))
7409       continue;
7410
7411     switch (Chain.getOpcode()) {
7412     case ISD::EntryToken:
7413       // Entry token is ideal chain operand, but handled in FindBetterChain.
7414       break;
7415
7416     case ISD::LOAD:
7417     case ISD::STORE: {
7418       // Get alias information for Chain.
7419       SDValue OpPtr;
7420       int64_t OpSize;
7421       const Value *OpSrcValue;
7422       int OpSrcValueOffset;
7423       unsigned OpSrcValueAlign;
7424       const MDNode *OpSrcTBAAInfo;
7425       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
7426                                     OpSrcValue, OpSrcValueOffset,
7427                                     OpSrcValueAlign,
7428                                     OpSrcTBAAInfo);
7429
7430       // If chain is alias then stop here.
7431       if (!(IsLoad && IsOpLoad) &&
7432           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
7433                   SrcTBAAInfo,
7434                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
7435                   OpSrcValueAlign, OpSrcTBAAInfo)) {
7436         Aliases.push_back(Chain);
7437       } else {
7438         // Look further up the chain.
7439         Chains.push_back(Chain.getOperand(0));
7440         ++Depth;
7441       }
7442       break;
7443     }
7444
7445     case ISD::TokenFactor:
7446       // We have to check each of the operands of the token factor for "small"
7447       // token factors, so we queue them up.  Adding the operands to the queue
7448       // (stack) in reverse order maintains the original order and increases the
7449       // likelihood that getNode will find a matching token factor (CSE.)
7450       if (Chain.getNumOperands() > 16) {
7451         Aliases.push_back(Chain);
7452         break;
7453       }
7454       for (unsigned n = Chain.getNumOperands(); n;)
7455         Chains.push_back(Chain.getOperand(--n));
7456       ++Depth;
7457       break;
7458
7459     default:
7460       // For all other instructions we will just have to take what we can get.
7461       Aliases.push_back(Chain);
7462       break;
7463     }
7464   }
7465 }
7466
7467 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
7468 /// for a better chain (aliasing node.)
7469 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7470   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
7471
7472   // Accumulate all the aliases to this node.
7473   GatherAllAliases(N, OldChain, Aliases);
7474
7475   if (Aliases.size() == 0) {
7476     // If no operands then chain to entry token.
7477     return DAG.getEntryNode();
7478   } else if (Aliases.size() == 1) {
7479     // If a single operand then chain to it.  We don't need to revisit it.
7480     return Aliases[0];
7481   }
7482
7483   // Construct a custom tailored token factor.
7484   return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7485                      &Aliases[0], Aliases.size());
7486 }
7487
7488 // SelectionDAG::Combine - This is the entry point for the file.
7489 //
7490 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7491                            CodeGenOpt::Level OptLevel) {
7492   /// run - This is the main entry point to this class.
7493   ///
7494   DAGCombiner(*this, AA, OptLevel).Run(Level);
7495 }