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