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