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