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