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