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