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