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