28a9471cd06693627193cd411fac39db7c969b5c
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::Legalize method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineConstantPool.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/Constants.h"
22 #include <iostream>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
27 /// hacks on it until the target machine can handle it.  This involves
28 /// eliminating value sizes the machine cannot handle (promoting small sizes to
29 /// large sizes or splitting up large values into small values) as well as
30 /// eliminating operations the machine cannot handle.
31 ///
32 /// This code also does a small amount of optimization and recognition of idioms
33 /// as part of its processing.  For example, if a target does not support a
34 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
35 /// will attempt merge setcc and brc instructions into brcc's.
36 ///
37 namespace {
38 class SelectionDAGLegalize {
39   TargetLowering &TLI;
40   SelectionDAG &DAG;
41
42   /// LegalizeAction - This enum indicates what action we should take for each
43   /// value type the can occur in the program.
44   enum LegalizeAction {
45     Legal,            // The target natively supports this value type.
46     Promote,          // This should be promoted to the next larger type.
47     Expand,           // This integer type should be broken into smaller pieces.
48   };
49
50   /// TransformToType - For any value types we are promoting or expanding, this
51   /// contains the value type that we are changing to.  For Expanded types, this
52   /// contains one step of the expand (e.g. i64 -> i32), even if there are
53   /// multiple steps required (e.g. i64 -> i16)
54   MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
55
56   /// ValueTypeActions - This is a bitvector that contains two bits for each
57   /// value type, where the two bits correspond to the LegalizeAction enum.
58   /// This can be queried with "getTypeAction(VT)".
59   unsigned ValueTypeActions;
60
61   /// NeedsAnotherIteration - This is set when we expand a large integer
62   /// operation into smaller integer operations, but the smaller operations are
63   /// not set.  This occurs only rarely in practice, for targets that don't have
64   /// 32-bit or larger integer registers.
65   bool NeedsAnotherIteration;
66
67   /// LegalizedNodes - For nodes that are of legal width, and that have more
68   /// than one use, this map indicates what regularized operand to use.  This
69   /// allows us to avoid legalizing the same thing more than once.
70   std::map<SDOperand, SDOperand> LegalizedNodes;
71
72   /// PromotedNodes - For nodes that are below legal width, and that have more
73   /// than one use, this map indicates what promoted value to use.  This allows
74   /// us to avoid promoting the same thing more than once.
75   std::map<SDOperand, SDOperand> PromotedNodes;
76
77   /// ExpandedNodes - For nodes that need to be expanded, and which have more
78   /// than one use, this map indicates which which operands are the expanded
79   /// version of the input.  This allows us to avoid expanding the same node
80   /// more than once.
81   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
82
83   void AddLegalizedOperand(SDOperand From, SDOperand To) {
84     bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
85     assert(isNew && "Got into the map somehow?");
86   }
87   void AddPromotedOperand(SDOperand From, SDOperand To) {
88     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
89     assert(isNew && "Got into the map somehow?");
90   }
91
92   /// setValueTypeAction - Set the action for a particular value type.  This
93   /// assumes an action has not already been set for this value type.
94   void setValueTypeAction(MVT::ValueType VT, LegalizeAction A) {
95     ValueTypeActions |= A << (VT*2);
96     if (A == Promote) {
97       MVT::ValueType PromoteTo;
98       if (VT == MVT::f32)
99         PromoteTo = MVT::f64;
100       else {
101         unsigned LargerReg = VT+1;
102         while (!TLI.hasNativeSupportFor((MVT::ValueType)LargerReg)) {
103           ++LargerReg;
104           assert(MVT::isInteger((MVT::ValueType)LargerReg) &&
105                  "Nothing to promote to??");
106         }
107         PromoteTo = (MVT::ValueType)LargerReg;
108       }
109
110       assert(MVT::isInteger(VT) == MVT::isInteger(PromoteTo) &&
111              MVT::isFloatingPoint(VT) == MVT::isFloatingPoint(PromoteTo) &&
112              "Can only promote from int->int or fp->fp!");
113       assert(VT < PromoteTo && "Must promote to a larger type!");
114       TransformToType[VT] = PromoteTo;
115     } else if (A == Expand) {
116       assert(MVT::isInteger(VT) && VT > MVT::i8 &&
117              "Cannot expand this type: target must support SOME integer reg!");
118       // Expand to the next smaller integer type!
119       TransformToType[VT] = (MVT::ValueType)(VT-1);
120     }
121   }
122
123 public:
124
125   SelectionDAGLegalize(TargetLowering &TLI, SelectionDAG &DAG);
126
127   /// Run - While there is still lowering to do, perform a pass over the DAG.
128   /// Most regularization can be done in a single pass, but targets that require
129   /// large values to be split into registers multiple times (e.g. i64 -> 4x
130   /// i16) require iteration for these values (the first iteration will demote
131   /// to i32, the second will demote to i16).
132   void Run() {
133     do {
134       NeedsAnotherIteration = false;
135       LegalizeDAG();
136     } while (NeedsAnotherIteration);
137   }
138
139   /// getTypeAction - Return how we should legalize values of this type, either
140   /// it is already legal or we need to expand it into multiple registers of
141   /// smaller integer type, or we need to promote it to a larger type.
142   LegalizeAction getTypeAction(MVT::ValueType VT) const {
143     return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
144   }
145
146   /// isTypeLegal - Return true if this type is legal on this target.
147   ///
148   bool isTypeLegal(MVT::ValueType VT) const {
149     return getTypeAction(VT) == Legal;
150   }
151
152 private:
153   void LegalizeDAG();
154
155   SDOperand LegalizeOp(SDOperand O);
156   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
157   SDOperand PromoteOp(SDOperand O);
158
159   SDOperand getIntPtrConstant(uint64_t Val) {
160     return DAG.getConstant(Val, TLI.getPointerTy());
161   }
162 };
163 }
164
165
166 SelectionDAGLegalize::SelectionDAGLegalize(TargetLowering &tli,
167                                            SelectionDAG &dag)
168   : TLI(tli), DAG(dag), ValueTypeActions(0) {
169
170   assert(MVT::LAST_VALUETYPE <= 16 &&
171          "Too many value types for ValueTypeActions to hold!");
172   
173   // Inspect all of the ValueType's possible, deciding how to process them.
174   for (unsigned IntReg = MVT::i1; IntReg <= MVT::i128; ++IntReg)
175     // If TLI says we are expanding this type, expand it!
176     if (TLI.getNumElements((MVT::ValueType)IntReg) != 1)
177       setValueTypeAction((MVT::ValueType)IntReg, Expand);
178     else if (!TLI.hasNativeSupportFor((MVT::ValueType)IntReg))
179       // Otherwise, if we don't have native support, we must promote to a
180       // larger type.
181       setValueTypeAction((MVT::ValueType)IntReg, Promote);
182   
183   // If the target does not have native support for F32, promote it to F64.
184   if (!TLI.hasNativeSupportFor(MVT::f32))
185     setValueTypeAction(MVT::f32, Promote);
186 }
187
188 void SelectionDAGLegalize::LegalizeDAG() {
189   SDOperand OldRoot = DAG.getRoot();
190   SDOperand NewRoot = LegalizeOp(OldRoot);
191   DAG.setRoot(NewRoot);
192
193   ExpandedNodes.clear();
194   LegalizedNodes.clear();
195
196   // Remove dead nodes now.
197   DAG.RemoveDeadNodes(OldRoot.Val);
198 }
199
200 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
201   assert(getTypeAction(Op.getValueType()) == Legal &&
202          "Caller should expand or promote operands that are not legal!");
203
204   // If this operation defines any values that cannot be represented in a
205   // register on this target, make sure to expand or promote them.
206   if (Op.Val->getNumValues() > 1) {
207     for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
208       switch (getTypeAction(Op.Val->getValueType(i))) {
209       case Legal: break;  // Nothing to do.
210       case Expand: {
211         SDOperand T1, T2;
212         ExpandOp(Op.getValue(i), T1, T2);
213         assert(LegalizedNodes.count(Op) &&
214                "Expansion didn't add legal operands!");
215         return LegalizedNodes[Op];
216       }
217       case Promote:
218         PromoteOp(Op.getValue(i));
219         assert(LegalizedNodes.count(Op) &&
220                "Expansion didn't add legal operands!");
221         return LegalizedNodes[Op];
222       }
223   }
224
225   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
226   if (I != LegalizedNodes.end()) return I->second;
227
228   SDOperand Tmp1, Tmp2, Tmp3;
229
230   SDOperand Result = Op;
231   SDNode *Node = Op.Val;
232
233   switch (Node->getOpcode()) {
234   default:
235     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
236     assert(0 && "Do not know how to legalize this operator!");
237     abort();
238   case ISD::EntryToken:
239   case ISD::FrameIndex:
240   case ISD::GlobalAddress:
241   case ISD::ExternalSymbol:
242   case ISD::ConstantPool:           // Nothing to do.
243     assert(getTypeAction(Node->getValueType(0)) == Legal &&
244            "This must be legal!");
245     break;
246   case ISD::CopyFromReg:
247     Tmp1 = LegalizeOp(Node->getOperand(0));
248     if (Tmp1 != Node->getOperand(0))
249       Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
250                                   Node->getValueType(0), Tmp1);
251     break;
252   case ISD::ImplicitDef:
253     Tmp1 = LegalizeOp(Node->getOperand(0));
254     if (Tmp1 != Node->getOperand(0))
255       Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
256     break;
257   case ISD::Constant:
258     // We know we don't need to expand constants here, constants only have one
259     // value and we check that it is fine above.
260
261     // FIXME: Maybe we should handle things like targets that don't support full
262     // 32-bit immediates?
263     break;
264   case ISD::ConstantFP: {
265     // Spill FP immediates to the constant pool if the target cannot directly
266     // codegen them.  Targets often have some immediate values that can be
267     // efficiently generated into an FP register without a load.  We explicitly
268     // leave these constants as ConstantFP nodes for the target to deal with.
269
270     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
271
272     // Check to see if this FP immediate is already legal.
273     bool isLegal = false;
274     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
275            E = TLI.legal_fpimm_end(); I != E; ++I)
276       if (CFP->isExactlyValue(*I)) {
277         isLegal = true;
278         break;
279       }
280
281     if (!isLegal) {
282       // Otherwise we need to spill the constant to memory.
283       MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
284
285       bool Extend = false;
286
287       // If a FP immediate is precise when represented as a float, we put it
288       // into the constant pool as a float, even if it's is statically typed
289       // as a double.
290       MVT::ValueType VT = CFP->getValueType(0);
291       bool isDouble = VT == MVT::f64;
292       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
293                                              Type::FloatTy, CFP->getValue());
294       if (isDouble && CFP->isExactlyValue((float)CFP->getValue())) {
295         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
296         VT = MVT::f32;
297         Extend = true;
298       }
299       
300       SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
301                                             TLI.getPointerTy());
302       Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
303       
304       if (Extend) Result = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Result);
305     }
306     break;
307   }
308   case ISD::TokenFactor: {
309     std::vector<SDOperand> Ops;
310     bool Changed = false;
311     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
312       Ops.push_back(LegalizeOp(Node->getOperand(i)));  // Legalize the operands
313       Changed |= Ops[i] != Node->getOperand(i);
314     }
315     if (Changed)
316       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
317     break;
318   }
319
320   case ISD::ADJCALLSTACKDOWN:
321   case ISD::ADJCALLSTACKUP:
322     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
323     // There is no need to legalize the size argument (Operand #1)
324     if (Tmp1 != Node->getOperand(0))
325       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
326                            Node->getOperand(1));
327     break;
328   case ISD::DYNAMIC_STACKALLOC:
329     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
330     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
331     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
332     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
333         Tmp3 != Node->getOperand(2))
334       Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
335                            Tmp1, Tmp2, Tmp3);
336     else
337       Result = Op.getValue(0);
338
339     // Since this op produces two values, make sure to remember that we
340     // legalized both of them.
341     AddLegalizedOperand(SDOperand(Node, 0), Result);
342     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
343     return Result.getValue(Op.ResNo);
344
345   case ISD::CALL:
346     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
347     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
348     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
349       std::vector<MVT::ValueType> RetTyVTs;
350       RetTyVTs.reserve(Node->getNumValues());
351       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
352         RetTyVTs.push_back(Node->getValueType(i));
353       Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2), 0);
354     } else {
355       Result = Result.getValue(0);
356     }
357     // Since calls produce multiple values, make sure to remember that we
358     // legalized all of them.
359     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
360       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
361     return Result.getValue(Op.ResNo);
362
363   case ISD::BR:
364     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
365     if (Tmp1 != Node->getOperand(0))
366       Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
367     break;
368
369   case ISD::BRCOND:
370     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
371     // FIXME: booleans might not be legal!
372     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the condition.
373     // Basic block destination (Op#2) is always legal.
374     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
375       Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
376                            Node->getOperand(2));
377     break;
378
379   case ISD::LOAD:
380     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
381     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
382     if (Tmp1 != Node->getOperand(0) ||
383         Tmp2 != Node->getOperand(1))
384       Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
385     else
386       Result = SDOperand(Node, 0);
387     
388     // Since loads produce two values, make sure to remember that we legalized
389     // both of them.
390     AddLegalizedOperand(SDOperand(Node, 0), Result);
391     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
392     return Result.getValue(Op.ResNo);
393
394   case ISD::EXTLOAD:
395   case ISD::SEXTLOAD:
396   case ISD::ZEXTLOAD:
397     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
398     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
399     if (Tmp1 != Node->getOperand(0) ||
400         Tmp2 != Node->getOperand(1))
401       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2,
402                            cast<MVTSDNode>(Node)->getExtraValueType());
403     else
404       Result = SDOperand(Node, 0);
405     
406     // Since loads produce two values, make sure to remember that we legalized
407     // both of them.
408     AddLegalizedOperand(SDOperand(Node, 0), Result);
409     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
410     return Result.getValue(Op.ResNo);
411
412   case ISD::EXTRACT_ELEMENT:
413     // Get both the low and high parts.
414     ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
415     if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
416       Result = Tmp2;  // 1 -> Hi
417     else
418       Result = Tmp1;  // 0 -> Lo
419     break;
420
421   case ISD::CopyToReg:
422     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
423     
424     switch (getTypeAction(Node->getOperand(1).getValueType())) {
425     case Legal:
426       // Legalize the incoming value (must be legal).
427       Tmp2 = LegalizeOp(Node->getOperand(1));
428       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
429         Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
430       break;
431     case Expand: {
432       SDOperand Lo, Hi;
433       ExpandOp(Node->getOperand(1), Lo, Hi);      
434       unsigned Reg = cast<RegSDNode>(Node)->getReg();
435       Result = DAG.getCopyToReg(Tmp1, Lo, Reg);
436       Result = DAG.getCopyToReg(Result, Hi, Reg+1);
437       assert(isTypeLegal(Result.getValueType()) &&
438              "Cannot expand multiple times yet (i64 -> i16)");
439       break;
440     }
441     case Promote:
442       assert(0 && "Don't know what it means to promote this!");
443       abort();
444     }
445     break;
446
447   case ISD::RET:
448     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
449     switch (Node->getNumOperands()) {
450     case 2:  // ret val
451       switch (getTypeAction(Node->getOperand(1).getValueType())) {
452       case Legal:
453         Tmp2 = LegalizeOp(Node->getOperand(1));
454         if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
455           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
456         break;
457       case Expand: {
458         SDOperand Lo, Hi;
459         ExpandOp(Node->getOperand(1), Lo, Hi);
460         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
461         break;                             
462       }
463       case Promote:
464         assert(0 && "Can't promote return value!");
465       }
466       break;
467     case 1:  // ret void
468       if (Tmp1 != Node->getOperand(0))
469         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
470       break;
471     default: { // ret <values>
472       std::vector<SDOperand> NewValues;
473       NewValues.push_back(Tmp1);
474       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
475         switch (getTypeAction(Node->getOperand(i).getValueType())) {
476         case Legal:
477           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
478           break;
479         case Expand: {
480           SDOperand Lo, Hi;
481           ExpandOp(Node->getOperand(i), Lo, Hi);
482           NewValues.push_back(Lo);
483           NewValues.push_back(Hi);
484           break;                             
485         }
486         case Promote:
487           assert(0 && "Can't promote return value!");
488         }
489       Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
490       break;
491     }
492     }
493     break;
494   case ISD::STORE:
495     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
496     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
497
498     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
499     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
500       if (CFP->getValueType(0) == MVT::f32) {
501         union {
502           unsigned I;
503           float    F;
504         } V;
505         V.F = CFP->getValue();
506         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
507                              DAG.getConstant(V.I, MVT::i32), Tmp2);
508       } else {
509         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
510         union {
511           uint64_t I;
512           double   F;
513         } V;
514         V.F = CFP->getValue();
515         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
516                              DAG.getConstant(V.I, MVT::i64), Tmp2);
517       }
518       Op = Result;
519       Node = Op.Val;
520     }
521
522     switch (getTypeAction(Node->getOperand(1).getValueType())) {
523     case Legal: {
524       SDOperand Val = LegalizeOp(Node->getOperand(1));
525       if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
526           Tmp2 != Node->getOperand(2))
527         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
528       break;
529     }
530     case Promote:
531       // Truncate the value and store the result.
532       Tmp3 = PromoteOp(Node->getOperand(1));
533       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
534                            Node->getOperand(1).getValueType());
535       break;
536
537     case Expand:
538       SDOperand Lo, Hi;
539       ExpandOp(Node->getOperand(1), Lo, Hi);
540
541       if (!TLI.isLittleEndian())
542         std::swap(Lo, Hi);
543
544       // FIXME: These two stores are independent of each other!
545       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
546
547       unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
548       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
549                          getIntPtrConstant(IncrementSize));
550       assert(isTypeLegal(Tmp2.getValueType()) &&
551              "Pointers must be legal!");
552       Result = DAG.getNode(ISD::STORE, MVT::Other, Result, Hi, Tmp2);
553     }
554     break;
555   case ISD::TRUNCSTORE:
556     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
557     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
558
559     switch (getTypeAction(Node->getOperand(1).getValueType())) {
560     case Legal:
561       Tmp2 = LegalizeOp(Node->getOperand(1));
562       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
563           Tmp3 != Node->getOperand(2))
564         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
565                              cast<MVTSDNode>(Node)->getExtraValueType());
566       break;
567     case Promote:
568     case Expand:
569       assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
570     }
571     break;
572   case ISD::SELECT:
573     // FIXME: BOOLS MAY REQUIRE PROMOTION!
574     Tmp1 = LegalizeOp(Node->getOperand(0));   // Cond
575     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
576     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
577     
578     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
579         Tmp3 != Node->getOperand(2))
580       Result = DAG.getNode(ISD::SELECT, Node->getValueType(0), Tmp1, Tmp2,Tmp3);
581     break;
582   case ISD::SETCC:
583     switch (getTypeAction(Node->getOperand(0).getValueType())) {
584     case Legal:
585       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
586       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
587       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
588         Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
589                               Tmp1, Tmp2);
590       break;
591     case Promote:
592       assert(0 && "Can't promote setcc operands yet!");
593       break;
594     case Expand: 
595       SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
596       ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
597       ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
598       switch (cast<SetCCSDNode>(Node)->getCondition()) {
599       case ISD::SETEQ:
600       case ISD::SETNE:
601         Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
602         Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
603         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
604         Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(), Tmp1,
605                               DAG.getConstant(0, Tmp1.getValueType()));
606         break;
607       default:
608         // FIXME: This generated code sucks.
609         ISD::CondCode LowCC;
610         switch (cast<SetCCSDNode>(Node)->getCondition()) {
611         default: assert(0 && "Unknown integer setcc!");
612         case ISD::SETLT:
613         case ISD::SETULT: LowCC = ISD::SETULT; break;
614         case ISD::SETGT:
615         case ISD::SETUGT: LowCC = ISD::SETUGT; break;
616         case ISD::SETLE:
617         case ISD::SETULE: LowCC = ISD::SETULE; break;
618         case ISD::SETGE:
619         case ISD::SETUGE: LowCC = ISD::SETUGE; break;
620         }
621         
622         // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
623         // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
624         // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
625
626         // NOTE: on targets without efficient SELECT of bools, we can always use
627         // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
628         Tmp1 = DAG.getSetCC(LowCC, LHSLo, RHSLo);
629         Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
630                             LHSHi, RHSHi);
631         Result = DAG.getSetCC(ISD::SETEQ, LHSHi, RHSHi);
632         Result = DAG.getNode(ISD::SELECT, MVT::i1, Result, Tmp1, Tmp2);
633         break;
634       }
635     }
636     break;
637
638   case ISD::MEMSET:
639   case ISD::MEMCPY:
640   case ISD::MEMMOVE: {
641     Tmp1 = LegalizeOp(Node->getOperand(0));
642     Tmp2 = LegalizeOp(Node->getOperand(1));
643     Tmp3 = LegalizeOp(Node->getOperand(2));
644     SDOperand Tmp4 = LegalizeOp(Node->getOperand(3));
645     SDOperand Tmp5 = LegalizeOp(Node->getOperand(4));
646     if (TLI.isOperationSupported(Node->getOpcode(), MVT::Other)) {
647       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
648           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
649           Tmp5 != Node->getOperand(4)) {
650         std::vector<SDOperand> Ops;
651         Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
652         Ops.push_back(Tmp4); Ops.push_back(Tmp5);
653         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
654       }
655     } else {
656       // Otherwise, the target does not support this operation.  Lower the
657       // operation to an explicit libcall as appropriate.
658       MVT::ValueType IntPtr = TLI.getPointerTy();
659       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
660       std::vector<std::pair<SDOperand, const Type*> > Args;
661
662       const char *FnName = 0;
663       if (Node->getOpcode() == ISD::MEMSET) {
664         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
665         // Extend the ubyte argument to be an int value for the call.
666         Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
667         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
668         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
669
670         FnName = "memset";
671       } else if (Node->getOpcode() == ISD::MEMCPY ||
672                  Node->getOpcode() == ISD::MEMMOVE) {
673         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
674         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
675         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
676         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
677       } else {
678         assert(0 && "Unknown op!");
679       }
680       std::pair<SDOperand,SDOperand> CallResult =
681         TLI.LowerCallTo(Tmp1, Type::VoidTy,
682                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
683       Result = LegalizeOp(CallResult.second);
684     }
685     break;
686   }
687   case ISD::ADD:
688   case ISD::SUB:
689   case ISD::MUL:
690   case ISD::UDIV:
691   case ISD::SDIV:
692   case ISD::UREM:
693   case ISD::SREM:
694   case ISD::AND:
695   case ISD::OR:
696   case ISD::XOR:
697   case ISD::SHL:
698   case ISD::SRL:
699   case ISD::SRA:
700     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
701     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
702     if (Tmp1 != Node->getOperand(0) ||
703         Tmp2 != Node->getOperand(1))
704       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
705     break;
706   case ISD::ZERO_EXTEND:
707   case ISD::SIGN_EXTEND:
708   case ISD::TRUNCATE:
709   case ISD::FP_EXTEND:
710   case ISD::FP_ROUND:
711   case ISD::FP_TO_SINT:
712   case ISD::FP_TO_UINT:
713   case ISD::SINT_TO_FP:
714   case ISD::UINT_TO_FP:
715
716     switch (getTypeAction(Node->getOperand(0).getValueType())) {
717     case Legal:
718       Tmp1 = LegalizeOp(Node->getOperand(0));
719       if (Tmp1 != Node->getOperand(0))
720         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
721       break;
722     case Expand:
723       assert(Node->getOpcode() != ISD::SINT_TO_FP &&
724              Node->getOpcode() != ISD::UINT_TO_FP &&
725              "Cannot lower Xint_to_fp to a call yet!");
726
727       // In the expand case, we must be dealing with a truncate, because
728       // otherwise the result would be larger than the source.
729       assert(Node->getOpcode() == ISD::TRUNCATE &&
730              "Shouldn't need to expand other operators here!");
731       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
732
733       // Since the result is legal, we should just be able to truncate the low
734       // part of the source.
735       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
736       break;
737
738     case Promote:
739       switch (Node->getOpcode()) {
740       case ISD::ZERO_EXTEND: {
741         // Mask out the high bits.
742         uint64_t MaskCst =
743           1ULL << (MVT::getSizeInBits(Node->getOperand(0).getValueType()))-1;
744         Tmp1 = PromoteOp(Node->getOperand(0));
745         Result = DAG.getNode(ISD::AND, Node->getValueType(0), Tmp1,
746                              DAG.getConstant(MaskCst, Node->getValueType(0)));
747         break;
748       }
749       case ISD::SIGN_EXTEND:
750       case ISD::TRUNCATE:
751       case ISD::FP_EXTEND:
752       case ISD::FP_ROUND:
753       case ISD::FP_TO_SINT:
754       case ISD::FP_TO_UINT:
755       case ISD::SINT_TO_FP:
756       case ISD::UINT_TO_FP:
757         Node->dump();
758         assert(0 && "Do not know how to promote this yet!");
759       }
760     }
761     break;
762   case ISD::FP_ROUND_INREG:
763   case ISD::SIGN_EXTEND_INREG:
764   case ISD::ZERO_EXTEND_INREG: {
765     Tmp1 = LegalizeOp(Node->getOperand(0));
766     MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
767
768     // If this operation is not supported, convert it to a shl/shr or load/store
769     // pair.
770     if (!TLI.isOperationSupported(Node->getOpcode(), ExtraVT)) {
771       // If this is an integer extend and shifts are supported, do that.
772       if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
773         // NOTE: we could fall back on load/store here too for targets without
774         // AND.  However, it is doubtful that any exist.
775         // AND out the appropriate bits.
776         SDOperand Mask =
777           DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
778                           Node->getValueType(0));
779         Result = DAG.getNode(ISD::AND, Node->getValueType(0),
780                              Node->getOperand(0), Mask);
781       } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
782         // NOTE: we could fall back on load/store here too for targets without
783         // SAR.  However, it is doubtful that any exist.
784         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
785                             MVT::getSizeInBits(ExtraVT);
786         SDOperand ShiftCst = DAG.getConstant(BitsDiff, MVT::i8);
787         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
788                              Node->getOperand(0), ShiftCst);
789         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
790                              Result, ShiftCst);
791       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
792         // The only way we can lower this is to turn it into a STORETRUNC,
793         // EXTLOAD pair, targetting a temporary location (a stack slot).
794
795         // NOTE: there is a choice here between constantly creating new stack
796         // slots and always reusing the same one.  We currently always create
797         // new ones, as reuse may inhibit scheduling.
798         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
799         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
800         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
801         MachineFunction &MF = DAG.getMachineFunction();
802         int SSFI = 
803           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
804         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
805         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
806                              Node->getOperand(0), StackSlot, ExtraVT);
807         Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
808                              Result, StackSlot, ExtraVT);
809       } else {
810         assert(0 && "Unknown op");
811       }
812       Result = LegalizeOp(Result);
813     } else {
814       if (Tmp1 != Node->getOperand(0))
815         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
816                              ExtraVT);
817     }
818     break;
819   }
820   }
821
822   if (!Op.Val->hasOneUse())
823     AddLegalizedOperand(Op, Result);
824
825   return Result;
826 }
827
828 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
829   MVT::ValueType VT = Op.getValueType();
830   MVT::ValueType NVT = TransformToType[VT];
831   assert(getTypeAction(VT) == Promote &&
832          "Caller should expand or legalize operands that are not promotable!");
833   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
834          "Cannot promote to smaller type!");
835
836   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
837   if (I != PromotedNodes.end()) return I->second;
838
839   SDOperand Tmp1, Tmp2, Tmp3;
840
841   SDOperand Result;
842   SDNode *Node = Op.Val;
843
844   // Promotion needs an optimization step to clean up after it, and is not
845   // careful to avoid operations the target does not support.  Make sure that
846   // all generated operations are legalized in the next iteration.
847   NeedsAnotherIteration = true;
848
849   switch (Node->getOpcode()) {
850   default:
851     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
852     assert(0 && "Do not know how to promote this operator!");
853     abort();
854   case ISD::Constant:
855     Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
856     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
857     break;
858   case ISD::ConstantFP:
859     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
860     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
861     break;
862
863   case ISD::TRUNCATE:
864     switch (getTypeAction(Node->getOperand(0).getValueType())) {
865     case Legal:
866       Result = LegalizeOp(Node->getOperand(0));
867       assert(Result.getValueType() >= NVT &&
868              "This truncation doesn't make sense!");
869       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
870         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
871       break;
872     case Expand:
873       assert(0 && "Cannot handle expand yet");
874     case Promote:
875       assert(0 && "Cannot handle promote-promote yet");
876     }
877     break;
878   case ISD::AND:
879   case ISD::OR:
880   case ISD::XOR:
881     // The logical ops can just execute, they don't care what the top bits
882     // coming in are.
883     Tmp1 = PromoteOp(Node->getOperand(0));
884     Tmp2 = PromoteOp(Node->getOperand(1));
885     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
886     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
887     break;
888
889   case ISD::ADD:
890   case ISD::MUL:
891     // The input may have strange things in the top bits of the registers, but
892     // these operations don't care.  They may have wierd bits going out, but
893     // that too is okay if they are integer operations.
894     Tmp1 = PromoteOp(Node->getOperand(0));
895     Tmp2 = PromoteOp(Node->getOperand(1));
896     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
897     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
898
899     // However, if this is a floating point operation, they will give excess
900     // precision that we may not be able to tolerate.  If we DO allow excess
901     // precision, just leave it, otherwise excise it.
902     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
903       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
904     break;
905
906   case ISD::LOAD:
907     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
908     Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
909     Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
910
911     // Remember that we legalized the chain.
912     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
913     break;
914   case ISD::SELECT:
915     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the condition
916     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
917     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
918     Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
919     break;
920   }
921
922   assert(Result.Val && "Didn't set a result!");
923   AddPromotedOperand(Op, Result);
924   return Result;
925 }
926
927 /// ExpandOp - Expand the specified SDOperand into its two component pieces
928 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
929 /// LegalizeNodes map is filled in for any results that are not expanded, the
930 /// ExpandedNodes map is filled in for any results that are expanded, and the
931 /// Lo/Hi values are returned.
932 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
933   MVT::ValueType VT = Op.getValueType();
934   MVT::ValueType NVT = TransformToType[VT];
935   SDNode *Node = Op.Val;
936   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
937   assert(MVT::isInteger(VT) && "Cannot expand FP values!");
938   assert(MVT::isInteger(NVT) && NVT < VT &&
939          "Cannot expand to FP value or to larger int value!");
940
941   // If there is more than one use of this, see if we already expanded it.
942   // There is no use remembering values that only have a single use, as the map
943   // entries will never be reused.
944   if (!Node->hasOneUse()) {
945     std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
946       = ExpandedNodes.find(Op);
947     if (I != ExpandedNodes.end()) {
948       Lo = I->second.first;
949       Hi = I->second.second;
950       return;
951     }
952   }
953
954   // Expanding to multiple registers needs to perform an optimization step, and
955   // is not careful to avoid operations the target does not support.  Make sure
956   // that all generated operations are legalized in the next iteration.
957   NeedsAnotherIteration = true;
958   const char *LibCallName = 0;
959
960   switch (Node->getOpcode()) {
961   default:
962     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
963     assert(0 && "Do not know how to expand this operator!");
964     abort();
965   case ISD::Constant: {
966     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
967     Lo = DAG.getConstant(Cst, NVT);
968     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
969     break;
970   }
971
972   case ISD::CopyFromReg: {
973     unsigned Reg = cast<RegSDNode>(Node)->getReg();
974     // Aggregate register values are always in consequtive pairs.
975     Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
976     Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
977     
978     // Remember that we legalized the chain.
979     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
980
981     assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
982     break;
983   }
984
985   case ISD::LOAD: {
986     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
987     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
988     Lo = DAG.getLoad(NVT, Ch, Ptr);
989
990     // Increment the pointer to the other half.
991     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
992     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
993                       getIntPtrConstant(IncrementSize));
994     // FIXME: This load is independent of the first one.
995     Hi = DAG.getLoad(NVT, Lo.getValue(1), Ptr);
996     
997     // Remember that we legalized the chain.
998     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
999     if (!TLI.isLittleEndian())
1000       std::swap(Lo, Hi);
1001     break;
1002   }
1003   case ISD::CALL: {
1004     SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1005     SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1006
1007     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1008            "Can only expand a call once so far, not i64 -> i16!");
1009
1010     std::vector<MVT::ValueType> RetTyVTs;
1011     RetTyVTs.reserve(3);
1012     RetTyVTs.push_back(NVT);
1013     RetTyVTs.push_back(NVT);
1014     RetTyVTs.push_back(MVT::Other);
1015     SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee);
1016     Lo = SDOperand(NC, 0);
1017     Hi = SDOperand(NC, 1);
1018
1019     // Insert the new chain mapping.
1020     AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1021     break;
1022   }
1023   case ISD::AND:
1024   case ISD::OR:
1025   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
1026     SDOperand LL, LH, RL, RH;
1027     ExpandOp(Node->getOperand(0), LL, LH);
1028     ExpandOp(Node->getOperand(1), RL, RH);
1029     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1030     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1031     break;
1032   }
1033   case ISD::SELECT: {
1034     SDOperand C, LL, LH, RL, RH;
1035     // FIXME: BOOLS MAY REQUIRE PROMOTION!
1036     C = LegalizeOp(Node->getOperand(0));
1037     ExpandOp(Node->getOperand(1), LL, LH);
1038     ExpandOp(Node->getOperand(2), RL, RH);
1039     Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1040     Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1041     break;
1042   }
1043   case ISD::SIGN_EXTEND: {
1044     // The low part is just a sign extension of the input (which degenerates to
1045     // a copy).
1046     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1047     
1048     // The high part is obtained by SRA'ing all but one of the bits of the lo
1049     // part.
1050     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
1051     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1, MVT::i8));
1052     break;
1053   }
1054   case ISD::ZERO_EXTEND:
1055     // The low part is just a zero extension of the input (which degenerates to
1056     // a copy).
1057     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1058     
1059     // The high part is just a zero.
1060     Hi = DAG.getConstant(0, NVT);
1061     break;
1062
1063     // These operators cannot be expanded directly, emit them as calls to
1064     // library functions.
1065   case ISD::FP_TO_SINT:
1066     if (Node->getOperand(0).getValueType() == MVT::f32)
1067       LibCallName = "__fixsfdi";
1068     else
1069       LibCallName = "__fixdfdi";
1070     break;
1071   case ISD::FP_TO_UINT:
1072     if (Node->getOperand(0).getValueType() == MVT::f32)
1073       LibCallName = "__fixunssfdi";
1074     else
1075       LibCallName = "__fixunsdfdi";
1076     break;
1077
1078   case ISD::ADD:  LibCallName = "__adddi3"; break;
1079   case ISD::SUB:  LibCallName = "__subdi3"; break;
1080   case ISD::MUL:  LibCallName = "__muldi3"; break;
1081   case ISD::SDIV: LibCallName = "__divdi3"; break;
1082   case ISD::UDIV: LibCallName = "__udivdi3"; break;
1083   case ISD::SREM: LibCallName = "__moddi3"; break;
1084   case ISD::UREM: LibCallName = "__umoddi3"; break;
1085   case ISD::SHL:  LibCallName = "__ashldi3"; break;
1086   case ISD::SRA:  LibCallName = "__ashrdi3"; break;
1087   case ISD::SRL:  LibCallName = "__lshrdi3"; break;
1088   }
1089
1090   // Int2FP -> __floatdisf/__floatdidf
1091
1092   // If this is to be expanded into a libcall... do so now.
1093   if (LibCallName) {
1094     TargetLowering::ArgListTy Args;
1095     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1096       Args.push_back(std::make_pair(Node->getOperand(i),
1097                  MVT::getTypeForValueType(Node->getOperand(i).getValueType())));
1098     SDOperand Callee = DAG.getExternalSymbol(LibCallName, TLI.getPointerTy());
1099
1100     // We don't care about token chains for libcalls.  We just use the entry
1101     // node as our input and ignore the output chain.  This allows us to place
1102     // calls wherever we need them to satisfy data dependences.
1103     SDOperand Result = TLI.LowerCallTo(DAG.getEntryNode(),
1104                            MVT::getTypeForValueType(Op.getValueType()), Callee,
1105                                        Args, DAG).first;
1106     ExpandOp(Result, Lo, Hi);
1107   }
1108
1109   // Remember in a map if the values will be reused later.
1110   if (!Node->hasOneUse()) {
1111     bool isNew = ExpandedNodes.insert(std::make_pair(Op,
1112                                             std::make_pair(Lo, Hi))).second;
1113     assert(isNew && "Value already expanded?!?");
1114   }
1115 }
1116
1117
1118 // SelectionDAG::Legalize - This is the entry point for the file.
1119 //
1120 void SelectionDAG::Legalize(TargetLowering &TLI) {
1121   /// run - This is the main entry point to this class.
1122   ///
1123   SelectionDAGLegalize(TLI, *this).Run();
1124 }
1125