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