Change the MachineDebugInfo to MachineModuleInfo to better reflect usage
[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/CodeGen/MachineJumpTableInfo.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetOptions.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include <map>
30 using namespace llvm;
31
32 #ifndef NDEBUG
33 static cl::opt<bool>
34 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
35                  cl::desc("Pop up a window to show dags before legalize"));
36 #else
37 static const bool ViewLegalizeDAGs = 0;
38 #endif
39
40 //===----------------------------------------------------------------------===//
41 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
42 /// hacks on it until the target machine can handle it.  This involves
43 /// eliminating value sizes the machine cannot handle (promoting small sizes to
44 /// large sizes or splitting up large values into small values) as well as
45 /// eliminating operations the machine cannot handle.
46 ///
47 /// This code also does a small amount of optimization and recognition of idioms
48 /// as part of its processing.  For example, if a target does not support a
49 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
50 /// will attempt merge setcc and brc instructions into brcc's.
51 ///
52 namespace {
53 class VISIBILITY_HIDDEN SelectionDAGLegalize {
54   TargetLowering &TLI;
55   SelectionDAG &DAG;
56
57   // Libcall insertion helpers.
58   
59   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
60   /// legalized.  We use this to ensure that calls are properly serialized
61   /// against each other, including inserted libcalls.
62   SDOperand LastCALLSEQ_END;
63   
64   /// IsLegalizingCall - This member is used *only* for purposes of providing
65   /// helpful assertions that a libcall isn't created while another call is 
66   /// being legalized (which could lead to non-serialized call sequences).
67   bool IsLegalizingCall;
68   
69   enum LegalizeAction {
70     Legal,      // The target natively supports this operation.
71     Promote,    // This operation should be executed in a larger type.
72     Expand      // Try to expand this to other ops, otherwise use a libcall.
73   };
74   
75   /// ValueTypeActions - This is a bitvector that contains two bits for each
76   /// value type, where the two bits correspond to the LegalizeAction enum.
77   /// This can be queried with "getTypeAction(VT)".
78   TargetLowering::ValueTypeActionImpl ValueTypeActions;
79
80   /// LegalizedNodes - For nodes that are of legal width, and that have more
81   /// than one use, this map indicates what regularized operand to use.  This
82   /// allows us to avoid legalizing the same thing more than once.
83   std::map<SDOperand, SDOperand> LegalizedNodes;
84
85   /// PromotedNodes - For nodes that are below legal width, and that have more
86   /// than one use, this map indicates what promoted value to use.  This allows
87   /// us to avoid promoting the same thing more than once.
88   std::map<SDOperand, SDOperand> PromotedNodes;
89
90   /// ExpandedNodes - For nodes that need to be expanded this map indicates
91   /// which which operands are the expanded version of the input.  This allows
92   /// us to avoid expanding the same node more than once.
93   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
94
95   /// SplitNodes - For vector nodes that need to be split, this map indicates
96   /// which which operands are the split version of the input.  This allows us
97   /// to avoid splitting the same node more than once.
98   std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
99   
100   /// PackedNodes - For nodes that need to be packed from MVT::Vector types to
101   /// concrete packed types, this contains the mapping of ones we have already
102   /// processed to the result.
103   std::map<SDOperand, SDOperand> PackedNodes;
104   
105   void AddLegalizedOperand(SDOperand From, SDOperand To) {
106     LegalizedNodes.insert(std::make_pair(From, To));
107     // If someone requests legalization of the new node, return itself.
108     if (From != To)
109       LegalizedNodes.insert(std::make_pair(To, To));
110   }
111   void AddPromotedOperand(SDOperand From, SDOperand To) {
112     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
113     assert(isNew && "Got into the map somehow?");
114     // If someone requests legalization of the new node, return itself.
115     LegalizedNodes.insert(std::make_pair(To, To));
116   }
117
118 public:
119
120   SelectionDAGLegalize(SelectionDAG &DAG);
121
122   /// getTypeAction - Return how we should legalize values of this type, either
123   /// it is already legal or we need to expand it into multiple registers of
124   /// smaller integer type, or we need to promote it to a larger type.
125   LegalizeAction getTypeAction(MVT::ValueType VT) const {
126     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
127   }
128
129   /// isTypeLegal - Return true if this type is legal on this target.
130   ///
131   bool isTypeLegal(MVT::ValueType VT) const {
132     return getTypeAction(VT) == Legal;
133   }
134
135   void LegalizeDAG();
136
137 private:
138   /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
139   /// appropriate for its type.
140   void HandleOp(SDOperand Op);
141     
142   /// LegalizeOp - We know that the specified value has a legal type.
143   /// Recursively ensure that the operands have legal types, then return the
144   /// result.
145   SDOperand LegalizeOp(SDOperand O);
146   
147   /// PromoteOp - Given an operation that produces a value in an invalid type,
148   /// promote it to compute the value into a larger type.  The produced value
149   /// will have the correct bits for the low portion of the register, but no
150   /// guarantee is made about the top bits: it may be zero, sign-extended, or
151   /// garbage.
152   SDOperand PromoteOp(SDOperand O);
153
154   /// ExpandOp - Expand the specified SDOperand into its two component pieces
155   /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
156   /// the LegalizeNodes map is filled in for any results that are not expanded,
157   /// the ExpandedNodes map is filled in for any results that are expanded, and
158   /// the Lo/Hi values are returned.   This applies to integer types and Vector
159   /// types.
160   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
161
162   /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
163   /// two smaller values of MVT::Vector type.
164   void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
165   
166   /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
167   /// equivalent operation that returns a packed value (e.g. MVT::V4F32).  When
168   /// this is called, we know that PackedVT is the right type for the result and
169   /// we know that this type is legal for the target.
170   SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
171   
172   /// isShuffleLegal - Return true if a vector shuffle is legal with the
173   /// specified mask and type.  Targets can specify exactly which masks they
174   /// support and the code generator is tasked with not creating illegal masks.
175   ///
176   /// Note that this will also return true for shuffles that are promoted to a
177   /// different type.
178   ///
179   /// If this is a legal shuffle, this method returns the (possibly promoted)
180   /// build_vector Mask.  If it's not a legal shuffle, it returns null.
181   SDNode *isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const;
182   
183   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
184                                     std::set<SDNode*> &NodesLeadingTo);
185
186   void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
187     
188   SDOperand CreateStackTemporary(MVT::ValueType VT);
189
190   SDOperand ExpandLibCall(const char *Name, SDNode *Node, bool isSigned,
191                           SDOperand &Hi);
192   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
193                           SDOperand Source);
194
195   SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
196   SDOperand ExpandBUILD_VECTOR(SDNode *Node);
197   SDOperand ExpandSCALAR_TO_VECTOR(SDNode *Node);
198   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
199                                  SDOperand LegalOp,
200                                  MVT::ValueType DestVT);
201   SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
202                                   bool isSigned);
203   SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
204                                   bool isSigned);
205
206   SDOperand ExpandBSWAP(SDOperand Op);
207   SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
208   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
209                    SDOperand &Lo, SDOperand &Hi);
210   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
211                         SDOperand &Lo, SDOperand &Hi);
212
213   SDOperand LowerVEXTRACT_VECTOR_ELT(SDOperand Op);
214   SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
215   
216   SDOperand getIntPtrConstant(uint64_t Val) {
217     return DAG.getConstant(Val, TLI.getPointerTy());
218   }
219 };
220 }
221
222 /// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
223 /// specified mask and type.  Targets can specify exactly which masks they
224 /// support and the code generator is tasked with not creating illegal masks.
225 ///
226 /// Note that this will also return true for shuffles that are promoted to a
227 /// different type.
228 SDNode *SelectionDAGLegalize::isShuffleLegal(MVT::ValueType VT, 
229                                              SDOperand Mask) const {
230   switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
231   default: return 0;
232   case TargetLowering::Legal:
233   case TargetLowering::Custom:
234     break;
235   case TargetLowering::Promote: {
236     // If this is promoted to a different type, convert the shuffle mask and
237     // ask if it is legal in the promoted type!
238     MVT::ValueType NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
239
240     // If we changed # elements, change the shuffle mask.
241     unsigned NumEltsGrowth =
242       MVT::getVectorNumElements(NVT) / MVT::getVectorNumElements(VT);
243     assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
244     if (NumEltsGrowth > 1) {
245       // Renumber the elements.
246       SmallVector<SDOperand, 8> Ops;
247       for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
248         SDOperand InOp = Mask.getOperand(i);
249         for (unsigned j = 0; j != NumEltsGrowth; ++j) {
250           if (InOp.getOpcode() == ISD::UNDEF)
251             Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
252           else {
253             unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
254             Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
255           }
256         }
257       }
258       Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, &Ops[0], Ops.size());
259     }
260     VT = NVT;
261     break;
262   }
263   }
264   return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
265 }
266
267 /// getScalarizedOpcode - Return the scalar opcode that corresponds to the
268 /// specified vector opcode.
269 static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
270   switch (VecOp) {
271   default: assert(0 && "Don't know how to scalarize this opcode!");
272   case ISD::VADD:  return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
273   case ISD::VSUB:  return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
274   case ISD::VMUL:  return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
275   case ISD::VSDIV: return MVT::isInteger(VT) ? ISD::SDIV: ISD::FDIV;
276   case ISD::VUDIV: return MVT::isInteger(VT) ? ISD::UDIV: ISD::FDIV;
277   case ISD::VAND:  return MVT::isInteger(VT) ? ISD::AND : 0;
278   case ISD::VOR:   return MVT::isInteger(VT) ? ISD::OR  : 0;
279   case ISD::VXOR:  return MVT::isInteger(VT) ? ISD::XOR : 0;
280   }
281 }
282
283 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
284   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
285     ValueTypeActions(TLI.getValueTypeActions()) {
286   assert(MVT::LAST_VALUETYPE <= 32 &&
287          "Too many value types for ValueTypeActions to hold!");
288 }
289
290 /// ComputeTopDownOrdering - Add the specified node to the Order list if it has
291 /// not been visited yet and if all of its operands have already been visited.
292 static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
293                                    std::map<SDNode*, unsigned> &Visited) {
294   if (++Visited[N] != N->getNumOperands())
295     return;  // Haven't visited all operands yet
296   
297   Order.push_back(N);
298   
299   if (N->hasOneUse()) { // Tail recurse in common case.
300     ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
301     return;
302   }
303   
304   // Now that we have N in, add anything that uses it if all of their operands
305   // are now done.
306   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
307     ComputeTopDownOrdering(*UI, Order, Visited);
308 }
309
310
311 void SelectionDAGLegalize::LegalizeDAG() {
312   LastCALLSEQ_END = DAG.getEntryNode();
313   IsLegalizingCall = false;
314   
315   // The legalize process is inherently a bottom-up recursive process (users
316   // legalize their uses before themselves).  Given infinite stack space, we
317   // could just start legalizing on the root and traverse the whole graph.  In
318   // practice however, this causes us to run out of stack space on large basic
319   // blocks.  To avoid this problem, compute an ordering of the nodes where each
320   // node is only legalized after all of its operands are legalized.
321   std::map<SDNode*, unsigned> Visited;
322   std::vector<SDNode*> Order;
323   
324   // Compute ordering from all of the leaves in the graphs, those (like the
325   // entry node) that have no operands.
326   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
327        E = DAG.allnodes_end(); I != E; ++I) {
328     if (I->getNumOperands() == 0) {
329       Visited[I] = 0 - 1U;
330       ComputeTopDownOrdering(I, Order, Visited);
331     }
332   }
333   
334   assert(Order.size() == Visited.size() &&
335          Order.size() == 
336             (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
337          "Error: DAG is cyclic!");
338   Visited.clear();
339   
340   for (unsigned i = 0, e = Order.size(); i != e; ++i)
341     HandleOp(SDOperand(Order[i], 0));
342
343   // Finally, it's possible the root changed.  Get the new root.
344   SDOperand OldRoot = DAG.getRoot();
345   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
346   DAG.setRoot(LegalizedNodes[OldRoot]);
347
348   ExpandedNodes.clear();
349   LegalizedNodes.clear();
350   PromotedNodes.clear();
351   SplitNodes.clear();
352   PackedNodes.clear();
353
354   // Remove dead nodes now.
355   DAG.RemoveDeadNodes();
356 }
357
358
359 /// FindCallEndFromCallStart - Given a chained node that is part of a call
360 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
361 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
362   if (Node->getOpcode() == ISD::CALLSEQ_END)
363     return Node;
364   if (Node->use_empty())
365     return 0;   // No CallSeqEnd
366   
367   // The chain is usually at the end.
368   SDOperand TheChain(Node, Node->getNumValues()-1);
369   if (TheChain.getValueType() != MVT::Other) {
370     // Sometimes it's at the beginning.
371     TheChain = SDOperand(Node, 0);
372     if (TheChain.getValueType() != MVT::Other) {
373       // Otherwise, hunt for it.
374       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
375         if (Node->getValueType(i) == MVT::Other) {
376           TheChain = SDOperand(Node, i);
377           break;
378         }
379           
380       // Otherwise, we walked into a node without a chain.  
381       if (TheChain.getValueType() != MVT::Other)
382         return 0;
383     }
384   }
385   
386   for (SDNode::use_iterator UI = Node->use_begin(),
387        E = Node->use_end(); UI != E; ++UI) {
388     
389     // Make sure to only follow users of our token chain.
390     SDNode *User = *UI;
391     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
392       if (User->getOperand(i) == TheChain)
393         if (SDNode *Result = FindCallEndFromCallStart(User))
394           return Result;
395   }
396   return 0;
397 }
398
399 /// FindCallStartFromCallEnd - Given a chained node that is part of a call 
400 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
401 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
402   assert(Node && "Didn't find callseq_start for a call??");
403   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
404   
405   assert(Node->getOperand(0).getValueType() == MVT::Other &&
406          "Node doesn't have a token chain argument!");
407   return FindCallStartFromCallEnd(Node->getOperand(0).Val);
408 }
409
410 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
411 /// see if any uses can reach Dest.  If no dest operands can get to dest, 
412 /// legalize them, legalize ourself, and return false, otherwise, return true.
413 ///
414 /// Keep track of the nodes we fine that actually do lead to Dest in
415 /// NodesLeadingTo.  This avoids retraversing them exponential number of times.
416 ///
417 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
418                                             std::set<SDNode*> &NodesLeadingTo) {
419   if (N == Dest) return true;  // N certainly leads to Dest :)
420   
421   // If we've already processed this node and it does lead to Dest, there is no
422   // need to reprocess it.
423   if (NodesLeadingTo.count(N)) return true;
424   
425   // If the first result of this node has been already legalized, then it cannot
426   // reach N.
427   switch (getTypeAction(N->getValueType(0))) {
428   case Legal: 
429     if (LegalizedNodes.count(SDOperand(N, 0))) return false;
430     break;
431   case Promote:
432     if (PromotedNodes.count(SDOperand(N, 0))) return false;
433     break;
434   case Expand:
435     if (ExpandedNodes.count(SDOperand(N, 0))) return false;
436     break;
437   }
438   
439   // Okay, this node has not already been legalized.  Check and legalize all
440   // operands.  If none lead to Dest, then we can legalize this node.
441   bool OperandsLeadToDest = false;
442   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
443     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
444       LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest, NodesLeadingTo);
445
446   if (OperandsLeadToDest) {
447     NodesLeadingTo.insert(N);
448     return true;
449   }
450
451   // Okay, this node looks safe, legalize it and return false.
452   HandleOp(SDOperand(N, 0));
453   return false;
454 }
455
456 /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
457 /// appropriate for its type.
458 void SelectionDAGLegalize::HandleOp(SDOperand Op) {
459   switch (getTypeAction(Op.getValueType())) {
460   default: assert(0 && "Bad type action!");
461   case Legal:   LegalizeOp(Op); break;
462   case Promote: PromoteOp(Op);  break;
463   case Expand:
464     if (Op.getValueType() != MVT::Vector) {
465       SDOperand X, Y;
466       ExpandOp(Op, X, Y);
467     } else {
468       SDNode *N = Op.Val;
469       unsigned NumOps = N->getNumOperands();
470       unsigned NumElements =
471         cast<ConstantSDNode>(N->getOperand(NumOps-2))->getValue();
472       MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(NumOps-1))->getVT();
473       MVT::ValueType PackedVT = getVectorType(EVT, NumElements);
474       if (PackedVT != MVT::Other && TLI.isTypeLegal(PackedVT)) {
475         // In the common case, this is a legal vector type, convert it to the
476         // packed operation and type now.
477         PackVectorOp(Op, PackedVT);
478       } else if (NumElements == 1) {
479         // Otherwise, if this is a single element vector, convert it to a
480         // scalar operation.
481         PackVectorOp(Op, EVT);
482       } else {
483         // Otherwise, this is a multiple element vector that isn't supported.
484         // Split it in half and legalize both parts.
485         SDOperand X, Y;
486         SplitVectorOp(Op, X, Y);
487       }
488     }
489     break;
490   }
491 }
492
493 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
494 /// a load from the constant pool.
495 static SDOperand ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
496                                   SelectionDAG &DAG, TargetLowering &TLI) {
497   bool Extend = false;
498
499   // If a FP immediate is precise when represented as a float and if the
500   // target can do an extending load from float to double, we put it into
501   // the constant pool as a float, even if it's is statically typed as a
502   // double.
503   MVT::ValueType VT = CFP->getValueType(0);
504   bool isDouble = VT == MVT::f64;
505   ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
506                                       Type::FloatTy, CFP->getValue());
507   if (!UseCP) {
508     double Val = LLVMC->getValue();
509     return isDouble
510       ? DAG.getConstant(DoubleToBits(Val), MVT::i64)
511       : DAG.getConstant(FloatToBits(Val), MVT::i32);
512   }
513
514   if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
515       // Only do this if the target has a native EXTLOAD instruction from f32.
516       TLI.isLoadXLegal(ISD::EXTLOAD, MVT::f32)) {
517     LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC,Type::FloatTy));
518     VT = MVT::f32;
519     Extend = true;
520   }
521
522   SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
523   if (Extend) {
524     return DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
525                           CPIdx, NULL, 0, MVT::f32);
526   } else {
527     return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0);
528   }
529 }
530
531
532 /// ExpandFCOPYSIGNToBitwiseOps - Expands fcopysign to a series of bitwise
533 /// operations.
534 static
535 SDOperand ExpandFCOPYSIGNToBitwiseOps(SDNode *Node, MVT::ValueType NVT,
536                                       SelectionDAG &DAG, TargetLowering &TLI) {
537   MVT::ValueType VT = Node->getValueType(0);
538   MVT::ValueType SrcVT = Node->getOperand(1).getValueType();
539   MVT::ValueType SrcNVT = (SrcVT == MVT::f64) ? MVT::i64 : MVT::i32;
540
541   // First get the sign bit of second operand.
542   SDOperand Mask1 = (SrcVT == MVT::f64)
543     ? DAG.getConstantFP(BitsToDouble(1ULL << 63), SrcVT)
544     : DAG.getConstantFP(BitsToFloat(1U << 31), SrcVT);
545   Mask1 = DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Mask1);
546   SDOperand SignBit= DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Node->getOperand(1));
547   SignBit = DAG.getNode(ISD::AND, SrcNVT, SignBit, Mask1);
548   // Shift right or sign-extend it if the two operands have different types.
549   int SizeDiff = MVT::getSizeInBits(SrcNVT) - MVT::getSizeInBits(NVT);
550   if (SizeDiff > 0) {
551     SignBit = DAG.getNode(ISD::SRL, SrcNVT, SignBit,
552                           DAG.getConstant(SizeDiff, TLI.getShiftAmountTy()));
553     SignBit = DAG.getNode(ISD::TRUNCATE, NVT, SignBit);
554   } else if (SizeDiff < 0)
555     SignBit = DAG.getNode(ISD::SIGN_EXTEND, NVT, SignBit);
556
557   // Clear the sign bit of first operand.
558   SDOperand Mask2 = (VT == MVT::f64)
559     ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
560     : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
561   Mask2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask2);
562   SDOperand Result = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
563   Result = DAG.getNode(ISD::AND, NVT, Result, Mask2);
564
565   // Or the value with the sign bit.
566   Result = DAG.getNode(ISD::OR, NVT, Result, SignBit);
567   return Result;
568 }
569
570
571 /// LegalizeOp - We know that the specified value has a legal type.
572 /// Recursively ensure that the operands have legal types, then return the
573 /// result.
574 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
575   assert(isTypeLegal(Op.getValueType()) &&
576          "Caller should expand or promote operands that are not legal!");
577   SDNode *Node = Op.Val;
578
579   // If this operation defines any values that cannot be represented in a
580   // register on this target, make sure to expand or promote them.
581   if (Node->getNumValues() > 1) {
582     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
583       if (getTypeAction(Node->getValueType(i)) != Legal) {
584         HandleOp(Op.getValue(i));
585         assert(LegalizedNodes.count(Op) &&
586                "Handling didn't add legal operands!");
587         return LegalizedNodes[Op];
588       }
589   }
590
591   // Note that LegalizeOp may be reentered even from single-use nodes, which
592   // means that we always must cache transformed nodes.
593   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
594   if (I != LegalizedNodes.end()) return I->second;
595
596   SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
597   SDOperand Result = Op;
598   bool isCustom = false;
599   
600   switch (Node->getOpcode()) {
601   case ISD::FrameIndex:
602   case ISD::EntryToken:
603   case ISD::Register:
604   case ISD::BasicBlock:
605   case ISD::TargetFrameIndex:
606   case ISD::TargetJumpTable:
607   case ISD::TargetConstant:
608   case ISD::TargetConstantFP:
609   case ISD::TargetConstantPool:
610   case ISD::TargetGlobalAddress:
611   case ISD::TargetExternalSymbol:
612   case ISD::VALUETYPE:
613   case ISD::SRCVALUE:
614   case ISD::STRING:
615   case ISD::CONDCODE:
616   case ISD::GLOBAL_OFFSET_TABLE:
617     // Primitives must all be legal.
618     assert(TLI.isOperationLegal(Node->getValueType(0), Node->getValueType(0)) &&
619            "This must be legal!");
620     break;
621   default:
622     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
623       // If this is a target node, legalize it by legalizing the operands then
624       // passing it through.
625       SmallVector<SDOperand, 8> Ops;
626       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
627         Ops.push_back(LegalizeOp(Node->getOperand(i)));
628
629       Result = DAG.UpdateNodeOperands(Result.getValue(0), &Ops[0], Ops.size());
630
631       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
632         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
633       return Result.getValue(Op.ResNo);
634     }
635     // Otherwise this is an unhandled builtin node.  splat.
636 #ifndef NDEBUG
637     cerr << "NODE: "; Node->dump(); cerr << "\n";
638 #endif
639     assert(0 && "Do not know how to legalize this operator!");
640     abort();
641   case ISD::GlobalAddress:
642   case ISD::ExternalSymbol:
643   case ISD::ConstantPool:
644   case ISD::JumpTable: // Nothing to do.
645     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
646     default: assert(0 && "This action is not supported yet!");
647     case TargetLowering::Custom:
648       Tmp1 = TLI.LowerOperation(Op, DAG);
649       if (Tmp1.Val) Result = Tmp1;
650       // FALLTHROUGH if the target doesn't want to lower this op after all.
651     case TargetLowering::Legal:
652       break;
653     }
654     break;
655   case ISD::AssertSext:
656   case ISD::AssertZext:
657     Tmp1 = LegalizeOp(Node->getOperand(0));
658     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
659     break;
660   case ISD::MERGE_VALUES:
661     // Legalize eliminates MERGE_VALUES nodes.
662     Result = Node->getOperand(Op.ResNo);
663     break;
664   case ISD::CopyFromReg:
665     Tmp1 = LegalizeOp(Node->getOperand(0));
666     Result = Op.getValue(0);
667     if (Node->getNumValues() == 2) {
668       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
669     } else {
670       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
671       if (Node->getNumOperands() == 3) {
672         Tmp2 = LegalizeOp(Node->getOperand(2));
673         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
674       } else {
675         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
676       }
677       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
678     }
679     // Since CopyFromReg produces two values, make sure to remember that we
680     // legalized both of them.
681     AddLegalizedOperand(Op.getValue(0), Result);
682     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
683     return Result.getValue(Op.ResNo);
684   case ISD::UNDEF: {
685     MVT::ValueType VT = Op.getValueType();
686     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
687     default: assert(0 && "This action is not supported yet!");
688     case TargetLowering::Expand:
689       if (MVT::isInteger(VT))
690         Result = DAG.getConstant(0, VT);
691       else if (MVT::isFloatingPoint(VT))
692         Result = DAG.getConstantFP(0, VT);
693       else
694         assert(0 && "Unknown value type!");
695       break;
696     case TargetLowering::Legal:
697       break;
698     }
699     break;
700   }
701     
702   case ISD::INTRINSIC_W_CHAIN:
703   case ISD::INTRINSIC_WO_CHAIN:
704   case ISD::INTRINSIC_VOID: {
705     SmallVector<SDOperand, 8> Ops;
706     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
707       Ops.push_back(LegalizeOp(Node->getOperand(i)));
708     Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
709     
710     // Allow the target to custom lower its intrinsics if it wants to.
711     if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == 
712         TargetLowering::Custom) {
713       Tmp3 = TLI.LowerOperation(Result, DAG);
714       if (Tmp3.Val) Result = Tmp3;
715     }
716
717     if (Result.Val->getNumValues() == 1) break;
718
719     // Must have return value and chain result.
720     assert(Result.Val->getNumValues() == 2 &&
721            "Cannot return more than two values!");
722
723     // Since loads produce two values, make sure to remember that we 
724     // legalized both of them.
725     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
726     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
727     return Result.getValue(Op.ResNo);
728   }    
729
730   case ISD::LOCATION:
731     assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
732     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
733     
734     switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
735     case TargetLowering::Promote:
736     default: assert(0 && "This action is not supported yet!");
737     case TargetLowering::Expand: {
738       MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
739       bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
740       bool useLABEL = TLI.isOperationLegal(ISD::LABEL, MVT::Other);
741       
742       if (MMI && (useDEBUG_LOC || useLABEL)) {
743         const std::string &FName =
744           cast<StringSDNode>(Node->getOperand(3))->getValue();
745         const std::string &DirName = 
746           cast<StringSDNode>(Node->getOperand(4))->getValue();
747         unsigned SrcFile = MMI->RecordSource(DirName, FName);
748
749         SmallVector<SDOperand, 8> Ops;
750         Ops.push_back(Tmp1);  // chain
751         SDOperand LineOp = Node->getOperand(1);
752         SDOperand ColOp = Node->getOperand(2);
753         
754         if (useDEBUG_LOC) {
755           Ops.push_back(LineOp);  // line #
756           Ops.push_back(ColOp);  // col #
757           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
758           Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, &Ops[0], Ops.size());
759         } else {
760           unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
761           unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
762           unsigned ID = MMI->RecordLabel(Line, Col, SrcFile);
763           Ops.push_back(DAG.getConstant(ID, MVT::i32));
764           Result = DAG.getNode(ISD::LABEL, MVT::Other,&Ops[0],Ops.size());
765         }
766       } else {
767         Result = Tmp1;  // chain
768       }
769       break;
770     }
771     case TargetLowering::Legal:
772       if (Tmp1 != Node->getOperand(0) ||
773           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
774         SmallVector<SDOperand, 8> Ops;
775         Ops.push_back(Tmp1);
776         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
777           Ops.push_back(Node->getOperand(1));  // line # must be legal.
778           Ops.push_back(Node->getOperand(2));  // col # must be legal.
779         } else {
780           // Otherwise promote them.
781           Ops.push_back(PromoteOp(Node->getOperand(1)));
782           Ops.push_back(PromoteOp(Node->getOperand(2)));
783         }
784         Ops.push_back(Node->getOperand(3));  // filename must be legal.
785         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
786         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
787       }
788       break;
789     }
790     break;
791     
792   case ISD::DEBUG_LOC:
793     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
794     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
795     default: assert(0 && "This action is not supported yet!");
796     case TargetLowering::Legal:
797       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
798       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
799       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
800       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
801       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
802       break;
803     }
804     break;    
805
806   case ISD::LABEL:
807     assert(Node->getNumOperands() == 2 && "Invalid LABEL node!");
808     switch (TLI.getOperationAction(ISD::LABEL, MVT::Other)) {
809     default: assert(0 && "This action is not supported yet!");
810     case TargetLowering::Legal:
811       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
812       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
813       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
814       break;
815     }
816     break;
817
818   case ISD::Constant:
819     // We know we don't need to expand constants here, constants only have one
820     // value and we check that it is fine above.
821
822     // FIXME: Maybe we should handle things like targets that don't support full
823     // 32-bit immediates?
824     break;
825   case ISD::ConstantFP: {
826     // Spill FP immediates to the constant pool if the target cannot directly
827     // codegen them.  Targets often have some immediate values that can be
828     // efficiently generated into an FP register without a load.  We explicitly
829     // leave these constants as ConstantFP nodes for the target to deal with.
830     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
831
832     // Check to see if this FP immediate is already legal.
833     bool isLegal = false;
834     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
835            E = TLI.legal_fpimm_end(); I != E; ++I)
836       if (CFP->isExactlyValue(*I)) {
837         isLegal = true;
838         break;
839       }
840
841     // If this is a legal constant, turn it into a TargetConstantFP node.
842     if (isLegal) {
843       Result = DAG.getTargetConstantFP(CFP->getValue(), CFP->getValueType(0));
844       break;
845     }
846
847     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
848     default: assert(0 && "This action is not supported yet!");
849     case TargetLowering::Custom:
850       Tmp3 = TLI.LowerOperation(Result, DAG);
851       if (Tmp3.Val) {
852         Result = Tmp3;
853         break;
854       }
855       // FALLTHROUGH
856     case TargetLowering::Expand:
857       Result = ExpandConstantFP(CFP, true, DAG, TLI);
858     }
859     break;
860   }
861   case ISD::TokenFactor:
862     if (Node->getNumOperands() == 2) {
863       Tmp1 = LegalizeOp(Node->getOperand(0));
864       Tmp2 = LegalizeOp(Node->getOperand(1));
865       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
866     } else if (Node->getNumOperands() == 3) {
867       Tmp1 = LegalizeOp(Node->getOperand(0));
868       Tmp2 = LegalizeOp(Node->getOperand(1));
869       Tmp3 = LegalizeOp(Node->getOperand(2));
870       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
871     } else {
872       SmallVector<SDOperand, 8> Ops;
873       // Legalize the operands.
874       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
875         Ops.push_back(LegalizeOp(Node->getOperand(i)));
876       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
877     }
878     break;
879     
880   case ISD::FORMAL_ARGUMENTS:
881   case ISD::CALL:
882     // The only option for this is to custom lower it.
883     Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
884     assert(Tmp3.Val && "Target didn't custom lower this node!");
885     assert(Tmp3.Val->getNumValues() == Result.Val->getNumValues() &&
886            "Lowering call/formal_arguments produced unexpected # results!");
887     
888     // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
889     // remember that we legalized all of them, so it doesn't get relegalized.
890     for (unsigned i = 0, e = Tmp3.Val->getNumValues(); i != e; ++i) {
891       Tmp1 = LegalizeOp(Tmp3.getValue(i));
892       if (Op.ResNo == i)
893         Tmp2 = Tmp1;
894       AddLegalizedOperand(SDOperand(Node, i), Tmp1);
895     }
896     return Tmp2;
897         
898   case ISD::BUILD_VECTOR:
899     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
900     default: assert(0 && "This action is not supported yet!");
901     case TargetLowering::Custom:
902       Tmp3 = TLI.LowerOperation(Result, DAG);
903       if (Tmp3.Val) {
904         Result = Tmp3;
905         break;
906       }
907       // FALLTHROUGH
908     case TargetLowering::Expand:
909       Result = ExpandBUILD_VECTOR(Result.Val);
910       break;
911     }
912     break;
913   case ISD::INSERT_VECTOR_ELT:
914     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
915     Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
916     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
917     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
918     
919     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
920                                    Node->getValueType(0))) {
921     default: assert(0 && "This action is not supported yet!");
922     case TargetLowering::Legal:
923       break;
924     case TargetLowering::Custom:
925       Tmp3 = TLI.LowerOperation(Result, DAG);
926       if (Tmp3.Val) {
927         Result = Tmp3;
928         break;
929       }
930       // FALLTHROUGH
931     case TargetLowering::Expand: {
932       // If the insert index is a constant, codegen this as a scalar_to_vector,
933       // then a shuffle that inserts it into the right position in the vector.
934       if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
935         SDOperand ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, 
936                                       Tmp1.getValueType(), Tmp2);
937         
938         unsigned NumElts = MVT::getVectorNumElements(Tmp1.getValueType());
939         MVT::ValueType ShufMaskVT = MVT::getIntVectorWithNumElements(NumElts);
940         MVT::ValueType ShufMaskEltVT = MVT::getVectorBaseType(ShufMaskVT);
941         
942         // We generate a shuffle of InVec and ScVec, so the shuffle mask should
943         // be 0,1,2,3,4,5... with the appropriate element replaced with elt 0 of
944         // the RHS.
945         SmallVector<SDOperand, 8> ShufOps;
946         for (unsigned i = 0; i != NumElts; ++i) {
947           if (i != InsertPos->getValue())
948             ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
949           else
950             ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
951         }
952         SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,
953                                          &ShufOps[0], ShufOps.size());
954         
955         Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
956                              Tmp1, ScVec, ShufMask);
957         Result = LegalizeOp(Result);
958         break;
959       }
960       
961       // If the target doesn't support this, we have to spill the input vector
962       // to a temporary stack slot, update the element, then reload it.  This is
963       // badness.  We could also load the value into a vector register (either
964       // with a "move to register" or "extload into register" instruction, then
965       // permute it into place, if the idx is a constant and if the idx is
966       // supported by the target.
967       MVT::ValueType VT    = Tmp1.getValueType();
968       MVT::ValueType EltVT = Tmp2.getValueType();
969       MVT::ValueType IdxVT = Tmp3.getValueType();
970       MVT::ValueType PtrVT = TLI.getPointerTy();
971       SDOperand StackPtr = CreateStackTemporary(VT);
972       // Store the vector.
973       SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Tmp1, StackPtr, NULL, 0);
974
975       // Truncate or zero extend offset to target pointer type.
976       unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
977       Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
978       // Add the offset to the index.
979       unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
980       Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
981       SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
982       // Store the scalar value.
983       Ch = DAG.getStore(Ch, Tmp2, StackPtr2, NULL, 0);
984       // Load the updated vector.
985       Result = DAG.getLoad(VT, Ch, StackPtr, NULL, 0);
986       break;
987     }
988     }
989     break;
990   case ISD::SCALAR_TO_VECTOR:
991     if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
992       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
993       break;
994     }
995     
996     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
997     Result = DAG.UpdateNodeOperands(Result, Tmp1);
998     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
999                                    Node->getValueType(0))) {
1000     default: assert(0 && "This action is not supported yet!");
1001     case TargetLowering::Legal:
1002       break;
1003     case TargetLowering::Custom:
1004       Tmp3 = TLI.LowerOperation(Result, DAG);
1005       if (Tmp3.Val) {
1006         Result = Tmp3;
1007         break;
1008       }
1009       // FALLTHROUGH
1010     case TargetLowering::Expand:
1011       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1012       break;
1013     }
1014     break;
1015   case ISD::VECTOR_SHUFFLE:
1016     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
1017     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
1018     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1019
1020     // Allow targets to custom lower the SHUFFLEs they support.
1021     switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
1022     default: assert(0 && "Unknown operation action!");
1023     case TargetLowering::Legal:
1024       assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
1025              "vector shuffle should not be created if not legal!");
1026       break;
1027     case TargetLowering::Custom:
1028       Tmp3 = TLI.LowerOperation(Result, DAG);
1029       if (Tmp3.Val) {
1030         Result = Tmp3;
1031         break;
1032       }
1033       // FALLTHROUGH
1034     case TargetLowering::Expand: {
1035       MVT::ValueType VT = Node->getValueType(0);
1036       MVT::ValueType EltVT = MVT::getVectorBaseType(VT);
1037       MVT::ValueType PtrVT = TLI.getPointerTy();
1038       SDOperand Mask = Node->getOperand(2);
1039       unsigned NumElems = Mask.getNumOperands();
1040       SmallVector<SDOperand,8> Ops;
1041       for (unsigned i = 0; i != NumElems; ++i) {
1042         SDOperand Arg = Mask.getOperand(i);
1043         if (Arg.getOpcode() == ISD::UNDEF) {
1044           Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
1045         } else {
1046           assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1047           unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
1048           if (Idx < NumElems)
1049             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
1050                                       DAG.getConstant(Idx, PtrVT)));
1051           else
1052             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
1053                                       DAG.getConstant(Idx - NumElems, PtrVT)));
1054         }
1055       }
1056       Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1057       break;
1058     }
1059     case TargetLowering::Promote: {
1060       // Change base type to a different vector type.
1061       MVT::ValueType OVT = Node->getValueType(0);
1062       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1063
1064       // Cast the two input vectors.
1065       Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
1066       Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
1067       
1068       // Convert the shuffle mask to the right # elements.
1069       Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
1070       assert(Tmp3.Val && "Shuffle not legal?");
1071       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
1072       Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
1073       break;
1074     }
1075     }
1076     break;
1077   
1078   case ISD::EXTRACT_VECTOR_ELT:
1079     Tmp1 = LegalizeOp(Node->getOperand(0));
1080     Tmp2 = LegalizeOp(Node->getOperand(1));
1081     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1082     
1083     switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT,
1084                                    Tmp1.getValueType())) {
1085     default: assert(0 && "This action is not supported yet!");
1086     case TargetLowering::Legal:
1087       break;
1088     case TargetLowering::Custom:
1089       Tmp3 = TLI.LowerOperation(Result, DAG);
1090       if (Tmp3.Val) {
1091         Result = Tmp3;
1092         break;
1093       }
1094       // FALLTHROUGH
1095     case TargetLowering::Expand:
1096       Result = ExpandEXTRACT_VECTOR_ELT(Result);
1097       break;
1098     }
1099     break;
1100
1101   case ISD::VEXTRACT_VECTOR_ELT: 
1102     Result = LegalizeOp(LowerVEXTRACT_VECTOR_ELT(Op));
1103     break;
1104     
1105   case ISD::CALLSEQ_START: {
1106     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1107     
1108     // Recursively Legalize all of the inputs of the call end that do not lead
1109     // to this call start.  This ensures that any libcalls that need be inserted
1110     // are inserted *before* the CALLSEQ_START.
1111     {std::set<SDNode*> NodesLeadingTo;
1112     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1113       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node,
1114                                    NodesLeadingTo);
1115     }
1116
1117     // Now that we legalized all of the inputs (which may have inserted
1118     // libcalls) create the new CALLSEQ_START node.
1119     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1120
1121     // Merge in the last call, to ensure that this call start after the last
1122     // call ended.
1123     if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1124       Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1125       Tmp1 = LegalizeOp(Tmp1);
1126     }
1127       
1128     // Do not try to legalize the target-specific arguments (#1+).
1129     if (Tmp1 != Node->getOperand(0)) {
1130       SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1131       Ops[0] = Tmp1;
1132       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1133     }
1134     
1135     // Remember that the CALLSEQ_START is legalized.
1136     AddLegalizedOperand(Op.getValue(0), Result);
1137     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1138       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1139     
1140     // Now that the callseq_start and all of the non-call nodes above this call
1141     // sequence have been legalized, legalize the call itself.  During this 
1142     // process, no libcalls can/will be inserted, guaranteeing that no calls
1143     // can overlap.
1144     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1145     SDOperand InCallSEQ = LastCALLSEQ_END;
1146     // Note that we are selecting this call!
1147     LastCALLSEQ_END = SDOperand(CallEnd, 0);
1148     IsLegalizingCall = true;
1149     
1150     // Legalize the call, starting from the CALLSEQ_END.
1151     LegalizeOp(LastCALLSEQ_END);
1152     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1153     return Result;
1154   }
1155   case ISD::CALLSEQ_END:
1156     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1157     // will cause this node to be legalized as well as handling libcalls right.
1158     if (LastCALLSEQ_END.Val != Node) {
1159       LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
1160       std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
1161       assert(I != LegalizedNodes.end() &&
1162              "Legalizing the call start should have legalized this node!");
1163       return I->second;
1164     }
1165     
1166     // Otherwise, the call start has been legalized and everything is going 
1167     // according to plan.  Just legalize ourselves normally here.
1168     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1169     // Do not try to legalize the target-specific arguments (#1+), except for
1170     // an optional flag input.
1171     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1172       if (Tmp1 != Node->getOperand(0)) {
1173         SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1174         Ops[0] = Tmp1;
1175         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1176       }
1177     } else {
1178       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1179       if (Tmp1 != Node->getOperand(0) ||
1180           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1181         SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1182         Ops[0] = Tmp1;
1183         Ops.back() = Tmp2;
1184         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1185       }
1186     }
1187     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1188     // This finishes up call legalization.
1189     IsLegalizingCall = false;
1190     
1191     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1192     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1193     if (Node->getNumValues() == 2)
1194       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1195     return Result.getValue(Op.ResNo);
1196   case ISD::DYNAMIC_STACKALLOC: {
1197     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1198     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1199     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1200     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1201
1202     Tmp1 = Result.getValue(0);
1203     Tmp2 = Result.getValue(1);
1204     switch (TLI.getOperationAction(Node->getOpcode(),
1205                                    Node->getValueType(0))) {
1206     default: assert(0 && "This action is not supported yet!");
1207     case TargetLowering::Expand: {
1208       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1209       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1210              " not tell us which reg is the stack pointer!");
1211       SDOperand Chain = Tmp1.getOperand(0);
1212       SDOperand Size  = Tmp2.getOperand(1);
1213       SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, Node->getValueType(0));
1214       Tmp1 = DAG.getNode(ISD::SUB, Node->getValueType(0), SP, Size);    // Value
1215       Tmp2 = DAG.getCopyToReg(SP.getValue(1), SPReg, Tmp1);      // Output chain
1216       Tmp1 = LegalizeOp(Tmp1);
1217       Tmp2 = LegalizeOp(Tmp2);
1218       break;
1219     }
1220     case TargetLowering::Custom:
1221       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1222       if (Tmp3.Val) {
1223         Tmp1 = LegalizeOp(Tmp3);
1224         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1225       }
1226       break;
1227     case TargetLowering::Legal:
1228       break;
1229     }
1230     // Since this op produce two values, make sure to remember that we
1231     // legalized both of them.
1232     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1233     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1234     return Op.ResNo ? Tmp2 : Tmp1;
1235   }
1236   case ISD::INLINEASM: {
1237     SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1238     bool Changed = false;
1239     // Legalize all of the operands of the inline asm, in case they are nodes
1240     // that need to be expanded or something.  Note we skip the asm string and
1241     // all of the TargetConstant flags.
1242     SDOperand Op = LegalizeOp(Ops[0]);
1243     Changed = Op != Ops[0];
1244     Ops[0] = Op;
1245
1246     bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
1247     for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
1248       unsigned NumVals = cast<ConstantSDNode>(Ops[i])->getValue() >> 3;
1249       for (++i; NumVals; ++i, --NumVals) {
1250         SDOperand Op = LegalizeOp(Ops[i]);
1251         if (Op != Ops[i]) {
1252           Changed = true;
1253           Ops[i] = Op;
1254         }
1255       }
1256     }
1257
1258     if (HasInFlag) {
1259       Op = LegalizeOp(Ops.back());
1260       Changed |= Op != Ops.back();
1261       Ops.back() = Op;
1262     }
1263     
1264     if (Changed)
1265       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1266       
1267     // INLINE asm returns a chain and flag, make sure to add both to the map.
1268     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1269     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1270     return Result.getValue(Op.ResNo);
1271   }
1272   case ISD::BR:
1273     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1274     // Ensure that libcalls are emitted before a branch.
1275     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1276     Tmp1 = LegalizeOp(Tmp1);
1277     LastCALLSEQ_END = DAG.getEntryNode();
1278     
1279     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1280     break;
1281   case ISD::BRIND:
1282     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1283     // Ensure that libcalls are emitted before a branch.
1284     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1285     Tmp1 = LegalizeOp(Tmp1);
1286     LastCALLSEQ_END = DAG.getEntryNode();
1287     
1288     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1289     default: assert(0 && "Indirect target must be legal type (pointer)!");
1290     case Legal:
1291       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1292       break;
1293     }
1294     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1295     break;
1296   case ISD::BR_JT:
1297     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1298     // Ensure that libcalls are emitted before a branch.
1299     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1300     Tmp1 = LegalizeOp(Tmp1);
1301     LastCALLSEQ_END = DAG.getEntryNode();
1302
1303     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
1304     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1305
1306     switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {  
1307     default: assert(0 && "This action is not supported yet!");
1308     case TargetLowering::Legal: break;
1309     case TargetLowering::Custom:
1310       Tmp1 = TLI.LowerOperation(Result, DAG);
1311       if (Tmp1.Val) Result = Tmp1;
1312       break;
1313     case TargetLowering::Expand: {
1314       SDOperand Chain = Result.getOperand(0);
1315       SDOperand Table = Result.getOperand(1);
1316       SDOperand Index = Result.getOperand(2);
1317
1318       MVT::ValueType PTy = TLI.getPointerTy();
1319       MachineFunction &MF = DAG.getMachineFunction();
1320       unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
1321       Index= DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(EntrySize, PTy));
1322       SDOperand Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
1323       
1324       SDOperand LD;
1325       switch (EntrySize) {
1326       default: assert(0 && "Size of jump table not supported yet."); break;
1327       case 4: LD = DAG.getLoad(MVT::i32, Chain, Addr, NULL, 0); break;
1328       case 8: LD = DAG.getLoad(MVT::i64, Chain, Addr, NULL, 0); break;
1329       }
1330
1331       if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1332         // For PIC, the sequence is:
1333         // BRIND(load(Jumptable + index) + RelocBase)
1334         // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
1335         SDOperand Reloc;
1336         if (TLI.usesGlobalOffsetTable())
1337           Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
1338         else
1339           Reloc = Table;
1340         Addr = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
1341         Addr = DAG.getNode(ISD::ADD, PTy, Addr, Reloc);
1342         Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), Addr);
1343       } else {
1344         Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD);
1345       }
1346     }
1347     }
1348     break;
1349   case ISD::BRCOND:
1350     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1351     // Ensure that libcalls are emitted before a return.
1352     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1353     Tmp1 = LegalizeOp(Tmp1);
1354     LastCALLSEQ_END = DAG.getEntryNode();
1355
1356     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1357     case Expand: assert(0 && "It's impossible to expand bools");
1358     case Legal:
1359       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1360       break;
1361     case Promote:
1362       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1363       
1364       // The top bits of the promoted condition are not necessarily zero, ensure
1365       // that the value is properly zero extended.
1366       if (!TLI.MaskedValueIsZero(Tmp2, 
1367                                  MVT::getIntVTBitMask(Tmp2.getValueType())^1))
1368         Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1369       break;
1370     }
1371
1372     // Basic block destination (Op#2) is always legal.
1373     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1374       
1375     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
1376     default: assert(0 && "This action is not supported yet!");
1377     case TargetLowering::Legal: break;
1378     case TargetLowering::Custom:
1379       Tmp1 = TLI.LowerOperation(Result, DAG);
1380       if (Tmp1.Val) Result = Tmp1;
1381       break;
1382     case TargetLowering::Expand:
1383       // Expand brcond's setcc into its constituent parts and create a BR_CC
1384       // Node.
1385       if (Tmp2.getOpcode() == ISD::SETCC) {
1386         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1387                              Tmp2.getOperand(0), Tmp2.getOperand(1),
1388                              Node->getOperand(2));
1389       } else {
1390         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
1391                              DAG.getCondCode(ISD::SETNE), Tmp2,
1392                              DAG.getConstant(0, Tmp2.getValueType()),
1393                              Node->getOperand(2));
1394       }
1395       break;
1396     }
1397     break;
1398   case ISD::BR_CC:
1399     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1400     // Ensure that libcalls are emitted before a branch.
1401     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1402     Tmp1 = LegalizeOp(Tmp1);
1403     Tmp2 = Node->getOperand(2);              // LHS 
1404     Tmp3 = Node->getOperand(3);              // RHS
1405     Tmp4 = Node->getOperand(1);              // CC
1406
1407     LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1408     LastCALLSEQ_END = DAG.getEntryNode();
1409
1410     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1411     // the LHS is a legal SETCC itself.  In this case, we need to compare
1412     // the result against zero to select between true and false values.
1413     if (Tmp3.Val == 0) {
1414       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1415       Tmp4 = DAG.getCondCode(ISD::SETNE);
1416     }
1417     
1418     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3, 
1419                                     Node->getOperand(4));
1420       
1421     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1422     default: assert(0 && "Unexpected action for BR_CC!");
1423     case TargetLowering::Legal: break;
1424     case TargetLowering::Custom:
1425       Tmp4 = TLI.LowerOperation(Result, DAG);
1426       if (Tmp4.Val) Result = Tmp4;
1427       break;
1428     }
1429     break;
1430   case ISD::LOAD: {
1431     LoadSDNode *LD = cast<LoadSDNode>(Node);
1432     Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1433     Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1434
1435     ISD::LoadExtType ExtType = LD->getExtensionType();
1436     if (ExtType == ISD::NON_EXTLOAD) {
1437       MVT::ValueType VT = Node->getValueType(0);
1438       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1439       Tmp3 = Result.getValue(0);
1440       Tmp4 = Result.getValue(1);
1441     
1442       switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1443       default: assert(0 && "This action is not supported yet!");
1444       case TargetLowering::Legal: break;
1445       case TargetLowering::Custom:
1446         Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1447         if (Tmp1.Val) {
1448           Tmp3 = LegalizeOp(Tmp1);
1449           Tmp4 = LegalizeOp(Tmp1.getValue(1));
1450         }
1451         break;
1452       case TargetLowering::Promote: {
1453         // Only promote a load of vector type to another.
1454         assert(MVT::isVector(VT) && "Cannot promote this load!");
1455         // Change base type to a different vector type.
1456         MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1457
1458         Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, LD->getSrcValue(),
1459                            LD->getSrcValueOffset());
1460         Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
1461         Tmp4 = LegalizeOp(Tmp1.getValue(1));
1462         break;
1463       }
1464       }
1465       // Since loads produce two values, make sure to remember that we 
1466       // legalized both of them.
1467       AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
1468       AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
1469       return Op.ResNo ? Tmp4 : Tmp3;
1470     } else {
1471       MVT::ValueType SrcVT = LD->getLoadedVT();
1472       switch (TLI.getLoadXAction(ExtType, SrcVT)) {
1473       default: assert(0 && "This action is not supported yet!");
1474       case TargetLowering::Promote:
1475         assert(SrcVT == MVT::i1 &&
1476                "Can only promote extending LOAD from i1 -> i8!");
1477         Result = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
1478                                 LD->getSrcValue(), LD->getSrcValueOffset(),
1479                                 MVT::i8);
1480       Tmp1 = Result.getValue(0);
1481       Tmp2 = Result.getValue(1);
1482       break;
1483       case TargetLowering::Custom:
1484         isCustom = true;
1485         // FALLTHROUGH
1486       case TargetLowering::Legal:
1487         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1488         Tmp1 = Result.getValue(0);
1489         Tmp2 = Result.getValue(1);
1490       
1491         if (isCustom) {
1492           Tmp3 = TLI.LowerOperation(Result, DAG);
1493           if (Tmp3.Val) {
1494             Tmp1 = LegalizeOp(Tmp3);
1495             Tmp2 = LegalizeOp(Tmp3.getValue(1));
1496           }
1497         }
1498         break;
1499       case TargetLowering::Expand:
1500         // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1501         if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1502           SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, LD->getSrcValue(),
1503                                        LD->getSrcValueOffset());
1504           Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1505           Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1506           Tmp2 = LegalizeOp(Load.getValue(1));
1507           break;
1508         }
1509         assert(ExtType != ISD::EXTLOAD && "EXTLOAD should always be supported!");
1510         // Turn the unsupported load into an EXTLOAD followed by an explicit
1511         // zero/sign extend inreg.
1512         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1513                                 Tmp1, Tmp2, LD->getSrcValue(),
1514                                 LD->getSrcValueOffset(), SrcVT);
1515         SDOperand ValRes;
1516         if (ExtType == ISD::SEXTLOAD)
1517           ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1518                                Result, DAG.getValueType(SrcVT));
1519         else
1520           ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1521         Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1522         Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1523         break;
1524       }
1525       // Since loads produce two values, make sure to remember that we legalized
1526       // both of them.
1527       AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1528       AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1529       return Op.ResNo ? Tmp2 : Tmp1;
1530     }
1531   }
1532   case ISD::EXTRACT_ELEMENT: {
1533     MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1534     switch (getTypeAction(OpTy)) {
1535     default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1536     case Legal:
1537       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1538         // 1 -> Hi
1539         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1540                              DAG.getConstant(MVT::getSizeInBits(OpTy)/2, 
1541                                              TLI.getShiftAmountTy()));
1542         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1543       } else {
1544         // 0 -> Lo
1545         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
1546                              Node->getOperand(0));
1547       }
1548       break;
1549     case Expand:
1550       // Get both the low and high parts.
1551       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1552       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1553         Result = Tmp2;  // 1 -> Hi
1554       else
1555         Result = Tmp1;  // 0 -> Lo
1556       break;
1557     }
1558     break;
1559   }
1560
1561   case ISD::CopyToReg:
1562     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1563
1564     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1565            "Register type must be legal!");
1566     // Legalize the incoming value (must be a legal type).
1567     Tmp2 = LegalizeOp(Node->getOperand(2));
1568     if (Node->getNumValues() == 1) {
1569       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
1570     } else {
1571       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1572       if (Node->getNumOperands() == 4) {
1573         Tmp3 = LegalizeOp(Node->getOperand(3));
1574         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
1575                                         Tmp3);
1576       } else {
1577         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1578       }
1579       
1580       // Since this produces two values, make sure to remember that we legalized
1581       // both of them.
1582       AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1583       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1584       return Result;
1585     }
1586     break;
1587
1588   case ISD::RET:
1589     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1590
1591     // Ensure that libcalls are emitted before a return.
1592     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1593     Tmp1 = LegalizeOp(Tmp1);
1594     LastCALLSEQ_END = DAG.getEntryNode();
1595       
1596     switch (Node->getNumOperands()) {
1597     case 3:  // ret val
1598       Tmp2 = Node->getOperand(1);
1599       Tmp3 = Node->getOperand(2);  // Signness
1600       switch (getTypeAction(Tmp2.getValueType())) {
1601       case Legal:
1602         Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
1603         break;
1604       case Expand:
1605         if (Tmp2.getValueType() != MVT::Vector) {
1606           SDOperand Lo, Hi;
1607           ExpandOp(Tmp2, Lo, Hi);
1608           if (Hi.Val)
1609             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
1610           else
1611             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3);
1612           Result = LegalizeOp(Result);
1613         } else {
1614           SDNode *InVal = Tmp2.Val;
1615           unsigned NumElems =
1616             cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1617           MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1618           
1619           // Figure out if there is a Packed type corresponding to this Vector
1620           // type.  If so, convert to the packed type.
1621           MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1622           if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1623             // Turn this into a return of the packed type.
1624             Tmp2 = PackVectorOp(Tmp2, TVT);
1625             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1626           } else if (NumElems == 1) {
1627             // Turn this into a return of the scalar type.
1628             Tmp2 = PackVectorOp(Tmp2, EVT);
1629             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1630             
1631             // FIXME: Returns of gcc generic vectors smaller than a legal type
1632             // should be returned in integer registers!
1633             
1634             // The scalarized value type may not be legal, e.g. it might require
1635             // promotion or expansion.  Relegalize the return.
1636             Result = LegalizeOp(Result);
1637           } else {
1638             // FIXME: Returns of gcc generic vectors larger than a legal vector
1639             // type should be returned by reference!
1640             SDOperand Lo, Hi;
1641             SplitVectorOp(Tmp2, Lo, Hi);
1642             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi, Tmp3);
1643             Result = LegalizeOp(Result);
1644           }
1645         }
1646         break;
1647       case Promote:
1648         Tmp2 = PromoteOp(Node->getOperand(1));
1649         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1650         Result = LegalizeOp(Result);
1651         break;
1652       }
1653       break;
1654     case 1:  // ret void
1655       Result = DAG.UpdateNodeOperands(Result, Tmp1);
1656       break;
1657     default: { // ret <values>
1658       SmallVector<SDOperand, 8> NewValues;
1659       NewValues.push_back(Tmp1);
1660       for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
1661         switch (getTypeAction(Node->getOperand(i).getValueType())) {
1662         case Legal:
1663           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1664           NewValues.push_back(Node->getOperand(i+1));
1665           break;
1666         case Expand: {
1667           SDOperand Lo, Hi;
1668           assert(Node->getOperand(i).getValueType() != MVT::Vector &&
1669                  "FIXME: TODO: implement returning non-legal vector types!");
1670           ExpandOp(Node->getOperand(i), Lo, Hi);
1671           NewValues.push_back(Lo);
1672           NewValues.push_back(Node->getOperand(i+1));
1673           if (Hi.Val) {
1674             NewValues.push_back(Hi);
1675             NewValues.push_back(Node->getOperand(i+1));
1676           }
1677           break;
1678         }
1679         case Promote:
1680           assert(0 && "Can't promote multiple return value yet!");
1681         }
1682           
1683       if (NewValues.size() == Node->getNumOperands())
1684         Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
1685       else
1686         Result = DAG.getNode(ISD::RET, MVT::Other,
1687                              &NewValues[0], NewValues.size());
1688       break;
1689     }
1690     }
1691
1692     if (Result.getOpcode() == ISD::RET) {
1693       switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
1694       default: assert(0 && "This action is not supported yet!");
1695       case TargetLowering::Legal: break;
1696       case TargetLowering::Custom:
1697         Tmp1 = TLI.LowerOperation(Result, DAG);
1698         if (Tmp1.Val) Result = Tmp1;
1699         break;
1700       }
1701     }
1702     break;
1703   case ISD::STORE: {
1704     StoreSDNode *ST = cast<StoreSDNode>(Node);
1705     Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
1706     Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
1707
1708     if (!ST->isTruncatingStore()) {
1709       // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1710       // FIXME: We shouldn't do this for TargetConstantFP's.
1711       // FIXME: move this to the DAG Combiner!  Note that we can't regress due
1712       // to phase ordering between legalized code and the dag combiner.  This
1713       // probably means that we need to integrate dag combiner and legalizer
1714       // together.
1715       if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
1716         if (CFP->getValueType(0) == MVT::f32) {
1717           Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
1718         } else {
1719           assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1720           Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
1721         }
1722         Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1723                               ST->getSrcValueOffset());
1724         break;
1725       }
1726       
1727       switch (getTypeAction(ST->getStoredVT())) {
1728       case Legal: {
1729         Tmp3 = LegalizeOp(ST->getValue());
1730         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1731                                         ST->getOffset());
1732
1733         MVT::ValueType VT = Tmp3.getValueType();
1734         switch (TLI.getOperationAction(ISD::STORE, VT)) {
1735         default: assert(0 && "This action is not supported yet!");
1736         case TargetLowering::Legal:  break;
1737         case TargetLowering::Custom:
1738           Tmp1 = TLI.LowerOperation(Result, DAG);
1739           if (Tmp1.Val) Result = Tmp1;
1740           break;
1741         case TargetLowering::Promote:
1742           assert(MVT::isVector(VT) && "Unknown legal promote case!");
1743           Tmp3 = DAG.getNode(ISD::BIT_CONVERT, 
1744                              TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1745           Result = DAG.getStore(Tmp1, Tmp3, Tmp2,
1746                                 ST->getSrcValue(), ST->getSrcValueOffset());
1747           break;
1748         }
1749         break;
1750       }
1751       case Promote:
1752         // Truncate the value and store the result.
1753         Tmp3 = PromoteOp(ST->getValue());
1754         Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1755                                    ST->getSrcValueOffset(), ST->getStoredVT());
1756         break;
1757
1758       case Expand:
1759         unsigned IncrementSize = 0;
1760         SDOperand Lo, Hi;
1761       
1762         // If this is a vector type, then we have to calculate the increment as
1763         // the product of the element size in bytes, and the number of elements
1764         // in the high half of the vector.
1765         if (ST->getValue().getValueType() == MVT::Vector) {
1766           SDNode *InVal = ST->getValue().Val;
1767           unsigned NumElems =
1768             cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1769           MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1770
1771           // Figure out if there is a Packed type corresponding to this Vector
1772           // type.  If so, convert to the packed type.
1773           MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1774           if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1775             // Turn this into a normal store of the packed type.
1776             Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
1777             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1778                                   ST->getSrcValueOffset());
1779             Result = LegalizeOp(Result);
1780             break;
1781           } else if (NumElems == 1) {
1782             // Turn this into a normal store of the scalar type.
1783             Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
1784             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1785                                   ST->getSrcValueOffset());
1786             // The scalarized value type may not be legal, e.g. it might require
1787             // promotion or expansion.  Relegalize the scalar store.
1788             Result = LegalizeOp(Result);
1789             break;
1790           } else {
1791             SplitVectorOp(Node->getOperand(1), Lo, Hi);
1792             IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1793           }
1794         } else {
1795           ExpandOp(Node->getOperand(1), Lo, Hi);
1796           IncrementSize = Hi.Val ? MVT::getSizeInBits(Hi.getValueType())/8 : 0;
1797
1798           if (!TLI.isLittleEndian())
1799             std::swap(Lo, Hi);
1800         }
1801
1802         Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
1803                           ST->getSrcValueOffset());
1804
1805         if (Hi.Val == NULL) {
1806           // Must be int <-> float one-to-one expansion.
1807           Result = Lo;
1808           break;
1809         }
1810
1811         Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1812                            getIntPtrConstant(IncrementSize));
1813         assert(isTypeLegal(Tmp2.getValueType()) &&
1814                "Pointers must be legal!");
1815         // FIXME: This sets the srcvalue of both halves to be the same, which is
1816         // wrong.
1817         Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
1818                           ST->getSrcValueOffset());
1819         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1820         break;
1821       }
1822     } else {
1823       // Truncating store
1824       assert(isTypeLegal(ST->getValue().getValueType()) &&
1825              "Cannot handle illegal TRUNCSTORE yet!");
1826       Tmp3 = LegalizeOp(ST->getValue());
1827     
1828       // The only promote case we handle is TRUNCSTORE:i1 X into
1829       //   -> TRUNCSTORE:i8 (and X, 1)
1830       if (ST->getStoredVT() == MVT::i1 &&
1831           TLI.getStoreXAction(MVT::i1) == TargetLowering::Promote) {
1832         // Promote the bool to a mask then store.
1833         Tmp3 = DAG.getNode(ISD::AND, Tmp3.getValueType(), Tmp3,
1834                            DAG.getConstant(1, Tmp3.getValueType()));
1835         Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1836                                    ST->getSrcValueOffset(), MVT::i8);
1837       } else if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1838                  Tmp2 != ST->getBasePtr()) {
1839         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1840                                         ST->getOffset());
1841       }
1842
1843       MVT::ValueType StVT = cast<StoreSDNode>(Result.Val)->getStoredVT();
1844       switch (TLI.getStoreXAction(StVT)) {
1845       default: assert(0 && "This action is not supported yet!");
1846       case TargetLowering::Legal: break;
1847       case TargetLowering::Custom:
1848         Tmp1 = TLI.LowerOperation(Result, DAG);
1849         if (Tmp1.Val) Result = Tmp1;
1850         break;
1851       }
1852     }
1853     break;
1854   }
1855   case ISD::PCMARKER:
1856     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1857     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1858     break;
1859   case ISD::STACKSAVE:
1860     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1861     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1862     Tmp1 = Result.getValue(0);
1863     Tmp2 = Result.getValue(1);
1864     
1865     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
1866     default: assert(0 && "This action is not supported yet!");
1867     case TargetLowering::Legal: break;
1868     case TargetLowering::Custom:
1869       Tmp3 = TLI.LowerOperation(Result, DAG);
1870       if (Tmp3.Val) {
1871         Tmp1 = LegalizeOp(Tmp3);
1872         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1873       }
1874       break;
1875     case TargetLowering::Expand:
1876       // Expand to CopyFromReg if the target set 
1877       // StackPointerRegisterToSaveRestore.
1878       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1879         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
1880                                   Node->getValueType(0));
1881         Tmp2 = Tmp1.getValue(1);
1882       } else {
1883         Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
1884         Tmp2 = Node->getOperand(0);
1885       }
1886       break;
1887     }
1888
1889     // Since stacksave produce two values, make sure to remember that we
1890     // legalized both of them.
1891     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1892     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1893     return Op.ResNo ? Tmp2 : Tmp1;
1894
1895   case ISD::STACKRESTORE:
1896     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1897     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1898     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1899       
1900     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
1901     default: assert(0 && "This action is not supported yet!");
1902     case TargetLowering::Legal: break;
1903     case TargetLowering::Custom:
1904       Tmp1 = TLI.LowerOperation(Result, DAG);
1905       if (Tmp1.Val) Result = Tmp1;
1906       break;
1907     case TargetLowering::Expand:
1908       // Expand to CopyToReg if the target set 
1909       // StackPointerRegisterToSaveRestore.
1910       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1911         Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
1912       } else {
1913         Result = Tmp1;
1914       }
1915       break;
1916     }
1917     break;
1918
1919   case ISD::READCYCLECOUNTER:
1920     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1921     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1922     switch (TLI.getOperationAction(ISD::READCYCLECOUNTER,
1923                                    Node->getValueType(0))) {
1924     default: assert(0 && "This action is not supported yet!");
1925     case TargetLowering::Legal:
1926       Tmp1 = Result.getValue(0);
1927       Tmp2 = Result.getValue(1);
1928       break;
1929     case TargetLowering::Custom:
1930       Result = TLI.LowerOperation(Result, DAG);
1931       Tmp1 = LegalizeOp(Result.getValue(0));
1932       Tmp2 = LegalizeOp(Result.getValue(1));
1933       break;
1934     }
1935
1936     // Since rdcc produce two values, make sure to remember that we legalized
1937     // both of them.
1938     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1939     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1940     return Result;
1941
1942   case ISD::SELECT:
1943     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1944     case Expand: assert(0 && "It's impossible to expand bools");
1945     case Legal:
1946       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1947       break;
1948     case Promote:
1949       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1950       // Make sure the condition is either zero or one.
1951       if (!TLI.MaskedValueIsZero(Tmp1,
1952                                  MVT::getIntVTBitMask(Tmp1.getValueType())^1))
1953         Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1954       break;
1955     }
1956     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1957     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1958
1959     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1960       
1961     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1962     default: assert(0 && "This action is not supported yet!");
1963     case TargetLowering::Legal: break;
1964     case TargetLowering::Custom: {
1965       Tmp1 = TLI.LowerOperation(Result, DAG);
1966       if (Tmp1.Val) Result = Tmp1;
1967       break;
1968     }
1969     case TargetLowering::Expand:
1970       if (Tmp1.getOpcode() == ISD::SETCC) {
1971         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
1972                               Tmp2, Tmp3,
1973                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1974       } else {
1975         Result = DAG.getSelectCC(Tmp1, 
1976                                  DAG.getConstant(0, Tmp1.getValueType()),
1977                                  Tmp2, Tmp3, ISD::SETNE);
1978       }
1979       break;
1980     case TargetLowering::Promote: {
1981       MVT::ValueType NVT =
1982         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1983       unsigned ExtOp, TruncOp;
1984       if (MVT::isVector(Tmp2.getValueType())) {
1985         ExtOp   = ISD::BIT_CONVERT;
1986         TruncOp = ISD::BIT_CONVERT;
1987       } else if (MVT::isInteger(Tmp2.getValueType())) {
1988         ExtOp   = ISD::ANY_EXTEND;
1989         TruncOp = ISD::TRUNCATE;
1990       } else {
1991         ExtOp   = ISD::FP_EXTEND;
1992         TruncOp = ISD::FP_ROUND;
1993       }
1994       // Promote each of the values to the new type.
1995       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1996       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1997       // Perform the larger operation, then round down.
1998       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1999       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
2000       break;
2001     }
2002     }
2003     break;
2004   case ISD::SELECT_CC: {
2005     Tmp1 = Node->getOperand(0);               // LHS
2006     Tmp2 = Node->getOperand(1);               // RHS
2007     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
2008     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
2009     SDOperand CC = Node->getOperand(4);
2010     
2011     LegalizeSetCCOperands(Tmp1, Tmp2, CC);
2012     
2013     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
2014     // the LHS is a legal SETCC itself.  In this case, we need to compare
2015     // the result against zero to select between true and false values.
2016     if (Tmp2.Val == 0) {
2017       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
2018       CC = DAG.getCondCode(ISD::SETNE);
2019     }
2020     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
2021
2022     // Everything is legal, see if we should expand this op or something.
2023     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
2024     default: assert(0 && "This action is not supported yet!");
2025     case TargetLowering::Legal: break;
2026     case TargetLowering::Custom:
2027       Tmp1 = TLI.LowerOperation(Result, DAG);
2028       if (Tmp1.Val) Result = Tmp1;
2029       break;
2030     }
2031     break;
2032   }
2033   case ISD::SETCC:
2034     Tmp1 = Node->getOperand(0);
2035     Tmp2 = Node->getOperand(1);
2036     Tmp3 = Node->getOperand(2);
2037     LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
2038     
2039     // If we had to Expand the SetCC operands into a SELECT node, then it may 
2040     // not always be possible to return a true LHS & RHS.  In this case, just 
2041     // return the value we legalized, returned in the LHS
2042     if (Tmp2.Val == 0) {
2043       Result = Tmp1;
2044       break;
2045     }
2046
2047     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
2048     default: assert(0 && "Cannot handle this action for SETCC yet!");
2049     case TargetLowering::Custom:
2050       isCustom = true;
2051       // FALLTHROUGH.
2052     case TargetLowering::Legal:
2053       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2054       if (isCustom) {
2055         Tmp4 = TLI.LowerOperation(Result, DAG);
2056         if (Tmp4.Val) Result = Tmp4;
2057       }
2058       break;
2059     case TargetLowering::Promote: {
2060       // First step, figure out the appropriate operation to use.
2061       // Allow SETCC to not be supported for all legal data types
2062       // Mostly this targets FP
2063       MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
2064       MVT::ValueType OldVT = NewInTy;
2065
2066       // Scan for the appropriate larger type to use.
2067       while (1) {
2068         NewInTy = (MVT::ValueType)(NewInTy+1);
2069
2070         assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
2071                "Fell off of the edge of the integer world");
2072         assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
2073                "Fell off of the edge of the floating point world");
2074           
2075         // If the target supports SETCC of this type, use it.
2076         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
2077           break;
2078       }
2079       if (MVT::isInteger(NewInTy))
2080         assert(0 && "Cannot promote Legal Integer SETCC yet");
2081       else {
2082         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
2083         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
2084       }
2085       Tmp1 = LegalizeOp(Tmp1);
2086       Tmp2 = LegalizeOp(Tmp2);
2087       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2088       Result = LegalizeOp(Result);
2089       break;
2090     }
2091     case TargetLowering::Expand:
2092       // Expand a setcc node into a select_cc of the same condition, lhs, and
2093       // rhs that selects between const 1 (true) and const 0 (false).
2094       MVT::ValueType VT = Node->getValueType(0);
2095       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
2096                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2097                            Tmp3);
2098       break;
2099     }
2100     break;
2101   case ISD::MEMSET:
2102   case ISD::MEMCPY:
2103   case ISD::MEMMOVE: {
2104     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
2105     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
2106
2107     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
2108       switch (getTypeAction(Node->getOperand(2).getValueType())) {
2109       case Expand: assert(0 && "Cannot expand a byte!");
2110       case Legal:
2111         Tmp3 = LegalizeOp(Node->getOperand(2));
2112         break;
2113       case Promote:
2114         Tmp3 = PromoteOp(Node->getOperand(2));
2115         break;
2116       }
2117     } else {
2118       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
2119     }
2120
2121     SDOperand Tmp4;
2122     switch (getTypeAction(Node->getOperand(3).getValueType())) {
2123     case Expand: {
2124       // Length is too big, just take the lo-part of the length.
2125       SDOperand HiPart;
2126       ExpandOp(Node->getOperand(3), Tmp4, HiPart);
2127       break;
2128     }
2129     case Legal:
2130       Tmp4 = LegalizeOp(Node->getOperand(3));
2131       break;
2132     case Promote:
2133       Tmp4 = PromoteOp(Node->getOperand(3));
2134       break;
2135     }
2136
2137     SDOperand Tmp5;
2138     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
2139     case Expand: assert(0 && "Cannot expand this yet!");
2140     case Legal:
2141       Tmp5 = LegalizeOp(Node->getOperand(4));
2142       break;
2143     case Promote:
2144       Tmp5 = PromoteOp(Node->getOperand(4));
2145       break;
2146     }
2147
2148     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2149     default: assert(0 && "This action not implemented for this operation!");
2150     case TargetLowering::Custom:
2151       isCustom = true;
2152       // FALLTHROUGH
2153     case TargetLowering::Legal:
2154       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, Tmp5);
2155       if (isCustom) {
2156         Tmp1 = TLI.LowerOperation(Result, DAG);
2157         if (Tmp1.Val) Result = Tmp1;
2158       }
2159       break;
2160     case TargetLowering::Expand: {
2161       // Otherwise, the target does not support this operation.  Lower the
2162       // operation to an explicit libcall as appropriate.
2163       MVT::ValueType IntPtr = TLI.getPointerTy();
2164       const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2165       TargetLowering::ArgListTy Args;
2166       TargetLowering::ArgListEntry Entry;
2167
2168       const char *FnName = 0;
2169       if (Node->getOpcode() == ISD::MEMSET) {
2170         Entry.Node = Tmp2; Entry.isSigned = false; Entry.Ty = IntPtrTy;
2171         Args.push_back(Entry);
2172         // Extend the (previously legalized) ubyte argument to be an int value
2173         // for the call.
2174         if (Tmp3.getValueType() > MVT::i32)
2175           Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
2176         else
2177           Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
2178         Entry.Node = Tmp3; Entry.Ty = Type::Int32Ty; Entry.isSigned = true;
2179         Args.push_back(Entry);
2180         Entry.Node = Tmp4; Entry.Ty = IntPtrTy; Entry.isSigned = false;
2181         Args.push_back(Entry);
2182
2183         FnName = "memset";
2184       } else if (Node->getOpcode() == ISD::MEMCPY ||
2185                  Node->getOpcode() == ISD::MEMMOVE) {
2186         Entry.Ty = IntPtrTy; Entry.isSigned = false;
2187         Entry.Node = Tmp2; Args.push_back(Entry);
2188         Entry.Node = Tmp3; Args.push_back(Entry);
2189         Entry.Node = Tmp4; Args.push_back(Entry);
2190         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
2191       } else {
2192         assert(0 && "Unknown op!");
2193       }
2194
2195       std::pair<SDOperand,SDOperand> CallResult =
2196         TLI.LowerCallTo(Tmp1, Type::VoidTy, false, false, CallingConv::C, false,
2197                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
2198       Result = CallResult.second;
2199       break;
2200     }
2201     }
2202     break;
2203   }
2204
2205   case ISD::SHL_PARTS:
2206   case ISD::SRA_PARTS:
2207   case ISD::SRL_PARTS: {
2208     SmallVector<SDOperand, 8> Ops;
2209     bool Changed = false;
2210     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2211       Ops.push_back(LegalizeOp(Node->getOperand(i)));
2212       Changed |= Ops.back() != Node->getOperand(i);
2213     }
2214     if (Changed)
2215       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
2216
2217     switch (TLI.getOperationAction(Node->getOpcode(),
2218                                    Node->getValueType(0))) {
2219     default: assert(0 && "This action is not supported yet!");
2220     case TargetLowering::Legal: break;
2221     case TargetLowering::Custom:
2222       Tmp1 = TLI.LowerOperation(Result, DAG);
2223       if (Tmp1.Val) {
2224         SDOperand Tmp2, RetVal(0, 0);
2225         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
2226           Tmp2 = LegalizeOp(Tmp1.getValue(i));
2227           AddLegalizedOperand(SDOperand(Node, i), Tmp2);
2228           if (i == Op.ResNo)
2229             RetVal = Tmp2;
2230         }
2231         assert(RetVal.Val && "Illegal result number");
2232         return RetVal;
2233       }
2234       break;
2235     }
2236
2237     // Since these produce multiple values, make sure to remember that we
2238     // legalized all of them.
2239     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2240       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
2241     return Result.getValue(Op.ResNo);
2242   }
2243
2244     // Binary operators
2245   case ISD::ADD:
2246   case ISD::SUB:
2247   case ISD::MUL:
2248   case ISD::MULHS:
2249   case ISD::MULHU:
2250   case ISD::UDIV:
2251   case ISD::SDIV:
2252   case ISD::AND:
2253   case ISD::OR:
2254   case ISD::XOR:
2255   case ISD::SHL:
2256   case ISD::SRL:
2257   case ISD::SRA:
2258   case ISD::FADD:
2259   case ISD::FSUB:
2260   case ISD::FMUL:
2261   case ISD::FDIV:
2262     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2263     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2264     case Expand: assert(0 && "Not possible");
2265     case Legal:
2266       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2267       break;
2268     case Promote:
2269       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2270       break;
2271     }
2272     
2273     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2274       
2275     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2276     default: assert(0 && "BinOp legalize operation not supported");
2277     case TargetLowering::Legal: break;
2278     case TargetLowering::Custom:
2279       Tmp1 = TLI.LowerOperation(Result, DAG);
2280       if (Tmp1.Val) Result = Tmp1;
2281       break;
2282     case TargetLowering::Expand: {
2283       if (Node->getValueType(0) == MVT::i32) {
2284         switch (Node->getOpcode()) {
2285         default:  assert(0 && "Do not know how to expand this integer BinOp!");
2286         case ISD::UDIV:
2287         case ISD::SDIV:
2288           RTLIB::Libcall LC = Node->getOpcode() == ISD::UDIV
2289             ? RTLIB::UDIV_I32 : RTLIB::SDIV_I32;
2290           SDOperand Dummy;
2291           bool isSigned = Node->getOpcode() == ISD::SDIV;
2292           Result = ExpandLibCall(TLI.getLibcallName(LC), Node, isSigned, Dummy);
2293         };
2294         break;
2295       }
2296
2297       assert(MVT::isVector(Node->getValueType(0)) &&
2298              "Cannot expand this binary operator!");
2299       // Expand the operation into a bunch of nasty scalar code.
2300       SmallVector<SDOperand, 8> Ops;
2301       MVT::ValueType EltVT = MVT::getVectorBaseType(Node->getValueType(0));
2302       MVT::ValueType PtrVT = TLI.getPointerTy();
2303       for (unsigned i = 0, e = MVT::getVectorNumElements(Node->getValueType(0));
2304            i != e; ++i) {
2305         SDOperand Idx = DAG.getConstant(i, PtrVT);
2306         SDOperand LHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1, Idx);
2307         SDOperand RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2, Idx);
2308         Ops.push_back(DAG.getNode(Node->getOpcode(), EltVT, LHS, RHS));
2309       }
2310       Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), 
2311                            &Ops[0], Ops.size());
2312       break;
2313     }
2314     case TargetLowering::Promote: {
2315       switch (Node->getOpcode()) {
2316       default:  assert(0 && "Do not know how to promote this BinOp!");
2317       case ISD::AND:
2318       case ISD::OR:
2319       case ISD::XOR: {
2320         MVT::ValueType OVT = Node->getValueType(0);
2321         MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2322         assert(MVT::isVector(OVT) && "Cannot promote this BinOp!");
2323         // Bit convert each of the values to the new type.
2324         Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
2325         Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
2326         Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2327         // Bit convert the result back the original type.
2328         Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
2329         break;
2330       }
2331       }
2332     }
2333     }
2334     break;
2335     
2336   case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
2337     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2338     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2339       case Expand: assert(0 && "Not possible");
2340       case Legal:
2341         Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2342         break;
2343       case Promote:
2344         Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2345         break;
2346     }
2347       
2348     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2349     
2350     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2351     default: assert(0 && "Operation not supported");
2352     case TargetLowering::Custom:
2353       Tmp1 = TLI.LowerOperation(Result, DAG);
2354       if (Tmp1.Val) Result = Tmp1;
2355       break;
2356     case TargetLowering::Legal: break;
2357     case TargetLowering::Expand: {
2358       // If this target supports fabs/fneg natively and select is cheap,
2359       // do this efficiently.
2360       if (!TLI.isSelectExpensive() &&
2361           TLI.getOperationAction(ISD::FABS, Tmp1.getValueType()) ==
2362           TargetLowering::Legal &&
2363           TLI.getOperationAction(ISD::FNEG, Tmp1.getValueType()) ==
2364           TargetLowering::Legal) {
2365         // Get the sign bit of the RHS.
2366         MVT::ValueType IVT = 
2367           Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
2368         SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
2369         SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
2370                                SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
2371         // Get the absolute value of the result.
2372         SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
2373         // Select between the nabs and abs value based on the sign bit of
2374         // the input.
2375         Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
2376                              DAG.getNode(ISD::FNEG, AbsVal.getValueType(), 
2377                                          AbsVal),
2378                              AbsVal);
2379         Result = LegalizeOp(Result);
2380         break;
2381       }
2382       
2383       // Otherwise, do bitwise ops!
2384       MVT::ValueType NVT = 
2385         Node->getValueType(0) == MVT::f32 ? MVT::i32 : MVT::i64;
2386       Result = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
2387       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), Result);
2388       Result = LegalizeOp(Result);
2389       break;
2390     }
2391     }
2392     break;
2393     
2394   case ISD::ADDC:
2395   case ISD::SUBC:
2396     Tmp1 = LegalizeOp(Node->getOperand(0));
2397     Tmp2 = LegalizeOp(Node->getOperand(1));
2398     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2399     // Since this produces two values, make sure to remember that we legalized
2400     // both of them.
2401     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2402     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2403     return Result;
2404
2405   case ISD::ADDE:
2406   case ISD::SUBE:
2407     Tmp1 = LegalizeOp(Node->getOperand(0));
2408     Tmp2 = LegalizeOp(Node->getOperand(1));
2409     Tmp3 = LegalizeOp(Node->getOperand(2));
2410     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2411     // Since this produces two values, make sure to remember that we legalized
2412     // both of them.
2413     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2414     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2415     return Result;
2416     
2417   case ISD::BUILD_PAIR: {
2418     MVT::ValueType PairTy = Node->getValueType(0);
2419     // TODO: handle the case where the Lo and Hi operands are not of legal type
2420     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2421     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2422     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2423     case TargetLowering::Promote:
2424     case TargetLowering::Custom:
2425       assert(0 && "Cannot promote/custom this yet!");
2426     case TargetLowering::Legal:
2427       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2428         Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2429       break;
2430     case TargetLowering::Expand:
2431       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2432       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2433       Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2434                          DAG.getConstant(MVT::getSizeInBits(PairTy)/2, 
2435                                          TLI.getShiftAmountTy()));
2436       Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
2437       break;
2438     }
2439     break;
2440   }
2441
2442   case ISD::UREM:
2443   case ISD::SREM:
2444   case ISD::FREM:
2445     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2446     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2447
2448     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2449     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
2450     case TargetLowering::Custom:
2451       isCustom = true;
2452       // FALLTHROUGH
2453     case TargetLowering::Legal:
2454       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2455       if (isCustom) {
2456         Tmp1 = TLI.LowerOperation(Result, DAG);
2457         if (Tmp1.Val) Result = Tmp1;
2458       }
2459       break;
2460     case TargetLowering::Expand:
2461       unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
2462       bool isSigned = DivOpc == ISD::SDIV;
2463       if (MVT::isInteger(Node->getValueType(0))) {
2464         if (TLI.getOperationAction(DivOpc, Node->getValueType(0)) ==
2465             TargetLowering::Legal) {
2466           // X % Y -> X-X/Y*Y
2467           MVT::ValueType VT = Node->getValueType(0);
2468           Result = DAG.getNode(DivOpc, VT, Tmp1, Tmp2);
2469           Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2470           Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2471         } else {
2472           assert(Node->getValueType(0) == MVT::i32 &&
2473                  "Cannot expand this binary operator!");
2474           RTLIB::Libcall LC = Node->getOpcode() == ISD::UREM
2475             ? RTLIB::UREM_I32 : RTLIB::SREM_I32;
2476           SDOperand Dummy;
2477           Result = ExpandLibCall(TLI.getLibcallName(LC), Node, isSigned, Dummy);
2478         }
2479       } else {
2480         // Floating point mod -> fmod libcall.
2481         RTLIB::Libcall LC = Node->getValueType(0) == MVT::f32
2482           ? RTLIB::REM_F32 : RTLIB::REM_F64;
2483         SDOperand Dummy;
2484         Result = ExpandLibCall(TLI.getLibcallName(LC), Node,
2485                                false/*sign irrelevant*/, Dummy);
2486       }
2487       break;
2488     }
2489     break;
2490   case ISD::VAARG: {
2491     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2492     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2493
2494     MVT::ValueType VT = Node->getValueType(0);
2495     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2496     default: assert(0 && "This action is not supported yet!");
2497     case TargetLowering::Custom:
2498       isCustom = true;
2499       // FALLTHROUGH
2500     case TargetLowering::Legal:
2501       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2502       Result = Result.getValue(0);
2503       Tmp1 = Result.getValue(1);
2504
2505       if (isCustom) {
2506         Tmp2 = TLI.LowerOperation(Result, DAG);
2507         if (Tmp2.Val) {
2508           Result = LegalizeOp(Tmp2);
2509           Tmp1 = LegalizeOp(Tmp2.getValue(1));
2510         }
2511       }
2512       break;
2513     case TargetLowering::Expand: {
2514       SrcValueSDNode *SV = cast<SrcValueSDNode>(Node->getOperand(2));
2515       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2516                                      SV->getValue(), SV->getOffset());
2517       // Increment the pointer, VAList, to the next vaarg
2518       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
2519                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
2520                                          TLI.getPointerTy()));
2521       // Store the incremented VAList to the legalized pointer
2522       Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, SV->getValue(),
2523                           SV->getOffset());
2524       // Load the actual argument out of the pointer VAList
2525       Result = DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
2526       Tmp1 = LegalizeOp(Result.getValue(1));
2527       Result = LegalizeOp(Result);
2528       break;
2529     }
2530     }
2531     // Since VAARG produces two values, make sure to remember that we 
2532     // legalized both of them.
2533     AddLegalizedOperand(SDOperand(Node, 0), Result);
2534     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
2535     return Op.ResNo ? Tmp1 : Result;
2536   }
2537     
2538   case ISD::VACOPY: 
2539     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2540     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
2541     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
2542
2543     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
2544     default: assert(0 && "This action is not supported yet!");
2545     case TargetLowering::Custom:
2546       isCustom = true;
2547       // FALLTHROUGH
2548     case TargetLowering::Legal:
2549       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
2550                                       Node->getOperand(3), Node->getOperand(4));
2551       if (isCustom) {
2552         Tmp1 = TLI.LowerOperation(Result, DAG);
2553         if (Tmp1.Val) Result = Tmp1;
2554       }
2555       break;
2556     case TargetLowering::Expand:
2557       // This defaults to loading a pointer from the input and storing it to the
2558       // output, returning the chain.
2559       SrcValueSDNode *SVD = cast<SrcValueSDNode>(Node->getOperand(3));
2560       SrcValueSDNode *SVS = cast<SrcValueSDNode>(Node->getOperand(4));
2561       Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, SVD->getValue(),
2562                          SVD->getOffset());
2563       Result = DAG.getStore(Tmp4.getValue(1), Tmp4, Tmp2, SVS->getValue(),
2564                             SVS->getOffset());
2565       break;
2566     }
2567     break;
2568
2569   case ISD::VAEND: 
2570     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2571     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2572
2573     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
2574     default: assert(0 && "This action is not supported yet!");
2575     case TargetLowering::Custom:
2576       isCustom = true;
2577       // FALLTHROUGH
2578     case TargetLowering::Legal:
2579       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2580       if (isCustom) {
2581         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
2582         if (Tmp1.Val) Result = Tmp1;
2583       }
2584       break;
2585     case TargetLowering::Expand:
2586       Result = Tmp1; // Default to a no-op, return the chain
2587       break;
2588     }
2589     break;
2590     
2591   case ISD::VASTART: 
2592     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2593     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2594
2595     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2596     
2597     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
2598     default: assert(0 && "This action is not supported yet!");
2599     case TargetLowering::Legal: break;
2600     case TargetLowering::Custom:
2601       Tmp1 = TLI.LowerOperation(Result, DAG);
2602       if (Tmp1.Val) Result = Tmp1;
2603       break;
2604     }
2605     break;
2606     
2607   case ISD::ROTL:
2608   case ISD::ROTR:
2609     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2610     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2611     
2612     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2613            "Cannot handle this yet!");
2614     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2615     break;
2616     
2617   case ISD::BSWAP:
2618     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2619     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2620     case TargetLowering::Custom:
2621       assert(0 && "Cannot custom legalize this yet!");
2622     case TargetLowering::Legal:
2623       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2624       break;
2625     case TargetLowering::Promote: {
2626       MVT::ValueType OVT = Tmp1.getValueType();
2627       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2628       unsigned DiffBits = getSizeInBits(NVT) - getSizeInBits(OVT);
2629
2630       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2631       Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2632       Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2633                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2634       break;
2635     }
2636     case TargetLowering::Expand:
2637       Result = ExpandBSWAP(Tmp1);
2638       break;
2639     }
2640     break;
2641     
2642   case ISD::CTPOP:
2643   case ISD::CTTZ:
2644   case ISD::CTLZ:
2645     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2646     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2647     case TargetLowering::Custom: assert(0 && "Cannot custom handle this yet!");
2648     case TargetLowering::Legal:
2649       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2650       break;
2651     case TargetLowering::Promote: {
2652       MVT::ValueType OVT = Tmp1.getValueType();
2653       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2654
2655       // Zero extend the argument.
2656       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2657       // Perform the larger operation, then subtract if needed.
2658       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2659       switch (Node->getOpcode()) {
2660       case ISD::CTPOP:
2661         Result = Tmp1;
2662         break;
2663       case ISD::CTTZ:
2664         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2665         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2666                             DAG.getConstant(getSizeInBits(NVT), NVT),
2667                             ISD::SETEQ);
2668         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2669                            DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2670         break;
2671       case ISD::CTLZ:
2672         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2673         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2674                              DAG.getConstant(getSizeInBits(NVT) -
2675                                              getSizeInBits(OVT), NVT));
2676         break;
2677       }
2678       break;
2679     }
2680     case TargetLowering::Expand:
2681       Result = ExpandBitCount(Node->getOpcode(), Tmp1);
2682       break;
2683     }
2684     break;
2685
2686     // Unary operators
2687   case ISD::FABS:
2688   case ISD::FNEG:
2689   case ISD::FSQRT:
2690   case ISD::FSIN:
2691   case ISD::FCOS:
2692     Tmp1 = LegalizeOp(Node->getOperand(0));
2693     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2694     case TargetLowering::Promote:
2695     case TargetLowering::Custom:
2696      isCustom = true;
2697      // FALLTHROUGH
2698     case TargetLowering::Legal:
2699       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2700       if (isCustom) {
2701         Tmp1 = TLI.LowerOperation(Result, DAG);
2702         if (Tmp1.Val) Result = Tmp1;
2703       }
2704       break;
2705     case TargetLowering::Expand:
2706       switch (Node->getOpcode()) {
2707       default: assert(0 && "Unreachable!");
2708       case ISD::FNEG:
2709         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2710         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2711         Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
2712         break;
2713       case ISD::FABS: {
2714         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2715         MVT::ValueType VT = Node->getValueType(0);
2716         Tmp2 = DAG.getConstantFP(0.0, VT);
2717         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2718         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2719         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2720         break;
2721       }
2722       case ISD::FSQRT:
2723       case ISD::FSIN:
2724       case ISD::FCOS: {
2725         MVT::ValueType VT = Node->getValueType(0);
2726         RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2727         switch(Node->getOpcode()) {
2728         case ISD::FSQRT:
2729           LC = VT == MVT::f32 ? RTLIB::SQRT_F32 : RTLIB::SQRT_F64;
2730           break;
2731         case ISD::FSIN:
2732           LC = VT == MVT::f32 ? RTLIB::SIN_F32 : RTLIB::SIN_F64;
2733           break;
2734         case ISD::FCOS:
2735           LC = VT == MVT::f32 ? RTLIB::COS_F32 : RTLIB::COS_F64;
2736           break;
2737         default: assert(0 && "Unreachable!");
2738         }
2739         SDOperand Dummy;
2740         Result = ExpandLibCall(TLI.getLibcallName(LC), Node,
2741                                false/*sign irrelevant*/, Dummy);
2742         break;
2743       }
2744       }
2745       break;
2746     }
2747     break;
2748   case ISD::FPOWI: {
2749     // We always lower FPOWI into a libcall.  No target support it yet.
2750     RTLIB::Libcall LC = Node->getValueType(0) == MVT::f32
2751       ? RTLIB::POWI_F32 : RTLIB::POWI_F64;
2752     SDOperand Dummy;
2753     Result = ExpandLibCall(TLI.getLibcallName(LC), Node,
2754                            false/*sign irrelevant*/, Dummy);
2755     break;
2756   }
2757   case ISD::BIT_CONVERT:
2758     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
2759       Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2760     } else {
2761       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2762                                      Node->getOperand(0).getValueType())) {
2763       default: assert(0 && "Unknown operation action!");
2764       case TargetLowering::Expand:
2765         Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2766         break;
2767       case TargetLowering::Legal:
2768         Tmp1 = LegalizeOp(Node->getOperand(0));
2769         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2770         break;
2771       }
2772     }
2773     break;
2774   case ISD::VBIT_CONVERT: {
2775     assert(Op.getOperand(0).getValueType() == MVT::Vector &&
2776            "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
2777     
2778     // The input has to be a vector type, we have to either scalarize it, pack
2779     // it, or convert it based on whether the input vector type is legal.
2780     SDNode *InVal = Node->getOperand(0).Val;
2781     unsigned NumElems =
2782       cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
2783     MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
2784     
2785     // Figure out if there is a Packed type corresponding to this Vector
2786     // type.  If so, convert to the packed type.
2787     MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2788     if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
2789       // Turn this into a bit convert of the packed input.
2790       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
2791                            PackVectorOp(Node->getOperand(0), TVT));
2792       break;
2793     } else if (NumElems == 1) {
2794       // Turn this into a bit convert of the scalar input.
2795       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
2796                            PackVectorOp(Node->getOperand(0), EVT));
2797       break;
2798     } else {
2799       // FIXME: UNIMP!  Store then reload
2800       assert(0 && "Cast from unsupported vector type not implemented yet!");
2801     }
2802   }
2803       
2804     // Conversion operators.  The source and destination have different types.
2805   case ISD::SINT_TO_FP:
2806   case ISD::UINT_TO_FP: {
2807     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2808     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2809     case Legal:
2810       switch (TLI.getOperationAction(Node->getOpcode(),
2811                                      Node->getOperand(0).getValueType())) {
2812       default: assert(0 && "Unknown operation action!");
2813       case TargetLowering::Custom:
2814         isCustom = true;
2815         // FALLTHROUGH
2816       case TargetLowering::Legal:
2817         Tmp1 = LegalizeOp(Node->getOperand(0));
2818         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2819         if (isCustom) {
2820           Tmp1 = TLI.LowerOperation(Result, DAG);
2821           if (Tmp1.Val) Result = Tmp1;
2822         }
2823         break;
2824       case TargetLowering::Expand:
2825         Result = ExpandLegalINT_TO_FP(isSigned,
2826                                       LegalizeOp(Node->getOperand(0)),
2827                                       Node->getValueType(0));
2828         break;
2829       case TargetLowering::Promote:
2830         Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2831                                        Node->getValueType(0),
2832                                        isSigned);
2833         break;
2834       }
2835       break;
2836     case Expand:
2837       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2838                              Node->getValueType(0), Node->getOperand(0));
2839       break;
2840     case Promote:
2841       Tmp1 = PromoteOp(Node->getOperand(0));
2842       if (isSigned) {
2843         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
2844                  Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
2845       } else {
2846         Tmp1 = DAG.getZeroExtendInReg(Tmp1,
2847                                       Node->getOperand(0).getValueType());
2848       }
2849       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2850       Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
2851       break;
2852     }
2853     break;
2854   }
2855   case ISD::TRUNCATE:
2856     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2857     case Legal:
2858       Tmp1 = LegalizeOp(Node->getOperand(0));
2859       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2860       break;
2861     case Expand:
2862       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2863
2864       // Since the result is legal, we should just be able to truncate the low
2865       // part of the source.
2866       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2867       break;
2868     case Promote:
2869       Result = PromoteOp(Node->getOperand(0));
2870       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2871       break;
2872     }
2873     break;
2874
2875   case ISD::FP_TO_SINT:
2876   case ISD::FP_TO_UINT:
2877     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2878     case Legal:
2879       Tmp1 = LegalizeOp(Node->getOperand(0));
2880
2881       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2882       default: assert(0 && "Unknown operation action!");
2883       case TargetLowering::Custom:
2884         isCustom = true;
2885         // FALLTHROUGH
2886       case TargetLowering::Legal:
2887         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2888         if (isCustom) {
2889           Tmp1 = TLI.LowerOperation(Result, DAG);
2890           if (Tmp1.Val) Result = Tmp1;
2891         }
2892         break;
2893       case TargetLowering::Promote:
2894         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2895                                        Node->getOpcode() == ISD::FP_TO_SINT);
2896         break;
2897       case TargetLowering::Expand:
2898         if (Node->getOpcode() == ISD::FP_TO_UINT) {
2899           SDOperand True, False;
2900           MVT::ValueType VT =  Node->getOperand(0).getValueType();
2901           MVT::ValueType NVT = Node->getValueType(0);
2902           unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2903           Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2904           Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2905                             Node->getOperand(0), Tmp2, ISD::SETLT);
2906           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2907           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2908                               DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2909                                           Tmp2));
2910           False = DAG.getNode(ISD::XOR, NVT, False, 
2911                               DAG.getConstant(1ULL << ShiftAmt, NVT));
2912           Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
2913           break;
2914         } else {
2915           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2916         }
2917         break;
2918       }
2919       break;
2920     case Expand: {
2921       // Convert f32 / f64 to i32 / i64.
2922       MVT::ValueType VT = Op.getValueType();
2923       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2924       switch (Node->getOpcode()) {
2925       case ISD::FP_TO_SINT:
2926         if (Node->getOperand(0).getValueType() == MVT::f32)
2927           LC = (VT == MVT::i32)
2928             ? RTLIB::FPTOSINT_F32_I32 : RTLIB::FPTOSINT_F32_I64;
2929         else
2930           LC = (VT == MVT::i32)
2931             ? RTLIB::FPTOSINT_F64_I32 : RTLIB::FPTOSINT_F64_I64;
2932         break;
2933       case ISD::FP_TO_UINT:
2934         if (Node->getOperand(0).getValueType() == MVT::f32)
2935           LC = (VT == MVT::i32)
2936             ? RTLIB::FPTOUINT_F32_I32 : RTLIB::FPTOSINT_F32_I64;
2937         else
2938           LC = (VT == MVT::i32)
2939             ? RTLIB::FPTOUINT_F64_I32 : RTLIB::FPTOSINT_F64_I64;
2940         break;
2941       default: assert(0 && "Unreachable!");
2942       }
2943       SDOperand Dummy;
2944       Result = ExpandLibCall(TLI.getLibcallName(LC), Node,
2945                              false/*sign irrelevant*/, Dummy);
2946       break;
2947     }
2948     case Promote:
2949       Tmp1 = PromoteOp(Node->getOperand(0));
2950       Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
2951       Result = LegalizeOp(Result);
2952       break;
2953     }
2954     break;
2955
2956   case ISD::ANY_EXTEND:
2957   case ISD::ZERO_EXTEND:
2958   case ISD::SIGN_EXTEND:
2959   case ISD::FP_EXTEND:
2960   case ISD::FP_ROUND:
2961     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2962     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
2963     case Legal:
2964       Tmp1 = LegalizeOp(Node->getOperand(0));
2965       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2966       break;
2967     case Promote:
2968       switch (Node->getOpcode()) {
2969       case ISD::ANY_EXTEND:
2970         Tmp1 = PromoteOp(Node->getOperand(0));
2971         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
2972         break;
2973       case ISD::ZERO_EXTEND:
2974         Result = PromoteOp(Node->getOperand(0));
2975         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2976         Result = DAG.getZeroExtendInReg(Result,
2977                                         Node->getOperand(0).getValueType());
2978         break;
2979       case ISD::SIGN_EXTEND:
2980         Result = PromoteOp(Node->getOperand(0));
2981         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2982         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2983                              Result,
2984                           DAG.getValueType(Node->getOperand(0).getValueType()));
2985         break;
2986       case ISD::FP_EXTEND:
2987         Result = PromoteOp(Node->getOperand(0));
2988         if (Result.getValueType() != Op.getValueType())
2989           // Dynamically dead while we have only 2 FP types.
2990           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2991         break;
2992       case ISD::FP_ROUND:
2993         Result = PromoteOp(Node->getOperand(0));
2994         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2995         break;
2996       }
2997     }
2998     break;
2999   case ISD::FP_ROUND_INREG:
3000   case ISD::SIGN_EXTEND_INREG: {
3001     Tmp1 = LegalizeOp(Node->getOperand(0));
3002     MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3003
3004     // If this operation is not supported, convert it to a shl/shr or load/store
3005     // pair.
3006     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
3007     default: assert(0 && "This action not supported for this op yet!");
3008     case TargetLowering::Legal:
3009       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
3010       break;
3011     case TargetLowering::Expand:
3012       // If this is an integer extend and shifts are supported, do that.
3013       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
3014         // NOTE: we could fall back on load/store here too for targets without
3015         // SAR.  However, it is doubtful that any exist.
3016         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
3017                             MVT::getSizeInBits(ExtraVT);
3018         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
3019         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
3020                              Node->getOperand(0), ShiftCst);
3021         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
3022                              Result, ShiftCst);
3023       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
3024         // The only way we can lower this is to turn it into a TRUNCSTORE,
3025         // EXTLOAD pair, targetting a temporary location (a stack slot).
3026
3027         // NOTE: there is a choice here between constantly creating new stack
3028         // slots and always reusing the same one.  We currently always create
3029         // new ones, as reuse may inhibit scheduling.
3030         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
3031         unsigned TySize = (unsigned)TLI.getTargetData()->getTypeSize(Ty);
3032         unsigned Align  = TLI.getTargetData()->getTypeAlignmentPref(Ty);
3033         MachineFunction &MF = DAG.getMachineFunction();
3034         int SSFI =
3035           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
3036         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3037         Result = DAG.getTruncStore(DAG.getEntryNode(), Node->getOperand(0),
3038                                    StackSlot, NULL, 0, ExtraVT);
3039         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
3040                                 Result, StackSlot, NULL, 0, ExtraVT);
3041       } else {
3042         assert(0 && "Unknown op");
3043       }
3044       break;
3045     }
3046     break;
3047   }
3048   }
3049   
3050   assert(Result.getValueType() == Op.getValueType() &&
3051          "Bad legalization!");
3052   
3053   // Make sure that the generated code is itself legal.
3054   if (Result != Op)
3055     Result = LegalizeOp(Result);
3056
3057   // Note that LegalizeOp may be reentered even from single-use nodes, which
3058   // means that we always must cache transformed nodes.
3059   AddLegalizedOperand(Op, Result);
3060   return Result;
3061 }
3062
3063 /// PromoteOp - Given an operation that produces a value in an invalid type,
3064 /// promote it to compute the value into a larger type.  The produced value will
3065 /// have the correct bits for the low portion of the register, but no guarantee
3066 /// is made about the top bits: it may be zero, sign-extended, or garbage.
3067 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
3068   MVT::ValueType VT = Op.getValueType();
3069   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3070   assert(getTypeAction(VT) == Promote &&
3071          "Caller should expand or legalize operands that are not promotable!");
3072   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
3073          "Cannot promote to smaller type!");
3074
3075   SDOperand Tmp1, Tmp2, Tmp3;
3076   SDOperand Result;
3077   SDNode *Node = Op.Val;
3078
3079   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
3080   if (I != PromotedNodes.end()) return I->second;
3081
3082   switch (Node->getOpcode()) {
3083   case ISD::CopyFromReg:
3084     assert(0 && "CopyFromReg must be legal!");
3085   default:
3086 #ifndef NDEBUG
3087     cerr << "NODE: "; Node->dump(); cerr << "\n";
3088 #endif
3089     assert(0 && "Do not know how to promote this operator!");
3090     abort();
3091   case ISD::UNDEF:
3092     Result = DAG.getNode(ISD::UNDEF, NVT);
3093     break;
3094   case ISD::Constant:
3095     if (VT != MVT::i1)
3096       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
3097     else
3098       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
3099     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
3100     break;
3101   case ISD::ConstantFP:
3102     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
3103     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
3104     break;
3105
3106   case ISD::SETCC:
3107     assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
3108     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
3109                          Node->getOperand(1), Node->getOperand(2));
3110     break;
3111     
3112   case ISD::TRUNCATE:
3113     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3114     case Legal:
3115       Result = LegalizeOp(Node->getOperand(0));
3116       assert(Result.getValueType() >= NVT &&
3117              "This truncation doesn't make sense!");
3118       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
3119         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
3120       break;
3121     case Promote:
3122       // The truncation is not required, because we don't guarantee anything
3123       // about high bits anyway.
3124       Result = PromoteOp(Node->getOperand(0));
3125       break;
3126     case Expand:
3127       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
3128       // Truncate the low part of the expanded value to the result type
3129       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
3130     }
3131     break;
3132   case ISD::SIGN_EXTEND:
3133   case ISD::ZERO_EXTEND:
3134   case ISD::ANY_EXTEND:
3135     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3136     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
3137     case Legal:
3138       // Input is legal?  Just do extend all the way to the larger type.
3139       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
3140       break;
3141     case Promote:
3142       // Promote the reg if it's smaller.
3143       Result = PromoteOp(Node->getOperand(0));
3144       // The high bits are not guaranteed to be anything.  Insert an extend.
3145       if (Node->getOpcode() == ISD::SIGN_EXTEND)
3146         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
3147                          DAG.getValueType(Node->getOperand(0).getValueType()));
3148       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
3149         Result = DAG.getZeroExtendInReg(Result,
3150                                         Node->getOperand(0).getValueType());
3151       break;
3152     }
3153     break;
3154   case ISD::BIT_CONVERT:
3155     Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
3156     Result = PromoteOp(Result);
3157     break;
3158     
3159   case ISD::FP_EXTEND:
3160     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
3161   case ISD::FP_ROUND:
3162     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3163     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
3164     case Promote:  assert(0 && "Unreachable with 2 FP types!");
3165     case Legal:
3166       // Input is legal?  Do an FP_ROUND_INREG.
3167       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
3168                            DAG.getValueType(VT));
3169       break;
3170     }
3171     break;
3172
3173   case ISD::SINT_TO_FP:
3174   case ISD::UINT_TO_FP:
3175     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3176     case Legal:
3177       // No extra round required here.
3178       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
3179       break;
3180
3181     case Promote:
3182       Result = PromoteOp(Node->getOperand(0));
3183       if (Node->getOpcode() == ISD::SINT_TO_FP)
3184         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
3185                              Result,
3186                          DAG.getValueType(Node->getOperand(0).getValueType()));
3187       else
3188         Result = DAG.getZeroExtendInReg(Result,
3189                                         Node->getOperand(0).getValueType());
3190       // No extra round required here.
3191       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
3192       break;
3193     case Expand:
3194       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
3195                              Node->getOperand(0));
3196       // Round if we cannot tolerate excess precision.
3197       if (NoExcessFPPrecision)
3198         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3199                              DAG.getValueType(VT));
3200       break;
3201     }
3202     break;
3203
3204   case ISD::SIGN_EXTEND_INREG:
3205     Result = PromoteOp(Node->getOperand(0));
3206     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
3207                          Node->getOperand(1));
3208     break;
3209   case ISD::FP_TO_SINT:
3210   case ISD::FP_TO_UINT:
3211     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3212     case Legal:
3213     case Expand:
3214       Tmp1 = Node->getOperand(0);
3215       break;
3216     case Promote:
3217       // The input result is prerounded, so we don't have to do anything
3218       // special.
3219       Tmp1 = PromoteOp(Node->getOperand(0));
3220       break;
3221     }
3222     // If we're promoting a UINT to a larger size, check to see if the new node
3223     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
3224     // we can use that instead.  This allows us to generate better code for
3225     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
3226     // legal, such as PowerPC.
3227     if (Node->getOpcode() == ISD::FP_TO_UINT && 
3228         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
3229         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
3230          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
3231       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
3232     } else {
3233       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3234     }
3235     break;
3236
3237   case ISD::FABS:
3238   case ISD::FNEG:
3239     Tmp1 = PromoteOp(Node->getOperand(0));
3240     assert(Tmp1.getValueType() == NVT);
3241     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3242     // NOTE: we do not have to do any extra rounding here for
3243     // NoExcessFPPrecision, because we know the input will have the appropriate
3244     // precision, and these operations don't modify precision at all.
3245     break;
3246
3247   case ISD::FSQRT:
3248   case ISD::FSIN:
3249   case ISD::FCOS:
3250     Tmp1 = PromoteOp(Node->getOperand(0));
3251     assert(Tmp1.getValueType() == NVT);
3252     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3253     if (NoExcessFPPrecision)
3254       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3255                            DAG.getValueType(VT));
3256     break;
3257
3258   case ISD::AND:
3259   case ISD::OR:
3260   case ISD::XOR:
3261   case ISD::ADD:
3262   case ISD::SUB:
3263   case ISD::MUL:
3264     // The input may have strange things in the top bits of the registers, but
3265     // these operations don't care.  They may have weird bits going out, but
3266     // that too is okay if they are integer operations.
3267     Tmp1 = PromoteOp(Node->getOperand(0));
3268     Tmp2 = PromoteOp(Node->getOperand(1));
3269     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3270     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3271     break;
3272   case ISD::FADD:
3273   case ISD::FSUB:
3274   case ISD::FMUL:
3275     Tmp1 = PromoteOp(Node->getOperand(0));
3276     Tmp2 = PromoteOp(Node->getOperand(1));
3277     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3278     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3279     
3280     // Floating point operations will give excess precision that we may not be
3281     // able to tolerate.  If we DO allow excess precision, just leave it,
3282     // otherwise excise it.
3283     // FIXME: Why would we need to round FP ops more than integer ones?
3284     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
3285     if (NoExcessFPPrecision)
3286       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3287                            DAG.getValueType(VT));
3288     break;
3289
3290   case ISD::SDIV:
3291   case ISD::SREM:
3292     // These operators require that their input be sign extended.
3293     Tmp1 = PromoteOp(Node->getOperand(0));
3294     Tmp2 = PromoteOp(Node->getOperand(1));
3295     if (MVT::isInteger(NVT)) {
3296       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3297                          DAG.getValueType(VT));
3298       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3299                          DAG.getValueType(VT));
3300     }
3301     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3302
3303     // Perform FP_ROUND: this is probably overly pessimistic.
3304     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
3305       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3306                            DAG.getValueType(VT));
3307     break;
3308   case ISD::FDIV:
3309   case ISD::FREM:
3310   case ISD::FCOPYSIGN:
3311     // These operators require that their input be fp extended.
3312     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3313       case Legal:
3314         Tmp1 = LegalizeOp(Node->getOperand(0));
3315         break;
3316       case Promote:
3317         Tmp1 = PromoteOp(Node->getOperand(0));
3318         break;
3319       case Expand:
3320         assert(0 && "not implemented");
3321     }
3322     switch (getTypeAction(Node->getOperand(1).getValueType())) {
3323       case Legal:
3324         Tmp2 = LegalizeOp(Node->getOperand(1));
3325         break;
3326       case Promote:
3327         Tmp2 = PromoteOp(Node->getOperand(1));
3328         break;
3329       case Expand:
3330         assert(0 && "not implemented");
3331     }
3332     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3333     
3334     // Perform FP_ROUND: this is probably overly pessimistic.
3335     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
3336       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3337                            DAG.getValueType(VT));
3338     break;
3339
3340   case ISD::UDIV:
3341   case ISD::UREM:
3342     // These operators require that their input be zero extended.
3343     Tmp1 = PromoteOp(Node->getOperand(0));
3344     Tmp2 = PromoteOp(Node->getOperand(1));
3345     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
3346     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3347     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3348     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3349     break;
3350
3351   case ISD::SHL:
3352     Tmp1 = PromoteOp(Node->getOperand(0));
3353     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
3354     break;
3355   case ISD::SRA:
3356     // The input value must be properly sign extended.
3357     Tmp1 = PromoteOp(Node->getOperand(0));
3358     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3359                        DAG.getValueType(VT));
3360     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
3361     break;
3362   case ISD::SRL:
3363     // The input value must be properly zero extended.
3364     Tmp1 = PromoteOp(Node->getOperand(0));
3365     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3366     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
3367     break;
3368
3369   case ISD::VAARG:
3370     Tmp1 = Node->getOperand(0);   // Get the chain.
3371     Tmp2 = Node->getOperand(1);   // Get the pointer.
3372     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
3373       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
3374       Result = TLI.CustomPromoteOperation(Tmp3, DAG);
3375     } else {
3376       SrcValueSDNode *SV = cast<SrcValueSDNode>(Node->getOperand(2));
3377       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
3378                                      SV->getValue(), SV->getOffset());
3379       // Increment the pointer, VAList, to the next vaarg
3380       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
3381                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
3382                                          TLI.getPointerTy()));
3383       // Store the incremented VAList to the legalized pointer
3384       Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, SV->getValue(),
3385                           SV->getOffset());
3386       // Load the actual argument out of the pointer VAList
3387       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList, NULL, 0, VT);
3388     }
3389     // Remember that we legalized the chain.
3390     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3391     break;
3392
3393   case ISD::LOAD: {
3394     LoadSDNode *LD = cast<LoadSDNode>(Node);
3395     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
3396       ? ISD::EXTLOAD : LD->getExtensionType();
3397     Result = DAG.getExtLoad(ExtType, NVT,
3398                             LD->getChain(), LD->getBasePtr(),
3399                             LD->getSrcValue(), LD->getSrcValueOffset(),
3400                             LD->getLoadedVT());
3401     // Remember that we legalized the chain.
3402     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3403     break;
3404   }
3405   case ISD::SELECT:
3406     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
3407     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
3408     Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
3409     break;
3410   case ISD::SELECT_CC:
3411     Tmp2 = PromoteOp(Node->getOperand(2));   // True
3412     Tmp3 = PromoteOp(Node->getOperand(3));   // False
3413     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3414                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
3415     break;
3416   case ISD::BSWAP:
3417     Tmp1 = Node->getOperand(0);
3418     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3419     Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3420     Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3421                          DAG.getConstant(getSizeInBits(NVT) - getSizeInBits(VT),
3422                                          TLI.getShiftAmountTy()));
3423     break;
3424   case ISD::CTPOP:
3425   case ISD::CTTZ:
3426   case ISD::CTLZ:
3427     // Zero extend the argument
3428     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
3429     // Perform the larger operation, then subtract if needed.
3430     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3431     switch(Node->getOpcode()) {
3432     case ISD::CTPOP:
3433       Result = Tmp1;
3434       break;
3435     case ISD::CTTZ:
3436       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3437       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
3438                           DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
3439       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3440                            DAG.getConstant(getSizeInBits(VT), NVT), Tmp1);
3441       break;
3442     case ISD::CTLZ:
3443       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3444       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3445                            DAG.getConstant(getSizeInBits(NVT) -
3446                                            getSizeInBits(VT), NVT));
3447       break;
3448     }
3449     break;
3450   case ISD::VEXTRACT_VECTOR_ELT:
3451     Result = PromoteOp(LowerVEXTRACT_VECTOR_ELT(Op));
3452     break;
3453   case ISD::EXTRACT_VECTOR_ELT:
3454     Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
3455     break;
3456   }
3457
3458   assert(Result.Val && "Didn't set a result!");
3459
3460   // Make sure the result is itself legal.
3461   Result = LegalizeOp(Result);
3462   
3463   // Remember that we promoted this!
3464   AddPromotedOperand(Op, Result);
3465   return Result;
3466 }
3467
3468 /// LowerVEXTRACT_VECTOR_ELT - Lower a VEXTRACT_VECTOR_ELT operation into a
3469 /// EXTRACT_VECTOR_ELT operation, to memory operations, or to scalar code based
3470 /// on the vector type.  The return type of this matches the element type of the
3471 /// vector, which may not be legal for the target.
3472 SDOperand SelectionDAGLegalize::LowerVEXTRACT_VECTOR_ELT(SDOperand Op) {
3473   // We know that operand #0 is the Vec vector.  If the index is a constant
3474   // or if the invec is a supported hardware type, we can use it.  Otherwise,
3475   // lower to a store then an indexed load.
3476   SDOperand Vec = Op.getOperand(0);
3477   SDOperand Idx = LegalizeOp(Op.getOperand(1));
3478   
3479   SDNode *InVal = Vec.Val;
3480   unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
3481   MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
3482   
3483   // Figure out if there is a Packed type corresponding to this Vector
3484   // type.  If so, convert to the packed type.
3485   MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
3486   if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
3487     // Turn this into a packed extract_vector_elt operation.
3488     Vec = PackVectorOp(Vec, TVT);
3489     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Op.getValueType(), Vec, Idx);
3490   } else if (NumElems == 1) {
3491     // This must be an access of the only element.  Return it.
3492     return PackVectorOp(Vec, EVT);
3493   } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3494     SDOperand Lo, Hi;
3495     SplitVectorOp(Vec, Lo, Hi);
3496     if (CIdx->getValue() < NumElems/2) {
3497       Vec = Lo;
3498     } else {
3499       Vec = Hi;
3500       Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
3501     }
3502     
3503     // It's now an extract from the appropriate high or low part.  Recurse.
3504     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
3505     return LowerVEXTRACT_VECTOR_ELT(Op);
3506   } else {
3507     // Variable index case for extract element.
3508     // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
3509     assert(0 && "unimp!");
3510     return SDOperand();
3511   }
3512 }
3513
3514 /// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
3515 /// memory traffic.
3516 SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
3517   SDOperand Vector = Op.getOperand(0);
3518   SDOperand Idx    = Op.getOperand(1);
3519   
3520   // If the target doesn't support this, store the value to a temporary
3521   // stack slot, then LOAD the scalar element back out.
3522   SDOperand StackPtr = CreateStackTemporary(Vector.getValueType());
3523   SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Vector, StackPtr, NULL, 0);
3524   
3525   // Add the offset to the index.
3526   unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
3527   Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
3528                     DAG.getConstant(EltSize, Idx.getValueType()));
3529   StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
3530   
3531   return DAG.getLoad(Op.getValueType(), Ch, StackPtr, NULL, 0);
3532 }
3533
3534
3535 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
3536 /// with condition CC on the current target.  This usually involves legalizing
3537 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
3538 /// there may be no choice but to create a new SetCC node to represent the
3539 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
3540 /// LHS, and the SDOperand returned in RHS has a nil SDNode value.
3541 void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
3542                                                  SDOperand &RHS,
3543                                                  SDOperand &CC) {
3544   SDOperand Tmp1, Tmp2, Result;    
3545   
3546   switch (getTypeAction(LHS.getValueType())) {
3547   case Legal:
3548     Tmp1 = LegalizeOp(LHS);   // LHS
3549     Tmp2 = LegalizeOp(RHS);   // RHS
3550     break;
3551   case Promote:
3552     Tmp1 = PromoteOp(LHS);   // LHS
3553     Tmp2 = PromoteOp(RHS);   // RHS
3554
3555     // If this is an FP compare, the operands have already been extended.
3556     if (MVT::isInteger(LHS.getValueType())) {
3557       MVT::ValueType VT = LHS.getValueType();
3558       MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3559
3560       // Otherwise, we have to insert explicit sign or zero extends.  Note
3561       // that we could insert sign extends for ALL conditions, but zero extend
3562       // is cheaper on many machines (an AND instead of two shifts), so prefer
3563       // it.
3564       switch (cast<CondCodeSDNode>(CC)->get()) {
3565       default: assert(0 && "Unknown integer comparison!");
3566       case ISD::SETEQ:
3567       case ISD::SETNE:
3568       case ISD::SETUGE:
3569       case ISD::SETUGT:
3570       case ISD::SETULE:
3571       case ISD::SETULT:
3572         // ALL of these operations will work if we either sign or zero extend
3573         // the operands (including the unsigned comparisons!).  Zero extend is
3574         // usually a simpler/cheaper operation, so prefer it.
3575         Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3576         Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3577         break;
3578       case ISD::SETGE:
3579       case ISD::SETGT:
3580       case ISD::SETLT:
3581       case ISD::SETLE:
3582         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3583                            DAG.getValueType(VT));
3584         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3585                            DAG.getValueType(VT));
3586         break;
3587       }
3588     }
3589     break;
3590   case Expand: {
3591     MVT::ValueType VT = LHS.getValueType();
3592     if (VT == MVT::f32 || VT == MVT::f64) {
3593       // Expand into one or more soft-fp libcall(s).
3594       RTLIB::Libcall LC1, LC2 = RTLIB::UNKNOWN_LIBCALL;
3595       ISD::CondCode CC1, CC2 = ISD::SETCC_INVALID;
3596       switch (cast<CondCodeSDNode>(CC)->get()) {
3597       case ISD::SETEQ:
3598       case ISD::SETOEQ:
3599         LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
3600         CC1 = ISD::SETEQ;
3601         break;
3602       case ISD::SETNE:
3603       case ISD::SETUNE:
3604         LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : RTLIB::UNE_F64;
3605         CC1 = ISD::SETNE;
3606         break;
3607       case ISD::SETGE:
3608       case ISD::SETOGE:
3609         LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
3610         CC1 = ISD::SETGE;
3611         break;
3612       case ISD::SETLT:
3613       case ISD::SETOLT:
3614         LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
3615         CC1 = ISD::SETLT;
3616         break;
3617       case ISD::SETLE:
3618       case ISD::SETOLE:
3619         LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
3620         CC1 = ISD::SETLE;
3621         break;
3622       case ISD::SETGT:
3623       case ISD::SETOGT:
3624         LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
3625         CC1 = ISD::SETGT;
3626         break;
3627       case ISD::SETUO:
3628       case ISD::SETO:
3629         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
3630         CC1 = cast<CondCodeSDNode>(CC)->get() == ISD::SETO
3631           ? ISD::SETEQ : ISD::SETNE;
3632         break;
3633       default:
3634         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
3635         CC1 = ISD::SETNE;
3636         switch (cast<CondCodeSDNode>(CC)->get()) {
3637         case ISD::SETONE:
3638           // SETONE = SETOLT | SETOGT
3639           LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
3640           CC1 = ISD::SETLT;
3641           // Fallthrough
3642         case ISD::SETUGT:
3643           LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
3644           CC2 = ISD::SETGT;
3645           break;
3646         case ISD::SETUGE:
3647           LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
3648           CC2 = ISD::SETGE;
3649           break;
3650         case ISD::SETULT:
3651           LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
3652           CC2 = ISD::SETLT;
3653           break;
3654         case ISD::SETULE:
3655           LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
3656           CC2 = ISD::SETLE;
3657           break;
3658         case ISD::SETUEQ:
3659           LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
3660           CC2 = ISD::SETEQ;
3661           break;
3662         default: assert(0 && "Unsupported FP setcc!");
3663         }
3664       }
3665       
3666       SDOperand Dummy;
3667       Tmp1 = ExpandLibCall(TLI.getLibcallName(LC1),
3668                            DAG.getNode(ISD::MERGE_VALUES, VT, LHS, RHS).Val, 
3669                            false /*sign irrelevant*/, Dummy);
3670       Tmp2 = DAG.getConstant(0, MVT::i32);
3671       CC = DAG.getCondCode(CC1);
3672       if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
3673         Tmp1 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), Tmp1, Tmp2, CC);
3674         LHS = ExpandLibCall(TLI.getLibcallName(LC2),
3675                             DAG.getNode(ISD::MERGE_VALUES, VT, LHS, RHS).Val, 
3676                             false /*sign irrelevant*/, Dummy);
3677         Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHS, Tmp2,
3678                            DAG.getCondCode(CC2));
3679         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
3680         Tmp2 = SDOperand();
3681       }
3682       LHS = Tmp1;
3683       RHS = Tmp2;
3684       return;
3685     }
3686
3687     SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
3688     ExpandOp(LHS, LHSLo, LHSHi);
3689     ExpandOp(RHS, RHSLo, RHSHi);    
3690     switch (cast<CondCodeSDNode>(CC)->get()) {
3691     case ISD::SETEQ:
3692     case ISD::SETNE:
3693       if (RHSLo == RHSHi)
3694         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
3695           if (RHSCST->isAllOnesValue()) {
3696             // Comparison to -1.
3697             Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
3698             Tmp2 = RHSLo;
3699             break;
3700           }
3701
3702       Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
3703       Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
3704       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
3705       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3706       break;
3707     default:
3708       // If this is a comparison of the sign bit, just look at the top part.
3709       // X > -1,  x < 0
3710       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
3711         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT && 
3712              CST->getValue() == 0) ||             // X < 0
3713             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
3714              CST->isAllOnesValue())) {            // X > -1
3715           Tmp1 = LHSHi;
3716           Tmp2 = RHSHi;
3717           break;
3718         }
3719
3720       // FIXME: This generated code sucks.
3721       ISD::CondCode LowCC;
3722       switch (cast<CondCodeSDNode>(CC)->get()) {
3723       default: assert(0 && "Unknown integer setcc!");
3724       case ISD::SETLT:
3725       case ISD::SETULT: LowCC = ISD::SETULT; break;
3726       case ISD::SETGT:
3727       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
3728       case ISD::SETLE:
3729       case ISD::SETULE: LowCC = ISD::SETULE; break;
3730       case ISD::SETGE:
3731       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
3732       }
3733
3734       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
3735       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
3736       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
3737
3738       // NOTE: on targets without efficient SELECT of bools, we can always use
3739       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
3740       Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
3741       Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi, CC);
3742       Result = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
3743       Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
3744                                       Result, Tmp1, Tmp2));
3745       Tmp1 = Result;
3746       Tmp2 = SDOperand();
3747     }
3748   }
3749   }
3750   LHS = Tmp1;
3751   RHS = Tmp2;
3752 }
3753
3754 /// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
3755 /// The resultant code need not be legal.  Note that SrcOp is the input operand
3756 /// to the BIT_CONVERT, not the BIT_CONVERT node itself.
3757 SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
3758                                                   SDOperand SrcOp) {
3759   // Create the stack frame object.
3760   SDOperand FIPtr = CreateStackTemporary(DestVT);
3761   
3762   // Emit a store to the stack slot.
3763   SDOperand Store = DAG.getStore(DAG.getEntryNode(), SrcOp, FIPtr, NULL, 0);
3764   // Result is a load from the stack slot.
3765   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
3766 }
3767
3768 SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
3769   // Create a vector sized/aligned stack slot, store the value to element #0,
3770   // then load the whole vector back out.
3771   SDOperand StackPtr = CreateStackTemporary(Node->getValueType(0));
3772   SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Node->getOperand(0), StackPtr,
3773                               NULL, 0);
3774   return DAG.getLoad(Node->getValueType(0), Ch, StackPtr, NULL, 0);
3775 }
3776
3777
3778 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
3779 /// support the operation, but do support the resultant packed vector type.
3780 SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
3781   
3782   // If the only non-undef value is the low element, turn this into a 
3783   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
3784   unsigned NumElems = Node->getNumOperands();
3785   bool isOnlyLowElement = true;
3786   SDOperand SplatValue = Node->getOperand(0);
3787   std::map<SDOperand, std::vector<unsigned> > Values;
3788   Values[SplatValue].push_back(0);
3789   bool isConstant = true;
3790   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
3791       SplatValue.getOpcode() != ISD::UNDEF)
3792     isConstant = false;
3793   
3794   for (unsigned i = 1; i < NumElems; ++i) {
3795     SDOperand V = Node->getOperand(i);
3796     Values[V].push_back(i);
3797     if (V.getOpcode() != ISD::UNDEF)
3798       isOnlyLowElement = false;
3799     if (SplatValue != V)
3800       SplatValue = SDOperand(0,0);
3801
3802     // If this isn't a constant element or an undef, we can't use a constant
3803     // pool load.
3804     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
3805         V.getOpcode() != ISD::UNDEF)
3806       isConstant = false;
3807   }
3808   
3809   if (isOnlyLowElement) {
3810     // If the low element is an undef too, then this whole things is an undef.
3811     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
3812       return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
3813     // Otherwise, turn this into a scalar_to_vector node.
3814     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3815                        Node->getOperand(0));
3816   }
3817   
3818   // If all elements are constants, create a load from the constant pool.
3819   if (isConstant) {
3820     MVT::ValueType VT = Node->getValueType(0);
3821     const Type *OpNTy = 
3822       MVT::getTypeForValueType(Node->getOperand(0).getValueType());
3823     std::vector<Constant*> CV;
3824     for (unsigned i = 0, e = NumElems; i != e; ++i) {
3825       if (ConstantFPSDNode *V = 
3826           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
3827         CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
3828       } else if (ConstantSDNode *V = 
3829                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
3830         CV.push_back(ConstantInt::get(OpNTy, V->getValue()));
3831       } else {
3832         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
3833         CV.push_back(UndefValue::get(OpNTy));
3834       }
3835     }
3836     Constant *CP = ConstantPacked::get(CV);
3837     SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
3838     return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0);
3839   }
3840   
3841   if (SplatValue.Val) {   // Splat of one value?
3842     // Build the shuffle constant vector: <0, 0, 0, 0>
3843     MVT::ValueType MaskVT = 
3844       MVT::getIntVectorWithNumElements(NumElems);
3845     SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
3846     std::vector<SDOperand> ZeroVec(NumElems, Zero);
3847     SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3848                                       &ZeroVec[0], ZeroVec.size());
3849
3850     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3851     if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
3852       // Get the splatted value into the low element of a vector register.
3853       SDOperand LowValVec = 
3854         DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
3855     
3856       // Return shuffle(LowValVec, undef, <0,0,0,0>)
3857       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
3858                          DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
3859                          SplatMask);
3860     }
3861   }
3862   
3863   // If there are only two unique elements, we may be able to turn this into a
3864   // vector shuffle.
3865   if (Values.size() == 2) {
3866     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
3867     MVT::ValueType MaskVT = 
3868       MVT::getIntVectorWithNumElements(NumElems);
3869     std::vector<SDOperand> MaskVec(NumElems);
3870     unsigned i = 0;
3871     for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3872            E = Values.end(); I != E; ++I) {
3873       for (std::vector<unsigned>::iterator II = I->second.begin(),
3874              EE = I->second.end(); II != EE; ++II)
3875         MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
3876       i += NumElems;
3877     }
3878     SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3879                                         &MaskVec[0], MaskVec.size());
3880
3881     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3882     if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
3883         isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
3884       SmallVector<SDOperand, 8> Ops;
3885       for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3886             E = Values.end(); I != E; ++I) {
3887         SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3888                                    I->first);
3889         Ops.push_back(Op);
3890       }
3891       Ops.push_back(ShuffleMask);
3892
3893       // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
3894       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), 
3895                          &Ops[0], Ops.size());
3896     }
3897   }
3898   
3899   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
3900   // aligned object on the stack, store each element into it, then load
3901   // the result as a vector.
3902   MVT::ValueType VT = Node->getValueType(0);
3903   // Create the stack frame object.
3904   SDOperand FIPtr = CreateStackTemporary(VT);
3905   
3906   // Emit a store of each element to the stack slot.
3907   SmallVector<SDOperand, 8> Stores;
3908   unsigned TypeByteSize = 
3909     MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
3910   // Store (in the right endianness) the elements to memory.
3911   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3912     // Ignore undef elements.
3913     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3914     
3915     unsigned Offset = TypeByteSize*i;
3916     
3917     SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
3918     Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
3919     
3920     Stores.push_back(DAG.getStore(DAG.getEntryNode(), Node->getOperand(i), Idx, 
3921                                   NULL, 0));
3922   }
3923   
3924   SDOperand StoreChain;
3925   if (!Stores.empty())    // Not all undef elements?
3926     StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3927                              &Stores[0], Stores.size());
3928   else
3929     StoreChain = DAG.getEntryNode();
3930   
3931   // Result is a load from the stack slot.
3932   return DAG.getLoad(VT, StoreChain, FIPtr, NULL, 0);
3933 }
3934
3935 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
3936 /// specified value type.
3937 SDOperand SelectionDAGLegalize::CreateStackTemporary(MVT::ValueType VT) {
3938   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3939   unsigned ByteSize = MVT::getSizeInBits(VT)/8;
3940   const Type *Ty = MVT::getTypeForValueType(VT);
3941   unsigned StackAlign = (unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty);
3942   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
3943   return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
3944 }
3945
3946 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
3947                                             SDOperand Op, SDOperand Amt,
3948                                             SDOperand &Lo, SDOperand &Hi) {
3949   // Expand the subcomponents.
3950   SDOperand LHSL, LHSH;
3951   ExpandOp(Op, LHSL, LHSH);
3952
3953   SDOperand Ops[] = { LHSL, LHSH, Amt };
3954   MVT::ValueType VT = LHSL.getValueType();
3955   Lo = DAG.getNode(NodeOp, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
3956   Hi = Lo.getValue(1);
3957 }
3958
3959
3960 /// ExpandShift - Try to find a clever way to expand this shift operation out to
3961 /// smaller elements.  If we can't find a way that is more efficient than a
3962 /// libcall on this target, return false.  Otherwise, return true with the
3963 /// low-parts expanded into Lo and Hi.
3964 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
3965                                        SDOperand &Lo, SDOperand &Hi) {
3966   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
3967          "This is not a shift!");
3968
3969   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
3970   SDOperand ShAmt = LegalizeOp(Amt);
3971   MVT::ValueType ShTy = ShAmt.getValueType();
3972   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
3973   unsigned NVTBits = MVT::getSizeInBits(NVT);
3974
3975   // Handle the case when Amt is an immediate.  Other cases are currently broken
3976   // and are disabled.
3977   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
3978     unsigned Cst = CN->getValue();
3979     // Expand the incoming operand to be shifted, so that we have its parts
3980     SDOperand InL, InH;
3981     ExpandOp(Op, InL, InH);
3982     switch(Opc) {
3983     case ISD::SHL:
3984       if (Cst > VTBits) {
3985         Lo = DAG.getConstant(0, NVT);
3986         Hi = DAG.getConstant(0, NVT);
3987       } else if (Cst > NVTBits) {
3988         Lo = DAG.getConstant(0, NVT);
3989         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
3990       } else if (Cst == NVTBits) {
3991         Lo = DAG.getConstant(0, NVT);
3992         Hi = InL;
3993       } else {
3994         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
3995         Hi = DAG.getNode(ISD::OR, NVT,
3996            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
3997            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
3998       }
3999       return true;
4000     case ISD::SRL:
4001       if (Cst > VTBits) {
4002         Lo = DAG.getConstant(0, NVT);
4003         Hi = DAG.getConstant(0, NVT);
4004       } else if (Cst > NVTBits) {
4005         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
4006         Hi = DAG.getConstant(0, NVT);
4007       } else if (Cst == NVTBits) {
4008         Lo = InH;
4009         Hi = DAG.getConstant(0, NVT);
4010       } else {
4011         Lo = DAG.getNode(ISD::OR, NVT,
4012            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
4013            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
4014         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
4015       }
4016       return true;
4017     case ISD::SRA:
4018       if (Cst > VTBits) {
4019         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
4020                               DAG.getConstant(NVTBits-1, ShTy));
4021       } else if (Cst > NVTBits) {
4022         Lo = DAG.getNode(ISD::SRA, NVT, InH,
4023                            DAG.getConstant(Cst-NVTBits, ShTy));
4024         Hi = DAG.getNode(ISD::SRA, NVT, InH,
4025                               DAG.getConstant(NVTBits-1, ShTy));
4026       } else if (Cst == NVTBits) {
4027         Lo = InH;
4028         Hi = DAG.getNode(ISD::SRA, NVT, InH,
4029                               DAG.getConstant(NVTBits-1, ShTy));
4030       } else {
4031         Lo = DAG.getNode(ISD::OR, NVT,
4032            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
4033            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
4034         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
4035       }
4036       return true;
4037     }
4038   }
4039   
4040   // Okay, the shift amount isn't constant.  However, if we can tell that it is
4041   // >= 32 or < 32, we can still simplify it, without knowing the actual value.
4042   uint64_t Mask = NVTBits, KnownZero, KnownOne;
4043   TLI.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
4044   
4045   // If we know that the high bit of the shift amount is one, then we can do
4046   // this as a couple of simple shifts.
4047   if (KnownOne & Mask) {
4048     // Mask out the high bit, which we know is set.
4049     Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
4050                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
4051     
4052     // Expand the incoming operand to be shifted, so that we have its parts
4053     SDOperand InL, InH;
4054     ExpandOp(Op, InL, InH);
4055     switch(Opc) {
4056     case ISD::SHL:
4057       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
4058       Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
4059       return true;
4060     case ISD::SRL:
4061       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
4062       Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
4063       return true;
4064     case ISD::SRA:
4065       Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
4066                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
4067       Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
4068       return true;
4069     }
4070   }
4071   
4072   // If we know that the high bit of the shift amount is zero, then we can do
4073   // this as a couple of simple shifts.
4074   if (KnownZero & Mask) {
4075     // Compute 32-amt.
4076     SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
4077                                  DAG.getConstant(NVTBits, Amt.getValueType()),
4078                                  Amt);
4079     
4080     // Expand the incoming operand to be shifted, so that we have its parts
4081     SDOperand InL, InH;
4082     ExpandOp(Op, InL, InH);
4083     switch(Opc) {
4084     case ISD::SHL:
4085       Lo = DAG.getNode(ISD::SHL, NVT, InL, Amt);
4086       Hi = DAG.getNode(ISD::OR, NVT,
4087                        DAG.getNode(ISD::SHL, NVT, InH, Amt),
4088                        DAG.getNode(ISD::SRL, NVT, InL, Amt2));
4089       return true;
4090     case ISD::SRL:
4091       Hi = DAG.getNode(ISD::SRL, NVT, InH, Amt);
4092       Lo = DAG.getNode(ISD::OR, NVT,
4093                        DAG.getNode(ISD::SRL, NVT, InL, Amt),
4094                        DAG.getNode(ISD::SHL, NVT, InH, Amt2));
4095       return true;
4096     case ISD::SRA:
4097       Hi = DAG.getNode(ISD::SRA, NVT, InH, Amt);
4098       Lo = DAG.getNode(ISD::OR, NVT,
4099                        DAG.getNode(ISD::SRL, NVT, InL, Amt),
4100                        DAG.getNode(ISD::SHL, NVT, InH, Amt2));
4101       return true;
4102     }
4103   }
4104   
4105   return false;
4106 }
4107
4108
4109 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
4110 // does not fit into a register, return the lo part and set the hi part to the
4111 // by-reg argument.  If it does fit into a single register, return the result
4112 // and leave the Hi part unset.
4113 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
4114                                               bool isSigned, SDOperand &Hi) {
4115   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
4116   // The input chain to this libcall is the entry node of the function. 
4117   // Legalizing the call will automatically add the previous call to the
4118   // dependence.
4119   SDOperand InChain = DAG.getEntryNode();
4120   
4121   TargetLowering::ArgListTy Args;
4122   TargetLowering::ArgListEntry Entry;
4123   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
4124     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
4125     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
4126     Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy; 
4127     Entry.isSigned = isSigned;
4128     Args.push_back(Entry);
4129   }
4130   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
4131
4132   // Splice the libcall in wherever FindInputOutputChains tells us to.
4133   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
4134   std::pair<SDOperand,SDOperand> CallInfo =
4135     TLI.LowerCallTo(InChain, RetTy, isSigned, false, CallingConv::C, false,
4136                     Callee, Args, DAG);
4137
4138   // Legalize the call sequence, starting with the chain.  This will advance
4139   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
4140   // was added by LowerCallTo (guaranteeing proper serialization of calls).
4141   LegalizeOp(CallInfo.second);
4142   SDOperand Result;
4143   switch (getTypeAction(CallInfo.first.getValueType())) {
4144   default: assert(0 && "Unknown thing");
4145   case Legal:
4146     Result = CallInfo.first;
4147     break;
4148   case Expand:
4149     ExpandOp(CallInfo.first, Result, Hi);
4150     break;
4151   }
4152   return Result;
4153 }
4154
4155
4156 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
4157 /// destination type is legal.
4158 SDOperand SelectionDAGLegalize::
4159 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
4160   assert(isTypeLegal(DestTy) && "Destination type is not legal!");
4161   assert(getTypeAction(Source.getValueType()) == Expand &&
4162          "This is not an expansion!");
4163   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
4164
4165   if (!isSigned) {
4166     assert(Source.getValueType() == MVT::i64 &&
4167            "This only works for 64-bit -> FP");
4168     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
4169     // incoming integer is set.  To handle this, we dynamically test to see if
4170     // it is set, and, if so, add a fudge factor.
4171     SDOperand Lo, Hi;
4172     ExpandOp(Source, Lo, Hi);
4173
4174     // If this is unsigned, and not supported, first perform the conversion to
4175     // signed, then adjust the result if the sign bit is set.
4176     SDOperand SignedConv = ExpandIntToFP(true, DestTy,
4177                    DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
4178
4179     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
4180                                      DAG.getConstant(0, Hi.getValueType()),
4181                                      ISD::SETLT);
4182     SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
4183     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
4184                                       SignSet, Four, Zero);
4185     uint64_t FF = 0x5f800000ULL;
4186     if (TLI.isLittleEndian()) FF <<= 32;
4187     static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
4188
4189     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
4190     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
4191     SDOperand FudgeInReg;
4192     if (DestTy == MVT::f32)
4193       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
4194     else {
4195       assert(DestTy == MVT::f64 && "Unexpected conversion");
4196       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
4197                                   CPIdx, NULL, 0, MVT::f32);
4198     }
4199     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
4200   }
4201
4202   // Check to see if the target has a custom way to lower this.  If so, use it.
4203   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
4204   default: assert(0 && "This action not implemented for this operation!");
4205   case TargetLowering::Legal:
4206   case TargetLowering::Expand:
4207     break;   // This case is handled below.
4208   case TargetLowering::Custom: {
4209     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
4210                                                   Source), DAG);
4211     if (NV.Val)
4212       return LegalizeOp(NV);
4213     break;   // The target decided this was legal after all
4214   }
4215   }
4216
4217   // Expand the source, then glue it back together for the call.  We must expand
4218   // the source in case it is shared (this pass of legalize must traverse it).
4219   SDOperand SrcLo, SrcHi;
4220   ExpandOp(Source, SrcLo, SrcHi);
4221   Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
4222
4223   RTLIB::Libcall LC;
4224   if (DestTy == MVT::f32)
4225     LC = RTLIB::SINTTOFP_I64_F32;
4226   else {
4227     assert(DestTy == MVT::f64 && "Unknown fp value type!");
4228     LC = RTLIB::SINTTOFP_I64_F64;
4229   }
4230   
4231   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
4232   SDOperand UnusedHiPart;
4233   return ExpandLibCall(TLI.getLibcallName(LC), Source.Val, isSigned,
4234                        UnusedHiPart);
4235 }
4236
4237 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
4238 /// INT_TO_FP operation of the specified operand when the target requests that
4239 /// we expand it.  At this point, we know that the result and operand types are
4240 /// legal for the target.
4241 SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
4242                                                      SDOperand Op0,
4243                                                      MVT::ValueType DestVT) {
4244   if (Op0.getValueType() == MVT::i32) {
4245     // simple 32-bit [signed|unsigned] integer to float/double expansion
4246     
4247     // get the stack frame index of a 8 byte buffer, pessimistically aligned
4248     MachineFunction &MF = DAG.getMachineFunction();
4249     const Type *F64Type = MVT::getTypeForValueType(MVT::f64);
4250     unsigned StackAlign =
4251       (unsigned)TLI.getTargetData()->getTypeAlignmentPref(F64Type);
4252     int SSFI = MF.getFrameInfo()->CreateStackObject(8, StackAlign);
4253     // get address of 8 byte buffer
4254     SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4255     // word offset constant for Hi/Lo address computation
4256     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
4257     // set up Hi and Lo (into buffer) address based on endian
4258     SDOperand Hi = StackSlot;
4259     SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
4260     if (TLI.isLittleEndian())
4261       std::swap(Hi, Lo);
4262     
4263     // if signed map to unsigned space
4264     SDOperand Op0Mapped;
4265     if (isSigned) {
4266       // constant used to invert sign bit (signed to unsigned mapping)
4267       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
4268       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
4269     } else {
4270       Op0Mapped = Op0;
4271     }
4272     // store the lo of the constructed double - based on integer input
4273     SDOperand Store1 = DAG.getStore(DAG.getEntryNode(),
4274                                     Op0Mapped, Lo, NULL, 0);
4275     // initial hi portion of constructed double
4276     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
4277     // store the hi of the constructed double - biased exponent
4278     SDOperand Store2=DAG.getStore(Store1, InitialHi, Hi, NULL, 0);
4279     // load the constructed double
4280     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot, NULL, 0);
4281     // FP constant to bias correct the final result
4282     SDOperand Bias = DAG.getConstantFP(isSigned ?
4283                                             BitsToDouble(0x4330000080000000ULL)
4284                                           : BitsToDouble(0x4330000000000000ULL),
4285                                      MVT::f64);
4286     // subtract the bias
4287     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
4288     // final result
4289     SDOperand Result;
4290     // handle final rounding
4291     if (DestVT == MVT::f64) {
4292       // do nothing
4293       Result = Sub;
4294     } else {
4295      // if f32 then cast to f32
4296       Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
4297     }
4298     return Result;
4299   }
4300   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
4301   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
4302
4303   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
4304                                    DAG.getConstant(0, Op0.getValueType()),
4305                                    ISD::SETLT);
4306   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
4307   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
4308                                     SignSet, Four, Zero);
4309
4310   // If the sign bit of the integer is set, the large number will be treated
4311   // as a negative number.  To counteract this, the dynamic code adds an
4312   // offset depending on the data type.
4313   uint64_t FF;
4314   switch (Op0.getValueType()) {
4315   default: assert(0 && "Unsupported integer type!");
4316   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
4317   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
4318   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
4319   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
4320   }
4321   if (TLI.isLittleEndian()) FF <<= 32;
4322   static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
4323
4324   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
4325   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
4326   SDOperand FudgeInReg;
4327   if (DestVT == MVT::f32)
4328     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
4329   else {
4330     assert(DestVT == MVT::f64 && "Unexpected conversion");
4331     FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
4332                                            DAG.getEntryNode(), CPIdx,
4333                                            NULL, 0, MVT::f32));
4334   }
4335
4336   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
4337 }
4338
4339 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
4340 /// *INT_TO_FP operation of the specified operand when the target requests that
4341 /// we promote it.  At this point, we know that the result and operand types are
4342 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
4343 /// operation that takes a larger input.
4344 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
4345                                                       MVT::ValueType DestVT,
4346                                                       bool isSigned) {
4347   // First step, figure out the appropriate *INT_TO_FP operation to use.
4348   MVT::ValueType NewInTy = LegalOp.getValueType();
4349
4350   unsigned OpToUse = 0;
4351
4352   // Scan for the appropriate larger type to use.
4353   while (1) {
4354     NewInTy = (MVT::ValueType)(NewInTy+1);
4355     assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
4356
4357     // If the target supports SINT_TO_FP of this type, use it.
4358     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
4359       default: break;
4360       case TargetLowering::Legal:
4361         if (!TLI.isTypeLegal(NewInTy))
4362           break;  // Can't use this datatype.
4363         // FALL THROUGH.
4364       case TargetLowering::Custom:
4365         OpToUse = ISD::SINT_TO_FP;
4366         break;
4367     }
4368     if (OpToUse) break;
4369     if (isSigned) continue;
4370
4371     // If the target supports UINT_TO_FP of this type, use it.
4372     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
4373       default: break;
4374       case TargetLowering::Legal:
4375         if (!TLI.isTypeLegal(NewInTy))
4376           break;  // Can't use this datatype.
4377         // FALL THROUGH.
4378       case TargetLowering::Custom:
4379         OpToUse = ISD::UINT_TO_FP;
4380         break;
4381     }
4382     if (OpToUse) break;
4383
4384     // Otherwise, try a larger type.
4385   }
4386
4387   // Okay, we found the operation and type to use.  Zero extend our input to the
4388   // desired type then run the operation on it.
4389   return DAG.getNode(OpToUse, DestVT,
4390                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
4391                                  NewInTy, LegalOp));
4392 }
4393
4394 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
4395 /// FP_TO_*INT operation of the specified operand when the target requests that
4396 /// we promote it.  At this point, we know that the result and operand types are
4397 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
4398 /// operation that returns a larger result.
4399 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
4400                                                       MVT::ValueType DestVT,
4401                                                       bool isSigned) {
4402   // First step, figure out the appropriate FP_TO*INT operation to use.
4403   MVT::ValueType NewOutTy = DestVT;
4404
4405   unsigned OpToUse = 0;
4406
4407   // Scan for the appropriate larger type to use.
4408   while (1) {
4409     NewOutTy = (MVT::ValueType)(NewOutTy+1);
4410     assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
4411
4412     // If the target supports FP_TO_SINT returning this type, use it.
4413     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
4414     default: break;
4415     case TargetLowering::Legal:
4416       if (!TLI.isTypeLegal(NewOutTy))
4417         break;  // Can't use this datatype.
4418       // FALL THROUGH.
4419     case TargetLowering::Custom:
4420       OpToUse = ISD::FP_TO_SINT;
4421       break;
4422     }
4423     if (OpToUse) break;
4424
4425     // If the target supports FP_TO_UINT of this type, use it.
4426     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
4427     default: break;
4428     case TargetLowering::Legal:
4429       if (!TLI.isTypeLegal(NewOutTy))
4430         break;  // Can't use this datatype.
4431       // FALL THROUGH.
4432     case TargetLowering::Custom:
4433       OpToUse = ISD::FP_TO_UINT;
4434       break;
4435     }
4436     if (OpToUse) break;
4437
4438     // Otherwise, try a larger type.
4439   }
4440
4441   // Okay, we found the operation and type to use.  Truncate the result of the
4442   // extended FP_TO_*INT operation to the desired size.
4443   return DAG.getNode(ISD::TRUNCATE, DestVT,
4444                      DAG.getNode(OpToUse, NewOutTy, LegalOp));
4445 }
4446
4447 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
4448 ///
4449 SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
4450   MVT::ValueType VT = Op.getValueType();
4451   MVT::ValueType SHVT = TLI.getShiftAmountTy();
4452   SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
4453   switch (VT) {
4454   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
4455   case MVT::i16:
4456     Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4457     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4458     return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
4459   case MVT::i32:
4460     Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
4461     Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4462     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4463     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
4464     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
4465     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
4466     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
4467     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
4468     return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
4469   case MVT::i64:
4470     Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
4471     Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
4472     Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
4473     Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4474     Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4475     Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
4476     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
4477     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
4478     Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
4479     Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
4480     Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
4481     Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
4482     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
4483     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
4484     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
4485     Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
4486     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
4487     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
4488     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
4489     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
4490     return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
4491   }
4492 }
4493
4494 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
4495 ///
4496 SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
4497   switch (Opc) {
4498   default: assert(0 && "Cannot expand this yet!");
4499   case ISD::CTPOP: {
4500     static const uint64_t mask[6] = {
4501       0x5555555555555555ULL, 0x3333333333333333ULL,
4502       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
4503       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
4504     };
4505     MVT::ValueType VT = Op.getValueType();
4506     MVT::ValueType ShVT = TLI.getShiftAmountTy();
4507     unsigned len = getSizeInBits(VT);
4508     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4509       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
4510       SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
4511       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4512       Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
4513                        DAG.getNode(ISD::AND, VT,
4514                                    DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
4515     }
4516     return Op;
4517   }
4518   case ISD::CTLZ: {
4519     // for now, we do this:
4520     // x = x | (x >> 1);
4521     // x = x | (x >> 2);
4522     // ...
4523     // x = x | (x >>16);
4524     // x = x | (x >>32); // for 64-bit input
4525     // return popcount(~x);
4526     //
4527     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
4528     MVT::ValueType VT = Op.getValueType();
4529     MVT::ValueType ShVT = TLI.getShiftAmountTy();
4530     unsigned len = getSizeInBits(VT);
4531     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4532       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4533       Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
4534     }
4535     Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
4536     return DAG.getNode(ISD::CTPOP, VT, Op);
4537   }
4538   case ISD::CTTZ: {
4539     // for now, we use: { return popcount(~x & (x - 1)); }
4540     // unless the target has ctlz but not ctpop, in which case we use:
4541     // { return 32 - nlz(~x & (x-1)); }
4542     // see also http://www.hackersdelight.org/HDcode/ntz.cc
4543     MVT::ValueType VT = Op.getValueType();
4544     SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
4545     SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
4546                        DAG.getNode(ISD::XOR, VT, Op, Tmp2),
4547                        DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
4548     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
4549     if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
4550         TLI.isOperationLegal(ISD::CTLZ, VT))
4551       return DAG.getNode(ISD::SUB, VT,
4552                          DAG.getConstant(getSizeInBits(VT), VT),
4553                          DAG.getNode(ISD::CTLZ, VT, Tmp3));
4554     return DAG.getNode(ISD::CTPOP, VT, Tmp3);
4555   }
4556   }
4557 }
4558
4559 /// ExpandOp - Expand the specified SDOperand into its two component pieces
4560 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
4561 /// LegalizeNodes map is filled in for any results that are not expanded, the
4562 /// ExpandedNodes map is filled in for any results that are expanded, and the
4563 /// Lo/Hi values are returned.
4564 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
4565   MVT::ValueType VT = Op.getValueType();
4566   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
4567   SDNode *Node = Op.Val;
4568   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
4569   assert(((MVT::isInteger(NVT) && NVT < VT) || MVT::isFloatingPoint(VT) ||
4570          VT == MVT::Vector) &&
4571          "Cannot expand to FP value or to larger int value!");
4572
4573   // See if we already expanded it.
4574   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4575     = ExpandedNodes.find(Op);
4576   if (I != ExpandedNodes.end()) {
4577     Lo = I->second.first;
4578     Hi = I->second.second;
4579     return;
4580   }
4581
4582   switch (Node->getOpcode()) {
4583   case ISD::CopyFromReg:
4584     assert(0 && "CopyFromReg must be legal!");
4585   default:
4586 #ifndef NDEBUG
4587     cerr << "NODE: "; Node->dump(); cerr << "\n";
4588 #endif
4589     assert(0 && "Do not know how to expand this operator!");
4590     abort();
4591   case ISD::UNDEF:
4592     NVT = TLI.getTypeToExpandTo(VT);
4593     Lo = DAG.getNode(ISD::UNDEF, NVT);
4594     Hi = DAG.getNode(ISD::UNDEF, NVT);
4595     break;
4596   case ISD::Constant: {
4597     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
4598     Lo = DAG.getConstant(Cst, NVT);
4599     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
4600     break;
4601   }
4602   case ISD::ConstantFP: {
4603     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
4604     Lo = ExpandConstantFP(CFP, false, DAG, TLI);
4605     if (getTypeAction(Lo.getValueType()) == Expand)
4606       ExpandOp(Lo, Lo, Hi);
4607     break;
4608   }
4609   case ISD::BUILD_PAIR:
4610     // Return the operands.
4611     Lo = Node->getOperand(0);
4612     Hi = Node->getOperand(1);
4613     break;
4614     
4615   case ISD::SIGN_EXTEND_INREG:
4616     ExpandOp(Node->getOperand(0), Lo, Hi);
4617     // sext_inreg the low part if needed.
4618     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
4619     
4620     // The high part gets the sign extension from the lo-part.  This handles
4621     // things like sextinreg V:i64 from i8.
4622     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4623                      DAG.getConstant(MVT::getSizeInBits(NVT)-1,
4624                                      TLI.getShiftAmountTy()));
4625     break;
4626
4627   case ISD::BSWAP: {
4628     ExpandOp(Node->getOperand(0), Lo, Hi);
4629     SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
4630     Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
4631     Lo = TempLo;
4632     break;
4633   }
4634     
4635   case ISD::CTPOP:
4636     ExpandOp(Node->getOperand(0), Lo, Hi);
4637     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
4638                      DAG.getNode(ISD::CTPOP, NVT, Lo),
4639                      DAG.getNode(ISD::CTPOP, NVT, Hi));
4640     Hi = DAG.getConstant(0, NVT);
4641     break;
4642
4643   case ISD::CTLZ: {
4644     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
4645     ExpandOp(Node->getOperand(0), Lo, Hi);
4646     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4647     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
4648     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
4649                                         ISD::SETNE);
4650     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
4651     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
4652
4653     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
4654     Hi = DAG.getConstant(0, NVT);
4655     break;
4656   }
4657
4658   case ISD::CTTZ: {
4659     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
4660     ExpandOp(Node->getOperand(0), Lo, Hi);
4661     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4662     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
4663     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
4664                                         ISD::SETNE);
4665     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
4666     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
4667
4668     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
4669     Hi = DAG.getConstant(0, NVT);
4670     break;
4671   }
4672
4673   case ISD::VAARG: {
4674     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4675     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4676     Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
4677     Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
4678
4679     // Remember that we legalized the chain.
4680     Hi = LegalizeOp(Hi);
4681     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
4682     if (!TLI.isLittleEndian())
4683       std::swap(Lo, Hi);
4684     break;
4685   }
4686     
4687   case ISD::LOAD: {
4688     LoadSDNode *LD = cast<LoadSDNode>(Node);
4689     SDOperand Ch  = LD->getChain();    // Legalize the chain.
4690     SDOperand Ptr = LD->getBasePtr();  // Legalize the pointer.
4691     ISD::LoadExtType ExtType = LD->getExtensionType();
4692
4693     if (ExtType == ISD::NON_EXTLOAD) {
4694       Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), LD->getSrcValueOffset());
4695       if (VT == MVT::f32 || VT == MVT::f64) {
4696         // f32->i32 or f64->i64 one to one expansion.
4697         // Remember that we legalized the chain.
4698         AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4699         // Recursively expand the new load.
4700         if (getTypeAction(NVT) == Expand)
4701           ExpandOp(Lo, Lo, Hi);
4702         break;
4703       }
4704
4705       // Increment the pointer to the other half.
4706       unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
4707       Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4708                         getIntPtrConstant(IncrementSize));
4709       // FIXME: This creates a bogus srcvalue!
4710       Hi = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), LD->getSrcValueOffset());
4711
4712       // Build a factor node to remember that this load is independent of the
4713       // other one.
4714       SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4715                                  Hi.getValue(1));
4716
4717       // Remember that we legalized the chain.
4718       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4719       if (!TLI.isLittleEndian())
4720         std::swap(Lo, Hi);
4721     } else {
4722       MVT::ValueType EVT = LD->getLoadedVT();
4723
4724       if (VT == MVT::f64 && EVT == MVT::f32) {
4725         // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
4726         SDOperand Load = DAG.getLoad(EVT, Ch, Ptr, LD->getSrcValue(),
4727                                      LD->getSrcValueOffset());
4728         // Remember that we legalized the chain.
4729         AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Load.getValue(1)));
4730         ExpandOp(DAG.getNode(ISD::FP_EXTEND, VT, Load), Lo, Hi);
4731         break;
4732       }
4733     
4734       if (EVT == NVT)
4735         Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(),
4736                          LD->getSrcValueOffset());
4737       else
4738         Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, LD->getSrcValue(),
4739                             LD->getSrcValueOffset(), EVT);
4740     
4741       // Remember that we legalized the chain.
4742       AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4743
4744       if (ExtType == ISD::SEXTLOAD) {
4745         // The high part is obtained by SRA'ing all but one of the bits of the
4746         // lo part.
4747         unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4748         Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4749                          DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
4750       } else if (ExtType == ISD::ZEXTLOAD) {
4751         // The high part is just a zero.
4752         Hi = DAG.getConstant(0, NVT);
4753       } else /* if (ExtType == ISD::EXTLOAD) */ {
4754         // The high part is undefined.
4755         Hi = DAG.getNode(ISD::UNDEF, NVT);
4756       }
4757     }
4758     break;
4759   }
4760   case ISD::AND:
4761   case ISD::OR:
4762   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
4763     SDOperand LL, LH, RL, RH;
4764     ExpandOp(Node->getOperand(0), LL, LH);
4765     ExpandOp(Node->getOperand(1), RL, RH);
4766     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
4767     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
4768     break;
4769   }
4770   case ISD::SELECT: {
4771     SDOperand LL, LH, RL, RH;
4772     ExpandOp(Node->getOperand(1), LL, LH);
4773     ExpandOp(Node->getOperand(2), RL, RH);
4774     if (getTypeAction(NVT) == Expand)
4775       NVT = TLI.getTypeToExpandTo(NVT);
4776     Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
4777     if (VT != MVT::f32)
4778       Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
4779     break;
4780   }
4781   case ISD::SELECT_CC: {
4782     SDOperand TL, TH, FL, FH;
4783     ExpandOp(Node->getOperand(2), TL, TH);
4784     ExpandOp(Node->getOperand(3), FL, FH);
4785     if (getTypeAction(NVT) == Expand)
4786       NVT = TLI.getTypeToExpandTo(NVT);
4787     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4788                      Node->getOperand(1), TL, FL, Node->getOperand(4));
4789     if (VT != MVT::f32)
4790       Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4791                        Node->getOperand(1), TH, FH, Node->getOperand(4));
4792     break;
4793   }
4794   case ISD::ANY_EXTEND:
4795     // The low part is any extension of the input (which degenerates to a copy).
4796     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
4797     // The high part is undefined.
4798     Hi = DAG.getNode(ISD::UNDEF, NVT);
4799     break;
4800   case ISD::SIGN_EXTEND: {
4801     // The low part is just a sign extension of the input (which degenerates to
4802     // a copy).
4803     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
4804
4805     // The high part is obtained by SRA'ing all but one of the bits of the lo
4806     // part.
4807     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4808     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4809                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
4810     break;
4811   }
4812   case ISD::ZERO_EXTEND:
4813     // The low part is just a zero extension of the input (which degenerates to
4814     // a copy).
4815     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4816
4817     // The high part is just a zero.
4818     Hi = DAG.getConstant(0, NVT);
4819     break;
4820     
4821   case ISD::BIT_CONVERT: {
4822     SDOperand Tmp;
4823     if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
4824       // If the target wants to, allow it to lower this itself.
4825       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4826       case Expand: assert(0 && "cannot expand FP!");
4827       case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
4828       case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
4829       }
4830       Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp), DAG);
4831     }
4832
4833     // f32 / f64 must be expanded to i32 / i64.
4834     if (VT == MVT::f32 || VT == MVT::f64) {
4835       Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
4836       if (getTypeAction(NVT) == Expand)
4837         ExpandOp(Lo, Lo, Hi);
4838       break;
4839     }
4840
4841     // If source operand will be expanded to the same type as VT, i.e.
4842     // i64 <- f64, i32 <- f32, expand the source operand instead.
4843     MVT::ValueType VT0 = Node->getOperand(0).getValueType();
4844     if (getTypeAction(VT0) == Expand && TLI.getTypeToTransformTo(VT0) == VT) {
4845       ExpandOp(Node->getOperand(0), Lo, Hi);
4846       break;
4847     }
4848
4849     // Turn this into a load/store pair by default.
4850     if (Tmp.Val == 0)
4851       Tmp = ExpandBIT_CONVERT(VT, Node->getOperand(0));
4852     
4853     ExpandOp(Tmp, Lo, Hi);
4854     break;
4855   }
4856
4857   case ISD::READCYCLECOUNTER:
4858     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
4859                  TargetLowering::Custom &&
4860            "Must custom expand ReadCycleCounter");
4861     Lo = TLI.LowerOperation(Op, DAG);
4862     assert(Lo.Val && "Node must be custom expanded!");
4863     Hi = Lo.getValue(1);
4864     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
4865                         LegalizeOp(Lo.getValue(2)));
4866     break;
4867
4868     // These operators cannot be expanded directly, emit them as calls to
4869     // library functions.
4870   case ISD::FP_TO_SINT: {
4871     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
4872       SDOperand Op;
4873       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4874       case Expand: assert(0 && "cannot expand FP!");
4875       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4876       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4877       }
4878
4879       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
4880
4881       // Now that the custom expander is done, expand the result, which is still
4882       // VT.
4883       if (Op.Val) {
4884         ExpandOp(Op, Lo, Hi);
4885         break;
4886       }
4887     }
4888
4889     RTLIB::Libcall LC;
4890     if (Node->getOperand(0).getValueType() == MVT::f32)
4891       LC = RTLIB::FPTOSINT_F32_I64;
4892     else
4893       LC = RTLIB::FPTOSINT_F64_I64;
4894     Lo = ExpandLibCall(TLI.getLibcallName(LC), Node,
4895                        false/*sign irrelevant*/, Hi);
4896     break;
4897   }
4898
4899   case ISD::FP_TO_UINT: {
4900     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
4901       SDOperand Op;
4902       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4903         case Expand: assert(0 && "cannot expand FP!");
4904         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4905         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4906       }
4907         
4908       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
4909
4910       // Now that the custom expander is done, expand the result.
4911       if (Op.Val) {
4912         ExpandOp(Op, Lo, Hi);
4913         break;
4914       }
4915     }
4916
4917     RTLIB::Libcall LC;
4918     if (Node->getOperand(0).getValueType() == MVT::f32)
4919       LC = RTLIB::FPTOUINT_F32_I64;
4920     else
4921       LC = RTLIB::FPTOUINT_F64_I64;
4922     Lo = ExpandLibCall(TLI.getLibcallName(LC), Node,
4923                        false/*sign irrelevant*/, Hi);
4924     break;
4925   }
4926
4927   case ISD::SHL: {
4928     // If the target wants custom lowering, do so.
4929     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4930     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
4931       SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
4932       Op = TLI.LowerOperation(Op, DAG);
4933       if (Op.Val) {
4934         // Now that the custom expander is done, expand the result, which is
4935         // still VT.
4936         ExpandOp(Op, Lo, Hi);
4937         break;
4938       }
4939     }
4940     
4941     // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit 
4942     // this X << 1 as X+X.
4943     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
4944       if (ShAmt->getValue() == 1 && TLI.isOperationLegal(ISD::ADDC, NVT) && 
4945           TLI.isOperationLegal(ISD::ADDE, NVT)) {
4946         SDOperand LoOps[2], HiOps[3];
4947         ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
4948         SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
4949         LoOps[1] = LoOps[0];
4950         Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
4951
4952         HiOps[1] = HiOps[0];
4953         HiOps[2] = Lo.getValue(1);
4954         Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
4955         break;
4956       }
4957     }
4958     
4959     // If we can emit an efficient shift operation, do so now.
4960     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4961       break;
4962
4963     // If this target supports SHL_PARTS, use it.
4964     TargetLowering::LegalizeAction Action =
4965       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
4966     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4967         Action == TargetLowering::Custom) {
4968       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4969       break;
4970     }
4971
4972     // Otherwise, emit a libcall.
4973     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SHL_I64), Node,
4974                        false/*left shift=unsigned*/, Hi);
4975     break;
4976   }
4977
4978   case ISD::SRA: {
4979     // If the target wants custom lowering, do so.
4980     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4981     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
4982       SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
4983       Op = TLI.LowerOperation(Op, DAG);
4984       if (Op.Val) {
4985         // Now that the custom expander is done, expand the result, which is
4986         // still VT.
4987         ExpandOp(Op, Lo, Hi);
4988         break;
4989       }
4990     }
4991     
4992     // If we can emit an efficient shift operation, do so now.
4993     if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
4994       break;
4995
4996     // If this target supports SRA_PARTS, use it.
4997     TargetLowering::LegalizeAction Action =
4998       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
4999     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
5000         Action == TargetLowering::Custom) {
5001       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
5002       break;
5003     }
5004
5005     // Otherwise, emit a libcall.
5006     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRA_I64), Node,
5007                        true/*ashr is signed*/, Hi);
5008     break;
5009   }
5010
5011   case ISD::SRL: {
5012     // If the target wants custom lowering, do so.
5013     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
5014     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
5015       SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
5016       Op = TLI.LowerOperation(Op, DAG);
5017       if (Op.Val) {
5018         // Now that the custom expander is done, expand the result, which is
5019         // still VT.
5020         ExpandOp(Op, Lo, Hi);
5021         break;
5022       }
5023     }
5024
5025     // If we can emit an efficient shift operation, do so now.
5026     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
5027       break;
5028
5029     // If this target supports SRL_PARTS, use it.
5030     TargetLowering::LegalizeAction Action =
5031       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
5032     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
5033         Action == TargetLowering::Custom) {
5034       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
5035       break;
5036     }
5037
5038     // Otherwise, emit a libcall.
5039     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRL_I64), Node,
5040                        false/*lshr is unsigned*/, Hi);
5041     break;
5042   }
5043
5044   case ISD::ADD:
5045   case ISD::SUB: {
5046     // If the target wants to custom expand this, let them.
5047     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
5048             TargetLowering::Custom) {
5049       Op = TLI.LowerOperation(Op, DAG);
5050       if (Op.Val) {
5051         ExpandOp(Op, Lo, Hi);
5052         break;
5053       }
5054     }
5055     
5056     // Expand the subcomponents.
5057     SDOperand LHSL, LHSH, RHSL, RHSH;
5058     ExpandOp(Node->getOperand(0), LHSL, LHSH);
5059     ExpandOp(Node->getOperand(1), RHSL, RHSH);
5060     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
5061     SDOperand LoOps[2], HiOps[3];
5062     LoOps[0] = LHSL;
5063     LoOps[1] = RHSL;
5064     HiOps[0] = LHSH;
5065     HiOps[1] = RHSH;
5066     if (Node->getOpcode() == ISD::ADD) {
5067       Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
5068       HiOps[2] = Lo.getValue(1);
5069       Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
5070     } else {
5071       Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
5072       HiOps[2] = Lo.getValue(1);
5073       Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
5074     }
5075     break;
5076   }
5077   case ISD::MUL: {
5078     // If the target wants to custom expand this, let them.
5079     if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
5080       SDOperand New = TLI.LowerOperation(Op, DAG);
5081       if (New.Val) {
5082         ExpandOp(New, Lo, Hi);
5083         break;
5084       }
5085     }
5086     
5087     bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
5088     bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
5089     if (HasMULHS || HasMULHU) {
5090       SDOperand LL, LH, RL, RH;
5091       ExpandOp(Node->getOperand(0), LL, LH);
5092       ExpandOp(Node->getOperand(1), RL, RH);
5093       unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
5094       // FIXME: Move this to the dag combiner.
5095       // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
5096       // extended the sign bit of the low half through the upper half, and if so
5097       // emit a MULHS instead of the alternate sequence that is valid for any
5098       // i64 x i64 multiply.
5099       if (HasMULHS &&
5100           // is RH an extension of the sign bit of RL?
5101           RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
5102           RH.getOperand(1).getOpcode() == ISD::Constant &&
5103           cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
5104           // is LH an extension of the sign bit of LL?
5105           LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
5106           LH.getOperand(1).getOpcode() == ISD::Constant &&
5107           cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
5108         // Low part:
5109         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
5110         // High part:
5111         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
5112         break;
5113       } else if (HasMULHU) {
5114         // Low part:
5115         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
5116         
5117         // High part:
5118         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
5119         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
5120         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
5121         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
5122         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
5123         break;
5124       }
5125     }
5126
5127     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::MUL_I64), Node,
5128                        false/*sign irrelevant*/, Hi);
5129     break;
5130   }
5131   case ISD::SDIV:
5132     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SDIV_I64), Node, true, Hi);
5133     break;
5134   case ISD::UDIV:
5135     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::UDIV_I64), Node, true, Hi);
5136     break;
5137   case ISD::SREM:
5138     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SREM_I64), Node, true, Hi);
5139     break;
5140   case ISD::UREM:
5141     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::UREM_I64), Node, true, Hi);
5142     break;
5143
5144   case ISD::FADD:
5145     Lo = ExpandLibCall(TLI.getLibcallName((VT == MVT::f32)
5146                                           ? RTLIB::ADD_F32 : RTLIB::ADD_F64),
5147                        Node, false, Hi);
5148     break;
5149   case ISD::FSUB:
5150     Lo = ExpandLibCall(TLI.getLibcallName((VT == MVT::f32)
5151                                           ? RTLIB::SUB_F32 : RTLIB::SUB_F64),
5152                        Node, false, Hi);
5153     break;
5154   case ISD::FMUL:
5155     Lo = ExpandLibCall(TLI.getLibcallName((VT == MVT::f32)
5156                                           ? RTLIB::MUL_F32 : RTLIB::MUL_F64),
5157                        Node, false, Hi);
5158     break;
5159   case ISD::FDIV:
5160     Lo = ExpandLibCall(TLI.getLibcallName((VT == MVT::f32)
5161                                           ? RTLIB::DIV_F32 : RTLIB::DIV_F64),
5162                        Node, false, Hi);
5163     break;
5164   case ISD::FP_EXTEND:
5165     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::FPEXT_F32_F64), Node, true,Hi);
5166     break;
5167   case ISD::FP_ROUND:
5168     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::FPROUND_F64_F32),Node,true,Hi);
5169     break;
5170   case ISD::FSQRT:
5171   case ISD::FSIN:
5172   case ISD::FCOS: {
5173     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5174     switch(Node->getOpcode()) {
5175     case ISD::FSQRT:
5176       LC = (VT == MVT::f32) ? RTLIB::SQRT_F32 : RTLIB::SQRT_F64;
5177       break;
5178     case ISD::FSIN:
5179       LC = (VT == MVT::f32) ? RTLIB::SIN_F32 : RTLIB::SIN_F64;
5180       break;
5181     case ISD::FCOS:
5182       LC = (VT == MVT::f32) ? RTLIB::COS_F32 : RTLIB::COS_F64;
5183       break;
5184     default: assert(0 && "Unreachable!");
5185     }
5186     Lo = ExpandLibCall(TLI.getLibcallName(LC), Node, false, Hi);
5187     break;
5188   }
5189   case ISD::FABS: {
5190     SDOperand Mask = (VT == MVT::f64)
5191       ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
5192       : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
5193     Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
5194     Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
5195     Lo = DAG.getNode(ISD::AND, NVT, Lo, Mask);
5196     if (getTypeAction(NVT) == Expand)
5197       ExpandOp(Lo, Lo, Hi);
5198     break;
5199   }
5200   case ISD::FNEG: {
5201     SDOperand Mask = (VT == MVT::f64)
5202       ? DAG.getConstantFP(BitsToDouble(1ULL << 63), VT)
5203       : DAG.getConstantFP(BitsToFloat(1U << 31), VT);
5204     Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
5205     Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
5206     Lo = DAG.getNode(ISD::XOR, NVT, Lo, Mask);
5207     if (getTypeAction(NVT) == Expand)
5208       ExpandOp(Lo, Lo, Hi);
5209     break;
5210   }
5211   case ISD::FCOPYSIGN: {
5212     Lo = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
5213     if (getTypeAction(NVT) == Expand)
5214       ExpandOp(Lo, Lo, Hi);
5215     break;
5216   }
5217   case ISD::SINT_TO_FP:
5218   case ISD::UINT_TO_FP: {
5219     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
5220     MVT::ValueType SrcVT = Node->getOperand(0).getValueType();
5221     RTLIB::Libcall LC;
5222     if (Node->getOperand(0).getValueType() == MVT::i64) {
5223       if (VT == MVT::f32)
5224         LC = isSigned ? RTLIB::SINTTOFP_I64_F32 : RTLIB::UINTTOFP_I64_F32;
5225       else
5226         LC = isSigned ? RTLIB::SINTTOFP_I64_F64 : RTLIB::UINTTOFP_I64_F64;
5227     } else {
5228       if (VT == MVT::f32)
5229         LC = isSigned ? RTLIB::SINTTOFP_I32_F32 : RTLIB::UINTTOFP_I32_F32;
5230       else
5231         LC = isSigned ? RTLIB::SINTTOFP_I32_F64 : RTLIB::UINTTOFP_I32_F64;
5232     }
5233
5234     // Promote the operand if needed.
5235     if (getTypeAction(SrcVT) == Promote) {
5236       SDOperand Tmp = PromoteOp(Node->getOperand(0));
5237       Tmp = isSigned
5238         ? DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp.getValueType(), Tmp,
5239                       DAG.getValueType(SrcVT))
5240         : DAG.getZeroExtendInReg(Tmp, SrcVT);
5241       Node = DAG.UpdateNodeOperands(Op, Tmp).Val;
5242     }
5243     Lo = ExpandLibCall(TLI.getLibcallName(LC), Node, isSigned, Hi);
5244     break;
5245   }
5246   }
5247
5248   // Make sure the resultant values have been legalized themselves, unless this
5249   // is a type that requires multi-step expansion.
5250   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
5251     Lo = LegalizeOp(Lo);
5252     if (Hi.Val)
5253       // Don't legalize the high part if it is expanded to a single node.
5254       Hi = LegalizeOp(Hi);
5255   }
5256
5257   // Remember in a map if the values will be reused later.
5258   bool isNew =
5259     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
5260   assert(isNew && "Value already expanded?!?");
5261 }
5262
5263 /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
5264 /// two smaller values of MVT::Vector type.
5265 void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
5266                                          SDOperand &Hi) {
5267   assert(Op.getValueType() == MVT::Vector && "Cannot split non-vector type!");
5268   SDNode *Node = Op.Val;
5269   unsigned NumElements = cast<ConstantSDNode>(*(Node->op_end()-2))->getValue();
5270   assert(NumElements > 1 && "Cannot split a single element vector!");
5271   unsigned NewNumElts = NumElements/2;
5272   SDOperand NewNumEltsNode = DAG.getConstant(NewNumElts, MVT::i32);
5273   SDOperand TypeNode = *(Node->op_end()-1);
5274   
5275   // See if we already split it.
5276   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
5277     = SplitNodes.find(Op);
5278   if (I != SplitNodes.end()) {
5279     Lo = I->second.first;
5280     Hi = I->second.second;
5281     return;
5282   }
5283   
5284   switch (Node->getOpcode()) {
5285   default: 
5286 #ifndef NDEBUG
5287     Node->dump();
5288 #endif
5289     assert(0 && "Unhandled operation in SplitVectorOp!");
5290   case ISD::VBUILD_VECTOR: {
5291     SmallVector<SDOperand, 8> LoOps(Node->op_begin(), 
5292                                     Node->op_begin()+NewNumElts);
5293     LoOps.push_back(NewNumEltsNode);
5294     LoOps.push_back(TypeNode);
5295     Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &LoOps[0], LoOps.size());
5296
5297     SmallVector<SDOperand, 8> HiOps(Node->op_begin()+NewNumElts, 
5298                                     Node->op_end()-2);
5299     HiOps.push_back(NewNumEltsNode);
5300     HiOps.push_back(TypeNode);
5301     Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &HiOps[0], HiOps.size());
5302     break;
5303   }
5304   case ISD::VADD:
5305   case ISD::VSUB:
5306   case ISD::VMUL:
5307   case ISD::VSDIV:
5308   case ISD::VUDIV:
5309   case ISD::VAND:
5310   case ISD::VOR:
5311   case ISD::VXOR: {
5312     SDOperand LL, LH, RL, RH;
5313     SplitVectorOp(Node->getOperand(0), LL, LH);
5314     SplitVectorOp(Node->getOperand(1), RL, RH);
5315     
5316     Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL,
5317                      NewNumEltsNode, TypeNode);
5318     Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH,
5319                      NewNumEltsNode, TypeNode);
5320     break;
5321   }
5322   case ISD::VLOAD: {
5323     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
5324     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
5325     MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
5326     
5327     Lo = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
5328     unsigned IncrementSize = NewNumElts * MVT::getSizeInBits(EVT)/8;
5329     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
5330                       getIntPtrConstant(IncrementSize));
5331     // FIXME: This creates a bogus srcvalue!
5332     Hi = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
5333     
5334     // Build a factor node to remember that this load is independent of the
5335     // other one.
5336     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
5337                                Hi.getValue(1));
5338     
5339     // Remember that we legalized the chain.
5340     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
5341     break;
5342   }
5343   case ISD::VBIT_CONVERT: {
5344     // We know the result is a vector.  The input may be either a vector or a
5345     // scalar value.
5346     if (Op.getOperand(0).getValueType() != MVT::Vector) {
5347       // Lower to a store/load.  FIXME: this could be improved probably.
5348       SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
5349
5350       SDOperand St = DAG.getStore(DAG.getEntryNode(),
5351                                   Op.getOperand(0), Ptr, NULL, 0);
5352       MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
5353       St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
5354       SplitVectorOp(St, Lo, Hi);
5355     } else {
5356       // If the input is a vector type, we have to either scalarize it, pack it
5357       // or convert it based on whether the input vector type is legal.
5358       SDNode *InVal = Node->getOperand(0).Val;
5359       unsigned NumElems =
5360         cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
5361       MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
5362
5363       // If the input is from a single element vector, scalarize the vector,
5364       // then treat like a scalar.
5365       if (NumElems == 1) {
5366         SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
5367         Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
5368                              Op.getOperand(1), Op.getOperand(2));
5369         SplitVectorOp(Scalar, Lo, Hi);
5370       } else {
5371         // Split the input vector.
5372         SplitVectorOp(Op.getOperand(0), Lo, Hi);
5373
5374         // Convert each of the pieces now.
5375         Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
5376                          NewNumEltsNode, TypeNode);
5377         Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
5378                          NewNumEltsNode, TypeNode);
5379       }
5380       break;
5381     }
5382   }
5383   }
5384       
5385   // Remember in a map if the values will be reused later.
5386   bool isNew =
5387     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
5388   assert(isNew && "Value already expanded?!?");
5389 }
5390
5391
5392 /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
5393 /// equivalent operation that returns a scalar (e.g. F32) or packed value
5394 /// (e.g. MVT::V4F32).  When this is called, we know that PackedVT is the right
5395 /// type for the result.
5396 SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op, 
5397                                              MVT::ValueType NewVT) {
5398   assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
5399   SDNode *Node = Op.Val;
5400   
5401   // See if we already packed it.
5402   std::map<SDOperand, SDOperand>::iterator I = PackedNodes.find(Op);
5403   if (I != PackedNodes.end()) return I->second;
5404   
5405   SDOperand Result;
5406   switch (Node->getOpcode()) {
5407   default: 
5408 #ifndef NDEBUG
5409     Node->dump(); cerr << "\n";
5410 #endif
5411     assert(0 && "Unknown vector operation in PackVectorOp!");
5412   case ISD::VADD:
5413   case ISD::VSUB:
5414   case ISD::VMUL:
5415   case ISD::VSDIV:
5416   case ISD::VUDIV:
5417   case ISD::VAND:
5418   case ISD::VOR:
5419   case ISD::VXOR:
5420     Result = DAG.getNode(getScalarizedOpcode(Node->getOpcode(), NewVT),
5421                          NewVT, 
5422                          PackVectorOp(Node->getOperand(0), NewVT),
5423                          PackVectorOp(Node->getOperand(1), NewVT));
5424     break;
5425   case ISD::VLOAD: {
5426     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
5427     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
5428     
5429     SrcValueSDNode *SV = cast<SrcValueSDNode>(Node->getOperand(2));
5430     Result = DAG.getLoad(NewVT, Ch, Ptr, SV->getValue(), SV->getOffset());
5431     
5432     // Remember that we legalized the chain.
5433     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
5434     break;
5435   }
5436   case ISD::VBUILD_VECTOR:
5437     if (Node->getOperand(0).getValueType() == NewVT) {
5438       // Returning a scalar?
5439       Result = Node->getOperand(0);
5440     } else {
5441       // Returning a BUILD_VECTOR?
5442       
5443       // If all elements of the build_vector are undefs, return an undef.
5444       bool AllUndef = true;
5445       for (unsigned i = 0, e = Node->getNumOperands()-2; i != e; ++i)
5446         if (Node->getOperand(i).getOpcode() != ISD::UNDEF) {
5447           AllUndef = false;
5448           break;
5449         }
5450       if (AllUndef) {
5451         Result = DAG.getNode(ISD::UNDEF, NewVT);
5452       } else {
5453         Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Node->op_begin(),
5454                              Node->getNumOperands()-2);
5455       }
5456     }
5457     break;
5458   case ISD::VINSERT_VECTOR_ELT:
5459     if (!MVT::isVector(NewVT)) {
5460       // Returning a scalar?  Must be the inserted element.
5461       Result = Node->getOperand(1);
5462     } else {
5463       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT,
5464                            PackVectorOp(Node->getOperand(0), NewVT),
5465                            Node->getOperand(1), Node->getOperand(2));
5466     }
5467     break;
5468   case ISD::VVECTOR_SHUFFLE:
5469     if (!MVT::isVector(NewVT)) {
5470       // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
5471       SDOperand EltNum = Node->getOperand(2).getOperand(0);
5472       if (cast<ConstantSDNode>(EltNum)->getValue())
5473         Result = PackVectorOp(Node->getOperand(1), NewVT);
5474       else
5475         Result = PackVectorOp(Node->getOperand(0), NewVT);
5476     } else {
5477       // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
5478       // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
5479       std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
5480                                          Node->getOperand(2).Val->op_end()-2);
5481       MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
5482       SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT,
5483                                  Node->getOperand(2).Val->op_begin(),
5484                                  Node->getOperand(2).Val->getNumOperands()-2);
5485       
5486       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
5487                            PackVectorOp(Node->getOperand(0), NewVT),
5488                            PackVectorOp(Node->getOperand(1), NewVT), BV);
5489     }
5490     break;
5491   case ISD::VBIT_CONVERT:
5492     if (Op.getOperand(0).getValueType() != MVT::Vector)
5493       Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
5494     else {
5495       // If the input is a vector type, we have to either scalarize it, pack it
5496       // or convert it based on whether the input vector type is legal.
5497       SDNode *InVal = Node->getOperand(0).Val;
5498       unsigned NumElems =
5499         cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
5500       MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
5501         
5502       // Figure out if there is a Packed type corresponding to this Vector
5503       // type.  If so, convert to the packed type.
5504       MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
5505       if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
5506         // Turn this into a bit convert of the packed input.
5507         Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
5508                              PackVectorOp(Node->getOperand(0), TVT));
5509         break;
5510       } else if (NumElems == 1) {
5511         // Turn this into a bit convert of the scalar input.
5512         Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
5513                              PackVectorOp(Node->getOperand(0), EVT));
5514         break;
5515       } else {
5516         // FIXME: UNIMP!
5517         assert(0 && "Cast from unsupported vector type not implemented yet!");
5518       }
5519     }
5520     break;
5521   case ISD::VSELECT:
5522     Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
5523                          PackVectorOp(Op.getOperand(1), NewVT),
5524                          PackVectorOp(Op.getOperand(2), NewVT));
5525     break;
5526   }
5527
5528   if (TLI.isTypeLegal(NewVT))
5529     Result = LegalizeOp(Result);
5530   bool isNew = PackedNodes.insert(std::make_pair(Op, Result)).second;
5531   assert(isNew && "Value already packed?");
5532   return Result;
5533 }
5534
5535
5536 // SelectionDAG::Legalize - This is the entry point for the file.
5537 //
5538 void SelectionDAG::Legalize() {
5539   if (ViewLegalizeDAGs) viewGraph();
5540
5541   /// run - This is the main entry point to this class.
5542   ///
5543   SelectionDAGLegalize(*this).LegalizeDAG();
5544 }
5545