move a bunch of code, no other change.
[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/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/Support/MathExtras.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include <iostream>
24 #include <set>
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
29 /// hacks on it until the target machine can handle it.  This involves
30 /// eliminating value sizes the machine cannot handle (promoting small sizes to
31 /// large sizes or splitting up large values into small values) as well as
32 /// eliminating operations the machine cannot handle.
33 ///
34 /// This code also does a small amount of optimization and recognition of idioms
35 /// as part of its processing.  For example, if a target does not support a
36 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
37 /// will attempt merge setcc and brc instructions into brcc's.
38 ///
39 namespace {
40 class SelectionDAGLegalize {
41   TargetLowering &TLI;
42   SelectionDAG &DAG;
43
44   /// LegalizeAction - This enum indicates what action we should take for each
45   /// value type the can occur in the program.
46   enum LegalizeAction {
47     Legal,            // The target natively supports this value type.
48     Promote,          // This should be promoted to the next larger type.
49     Expand,           // This integer type should be broken into smaller pieces.
50   };
51
52   /// ValueTypeActions - This is a bitvector that contains two bits for each
53   /// value type, where the two bits correspond to the LegalizeAction enum.
54   /// This can be queried with "getTypeAction(VT)".
55   unsigned long long ValueTypeActions;
56
57   /// LegalizedNodes - For nodes that are of legal width, and that have more
58   /// than one use, this map indicates what regularized operand to use.  This
59   /// allows us to avoid legalizing the same thing more than once.
60   std::map<SDOperand, SDOperand> LegalizedNodes;
61
62   /// PromotedNodes - For nodes that are below legal width, and that have more
63   /// than one use, this map indicates what promoted value to use.  This allows
64   /// us to avoid promoting the same thing more than once.
65   std::map<SDOperand, SDOperand> PromotedNodes;
66
67   /// ExpandedNodes - For nodes that need to be expanded, and which have more
68   /// than one use, this map indicates which which operands are the expanded
69   /// version of the input.  This allows us to avoid expanding the same node
70   /// more than once.
71   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
72
73   void AddLegalizedOperand(SDOperand From, SDOperand To) {
74     LegalizedNodes.insert(std::make_pair(From, To));
75     // If someone requests legalization of the new node, return itself.
76     if (From != To)
77       LegalizedNodes.insert(std::make_pair(To, To));
78   }
79   void AddPromotedOperand(SDOperand From, SDOperand To) {
80     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
81     assert(isNew && "Got into the map somehow?");
82     // If someone requests legalization of the new node, return itself.
83     LegalizedNodes.insert(std::make_pair(To, To));
84   }
85
86 public:
87
88   SelectionDAGLegalize(SelectionDAG &DAG);
89
90   /// getTypeAction - Return how we should legalize values of this type, either
91   /// it is already legal or we need to expand it into multiple registers of
92   /// smaller integer type, or we need to promote it to a larger type.
93   LegalizeAction getTypeAction(MVT::ValueType VT) const {
94     return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
95   }
96
97   /// isTypeLegal - Return true if this type is legal on this target.
98   ///
99   bool isTypeLegal(MVT::ValueType VT) const {
100     return getTypeAction(VT) == Legal;
101   }
102
103   void LegalizeDAG();
104
105 private:
106
107   SDOperand LegalizeOp(SDOperand O);
108   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
109   SDOperand PromoteOp(SDOperand O);
110
111   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
112                           SDOperand &Hi);
113   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
114                           SDOperand Source);
115
116   SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
117   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
118                                  SDOperand LegalOp,
119                                  MVT::ValueType DestVT);
120   SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
121                                   bool isSigned);
122   SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
123                                   bool isSigned);
124
125   SDOperand ExpandBSWAP(SDOperand Op);
126   SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
127   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
128                    SDOperand &Lo, SDOperand &Hi);
129   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
130                         SDOperand &Lo, SDOperand &Hi);
131   void SpliceCallInto(const SDOperand &CallResult, SDNode *OutChain);
132
133   SDOperand getIntPtrConstant(uint64_t Val) {
134     return DAG.getConstant(Val, TLI.getPointerTy());
135   }
136 };
137 }
138
139 static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
140   switch (VecOp) {
141   default: assert(0 && "Don't know how to scalarize this opcode!");
142   case ISD::VADD: return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
143   case ISD::VSUB: return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
144   case ISD::VMUL: return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
145   }
146 }
147
148 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
149   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
150     ValueTypeActions(TLI.getValueTypeActions()) {
151   assert(MVT::LAST_VALUETYPE <= 32 &&
152          "Too many value types for ValueTypeActions to hold!");
153 }
154
155 /// ComputeTopDownOrdering - Add the specified node to the Order list if it has
156 /// not been visited yet and if all of its operands have already been visited.
157 static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
158                                    std::map<SDNode*, unsigned> &Visited) {
159   if (++Visited[N] != N->getNumOperands())
160     return;  // Haven't visited all operands yet
161   
162   Order.push_back(N);
163   
164   if (N->hasOneUse()) { // Tail recurse in common case.
165     ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
166     return;
167   }
168   
169   // Now that we have N in, add anything that uses it if all of their operands
170   // are now done.
171   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
172     ComputeTopDownOrdering(*UI, Order, Visited);
173 }
174
175
176 void SelectionDAGLegalize::LegalizeDAG() {
177   // The legalize process is inherently a bottom-up recursive process (users
178   // legalize their uses before themselves).  Given infinite stack space, we
179   // could just start legalizing on the root and traverse the whole graph.  In
180   // practice however, this causes us to run out of stack space on large basic
181   // blocks.  To avoid this problem, compute an ordering of the nodes where each
182   // node is only legalized after all of its operands are legalized.
183   std::map<SDNode*, unsigned> Visited;
184   std::vector<SDNode*> Order;
185   
186   // Compute ordering from all of the leaves in the graphs, those (like the
187   // entry node) that have no operands.
188   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
189        E = DAG.allnodes_end(); I != E; ++I) {
190     if (I->getNumOperands() == 0) {
191       Visited[I] = 0 - 1U;
192       ComputeTopDownOrdering(I, Order, Visited);
193     }
194   }
195   
196   assert(Order.size() == Visited.size() &&
197          Order.size() == 
198             (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
199          "Error: DAG is cyclic!");
200   Visited.clear();
201   
202   for (unsigned i = 0, e = Order.size(); i != e; ++i) {
203     SDNode *N = Order[i];
204     switch (getTypeAction(N->getValueType(0))) {
205     default: assert(0 && "Bad type action!");
206     case Legal:
207       LegalizeOp(SDOperand(N, 0));
208       break;
209     case Promote:
210       PromoteOp(SDOperand(N, 0));
211       break;
212     case Expand: {
213       SDOperand X, Y;
214       ExpandOp(SDOperand(N, 0), X, Y);
215       break;
216     }
217     }
218   }
219
220   // Finally, it's possible the root changed.  Get the new root.
221   SDOperand OldRoot = DAG.getRoot();
222   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
223   DAG.setRoot(LegalizedNodes[OldRoot]);
224
225   ExpandedNodes.clear();
226   LegalizedNodes.clear();
227   PromotedNodes.clear();
228
229   // Remove dead nodes now.
230   DAG.RemoveDeadNodes(OldRoot.Val);
231 }
232
233 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
234   assert(isTypeLegal(Op.getValueType()) &&
235          "Caller should expand or promote operands that are not legal!");
236   SDNode *Node = Op.Val;
237
238   // If this operation defines any values that cannot be represented in a
239   // register on this target, make sure to expand or promote them.
240   if (Node->getNumValues() > 1) {
241     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
242       switch (getTypeAction(Node->getValueType(i))) {
243       case Legal: break;  // Nothing to do.
244       case Expand: {
245         SDOperand T1, T2;
246         ExpandOp(Op.getValue(i), T1, T2);
247         assert(LegalizedNodes.count(Op) &&
248                "Expansion didn't add legal operands!");
249         return LegalizedNodes[Op];
250       }
251       case Promote:
252         PromoteOp(Op.getValue(i));
253         assert(LegalizedNodes.count(Op) &&
254                "Promotion didn't add legal operands!");
255         return LegalizedNodes[Op];
256       }
257   }
258
259   // Note that LegalizeOp may be reentered even from single-use nodes, which
260   // means that we always must cache transformed nodes.
261   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
262   if (I != LegalizedNodes.end()) return I->second;
263
264   SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
265   SDOperand Result = Op;
266   bool isCustom = false;
267   
268   switch (Node->getOpcode()) {
269   default:
270     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
271       // If this is a target node, legalize it by legalizing the operands then
272       // passing it through.
273       std::vector<SDOperand> Ops;
274       bool Changed = false;
275       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
276         Ops.push_back(LegalizeOp(Node->getOperand(i)));
277         Changed = Changed || Node->getOperand(i) != Ops.back();
278       }
279       if (Changed)
280         if (Node->getNumValues() == 1)
281           Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
282         else {
283           std::vector<MVT::ValueType> VTs(Node->value_begin(),
284                                           Node->value_end());
285           Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
286         }
287
288       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
289         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
290       return Result.getValue(Op.ResNo);
291     }
292     // Otherwise this is an unhandled builtin node.  splat.
293     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
294     assert(0 && "Do not know how to legalize this operator!");
295     abort();
296   case ISD::EntryToken:
297   case ISD::FrameIndex:
298   case ISD::TargetFrameIndex:
299   case ISD::Register:
300   case ISD::TargetConstant:
301   case ISD::TargetConstantPool:
302   case ISD::GlobalAddress:
303   case ISD::TargetGlobalAddress:
304   case ISD::ExternalSymbol:
305   case ISD::TargetExternalSymbol:
306   case ISD::ConstantPool:           // Nothing to do.
307   case ISD::BasicBlock:
308   case ISD::CONDCODE:
309   case ISD::VALUETYPE:
310   case ISD::SRCVALUE:
311   case ISD::STRING:
312     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
313     default: assert(0 && "This action is not supported yet!");
314     case TargetLowering::Custom: {
315       SDOperand Tmp = TLI.LowerOperation(Op, DAG);
316       if (Tmp.Val) {
317         Result = Tmp;
318         break;
319       }
320     } // FALLTHROUGH if the target doesn't want to lower this op after all.
321     case TargetLowering::Legal:
322       assert(isTypeLegal(Node->getValueType(0)) && "This must be legal!");
323       break;
324     }
325     break;
326   case ISD::AssertSext:
327   case ISD::AssertZext:
328     Tmp1 = LegalizeOp(Node->getOperand(0));
329     if (Tmp1 != Node->getOperand(0))
330       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
331                            Node->getOperand(1));
332     break;
333   case ISD::MERGE_VALUES:
334     Result = Node->getOperand(Op.ResNo);
335     break;
336   case ISD::CopyFromReg:
337     Tmp1 = LegalizeOp(Node->getOperand(0));
338     Result = Op.getValue(0);
339     if (Node->getNumValues() == 2) {
340       if (Tmp1 != Node->getOperand(0))
341         Result = DAG.getCopyFromReg(Tmp1, 
342                             cast<RegisterSDNode>(Node->getOperand(1))->getReg(),
343                                     Node->getValueType(0));
344     } else {
345       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
346       if (Node->getNumOperands() == 3)
347         Tmp2 = LegalizeOp(Node->getOperand(2));
348       if (Tmp1 != Node->getOperand(0) ||
349           (Node->getNumOperands() == 3 && Tmp2 != Node->getOperand(2)))
350         Result = DAG.getCopyFromReg(Tmp1, 
351                             cast<RegisterSDNode>(Node->getOperand(1))->getReg(),
352                                     Node->getValueType(0), Tmp2);
353       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
354     }
355     // Since CopyFromReg produces two values, make sure to remember that we
356     // legalized both of them.
357     AddLegalizedOperand(Op.getValue(0), Result);
358     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
359     return Result.getValue(Op.ResNo);
360   case ISD::UNDEF: {
361     MVT::ValueType VT = Op.getValueType();
362     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
363     default: assert(0 && "This action is not supported yet!");
364     case TargetLowering::Expand:
365       if (MVT::isInteger(VT))
366         Result = DAG.getConstant(0, VT);
367       else if (MVT::isFloatingPoint(VT))
368         Result = DAG.getConstantFP(0, VT);
369       else
370         assert(0 && "Unknown value type!");
371       break;
372     case TargetLowering::Legal:
373       break;
374     }
375     break;
376   }
377
378   case ISD::LOCATION:
379     assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
380     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
381     
382     switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
383     case TargetLowering::Promote:
384     default: assert(0 && "This action is not supported yet!");
385     case TargetLowering::Expand: {
386       MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
387       bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
388       bool useDEBUG_LABEL = TLI.isOperationLegal(ISD::DEBUG_LABEL, MVT::Other);
389       
390       if (DebugInfo && (useDEBUG_LOC || useDEBUG_LABEL)) {
391         const std::string &FName =
392           cast<StringSDNode>(Node->getOperand(3))->getValue();
393         const std::string &DirName = 
394           cast<StringSDNode>(Node->getOperand(4))->getValue();
395         unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
396
397         std::vector<SDOperand> Ops;
398         Ops.push_back(Tmp1);  // chain
399         SDOperand LineOp = Node->getOperand(1);
400         SDOperand ColOp = Node->getOperand(2);
401         
402         if (useDEBUG_LOC) {
403           Ops.push_back(LineOp);  // line #
404           Ops.push_back(ColOp);  // col #
405           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
406           Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
407         } else {
408           unsigned Line = dyn_cast<ConstantSDNode>(LineOp)->getValue();
409           unsigned Col = dyn_cast<ConstantSDNode>(ColOp)->getValue();
410           unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
411           Ops.push_back(DAG.getConstant(ID, MVT::i32));
412           Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
413         }
414       } else {
415         Result = Tmp1;  // chain
416       }
417       break;
418     }
419     case TargetLowering::Legal:
420       if (Tmp1 != Node->getOperand(0) ||
421           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
422         std::vector<SDOperand> Ops;
423         Ops.push_back(Tmp1);
424         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
425           Ops.push_back(Node->getOperand(1));  // line # must be legal.
426           Ops.push_back(Node->getOperand(2));  // col # must be legal.
427         } else {
428           // Otherwise promote them.
429           Ops.push_back(PromoteOp(Node->getOperand(1)));
430           Ops.push_back(PromoteOp(Node->getOperand(2)));
431         }
432         Ops.push_back(Node->getOperand(3));  // filename must be legal.
433         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
434         Result = DAG.getNode(ISD::LOCATION, MVT::Other, Ops);
435       }
436       break;
437     }
438     break;
439     
440   case ISD::DEBUG_LOC:
441     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
442     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
443     default: assert(0 && "This action is not supported yet!");
444     case TargetLowering::Legal:
445       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
446       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
447       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
448       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
449       
450       if (Tmp1 != Node->getOperand(0) ||
451           Tmp2 != Node->getOperand(1) ||
452           Tmp3 != Node->getOperand(2) ||
453           Tmp4 != Node->getOperand(3)) {
454         Result = DAG.getNode(ISD::DEBUG_LOC,MVT::Other, Tmp1, Tmp2, Tmp3, Tmp4);
455       }
456       break;
457     }
458     break;    
459
460   case ISD::DEBUG_LABEL:
461     assert(Node->getNumOperands() == 2 && "Invalid DEBUG_LABEL node!");
462     switch (TLI.getOperationAction(ISD::DEBUG_LABEL, MVT::Other)) {
463     default: assert(0 && "This action is not supported yet!");
464     case TargetLowering::Legal:
465       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
466       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
467       
468       if (Tmp1 != Node->getOperand(0) ||
469           Tmp2 != Node->getOperand(1)) {
470         Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Tmp1, Tmp2);
471       }
472       break;
473     }
474     break;    
475
476   case ISD::Constant:
477     // We know we don't need to expand constants here, constants only have one
478     // value and we check that it is fine above.
479
480     // FIXME: Maybe we should handle things like targets that don't support full
481     // 32-bit immediates?
482     break;
483   case ISD::ConstantFP: {
484     // Spill FP immediates to the constant pool if the target cannot directly
485     // codegen them.  Targets often have some immediate values that can be
486     // efficiently generated into an FP register without a load.  We explicitly
487     // leave these constants as ConstantFP nodes for the target to deal with.
488     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
489
490     // Check to see if this FP immediate is already legal.
491     bool isLegal = false;
492     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
493            E = TLI.legal_fpimm_end(); I != E; ++I)
494       if (CFP->isExactlyValue(*I)) {
495         isLegal = true;
496         break;
497       }
498
499     if (!isLegal) {
500       // Otherwise we need to spill the constant to memory.
501       bool Extend = false;
502
503       // If a FP immediate is precise when represented as a float and if the
504       // target can do an extending load from float to double, we put it into
505       // the constant pool as a float, even if it's is statically typed as a
506       // double.
507       MVT::ValueType VT = CFP->getValueType(0);
508       bool isDouble = VT == MVT::f64;
509       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
510                                              Type::FloatTy, CFP->getValue());
511       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
512           // Only do this if the target has a native EXTLOAD instruction from
513           // f32.
514           TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
515         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
516         VT = MVT::f32;
517         Extend = true;
518       }
519
520       SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
521       if (Extend) {
522         Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
523                                 CPIdx, DAG.getSrcValue(NULL), MVT::f32);
524       } else {
525         Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
526                              DAG.getSrcValue(NULL));
527       }
528     }
529     break;
530   }
531   case ISD::ConstantVec: {
532     // We assume that vector constants are not legal, and will be immediately
533     // spilled to the constant pool.
534     //
535     // FIXME: Allow custom lowering to TargetConstantVec's.
536     //
537     // Create a ConstantPacked, and put it in the constant pool.
538     std::vector<Constant*> CV;
539     MVT::ValueType VT = Node->getValueType(0);
540     for (unsigned I = 0, E = Node->getNumOperands(); I < E; ++I) {
541       SDOperand OpN = Node->getOperand(I);
542       const Type* OpNTy = MVT::getTypeForValueType(OpN.getValueType());
543       if (MVT::isFloatingPoint(VT))
544         CV.push_back(ConstantFP::get(OpNTy, 
545                                      cast<ConstantFPSDNode>(OpN)->getValue()));
546       else
547         CV.push_back(ConstantUInt::get(OpNTy,
548                                        cast<ConstantSDNode>(OpN)->getValue()));
549     }
550     Constant *CP = ConstantPacked::get(CV);
551     SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
552     Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
553     break;
554   }
555   case ISD::TokenFactor:
556     if (Node->getNumOperands() == 2) {
557       bool Changed = false;
558       SDOperand Op0 = LegalizeOp(Node->getOperand(0));
559       SDOperand Op1 = LegalizeOp(Node->getOperand(1));
560       if (Op0 != Node->getOperand(0) || Op1 != Node->getOperand(1))
561         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
562     } else {
563       std::vector<SDOperand> Ops;
564       bool Changed = false;
565       // Legalize the operands.
566       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
567         SDOperand Op = Node->getOperand(i);
568         Ops.push_back(LegalizeOp(Op));
569         Changed |= Ops[i] != Op;
570       }
571       if (Changed)
572         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
573     }
574     break;
575
576   case ISD::CALLSEQ_START:
577   case ISD::CALLSEQ_END:
578     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
579     // Do not try to legalize the target-specific arguments (#1+)
580     Tmp2 = Node->getOperand(0);
581     if (Tmp1 != Tmp2)
582       Node->setAdjCallChain(Tmp1);
583     
584     // If this has a flag input, do legalize it.
585     if (Node->getOperand(Node->getNumOperands()-1).getValueType() == MVT::Flag){
586       Tmp1 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
587       if (Tmp1 != Node->getOperand(Node->getNumOperands()-1))
588         Node->setAdjCallFlag(Tmp1);
589     }
590       
591     // Note that we do not create new CALLSEQ_DOWN/UP nodes here.  These
592     // nodes are treated specially and are mutated in place.  This makes the dag
593     // legalization process more efficient and also makes libcall insertion
594     // easier.
595     break;
596   case ISD::DYNAMIC_STACKALLOC: {
597     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
598     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
599     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
600     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
601         Tmp3 != Node->getOperand(2)) {
602       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
603       std::vector<SDOperand> Ops;
604       Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
605       Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
606     } else
607       Result = Op.getValue(0);
608
609     Tmp1 = Result;
610     Tmp2 = Result.getValue(1);
611     switch (TLI.getOperationAction(Node->getOpcode(),
612                                    Node->getValueType(0))) {
613     default: assert(0 && "This action is not supported yet!");
614     case TargetLowering::Expand: {
615       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
616       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
617              " not tell us which reg is the stack pointer!");
618       SDOperand Chain = Tmp1.getOperand(0);
619       SDOperand Size  = Tmp2.getOperand(1);
620       SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, Node->getValueType(0));
621       Tmp1 = DAG.getNode(ISD::SUB, Node->getValueType(0), SP, Size);    // Value
622       Tmp2 = DAG.getCopyToReg(SP.getValue(1), SPReg, Tmp1);      // Output chain
623       break;
624     }
625     case TargetLowering::Custom:
626       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
627       if (Tmp3.Val) {
628         Tmp1 = Tmp3;
629         Tmp2 = Tmp3.getValue(1);
630       }
631       break;
632     case TargetLowering::Legal:
633       break;
634     }
635     // Since this op produce two values, make sure to remember that we
636     // legalized both of them.
637     AddLegalizedOperand(SDOperand(Node, 0), LegalizeOp(Tmp1));
638     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Tmp2));
639     return Op.ResNo ? Tmp2 : Tmp1;
640   }
641   case ISD::INLINEASM:
642     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
643     Tmp2 = Node->getOperand(Node->getNumOperands()-1);
644     if (Tmp2.getValueType() != MVT::Flag)     // Legalize Flag if it exists.
645       Tmp2 = Tmp3 = SDOperand(0, 0);
646     else
647       Tmp3 = LegalizeOp(Tmp2);
648     
649     if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
650       std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
651       Ops[0] = Tmp1;
652       Ops.back() = Tmp3;
653       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
654       Result = DAG.getNode(ISD::INLINEASM, VTs, Ops);
655     } else {
656       Result = SDOperand(Node, 0);
657     }
658       
659     // INLINE asm returns a chain and flag, make sure to add both to the map.
660     AddLegalizedOperand(SDOperand(Node, 0), Result);
661     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
662     return Result.getValue(Op.ResNo);
663   case ISD::BR:
664     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
665     if (Tmp1 != Node->getOperand(0))
666       Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
667     break;
668
669   case ISD::BRCOND:
670     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
671     
672     switch (getTypeAction(Node->getOperand(1).getValueType())) {
673     case Expand: assert(0 && "It's impossible to expand bools");
674     case Legal:
675       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
676       break;
677     case Promote:
678       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
679       break;
680     }
681
682     // Basic block destination (Op#2) is always legal.
683     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
684       Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
685                            Node->getOperand(2));
686       
687     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
688     default: assert(0 && "This action is not supported yet!");
689     case TargetLowering::Legal: break;
690     case TargetLowering::Custom:
691       Tmp1 = TLI.LowerOperation(Result, DAG);
692       if (Tmp1.Val) Result = Tmp1;
693       break;
694     case TargetLowering::Expand:
695       // Expand brcond's setcc into its constituent parts and create a BR_CC
696       // Node.
697       if (Tmp2.getOpcode() == ISD::SETCC) {
698         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
699                              Tmp2.getOperand(0), Tmp2.getOperand(1),
700                              Node->getOperand(2));
701       } else {
702         // Make sure the condition is either zero or one.  It may have been
703         // promoted from something else.
704         Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
705         
706         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
707                              DAG.getCondCode(ISD::SETNE), Tmp2,
708                              DAG.getConstant(0, Tmp2.getValueType()),
709                              Node->getOperand(2));
710       }
711       break;
712     }
713     break;
714   case ISD::BR_CC:
715     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
716     if (!isTypeLegal(Node->getOperand(2).getValueType())) {
717       Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
718                                     Node->getOperand(2),  // LHS
719                                     Node->getOperand(3),  // RHS
720                                     Node->getOperand(1)));
721       // If we get a SETCC back from legalizing the SETCC node we just
722       // created, then use its LHS, RHS, and CC directly in creating a new
723       // node.  Otherwise, select between the true and false value based on
724       // comparing the result of the legalized with zero.
725       if (Tmp2.getOpcode() == ISD::SETCC) {
726         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
727                              Tmp2.getOperand(0), Tmp2.getOperand(1),
728                              Node->getOperand(4));
729       } else {
730         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
731                              DAG.getCondCode(ISD::SETNE),
732                              Tmp2, DAG.getConstant(0, Tmp2.getValueType()), 
733                              Node->getOperand(4));
734       }
735       break;
736     }
737
738     Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
739     Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
740
741     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
742         Tmp3 != Node->getOperand(3)) {
743       Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Node->getOperand(1),
744                            Tmp2, Tmp3, Node->getOperand(4));
745     }
746       
747     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
748     default: assert(0 && "Unexpected action for BR_CC!");
749     case TargetLowering::Legal: break;
750     case TargetLowering::Custom:
751       Tmp4 = TLI.LowerOperation(Result, DAG);
752       if (Tmp4.Val) Result = Tmp4;
753       break;
754     }
755     break;
756   case ISD::BRCONDTWOWAY:
757     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
758     switch (getTypeAction(Node->getOperand(1).getValueType())) {
759     case Expand: assert(0 && "It's impossible to expand bools");
760     case Legal:
761       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
762       break;
763     case Promote:
764       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
765       break;
766     }
767       
768       
769     // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
770     // pair.
771     switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
772     case TargetLowering::Promote:
773     default: assert(0 && "This action is not supported yet!");
774     case TargetLowering::Legal:
775       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
776         std::vector<SDOperand> Ops;
777         Ops.push_back(Tmp1);
778         Ops.push_back(Tmp2);
779         Ops.push_back(Node->getOperand(2));
780         Ops.push_back(Node->getOperand(3));
781         Result = DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops);
782       }
783       break;
784     case TargetLowering::Expand:
785       // If BRTWOWAY_CC is legal for this target, then simply expand this node
786       // to that.  Otherwise, skip BRTWOWAY_CC and expand directly to a
787       // BRCOND/BR pair.
788       if (TLI.isOperationLegal(ISD::BRTWOWAY_CC, MVT::Other)) {
789         if (Tmp2.getOpcode() == ISD::SETCC) {
790           Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
791                                     Tmp2.getOperand(0), Tmp2.getOperand(1),
792                                     Node->getOperand(2), Node->getOperand(3));
793         } else {
794           Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2, 
795                                     DAG.getConstant(0, Tmp2.getValueType()),
796                                     Node->getOperand(2), Node->getOperand(3));
797         }
798       } else {
799         Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
800                              Node->getOperand(2));
801         Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
802       }
803       break;
804     }
805     break;
806   case ISD::BRTWOWAY_CC:
807     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
808     if (isTypeLegal(Node->getOperand(2).getValueType())) {
809       Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
810       Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
811       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
812           Tmp3 != Node->getOperand(3)) {
813         Result = DAG.getBR2Way_CC(Tmp1, Node->getOperand(1), Tmp2, Tmp3,
814                                   Node->getOperand(4), Node->getOperand(5));
815       }
816       break;
817     } else {
818       Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
819                                     Node->getOperand(2),  // LHS
820                                     Node->getOperand(3),  // RHS
821                                     Node->getOperand(1)));
822       // If this target does not support BRTWOWAY_CC, lower it to a BRCOND/BR
823       // pair.
824       switch (TLI.getOperationAction(ISD::BRTWOWAY_CC, MVT::Other)) {
825       default: assert(0 && "This action is not supported yet!");
826       case TargetLowering::Legal:
827         // If we get a SETCC back from legalizing the SETCC node we just
828         // created, then use its LHS, RHS, and CC directly in creating a new
829         // node.  Otherwise, select between the true and false value based on
830         // comparing the result of the legalized with zero.
831         if (Tmp2.getOpcode() == ISD::SETCC) {
832           Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
833                                     Tmp2.getOperand(0), Tmp2.getOperand(1),
834                                     Node->getOperand(4), Node->getOperand(5));
835         } else {
836           Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2, 
837                                     DAG.getConstant(0, Tmp2.getValueType()),
838                                     Node->getOperand(4), Node->getOperand(5));
839         }
840         break;
841       case TargetLowering::Expand: 
842         Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
843                              Node->getOperand(4));
844         Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(5));
845         break;
846       }
847     }
848     break;
849   case ISD::LOAD: {
850     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
851     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
852
853     MVT::ValueType VT = Node->getValueType(0);
854     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
855       Result = DAG.getLoad(VT, Tmp1, Tmp2, Node->getOperand(2));
856     else
857       Result = SDOperand(Node, 0);
858     
859     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
860     default: assert(0 && "This action is not supported yet!");
861     case TargetLowering::Custom:
862       Tmp1 = TLI.LowerOperation(Result, DAG);
863       if (Tmp1.Val) {
864         // Since loads produce two values, make sure to remember that we 
865         // legalized both of them.
866         AddLegalizedOperand(SDOperand(Node, 0), LegalizeOp(Tmp1));
867         AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Tmp1.getValue(1)));
868         return Tmp1.getValue(Op.ResNo);
869       }
870       // FALLTHROUGH if the target thinks it is legal.
871     case TargetLowering::Legal:
872       // Since loads produce two values, make sure to remember that we legalized
873       // both of them.
874       AddLegalizedOperand(SDOperand(Node, 0), Result);
875       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
876       return Result.getValue(Op.ResNo);
877     }
878     assert(0 && "Unreachable");
879   }
880   case ISD::EXTLOAD:
881   case ISD::SEXTLOAD:
882   case ISD::ZEXTLOAD: {
883     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
884     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
885
886     MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
887     switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
888     default: assert(0 && "This action is not supported yet!");
889     case TargetLowering::Promote:
890       assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
891       Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
892                               Tmp1, Tmp2, Node->getOperand(2), MVT::i8);
893       // Since loads produce two values, make sure to remember that we legalized
894       // both of them.
895       AddLegalizedOperand(SDOperand(Node, 0), Result);
896       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
897       return Result.getValue(Op.ResNo);
898
899     case TargetLowering::Custom:
900       isCustom = true;
901       // FALLTHROUGH
902     case TargetLowering::Legal:
903       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
904         Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
905                                 Tmp1, Tmp2, Node->getOperand(2), SrcVT);
906       else
907         Result = SDOperand(Node, 0);
908       Tmp1 = Result.getValue(1);
909       
910       if (isCustom) {
911         Tmp3 = TLI.LowerOperation(Tmp3, DAG);
912         if (Tmp3.Val) {
913           Result = LegalizeOp(Tmp3);
914           Tmp1 = LegalizeOp(Tmp3.getValue(1));
915         }
916       }
917
918       // Since loads produce two values, make sure to remember that we legalized
919       // both of them.
920       AddLegalizedOperand(SDOperand(Node, 0), Result);
921       AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
922       return Op.ResNo ? Tmp1 : Result;
923     case TargetLowering::Expand:
924       // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
925       if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
926         SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
927         Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
928         Result = LegalizeOp(Result);  // Relegalize new nodes.
929         Load = LegalizeOp(Load);
930         AddLegalizedOperand(SDOperand(Node, 0), Result);
931         AddLegalizedOperand(SDOperand(Node, 1), Load.getValue(1));
932         return Op.ResNo ? Load.getValue(1) : Result;
933       }
934       assert(Node->getOpcode() != ISD::EXTLOAD &&
935              "EXTLOAD should always be supported!");
936       // Turn the unsupported load into an EXTLOAD followed by an explicit
937       // zero/sign extend inreg.
938       Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
939                               Tmp1, Tmp2, Node->getOperand(2), SrcVT);
940       SDOperand ValRes;
941       if (Node->getOpcode() == ISD::SEXTLOAD)
942         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
943                              Result, DAG.getValueType(SrcVT));
944       else
945         ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
946       Result = LegalizeOp(Result);  // Relegalize new nodes.
947       ValRes = LegalizeOp(ValRes);  // Relegalize new nodes.
948       AddLegalizedOperand(SDOperand(Node, 0), ValRes);
949       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
950       return Op.ResNo ? Result.getValue(1) : ValRes;
951     }
952     assert(0 && "Unreachable");
953   }
954   case ISD::EXTRACT_ELEMENT: {
955     MVT::ValueType OpTy = Node->getOperand(0).getValueType();
956     switch (getTypeAction(OpTy)) {
957     default:
958       assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
959       break;
960     case Legal:
961       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
962         // 1 -> Hi
963         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
964                              DAG.getConstant(MVT::getSizeInBits(OpTy)/2, 
965                                              TLI.getShiftAmountTy()));
966         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
967       } else {
968         // 0 -> Lo
969         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
970                              Node->getOperand(0));
971       }
972       break;
973     case Expand:
974       // Get both the low and high parts.
975       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
976       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
977         Result = Tmp2;  // 1 -> Hi
978       else
979         Result = Tmp1;  // 0 -> Lo
980       break;
981     }
982     break;
983   }
984
985   case ISD::CopyToReg:
986     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
987
988     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
989            "Register type must be legal!");
990     // Legalize the incoming value (must be a legal type).
991     Tmp2 = LegalizeOp(Node->getOperand(2));
992     if (Node->getNumValues() == 1) {
993       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2))
994         Result = DAG.getNode(ISD::CopyToReg, MVT::Other, Tmp1,
995                              Node->getOperand(1), Tmp2);
996     } else {
997       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
998       if (Node->getNumOperands() == 4)
999         Tmp3 = LegalizeOp(Node->getOperand(3));
1000       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
1001           (Node->getNumOperands() == 4 && Tmp3 != Node->getOperand(3))) {
1002         unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
1003         Result = DAG.getCopyToReg(Tmp1, Reg, Tmp2, Tmp3);
1004       }
1005       
1006       // Since this produces two values, make sure to remember that we legalized
1007       // both of them.
1008       AddLegalizedOperand(SDOperand(Node, 0), Result);
1009       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1010       return Result.getValue(Op.ResNo);
1011     }
1012     break;
1013
1014   case ISD::RET:
1015     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1016     switch (Node->getNumOperands()) {
1017     case 2:  // ret val
1018       switch (getTypeAction(Node->getOperand(1).getValueType())) {
1019       case Legal:
1020         Tmp2 = LegalizeOp(Node->getOperand(1));
1021         if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1022           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
1023         break;
1024       case Expand: {
1025         SDOperand Lo, Hi;
1026         ExpandOp(Node->getOperand(1), Lo, Hi);
1027         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1028         break;
1029       }
1030       case Promote:
1031         Tmp2 = PromoteOp(Node->getOperand(1));
1032         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
1033         break;
1034       }
1035       break;
1036     case 1:  // ret void
1037       if (Tmp1 != Node->getOperand(0))
1038         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
1039       break;
1040     default: { // ret <values>
1041       std::vector<SDOperand> NewValues;
1042       NewValues.push_back(Tmp1);
1043       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1044         switch (getTypeAction(Node->getOperand(i).getValueType())) {
1045         case Legal:
1046           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1047           break;
1048         case Expand: {
1049           SDOperand Lo, Hi;
1050           ExpandOp(Node->getOperand(i), Lo, Hi);
1051           NewValues.push_back(Lo);
1052           NewValues.push_back(Hi);
1053           break;
1054         }
1055         case Promote:
1056           assert(0 && "Can't promote multiple return value yet!");
1057         }
1058       Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1059       break;
1060     }
1061     }
1062
1063     switch (TLI.getOperationAction(Node->getOpcode(),
1064                                    Node->getValueType(0))) {
1065     default: assert(0 && "This action is not supported yet!");
1066     case TargetLowering::Legal: break;
1067     case TargetLowering::Custom:
1068       Tmp1 = TLI.LowerOperation(Result, DAG);
1069       if (Tmp1.Val) Result = Tmp1;
1070       break;
1071     }
1072     break;
1073   case ISD::STORE: {
1074     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1075     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1076
1077     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1078     // FIXME: We shouldn't do this for TargetConstantFP's.
1079     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1080       if (CFP->getValueType(0) == MVT::f32) {
1081         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
1082                              DAG.getConstant(FloatToBits(CFP->getValue()),
1083                                              MVT::i32),
1084                              Tmp2, Node->getOperand(3));
1085       } else {
1086         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1087         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
1088                              DAG.getConstant(DoubleToBits(CFP->getValue()),
1089                                              MVT::i64),
1090                              Tmp2, Node->getOperand(3));
1091       }
1092       break;
1093     }
1094
1095     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1096     case Legal: {
1097       SDOperand Val = LegalizeOp(Node->getOperand(1));
1098       if (Tmp1 != Node->getOperand(0) || Val != Node->getOperand(1) ||
1099           Tmp2 != Node->getOperand(2))
1100         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2,
1101                              Node->getOperand(3));
1102
1103       MVT::ValueType VT = Result.Val->getOperand(1).getValueType();
1104       switch (TLI.getOperationAction(ISD::STORE, VT)) {
1105       default: assert(0 && "This action is not supported yet!");
1106       case TargetLowering::Legal:  break;
1107       case TargetLowering::Custom:
1108         Tmp1 = TLI.LowerOperation(Result, DAG);
1109         if (Tmp1.Val) Result = Tmp1;
1110         break;
1111       }
1112       break;
1113     }
1114     case Promote:
1115       // Truncate the value and store the result.
1116       Tmp3 = PromoteOp(Node->getOperand(1));
1117       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1118                            Node->getOperand(3),
1119                           DAG.getValueType(Node->getOperand(1).getValueType()));
1120       break;
1121
1122     case Expand:
1123       SDOperand Lo, Hi;
1124       ExpandOp(Node->getOperand(1), Lo, Hi);
1125
1126       if (!TLI.isLittleEndian())
1127         std::swap(Lo, Hi);
1128
1129       Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1130                        Node->getOperand(3));
1131       // If this is a vector type, then we have to calculate the increment as
1132       // the product of the element size in bytes, and the number of elements
1133       // in the high half of the vector.
1134       unsigned IncrementSize;
1135       if (MVT::Vector == Hi.getValueType()) {
1136         unsigned NumElems = cast<ConstantSDNode>(Hi.getOperand(2))->getValue();
1137         MVT::ValueType EVT = cast<VTSDNode>(Hi.getOperand(3))->getVT();
1138         IncrementSize = NumElems * MVT::getSizeInBits(EVT)/8;
1139       } else {
1140         IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1141       }
1142       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1143                          getIntPtrConstant(IncrementSize));
1144       assert(isTypeLegal(Tmp2.getValueType()) &&
1145              "Pointers must be legal!");
1146       // FIXME: This sets the srcvalue of both halves to be the same, which is
1147       // wrong.
1148       Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1149                        Node->getOperand(3));
1150       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1151       break;
1152     }
1153     break;
1154   }
1155   case ISD::PCMARKER:
1156     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1157     if (Tmp1 != Node->getOperand(0))
1158       Result = DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp1,Node->getOperand(1));
1159     break;
1160   case ISD::STACKSAVE:
1161     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1162     if (Tmp1 != Node->getOperand(0)) {
1163       std::vector<MVT::ValueType> VTs;
1164       VTs.push_back(Node->getValueType(0));
1165       VTs.push_back(MVT::Other);
1166       std::vector<SDOperand> Ops;
1167       Ops.push_back(Tmp1);
1168       Result = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1169     }
1170     
1171     Tmp1 = Result.getValue(1);
1172     
1173     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
1174     default: assert(0 && "This action is not supported yet!");
1175     case TargetLowering::Legal: break;
1176     case TargetLowering::Custom:
1177       Tmp2 = TLI.LowerOperation(Result, DAG);
1178       if (Tmp2.Val) {
1179         Result = LegalizeOp(Tmp2);
1180         Tmp1 = LegalizeOp(Tmp2.getValue(1));
1181       }
1182       break;
1183     case TargetLowering::Expand:
1184       // Expand to CopyFromReg if the target set 
1185       // StackPointerRegisterToSaveRestore.
1186       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1187         Tmp2 = DAG.getCopyFromReg(Result.getOperand(0), SP,
1188                                   Node->getValueType(0));
1189         Result = Tmp2;
1190         Tmp1 = Tmp2.getValue(1);
1191       } else {
1192         Result = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
1193         Tmp1 = Node->getOperand(0);
1194       }
1195       break;
1196     }
1197
1198     // Since stacksave produce two values, make sure to remember that we
1199     // legalized both of them.
1200     AddLegalizedOperand(SDOperand(Node, 0), Result);
1201     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
1202     return Op.ResNo ? Tmp1 : Result;
1203
1204   case ISD::STACKRESTORE:
1205     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1206     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1207     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1208       Result = DAG.getNode(ISD::STACKRESTORE, MVT::Other, Tmp1, Tmp2);
1209       
1210     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
1211     default: assert(0 && "This action is not supported yet!");
1212     case TargetLowering::Legal: break;
1213     case TargetLowering::Custom:
1214       Tmp1 = TLI.LowerOperation(Result, DAG);
1215       if (Tmp1.Val) Result = Tmp1;
1216       break;
1217     case TargetLowering::Expand:
1218       // Expand to CopyToReg if the target set 
1219       // StackPointerRegisterToSaveRestore.
1220       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1221         Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
1222       } else {
1223         Result = Tmp1;
1224       }
1225       break;
1226     }
1227     break;
1228
1229   case ISD::READCYCLECOUNTER:
1230     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1231     if (Tmp1 != Node->getOperand(0)) {
1232       std::vector<MVT::ValueType> rtypes;
1233       std::vector<SDOperand> rvals;
1234       rtypes.push_back(MVT::i64);
1235       rtypes.push_back(MVT::Other);
1236       rvals.push_back(Tmp1);
1237       Result = DAG.getNode(ISD::READCYCLECOUNTER, rtypes, rvals);
1238     }
1239
1240     // Since rdcc produce two values, make sure to remember that we legalized
1241     // both of them.
1242     AddLegalizedOperand(SDOperand(Node, 0), Result);
1243     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1244     return Result.getValue(Op.ResNo);
1245
1246   case ISD::TRUNCSTORE: {
1247     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1248     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1249
1250     assert(isTypeLegal(Node->getOperand(1).getValueType()) &&
1251            "Cannot handle illegal TRUNCSTORE yet!");
1252     Tmp2 = LegalizeOp(Node->getOperand(1));
1253     
1254     // The only promote case we handle is TRUNCSTORE:i1 X into
1255     //   -> TRUNCSTORE:i8 (and X, 1)
1256     if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1257         TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) == 
1258               TargetLowering::Promote) {
1259       // Promote the bool to a mask then store.
1260       Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1261                          DAG.getConstant(1, Tmp2.getValueType()));
1262       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1263                            Node->getOperand(3), DAG.getValueType(MVT::i8));
1264
1265     } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1266                Tmp3 != Node->getOperand(2)) {
1267       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1268                            Node->getOperand(3), Node->getOperand(4));
1269     }
1270
1271     MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
1272     switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
1273     default: assert(0 && "This action is not supported yet!");
1274     case TargetLowering::Legal: break;
1275     case TargetLowering::Custom:
1276       Tmp1 = TLI.LowerOperation(Result, DAG);
1277       if (Tmp1.Val) Result = Tmp1;
1278       break;
1279     }
1280     break;
1281   }
1282   case ISD::SELECT:
1283     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1284     case Expand: assert(0 && "It's impossible to expand bools");
1285     case Legal:
1286       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1287       break;
1288     case Promote:
1289       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1290       break;
1291     }
1292     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1293     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1294
1295     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1296         Tmp3 != Node->getOperand(2))
1297       Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
1298                            Tmp1, Tmp2, Tmp3);
1299       
1300     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1301     default: assert(0 && "This action is not supported yet!");
1302     case TargetLowering::Legal: break;
1303     case TargetLowering::Custom: {
1304       Tmp1 = TLI.LowerOperation(Result, DAG);
1305       if (Tmp1.Val) Result = Tmp1;
1306       break;
1307     }
1308     case TargetLowering::Expand:
1309       if (Tmp1.getOpcode() == ISD::SETCC) {
1310         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
1311                               Tmp2, Tmp3,
1312                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1313       } else {
1314         // Make sure the condition is either zero or one.  It may have been
1315         // promoted from something else.
1316         Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1317         Result = DAG.getSelectCC(Tmp1, 
1318                                  DAG.getConstant(0, Tmp1.getValueType()),
1319                                  Tmp2, Tmp3, ISD::SETNE);
1320       }
1321       break;
1322     case TargetLowering::Promote: {
1323       MVT::ValueType NVT =
1324         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1325       unsigned ExtOp, TruncOp;
1326       if (MVT::isInteger(Tmp2.getValueType())) {
1327         ExtOp   = ISD::ANY_EXTEND;
1328         TruncOp = ISD::TRUNCATE;
1329       } else {
1330         ExtOp   = ISD::FP_EXTEND;
1331         TruncOp = ISD::FP_ROUND;
1332       }
1333       // Promote each of the values to the new type.
1334       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1335       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1336       // Perform the larger operation, then round down.
1337       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1338       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1339       break;
1340     }
1341     }
1342     break;
1343   case ISD::SELECT_CC:
1344     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1345     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1346     
1347     if (isTypeLegal(Node->getOperand(0).getValueType())) {
1348       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1349       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1350       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1351           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3)) {
1352         Result = DAG.getNode(ISD::SELECT_CC, Node->getValueType(0), Tmp1,Tmp2, 
1353                              Tmp3, Tmp4, Node->getOperand(4));
1354       }
1355       
1356       // Everything is legal, see if we should expand this op or something.
1357       switch (TLI.getOperationAction(ISD::SELECT_CC,
1358                                      Node->getOperand(0).getValueType())) {
1359       default: assert(0 && "This action is not supported yet!");
1360       case TargetLowering::Legal: break;
1361       case TargetLowering::Custom:
1362         Tmp1 = TLI.LowerOperation(Result, DAG);
1363         if (Tmp1.Val) Result = Tmp1;
1364         break;
1365       }
1366       break;
1367     } else {
1368       Tmp1 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
1369                                     Node->getOperand(0),  // LHS
1370                                     Node->getOperand(1),  // RHS
1371                                     Node->getOperand(4)));
1372       // If we get a SETCC back from legalizing the SETCC node we just
1373       // created, then use its LHS, RHS, and CC directly in creating a new
1374       // node.  Otherwise, select between the true and false value based on
1375       // comparing the result of the legalized with zero.
1376       if (Tmp1.getOpcode() == ISD::SETCC) {
1377         Result = DAG.getNode(ISD::SELECT_CC, Tmp3.getValueType(),
1378                              Tmp1.getOperand(0), Tmp1.getOperand(1),
1379                              Tmp3, Tmp4, Tmp1.getOperand(2));
1380       } else {
1381         Result = DAG.getSelectCC(Tmp1,
1382                                  DAG.getConstant(0, Tmp1.getValueType()), 
1383                                  Tmp3, Tmp4, ISD::SETNE);
1384       }
1385     }
1386     break;
1387   case ISD::SETCC:
1388     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1389     case Legal:
1390       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1391       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1392       break;
1393     case Promote:
1394       Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
1395       Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
1396
1397       // If this is an FP compare, the operands have already been extended.
1398       if (MVT::isInteger(Node->getOperand(0).getValueType())) {
1399         MVT::ValueType VT = Node->getOperand(0).getValueType();
1400         MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1401
1402         // Otherwise, we have to insert explicit sign or zero extends.  Note
1403         // that we could insert sign extends for ALL conditions, but zero extend
1404         // is cheaper on many machines (an AND instead of two shifts), so prefer
1405         // it.
1406         switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1407         default: assert(0 && "Unknown integer comparison!");
1408         case ISD::SETEQ:
1409         case ISD::SETNE:
1410         case ISD::SETUGE:
1411         case ISD::SETUGT:
1412         case ISD::SETULE:
1413         case ISD::SETULT:
1414           // ALL of these operations will work if we either sign or zero extend
1415           // the operands (including the unsigned comparisons!).  Zero extend is
1416           // usually a simpler/cheaper operation, so prefer it.
1417           Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1418           Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
1419           break;
1420         case ISD::SETGE:
1421         case ISD::SETGT:
1422         case ISD::SETLT:
1423         case ISD::SETLE:
1424           Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
1425                              DAG.getValueType(VT));
1426           Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
1427                              DAG.getValueType(VT));
1428           break;
1429         }
1430       }
1431       break;
1432     case Expand:
1433       SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
1434       ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
1435       ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
1436       switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1437       case ISD::SETEQ:
1438       case ISD::SETNE:
1439         if (RHSLo == RHSHi)
1440           if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
1441             if (RHSCST->isAllOnesValue()) {
1442               // Comparison to -1.
1443               Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1444               Tmp2 = RHSLo;
1445               break;
1446             }
1447
1448         Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1449         Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1450         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
1451         Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1452         break;
1453       default:
1454         // If this is a comparison of the sign bit, just look at the top part.
1455         // X > -1,  x < 0
1456         if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
1457           if ((cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETLT &&
1458                CST->getValue() == 0) ||              // X < 0
1459               (cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETGT &&
1460                (CST->isAllOnesValue()))) {            // X > -1
1461             Tmp1 = LHSHi;
1462             Tmp2 = RHSHi;
1463             break;
1464           }
1465
1466         // FIXME: This generated code sucks.
1467         ISD::CondCode LowCC;
1468         switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1469         default: assert(0 && "Unknown integer setcc!");
1470         case ISD::SETLT:
1471         case ISD::SETULT: LowCC = ISD::SETULT; break;
1472         case ISD::SETGT:
1473         case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1474         case ISD::SETLE:
1475         case ISD::SETULE: LowCC = ISD::SETULE; break;
1476         case ISD::SETGE:
1477         case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1478         }
1479
1480         // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1481         // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1482         // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1483
1484         // NOTE: on targets without efficient SELECT of bools, we can always use
1485         // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1486         Tmp1 = DAG.getSetCC(Node->getValueType(0), LHSLo, RHSLo, LowCC);
1487         Tmp2 = DAG.getNode(ISD::SETCC, Node->getValueType(0), LHSHi, RHSHi,
1488                            Node->getOperand(2));
1489         Result = DAG.getSetCC(Node->getValueType(0), LHSHi, RHSHi, ISD::SETEQ);
1490         Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1491                                         Result, Tmp1, Tmp2));
1492         AddLegalizedOperand(SDOperand(Node, 0), Result);
1493         return Result;
1494       }
1495     }
1496
1497     switch (TLI.getOperationAction(ISD::SETCC,
1498                                    Node->getOperand(0).getValueType())) {
1499     default: assert(0 && "Cannot handle this action for SETCC yet!");
1500     case TargetLowering::Custom:
1501       isCustom = true;
1502       // FALLTHROUGH.
1503     case TargetLowering::Legal:
1504       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1505         Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1506                              Node->getOperand(2));
1507       if (isCustom) {
1508         Tmp3 = TLI.LowerOperation(Result, DAG);
1509         if (Tmp3.Val) Result = Tmp3;
1510       }
1511       break;
1512     case TargetLowering::Promote: {
1513       // First step, figure out the appropriate operation to use.
1514       // Allow SETCC to not be supported for all legal data types
1515       // Mostly this targets FP
1516       MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1517       MVT::ValueType OldVT = NewInTy;
1518
1519       // Scan for the appropriate larger type to use.
1520       while (1) {
1521         NewInTy = (MVT::ValueType)(NewInTy+1);
1522
1523         assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1524                "Fell off of the edge of the integer world");
1525         assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1526                "Fell off of the edge of the floating point world");
1527           
1528         // If the target supports SETCC of this type, use it.
1529         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
1530           break;
1531       }
1532       if (MVT::isInteger(NewInTy))
1533         assert(0 && "Cannot promote Legal Integer SETCC yet");
1534       else {
1535         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1536         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1537       }
1538       
1539       Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1540                            Node->getOperand(2));
1541       Result = LegalizeOp(Result);
1542       break;
1543     }
1544     case TargetLowering::Expand:
1545       // Expand a setcc node into a select_cc of the same condition, lhs, and
1546       // rhs that selects between const 1 (true) and const 0 (false).
1547       MVT::ValueType VT = Node->getValueType(0);
1548       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
1549                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1550                            Node->getOperand(2));
1551       Result = LegalizeOp(Result);
1552       break;
1553     }
1554     break;
1555   case ISD::MEMSET:
1556   case ISD::MEMCPY:
1557   case ISD::MEMMOVE: {
1558     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1559     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1560
1561     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1562       switch (getTypeAction(Node->getOperand(2).getValueType())) {
1563       case Expand: assert(0 && "Cannot expand a byte!");
1564       case Legal:
1565         Tmp3 = LegalizeOp(Node->getOperand(2));
1566         break;
1567       case Promote:
1568         Tmp3 = PromoteOp(Node->getOperand(2));
1569         break;
1570       }
1571     } else {
1572       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1573     }
1574
1575     SDOperand Tmp4;
1576     switch (getTypeAction(Node->getOperand(3).getValueType())) {
1577     case Expand: {
1578       // Length is too big, just take the lo-part of the length.
1579       SDOperand HiPart;
1580       ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1581       break;
1582     }
1583     case Legal:
1584       Tmp4 = LegalizeOp(Node->getOperand(3));
1585       break;
1586     case Promote:
1587       Tmp4 = PromoteOp(Node->getOperand(3));
1588       break;
1589     }
1590
1591     SDOperand Tmp5;
1592     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1593     case Expand: assert(0 && "Cannot expand this yet!");
1594     case Legal:
1595       Tmp5 = LegalizeOp(Node->getOperand(4));
1596       break;
1597     case Promote:
1598       Tmp5 = PromoteOp(Node->getOperand(4));
1599       break;
1600     }
1601
1602     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1603     default: assert(0 && "This action not implemented for this operation!");
1604     case TargetLowering::Custom:
1605       isCustom = true;
1606       // FALLTHROUGH
1607     case TargetLowering::Legal:
1608       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1609           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
1610           Tmp5 != Node->getOperand(4)) {
1611         std::vector<SDOperand> Ops;
1612         Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
1613         Ops.push_back(Tmp4); Ops.push_back(Tmp5);
1614         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
1615       }
1616       if (isCustom) {
1617         Tmp1 = TLI.LowerOperation(Result, DAG);
1618         if (Tmp1.Val) Result = Tmp1;
1619       }
1620       break;
1621     case TargetLowering::Expand: {
1622       // Otherwise, the target does not support this operation.  Lower the
1623       // operation to an explicit libcall as appropriate.
1624       MVT::ValueType IntPtr = TLI.getPointerTy();
1625       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1626       std::vector<std::pair<SDOperand, const Type*> > Args;
1627
1628       const char *FnName = 0;
1629       if (Node->getOpcode() == ISD::MEMSET) {
1630         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1631         // Extend the ubyte argument to be an int value for the call.
1632         Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1633         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1634         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1635
1636         FnName = "memset";
1637       } else if (Node->getOpcode() == ISD::MEMCPY ||
1638                  Node->getOpcode() == ISD::MEMMOVE) {
1639         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1640         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1641         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1642         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1643       } else {
1644         assert(0 && "Unknown op!");
1645       }
1646
1647       std::pair<SDOperand,SDOperand> CallResult =
1648         TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1649                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1650       Result = CallResult.second;
1651       break;
1652     }
1653     }
1654     break;
1655   }
1656
1657   case ISD::READPORT:
1658     Tmp1 = LegalizeOp(Node->getOperand(0));
1659     Tmp2 = LegalizeOp(Node->getOperand(1));
1660
1661     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1662       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1663       std::vector<SDOperand> Ops;
1664       Ops.push_back(Tmp1);
1665       Ops.push_back(Tmp2);
1666       Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1667     } else
1668       Result = SDOperand(Node, 0);
1669     // Since these produce two values, make sure to remember that we legalized
1670     // both of them.
1671     AddLegalizedOperand(SDOperand(Node, 0), Result);
1672     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1673     return Result.getValue(Op.ResNo);
1674   case ISD::WRITEPORT:
1675     Tmp1 = LegalizeOp(Node->getOperand(0));
1676     Tmp2 = LegalizeOp(Node->getOperand(1));
1677     Tmp3 = LegalizeOp(Node->getOperand(2));
1678     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1679         Tmp3 != Node->getOperand(2))
1680       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1681     break;
1682
1683   case ISD::READIO:
1684     Tmp1 = LegalizeOp(Node->getOperand(0));
1685     Tmp2 = LegalizeOp(Node->getOperand(1));
1686
1687     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1688     case TargetLowering::Custom:
1689     default: assert(0 && "This action not implemented for this operation!");
1690     case TargetLowering::Legal:
1691       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1692         std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1693         std::vector<SDOperand> Ops;
1694         Ops.push_back(Tmp1);
1695         Ops.push_back(Tmp2);
1696         Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1697       } else
1698         Result = SDOperand(Node, 0);
1699       break;
1700     case TargetLowering::Expand:
1701       // Replace this with a load from memory.
1702       Result = DAG.getLoad(Node->getValueType(0), Node->getOperand(0),
1703                            Node->getOperand(1), DAG.getSrcValue(NULL));
1704       Result = LegalizeOp(Result);
1705       break;
1706     }
1707
1708     // Since these produce two values, make sure to remember that we legalized
1709     // both of them.
1710     AddLegalizedOperand(SDOperand(Node, 0), Result);
1711     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1712     return Result.getValue(Op.ResNo);
1713
1714   case ISD::WRITEIO:
1715     Tmp1 = LegalizeOp(Node->getOperand(0));
1716     Tmp2 = LegalizeOp(Node->getOperand(1));
1717     Tmp3 = LegalizeOp(Node->getOperand(2));
1718
1719     switch (TLI.getOperationAction(Node->getOpcode(),
1720                                    Node->getOperand(1).getValueType())) {
1721     case TargetLowering::Custom:
1722     default: assert(0 && "This action not implemented for this operation!");
1723     case TargetLowering::Legal:
1724       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1725           Tmp3 != Node->getOperand(2))
1726         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1727       break;
1728     case TargetLowering::Expand:
1729       // Replace this with a store to memory.
1730       Result = DAG.getNode(ISD::STORE, MVT::Other, Node->getOperand(0),
1731                            Node->getOperand(1), Node->getOperand(2),
1732                            DAG.getSrcValue(NULL));
1733       break;
1734     }
1735     break;
1736
1737   case ISD::ADD_PARTS:
1738   case ISD::SUB_PARTS:
1739   case ISD::SHL_PARTS:
1740   case ISD::SRA_PARTS:
1741   case ISD::SRL_PARTS: {
1742     std::vector<SDOperand> Ops;
1743     bool Changed = false;
1744     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1745       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1746       Changed |= Ops.back() != Node->getOperand(i);
1747     }
1748     if (Changed) {
1749       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1750       Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
1751     }
1752
1753     switch (TLI.getOperationAction(Node->getOpcode(),
1754                                    Node->getValueType(0))) {
1755     default: assert(0 && "This action is not supported yet!");
1756     case TargetLowering::Legal: break;
1757     case TargetLowering::Custom:
1758       Tmp1 = TLI.LowerOperation(Result, DAG);
1759       if (Tmp1.Val) {
1760         SDOperand Tmp2, RetVal(0, 0);
1761         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1762           Tmp2 = LegalizeOp(Tmp1.getValue(i));
1763           AddLegalizedOperand(SDOperand(Node, i), Tmp2);
1764           if (i == Op.ResNo)
1765             RetVal = Tmp2;
1766         }
1767         assert(RetVal.Val && "Illegal result number");
1768         return RetVal;
1769       }
1770       break;
1771     }
1772
1773     // Since these produce multiple values, make sure to remember that we
1774     // legalized all of them.
1775     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1776       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
1777     return Result.getValue(Op.ResNo);
1778   }
1779
1780     // Binary operators
1781   case ISD::ADD:
1782   case ISD::SUB:
1783   case ISD::MUL:
1784   case ISD::MULHS:
1785   case ISD::MULHU:
1786   case ISD::UDIV:
1787   case ISD::SDIV:
1788   case ISD::AND:
1789   case ISD::OR:
1790   case ISD::XOR:
1791   case ISD::SHL:
1792   case ISD::SRL:
1793   case ISD::SRA:
1794   case ISD::FADD:
1795   case ISD::FSUB:
1796   case ISD::FMUL:
1797   case ISD::FDIV:
1798     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1799     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1800     case Expand: assert(0 && "Not possible");
1801     case Legal:
1802       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1803       break;
1804     case Promote:
1805       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1806       break;
1807     }
1808       
1809     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1810       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
1811       
1812     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1813     default: assert(0 && "Operation not supported");
1814     case TargetLowering::Legal: break;
1815     case TargetLowering::Custom:
1816       Tmp1 = TLI.LowerOperation(Result, DAG);
1817       if (Tmp1.Val) Result = Tmp1;
1818       break;
1819     }
1820     break;
1821
1822   case ISD::BUILD_PAIR: {
1823     MVT::ValueType PairTy = Node->getValueType(0);
1824     // TODO: handle the case where the Lo and Hi operands are not of legal type
1825     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
1826     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
1827     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
1828     case TargetLowering::Promote:
1829     case TargetLowering::Custom:
1830       assert(0 && "Cannot promote/custom this yet!");
1831     case TargetLowering::Legal:
1832       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1833         Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
1834       break;
1835     case TargetLowering::Expand:
1836       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
1837       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
1838       Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
1839                          DAG.getConstant(MVT::getSizeInBits(PairTy)/2, 
1840                                          TLI.getShiftAmountTy()));
1841       Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
1842       break;
1843     }
1844     break;
1845   }
1846
1847   case ISD::UREM:
1848   case ISD::SREM:
1849   case ISD::FREM:
1850     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1851     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1852
1853     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1854     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
1855     case TargetLowering::Custom:
1856       isCustom = true;
1857       // FALLTHROUGH
1858     case TargetLowering::Legal:
1859       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1860         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), 
1861                              Tmp1, Tmp2);
1862       if (isCustom) {
1863         Tmp1 = TLI.LowerOperation(Result, DAG);
1864         if (Tmp1.Val) Result = Tmp1;
1865       }
1866       break;
1867     case TargetLowering::Expand:
1868       if (MVT::isInteger(Node->getValueType(0))) {
1869         // X % Y -> X-X/Y*Y
1870         MVT::ValueType VT = Node->getValueType(0);
1871         unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
1872         Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
1873         Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
1874         Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
1875       } else {
1876         // Floating point mod -> fmod libcall.
1877         const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
1878         SDOperand Dummy;
1879         Result = ExpandLibCall(FnName, Node, Dummy);
1880       }
1881       break;
1882     }
1883     break;
1884   case ISD::VAARG: {
1885     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1886     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1887
1888     MVT::ValueType VT = Node->getValueType(0);
1889     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1890     default: assert(0 && "This action is not supported yet!");
1891     case TargetLowering::Custom:
1892       isCustom = true;
1893       // FALLTHROUGH
1894     case TargetLowering::Legal:
1895       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1896         Result = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
1897       else
1898         Result = SDOperand(Node, 0);
1899       Tmp1 = Result.getValue(1);
1900
1901       if (isCustom) {
1902         Tmp2 = TLI.LowerOperation(Result, DAG);
1903         if (Tmp2.Val) {
1904           Result = LegalizeOp(Tmp2);
1905           Tmp1 = LegalizeOp(Tmp2.getValue(1));
1906         }
1907       }
1908       break;
1909     case TargetLowering::Expand: {
1910       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
1911                                      Node->getOperand(2));
1912       // Increment the pointer, VAList, to the next vaarg
1913       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
1914                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
1915                                          TLI.getPointerTy()));
1916       // Store the incremented VAList to the legalized pointer
1917       Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
1918                          Node->getOperand(2));
1919       // Load the actual argument out of the pointer VAList
1920       Result = DAG.getLoad(VT, Tmp3, VAList, DAG.getSrcValue(0));
1921       Tmp1 = LegalizeOp(Result.getValue(1));
1922       Result = LegalizeOp(Result);
1923       break;
1924     }
1925     }
1926     // Since VAARG produces two values, make sure to remember that we 
1927     // legalized both of them.
1928     AddLegalizedOperand(SDOperand(Node, 0), Result);
1929     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
1930     return Op.ResNo ? Tmp1 : Result;
1931   }
1932     
1933   case ISD::VACOPY: 
1934     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1935     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
1936     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
1937
1938     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
1939     default: assert(0 && "This action is not supported yet!");
1940     case TargetLowering::Custom:
1941       isCustom = true;
1942       // FALLTHROUGH
1943     case TargetLowering::Legal:
1944       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1945           Tmp3 != Node->getOperand(2))
1946         Result = DAG.getNode(ISD::VACOPY, MVT::Other, Tmp1, Tmp2, Tmp3,
1947                              Node->getOperand(3), Node->getOperand(4));
1948       if (isCustom) {
1949         Tmp1 = TLI.LowerOperation(Result, DAG);
1950         if (Tmp1.Val) Result = Tmp1;
1951       }
1952       break;
1953     case TargetLowering::Expand:
1954       // This defaults to loading a pointer from the input and storing it to the
1955       // output, returning the chain.
1956       Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, Node->getOperand(3));
1957       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp4.getValue(1), Tmp4, Tmp2,
1958                            Node->getOperand(4));
1959       break;
1960     }
1961     break;
1962
1963   case ISD::VAEND: 
1964     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1965     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1966
1967     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
1968     default: assert(0 && "This action is not supported yet!");
1969     case TargetLowering::Custom:
1970       isCustom = true;
1971       // FALLTHROUGH
1972     case TargetLowering::Legal:
1973       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1974         Result = DAG.getNode(ISD::VAEND, MVT::Other, Tmp1, Tmp2, 
1975                              Node->getOperand(2));
1976       if (isCustom) {
1977         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
1978         if (Tmp1.Val) Result = Tmp1;
1979       }
1980       break;
1981     case TargetLowering::Expand:
1982       Result = Tmp1; // Default to a no-op, return the chain
1983       break;
1984     }
1985     break;
1986     
1987   case ISD::VASTART: 
1988     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1989     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1990
1991     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1992       Result = DAG.getNode(ISD::VASTART, MVT::Other, Tmp1, Tmp2, 
1993                            Node->getOperand(2));
1994       
1995     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
1996     default: assert(0 && "This action is not supported yet!");
1997     case TargetLowering::Legal: break;
1998     case TargetLowering::Custom:
1999       Tmp1 = TLI.LowerOperation(Result, DAG);
2000       if (Tmp1.Val) Result = Tmp1;
2001       break;
2002     }
2003     break;
2004     
2005   case ISD::ROTL:
2006   case ISD::ROTR:
2007     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2008     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2009     
2010     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2011            "Cannot handle this yet!");
2012     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2013       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
2014     break;
2015     
2016   case ISD::BSWAP:
2017     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2018     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2019     case TargetLowering::Custom:
2020       assert(0 && "Cannot custom legalize this yet!");
2021     case TargetLowering::Legal:
2022       if (Tmp1 != Node->getOperand(0))
2023         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2024       break;
2025     case TargetLowering::Promote: {
2026       MVT::ValueType OVT = Tmp1.getValueType();
2027       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2028       unsigned DiffBits = getSizeInBits(NVT) - getSizeInBits(OVT);
2029
2030       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2031       Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2032       Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2033                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2034       break;
2035     }
2036     case TargetLowering::Expand:
2037       Result = ExpandBSWAP(Tmp1);
2038       break;
2039     }
2040     break;
2041     
2042   case ISD::CTPOP:
2043   case ISD::CTTZ:
2044   case ISD::CTLZ:
2045     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2046     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2047     case TargetLowering::Custom: assert(0 && "Cannot custom handle this yet!");
2048     case TargetLowering::Legal:
2049       if (Tmp1 != Node->getOperand(0))
2050         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2051       break;
2052     case TargetLowering::Promote: {
2053       MVT::ValueType OVT = Tmp1.getValueType();
2054       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2055
2056       // Zero extend the argument.
2057       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2058       // Perform the larger operation, then subtract if needed.
2059       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2060       switch (Node->getOpcode()) {
2061       case ISD::CTPOP:
2062         Result = Tmp1;
2063         break;
2064       case ISD::CTTZ:
2065         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2066         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2067                             DAG.getConstant(getSizeInBits(NVT), NVT),
2068                             ISD::SETEQ);
2069         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2070                            DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2071         break;
2072       case ISD::CTLZ:
2073         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2074         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2075                              DAG.getConstant(getSizeInBits(NVT) -
2076                                              getSizeInBits(OVT), NVT));
2077         break;
2078       }
2079       break;
2080     }
2081     case TargetLowering::Expand:
2082       Result = ExpandBitCount(Node->getOpcode(), Tmp1);
2083       break;
2084     }
2085     break;
2086
2087     // Unary operators
2088   case ISD::FABS:
2089   case ISD::FNEG:
2090   case ISD::FSQRT:
2091   case ISD::FSIN:
2092   case ISD::FCOS:
2093     Tmp1 = LegalizeOp(Node->getOperand(0));
2094     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2095     case TargetLowering::Promote:
2096     case TargetLowering::Custom:
2097       assert(0 && "Cannot promote/custom handle this yet!");
2098     case TargetLowering::Legal:
2099       if (Tmp1 != Node->getOperand(0))
2100         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2101       break;
2102     case TargetLowering::Expand:
2103       switch (Node->getOpcode()) {
2104       default: assert(0 && "Unreachable!");
2105       case ISD::FNEG:
2106         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2107         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2108         Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
2109         break;
2110       case ISD::FABS: {
2111         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2112         MVT::ValueType VT = Node->getValueType(0);
2113         Tmp2 = DAG.getConstantFP(0.0, VT);
2114         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2115         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2116         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2117         break;
2118       }
2119       case ISD::FSQRT:
2120       case ISD::FSIN:
2121       case ISD::FCOS: {
2122         MVT::ValueType VT = Node->getValueType(0);
2123         const char *FnName = 0;
2124         switch(Node->getOpcode()) {
2125         case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2126         case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2127         case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2128         default: assert(0 && "Unreachable!");
2129         }
2130         SDOperand Dummy;
2131         Result = ExpandLibCall(FnName, Node, Dummy);
2132         break;
2133       }
2134       }
2135       break;
2136     }
2137     break;
2138     
2139   case ISD::BIT_CONVERT:
2140     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
2141       Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2142     } else {
2143       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2144                                      Node->getOperand(0).getValueType())) {
2145       default: assert(0 && "Unknown operation action!");
2146       case TargetLowering::Expand:
2147         Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2148         break;
2149       case TargetLowering::Legal:
2150         Tmp1 = LegalizeOp(Node->getOperand(0));
2151         if (Tmp1 != Node->getOperand(0))
2152           Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), Tmp1);
2153         break;
2154       }
2155     }
2156     break;
2157     // Conversion operators.  The source and destination have different types.
2158   case ISD::SINT_TO_FP:
2159   case ISD::UINT_TO_FP: {
2160     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2161     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2162     case Legal:
2163       switch (TLI.getOperationAction(Node->getOpcode(),
2164                                      Node->getOperand(0).getValueType())) {
2165       default: assert(0 && "Unknown operation action!");
2166       case TargetLowering::Custom:
2167         isCustom = true;
2168         // FALLTHROUGH
2169       case TargetLowering::Legal:
2170         Tmp1 = LegalizeOp(Node->getOperand(0));
2171         if (Tmp1 != Node->getOperand(0))
2172           Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2173         if (isCustom) {
2174           Tmp1 = TLI.LowerOperation(Result, DAG);
2175           if (Tmp1.Val) Result = Tmp1;
2176         }
2177         break;
2178       case TargetLowering::Expand:
2179         Result = ExpandLegalINT_TO_FP(isSigned,
2180                                       LegalizeOp(Node->getOperand(0)),
2181                                       Node->getValueType(0));
2182         break;
2183       case TargetLowering::Promote:
2184         Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2185                                        Node->getValueType(0),
2186                                        isSigned);
2187         break;
2188       }
2189       break;
2190     case Expand:
2191       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2192                              Node->getValueType(0), Node->getOperand(0));
2193       break;
2194     case Promote:
2195       if (isSigned) {
2196         Result = PromoteOp(Node->getOperand(0));
2197         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2198                  Result, DAG.getValueType(Node->getOperand(0).getValueType()));
2199         Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
2200       } else {
2201         Result = PromoteOp(Node->getOperand(0));
2202         Result = DAG.getZeroExtendInReg(Result,
2203                                         Node->getOperand(0).getValueType());
2204         Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
2205       }
2206       break;
2207     }
2208     break;
2209   }
2210   case ISD::TRUNCATE:
2211     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2212     case Legal:
2213       Tmp1 = LegalizeOp(Node->getOperand(0));
2214       if (Tmp1 != Node->getOperand(0))
2215         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2216       break;
2217     case Expand:
2218       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2219
2220       // Since the result is legal, we should just be able to truncate the low
2221       // part of the source.
2222       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2223       break;
2224     case Promote:
2225       Result = PromoteOp(Node->getOperand(0));
2226       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2227       break;
2228     }
2229     break;
2230
2231   case ISD::FP_TO_SINT:
2232   case ISD::FP_TO_UINT:
2233     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2234     case Legal:
2235       Tmp1 = LegalizeOp(Node->getOperand(0));
2236
2237       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2238       default: assert(0 && "Unknown operation action!");
2239       case TargetLowering::Custom:
2240         isCustom = true;
2241         // FALLTHROUGH
2242       case TargetLowering::Legal:
2243         if (Tmp1 != Node->getOperand(0))
2244           Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2245
2246         if (isCustom) {
2247           Tmp1 = TLI.LowerOperation(Result, DAG);
2248           if (Tmp1.Val) Result = Tmp1;
2249         }
2250         break;
2251       case TargetLowering::Promote:
2252         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2253                                        Node->getOpcode() == ISD::FP_TO_SINT);
2254         break;
2255       case TargetLowering::Expand:
2256         if (Node->getOpcode() == ISD::FP_TO_UINT) {
2257           SDOperand True, False;
2258           MVT::ValueType VT =  Node->getOperand(0).getValueType();
2259           MVT::ValueType NVT = Node->getValueType(0);
2260           unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2261           Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2262           Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2263                             Node->getOperand(0), Tmp2, ISD::SETLT);
2264           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2265           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2266                               DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2267                                           Tmp2));
2268           False = DAG.getNode(ISD::XOR, NVT, False, 
2269                               DAG.getConstant(1ULL << ShiftAmt, NVT));
2270           Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
2271           break;
2272         } else {
2273           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2274         }
2275         break;
2276       }
2277       break;
2278     case Expand:
2279       assert(0 && "Shouldn't need to expand other operators here!");
2280     case Promote:
2281       Result = PromoteOp(Node->getOperand(0));
2282       Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2283       break;
2284     }
2285     break;
2286
2287   case ISD::ANY_EXTEND:
2288   case ISD::ZERO_EXTEND:
2289   case ISD::SIGN_EXTEND:
2290   case ISD::FP_EXTEND:
2291   case ISD::FP_ROUND:
2292     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2293     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
2294     case Legal:
2295       Tmp1 = LegalizeOp(Node->getOperand(0));
2296       if (Tmp1 != Node->getOperand(0))
2297         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2298       break;
2299     case Promote:
2300       switch (Node->getOpcode()) {
2301       case ISD::ANY_EXTEND:
2302         Result = PromoteOp(Node->getOperand(0));
2303         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2304         break;
2305       case ISD::ZERO_EXTEND:
2306         Result = PromoteOp(Node->getOperand(0));
2307         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2308         Result = DAG.getZeroExtendInReg(Result,
2309                                         Node->getOperand(0).getValueType());
2310         break;
2311       case ISD::SIGN_EXTEND:
2312         Result = PromoteOp(Node->getOperand(0));
2313         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2314         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2315                              Result,
2316                           DAG.getValueType(Node->getOperand(0).getValueType()));
2317         break;
2318       case ISD::FP_EXTEND:
2319         Result = PromoteOp(Node->getOperand(0));
2320         if (Result.getValueType() != Op.getValueType())
2321           // Dynamically dead while we have only 2 FP types.
2322           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2323         break;
2324       case ISD::FP_ROUND:
2325         Result = PromoteOp(Node->getOperand(0));
2326         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2327         break;
2328       }
2329     }
2330     break;
2331   case ISD::FP_ROUND_INREG:
2332   case ISD::SIGN_EXTEND_INREG: {
2333     Tmp1 = LegalizeOp(Node->getOperand(0));
2334     MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2335
2336     // If this operation is not supported, convert it to a shl/shr or load/store
2337     // pair.
2338     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2339     default: assert(0 && "This action not supported for this op yet!");
2340     case TargetLowering::Legal:
2341       if (Tmp1 != Node->getOperand(0))
2342         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
2343                              DAG.getValueType(ExtraVT));
2344       break;
2345     case TargetLowering::Expand:
2346       // If this is an integer extend and shifts are supported, do that.
2347       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2348         // NOTE: we could fall back on load/store here too for targets without
2349         // SAR.  However, it is doubtful that any exist.
2350         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2351                             MVT::getSizeInBits(ExtraVT);
2352         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2353         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2354                              Node->getOperand(0), ShiftCst);
2355         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2356                              Result, ShiftCst);
2357       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2358         // The only way we can lower this is to turn it into a STORETRUNC,
2359         // EXTLOAD pair, targetting a temporary location (a stack slot).
2360
2361         // NOTE: there is a choice here between constantly creating new stack
2362         // slots and always reusing the same one.  We currently always create
2363         // new ones, as reuse may inhibit scheduling.
2364         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2365         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2366         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2367         MachineFunction &MF = DAG.getMachineFunction();
2368         int SSFI =
2369           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2370         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2371         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2372                              Node->getOperand(0), StackSlot,
2373                              DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2374         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2375                                 Result, StackSlot, DAG.getSrcValue(NULL),
2376                                 ExtraVT);
2377       } else {
2378         assert(0 && "Unknown op");
2379       }
2380       break;
2381     }
2382     break;
2383   }
2384   }
2385   
2386   // Make sure that the generated code is itself legal.
2387   if (Result != Op)
2388     Result = LegalizeOp(Result);
2389
2390   // Note that LegalizeOp may be reentered even from single-use nodes, which
2391   // means that we always must cache transformed nodes.
2392   AddLegalizedOperand(Op, Result);
2393   return Result;
2394 }
2395
2396 /// PromoteOp - Given an operation that produces a value in an invalid type,
2397 /// promote it to compute the value into a larger type.  The produced value will
2398 /// have the correct bits for the low portion of the register, but no guarantee
2399 /// is made about the top bits: it may be zero, sign-extended, or garbage.
2400 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2401   MVT::ValueType VT = Op.getValueType();
2402   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2403   assert(getTypeAction(VT) == Promote &&
2404          "Caller should expand or legalize operands that are not promotable!");
2405   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2406          "Cannot promote to smaller type!");
2407
2408   SDOperand Tmp1, Tmp2, Tmp3;
2409   SDOperand Result;
2410   SDNode *Node = Op.Val;
2411
2412   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2413   if (I != PromotedNodes.end()) return I->second;
2414
2415   switch (Node->getOpcode()) {
2416   case ISD::CopyFromReg:
2417     assert(0 && "CopyFromReg must be legal!");
2418   default:
2419     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2420     assert(0 && "Do not know how to promote this operator!");
2421     abort();
2422   case ISD::UNDEF:
2423     Result = DAG.getNode(ISD::UNDEF, NVT);
2424     break;
2425   case ISD::Constant:
2426     if (VT != MVT::i1)
2427       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2428     else
2429       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2430     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2431     break;
2432   case ISD::ConstantFP:
2433     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2434     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2435     break;
2436
2437   case ISD::SETCC:
2438     assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2439     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2440                          Node->getOperand(1), Node->getOperand(2));
2441     break;
2442
2443   case ISD::TRUNCATE:
2444     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2445     case Legal:
2446       Result = LegalizeOp(Node->getOperand(0));
2447       assert(Result.getValueType() >= NVT &&
2448              "This truncation doesn't make sense!");
2449       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2450         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2451       break;
2452     case Promote:
2453       // The truncation is not required, because we don't guarantee anything
2454       // about high bits anyway.
2455       Result = PromoteOp(Node->getOperand(0));
2456       break;
2457     case Expand:
2458       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2459       // Truncate the low part of the expanded value to the result type
2460       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2461     }
2462     break;
2463   case ISD::SIGN_EXTEND:
2464   case ISD::ZERO_EXTEND:
2465   case ISD::ANY_EXTEND:
2466     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2467     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2468     case Legal:
2469       // Input is legal?  Just do extend all the way to the larger type.
2470       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2471       break;
2472     case Promote:
2473       // Promote the reg if it's smaller.
2474       Result = PromoteOp(Node->getOperand(0));
2475       // The high bits are not guaranteed to be anything.  Insert an extend.
2476       if (Node->getOpcode() == ISD::SIGN_EXTEND)
2477         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2478                          DAG.getValueType(Node->getOperand(0).getValueType()));
2479       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2480         Result = DAG.getZeroExtendInReg(Result,
2481                                         Node->getOperand(0).getValueType());
2482       break;
2483     }
2484     break;
2485   case ISD::BIT_CONVERT:
2486     Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2487     Result = PromoteOp(Result);
2488     break;
2489     
2490   case ISD::FP_EXTEND:
2491     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2492   case ISD::FP_ROUND:
2493     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2494     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2495     case Promote:  assert(0 && "Unreachable with 2 FP types!");
2496     case Legal:
2497       // Input is legal?  Do an FP_ROUND_INREG.
2498       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
2499                            DAG.getValueType(VT));
2500       break;
2501     }
2502     break;
2503
2504   case ISD::SINT_TO_FP:
2505   case ISD::UINT_TO_FP:
2506     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2507     case Legal:
2508       // No extra round required here.
2509       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2510       break;
2511
2512     case Promote:
2513       Result = PromoteOp(Node->getOperand(0));
2514       if (Node->getOpcode() == ISD::SINT_TO_FP)
2515         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2516                              Result,
2517                          DAG.getValueType(Node->getOperand(0).getValueType()));
2518       else
2519         Result = DAG.getZeroExtendInReg(Result,
2520                                         Node->getOperand(0).getValueType());
2521       // No extra round required here.
2522       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2523       break;
2524     case Expand:
2525       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2526                              Node->getOperand(0));
2527       // Round if we cannot tolerate excess precision.
2528       if (NoExcessFPPrecision)
2529         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2530                              DAG.getValueType(VT));
2531       break;
2532     }
2533     break;
2534
2535   case ISD::SIGN_EXTEND_INREG:
2536     Result = PromoteOp(Node->getOperand(0));
2537     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
2538                          Node->getOperand(1));
2539     break;
2540   case ISD::FP_TO_SINT:
2541   case ISD::FP_TO_UINT:
2542     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2543     case Legal:
2544       Tmp1 = Node->getOperand(0);
2545       break;
2546     case Promote:
2547       // The input result is prerounded, so we don't have to do anything
2548       // special.
2549       Tmp1 = PromoteOp(Node->getOperand(0));
2550       break;
2551     case Expand:
2552       assert(0 && "not implemented");
2553     }
2554     // If we're promoting a UINT to a larger size, check to see if the new node
2555     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2556     // we can use that instead.  This allows us to generate better code for
2557     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2558     // legal, such as PowerPC.
2559     if (Node->getOpcode() == ISD::FP_TO_UINT && 
2560         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2561         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2562          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2563       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2564     } else {
2565       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2566     }
2567     break;
2568
2569   case ISD::FABS:
2570   case ISD::FNEG:
2571     Tmp1 = PromoteOp(Node->getOperand(0));
2572     assert(Tmp1.getValueType() == NVT);
2573     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2574     // NOTE: we do not have to do any extra rounding here for
2575     // NoExcessFPPrecision, because we know the input will have the appropriate
2576     // precision, and these operations don't modify precision at all.
2577     break;
2578
2579   case ISD::FSQRT:
2580   case ISD::FSIN:
2581   case ISD::FCOS:
2582     Tmp1 = PromoteOp(Node->getOperand(0));
2583     assert(Tmp1.getValueType() == NVT);
2584     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2585     if (NoExcessFPPrecision)
2586       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2587                            DAG.getValueType(VT));
2588     break;
2589
2590   case ISD::AND:
2591   case ISD::OR:
2592   case ISD::XOR:
2593   case ISD::ADD:
2594   case ISD::SUB:
2595   case ISD::MUL:
2596     // The input may have strange things in the top bits of the registers, but
2597     // these operations don't care.  They may have weird bits going out, but
2598     // that too is okay if they are integer operations.
2599     Tmp1 = PromoteOp(Node->getOperand(0));
2600     Tmp2 = PromoteOp(Node->getOperand(1));
2601     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2602     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2603     break;
2604   case ISD::FADD:
2605   case ISD::FSUB:
2606   case ISD::FMUL:
2607     Tmp1 = PromoteOp(Node->getOperand(0));
2608     Tmp2 = PromoteOp(Node->getOperand(1));
2609     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2610     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2611     
2612     // Floating point operations will give excess precision that we may not be
2613     // able to tolerate.  If we DO allow excess precision, just leave it,
2614     // otherwise excise it.
2615     // FIXME: Why would we need to round FP ops more than integer ones?
2616     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2617     if (NoExcessFPPrecision)
2618       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2619                            DAG.getValueType(VT));
2620     break;
2621
2622   case ISD::SDIV:
2623   case ISD::SREM:
2624     // These operators require that their input be sign extended.
2625     Tmp1 = PromoteOp(Node->getOperand(0));
2626     Tmp2 = PromoteOp(Node->getOperand(1));
2627     if (MVT::isInteger(NVT)) {
2628       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2629                          DAG.getValueType(VT));
2630       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2631                          DAG.getValueType(VT));
2632     }
2633     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2634
2635     // Perform FP_ROUND: this is probably overly pessimistic.
2636     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2637       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2638                            DAG.getValueType(VT));
2639     break;
2640   case ISD::FDIV:
2641   case ISD::FREM:
2642     // These operators require that their input be fp extended.
2643     Tmp1 = PromoteOp(Node->getOperand(0));
2644     Tmp2 = PromoteOp(Node->getOperand(1));
2645     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2646     
2647     // Perform FP_ROUND: this is probably overly pessimistic.
2648     if (NoExcessFPPrecision)
2649       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2650                            DAG.getValueType(VT));
2651     break;
2652
2653   case ISD::UDIV:
2654   case ISD::UREM:
2655     // These operators require that their input be zero extended.
2656     Tmp1 = PromoteOp(Node->getOperand(0));
2657     Tmp2 = PromoteOp(Node->getOperand(1));
2658     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
2659     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2660     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
2661     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2662     break;
2663
2664   case ISD::SHL:
2665     Tmp1 = PromoteOp(Node->getOperand(0));
2666     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
2667     break;
2668   case ISD::SRA:
2669     // The input value must be properly sign extended.
2670     Tmp1 = PromoteOp(Node->getOperand(0));
2671     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2672                        DAG.getValueType(VT));
2673     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
2674     break;
2675   case ISD::SRL:
2676     // The input value must be properly zero extended.
2677     Tmp1 = PromoteOp(Node->getOperand(0));
2678     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2679     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
2680     break;
2681
2682   case ISD::VAARG:
2683     Tmp1 = Node->getOperand(0);   // Get the chain.
2684     Tmp2 = Node->getOperand(1);   // Get the pointer.
2685     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
2686       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
2687       Result = TLI.CustomPromoteOperation(Tmp3, DAG);
2688     } else {
2689       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2690                                      Node->getOperand(2));
2691       // Increment the pointer, VAList, to the next vaarg
2692       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
2693                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
2694                                          TLI.getPointerTy()));
2695       // Store the incremented VAList to the legalized pointer
2696       Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
2697                          Node->getOperand(2));
2698       // Load the actual argument out of the pointer VAList
2699       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList,
2700                               DAG.getSrcValue(0), VT);
2701     }
2702     // Remember that we legalized the chain.
2703     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2704     break;
2705
2706   case ISD::LOAD:
2707     Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Node->getOperand(0),
2708                             Node->getOperand(1), Node->getOperand(2), VT);
2709     // Remember that we legalized the chain.
2710     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2711     break;
2712   case ISD::SEXTLOAD:
2713   case ISD::ZEXTLOAD:
2714   case ISD::EXTLOAD:
2715     Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
2716                             Node->getOperand(1), Node->getOperand(2),
2717                             cast<VTSDNode>(Node->getOperand(3))->getVT());
2718     // Remember that we legalized the chain.
2719     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2720     break;
2721   case ISD::SELECT:
2722     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
2723     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
2724     Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
2725     break;
2726   case ISD::SELECT_CC:
2727     Tmp2 = PromoteOp(Node->getOperand(2));   // True
2728     Tmp3 = PromoteOp(Node->getOperand(3));   // False
2729     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2730                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
2731     break;
2732   case ISD::BSWAP:
2733     Tmp1 = Node->getOperand(0);
2734     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2735     Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2736     Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2737                          DAG.getConstant(getSizeInBits(NVT) - getSizeInBits(VT),
2738                                          TLI.getShiftAmountTy()));
2739     break;
2740   case ISD::CTPOP:
2741   case ISD::CTTZ:
2742   case ISD::CTLZ:
2743     // Zero extend the argument
2744     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
2745     // Perform the larger operation, then subtract if needed.
2746     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2747     switch(Node->getOpcode()) {
2748     case ISD::CTPOP:
2749       Result = Tmp1;
2750       break;
2751     case ISD::CTTZ:
2752       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2753       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2754                           DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
2755       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2756                            DAG.getConstant(getSizeInBits(VT), NVT), Tmp1);
2757       break;
2758     case ISD::CTLZ:
2759       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2760       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2761                            DAG.getConstant(getSizeInBits(NVT) -
2762                                            getSizeInBits(VT), NVT));
2763       break;
2764     }
2765     break;
2766   }
2767
2768   assert(Result.Val && "Didn't set a result!");
2769
2770   // Make sure the result is itself legal.
2771   Result = LegalizeOp(Result);
2772   
2773   // Remember that we promoted this!
2774   AddPromotedOperand(Op, Result);
2775   return Result;
2776 }
2777
2778 /// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
2779 /// The resultant code need not be legal.  Note that SrcOp is the input operand
2780 /// to the BIT_CONVERT, not the BIT_CONVERT node itself.
2781 SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
2782                                                   SDOperand SrcOp) {
2783   // Create the stack frame object.
2784   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
2785   unsigned ByteSize = MVT::getSizeInBits(DestVT)/8;
2786   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
2787   SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
2788   
2789   // Emit a store to the stack slot.
2790   SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
2791                                 SrcOp, FIPtr, DAG.getSrcValue(NULL));
2792   // Result is a load from the stack slot.
2793   return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
2794 }
2795
2796 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
2797                                             SDOperand Op, SDOperand Amt,
2798                                             SDOperand &Lo, SDOperand &Hi) {
2799   // Expand the subcomponents.
2800   SDOperand LHSL, LHSH;
2801   ExpandOp(Op, LHSL, LHSH);
2802
2803   std::vector<SDOperand> Ops;
2804   Ops.push_back(LHSL);
2805   Ops.push_back(LHSH);
2806   Ops.push_back(Amt);
2807   std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
2808   Lo = DAG.getNode(NodeOp, VTs, Ops);
2809   Hi = Lo.getValue(1);
2810 }
2811
2812
2813 /// ExpandShift - Try to find a clever way to expand this shift operation out to
2814 /// smaller elements.  If we can't find a way that is more efficient than a
2815 /// libcall on this target, return false.  Otherwise, return true with the
2816 /// low-parts expanded into Lo and Hi.
2817 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
2818                                        SDOperand &Lo, SDOperand &Hi) {
2819   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
2820          "This is not a shift!");
2821
2822   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
2823   SDOperand ShAmt = LegalizeOp(Amt);
2824   MVT::ValueType ShTy = ShAmt.getValueType();
2825   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
2826   unsigned NVTBits = MVT::getSizeInBits(NVT);
2827
2828   // Handle the case when Amt is an immediate.  Other cases are currently broken
2829   // and are disabled.
2830   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
2831     unsigned Cst = CN->getValue();
2832     // Expand the incoming operand to be shifted, so that we have its parts
2833     SDOperand InL, InH;
2834     ExpandOp(Op, InL, InH);
2835     switch(Opc) {
2836     case ISD::SHL:
2837       if (Cst > VTBits) {
2838         Lo = DAG.getConstant(0, NVT);
2839         Hi = DAG.getConstant(0, NVT);
2840       } else if (Cst > NVTBits) {
2841         Lo = DAG.getConstant(0, NVT);
2842         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
2843       } else if (Cst == NVTBits) {
2844         Lo = DAG.getConstant(0, NVT);
2845         Hi = InL;
2846       } else {
2847         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
2848         Hi = DAG.getNode(ISD::OR, NVT,
2849            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
2850            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
2851       }
2852       return true;
2853     case ISD::SRL:
2854       if (Cst > VTBits) {
2855         Lo = DAG.getConstant(0, NVT);
2856         Hi = DAG.getConstant(0, NVT);
2857       } else if (Cst > NVTBits) {
2858         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
2859         Hi = DAG.getConstant(0, NVT);
2860       } else if (Cst == NVTBits) {
2861         Lo = InH;
2862         Hi = DAG.getConstant(0, NVT);
2863       } else {
2864         Lo = DAG.getNode(ISD::OR, NVT,
2865            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
2866            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
2867         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
2868       }
2869       return true;
2870     case ISD::SRA:
2871       if (Cst > VTBits) {
2872         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
2873                               DAG.getConstant(NVTBits-1, ShTy));
2874       } else if (Cst > NVTBits) {
2875         Lo = DAG.getNode(ISD::SRA, NVT, InH,
2876                            DAG.getConstant(Cst-NVTBits, ShTy));
2877         Hi = DAG.getNode(ISD::SRA, NVT, InH,
2878                               DAG.getConstant(NVTBits-1, ShTy));
2879       } else if (Cst == NVTBits) {
2880         Lo = InH;
2881         Hi = DAG.getNode(ISD::SRA, NVT, InH,
2882                               DAG.getConstant(NVTBits-1, ShTy));
2883       } else {
2884         Lo = DAG.getNode(ISD::OR, NVT,
2885            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
2886            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
2887         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
2888       }
2889       return true;
2890     }
2891   }
2892   return false;
2893 }
2894
2895 /// FindLatestCallSeqStart - Scan up the dag to find the latest (highest
2896 /// NodeDepth) node that is an CallSeqStart operation and occurs later than
2897 /// Found.
2898 static void FindLatestCallSeqStart(SDNode *Node, SDNode *&Found,
2899                                    std::set<SDNode*> &Visited) {
2900   if (Node->getNodeDepth() <= Found->getNodeDepth() ||
2901       !Visited.insert(Node).second) return;
2902   
2903   // If we found an CALLSEQ_START, we already know this node occurs later
2904   // than the Found node. Just remember this node and return.
2905   if (Node->getOpcode() == ISD::CALLSEQ_START) {
2906     Found = Node;
2907     return;
2908   }
2909
2910   // Otherwise, scan the operands of Node to see if any of them is a call.
2911   assert(Node->getNumOperands() != 0 &&
2912          "All leaves should have depth equal to the entry node!");
2913   for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
2914     FindLatestCallSeqStart(Node->getOperand(i).Val, Found, Visited);
2915
2916   // Tail recurse for the last iteration.
2917   FindLatestCallSeqStart(Node->getOperand(Node->getNumOperands()-1).Val,
2918                          Found, Visited);
2919 }
2920
2921
2922 /// FindEarliestCallSeqEnd - Scan down the dag to find the earliest (lowest
2923 /// NodeDepth) node that is an CallSeqEnd operation and occurs more recent
2924 /// than Found.
2925 static void FindEarliestCallSeqEnd(SDNode *Node, SDNode *&Found,
2926                                    std::set<SDNode*> &Visited) {
2927   if ((Found && Node->getNodeDepth() >= Found->getNodeDepth()) ||
2928       !Visited.insert(Node).second) return;
2929
2930   // If we found an CALLSEQ_END, we already know this node occurs earlier
2931   // than the Found node. Just remember this node and return.
2932   if (Node->getOpcode() == ISD::CALLSEQ_END) {
2933     Found = Node;
2934     return;
2935   }
2936
2937   // Otherwise, scan the operands of Node to see if any of them is a call.
2938   SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
2939   if (UI == E) return;
2940   for (--E; UI != E; ++UI)
2941     FindEarliestCallSeqEnd(*UI, Found, Visited);
2942
2943   // Tail recurse for the last iteration.
2944   FindEarliestCallSeqEnd(*UI, Found, Visited);
2945 }
2946
2947 /// FindCallSeqEnd - Given a chained node that is part of a call sequence,
2948 /// find the CALLSEQ_END node that terminates the call sequence.
2949 static SDNode *FindCallSeqEnd(SDNode *Node) {
2950   if (Node->getOpcode() == ISD::CALLSEQ_END)
2951     return Node;
2952   if (Node->use_empty())
2953     return 0;   // No CallSeqEnd
2954
2955   // The chain is usually at the end.
2956   SDOperand TheChain(Node, Node->getNumValues()-1);
2957   if (TheChain.getValueType() != MVT::Other) {
2958     // Sometimes it's at the beginning.
2959     TheChain = SDOperand(Node, 0);
2960     if (TheChain.getValueType() != MVT::Other) {
2961       // Otherwise, hunt for it.
2962       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
2963         if (Node->getValueType(i) == MVT::Other) {
2964           TheChain = SDOperand(Node, i);
2965           break;
2966         }
2967
2968       // Otherwise, we walked into a node without a chain.  
2969       if (TheChain.getValueType() != MVT::Other)
2970         return 0;
2971     }
2972   }
2973
2974   for (SDNode::use_iterator UI = Node->use_begin(),
2975          E = Node->use_end(); UI != E; ++UI) {
2976
2977     // Make sure to only follow users of our token chain.
2978     SDNode *User = *UI;
2979     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2980       if (User->getOperand(i) == TheChain)
2981         if (SDNode *Result = FindCallSeqEnd(User))
2982           return Result;
2983   }
2984   return 0;
2985 }
2986
2987 /// FindCallSeqStart - Given a chained node that is part of a call sequence,
2988 /// find the CALLSEQ_START node that initiates the call sequence.
2989 static SDNode *FindCallSeqStart(SDNode *Node) {
2990   assert(Node && "Didn't find callseq_start for a call??");
2991   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
2992
2993   assert(Node->getOperand(0).getValueType() == MVT::Other &&
2994          "Node doesn't have a token chain argument!");
2995   return FindCallSeqStart(Node->getOperand(0).Val);
2996 }
2997
2998
2999 /// FindInputOutputChains - If we are replacing an operation with a call we need
3000 /// to find the call that occurs before and the call that occurs after it to
3001 /// properly serialize the calls in the block.  The returned operand is the
3002 /// input chain value for the new call (e.g. the entry node or the previous
3003 /// call), and OutChain is set to be the chain node to update to point to the
3004 /// end of the call chain.
3005 static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
3006                                        SDOperand Entry) {
3007   SDNode *LatestCallSeqStart = Entry.Val;
3008   SDNode *LatestCallSeqEnd = 0;
3009   std::set<SDNode*> Visited;
3010   FindLatestCallSeqStart(OpNode, LatestCallSeqStart, Visited);
3011   Visited.clear();
3012   //std::cerr<<"Found node: "; LatestCallSeqStart->dump(); std::cerr <<"\n";
3013
3014   // It is possible that no ISD::CALLSEQ_START was found because there is no
3015   // previous call in the function.  LatestCallStackDown may in that case be
3016   // the entry node itself.  Do not attempt to find a matching CALLSEQ_END
3017   // unless LatestCallStackDown is an CALLSEQ_START.
3018   if (LatestCallSeqStart->getOpcode() == ISD::CALLSEQ_START) {
3019     LatestCallSeqEnd = FindCallSeqEnd(LatestCallSeqStart);
3020     //std::cerr<<"Found end node: "; LatestCallSeqEnd->dump(); std::cerr <<"\n";
3021   } else {
3022     LatestCallSeqEnd = Entry.Val;
3023   }
3024   assert(LatestCallSeqEnd && "NULL return from FindCallSeqEnd");
3025
3026   // Finally, find the first call that this must come before, first we find the
3027   // CallSeqEnd that ends the call.
3028   OutChain = 0;
3029   FindEarliestCallSeqEnd(OpNode, OutChain, Visited);
3030   Visited.clear();
3031
3032   // If we found one, translate from the adj up to the callseq_start.
3033   if (OutChain)
3034     OutChain = FindCallSeqStart(OutChain);
3035
3036   return SDOperand(LatestCallSeqEnd, 0);
3037 }
3038
3039 /// SpliceCallInto - Given the result chain of a libcall (CallResult), and a
3040 void SelectionDAGLegalize::SpliceCallInto(const SDOperand &CallResult,
3041                                           SDNode *OutChain) {
3042   // Nothing to splice it into?
3043   if (OutChain == 0) return;
3044
3045   assert(OutChain->getOperand(0).getValueType() == MVT::Other);
3046   //OutChain->dump();
3047
3048   // Form a token factor node merging the old inval and the new inval.
3049   SDOperand InToken = DAG.getNode(ISD::TokenFactor, MVT::Other, CallResult,
3050                                   OutChain->getOperand(0));
3051   // Change the node to refer to the new token.
3052   OutChain->setAdjCallChain(InToken);
3053 }
3054
3055
3056 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3057 // does not fit into a register, return the lo part and set the hi part to the
3058 // by-reg argument.  If it does fit into a single register, return the result
3059 // and leave the Hi part unset.
3060 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3061                                               SDOperand &Hi) {
3062   SDNode *OutChain;
3063   SDOperand InChain = FindInputOutputChains(Node, OutChain,
3064                                             DAG.getEntryNode());
3065   if (InChain.Val == 0)
3066     InChain = DAG.getEntryNode();
3067
3068   TargetLowering::ArgListTy Args;
3069   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3070     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3071     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3072     Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3073   }
3074   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3075
3076   // Splice the libcall in wherever FindInputOutputChains tells us to.
3077   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3078   std::pair<SDOperand,SDOperand> CallInfo =
3079     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3080                     Callee, Args, DAG);
3081
3082   SDOperand Result;
3083   switch (getTypeAction(CallInfo.first.getValueType())) {
3084   default: assert(0 && "Unknown thing");
3085   case Legal:
3086     Result = CallInfo.first;
3087     break;
3088   case Expand:
3089     ExpandOp(CallInfo.first, Result, Hi);
3090     break;
3091   }
3092
3093   CallInfo.second = LegalizeOp(CallInfo.second);
3094   SpliceCallInto(CallInfo.second, OutChain);
3095   return Result;
3096 }
3097
3098
3099 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3100 /// destination type is legal.
3101 SDOperand SelectionDAGLegalize::
3102 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3103   assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3104   assert(getTypeAction(Source.getValueType()) == Expand &&
3105          "This is not an expansion!");
3106   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3107
3108   if (!isSigned) {
3109     assert(Source.getValueType() == MVT::i64 &&
3110            "This only works for 64-bit -> FP");
3111     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3112     // incoming integer is set.  To handle this, we dynamically test to see if
3113     // it is set, and, if so, add a fudge factor.
3114     SDOperand Lo, Hi;
3115     ExpandOp(Source, Lo, Hi);
3116
3117     // If this is unsigned, and not supported, first perform the conversion to
3118     // signed, then adjust the result if the sign bit is set.
3119     SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3120                    DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3121
3122     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3123                                      DAG.getConstant(0, Hi.getValueType()),
3124                                      ISD::SETLT);
3125     SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3126     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3127                                       SignSet, Four, Zero);
3128     uint64_t FF = 0x5f800000ULL;
3129     if (TLI.isLittleEndian()) FF <<= 32;
3130     static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3131
3132     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3133     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3134     SDOperand FudgeInReg;
3135     if (DestTy == MVT::f32)
3136       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3137                                DAG.getSrcValue(NULL));
3138     else {
3139       assert(DestTy == MVT::f64 && "Unexpected conversion");
3140       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3141                                   CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3142     }
3143     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3144   }
3145
3146   // Check to see if the target has a custom way to lower this.  If so, use it.
3147   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3148   default: assert(0 && "This action not implemented for this operation!");
3149   case TargetLowering::Legal:
3150   case TargetLowering::Expand:
3151     break;   // This case is handled below.
3152   case TargetLowering::Custom: {
3153     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3154                                                   Source), DAG);
3155     if (NV.Val)
3156       return LegalizeOp(NV);
3157     break;   // The target decided this was legal after all
3158   }
3159   }
3160
3161   // Expand the source, then glue it back together for the call.  We must expand
3162   // the source in case it is shared (this pass of legalize must traverse it).
3163   SDOperand SrcLo, SrcHi;
3164   ExpandOp(Source, SrcLo, SrcHi);
3165   Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3166
3167   SDNode *OutChain = 0;
3168   SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
3169                                             DAG.getEntryNode());
3170   const char *FnName = 0;
3171   if (DestTy == MVT::f32)
3172     FnName = "__floatdisf";
3173   else {
3174     assert(DestTy == MVT::f64 && "Unknown fp value type!");
3175     FnName = "__floatdidf";
3176   }
3177
3178   SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
3179
3180   TargetLowering::ArgListTy Args;
3181   const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
3182
3183   Args.push_back(std::make_pair(Source, ArgTy));
3184
3185   // We don't care about token chains for libcalls.  We just use the entry
3186   // node as our input and ignore the output chain.  This allows us to place
3187   // calls wherever we need them to satisfy data dependences.
3188   const Type *RetTy = MVT::getTypeForValueType(DestTy);
3189
3190   std::pair<SDOperand,SDOperand> CallResult =
3191     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, true,
3192                     Callee, Args, DAG);
3193
3194   SpliceCallInto(CallResult.second, OutChain);
3195   return CallResult.first;
3196 }
3197
3198 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
3199 /// INT_TO_FP operation of the specified operand when the target requests that
3200 /// we expand it.  At this point, we know that the result and operand types are
3201 /// legal for the target.
3202 SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
3203                                                      SDOperand Op0,
3204                                                      MVT::ValueType DestVT) {
3205   if (Op0.getValueType() == MVT::i32) {
3206     // simple 32-bit [signed|unsigned] integer to float/double expansion
3207     
3208     // get the stack frame index of a 8 byte buffer
3209     MachineFunction &MF = DAG.getMachineFunction();
3210     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3211     // get address of 8 byte buffer
3212     SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3213     // word offset constant for Hi/Lo address computation
3214     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
3215     // set up Hi and Lo (into buffer) address based on endian
3216     SDOperand Hi, Lo;
3217     if (TLI.isLittleEndian()) {
3218       Hi = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
3219       Lo = StackSlot;
3220     } else {
3221       Hi = StackSlot;
3222       Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
3223     }
3224     // if signed map to unsigned space
3225     SDOperand Op0Mapped;
3226     if (isSigned) {
3227       // constant used to invert sign bit (signed to unsigned mapping)
3228       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
3229       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
3230     } else {
3231       Op0Mapped = Op0;
3232     }
3233     // store the lo of the constructed double - based on integer input
3234     SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3235                                    Op0Mapped, Lo, DAG.getSrcValue(NULL));
3236     // initial hi portion of constructed double
3237     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
3238     // store the hi of the constructed double - biased exponent
3239     SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
3240                                    InitialHi, Hi, DAG.getSrcValue(NULL));
3241     // load the constructed double
3242     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
3243                                DAG.getSrcValue(NULL));
3244     // FP constant to bias correct the final result
3245     SDOperand Bias = DAG.getConstantFP(isSigned ?
3246                                             BitsToDouble(0x4330000080000000ULL)
3247                                           : BitsToDouble(0x4330000000000000ULL),
3248                                      MVT::f64);
3249     // subtract the bias
3250     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
3251     // final result
3252     SDOperand Result;
3253     // handle final rounding
3254     if (DestVT == MVT::f64) {
3255       // do nothing
3256       Result = Sub;
3257     } else {
3258      // if f32 then cast to f32
3259       Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
3260     }
3261     return Result;
3262   }
3263   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
3264   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
3265
3266   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
3267                                    DAG.getConstant(0, Op0.getValueType()),
3268                                    ISD::SETLT);
3269   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3270   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3271                                     SignSet, Four, Zero);
3272
3273   // If the sign bit of the integer is set, the large number will be treated
3274   // as a negative number.  To counteract this, the dynamic code adds an
3275   // offset depending on the data type.
3276   uint64_t FF;
3277   switch (Op0.getValueType()) {
3278   default: assert(0 && "Unsupported integer type!");
3279   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
3280   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
3281   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
3282   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
3283   }
3284   if (TLI.isLittleEndian()) FF <<= 32;
3285   static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3286
3287   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3288   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3289   SDOperand FudgeInReg;
3290   if (DestVT == MVT::f32)
3291     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3292                              DAG.getSrcValue(NULL));
3293   else {
3294     assert(DestVT == MVT::f64 && "Unexpected conversion");
3295     FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
3296                                            DAG.getEntryNode(), CPIdx,
3297                                            DAG.getSrcValue(NULL), MVT::f32));
3298   }
3299
3300   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
3301 }
3302
3303 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
3304 /// *INT_TO_FP operation of the specified operand when the target requests that
3305 /// we promote it.  At this point, we know that the result and operand types are
3306 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3307 /// operation that takes a larger input.
3308 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
3309                                                       MVT::ValueType DestVT,
3310                                                       bool isSigned) {
3311   // First step, figure out the appropriate *INT_TO_FP operation to use.
3312   MVT::ValueType NewInTy = LegalOp.getValueType();
3313
3314   unsigned OpToUse = 0;
3315
3316   // Scan for the appropriate larger type to use.
3317   while (1) {
3318     NewInTy = (MVT::ValueType)(NewInTy+1);
3319     assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
3320
3321     // If the target supports SINT_TO_FP of this type, use it.
3322     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
3323       default: break;
3324       case TargetLowering::Legal:
3325         if (!TLI.isTypeLegal(NewInTy))
3326           break;  // Can't use this datatype.
3327         // FALL THROUGH.
3328       case TargetLowering::Custom:
3329         OpToUse = ISD::SINT_TO_FP;
3330         break;
3331     }
3332     if (OpToUse) break;
3333     if (isSigned) continue;
3334
3335     // If the target supports UINT_TO_FP of this type, use it.
3336     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
3337       default: break;
3338       case TargetLowering::Legal:
3339         if (!TLI.isTypeLegal(NewInTy))
3340           break;  // Can't use this datatype.
3341         // FALL THROUGH.
3342       case TargetLowering::Custom:
3343         OpToUse = ISD::UINT_TO_FP;
3344         break;
3345     }
3346     if (OpToUse) break;
3347
3348     // Otherwise, try a larger type.
3349   }
3350
3351   // Okay, we found the operation and type to use.  Zero extend our input to the
3352   // desired type then run the operation on it.
3353   return DAG.getNode(OpToUse, DestVT,
3354                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3355                                  NewInTy, LegalOp));
3356 }
3357
3358 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
3359 /// FP_TO_*INT operation of the specified operand when the target requests that
3360 /// we promote it.  At this point, we know that the result and operand types are
3361 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3362 /// operation that returns a larger result.
3363 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
3364                                                       MVT::ValueType DestVT,
3365                                                       bool isSigned) {
3366   // First step, figure out the appropriate FP_TO*INT operation to use.
3367   MVT::ValueType NewOutTy = DestVT;
3368
3369   unsigned OpToUse = 0;
3370
3371   // Scan for the appropriate larger type to use.
3372   while (1) {
3373     NewOutTy = (MVT::ValueType)(NewOutTy+1);
3374     assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
3375
3376     // If the target supports FP_TO_SINT returning this type, use it.
3377     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
3378     default: break;
3379     case TargetLowering::Legal:
3380       if (!TLI.isTypeLegal(NewOutTy))
3381         break;  // Can't use this datatype.
3382       // FALL THROUGH.
3383     case TargetLowering::Custom:
3384       OpToUse = ISD::FP_TO_SINT;
3385       break;
3386     }
3387     if (OpToUse) break;
3388
3389     // If the target supports FP_TO_UINT of this type, use it.
3390     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
3391     default: break;
3392     case TargetLowering::Legal:
3393       if (!TLI.isTypeLegal(NewOutTy))
3394         break;  // Can't use this datatype.
3395       // FALL THROUGH.
3396     case TargetLowering::Custom:
3397       OpToUse = ISD::FP_TO_UINT;
3398       break;
3399     }
3400     if (OpToUse) break;
3401
3402     // Otherwise, try a larger type.
3403   }
3404
3405   // Okay, we found the operation and type to use.  Truncate the result of the
3406   // extended FP_TO_*INT operation to the desired size.
3407   return DAG.getNode(ISD::TRUNCATE, DestVT,
3408                      DAG.getNode(OpToUse, NewOutTy, LegalOp));
3409 }
3410
3411 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
3412 ///
3413 SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
3414   MVT::ValueType VT = Op.getValueType();
3415   MVT::ValueType SHVT = TLI.getShiftAmountTy();
3416   SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
3417   switch (VT) {
3418   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
3419   case MVT::i16:
3420     Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3421     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3422     return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
3423   case MVT::i32:
3424     Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3425     Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3426     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3427     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3428     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
3429     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
3430     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3431     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3432     return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3433   case MVT::i64:
3434     Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
3435     Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
3436     Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3437     Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3438     Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3439     Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3440     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
3441     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
3442     Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
3443     Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
3444     Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
3445     Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
3446     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
3447     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
3448     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
3449     Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
3450     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3451     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3452     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
3453     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3454     return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
3455   }
3456 }
3457
3458 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
3459 ///
3460 SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
3461   switch (Opc) {
3462   default: assert(0 && "Cannot expand this yet!");
3463   case ISD::CTPOP: {
3464     static const uint64_t mask[6] = {
3465       0x5555555555555555ULL, 0x3333333333333333ULL,
3466       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
3467       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
3468     };
3469     MVT::ValueType VT = Op.getValueType();
3470     MVT::ValueType ShVT = TLI.getShiftAmountTy();
3471     unsigned len = getSizeInBits(VT);
3472     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
3473       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
3474       SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
3475       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
3476       Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
3477                        DAG.getNode(ISD::AND, VT,
3478                                    DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
3479     }
3480     return Op;
3481   }
3482   case ISD::CTLZ: {
3483     // for now, we do this:
3484     // x = x | (x >> 1);
3485     // x = x | (x >> 2);
3486     // ...
3487     // x = x | (x >>16);
3488     // x = x | (x >>32); // for 64-bit input
3489     // return popcount(~x);
3490     //
3491     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
3492     MVT::ValueType VT = Op.getValueType();
3493     MVT::ValueType ShVT = TLI.getShiftAmountTy();
3494     unsigned len = getSizeInBits(VT);
3495     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
3496       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
3497       Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
3498     }
3499     Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
3500     return DAG.getNode(ISD::CTPOP, VT, Op);
3501   }
3502   case ISD::CTTZ: {
3503     // for now, we use: { return popcount(~x & (x - 1)); }
3504     // unless the target has ctlz but not ctpop, in which case we use:
3505     // { return 32 - nlz(~x & (x-1)); }
3506     // see also http://www.hackersdelight.org/HDcode/ntz.cc
3507     MVT::ValueType VT = Op.getValueType();
3508     SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
3509     SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
3510                        DAG.getNode(ISD::XOR, VT, Op, Tmp2),
3511                        DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
3512     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
3513     if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
3514         TLI.isOperationLegal(ISD::CTLZ, VT))
3515       return DAG.getNode(ISD::SUB, VT,
3516                          DAG.getConstant(getSizeInBits(VT), VT),
3517                          DAG.getNode(ISD::CTLZ, VT, Tmp3));
3518     return DAG.getNode(ISD::CTPOP, VT, Tmp3);
3519   }
3520   }
3521 }
3522
3523
3524 /// ExpandOp - Expand the specified SDOperand into its two component pieces
3525 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
3526 /// LegalizeNodes map is filled in for any results that are not expanded, the
3527 /// ExpandedNodes map is filled in for any results that are expanded, and the
3528 /// Lo/Hi values are returned.
3529 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
3530   MVT::ValueType VT = Op.getValueType();
3531   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3532   SDNode *Node = Op.Val;
3533   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
3534   assert((MVT::isInteger(VT) || VT == MVT::Vector) && 
3535          "Cannot expand FP values!");
3536   assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
3537          "Cannot expand to FP value or to larger int value!");
3538
3539   // See if we already expanded it.
3540   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
3541     = ExpandedNodes.find(Op);
3542   if (I != ExpandedNodes.end()) {
3543     Lo = I->second.first;
3544     Hi = I->second.second;
3545     return;
3546   }
3547
3548   switch (Node->getOpcode()) {
3549   case ISD::CopyFromReg:
3550     assert(0 && "CopyFromReg must be legal!");
3551   default:
3552     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
3553     assert(0 && "Do not know how to expand this operator!");
3554     abort();
3555   case ISD::UNDEF:
3556     Lo = DAG.getNode(ISD::UNDEF, NVT);
3557     Hi = DAG.getNode(ISD::UNDEF, NVT);
3558     break;
3559   case ISD::Constant: {
3560     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
3561     Lo = DAG.getConstant(Cst, NVT);
3562     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
3563     break;
3564   }
3565   case ISD::ConstantVec: {
3566     unsigned NumElements = Node->getNumOperands();
3567     // If we only have two elements left in the constant vector, just break it
3568     // apart into the two scalar constants it contains.  Otherwise, bisect the
3569     // ConstantVec, and return each half as a new ConstantVec.
3570     // FIXME: this is hard coded as big endian, it may have to change to support
3571     // SSE and Alpha MVI
3572     if (NumElements == 2) {
3573       Hi = Node->getOperand(0);
3574       Lo = Node->getOperand(1);
3575     } else {
3576       NumElements /= 2; 
3577       std::vector<SDOperand> LoOps, HiOps;
3578       for (unsigned I = 0, E = NumElements; I < E; ++I) {
3579         HiOps.push_back(Node->getOperand(I));
3580         LoOps.push_back(Node->getOperand(I+NumElements));
3581       }
3582       Lo = DAG.getNode(ISD::ConstantVec, MVT::Vector, LoOps);
3583       Hi = DAG.getNode(ISD::ConstantVec, MVT::Vector, HiOps);
3584     }
3585     break;
3586   }
3587
3588   case ISD::BUILD_PAIR:
3589     // Return the operands.
3590     Lo = Node->getOperand(0);
3591     Hi = Node->getOperand(1);
3592     break;
3593     
3594   case ISD::SIGN_EXTEND_INREG:
3595     ExpandOp(Node->getOperand(0), Lo, Hi);
3596     // Sign extend the lo-part.
3597     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
3598                      DAG.getConstant(MVT::getSizeInBits(NVT)-1,
3599                                      TLI.getShiftAmountTy()));
3600     // sext_inreg the low part if needed.
3601     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
3602     break;
3603
3604   case ISD::BSWAP: {
3605     ExpandOp(Node->getOperand(0), Lo, Hi);
3606     SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
3607     Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
3608     Lo = TempLo;
3609     break;
3610   }
3611     
3612   case ISD::CTPOP:
3613     ExpandOp(Node->getOperand(0), Lo, Hi);
3614     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
3615                      DAG.getNode(ISD::CTPOP, NVT, Lo),
3616                      DAG.getNode(ISD::CTPOP, NVT, Hi));
3617     Hi = DAG.getConstant(0, NVT);
3618     break;
3619
3620   case ISD::CTLZ: {
3621     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
3622     ExpandOp(Node->getOperand(0), Lo, Hi);
3623     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3624     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
3625     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
3626                                         ISD::SETNE);
3627     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
3628     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
3629
3630     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
3631     Hi = DAG.getConstant(0, NVT);
3632     break;
3633   }
3634
3635   case ISD::CTTZ: {
3636     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
3637     ExpandOp(Node->getOperand(0), Lo, Hi);
3638     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3639     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
3640     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
3641                                         ISD::SETNE);
3642     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
3643     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
3644
3645     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
3646     Hi = DAG.getConstant(0, NVT);
3647     break;
3648   }
3649
3650   case ISD::VAARG: {
3651     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
3652     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
3653     Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
3654     Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
3655
3656     // Remember that we legalized the chain.
3657     Hi = LegalizeOp(Hi);
3658     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
3659     if (!TLI.isLittleEndian())
3660       std::swap(Lo, Hi);
3661     break;
3662   }
3663     
3664   case ISD::LOAD: {
3665     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
3666     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
3667     Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
3668
3669     // Increment the pointer to the other half.
3670     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
3671     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3672                       getIntPtrConstant(IncrementSize));
3673     // FIXME: This creates a bogus srcvalue!
3674     Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
3675
3676     // Build a factor node to remember that this load is independent of the
3677     // other one.
3678     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
3679                                Hi.getValue(1));
3680
3681     // Remember that we legalized the chain.
3682     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
3683     if (!TLI.isLittleEndian())
3684       std::swap(Lo, Hi);
3685     break;
3686   }
3687   case ISD::VLOAD: {
3688     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
3689     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
3690     unsigned NumElements =cast<ConstantSDNode>(Node->getOperand(2))->getValue();
3691     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3692     
3693     // If we only have two elements, turn into a pair of scalar loads.
3694     // FIXME: handle case where a vector of two elements is fine, such as
3695     //   2 x double on SSE2.
3696     if (NumElements == 2) {
3697       Lo = DAG.getLoad(EVT, Ch, Ptr, Node->getOperand(4));
3698       // Increment the pointer to the other half.
3699       unsigned IncrementSize = MVT::getSizeInBits(EVT)/8;
3700       Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3701                         getIntPtrConstant(IncrementSize));
3702       // FIXME: This creates a bogus srcvalue!
3703       Hi = DAG.getLoad(EVT, Ch, Ptr, Node->getOperand(4));
3704     } else {
3705       NumElements /= 2; // Split the vector in half
3706       Lo = DAG.getVecLoad(NumElements, EVT, Ch, Ptr, Node->getOperand(4));
3707       unsigned IncrementSize = NumElements * MVT::getSizeInBits(EVT)/8;
3708       Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3709                         getIntPtrConstant(IncrementSize));
3710       // FIXME: This creates a bogus srcvalue!
3711       Hi = DAG.getVecLoad(NumElements, EVT, Ch, Ptr, Node->getOperand(4));
3712     }
3713     
3714     // Build a factor node to remember that this load is independent of the
3715     // other one.
3716     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
3717                                Hi.getValue(1));
3718     
3719     // Remember that we legalized the chain.
3720     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
3721     if (!TLI.isLittleEndian())
3722       std::swap(Lo, Hi);
3723     break;
3724   }
3725   case ISD::VADD:
3726   case ISD::VSUB:
3727   case ISD::VMUL: {
3728     unsigned NumElements =cast<ConstantSDNode>(Node->getOperand(2))->getValue();
3729     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3730     SDOperand LL, LH, RL, RH;
3731     
3732     ExpandOp(Node->getOperand(0), LL, LH);
3733     ExpandOp(Node->getOperand(1), RL, RH);
3734
3735     // If we only have two elements, turn into a pair of scalar loads.
3736     // FIXME: handle case where a vector of two elements is fine, such as
3737     //   2 x double on SSE2.
3738     if (NumElements == 2) {
3739       unsigned Opc = getScalarizedOpcode(Node->getOpcode(), EVT);
3740       Lo = DAG.getNode(Opc, EVT, LL, RL);
3741       Hi = DAG.getNode(Opc, EVT, LH, RH);
3742     } else {
3743       Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL, LL.getOperand(2),
3744                        LL.getOperand(3));
3745       Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH, LH.getOperand(2),
3746                        LH.getOperand(3));
3747     }
3748     break;
3749   }
3750   case ISD::AND:
3751   case ISD::OR:
3752   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
3753     SDOperand LL, LH, RL, RH;
3754     ExpandOp(Node->getOperand(0), LL, LH);
3755     ExpandOp(Node->getOperand(1), RL, RH);
3756     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
3757     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
3758     break;
3759   }
3760   case ISD::SELECT: {
3761     SDOperand LL, LH, RL, RH;
3762     ExpandOp(Node->getOperand(1), LL, LH);
3763     ExpandOp(Node->getOperand(2), RL, RH);
3764     Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
3765     Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
3766     break;
3767   }
3768   case ISD::SELECT_CC: {
3769     SDOperand TL, TH, FL, FH;
3770     ExpandOp(Node->getOperand(2), TL, TH);
3771     ExpandOp(Node->getOperand(3), FL, FH);
3772     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3773                      Node->getOperand(1), TL, FL, Node->getOperand(4));
3774     Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3775                      Node->getOperand(1), TH, FH, Node->getOperand(4));
3776     break;
3777   }
3778   case ISD::SEXTLOAD: {
3779     SDOperand Chain = Node->getOperand(0);
3780     SDOperand Ptr   = Node->getOperand(1);
3781     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3782     
3783     if (EVT == NVT)
3784       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3785     else
3786       Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3787                           EVT);
3788     
3789     // Remember that we legalized the chain.
3790     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
3791     
3792     // The high part is obtained by SRA'ing all but one of the bits of the lo
3793     // part.
3794     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
3795     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
3796                                                        TLI.getShiftAmountTy()));
3797     break;
3798   }
3799   case ISD::ZEXTLOAD: {
3800     SDOperand Chain = Node->getOperand(0);
3801     SDOperand Ptr   = Node->getOperand(1);
3802     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3803     
3804     if (EVT == NVT)
3805       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3806     else
3807       Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3808                           EVT);
3809     
3810     // Remember that we legalized the chain.
3811     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
3812
3813     // The high part is just a zero.
3814     Hi = DAG.getConstant(0, NVT);
3815     break;
3816   }
3817   case ISD::EXTLOAD: {
3818     SDOperand Chain = Node->getOperand(0);
3819     SDOperand Ptr   = Node->getOperand(1);
3820     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3821     
3822     if (EVT == NVT)
3823       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3824     else
3825       Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3826                           EVT);
3827     
3828     // Remember that we legalized the chain.
3829     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
3830     
3831     // The high part is undefined.
3832     Hi = DAG.getNode(ISD::UNDEF, NVT);
3833     break;
3834   }
3835   case ISD::ANY_EXTEND:
3836     // The low part is any extension of the input (which degenerates to a copy).
3837     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
3838     // The high part is undefined.
3839     Hi = DAG.getNode(ISD::UNDEF, NVT);
3840     break;
3841   case ISD::SIGN_EXTEND: {
3842     // The low part is just a sign extension of the input (which degenerates to
3843     // a copy).
3844     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
3845
3846     // The high part is obtained by SRA'ing all but one of the bits of the lo
3847     // part.
3848     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
3849     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
3850                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
3851     break;
3852   }
3853   case ISD::ZERO_EXTEND:
3854     // The low part is just a zero extension of the input (which degenerates to
3855     // a copy).
3856     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
3857
3858     // The high part is just a zero.
3859     Hi = DAG.getConstant(0, NVT);
3860     break;
3861     
3862   case ISD::BIT_CONVERT: {
3863     SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0), 
3864                                       Node->getOperand(0));
3865     ExpandOp(Tmp, Lo, Hi);
3866     break;
3867   }
3868
3869   case ISD::READCYCLECOUNTER:
3870     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
3871                  TargetLowering::Custom &&
3872            "Must custom expand ReadCycleCounter");
3873     Lo = TLI.LowerOperation(Op, DAG);
3874     assert(Lo.Val && "Node must be custom expanded!");
3875     Hi = Lo.getValue(1);
3876     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
3877                         LegalizeOp(Lo.getValue(2)));
3878     break;
3879
3880     // These operators cannot be expanded directly, emit them as calls to
3881     // library functions.
3882   case ISD::FP_TO_SINT:
3883     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
3884       SDOperand Op;
3885       switch (getTypeAction(Node->getOperand(0).getValueType())) {
3886       case Expand: assert(0 && "cannot expand FP!");
3887       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
3888       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
3889       }
3890
3891       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
3892
3893       // Now that the custom expander is done, expand the result, which is still
3894       // VT.
3895       if (Op.Val) {
3896         ExpandOp(Op, Lo, Hi);
3897         break;
3898       }
3899     }
3900
3901     if (Node->getOperand(0).getValueType() == MVT::f32)
3902       Lo = ExpandLibCall("__fixsfdi", Node, Hi);
3903     else
3904       Lo = ExpandLibCall("__fixdfdi", Node, Hi);
3905     break;
3906
3907   case ISD::FP_TO_UINT:
3908     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
3909       SDOperand Op;
3910       switch (getTypeAction(Node->getOperand(0).getValueType())) {
3911         case Expand: assert(0 && "cannot expand FP!");
3912         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
3913         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
3914       }
3915         
3916       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
3917
3918       // Now that the custom expander is done, expand the result.
3919       if (Op.Val) {
3920         ExpandOp(Op, Lo, Hi);
3921         break;
3922       }
3923     }
3924
3925     if (Node->getOperand(0).getValueType() == MVT::f32)
3926       Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
3927     else
3928       Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
3929     break;
3930
3931   case ISD::SHL: {
3932     // If the target wants custom lowering, do so.
3933     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
3934     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
3935       SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
3936       Op = TLI.LowerOperation(Op, DAG);
3937       if (Op.Val) {
3938         // Now that the custom expander is done, expand the result, which is
3939         // still VT.
3940         ExpandOp(Op, Lo, Hi);
3941         break;
3942       }
3943     }
3944     
3945     // If we can emit an efficient shift operation, do so now.
3946     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
3947       break;
3948
3949     // If this target supports SHL_PARTS, use it.
3950     TargetLowering::LegalizeAction Action =
3951       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
3952     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
3953         Action == TargetLowering::Custom) {
3954       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
3955       break;
3956     }
3957
3958     // Otherwise, emit a libcall.
3959     Lo = ExpandLibCall("__ashldi3", Node, Hi);
3960     break;
3961   }
3962
3963   case ISD::SRA: {
3964     // If the target wants custom lowering, do so.
3965     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
3966     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
3967       SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
3968       Op = TLI.LowerOperation(Op, DAG);
3969       if (Op.Val) {
3970         // Now that the custom expander is done, expand the result, which is
3971         // still VT.
3972         ExpandOp(Op, Lo, Hi);
3973         break;
3974       }
3975     }
3976     
3977     // If we can emit an efficient shift operation, do so now.
3978     if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
3979       break;
3980
3981     // If this target supports SRA_PARTS, use it.
3982     TargetLowering::LegalizeAction Action =
3983       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
3984     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
3985         Action == TargetLowering::Custom) {
3986       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
3987       break;
3988     }
3989
3990     // Otherwise, emit a libcall.
3991     Lo = ExpandLibCall("__ashrdi3", Node, Hi);
3992     break;
3993   }
3994
3995   case ISD::SRL: {
3996     // If the target wants custom lowering, do so.
3997     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
3998     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
3999       SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
4000       Op = TLI.LowerOperation(Op, DAG);
4001       if (Op.Val) {
4002         // Now that the custom expander is done, expand the result, which is
4003         // still VT.
4004         ExpandOp(Op, Lo, Hi);
4005         break;
4006       }
4007     }
4008
4009     // If we can emit an efficient shift operation, do so now.
4010     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4011       break;
4012
4013     // If this target supports SRL_PARTS, use it.
4014     TargetLowering::LegalizeAction Action =
4015       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
4016     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4017         Action == TargetLowering::Custom) {
4018       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4019       break;
4020     }
4021
4022     // Otherwise, emit a libcall.
4023     Lo = ExpandLibCall("__lshrdi3", Node, Hi);
4024     break;
4025   }
4026
4027   case ISD::ADD:
4028   case ISD::SUB: {
4029     // If the target wants to custom expand this, let them.
4030     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
4031             TargetLowering::Custom) {
4032       Op = TLI.LowerOperation(Op, DAG);
4033       if (Op.Val) {
4034         ExpandOp(Op, Lo, Hi);
4035         break;
4036       }
4037     }
4038     
4039     // Expand the subcomponents.
4040     SDOperand LHSL, LHSH, RHSL, RHSH;
4041     ExpandOp(Node->getOperand(0), LHSL, LHSH);
4042     ExpandOp(Node->getOperand(1), RHSL, RHSH);
4043     
4044     std::vector<SDOperand> Ops;
4045     Ops.push_back(LHSL);
4046     Ops.push_back(LHSH);
4047     Ops.push_back(RHSL);
4048     Ops.push_back(RHSH);
4049     std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
4050     unsigned Opc = 
4051       Node->getOpcode() == ISD::ADD ? ISD::ADD_PARTS : ISD::SUB_PARTS;
4052     Lo = DAG.getNode(Opc, VTs, Ops);
4053     Hi = Lo.getValue(1);
4054     break;
4055   }
4056   case ISD::MUL: {
4057     if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
4058       SDOperand LL, LH, RL, RH;
4059       ExpandOp(Node->getOperand(0), LL, LH);
4060       ExpandOp(Node->getOperand(1), RL, RH);
4061       unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
4062       // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
4063       // extended the sign bit of the low half through the upper half, and if so
4064       // emit a MULHS instead of the alternate sequence that is valid for any
4065       // i64 x i64 multiply.
4066       if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
4067           // is RH an extension of the sign bit of RL?
4068           RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
4069           RH.getOperand(1).getOpcode() == ISD::Constant &&
4070           cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
4071           // is LH an extension of the sign bit of LL?
4072           LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
4073           LH.getOperand(1).getOpcode() == ISD::Constant &&
4074           cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
4075         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
4076       } else {
4077         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
4078         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
4079         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
4080         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
4081         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
4082       }
4083       Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
4084     } else {
4085       Lo = ExpandLibCall("__muldi3" , Node, Hi);
4086     }
4087     break;
4088   }
4089   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
4090   case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
4091   case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
4092   case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
4093   }
4094
4095   // Make sure the resultant values have been legalized themselves, unless this
4096   // is a type that requires multi-step expansion.
4097   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
4098     Lo = LegalizeOp(Lo);
4099     Hi = LegalizeOp(Hi);
4100   }
4101
4102   // Remember in a map if the values will be reused later.
4103   bool isNew =
4104     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4105   assert(isNew && "Value already expanded?!?");
4106 }
4107
4108
4109 // SelectionDAG::Legalize - This is the entry point for the file.
4110 //
4111 void SelectionDAG::Legalize() {
4112   /// run - This is the main entry point to this class.
4113   ///
4114   SelectionDAGLegalize(*this).LegalizeDAG();
4115 }
4116