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