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