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