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