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