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