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