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