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