ctpop lowering in legalize
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::Legalize method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineConstantPool.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/Constants.h"
22 #include <iostream>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
27 /// hacks on it until the target machine can handle it.  This involves
28 /// eliminating value sizes the machine cannot handle (promoting small sizes to
29 /// large sizes or splitting up large values into small values) as well as
30 /// eliminating operations the machine cannot handle.
31 ///
32 /// This code also does a small amount of optimization and recognition of idioms
33 /// as part of its processing.  For example, if a target does not support a
34 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
35 /// will attempt merge setcc and brc instructions into brcc's.
36 ///
37 namespace {
38 class SelectionDAGLegalize {
39   TargetLowering &TLI;
40   SelectionDAG &DAG;
41
42   /// LegalizeAction - This enum indicates what action we should take for each
43   /// value type the can occur in the program.
44   enum LegalizeAction {
45     Legal,            // The target natively supports this value type.
46     Promote,          // This should be promoted to the next larger type.
47     Expand,           // This integer type should be broken into smaller pieces.
48   };
49
50   /// ValueTypeActions - This is a bitvector that contains two bits for each
51   /// value type, where the two bits correspond to the LegalizeAction enum.
52   /// This can be queried with "getTypeAction(VT)".
53   unsigned ValueTypeActions;
54
55   /// NeedsAnotherIteration - This is set when we expand a large integer
56   /// operation into smaller integer operations, but the smaller operations are
57   /// not set.  This occurs only rarely in practice, for targets that don't have
58   /// 32-bit or larger integer registers.
59   bool NeedsAnotherIteration;
60
61   /// LegalizedNodes - For nodes that are of legal width, and that have more
62   /// than one use, this map indicates what regularized operand to use.  This
63   /// allows us to avoid legalizing the same thing more than once.
64   std::map<SDOperand, SDOperand> LegalizedNodes;
65
66   /// PromotedNodes - For nodes that are below legal width, and that have more
67   /// than one use, this map indicates what promoted value to use.  This allows
68   /// us to avoid promoting the same thing more than once.
69   std::map<SDOperand, SDOperand> PromotedNodes;
70
71   /// ExpandedNodes - For nodes that need to be expanded, and which have more
72   /// than one use, this map indicates which which operands are the expanded
73   /// version of the input.  This allows us to avoid expanding the same node
74   /// more than once.
75   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
76
77   void AddLegalizedOperand(SDOperand From, SDOperand To) {
78     bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
79     assert(isNew && "Got into the map somehow?");
80   }
81   void AddPromotedOperand(SDOperand From, SDOperand To) {
82     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
83     assert(isNew && "Got into the map somehow?");
84   }
85
86 public:
87
88   SelectionDAGLegalize(SelectionDAG &DAG);
89
90   /// Run - While there is still lowering to do, perform a pass over the DAG.
91   /// Most regularization can be done in a single pass, but targets that require
92   /// large values to be split into registers multiple times (e.g. i64 -> 4x
93   /// i16) require iteration for these values (the first iteration will demote
94   /// to i32, the second will demote to i16).
95   void Run() {
96     do {
97       NeedsAnotherIteration = false;
98       LegalizeDAG();
99     } while (NeedsAnotherIteration);
100   }
101
102   /// getTypeAction - Return how we should legalize values of this type, either
103   /// it is already legal or we need to expand it into multiple registers of
104   /// smaller integer type, or we need to promote it to a larger type.
105   LegalizeAction getTypeAction(MVT::ValueType VT) const {
106     return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
107   }
108
109   /// isTypeLegal - Return true if this type is legal on this target.
110   ///
111   bool isTypeLegal(MVT::ValueType VT) const {
112     return getTypeAction(VT) == Legal;
113   }
114
115 private:
116   void LegalizeDAG();
117
118   SDOperand LegalizeOp(SDOperand O);
119   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
120   SDOperand PromoteOp(SDOperand O);
121
122   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
123                           SDOperand &Hi);
124   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
125                           SDOperand Source);
126   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
127                    SDOperand &Lo, SDOperand &Hi);
128   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
129                         SDOperand &Lo, SDOperand &Hi);
130   void ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
131                      SDOperand &Lo, SDOperand &Hi);
132
133   SDOperand getIntPtrConstant(uint64_t Val) {
134     return DAG.getConstant(Val, TLI.getPointerTy());
135   }
136 };
137 }
138
139
140 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
141   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
142     ValueTypeActions(TLI.getValueTypeActions()) {
143   assert(MVT::LAST_VALUETYPE <= 16 &&
144          "Too many value types for ValueTypeActions to hold!");
145 }
146
147 void SelectionDAGLegalize::LegalizeDAG() {
148   SDOperand OldRoot = DAG.getRoot();
149   SDOperand NewRoot = LegalizeOp(OldRoot);
150   DAG.setRoot(NewRoot);
151
152   ExpandedNodes.clear();
153   LegalizedNodes.clear();
154   PromotedNodes.clear();
155
156   // Remove dead nodes now.
157   DAG.RemoveDeadNodes(OldRoot.Val);
158 }
159
160 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
161   assert(getTypeAction(Op.getValueType()) == Legal &&
162          "Caller should expand or promote operands that are not legal!");
163
164   // If this operation defines any values that cannot be represented in a
165   // register on this target, make sure to expand or promote them.
166   if (Op.Val->getNumValues() > 1) {
167     for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
168       switch (getTypeAction(Op.Val->getValueType(i))) {
169       case Legal: break;  // Nothing to do.
170       case Expand: {
171         SDOperand T1, T2;
172         ExpandOp(Op.getValue(i), T1, T2);
173         assert(LegalizedNodes.count(Op) &&
174                "Expansion didn't add legal operands!");
175         return LegalizedNodes[Op];
176       }
177       case Promote:
178         PromoteOp(Op.getValue(i));
179         assert(LegalizedNodes.count(Op) &&
180                "Expansion didn't add legal operands!");
181         return LegalizedNodes[Op];
182       }
183   }
184
185   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
186   if (I != LegalizedNodes.end()) return I->second;
187
188   SDOperand Tmp1, Tmp2, Tmp3;
189
190   SDOperand Result = Op;
191   SDNode *Node = Op.Val;
192
193   switch (Node->getOpcode()) {
194   default:
195     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
196     assert(0 && "Do not know how to legalize this operator!");
197     abort();
198   case ISD::EntryToken:
199   case ISD::FrameIndex:
200   case ISD::GlobalAddress:
201   case ISD::ExternalSymbol:
202   case ISD::ConstantPool:           // Nothing to do.
203     assert(getTypeAction(Node->getValueType(0)) == Legal &&
204            "This must be legal!");
205     break;
206   case ISD::CopyFromReg:
207     Tmp1 = LegalizeOp(Node->getOperand(0));
208     if (Tmp1 != Node->getOperand(0))
209       Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
210                                   Node->getValueType(0), Tmp1);
211     else
212       Result = Op.getValue(0);
213
214     // Since CopyFromReg produces two values, make sure to remember that we
215     // legalized both of them.
216     AddLegalizedOperand(Op.getValue(0), Result);
217     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
218     return Result.getValue(Op.ResNo);
219   case ISD::ImplicitDef:
220     Tmp1 = LegalizeOp(Node->getOperand(0));
221     if (Tmp1 != Node->getOperand(0))
222       Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
223     break;
224   case ISD::UNDEF: {
225     MVT::ValueType VT = Op.getValueType();
226     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
227     default: assert(0 && "This action is not supported yet!");
228     case TargetLowering::Expand:
229     case TargetLowering::Promote:
230       if (MVT::isInteger(VT))
231         Result = DAG.getConstant(0, VT);
232       else if (MVT::isFloatingPoint(VT))
233         Result = DAG.getConstantFP(0, VT);
234       else
235         assert(0 && "Unknown value type!");
236       break;
237     case TargetLowering::Legal:
238       break;
239     }
240     break;
241   }
242   case ISD::Constant:
243     // We know we don't need to expand constants here, constants only have one
244     // value and we check that it is fine above.
245
246     // FIXME: Maybe we should handle things like targets that don't support full
247     // 32-bit immediates?
248     break;
249   case ISD::ConstantFP: {
250     // Spill FP immediates to the constant pool if the target cannot directly
251     // codegen them.  Targets often have some immediate values that can be
252     // efficiently generated into an FP register without a load.  We explicitly
253     // leave these constants as ConstantFP nodes for the target to deal with.
254
255     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
256
257     // Check to see if this FP immediate is already legal.
258     bool isLegal = false;
259     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
260            E = TLI.legal_fpimm_end(); I != E; ++I)
261       if (CFP->isExactlyValue(*I)) {
262         isLegal = true;
263         break;
264       }
265
266     if (!isLegal) {
267       // Otherwise we need to spill the constant to memory.
268       MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
269
270       bool Extend = false;
271
272       // If a FP immediate is precise when represented as a float, we put it
273       // into the constant pool as a float, even if it's is statically typed
274       // as a double.
275       MVT::ValueType VT = CFP->getValueType(0);
276       bool isDouble = VT == MVT::f64;
277       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
278                                              Type::FloatTy, CFP->getValue());
279       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
280           // Only do this if the target has a native EXTLOAD instruction from
281           // f32.
282           TLI.getOperationAction(ISD::EXTLOAD,
283                                  MVT::f32) == TargetLowering::Legal) {
284         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
285         VT = MVT::f32;
286         Extend = true;
287       }
288
289       SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
290                                             TLI.getPointerTy());
291       if (Extend) {
292         Result = DAG.getNode(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(), CPIdx,
293                              DAG.getSrcValue(NULL), MVT::f32);
294       } else {
295         Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
296       }
297     }
298     break;
299   }
300   case ISD::TokenFactor: {
301     std::vector<SDOperand> Ops;
302     bool Changed = false;
303     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
304       SDOperand Op = Node->getOperand(i);
305       // Fold single-use TokenFactor nodes into this token factor as we go.
306       if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
307         Changed = true;
308         for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
309           Ops.push_back(LegalizeOp(Op.getOperand(j)));
310       } else {
311         Ops.push_back(LegalizeOp(Op));  // Legalize the operands
312         Changed |= Ops[i] != Op;
313       }
314     }
315     if (Changed)
316       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
317     break;
318   }
319
320   case ISD::ADJCALLSTACKDOWN:
321   case ISD::ADJCALLSTACKUP:
322     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
323     // There is no need to legalize the size argument (Operand #1)
324     if (Tmp1 != Node->getOperand(0))
325       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
326                            Node->getOperand(1));
327     break;
328   case ISD::DYNAMIC_STACKALLOC:
329     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
330     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
331     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
332     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
333         Tmp3 != Node->getOperand(2))
334       Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
335                            Tmp1, Tmp2, Tmp3);
336     else
337       Result = Op.getValue(0);
338
339     // Since this op produces two values, make sure to remember that we
340     // legalized both of them.
341     AddLegalizedOperand(SDOperand(Node, 0), Result);
342     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
343     return Result.getValue(Op.ResNo);
344
345   case ISD::CALL: {
346     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
347     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
348
349     bool Changed = false;
350     std::vector<SDOperand> Ops;
351     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
352       Ops.push_back(LegalizeOp(Node->getOperand(i)));
353       Changed |= Ops.back() != Node->getOperand(i);
354     }
355
356     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
357       std::vector<MVT::ValueType> RetTyVTs;
358       RetTyVTs.reserve(Node->getNumValues());
359       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
360         RetTyVTs.push_back(Node->getValueType(i));
361       Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops), 0);
362     } else {
363       Result = Result.getValue(0);
364     }
365     // Since calls produce multiple values, make sure to remember that we
366     // legalized all of them.
367     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
368       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
369     return Result.getValue(Op.ResNo);
370   }
371   case ISD::BR:
372     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
373     if (Tmp1 != Node->getOperand(0))
374       Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
375     break;
376
377   case ISD::BRCOND:
378     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
379
380     switch (getTypeAction(Node->getOperand(1).getValueType())) {
381     case Expand: assert(0 && "It's impossible to expand bools");
382     case Legal:
383       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
384       break;
385     case Promote:
386       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
387       break;
388     }
389     // Basic block destination (Op#2) is always legal.
390     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
391       Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
392                            Node->getOperand(2));
393     break;
394   case ISD::BRCONDTWOWAY:
395     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
396     switch (getTypeAction(Node->getOperand(1).getValueType())) {
397     case Expand: assert(0 && "It's impossible to expand bools");
398     case Legal:
399       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
400       break;
401     case Promote:
402       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
403       break;
404     }
405     // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
406     // pair.
407     switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
408     case TargetLowering::Promote:
409     default: assert(0 && "This action is not supported yet!");
410     case TargetLowering::Legal:
411       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
412         std::vector<SDOperand> Ops;
413         Ops.push_back(Tmp1);
414         Ops.push_back(Tmp2);
415         Ops.push_back(Node->getOperand(2));
416         Ops.push_back(Node->getOperand(3));
417         Result = DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops);
418       }
419       break;
420     case TargetLowering::Expand:
421       Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
422                            Node->getOperand(2));
423       Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
424       break;
425     }
426     break;
427
428   case ISD::LOAD:
429     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
430     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
431
432     if (Tmp1 != Node->getOperand(0) ||
433         Tmp2 != Node->getOperand(1))
434       Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2, Node->getOperand(2));
435     else
436       Result = SDOperand(Node, 0);
437
438     // Since loads produce two values, make sure to remember that we legalized
439     // both of them.
440     AddLegalizedOperand(SDOperand(Node, 0), Result);
441     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
442     return Result.getValue(Op.ResNo);
443
444   case ISD::EXTLOAD:
445   case ISD::SEXTLOAD:
446   case ISD::ZEXTLOAD: {
447     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
448     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
449
450     MVT::ValueType SrcVT = cast<MVTSDNode>(Node)->getExtraValueType();
451     switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
452     default: assert(0 && "This action is not supported yet!");
453     case TargetLowering::Promote:
454       assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
455       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0),
456                            Tmp1, Tmp2, Node->getOperand(2), MVT::i8);
457       // Since loads produce two values, make sure to remember that we legalized
458       // both of them.
459       AddLegalizedOperand(SDOperand(Node, 0), Result);
460       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
461       return Result.getValue(Op.ResNo);
462
463     case TargetLowering::Legal:
464       if (Tmp1 != Node->getOperand(0) ||
465           Tmp2 != Node->getOperand(1))
466         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0),
467                              Tmp1, Tmp2, Node->getOperand(2), SrcVT);
468       else
469         Result = SDOperand(Node, 0);
470
471       // Since loads produce two values, make sure to remember that we legalized
472       // both of them.
473       AddLegalizedOperand(SDOperand(Node, 0), Result);
474       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
475       return Result.getValue(Op.ResNo);
476     case TargetLowering::Expand:
477       assert(Node->getOpcode() != ISD::EXTLOAD &&
478              "EXTLOAD should always be supported!");
479       // Turn the unsupported load into an EXTLOAD followed by an explicit
480       // zero/sign extend inreg.
481       Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
482                            Tmp1, Tmp2, Node->getOperand(2), SrcVT);
483       SDOperand ValRes;
484       if (Node->getOpcode() == ISD::SEXTLOAD)
485         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
486                              Result, SrcVT);
487       else
488         ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
489       AddLegalizedOperand(SDOperand(Node, 0), ValRes);
490       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
491       if (Op.ResNo)
492         return Result.getValue(1);
493       return ValRes;
494     }
495     assert(0 && "Unreachable");
496   }
497   case ISD::EXTRACT_ELEMENT:
498     // Get both the low and high parts.
499     ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
500     if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
501       Result = Tmp2;  // 1 -> Hi
502     else
503       Result = Tmp1;  // 0 -> Lo
504     break;
505
506   case ISD::CopyToReg:
507     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
508
509     switch (getTypeAction(Node->getOperand(1).getValueType())) {
510     case Legal:
511       // Legalize the incoming value (must be legal).
512       Tmp2 = LegalizeOp(Node->getOperand(1));
513       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
514         Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
515       break;
516     case Promote:
517       Tmp2 = PromoteOp(Node->getOperand(1));
518       Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
519       break;
520     case Expand:
521       SDOperand Lo, Hi;
522       ExpandOp(Node->getOperand(1), Lo, Hi);
523       unsigned Reg = cast<RegSDNode>(Node)->getReg();
524       Lo = DAG.getCopyToReg(Tmp1, Lo, Reg);
525       Hi = DAG.getCopyToReg(Tmp1, Hi, Reg+1);
526       // Note that the copytoreg nodes are independent of each other.
527       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
528       assert(isTypeLegal(Result.getValueType()) &&
529              "Cannot expand multiple times yet (i64 -> i16)");
530       break;
531     }
532     break;
533
534   case ISD::RET:
535     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
536     switch (Node->getNumOperands()) {
537     case 2:  // ret val
538       switch (getTypeAction(Node->getOperand(1).getValueType())) {
539       case Legal:
540         Tmp2 = LegalizeOp(Node->getOperand(1));
541         if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
542           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
543         break;
544       case Expand: {
545         SDOperand Lo, Hi;
546         ExpandOp(Node->getOperand(1), Lo, Hi);
547         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
548         break;
549       }
550       case Promote:
551         Tmp2 = PromoteOp(Node->getOperand(1));
552         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
553         break;
554       }
555       break;
556     case 1:  // ret void
557       if (Tmp1 != Node->getOperand(0))
558         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
559       break;
560     default: { // ret <values>
561       std::vector<SDOperand> NewValues;
562       NewValues.push_back(Tmp1);
563       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
564         switch (getTypeAction(Node->getOperand(i).getValueType())) {
565         case Legal:
566           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
567           break;
568         case Expand: {
569           SDOperand Lo, Hi;
570           ExpandOp(Node->getOperand(i), Lo, Hi);
571           NewValues.push_back(Lo);
572           NewValues.push_back(Hi);
573           break;
574         }
575         case Promote:
576           assert(0 && "Can't promote multiple return value yet!");
577         }
578       Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
579       break;
580     }
581     }
582     break;
583   case ISD::STORE:
584     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
585     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
586
587     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
588     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
589       if (CFP->getValueType(0) == MVT::f32) {
590         union {
591           unsigned I;
592           float    F;
593         } V;
594         V.F = CFP->getValue();
595         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, 
596                               DAG.getConstant(V.I, MVT::i32), Tmp2, Node->getOperand(3));
597       } else {
598         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
599         union {
600           uint64_t I;
601           double   F;
602         } V;
603         V.F = CFP->getValue();
604         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, 
605                              DAG.getConstant(V.I, MVT::i64), Tmp2, Node->getOperand(3));
606       }
607       Node = Result.Val;
608     }
609
610     switch (getTypeAction(Node->getOperand(1).getValueType())) {
611     case Legal: {
612       SDOperand Val = LegalizeOp(Node->getOperand(1));
613       if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
614           Tmp2 != Node->getOperand(2))
615         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2, Node->getOperand(3));
616       break;
617     }
618     case Promote:
619       // Truncate the value and store the result.
620       Tmp3 = PromoteOp(Node->getOperand(1));
621       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
622                            Node->getOperand(3),
623                            Node->getOperand(1).getValueType()); 
624       break;
625
626     case Expand:
627       SDOperand Lo, Hi;
628       ExpandOp(Node->getOperand(1), Lo, Hi);
629
630       if (!TLI.isLittleEndian())
631         std::swap(Lo, Hi);
632
633       Lo = DAG.getNode(ISD::STORE, MVT::Other,Tmp1, Lo, Tmp2,Node->getOperand(3));
634
635       unsigned IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
636       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
637                          getIntPtrConstant(IncrementSize));
638       assert(isTypeLegal(Tmp2.getValueType()) &&
639              "Pointers must be legal!");
640       //Again, claiming both parts of the store came form the same Instr
641       Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2, Node->getOperand(3));
642                               
643       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
644       break;
645     }
646     break;
647   case ISD::PCMARKER:
648     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
649     if (Tmp1 != Node->getOperand(0))
650       Result = DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp1,Node->getOperand(1));
651     break;
652   case ISD::TRUNCSTORE:
653     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
654     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
655
656     switch (getTypeAction(Node->getOperand(1).getValueType())) {
657     case Legal:
658       Tmp2 = LegalizeOp(Node->getOperand(1));
659       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
660           Tmp3 != Node->getOperand(2))
661         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
662                              Node->getOperand(3),
663                              cast<MVTSDNode>(Node)->getExtraValueType());
664       break;
665     case Promote:
666     case Expand:
667       assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
668     }
669     break;
670   case ISD::SELECT:
671     switch (getTypeAction(Node->getOperand(0).getValueType())) {
672     case Expand: assert(0 && "It's impossible to expand bools");
673     case Legal:
674       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
675       break;
676     case Promote:
677       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
678       break;
679     }
680     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
681     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
682
683     switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
684     default: assert(0 && "This action is not supported yet!");
685     case TargetLowering::Legal:
686       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
687           Tmp3 != Node->getOperand(2))
688         Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
689                              Tmp1, Tmp2, Tmp3);
690       break;
691     case TargetLowering::Promote: {
692       MVT::ValueType NVT =
693         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
694       unsigned ExtOp, TruncOp;
695       if (MVT::isInteger(Tmp2.getValueType())) {
696         ExtOp = ISD::ZERO_EXTEND;
697         TruncOp  = ISD::TRUNCATE;
698       } else {
699         ExtOp = ISD::FP_EXTEND;
700         TruncOp  = ISD::FP_ROUND;
701       }
702       // Promote each of the values to the new type.
703       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
704       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
705       // Perform the larger operation, then round down.
706       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
707       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
708       break;
709     }
710     }
711     break;
712   case ISD::SETCC:
713     switch (getTypeAction(Node->getOperand(0).getValueType())) {
714     case Legal:
715       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
716       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
717       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
718         Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
719                               Node->getValueType(0), Tmp1, Tmp2);
720       break;
721     case Promote:
722       Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
723       Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
724
725       // If this is an FP compare, the operands have already been extended.
726       if (MVT::isInteger(Node->getOperand(0).getValueType())) {
727         MVT::ValueType VT = Node->getOperand(0).getValueType();
728         MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
729
730         // Otherwise, we have to insert explicit sign or zero extends.  Note
731         // that we could insert sign extends for ALL conditions, but zero extend
732         // is cheaper on many machines (an AND instead of two shifts), so prefer
733         // it.
734         switch (cast<SetCCSDNode>(Node)->getCondition()) {
735         default: assert(0 && "Unknown integer comparison!");
736         case ISD::SETEQ:
737         case ISD::SETNE:
738         case ISD::SETUGE:
739         case ISD::SETUGT:
740         case ISD::SETULE:
741         case ISD::SETULT:
742           // ALL of these operations will work if we either sign or zero extend
743           // the operands (including the unsigned comparisons!).  Zero extend is
744           // usually a simpler/cheaper operation, so prefer it.
745           Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
746           Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
747           break;
748         case ISD::SETGE:
749         case ISD::SETGT:
750         case ISD::SETLT:
751         case ISD::SETLE:
752           Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
753           Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
754           break;
755         }
756
757       }
758       Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
759                             Node->getValueType(0), Tmp1, Tmp2);
760       break;
761     case Expand:
762       SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
763       ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
764       ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
765       switch (cast<SetCCSDNode>(Node)->getCondition()) {
766       case ISD::SETEQ:
767       case ISD::SETNE:
768         if (RHSLo == RHSHi)
769           if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
770             if (RHSCST->isAllOnesValue()) {
771               // Comparison to -1.
772               Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
773               Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
774                                     Node->getValueType(0), Tmp1, RHSLo);
775               break;
776             }
777
778         Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
779         Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
780         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
781         Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
782                               Node->getValueType(0), Tmp1,
783                               DAG.getConstant(0, Tmp1.getValueType()));
784         break;
785       default:
786         // If this is a comparison of the sign bit, just look at the top part.
787         // X > -1,  x < 0
788         if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
789           if ((cast<SetCCSDNode>(Node)->getCondition() == ISD::SETLT &&
790                CST->getValue() == 0) ||              // X < 0
791               (cast<SetCCSDNode>(Node)->getCondition() == ISD::SETGT &&
792                (CST->isAllOnesValue())))             // X > -1
793             return DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
794                                 Node->getValueType(0), LHSHi, RHSHi);
795
796         // FIXME: This generated code sucks.
797         ISD::CondCode LowCC;
798         switch (cast<SetCCSDNode>(Node)->getCondition()) {
799         default: assert(0 && "Unknown integer setcc!");
800         case ISD::SETLT:
801         case ISD::SETULT: LowCC = ISD::SETULT; break;
802         case ISD::SETGT:
803         case ISD::SETUGT: LowCC = ISD::SETUGT; break;
804         case ISD::SETLE:
805         case ISD::SETULE: LowCC = ISD::SETULE; break;
806         case ISD::SETGE:
807         case ISD::SETUGE: LowCC = ISD::SETUGE; break;
808         }
809
810         // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
811         // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
812         // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
813
814         // NOTE: on targets without efficient SELECT of bools, we can always use
815         // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
816         Tmp1 = DAG.getSetCC(LowCC, Node->getValueType(0), LHSLo, RHSLo);
817         Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
818                             Node->getValueType(0), LHSHi, RHSHi);
819         Result = DAG.getSetCC(ISD::SETEQ, Node->getValueType(0), LHSHi, RHSHi);
820         Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
821                              Result, Tmp1, Tmp2);
822         break;
823       }
824     }
825     break;
826
827   case ISD::MEMSET:
828   case ISD::MEMCPY:
829   case ISD::MEMMOVE: {
830     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
831     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
832
833     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
834       switch (getTypeAction(Node->getOperand(2).getValueType())) {
835       case Expand: assert(0 && "Cannot expand a byte!");
836       case Legal:
837         Tmp3 = LegalizeOp(Node->getOperand(2));
838         break;
839       case Promote:
840         Tmp3 = PromoteOp(Node->getOperand(2));
841         break;
842       }
843     } else {
844       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
845     }
846
847     SDOperand Tmp4;
848     switch (getTypeAction(Node->getOperand(3).getValueType())) {
849     case Expand: assert(0 && "Cannot expand this yet!");
850     case Legal:
851       Tmp4 = LegalizeOp(Node->getOperand(3));
852       break;
853     case Promote:
854       Tmp4 = PromoteOp(Node->getOperand(3));
855       break;
856     }
857
858     SDOperand Tmp5;
859     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
860     case Expand: assert(0 && "Cannot expand this yet!");
861     case Legal:
862       Tmp5 = LegalizeOp(Node->getOperand(4));
863       break;
864     case Promote:
865       Tmp5 = PromoteOp(Node->getOperand(4));
866       break;
867     }
868
869     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
870     default: assert(0 && "This action not implemented for this operation!");
871     case TargetLowering::Legal:
872       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
873           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
874           Tmp5 != Node->getOperand(4)) {
875         std::vector<SDOperand> Ops;
876         Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
877         Ops.push_back(Tmp4); Ops.push_back(Tmp5);
878         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
879       }
880       break;
881     case TargetLowering::Expand: {
882       // Otherwise, the target does not support this operation.  Lower the
883       // operation to an explicit libcall as appropriate.
884       MVT::ValueType IntPtr = TLI.getPointerTy();
885       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
886       std::vector<std::pair<SDOperand, const Type*> > Args;
887
888       const char *FnName = 0;
889       if (Node->getOpcode() == ISD::MEMSET) {
890         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
891         // Extend the ubyte argument to be an int value for the call.
892         Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
893         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
894         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
895
896         FnName = "memset";
897       } else if (Node->getOpcode() == ISD::MEMCPY ||
898                  Node->getOpcode() == ISD::MEMMOVE) {
899         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
900         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
901         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
902         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
903       } else {
904         assert(0 && "Unknown op!");
905       }
906       std::pair<SDOperand,SDOperand> CallResult =
907         TLI.LowerCallTo(Tmp1, Type::VoidTy, false,
908                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
909       Result = LegalizeOp(CallResult.second);
910       break;
911     }
912     case TargetLowering::Custom:
913       std::vector<SDOperand> Ops;
914       Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
915       Ops.push_back(Tmp4); Ops.push_back(Tmp5);
916       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
917       Result = TLI.LowerOperation(Result);
918       Result = LegalizeOp(Result);
919       break;
920     }
921     break;
922   }
923   case ISD::ADD_PARTS:
924   case ISD::SUB_PARTS:
925   case ISD::SHL_PARTS:
926   case ISD::SRA_PARTS:
927   case ISD::SRL_PARTS: {
928     std::vector<SDOperand> Ops;
929     bool Changed = false;
930     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
931       Ops.push_back(LegalizeOp(Node->getOperand(i)));
932       Changed |= Ops.back() != Node->getOperand(i);
933     }
934     if (Changed)
935       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
936
937     // Since these produce multiple values, make sure to remember that we
938     // legalized all of them.
939     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
940       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
941     return Result.getValue(Op.ResNo);
942   }
943
944     // Binary operators
945   case ISD::ADD:
946   case ISD::SUB:
947   case ISD::MUL:
948   case ISD::MULHS:
949   case ISD::MULHU:
950   case ISD::UDIV:
951   case ISD::SDIV:
952   case ISD::AND:
953   case ISD::OR:
954   case ISD::XOR:
955   case ISD::SHL:
956   case ISD::SRL:
957   case ISD::SRA:
958     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
959     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
960     if (Tmp1 != Node->getOperand(0) ||
961         Tmp2 != Node->getOperand(1))
962       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
963     break;
964
965   case ISD::UREM:
966   case ISD::SREM:
967     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
968     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
969     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
970     case TargetLowering::Legal:
971       if (Tmp1 != Node->getOperand(0) ||
972           Tmp2 != Node->getOperand(1))
973         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
974                              Tmp2);
975       break;
976     case TargetLowering::Promote:
977     case TargetLowering::Custom:
978       assert(0 && "Cannot promote/custom handle this yet!");
979     case TargetLowering::Expand: {
980       MVT::ValueType VT = Node->getValueType(0);
981       unsigned Opc = (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
982       Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
983       Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
984       Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
985       }
986       break;
987     }
988     break;
989
990   case ISD::CTPOP:
991   case ISD::CTTZ:
992   case ISD::CTLZ:
993     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
994     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
995     case TargetLowering::Legal:
996       if (Tmp1 != Node->getOperand(0))
997         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
998       break;
999     case TargetLowering::Promote: {
1000       MVT::ValueType OVT = Tmp1.getValueType();
1001       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1002       //Zero extend the argument
1003       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
1004       // Perform the larger operation, then subtract if needed.
1005       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1006       switch(Node->getOpcode())
1007       {
1008       case ISD::CTPOP:
1009         Result = Tmp1;
1010         break;
1011       case ISD::CTTZ:
1012         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
1013         Tmp2 = DAG.getSetCC(ISD::SETEQ, MVT::i1, Tmp1, 
1014                             DAG.getConstant(getSizeInBits(NVT), NVT));
1015         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2, 
1016                            DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
1017         break;
1018       case ISD::CTLZ:
1019         //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
1020         Result = DAG.getNode(ISD::SUB, NVT, Tmp1, 
1021                              DAG.getConstant(getSizeInBits(NVT) - 
1022                                              getSizeInBits(OVT), NVT));
1023         break;
1024       }
1025       break;
1026     }
1027     case TargetLowering::Custom:
1028       assert(0 && "Cannot custom handle this yet!");
1029     case TargetLowering::Expand:
1030       switch(Node->getOpcode())
1031       {
1032       case ISD::CTPOP: {
1033         static const uint64_t mask[6][9] = {
1034           {0, 0x55, 0x5555, 0, 0x55555555, 0, 0, 0, 0x5555555555555555ULL},
1035           {0, 0x33, 0x3333, 0, 0x33333333, 0, 0, 0, 0x3333333333333333ULL},
1036           {0, 0x0F, 0x0F0F, 0, 0x0F0F0F0F, 0, 0, 0, 0x0F0F0F0F0F0F0F0FULL},
1037           {0,    0, 0x00FF, 0, 0x00FF00FF, 0, 0, 0, 0x00FF00FF00FF00FFULL},
1038           {0,    0,      0, 0, 0x0000FFFF, 0, 0, 0, 0x0000FFFF0000FFFFULL},
1039           {0,    0,      0, 0,          0, 0, 0, 0, 0x00000000FFFFFFFFULL}};
1040         MVT::ValueType VT = Tmp1.getValueType();
1041         int len = getSizeInBits(VT);
1042         for (int i = 0; (1 << i) <= (len / 2); ++i) {
1043           //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
1044           Tmp2 = DAG.getConstant(mask[i][len/8], VT);
1045           Tmp3 = DAG.getConstant(1 << i, VT);
1046           Tmp1 = DAG.getNode(ISD::ADD, VT, 
1047                              DAG.getNode(ISD::AND, VT, Tmp1, Tmp2),
1048                              DAG.getNode(ISD::AND, VT,
1049                                          DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3),
1050                                          Tmp2));
1051         }
1052         Result = Tmp1;
1053         break;
1054       }
1055 //       case ISD::CTTZ:
1056 //         break;
1057 //       case ISD::CTLZ:
1058 //         break;
1059       default:
1060         assert(0 && "Cannot expand this yet!");
1061         break;
1062       }
1063       break;
1064     }
1065     break;
1066     
1067     // Unary operators
1068   case ISD::FABS:
1069   case ISD::FNEG:
1070   case ISD::FSQRT:
1071   case ISD::FSIN:
1072   case ISD::FCOS:
1073     Tmp1 = LegalizeOp(Node->getOperand(0));
1074     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1075     case TargetLowering::Legal:
1076       if (Tmp1 != Node->getOperand(0))
1077         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1078       break;
1079     case TargetLowering::Promote:
1080     case TargetLowering::Custom:
1081       assert(0 && "Cannot promote/custom handle this yet!");
1082     case TargetLowering::Expand:
1083       switch(Node->getOpcode()) {
1084       case ISD::FNEG: {
1085         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
1086         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
1087         Result = LegalizeOp(DAG.getNode(ISD::SUB, Node->getValueType(0),
1088                                         Tmp2, Tmp1));
1089         break;
1090       }
1091       case ISD::FABS: {
1092         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
1093         MVT::ValueType VT = Node->getValueType(0);
1094         Tmp2 = DAG.getConstantFP(0.0, VT);
1095         Tmp2 = DAG.getSetCC(ISD::SETUGT, TLI.getSetCCResultTy(), Tmp1, Tmp2);
1096         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
1097         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
1098         Result = LegalizeOp(Result);
1099         break;
1100       }
1101       case ISD::FSQRT:
1102       case ISD::FSIN:
1103       case ISD::FCOS: {
1104         MVT::ValueType VT = Node->getValueType(0);
1105         Type *T = VT == MVT::f32 ? Type::FloatTy : Type::DoubleTy;
1106         const char *FnName = 0;
1107         switch(Node->getOpcode()) {
1108         case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
1109         case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
1110         case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
1111         default: assert(0 && "Unreachable!");
1112         }
1113         std::vector<std::pair<SDOperand, const Type*> > Args;
1114         Args.push_back(std::make_pair(Tmp1, T));
1115         std::pair<SDOperand,SDOperand> CallResult =
1116           TLI.LowerCallTo(DAG.getEntryNode(), T, false,
1117                           DAG.getExternalSymbol(FnName, VT), Args, DAG);
1118         Result = LegalizeOp(CallResult.first);
1119         break;
1120       }
1121       default:
1122         assert(0 && "Unreachable!");
1123       }
1124       break;
1125     }
1126     break;
1127
1128     // Conversion operators.  The source and destination have different types.
1129   case ISD::ZERO_EXTEND:
1130   case ISD::SIGN_EXTEND:
1131   case ISD::TRUNCATE:
1132   case ISD::FP_EXTEND:
1133   case ISD::FP_ROUND:
1134   case ISD::FP_TO_SINT:
1135   case ISD::FP_TO_UINT:
1136   case ISD::SINT_TO_FP:
1137   case ISD::UINT_TO_FP:
1138     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1139     case Legal:
1140       Tmp1 = LegalizeOp(Node->getOperand(0));
1141       if (Tmp1 != Node->getOperand(0))
1142         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1143       break;
1144     case Expand:
1145       if (Node->getOpcode() == ISD::SINT_TO_FP ||
1146           Node->getOpcode() == ISD::UINT_TO_FP) {
1147         Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
1148                                Node->getValueType(0), Node->getOperand(0));
1149         Result = LegalizeOp(Result);
1150         break;
1151       } else if (Node->getOpcode() == ISD::TRUNCATE) {
1152         // In the expand case, we must be dealing with a truncate, because
1153         // otherwise the result would be larger than the source.
1154         ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1155
1156         // Since the result is legal, we should just be able to truncate the low
1157         // part of the source.
1158         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
1159         break;
1160       }
1161       assert(0 && "Shouldn't need to expand other operators here!");
1162
1163     case Promote:
1164       switch (Node->getOpcode()) {
1165       case ISD::ZERO_EXTEND:
1166         Result = PromoteOp(Node->getOperand(0));
1167         // NOTE: Any extend would work here...
1168         Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1169         Result = DAG.getZeroExtendInReg(Result,
1170                                         Node->getOperand(0).getValueType());
1171         break;
1172       case ISD::SIGN_EXTEND:
1173         Result = PromoteOp(Node->getOperand(0));
1174         // NOTE: Any extend would work here...
1175         Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1176         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1177                              Result, Node->getOperand(0).getValueType());
1178         break;
1179       case ISD::TRUNCATE:
1180         Result = PromoteOp(Node->getOperand(0));
1181         Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
1182         break;
1183       case ISD::FP_EXTEND:
1184         Result = PromoteOp(Node->getOperand(0));
1185         if (Result.getValueType() != Op.getValueType())
1186           // Dynamically dead while we have only 2 FP types.
1187           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
1188         break;
1189       case ISD::FP_ROUND:
1190       case ISD::FP_TO_SINT:
1191       case ISD::FP_TO_UINT:
1192         Result = PromoteOp(Node->getOperand(0));
1193         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
1194         break;
1195       case ISD::SINT_TO_FP:
1196         Result = PromoteOp(Node->getOperand(0));
1197         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1198                              Result, Node->getOperand(0).getValueType());
1199         Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
1200         break;
1201       case ISD::UINT_TO_FP:
1202         Result = PromoteOp(Node->getOperand(0));
1203         Result = DAG.getZeroExtendInReg(Result,
1204                                         Node->getOperand(0).getValueType());
1205         Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
1206         break;
1207       }
1208     }
1209     break;
1210   case ISD::FP_ROUND_INREG:
1211   case ISD::SIGN_EXTEND_INREG: {
1212     Tmp1 = LegalizeOp(Node->getOperand(0));
1213     MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
1214
1215     // If this operation is not supported, convert it to a shl/shr or load/store
1216     // pair.
1217     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
1218     default: assert(0 && "This action not supported for this op yet!");
1219     case TargetLowering::Legal:
1220       if (Tmp1 != Node->getOperand(0))
1221         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1222                              ExtraVT);
1223       break;
1224     case TargetLowering::Expand:
1225       // If this is an integer extend and shifts are supported, do that.
1226       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1227         // NOTE: we could fall back on load/store here too for targets without
1228         // SAR.  However, it is doubtful that any exist.
1229         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
1230                             MVT::getSizeInBits(ExtraVT);
1231         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
1232         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
1233                              Node->getOperand(0), ShiftCst);
1234         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
1235                              Result, ShiftCst);
1236       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
1237         // The only way we can lower this is to turn it into a STORETRUNC,
1238         // EXTLOAD pair, targetting a temporary location (a stack slot).
1239
1240         // NOTE: there is a choice here between constantly creating new stack
1241         // slots and always reusing the same one.  We currently always create
1242         // new ones, as reuse may inhibit scheduling.
1243         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
1244         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
1245         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
1246         MachineFunction &MF = DAG.getMachineFunction();
1247         int SSFI =
1248           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
1249         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
1250         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
1251                              Node->getOperand(0), StackSlot, DAG.getSrcValue(NULL), ExtraVT);
1252         Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
1253                              Result, StackSlot, DAG.getSrcValue(NULL), ExtraVT);
1254       } else {
1255         assert(0 && "Unknown op");
1256       }
1257       Result = LegalizeOp(Result);
1258       break;
1259     }
1260     break;
1261   }
1262   }
1263
1264   if (!Op.Val->hasOneUse())
1265     AddLegalizedOperand(Op, Result);
1266
1267   return Result;
1268 }
1269
1270 /// PromoteOp - Given an operation that produces a value in an invalid type,
1271 /// promote it to compute the value into a larger type.  The produced value will
1272 /// have the correct bits for the low portion of the register, but no guarantee
1273 /// is made about the top bits: it may be zero, sign-extended, or garbage.
1274 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
1275   MVT::ValueType VT = Op.getValueType();
1276   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1277   assert(getTypeAction(VT) == Promote &&
1278          "Caller should expand or legalize operands that are not promotable!");
1279   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
1280          "Cannot promote to smaller type!");
1281
1282   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
1283   if (I != PromotedNodes.end()) return I->second;
1284
1285   SDOperand Tmp1, Tmp2, Tmp3;
1286
1287   SDOperand Result;
1288   SDNode *Node = Op.Val;
1289
1290   // Promotion needs an optimization step to clean up after it, and is not
1291   // careful to avoid operations the target does not support.  Make sure that
1292   // all generated operations are legalized in the next iteration.
1293   NeedsAnotherIteration = true;
1294
1295   switch (Node->getOpcode()) {
1296   default:
1297     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1298     assert(0 && "Do not know how to promote this operator!");
1299     abort();
1300   case ISD::UNDEF:
1301     Result = DAG.getNode(ISD::UNDEF, NVT);
1302     break;
1303   case ISD::Constant:
1304     Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
1305     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
1306     break;
1307   case ISD::ConstantFP:
1308     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
1309     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
1310     break;
1311   case ISD::CopyFromReg:
1312     Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(), NVT,
1313                                 Node->getOperand(0));
1314     // Remember that we legalized the chain.
1315     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1316     break;
1317
1318   case ISD::SETCC:
1319     assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
1320            "SetCC type is not legal??");
1321     Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
1322                           TLI.getSetCCResultTy(), Node->getOperand(0),
1323                           Node->getOperand(1));
1324     Result = LegalizeOp(Result);
1325     break;
1326
1327   case ISD::TRUNCATE:
1328     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1329     case Legal:
1330       Result = LegalizeOp(Node->getOperand(0));
1331       assert(Result.getValueType() >= NVT &&
1332              "This truncation doesn't make sense!");
1333       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
1334         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
1335       break;
1336     case Promote:
1337       // The truncation is not required, because we don't guarantee anything
1338       // about high bits anyway.
1339       Result = PromoteOp(Node->getOperand(0));
1340       break;
1341     case Expand:
1342       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1343       // Truncate the low part of the expanded value to the result type
1344       Result = DAG.getNode(ISD::TRUNCATE, VT, Tmp1);
1345     }
1346     break;
1347   case ISD::SIGN_EXTEND:
1348   case ISD::ZERO_EXTEND:
1349     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1350     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
1351     case Legal:
1352       // Input is legal?  Just do extend all the way to the larger type.
1353       Result = LegalizeOp(Node->getOperand(0));
1354       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1355       break;
1356     case Promote:
1357       // Promote the reg if it's smaller.
1358       Result = PromoteOp(Node->getOperand(0));
1359       // The high bits are not guaranteed to be anything.  Insert an extend.
1360       if (Node->getOpcode() == ISD::SIGN_EXTEND)
1361         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
1362                              Node->getOperand(0).getValueType());
1363       else
1364         Result = DAG.getZeroExtendInReg(Result,
1365                                         Node->getOperand(0).getValueType());
1366       break;
1367     }
1368     break;
1369
1370   case ISD::FP_EXTEND:
1371     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
1372   case ISD::FP_ROUND:
1373     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1374     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
1375     case Promote:  assert(0 && "Unreachable with 2 FP types!");
1376     case Legal:
1377       // Input is legal?  Do an FP_ROUND_INREG.
1378       Result = LegalizeOp(Node->getOperand(0));
1379       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1380       break;
1381     }
1382     break;
1383
1384   case ISD::SINT_TO_FP:
1385   case ISD::UINT_TO_FP:
1386     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1387     case Legal:
1388       Result = LegalizeOp(Node->getOperand(0));
1389       // No extra round required here.
1390       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1391       break;
1392
1393     case Promote:
1394       Result = PromoteOp(Node->getOperand(0));
1395       if (Node->getOpcode() == ISD::SINT_TO_FP)
1396         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1397                              Result, Node->getOperand(0).getValueType());
1398       else
1399         Result = DAG.getZeroExtendInReg(Result,
1400                                         Node->getOperand(0).getValueType());
1401       // No extra round required here.
1402       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1403       break;
1404     case Expand:
1405       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
1406                              Node->getOperand(0));
1407       Result = LegalizeOp(Result);
1408
1409       // Round if we cannot tolerate excess precision.
1410       if (NoExcessFPPrecision)
1411         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1412       break;
1413     }
1414     break;
1415
1416   case ISD::FP_TO_SINT:
1417   case ISD::FP_TO_UINT:
1418     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1419     case Legal:
1420       Tmp1 = LegalizeOp(Node->getOperand(0));
1421       break;
1422     case Promote:
1423       // The input result is prerounded, so we don't have to do anything
1424       // special.
1425       Tmp1 = PromoteOp(Node->getOperand(0));
1426       break;
1427     case Expand:
1428       assert(0 && "not implemented");
1429     }
1430     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1431     break;
1432
1433   case ISD::FABS:
1434   case ISD::FNEG:
1435     Tmp1 = PromoteOp(Node->getOperand(0));
1436     assert(Tmp1.getValueType() == NVT);
1437     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1438     // NOTE: we do not have to do any extra rounding here for
1439     // NoExcessFPPrecision, because we know the input will have the appropriate
1440     // precision, and these operations don't modify precision at all.
1441     break;
1442
1443   case ISD::FSQRT:
1444   case ISD::FSIN:
1445   case ISD::FCOS:
1446     Tmp1 = PromoteOp(Node->getOperand(0));
1447     assert(Tmp1.getValueType() == NVT);
1448     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1449     if(NoExcessFPPrecision)
1450       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1451     break;
1452
1453   case ISD::AND:
1454   case ISD::OR:
1455   case ISD::XOR:
1456   case ISD::ADD:
1457   case ISD::SUB:
1458   case ISD::MUL:
1459     // The input may have strange things in the top bits of the registers, but
1460     // these operations don't care.  They may have wierd bits going out, but
1461     // that too is okay if they are integer operations.
1462     Tmp1 = PromoteOp(Node->getOperand(0));
1463     Tmp2 = PromoteOp(Node->getOperand(1));
1464     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
1465     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1466
1467     // However, if this is a floating point operation, they will give excess
1468     // precision that we may not be able to tolerate.  If we DO allow excess
1469     // precision, just leave it, otherwise excise it.
1470     // FIXME: Why would we need to round FP ops more than integer ones?
1471     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
1472     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1473       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1474     break;
1475
1476   case ISD::SDIV:
1477   case ISD::SREM:
1478     // These operators require that their input be sign extended.
1479     Tmp1 = PromoteOp(Node->getOperand(0));
1480     Tmp2 = PromoteOp(Node->getOperand(1));
1481     if (MVT::isInteger(NVT)) {
1482       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1483       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
1484     }
1485     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1486
1487     // Perform FP_ROUND: this is probably overly pessimistic.
1488     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1489       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1490     break;
1491
1492   case ISD::UDIV:
1493   case ISD::UREM:
1494     // These operators require that their input be zero extended.
1495     Tmp1 = PromoteOp(Node->getOperand(0));
1496     Tmp2 = PromoteOp(Node->getOperand(1));
1497     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1498     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1499     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
1500     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1501     break;
1502
1503   case ISD::SHL:
1504     Tmp1 = PromoteOp(Node->getOperand(0));
1505     Tmp2 = LegalizeOp(Node->getOperand(1));
1506     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1507     break;
1508   case ISD::SRA:
1509     // The input value must be properly sign extended.
1510     Tmp1 = PromoteOp(Node->getOperand(0));
1511     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1512     Tmp2 = LegalizeOp(Node->getOperand(1));
1513     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1514     break;
1515   case ISD::SRL:
1516     // The input value must be properly zero extended.
1517     Tmp1 = PromoteOp(Node->getOperand(0));
1518     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1519     Tmp2 = LegalizeOp(Node->getOperand(1));
1520     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1521     break;
1522   case ISD::LOAD:
1523     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1524     Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
1525     // FIXME: When the DAG combiner exists, change this to use EXTLOAD!
1526     if (MVT::isInteger(NVT))
1527       Result = DAG.getNode(ISD::ZEXTLOAD, NVT, Tmp1, Tmp2, Node->getOperand(2), VT);
1528     else
1529       Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, Node->getOperand(2), VT);
1530
1531     // Remember that we legalized the chain.
1532     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1533     break;
1534   case ISD::SELECT:
1535     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1536     case Expand: assert(0 && "It's impossible to expand bools");
1537     case Legal:
1538       Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
1539       break;
1540     case Promote:
1541       Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
1542       break;
1543     }
1544     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
1545     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
1546     Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1547     break;
1548   case ISD::CALL: {
1549     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1550     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1551
1552     std::vector<SDOperand> Ops;
1553     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
1554       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1555
1556     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1557            "Can only promote single result calls");
1558     std::vector<MVT::ValueType> RetTyVTs;
1559     RetTyVTs.reserve(2);
1560     RetTyVTs.push_back(NVT);
1561     RetTyVTs.push_back(MVT::Other);
1562     SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops);
1563     Result = SDOperand(NC, 0);
1564
1565     // Insert the new chain mapping.
1566     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1567     break;
1568   }
1569   case ISD::CTPOP:
1570   case ISD::CTTZ:
1571   case ISD::CTLZ:
1572     Tmp1 = Node->getOperand(0);
1573     //Zero extend the argument
1574     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
1575     // Perform the larger operation, then subtract if needed.
1576     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1577     switch(Node->getOpcode())
1578     {
1579     case ISD::CTPOP:
1580       Result = Tmp1;
1581       break;
1582     case ISD::CTTZ:
1583       //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
1584       Tmp2 = DAG.getSetCC(ISD::SETEQ, MVT::i1, Tmp1, 
1585                           DAG.getConstant(getSizeInBits(NVT), NVT));
1586       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2, 
1587                            DAG.getConstant(getSizeInBits(VT),NVT), Tmp1);
1588       break;
1589     case ISD::CTLZ:
1590       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
1591       Result = DAG.getNode(ISD::SUB, NVT, Tmp1, 
1592                            DAG.getConstant(getSizeInBits(NVT) - 
1593                                            getSizeInBits(VT), NVT));
1594       break;
1595     }
1596     break;
1597   }
1598
1599   assert(Result.Val && "Didn't set a result!");
1600   AddPromotedOperand(Op, Result);
1601   return Result;
1602 }
1603
1604 /// ExpandAddSub - Find a clever way to expand this add operation into
1605 /// subcomponents.
1606 void SelectionDAGLegalize::
1607 ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
1608               SDOperand &Lo, SDOperand &Hi) {
1609   // Expand the subcomponents.
1610   SDOperand LHSL, LHSH, RHSL, RHSH;
1611   ExpandOp(LHS, LHSL, LHSH);
1612   ExpandOp(RHS, RHSL, RHSH);
1613
1614   // FIXME: this should be moved to the dag combiner someday.
1615   if (NodeOp == ISD::ADD_PARTS || NodeOp == ISD::SUB_PARTS)
1616     if (LHSL.getValueType() == MVT::i32) {
1617       SDOperand LowEl;
1618       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHSL))
1619         if (C->getValue() == 0)
1620           LowEl = RHSL;
1621       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHSL))
1622         if (C->getValue() == 0)
1623           LowEl = LHSL;
1624       if (LowEl.Val) {
1625         // Turn this into an add/sub of the high part only.
1626         SDOperand HiEl =
1627           DAG.getNode(NodeOp == ISD::ADD_PARTS ? ISD::ADD : ISD::SUB,
1628                       LowEl.getValueType(), LHSH, RHSH);
1629         Lo = LowEl;
1630         Hi = HiEl;
1631         return;
1632       }
1633     }
1634
1635   std::vector<SDOperand> Ops;
1636   Ops.push_back(LHSL);
1637   Ops.push_back(LHSH);
1638   Ops.push_back(RHSL);
1639   Ops.push_back(RHSH);
1640   Lo = DAG.getNode(NodeOp, LHSL.getValueType(), Ops);
1641   Hi = Lo.getValue(1);
1642 }
1643
1644 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
1645                                             SDOperand Op, SDOperand Amt,
1646                                             SDOperand &Lo, SDOperand &Hi) {
1647   // Expand the subcomponents.
1648   SDOperand LHSL, LHSH;
1649   ExpandOp(Op, LHSL, LHSH);
1650
1651   std::vector<SDOperand> Ops;
1652   Ops.push_back(LHSL);
1653   Ops.push_back(LHSH);
1654   Ops.push_back(Amt);
1655   Lo = DAG.getNode(NodeOp, LHSL.getValueType(), Ops);
1656   Hi = Lo.getValue(1);
1657 }
1658
1659
1660 /// ExpandShift - Try to find a clever way to expand this shift operation out to
1661 /// smaller elements.  If we can't find a way that is more efficient than a
1662 /// libcall on this target, return false.  Otherwise, return true with the
1663 /// low-parts expanded into Lo and Hi.
1664 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
1665                                        SDOperand &Lo, SDOperand &Hi) {
1666   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
1667          "This is not a shift!");
1668
1669   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
1670   SDOperand ShAmt = LegalizeOp(Amt);
1671   MVT::ValueType ShTy = ShAmt.getValueType();
1672   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
1673   unsigned NVTBits = MVT::getSizeInBits(NVT);
1674
1675   // Handle the case when Amt is an immediate.  Other cases are currently broken
1676   // and are disabled.
1677   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
1678     unsigned Cst = CN->getValue();
1679     // Expand the incoming operand to be shifted, so that we have its parts
1680     SDOperand InL, InH;
1681     ExpandOp(Op, InL, InH);
1682     switch(Opc) {
1683     case ISD::SHL:
1684       if (Cst > VTBits) {
1685         Lo = DAG.getConstant(0, NVT);
1686         Hi = DAG.getConstant(0, NVT);
1687       } else if (Cst > NVTBits) {
1688         Lo = DAG.getConstant(0, NVT);
1689         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
1690       } else if (Cst == NVTBits) {
1691         Lo = DAG.getConstant(0, NVT);
1692         Hi = InL;
1693       } else {
1694         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
1695         Hi = DAG.getNode(ISD::OR, NVT,
1696            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
1697            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
1698       }
1699       return true;
1700     case ISD::SRL:
1701       if (Cst > VTBits) {
1702         Lo = DAG.getConstant(0, NVT);
1703         Hi = DAG.getConstant(0, NVT);
1704       } else if (Cst > NVTBits) {
1705         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
1706         Hi = DAG.getConstant(0, NVT);
1707       } else if (Cst == NVTBits) {
1708         Lo = InH;
1709         Hi = DAG.getConstant(0, NVT);
1710       } else {
1711         Lo = DAG.getNode(ISD::OR, NVT,
1712            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
1713            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
1714         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
1715       }
1716       return true;
1717     case ISD::SRA:
1718       if (Cst > VTBits) {
1719         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
1720                               DAG.getConstant(NVTBits-1, ShTy));
1721       } else if (Cst > NVTBits) {
1722         Lo = DAG.getNode(ISD::SRA, NVT, InH,
1723                            DAG.getConstant(Cst-NVTBits, ShTy));
1724         Hi = DAG.getNode(ISD::SRA, NVT, InH,
1725                               DAG.getConstant(NVTBits-1, ShTy));
1726       } else if (Cst == NVTBits) {
1727         Lo = InH;
1728         Hi = DAG.getNode(ISD::SRA, NVT, InH,
1729                               DAG.getConstant(NVTBits-1, ShTy));
1730       } else {
1731         Lo = DAG.getNode(ISD::OR, NVT,
1732            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
1733            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
1734         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
1735       }
1736       return true;
1737     }
1738   }
1739   // FIXME: The following code for expanding shifts using ISD::SELECT is buggy,
1740   // so disable it for now.  Currently targets are handling this via SHL_PARTS
1741   // and friends.
1742   return false;
1743
1744   // If we have an efficient select operation (or if the selects will all fold
1745   // away), lower to some complex code, otherwise just emit the libcall.
1746   if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
1747       !isa<ConstantSDNode>(Amt))
1748     return false;
1749
1750   SDOperand InL, InH;
1751   ExpandOp(Op, InL, InH);
1752   SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
1753                                DAG.getConstant(NVTBits, ShTy), ShAmt);
1754
1755   // Compare the unmasked shift amount against 32.
1756   SDOperand Cond = DAG.getSetCC(ISD::SETGE, TLI.getSetCCResultTy(), ShAmt,
1757                                 DAG.getConstant(NVTBits, ShTy));
1758
1759   if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
1760     ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
1761                         DAG.getConstant(NVTBits-1, ShTy));
1762     NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
1763                         DAG.getConstant(NVTBits-1, ShTy));
1764   }
1765
1766   if (Opc == ISD::SHL) {
1767     SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
1768                                DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
1769                                DAG.getNode(ISD::SRL, NVT, InL, NAmt));
1770     SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
1771
1772     Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1773     Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
1774   } else {
1775     SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
1776                                      DAG.getSetCC(ISD::SETEQ,
1777                                                   TLI.getSetCCResultTy(), NAmt,
1778                                                   DAG.getConstant(32, ShTy)),
1779                                      DAG.getConstant(0, NVT),
1780                                      DAG.getNode(ISD::SHL, NVT, InH, NAmt));
1781     SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
1782                                HiLoPart,
1783                                DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
1784     SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);  // T2 = InH >> ShAmt&31
1785
1786     SDOperand HiPart;
1787     if (Opc == ISD::SRA)
1788       HiPart = DAG.getNode(ISD::SRA, NVT, InH,
1789                            DAG.getConstant(NVTBits-1, ShTy));
1790     else
1791       HiPart = DAG.getConstant(0, NVT);
1792     Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1793     Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
1794   }
1795   return true;
1796 }
1797
1798 /// FindLatestAdjCallStackDown - Scan up the dag to find the latest (highest
1799 /// NodeDepth) node that is an AdjCallStackDown operation and occurs later than
1800 /// Found.
1801 static void FindLatestAdjCallStackDown(SDNode *Node, SDNode *&Found) {
1802   if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
1803
1804   // If we found an ADJCALLSTACKDOWN, we already know this node occurs later
1805   // than the Found node. Just remember this node and return.
1806   if (Node->getOpcode() == ISD::ADJCALLSTACKDOWN) {
1807     Found = Node;
1808     return;
1809   }
1810
1811   // Otherwise, scan the operands of Node to see if any of them is a call.
1812   assert(Node->getNumOperands() != 0 &&
1813          "All leaves should have depth equal to the entry node!");
1814   for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
1815     FindLatestAdjCallStackDown(Node->getOperand(i).Val, Found);
1816
1817   // Tail recurse for the last iteration.
1818   FindLatestAdjCallStackDown(Node->getOperand(Node->getNumOperands()-1).Val,
1819                              Found);
1820 }
1821
1822
1823 /// FindEarliestAdjCallStackUp - Scan down the dag to find the earliest (lowest
1824 /// NodeDepth) node that is an AdjCallStackUp operation and occurs more recent
1825 /// than Found.
1826 static void FindEarliestAdjCallStackUp(SDNode *Node, SDNode *&Found) {
1827   if (Found && Node->getNodeDepth() >= Found->getNodeDepth()) return;
1828
1829   // If we found an ADJCALLSTACKUP, we already know this node occurs earlier
1830   // than the Found node. Just remember this node and return.
1831   if (Node->getOpcode() == ISD::ADJCALLSTACKUP) {
1832     Found = Node;
1833     return;
1834   }
1835
1836   // Otherwise, scan the operands of Node to see if any of them is a call.
1837   SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
1838   if (UI == E) return;
1839   for (--E; UI != E; ++UI)
1840     FindEarliestAdjCallStackUp(*UI, Found);
1841
1842   // Tail recurse for the last iteration.
1843   FindEarliestAdjCallStackUp(*UI, Found);
1844 }
1845
1846 /// FindAdjCallStackUp - Given a chained node that is part of a call sequence,
1847 /// find the ADJCALLSTACKUP node that terminates the call sequence.
1848 static SDNode *FindAdjCallStackUp(SDNode *Node) {
1849   if (Node->getOpcode() == ISD::ADJCALLSTACKUP)
1850     return Node;
1851   if (Node->use_empty())
1852     return 0;   // No adjcallstackup
1853
1854   if (Node->hasOneUse())  // Simple case, only has one user to check.
1855     return FindAdjCallStackUp(*Node->use_begin());
1856
1857   SDOperand TheChain(Node, Node->getNumValues()-1);
1858   assert(TheChain.getValueType() == MVT::Other && "Is not a token chain!");
1859
1860   for (SDNode::use_iterator UI = Node->use_begin(),
1861          E = Node->use_end(); ; ++UI) {
1862     assert(UI != E && "Didn't find a user of the tokchain, no ADJCALLSTACKUP!");
1863
1864     // Make sure to only follow users of our token chain.
1865     SDNode *User = *UI;
1866     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1867       if (User->getOperand(i) == TheChain)
1868         return FindAdjCallStackUp(User);
1869   }
1870   assert(0 && "Unreachable");
1871   abort();
1872 }
1873
1874 /// FindInputOutputChains - If we are replacing an operation with a call we need
1875 /// to find the call that occurs before and the call that occurs after it to
1876 /// properly serialize the calls in the block.
1877 static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
1878                                        SDOperand Entry) {
1879   SDNode *LatestAdjCallStackDown = Entry.Val;
1880   SDNode *LatestAdjCallStackUp = 0;
1881   FindLatestAdjCallStackDown(OpNode, LatestAdjCallStackDown);
1882   //std::cerr << "Found node: "; LatestAdjCallStackDown->dump(); std::cerr <<"\n";
1883
1884   // It is possible that no ISD::ADJCALLSTACKDOWN was found because there is no
1885   // previous call in the function.  LatestCallStackDown may in that case be
1886   // the entry node itself.  Do not attempt to find a matching ADJCALLSTACKUP
1887   // unless LatestCallStackDown is an ADJCALLSTACKDOWN.
1888   if (LatestAdjCallStackDown->getOpcode() == ISD::ADJCALLSTACKDOWN)
1889     LatestAdjCallStackUp = FindAdjCallStackUp(LatestAdjCallStackDown);
1890   else
1891     LatestAdjCallStackUp = Entry.Val;
1892   assert(LatestAdjCallStackUp && "NULL return from FindAdjCallStackUp");
1893
1894   SDNode *EarliestAdjCallStackUp = 0;
1895   FindEarliestAdjCallStackUp(OpNode, EarliestAdjCallStackUp);
1896
1897   if (EarliestAdjCallStackUp) {
1898     //std::cerr << "Found node: ";
1899     //EarliestAdjCallStackUp->dump(); std::cerr <<"\n";
1900   }
1901
1902   return SDOperand(LatestAdjCallStackUp, 0);
1903 }
1904
1905
1906
1907 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
1908 // does not fit into a register, return the lo part and set the hi part to the
1909 // by-reg argument.  If it does fit into a single register, return the result
1910 // and leave the Hi part unset.
1911 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
1912                                               SDOperand &Hi) {
1913   SDNode *OutChain;
1914   SDOperand InChain = FindInputOutputChains(Node, OutChain,
1915                                             DAG.getEntryNode());
1916   if (InChain.Val == 0)
1917     InChain = DAG.getEntryNode();
1918
1919   TargetLowering::ArgListTy Args;
1920   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1921     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
1922     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
1923     Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
1924   }
1925   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
1926
1927   // We don't care about token chains for libcalls.  We just use the entry
1928   // node as our input and ignore the output chain.  This allows us to place
1929   // calls wherever we need them to satisfy data dependences.
1930   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
1931   SDOperand Result = TLI.LowerCallTo(InChain, RetTy, false, Callee,
1932                                      Args, DAG).first;
1933   switch (getTypeAction(Result.getValueType())) {
1934   default: assert(0 && "Unknown thing");
1935   case Legal:
1936     return Result;
1937   case Promote:
1938     assert(0 && "Cannot promote this yet!");
1939   case Expand:
1940     SDOperand Lo;
1941     ExpandOp(Result, Lo, Hi);
1942     return Lo;
1943   }
1944 }
1945
1946
1947 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
1948 /// destination type is legal.
1949 SDOperand SelectionDAGLegalize::
1950 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
1951   assert(getTypeAction(DestTy) == Legal && "Destination type is not legal!");
1952   assert(getTypeAction(Source.getValueType()) == Expand &&
1953          "This is not an expansion!");
1954   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1955
1956   SDNode *OutChain;
1957   SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
1958                                             DAG.getEntryNode());
1959
1960   const char *FnName = 0;
1961   if (isSigned) {
1962     if (DestTy == MVT::f32)
1963       FnName = "__floatdisf";
1964     else {
1965       assert(DestTy == MVT::f64 && "Unknown fp value type!");
1966       FnName = "__floatdidf";
1967     }
1968   } else {
1969     // If this is unsigned, and not supported, first perform the conversion to
1970     // signed, then adjust the result if the sign bit is set.
1971     SDOperand SignedConv = ExpandIntToFP(true, DestTy, Source);
1972
1973     assert(Source.getValueType() == MVT::i64 &&
1974            "This only works for 64-bit -> FP");
1975     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
1976     // incoming integer is set.  To handle this, we dynamically test to see if
1977     // it is set, and, if so, add a fudge factor.
1978     SDOperand Lo, Hi;
1979     ExpandOp(Source, Lo, Hi);
1980
1981     SDOperand SignSet = DAG.getSetCC(ISD::SETLT, TLI.getSetCCResultTy(), Hi,
1982                                      DAG.getConstant(0, Hi.getValueType()));
1983     SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
1984     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
1985                                       SignSet, Four, Zero);
1986     // FIXME: This is almost certainly broken for big-endian systems.  Should
1987     // this just put the fudge factor in the low bits of the uint64 constant or?
1988     static Constant *FudgeFactor =
1989       ConstantUInt::get(Type::ULongTy, 0x5f800000ULL << 32);
1990
1991     MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
1992     SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(FudgeFactor),
1993                                           TLI.getPointerTy());
1994     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
1995     SDOperand FudgeInReg;
1996     if (DestTy == MVT::f32)
1997       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
1998     else {
1999       assert(DestTy == MVT::f64 && "Unexpected conversion");
2000       FudgeInReg = DAG.getNode(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
2001                                CPIdx, DAG.getSrcValue(NULL), MVT::f32);
2002     }
2003     return DAG.getNode(ISD::ADD, DestTy, SignedConv, FudgeInReg);
2004   }
2005   SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
2006
2007   TargetLowering::ArgListTy Args;
2008   const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
2009   Args.push_back(std::make_pair(Source, ArgTy));
2010
2011   // We don't care about token chains for libcalls.  We just use the entry
2012   // node as our input and ignore the output chain.  This allows us to place
2013   // calls wherever we need them to satisfy data dependences.
2014   const Type *RetTy = MVT::getTypeForValueType(DestTy);
2015   return TLI.LowerCallTo(InChain, RetTy, false, Callee, Args, DAG).first;
2016 }
2017
2018
2019
2020 /// ExpandOp - Expand the specified SDOperand into its two component pieces
2021 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
2022 /// LegalizeNodes map is filled in for any results that are not expanded, the
2023 /// ExpandedNodes map is filled in for any results that are expanded, and the
2024 /// Lo/Hi values are returned.
2025 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
2026   MVT::ValueType VT = Op.getValueType();
2027   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2028   SDNode *Node = Op.Val;
2029   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
2030   assert(MVT::isInteger(VT) && "Cannot expand FP values!");
2031   assert(MVT::isInteger(NVT) && NVT < VT &&
2032          "Cannot expand to FP value or to larger int value!");
2033
2034   // If there is more than one use of this, see if we already expanded it.
2035   // There is no use remembering values that only have a single use, as the map
2036   // entries will never be reused.
2037   if (!Node->hasOneUse()) {
2038     std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
2039       = ExpandedNodes.find(Op);
2040     if (I != ExpandedNodes.end()) {
2041       Lo = I->second.first;
2042       Hi = I->second.second;
2043       return;
2044     }
2045   }
2046
2047   // Expanding to multiple registers needs to perform an optimization step, and
2048   // is not careful to avoid operations the target does not support.  Make sure
2049   // that all generated operations are legalized in the next iteration.
2050   NeedsAnotherIteration = true;
2051
2052   switch (Node->getOpcode()) {
2053   default:
2054     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2055     assert(0 && "Do not know how to expand this operator!");
2056     abort();
2057   case ISD::UNDEF:
2058     Lo = DAG.getNode(ISD::UNDEF, NVT);
2059     Hi = DAG.getNode(ISD::UNDEF, NVT);
2060     break;
2061   case ISD::Constant: {
2062     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
2063     Lo = DAG.getConstant(Cst, NVT);
2064     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
2065     break;
2066   }
2067
2068   case ISD::CopyFromReg: {
2069     unsigned Reg = cast<RegSDNode>(Node)->getReg();
2070     // Aggregate register values are always in consequtive pairs.
2071     Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
2072     Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
2073
2074     // Remember that we legalized the chain.
2075     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
2076
2077     assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
2078     break;
2079   }
2080
2081   case ISD::BUILD_PAIR:
2082     // Legalize both operands.  FIXME: in the future we should handle the case
2083     // where the two elements are not legal.
2084     assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
2085     Lo = LegalizeOp(Node->getOperand(0));
2086     Hi = LegalizeOp(Node->getOperand(1));
2087     break;
2088
2089   case ISD::LOAD: {
2090     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2091     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2092     Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
2093
2094     // Increment the pointer to the other half.
2095     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
2096     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
2097                       getIntPtrConstant(IncrementSize));
2098     //Is this safe?  declaring that the two parts of the split load  
2099     //are from the same instruction?
2100     Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
2101
2102     // Build a factor node to remember that this load is independent of the
2103     // other one.
2104     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2105                                Hi.getValue(1));
2106
2107     // Remember that we legalized the chain.
2108     AddLegalizedOperand(Op.getValue(1), TF);
2109     if (!TLI.isLittleEndian())
2110       std::swap(Lo, Hi);
2111     break;
2112   }
2113   case ISD::CALL: {
2114     SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2115     SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
2116
2117     bool Changed = false;
2118     std::vector<SDOperand> Ops;
2119     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
2120       Ops.push_back(LegalizeOp(Node->getOperand(i)));
2121       Changed |= Ops.back() != Node->getOperand(i);
2122     }
2123
2124     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
2125            "Can only expand a call once so far, not i64 -> i16!");
2126
2127     std::vector<MVT::ValueType> RetTyVTs;
2128     RetTyVTs.reserve(3);
2129     RetTyVTs.push_back(NVT);
2130     RetTyVTs.push_back(NVT);
2131     RetTyVTs.push_back(MVT::Other);
2132     SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops);
2133     Lo = SDOperand(NC, 0);
2134     Hi = SDOperand(NC, 1);
2135
2136     // Insert the new chain mapping.
2137     AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
2138     break;
2139   }
2140   case ISD::AND:
2141   case ISD::OR:
2142   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
2143     SDOperand LL, LH, RL, RH;
2144     ExpandOp(Node->getOperand(0), LL, LH);
2145     ExpandOp(Node->getOperand(1), RL, RH);
2146     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
2147     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
2148     break;
2149   }
2150   case ISD::SELECT: {
2151     SDOperand C, LL, LH, RL, RH;
2152
2153     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2154     case Expand: assert(0 && "It's impossible to expand bools");
2155     case Legal:
2156       C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2157       break;
2158     case Promote:
2159       C = PromoteOp(Node->getOperand(0));  // Promote the condition.
2160       break;
2161     }
2162     ExpandOp(Node->getOperand(1), LL, LH);
2163     ExpandOp(Node->getOperand(2), RL, RH);
2164     Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
2165     Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
2166     break;
2167   }
2168   case ISD::SIGN_EXTEND: {
2169     SDOperand In;
2170     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2171     case Expand: assert(0 && "expand-expand not implemented yet!");
2172     case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2173     case Promote:
2174       In = PromoteOp(Node->getOperand(0));
2175       // Emit the appropriate sign_extend_inreg to get the value we want.
2176       In = DAG.getNode(ISD::SIGN_EXTEND_INREG, In.getValueType(), In,
2177                        Node->getOperand(0).getValueType());
2178       break;
2179     }
2180
2181     // The low part is just a sign extension of the input (which degenerates to
2182     // a copy).
2183     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, In);
2184
2185     // The high part is obtained by SRA'ing all but one of the bits of the lo
2186     // part.
2187     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
2188     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
2189                                                        TLI.getShiftAmountTy()));
2190     break;
2191   }
2192   case ISD::ZERO_EXTEND: {
2193     SDOperand In;
2194     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2195     case Expand: assert(0 && "expand-expand not implemented yet!");
2196     case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2197     case Promote:
2198       In = PromoteOp(Node->getOperand(0));
2199       // Emit the appropriate zero_extend_inreg to get the value we want.
2200       In = DAG.getZeroExtendInReg(In, Node->getOperand(0).getValueType());
2201       break;
2202     }
2203
2204     // The low part is just a zero extension of the input (which degenerates to
2205     // a copy).
2206     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, In);
2207
2208     // The high part is just a zero.
2209     Hi = DAG.getConstant(0, NVT);
2210     break;
2211   }
2212     // These operators cannot be expanded directly, emit them as calls to
2213     // library functions.
2214   case ISD::FP_TO_SINT:
2215     if (Node->getOperand(0).getValueType() == MVT::f32)
2216       Lo = ExpandLibCall("__fixsfdi", Node, Hi);
2217     else
2218       Lo = ExpandLibCall("__fixdfdi", Node, Hi);
2219     break;
2220   case ISD::FP_TO_UINT:
2221     if (Node->getOperand(0).getValueType() == MVT::f32)
2222       Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
2223     else
2224       Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
2225     break;
2226
2227   case ISD::SHL:
2228     // If we can emit an efficient shift operation, do so now.
2229     if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2230       break;
2231
2232     // If this target supports SHL_PARTS, use it.
2233     if (TLI.getOperationAction(ISD::SHL_PARTS, NVT) == TargetLowering::Legal) {
2234       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), Node->getOperand(1),
2235                        Lo, Hi);
2236       break;
2237     }
2238
2239     // Otherwise, emit a libcall.
2240     Lo = ExpandLibCall("__ashldi3", Node, Hi);
2241     break;
2242
2243   case ISD::SRA:
2244     // If we can emit an efficient shift operation, do so now.
2245     if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2246       break;
2247
2248     // If this target supports SRA_PARTS, use it.
2249     if (TLI.getOperationAction(ISD::SRA_PARTS, NVT) == TargetLowering::Legal) {
2250       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), Node->getOperand(1),
2251                        Lo, Hi);
2252       break;
2253     }
2254
2255     // Otherwise, emit a libcall.
2256     Lo = ExpandLibCall("__ashrdi3", Node, Hi);
2257     break;
2258   case ISD::SRL:
2259     // If we can emit an efficient shift operation, do so now.
2260     if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2261       break;
2262
2263     // If this target supports SRL_PARTS, use it.
2264     if (TLI.getOperationAction(ISD::SRL_PARTS, NVT) == TargetLowering::Legal) {
2265       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), Node->getOperand(1),
2266                        Lo, Hi);
2267       break;
2268     }
2269
2270     // Otherwise, emit a libcall.
2271     Lo = ExpandLibCall("__lshrdi3", Node, Hi);
2272     break;
2273
2274   case ISD::ADD:
2275     ExpandByParts(ISD::ADD_PARTS, Node->getOperand(0), Node->getOperand(1),
2276                   Lo, Hi);
2277     break;
2278   case ISD::SUB:
2279     ExpandByParts(ISD::SUB_PARTS, Node->getOperand(0), Node->getOperand(1),
2280                   Lo, Hi);
2281     break;
2282   case ISD::MUL: {
2283     if (TLI.getOperationAction(ISD::MULHU, NVT) == TargetLowering::Legal) {
2284       SDOperand LL, LH, RL, RH;
2285       ExpandOp(Node->getOperand(0), LL, LH);
2286       ExpandOp(Node->getOperand(1), RL, RH);
2287       Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
2288       RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
2289       LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
2290       Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
2291       Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
2292       Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
2293     } else {
2294       Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
2295     }
2296     break;
2297   }
2298   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
2299   case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
2300   case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
2301   case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
2302   }
2303
2304   // Remember in a map if the values will be reused later.
2305   if (!Node->hasOneUse()) {
2306     bool isNew = ExpandedNodes.insert(std::make_pair(Op,
2307                                             std::make_pair(Lo, Hi))).second;
2308     assert(isNew && "Value already expanded?!?");
2309   }
2310 }
2311
2312
2313 // SelectionDAG::Legalize - This is the entry point for the file.
2314 //
2315 void SelectionDAG::Legalize() {
2316   /// run - This is the main entry point to this class.
2317   ///
2318   SelectionDAGLegalize(*this).Run();
2319 }
2320