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