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