e6585c2d5deebfe4226fce29ae3002d73c66e825
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::Legalize method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/Target/TargetLowering.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Target/TargetOptions.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/CommandLine.h"
24 #include <iostream>
25 #include <map>
26 using namespace llvm;
27
28 #ifndef NDEBUG
29 static cl::opt<bool>
30 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
31                  cl::desc("Pop up a window to show dags before legalize"));
32 #else
33 static const bool ViewLegalizeDAGs = 0;
34 #endif
35
36 //===----------------------------------------------------------------------===//
37 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
38 /// hacks on it until the target machine can handle it.  This involves
39 /// eliminating value sizes the machine cannot handle (promoting small sizes to
40 /// large sizes or splitting up large values into small values) as well as
41 /// eliminating operations the machine cannot handle.
42 ///
43 /// This code also does a small amount of optimization and recognition of idioms
44 /// as part of its processing.  For example, if a target does not support a
45 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
46 /// will attempt merge setcc and brc instructions into brcc's.
47 ///
48 namespace {
49 class SelectionDAGLegalize {
50   TargetLowering &TLI;
51   SelectionDAG &DAG;
52
53   // Libcall insertion helpers.
54   
55   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
56   /// legalized.  We use this to ensure that calls are properly serialized
57   /// against each other, including inserted libcalls.
58   SDOperand LastCALLSEQ_END;
59   
60   /// IsLegalizingCall - This member is used *only* for purposes of providing
61   /// helpful assertions that a libcall isn't created while another call is 
62   /// being legalized (which could lead to non-serialized call sequences).
63   bool IsLegalizingCall;
64   
65   enum LegalizeAction {
66     Legal,      // The target natively supports this operation.
67     Promote,    // This operation should be executed in a larger type.
68     Expand,     // Try to expand this to other ops, otherwise use a libcall.
69   };
70   
71   /// ValueTypeActions - This is a bitvector that contains two bits for each
72   /// value type, where the two bits correspond to the LegalizeAction enum.
73   /// This can be queried with "getTypeAction(VT)".
74   TargetLowering::ValueTypeActionImpl ValueTypeActions;
75
76   /// LegalizedNodes - For nodes that are of legal width, and that have more
77   /// than one use, this map indicates what regularized operand to use.  This
78   /// allows us to avoid legalizing the same thing more than once.
79   std::map<SDOperand, SDOperand> LegalizedNodes;
80
81   /// PromotedNodes - For nodes that are below legal width, and that have more
82   /// than one use, this map indicates what promoted value to use.  This allows
83   /// us to avoid promoting the same thing more than once.
84   std::map<SDOperand, SDOperand> PromotedNodes;
85
86   /// ExpandedNodes - For nodes that need to be expanded this map indicates
87   /// which which operands are the expanded version of the input.  This allows
88   /// us to avoid expanding the same node more than once.
89   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
90
91   /// SplitNodes - For vector nodes that need to be split, this map indicates
92   /// which which operands are the split version of the input.  This allows us
93   /// to avoid splitting the same node more than once.
94   std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
95   
96   /// PackedNodes - For nodes that need to be packed from MVT::Vector types to
97   /// concrete packed types, this contains the mapping of ones we have already
98   /// processed to the result.
99   std::map<SDOperand, SDOperand> PackedNodes;
100   
101   void AddLegalizedOperand(SDOperand From, SDOperand To) {
102     LegalizedNodes.insert(std::make_pair(From, To));
103     // If someone requests legalization of the new node, return itself.
104     if (From != To)
105       LegalizedNodes.insert(std::make_pair(To, To));
106   }
107   void AddPromotedOperand(SDOperand From, SDOperand To) {
108     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
109     assert(isNew && "Got into the map somehow?");
110     // If someone requests legalization of the new node, return itself.
111     LegalizedNodes.insert(std::make_pair(To, To));
112   }
113
114 public:
115
116   SelectionDAGLegalize(SelectionDAG &DAG);
117
118   /// getTypeAction - Return how we should legalize values of this type, either
119   /// it is already legal or we need to expand it into multiple registers of
120   /// smaller integer type, or we need to promote it to a larger type.
121   LegalizeAction getTypeAction(MVT::ValueType VT) const {
122     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
123   }
124
125   /// isTypeLegal - Return true if this type is legal on this target.
126   ///
127   bool isTypeLegal(MVT::ValueType VT) const {
128     return getTypeAction(VT) == Legal;
129   }
130
131   void LegalizeDAG();
132
133 private:
134   /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
135   /// appropriate for its type.
136   void HandleOp(SDOperand Op);
137     
138   /// LegalizeOp - We know that the specified value has a legal type.
139   /// Recursively ensure that the operands have legal types, then return the
140   /// result.
141   SDOperand LegalizeOp(SDOperand O);
142   
143   /// PromoteOp - Given an operation that produces a value in an invalid type,
144   /// promote it to compute the value into a larger type.  The produced value
145   /// will have the correct bits for the low portion of the register, but no
146   /// guarantee is made about the top bits: it may be zero, sign-extended, or
147   /// garbage.
148   SDOperand PromoteOp(SDOperand O);
149
150   /// ExpandOp - Expand the specified SDOperand into its two component pieces
151   /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
152   /// the LegalizeNodes map is filled in for any results that are not expanded,
153   /// the ExpandedNodes map is filled in for any results that are expanded, and
154   /// the Lo/Hi values are returned.   This applies to integer types and Vector
155   /// types.
156   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
157
158   /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
159   /// two smaller values of MVT::Vector type.
160   void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
161   
162   /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
163   /// equivalent operation that returns a packed value (e.g. MVT::V4F32).  When
164   /// this is called, we know that PackedVT is the right type for the result and
165   /// we know that this type is legal for the target.
166   SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
167   
168   /// isShuffleLegal - Return true if a vector shuffle is legal with the
169   /// specified mask and type.  Targets can specify exactly which masks they
170   /// support and the code generator is tasked with not creating illegal masks.
171   ///
172   /// Note that this will also return true for shuffles that are promoted to a
173   /// different type.
174   ///
175   /// If this is a legal shuffle, this method returns the (possibly promoted)
176   /// build_vector Mask.  If it's not a legal shuffle, it returns null.
177   SDNode *isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const;
178   
179   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
180
181   void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
182     
183   SDOperand CreateStackTemporary(MVT::ValueType VT);
184
185   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
186                           SDOperand &Hi);
187   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
188                           SDOperand Source);
189
190   SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
191   SDOperand ExpandBUILD_VECTOR(SDNode *Node);
192   SDOperand ExpandSCALAR_TO_VECTOR(SDNode *Node);
193   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
194                                  SDOperand LegalOp,
195                                  MVT::ValueType DestVT);
196   SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
197                                   bool isSigned);
198   SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
199                                   bool isSigned);
200
201   SDOperand ExpandBSWAP(SDOperand Op);
202   SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
203   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
204                    SDOperand &Lo, SDOperand &Hi);
205   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
206                         SDOperand &Lo, SDOperand &Hi);
207
208   SDOperand LowerVEXTRACT_VECTOR_ELT(SDOperand Op);
209   SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
210   
211   SDOperand getIntPtrConstant(uint64_t Val) {
212     return DAG.getConstant(Val, TLI.getPointerTy());
213   }
214 };
215 }
216
217 /// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
218 /// specified mask and type.  Targets can specify exactly which masks they
219 /// support and the code generator is tasked with not creating illegal masks.
220 ///
221 /// Note that this will also return true for shuffles that are promoted to a
222 /// different type.
223 SDNode *SelectionDAGLegalize::isShuffleLegal(MVT::ValueType VT, 
224                                              SDOperand Mask) const {
225   switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
226   default: return 0;
227   case TargetLowering::Legal:
228   case TargetLowering::Custom:
229     break;
230   case TargetLowering::Promote: {
231     // If this is promoted to a different type, convert the shuffle mask and
232     // ask if it is legal in the promoted type!
233     MVT::ValueType NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
234
235     // If we changed # elements, change the shuffle mask.
236     unsigned NumEltsGrowth =
237       MVT::getVectorNumElements(NVT) / MVT::getVectorNumElements(VT);
238     assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
239     if (NumEltsGrowth > 1) {
240       // Renumber the elements.
241       std::vector<SDOperand> Ops;
242       for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
243         SDOperand InOp = Mask.getOperand(i);
244         for (unsigned j = 0; j != NumEltsGrowth; ++j) {
245           if (InOp.getOpcode() == ISD::UNDEF)
246             Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
247           else {
248             unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
249             Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
250           }
251         }
252       }
253       Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, Ops);
254     }
255     VT = NVT;
256     break;
257   }
258   }
259   return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
260 }
261
262 /// getScalarizedOpcode - Return the scalar opcode that corresponds to the
263 /// specified vector opcode.
264 static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
265   switch (VecOp) {
266   default: assert(0 && "Don't know how to scalarize this opcode!");
267   case ISD::VADD:  return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
268   case ISD::VSUB:  return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
269   case ISD::VMUL:  return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
270   case ISD::VSDIV: return MVT::isInteger(VT) ? ISD::SDIV: ISD::FDIV;
271   case ISD::VUDIV: return MVT::isInteger(VT) ? ISD::UDIV: ISD::FDIV;
272   case ISD::VAND:  return MVT::isInteger(VT) ? ISD::AND : 0;
273   case ISD::VOR:   return MVT::isInteger(VT) ? ISD::OR  : 0;
274   case ISD::VXOR:  return MVT::isInteger(VT) ? ISD::XOR : 0;
275   }
276 }
277
278 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
279   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
280     ValueTypeActions(TLI.getValueTypeActions()) {
281   assert(MVT::LAST_VALUETYPE <= 32 &&
282          "Too many value types for ValueTypeActions to hold!");
283 }
284
285 /// ComputeTopDownOrdering - Add the specified node to the Order list if it has
286 /// not been visited yet and if all of its operands have already been visited.
287 static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
288                                    std::map<SDNode*, unsigned> &Visited) {
289   if (++Visited[N] != N->getNumOperands())
290     return;  // Haven't visited all operands yet
291   
292   Order.push_back(N);
293   
294   if (N->hasOneUse()) { // Tail recurse in common case.
295     ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
296     return;
297   }
298   
299   // Now that we have N in, add anything that uses it if all of their operands
300   // are now done.
301   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
302     ComputeTopDownOrdering(*UI, Order, Visited);
303 }
304
305
306 void SelectionDAGLegalize::LegalizeDAG() {
307   LastCALLSEQ_END = DAG.getEntryNode();
308   IsLegalizingCall = false;
309   
310   // The legalize process is inherently a bottom-up recursive process (users
311   // legalize their uses before themselves).  Given infinite stack space, we
312   // could just start legalizing on the root and traverse the whole graph.  In
313   // practice however, this causes us to run out of stack space on large basic
314   // blocks.  To avoid this problem, compute an ordering of the nodes where each
315   // node is only legalized after all of its operands are legalized.
316   std::map<SDNode*, unsigned> Visited;
317   std::vector<SDNode*> Order;
318   
319   // Compute ordering from all of the leaves in the graphs, those (like the
320   // entry node) that have no operands.
321   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
322        E = DAG.allnodes_end(); I != E; ++I) {
323     if (I->getNumOperands() == 0) {
324       Visited[I] = 0 - 1U;
325       ComputeTopDownOrdering(I, Order, Visited);
326     }
327   }
328   
329   assert(Order.size() == Visited.size() &&
330          Order.size() == 
331             (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
332          "Error: DAG is cyclic!");
333   Visited.clear();
334   
335   for (unsigned i = 0, e = Order.size(); i != e; ++i)
336     HandleOp(SDOperand(Order[i], 0));
337
338   // Finally, it's possible the root changed.  Get the new root.
339   SDOperand OldRoot = DAG.getRoot();
340   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
341   DAG.setRoot(LegalizedNodes[OldRoot]);
342
343   ExpandedNodes.clear();
344   LegalizedNodes.clear();
345   PromotedNodes.clear();
346   SplitNodes.clear();
347   PackedNodes.clear();
348
349   // Remove dead nodes now.
350   DAG.RemoveDeadNodes(OldRoot.Val);
351 }
352
353
354 /// FindCallEndFromCallStart - Given a chained node that is part of a call
355 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
356 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
357   if (Node->getOpcode() == ISD::CALLSEQ_END)
358     return Node;
359   if (Node->use_empty())
360     return 0;   // No CallSeqEnd
361   
362   // The chain is usually at the end.
363   SDOperand TheChain(Node, Node->getNumValues()-1);
364   if (TheChain.getValueType() != MVT::Other) {
365     // Sometimes it's at the beginning.
366     TheChain = SDOperand(Node, 0);
367     if (TheChain.getValueType() != MVT::Other) {
368       // Otherwise, hunt for it.
369       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
370         if (Node->getValueType(i) == MVT::Other) {
371           TheChain = SDOperand(Node, i);
372           break;
373         }
374           
375       // Otherwise, we walked into a node without a chain.  
376       if (TheChain.getValueType() != MVT::Other)
377         return 0;
378     }
379   }
380   
381   for (SDNode::use_iterator UI = Node->use_begin(),
382        E = Node->use_end(); UI != E; ++UI) {
383     
384     // Make sure to only follow users of our token chain.
385     SDNode *User = *UI;
386     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
387       if (User->getOperand(i) == TheChain)
388         if (SDNode *Result = FindCallEndFromCallStart(User))
389           return Result;
390   }
391   return 0;
392 }
393
394 /// FindCallStartFromCallEnd - Given a chained node that is part of a call 
395 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
396 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
397   assert(Node && "Didn't find callseq_start for a call??");
398   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
399   
400   assert(Node->getOperand(0).getValueType() == MVT::Other &&
401          "Node doesn't have a token chain argument!");
402   return FindCallStartFromCallEnd(Node->getOperand(0).Val);
403 }
404
405 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
406 /// see if any uses can reach Dest.  If no dest operands can get to dest, 
407 /// legalize them, legalize ourself, and return false, otherwise, return true.
408 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, 
409                                                         SDNode *Dest) {
410   if (N == Dest) return true;  // N certainly leads to Dest :)
411   
412   // If the first result of this node has been already legalized, then it cannot
413   // reach N.
414   switch (getTypeAction(N->getValueType(0))) {
415   case Legal: 
416     if (LegalizedNodes.count(SDOperand(N, 0))) return false;
417     break;
418   case Promote:
419     if (PromotedNodes.count(SDOperand(N, 0))) return false;
420     break;
421   case Expand:
422     if (ExpandedNodes.count(SDOperand(N, 0))) return false;
423     break;
424   }
425   
426   // Okay, this node has not already been legalized.  Check and legalize all
427   // operands.  If none lead to Dest, then we can legalize this node.
428   bool OperandsLeadToDest = false;
429   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
430     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
431       LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest);
432
433   if (OperandsLeadToDest) return true;
434
435   // Okay, this node looks safe, legalize it and return false.
436   switch (getTypeAction(N->getValueType(0))) {
437   case Legal:
438     LegalizeOp(SDOperand(N, 0));
439     break;
440   case Promote:
441     PromoteOp(SDOperand(N, 0));
442     break;
443   case Expand: {
444     SDOperand X, Y;
445     ExpandOp(SDOperand(N, 0), X, Y);
446     break;
447   }
448   }
449   return false;
450 }
451
452 /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
453 /// appropriate for its type.
454 void SelectionDAGLegalize::HandleOp(SDOperand Op) {
455   switch (getTypeAction(Op.getValueType())) {
456   default: assert(0 && "Bad type action!");
457   case Legal:   LegalizeOp(Op); break;
458   case Promote: PromoteOp(Op);  break;
459   case Expand:
460     if (Op.getValueType() != MVT::Vector) {
461       SDOperand X, Y;
462       ExpandOp(Op, X, Y);
463     } else {
464       SDNode *N = Op.Val;
465       unsigned NumOps = N->getNumOperands();
466       unsigned NumElements =
467         cast<ConstantSDNode>(N->getOperand(NumOps-2))->getValue();
468       MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(NumOps-1))->getVT();
469       MVT::ValueType PackedVT = getVectorType(EVT, NumElements);
470       if (PackedVT != MVT::Other && TLI.isTypeLegal(PackedVT)) {
471         // In the common case, this is a legal vector type, convert it to the
472         // packed operation and type now.
473         PackVectorOp(Op, PackedVT);
474       } else if (NumElements == 1) {
475         // Otherwise, if this is a single element vector, convert it to a
476         // scalar operation.
477         PackVectorOp(Op, EVT);
478       } else {
479         // Otherwise, this is a multiple element vector that isn't supported.
480         // Split it in half and legalize both parts.
481         SDOperand X, Y;
482         SplitVectorOp(Op, X, Y);
483       }
484     }
485     break;
486   }
487 }
488
489
490 /// LegalizeOp - We know that the specified value has a legal type.
491 /// Recursively ensure that the operands have legal types, then return the
492 /// result.
493 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
494   assert(isTypeLegal(Op.getValueType()) &&
495          "Caller should expand or promote operands that are not legal!");
496   SDNode *Node = Op.Val;
497
498   // If this operation defines any values that cannot be represented in a
499   // register on this target, make sure to expand or promote them.
500   if (Node->getNumValues() > 1) {
501     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
502       if (getTypeAction(Node->getValueType(i)) != Legal) {
503         HandleOp(Op.getValue(i));
504         assert(LegalizedNodes.count(Op) &&
505                "Handling didn't add legal operands!");
506         return LegalizedNodes[Op];
507       }
508   }
509
510   // Note that LegalizeOp may be reentered even from single-use nodes, which
511   // means that we always must cache transformed nodes.
512   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
513   if (I != LegalizedNodes.end()) return I->second;
514
515   SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
516   SDOperand Result = Op;
517   bool isCustom = false;
518   
519   switch (Node->getOpcode()) {
520   case ISD::FrameIndex:
521   case ISD::EntryToken:
522   case ISD::Register:
523   case ISD::BasicBlock:
524   case ISD::TargetFrameIndex:
525   case ISD::TargetConstant:
526   case ISD::TargetConstantFP:
527   case ISD::TargetConstantPool:
528   case ISD::TargetGlobalAddress:
529   case ISD::TargetExternalSymbol:
530   case ISD::VALUETYPE:
531   case ISD::SRCVALUE:
532   case ISD::STRING:
533   case ISD::CONDCODE:
534     // Primitives must all be legal.
535     assert(TLI.isOperationLegal(Node->getValueType(0), Node->getValueType(0)) &&
536            "This must be legal!");
537     break;
538   default:
539     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
540       // If this is a target node, legalize it by legalizing the operands then
541       // passing it through.
542       std::vector<SDOperand> Ops;
543       bool Changed = false;
544       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
545         Ops.push_back(LegalizeOp(Node->getOperand(i)));
546         Changed = Changed || Node->getOperand(i) != Ops.back();
547       }
548       if (Changed)
549         if (Node->getNumValues() == 1)
550           Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
551         else {
552           std::vector<MVT::ValueType> VTs(Node->value_begin(),
553                                           Node->value_end());
554           Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
555         }
556
557       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
558         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
559       return Result.getValue(Op.ResNo);
560     }
561     // Otherwise this is an unhandled builtin node.  splat.
562     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
563     assert(0 && "Do not know how to legalize this operator!");
564     abort();
565   case ISD::GlobalAddress:
566   case ISD::ExternalSymbol:
567   case ISD::ConstantPool:           // Nothing to do.
568     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
569     default: assert(0 && "This action is not supported yet!");
570     case TargetLowering::Custom:
571       Tmp1 = TLI.LowerOperation(Op, DAG);
572       if (Tmp1.Val) Result = Tmp1;
573       // FALLTHROUGH if the target doesn't want to lower this op after all.
574     case TargetLowering::Legal:
575       break;
576     }
577     break;
578   case ISD::AssertSext:
579   case ISD::AssertZext:
580     Tmp1 = LegalizeOp(Node->getOperand(0));
581     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
582     break;
583   case ISD::MERGE_VALUES:
584     // Legalize eliminates MERGE_VALUES nodes.
585     Result = Node->getOperand(Op.ResNo);
586     break;
587   case ISD::CopyFromReg:
588     Tmp1 = LegalizeOp(Node->getOperand(0));
589     Result = Op.getValue(0);
590     if (Node->getNumValues() == 2) {
591       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
592     } else {
593       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
594       if (Node->getNumOperands() == 3) {
595         Tmp2 = LegalizeOp(Node->getOperand(2));
596         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
597       } else {
598         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
599       }
600       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
601     }
602     // Since CopyFromReg produces two values, make sure to remember that we
603     // legalized both of them.
604     AddLegalizedOperand(Op.getValue(0), Result);
605     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
606     return Result.getValue(Op.ResNo);
607   case ISD::UNDEF: {
608     MVT::ValueType VT = Op.getValueType();
609     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
610     default: assert(0 && "This action is not supported yet!");
611     case TargetLowering::Expand:
612       if (MVT::isInteger(VT))
613         Result = DAG.getConstant(0, VT);
614       else if (MVT::isFloatingPoint(VT))
615         Result = DAG.getConstantFP(0, VT);
616       else
617         assert(0 && "Unknown value type!");
618       break;
619     case TargetLowering::Legal:
620       break;
621     }
622     break;
623   }
624     
625   case ISD::INTRINSIC_W_CHAIN:
626   case ISD::INTRINSIC_WO_CHAIN:
627   case ISD::INTRINSIC_VOID: {
628     std::vector<SDOperand> Ops;
629     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
630       Ops.push_back(LegalizeOp(Node->getOperand(i)));
631     Result = DAG.UpdateNodeOperands(Result, Ops);
632     
633     // Allow the target to custom lower its intrinsics if it wants to.
634     if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == 
635         TargetLowering::Custom) {
636       Tmp3 = TLI.LowerOperation(Result, DAG);
637       if (Tmp3.Val) Result = Tmp3;
638     }
639
640     if (Result.Val->getNumValues() == 1) break;
641
642     // Must have return value and chain result.
643     assert(Result.Val->getNumValues() == 2 &&
644            "Cannot return more than two values!");
645
646     // Since loads produce two values, make sure to remember that we 
647     // legalized both of them.
648     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
649     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
650     return Result.getValue(Op.ResNo);
651   }    
652
653   case ISD::LOCATION:
654     assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
655     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
656     
657     switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
658     case TargetLowering::Promote:
659     default: assert(0 && "This action is not supported yet!");
660     case TargetLowering::Expand: {
661       MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
662       bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
663       bool useDEBUG_LABEL = TLI.isOperationLegal(ISD::DEBUG_LABEL, MVT::Other);
664       
665       if (DebugInfo && (useDEBUG_LOC || useDEBUG_LABEL)) {
666         const std::string &FName =
667           cast<StringSDNode>(Node->getOperand(3))->getValue();
668         const std::string &DirName = 
669           cast<StringSDNode>(Node->getOperand(4))->getValue();
670         unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
671
672         std::vector<SDOperand> Ops;
673         Ops.push_back(Tmp1);  // chain
674         SDOperand LineOp = Node->getOperand(1);
675         SDOperand ColOp = Node->getOperand(2);
676         
677         if (useDEBUG_LOC) {
678           Ops.push_back(LineOp);  // line #
679           Ops.push_back(ColOp);  // col #
680           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
681           Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
682         } else {
683           unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
684           unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
685           unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
686           Ops.push_back(DAG.getConstant(ID, MVT::i32));
687           Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
688         }
689       } else {
690         Result = Tmp1;  // chain
691       }
692       break;
693     }
694     case TargetLowering::Legal:
695       if (Tmp1 != Node->getOperand(0) ||
696           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
697         std::vector<SDOperand> Ops;
698         Ops.push_back(Tmp1);
699         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
700           Ops.push_back(Node->getOperand(1));  // line # must be legal.
701           Ops.push_back(Node->getOperand(2));  // col # must be legal.
702         } else {
703           // Otherwise promote them.
704           Ops.push_back(PromoteOp(Node->getOperand(1)));
705           Ops.push_back(PromoteOp(Node->getOperand(2)));
706         }
707         Ops.push_back(Node->getOperand(3));  // filename must be legal.
708         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
709         Result = DAG.UpdateNodeOperands(Result, Ops);
710       }
711       break;
712     }
713     break;
714     
715   case ISD::DEBUG_LOC:
716     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
717     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
718     default: assert(0 && "This action is not supported yet!");
719     case TargetLowering::Legal:
720       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
721       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
722       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
723       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
724       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
725       break;
726     }
727     break;    
728
729   case ISD::DEBUG_LABEL:
730     assert(Node->getNumOperands() == 2 && "Invalid DEBUG_LABEL node!");
731     switch (TLI.getOperationAction(ISD::DEBUG_LABEL, MVT::Other)) {
732     default: assert(0 && "This action is not supported yet!");
733     case TargetLowering::Legal:
734       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
735       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
736       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
737       break;
738     }
739     break;
740
741   case ISD::Constant:
742     // We know we don't need to expand constants here, constants only have one
743     // value and we check that it is fine above.
744
745     // FIXME: Maybe we should handle things like targets that don't support full
746     // 32-bit immediates?
747     break;
748   case ISD::ConstantFP: {
749     // Spill FP immediates to the constant pool if the target cannot directly
750     // codegen them.  Targets often have some immediate values that can be
751     // efficiently generated into an FP register without a load.  We explicitly
752     // leave these constants as ConstantFP nodes for the target to deal with.
753     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
754
755     // Check to see if this FP immediate is already legal.
756     bool isLegal = false;
757     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
758            E = TLI.legal_fpimm_end(); I != E; ++I)
759       if (CFP->isExactlyValue(*I)) {
760         isLegal = true;
761         break;
762       }
763
764     // If this is a legal constant, turn it into a TargetConstantFP node.
765     if (isLegal) {
766       Result = DAG.getTargetConstantFP(CFP->getValue(), CFP->getValueType(0));
767       break;
768     }
769
770     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
771     default: assert(0 && "This action is not supported yet!");
772     case TargetLowering::Custom:
773       Tmp3 = TLI.LowerOperation(Result, DAG);
774       if (Tmp3.Val) {
775         Result = Tmp3;
776         break;
777       }
778       // FALLTHROUGH
779     case TargetLowering::Expand:
780       // Otherwise we need to spill the constant to memory.
781       bool Extend = false;
782
783       // If a FP immediate is precise when represented as a float and if the
784       // target can do an extending load from float to double, we put it into
785       // the constant pool as a float, even if it's is statically typed as a
786       // double.
787       MVT::ValueType VT = CFP->getValueType(0);
788       bool isDouble = VT == MVT::f64;
789       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
790                                              Type::FloatTy, CFP->getValue());
791       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
792           // Only do this if the target has a native EXTLOAD instruction from
793           // f32.
794           TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
795         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
796         VT = MVT::f32;
797         Extend = true;
798       }
799
800       SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
801       if (Extend) {
802         Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
803                                 CPIdx, DAG.getSrcValue(NULL), MVT::f32);
804       } else {
805         Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
806                              DAG.getSrcValue(NULL));
807       }
808     }
809     break;
810   }
811   case ISD::TokenFactor:
812     if (Node->getNumOperands() == 2) {
813       Tmp1 = LegalizeOp(Node->getOperand(0));
814       Tmp2 = LegalizeOp(Node->getOperand(1));
815       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
816     } else if (Node->getNumOperands() == 3) {
817       Tmp1 = LegalizeOp(Node->getOperand(0));
818       Tmp2 = LegalizeOp(Node->getOperand(1));
819       Tmp3 = LegalizeOp(Node->getOperand(2));
820       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
821     } else {
822       std::vector<SDOperand> Ops;
823       // Legalize the operands.
824       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
825         Ops.push_back(LegalizeOp(Node->getOperand(i)));
826       Result = DAG.UpdateNodeOperands(Result, Ops);
827     }
828     break;
829     
830   case ISD::FORMAL_ARGUMENTS:
831     // The only option for this is to custom lower it.
832     Result = TLI.LowerOperation(Result, DAG);
833     assert(Result.Val && "Target didn't custom lower ISD::FORMAL_ARGUMENTS!");
834     break;
835         
836   case ISD::BUILD_VECTOR:
837     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
838     default: assert(0 && "This action is not supported yet!");
839     case TargetLowering::Custom:
840       Tmp3 = TLI.LowerOperation(Result, DAG);
841       if (Tmp3.Val) {
842         Result = Tmp3;
843         break;
844       }
845       // FALLTHROUGH
846     case TargetLowering::Expand:
847       Result = ExpandBUILD_VECTOR(Result.Val);
848       break;
849     }
850     break;
851   case ISD::INSERT_VECTOR_ELT:
852     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
853     Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
854     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
855     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
856     
857     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
858                                    Node->getValueType(0))) {
859     default: assert(0 && "This action is not supported yet!");
860     case TargetLowering::Legal:
861       break;
862     case TargetLowering::Custom:
863       Tmp3 = TLI.LowerOperation(Result, DAG);
864       if (Tmp3.Val) {
865         Result = Tmp3;
866         break;
867       }
868       // FALLTHROUGH
869     case TargetLowering::Expand: {
870       // If the target doesn't support this, we have to spill the input vector
871       // to a temporary stack slot, update the element, then reload it.  This is
872       // badness.  We could also load the value into a vector register (either
873       // with a "move to register" or "extload into register" instruction, then
874       // permute it into place, if the idx is a constant and if the idx is
875       // supported by the target.
876       MVT::ValueType VT    = Tmp1.getValueType();
877       MVT::ValueType EltVT = Tmp2.getValueType();
878       MVT::ValueType IdxVT = Tmp3.getValueType();
879       MVT::ValueType PtrVT = TLI.getPointerTy();
880       SDOperand StackPtr = CreateStackTemporary(VT);
881       // Store the vector.
882       SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
883                                  Tmp1, StackPtr, DAG.getSrcValue(NULL));
884
885       // Truncate or zero extend offset to target pointer type.
886       unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
887       Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
888       // Add the offset to the index.
889       unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
890       Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
891       SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
892       // Store the scalar value.
893       Ch = DAG.getNode(ISD::STORE, MVT::Other, Ch,
894                        Tmp2, StackPtr2, DAG.getSrcValue(NULL));
895       // Load the updated vector.
896       Result = DAG.getLoad(VT, Ch, StackPtr, DAG.getSrcValue(NULL));
897       break;
898     }
899     }
900     break;
901   case ISD::SCALAR_TO_VECTOR:
902     if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
903       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
904       break;
905     }
906     
907     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
908     Result = DAG.UpdateNodeOperands(Result, Tmp1);
909     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
910                                    Node->getValueType(0))) {
911     default: assert(0 && "This action is not supported yet!");
912     case TargetLowering::Legal:
913       break;
914     case TargetLowering::Custom:
915       Tmp3 = TLI.LowerOperation(Result, DAG);
916       if (Tmp3.Val) {
917         Result = Tmp3;
918         break;
919       }
920       // FALLTHROUGH
921     case TargetLowering::Expand:
922       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
923       break;
924     }
925     break;
926   case ISD::VECTOR_SHUFFLE:
927     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
928     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
929     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
930
931     // Allow targets to custom lower the SHUFFLEs they support.
932     switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
933     default: assert(0 && "Unknown operation action!");
934     case TargetLowering::Legal:
935       assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
936              "vector shuffle should not be created if not legal!");
937       break;
938     case TargetLowering::Custom:
939       Tmp3 = TLI.LowerOperation(Result, DAG);
940       if (Tmp3.Val) {
941         Result = Tmp3;
942         break;
943       }
944       // FALLTHROUGH
945     case TargetLowering::Expand: {
946       MVT::ValueType VT = Node->getValueType(0);
947       MVT::ValueType EltVT = MVT::getVectorBaseType(VT);
948       MVT::ValueType PtrVT = TLI.getPointerTy();
949       SDOperand Mask = Node->getOperand(2);
950       unsigned NumElems = Mask.getNumOperands();
951       std::vector<SDOperand> Ops;
952       for (unsigned i = 0; i != NumElems; ++i) {
953         SDOperand Arg = Mask.getOperand(i);
954         if (Arg.getOpcode() == ISD::UNDEF) {
955           Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
956         } else {
957           assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
958           unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
959           if (Idx < NumElems)
960             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
961                                       DAG.getConstant(Idx, PtrVT)));
962           else
963             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
964                                       DAG.getConstant(Idx - NumElems, PtrVT)));
965         }
966       }
967       Result = DAG.getNode(ISD::BUILD_VECTOR, VT, Ops);
968       break;
969     }
970     case TargetLowering::Promote: {
971       // Change base type to a different vector type.
972       MVT::ValueType OVT = Node->getValueType(0);
973       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
974
975       // Cast the two input vectors.
976       Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
977       Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
978       
979       // Convert the shuffle mask to the right # elements.
980       Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
981       assert(Tmp3.Val && "Shuffle not legal?");
982       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
983       Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
984       break;
985     }
986     }
987     break;
988   
989   case ISD::EXTRACT_VECTOR_ELT:
990     Tmp1 = LegalizeOp(Node->getOperand(0));
991     Tmp2 = LegalizeOp(Node->getOperand(1));
992     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
993     
994     switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT,
995                                    Tmp1.getValueType())) {
996     default: assert(0 && "This action is not supported yet!");
997     case TargetLowering::Legal:
998       break;
999     case TargetLowering::Custom:
1000       Tmp3 = TLI.LowerOperation(Result, DAG);
1001       if (Tmp3.Val) {
1002         Result = Tmp3;
1003         break;
1004       }
1005       // FALLTHROUGH
1006     case TargetLowering::Expand:
1007       Result = ExpandEXTRACT_VECTOR_ELT(Result);
1008       break;
1009     }
1010     break;
1011
1012   case ISD::VEXTRACT_VECTOR_ELT: 
1013     Result = LegalizeOp(LowerVEXTRACT_VECTOR_ELT(Op));
1014     break;
1015     
1016   case ISD::CALLSEQ_START: {
1017     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1018     
1019     // Recursively Legalize all of the inputs of the call end that do not lead
1020     // to this call start.  This ensures that any libcalls that need be inserted
1021     // are inserted *before* the CALLSEQ_START.
1022     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1023       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node);
1024
1025     // Now that we legalized all of the inputs (which may have inserted
1026     // libcalls) create the new CALLSEQ_START node.
1027     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1028
1029     // Merge in the last call, to ensure that this call start after the last
1030     // call ended.
1031     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1032     Tmp1 = LegalizeOp(Tmp1);
1033       
1034     // Do not try to legalize the target-specific arguments (#1+).
1035     if (Tmp1 != Node->getOperand(0)) {
1036       std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1037       Ops[0] = Tmp1;
1038       Result = DAG.UpdateNodeOperands(Result, Ops);
1039     }
1040     
1041     // Remember that the CALLSEQ_START is legalized.
1042     AddLegalizedOperand(Op.getValue(0), Result);
1043     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1044       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1045     
1046     // Now that the callseq_start and all of the non-call nodes above this call
1047     // sequence have been legalized, legalize the call itself.  During this 
1048     // process, no libcalls can/will be inserted, guaranteeing that no calls
1049     // can overlap.
1050     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1051     SDOperand InCallSEQ = LastCALLSEQ_END;
1052     // Note that we are selecting this call!
1053     LastCALLSEQ_END = SDOperand(CallEnd, 0);
1054     IsLegalizingCall = true;
1055     
1056     // Legalize the call, starting from the CALLSEQ_END.
1057     LegalizeOp(LastCALLSEQ_END);
1058     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1059     return Result;
1060   }
1061   case ISD::CALLSEQ_END:
1062     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1063     // will cause this node to be legalized as well as handling libcalls right.
1064     if (LastCALLSEQ_END.Val != Node) {
1065       LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
1066       std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
1067       assert(I != LegalizedNodes.end() &&
1068              "Legalizing the call start should have legalized this node!");
1069       return I->second;
1070     }
1071     
1072     // Otherwise, the call start has been legalized and everything is going 
1073     // according to plan.  Just legalize ourselves normally here.
1074     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1075     // Do not try to legalize the target-specific arguments (#1+), except for
1076     // an optional flag input.
1077     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1078       if (Tmp1 != Node->getOperand(0)) {
1079         std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1080         Ops[0] = Tmp1;
1081         Result = DAG.UpdateNodeOperands(Result, Ops);
1082       }
1083     } else {
1084       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1085       if (Tmp1 != Node->getOperand(0) ||
1086           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1087         std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1088         Ops[0] = Tmp1;
1089         Ops.back() = Tmp2;
1090         Result = DAG.UpdateNodeOperands(Result, Ops);
1091       }
1092     }
1093     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1094     // This finishes up call legalization.
1095     IsLegalizingCall = false;
1096     
1097     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1098     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1099     if (Node->getNumValues() == 2)
1100       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1101     return Result.getValue(Op.ResNo);
1102   case ISD::DYNAMIC_STACKALLOC: {
1103     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1104     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1105     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1106     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1107
1108     Tmp1 = Result.getValue(0);
1109     Tmp2 = Result.getValue(1);
1110     switch (TLI.getOperationAction(Node->getOpcode(),
1111                                    Node->getValueType(0))) {
1112     default: assert(0 && "This action is not supported yet!");
1113     case TargetLowering::Expand: {
1114       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1115       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1116              " not tell us which reg is the stack pointer!");
1117       SDOperand Chain = Tmp1.getOperand(0);
1118       SDOperand Size  = Tmp2.getOperand(1);
1119       SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, Node->getValueType(0));
1120       Tmp1 = DAG.getNode(ISD::SUB, Node->getValueType(0), SP, Size);    // Value
1121       Tmp2 = DAG.getCopyToReg(SP.getValue(1), SPReg, Tmp1);      // Output chain
1122       Tmp1 = LegalizeOp(Tmp1);
1123       Tmp2 = LegalizeOp(Tmp2);
1124       break;
1125     }
1126     case TargetLowering::Custom:
1127       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1128       if (Tmp3.Val) {
1129         Tmp1 = LegalizeOp(Tmp3);
1130         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1131       }
1132       break;
1133     case TargetLowering::Legal:
1134       break;
1135     }
1136     // Since this op produce two values, make sure to remember that we
1137     // legalized both of them.
1138     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1139     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1140     return Op.ResNo ? Tmp2 : Tmp1;
1141   }
1142   case ISD::INLINEASM:
1143     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
1144     Tmp2 = Node->getOperand(Node->getNumOperands()-1);
1145     if (Tmp2.getValueType() == MVT::Flag)     // Legalize Flag if it exists.
1146       Tmp2 = Tmp3 = SDOperand(0, 0);
1147     else
1148       Tmp3 = LegalizeOp(Tmp2);
1149     
1150     if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
1151       std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1152       Ops[0] = Tmp1;
1153       if (Tmp3.Val) Ops.back() = Tmp3;
1154       Result = DAG.UpdateNodeOperands(Result, Ops);
1155     }
1156       
1157     // INLINE asm returns a chain and flag, make sure to add both to the map.
1158     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1159     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1160     return Result.getValue(Op.ResNo);
1161   case ISD::BR:
1162     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1163     // Ensure that libcalls are emitted before a branch.
1164     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1165     Tmp1 = LegalizeOp(Tmp1);
1166     LastCALLSEQ_END = DAG.getEntryNode();
1167     
1168     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1169     break;
1170
1171   case ISD::BRCOND:
1172     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1173     // Ensure that libcalls are emitted before a return.
1174     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1175     Tmp1 = LegalizeOp(Tmp1);
1176     LastCALLSEQ_END = DAG.getEntryNode();
1177
1178     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1179     case Expand: assert(0 && "It's impossible to expand bools");
1180     case Legal:
1181       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1182       break;
1183     case Promote:
1184       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1185       break;
1186     }
1187
1188     // Basic block destination (Op#2) is always legal.
1189     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1190       
1191     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
1192     default: assert(0 && "This action is not supported yet!");
1193     case TargetLowering::Legal: break;
1194     case TargetLowering::Custom:
1195       Tmp1 = TLI.LowerOperation(Result, DAG);
1196       if (Tmp1.Val) Result = Tmp1;
1197       break;
1198     case TargetLowering::Expand:
1199       // Expand brcond's setcc into its constituent parts and create a BR_CC
1200       // Node.
1201       if (Tmp2.getOpcode() == ISD::SETCC) {
1202         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1203                              Tmp2.getOperand(0), Tmp2.getOperand(1),
1204                              Node->getOperand(2));
1205       } else {
1206         // Make sure the condition is either zero or one.  It may have been
1207         // promoted from something else.
1208         unsigned NumBits = MVT::getSizeInBits(Tmp2.getValueType());
1209         if (!TLI.MaskedValueIsZero(Tmp2, (~0ULL >> (64-NumBits))^1))
1210           Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1211         
1212         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
1213                              DAG.getCondCode(ISD::SETNE), Tmp2,
1214                              DAG.getConstant(0, Tmp2.getValueType()),
1215                              Node->getOperand(2));
1216       }
1217       break;
1218     }
1219     break;
1220   case ISD::BR_CC:
1221     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1222     // Ensure that libcalls are emitted before a branch.
1223     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1224     Tmp1 = LegalizeOp(Tmp1);
1225     LastCALLSEQ_END = DAG.getEntryNode();
1226     
1227     Tmp2 = Node->getOperand(2);              // LHS 
1228     Tmp3 = Node->getOperand(3);              // RHS
1229     Tmp4 = Node->getOperand(1);              // CC
1230
1231     LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1232     
1233     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1234     // the LHS is a legal SETCC itself.  In this case, we need to compare
1235     // the result against zero to select between true and false values.
1236     if (Tmp3.Val == 0) {
1237       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1238       Tmp4 = DAG.getCondCode(ISD::SETNE);
1239     }
1240     
1241     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3, 
1242                                     Node->getOperand(4));
1243       
1244     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1245     default: assert(0 && "Unexpected action for BR_CC!");
1246     case TargetLowering::Legal: break;
1247     case TargetLowering::Custom:
1248       Tmp4 = TLI.LowerOperation(Result, DAG);
1249       if (Tmp4.Val) Result = Tmp4;
1250       break;
1251     }
1252     break;
1253   case ISD::LOAD: {
1254     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1255     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1256
1257     MVT::ValueType VT = Node->getValueType(0);
1258     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1259     Tmp2 = Result.getValue(0);
1260     Tmp3 = Result.getValue(1);
1261     
1262     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1263     default: assert(0 && "This action is not supported yet!");
1264     case TargetLowering::Legal: break;
1265     case TargetLowering::Custom:
1266       Tmp1 = TLI.LowerOperation(Tmp2, DAG);
1267       if (Tmp1.Val) {
1268         Tmp2 = LegalizeOp(Tmp1);
1269         Tmp3 = LegalizeOp(Tmp1.getValue(1));
1270       }
1271       break;
1272     }
1273     // Since loads produce two values, make sure to remember that we 
1274     // legalized both of them.
1275     AddLegalizedOperand(SDOperand(Node, 0), Tmp2);
1276     AddLegalizedOperand(SDOperand(Node, 1), Tmp3);
1277     return Op.ResNo ? Tmp3 : Tmp2;
1278   }
1279   case ISD::EXTLOAD:
1280   case ISD::SEXTLOAD:
1281   case ISD::ZEXTLOAD: {
1282     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1283     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1284
1285     MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
1286     switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
1287     default: assert(0 && "This action is not supported yet!");
1288     case TargetLowering::Promote:
1289       assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
1290       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1291                                       DAG.getValueType(MVT::i8));
1292       Tmp1 = Result.getValue(0);
1293       Tmp2 = Result.getValue(1);
1294       break;
1295     case TargetLowering::Custom:
1296       isCustom = true;
1297       // FALLTHROUGH
1298     case TargetLowering::Legal:
1299       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1300                                       Node->getOperand(3));
1301       Tmp1 = Result.getValue(0);
1302       Tmp2 = Result.getValue(1);
1303       
1304       if (isCustom) {
1305         Tmp3 = TLI.LowerOperation(Tmp3, DAG);
1306         if (Tmp3.Val) {
1307           Tmp1 = LegalizeOp(Tmp3);
1308           Tmp2 = LegalizeOp(Tmp3.getValue(1));
1309         }
1310       }
1311       break;
1312     case TargetLowering::Expand:
1313       // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1314       if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1315         SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
1316         Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1317         Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1318         Tmp2 = LegalizeOp(Load.getValue(1));
1319         break;
1320       }
1321       assert(Node->getOpcode() != ISD::EXTLOAD &&
1322              "EXTLOAD should always be supported!");
1323       // Turn the unsupported load into an EXTLOAD followed by an explicit
1324       // zero/sign extend inreg.
1325       Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1326                               Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1327       SDOperand ValRes;
1328       if (Node->getOpcode() == ISD::SEXTLOAD)
1329         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1330                              Result, DAG.getValueType(SrcVT));
1331       else
1332         ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1333       Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1334       Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1335       break;
1336     }
1337     // Since loads produce two values, make sure to remember that we legalized
1338     // both of them.
1339     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1340     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1341     return Op.ResNo ? Tmp2 : Tmp1;
1342   }
1343   case ISD::EXTRACT_ELEMENT: {
1344     MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1345     switch (getTypeAction(OpTy)) {
1346     default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1347     case Legal:
1348       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1349         // 1 -> Hi
1350         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1351                              DAG.getConstant(MVT::getSizeInBits(OpTy)/2, 
1352                                              TLI.getShiftAmountTy()));
1353         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1354       } else {
1355         // 0 -> Lo
1356         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
1357                              Node->getOperand(0));
1358       }
1359       break;
1360     case Expand:
1361       // Get both the low and high parts.
1362       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1363       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1364         Result = Tmp2;  // 1 -> Hi
1365       else
1366         Result = Tmp1;  // 0 -> Lo
1367       break;
1368     }
1369     break;
1370   }
1371
1372   case ISD::CopyToReg:
1373     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1374
1375     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1376            "Register type must be legal!");
1377     // Legalize the incoming value (must be a legal type).
1378     Tmp2 = LegalizeOp(Node->getOperand(2));
1379     if (Node->getNumValues() == 1) {
1380       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
1381     } else {
1382       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1383       if (Node->getNumOperands() == 4) {
1384         Tmp3 = LegalizeOp(Node->getOperand(3));
1385         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
1386                                         Tmp3);
1387       } else {
1388         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1389       }
1390       
1391       // Since this produces two values, make sure to remember that we legalized
1392       // both of them.
1393       AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1394       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1395       return Result;
1396     }
1397     break;
1398
1399   case ISD::RET:
1400     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1401
1402     // Ensure that libcalls are emitted before a return.
1403     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1404     Tmp1 = LegalizeOp(Tmp1);
1405     LastCALLSEQ_END = DAG.getEntryNode();
1406       
1407     switch (Node->getNumOperands()) {
1408     case 2:  // ret val
1409       Tmp2 = Node->getOperand(1);
1410       switch (getTypeAction(Tmp2.getValueType())) {
1411       case Legal:
1412         Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2));
1413         break;
1414       case Expand:
1415         if (Tmp2.getValueType() != MVT::Vector) {
1416           SDOperand Lo, Hi;
1417           ExpandOp(Tmp2, Lo, Hi);
1418           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1419         } else {
1420           SDNode *InVal = Tmp2.Val;
1421           unsigned NumElems =
1422             cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1423           MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1424           
1425           // Figure out if there is a Packed type corresponding to this Vector
1426           // type.  If so, convert to the packed type.
1427           MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1428           if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1429             // Turn this into a return of the packed type.
1430             Tmp2 = PackVectorOp(Tmp2, TVT);
1431             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1432           } else if (NumElems == 1) {
1433             // Turn this into a return of the scalar type.
1434             Tmp2 = PackVectorOp(Tmp2, EVT);
1435             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1436             
1437             // FIXME: Returns of gcc generic vectors smaller than a legal type
1438             // should be returned in integer registers!
1439             
1440             // The scalarized value type may not be legal, e.g. it might require
1441             // promotion or expansion.  Relegalize the return.
1442             Result = LegalizeOp(Result);
1443           } else {
1444             // FIXME: Returns of gcc generic vectors larger than a legal vector
1445             // type should be returned by reference!
1446             SDOperand Lo, Hi;
1447             SplitVectorOp(Tmp2, Lo, Hi);
1448             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1449             Result = LegalizeOp(Result);
1450           }
1451         }
1452         break;
1453       case Promote:
1454         Tmp2 = PromoteOp(Node->getOperand(1));
1455         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1456         Result = LegalizeOp(Result);
1457         break;
1458       }
1459       break;
1460     case 1:  // ret void
1461       Result = DAG.UpdateNodeOperands(Result, Tmp1);
1462       break;
1463     default: { // ret <values>
1464       std::vector<SDOperand> NewValues;
1465       NewValues.push_back(Tmp1);
1466       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1467         switch (getTypeAction(Node->getOperand(i).getValueType())) {
1468         case Legal:
1469           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1470           break;
1471         case Expand: {
1472           SDOperand Lo, Hi;
1473           assert(Node->getOperand(i).getValueType() != MVT::Vector &&
1474                  "FIXME: TODO: implement returning non-legal vector types!");
1475           ExpandOp(Node->getOperand(i), Lo, Hi);
1476           NewValues.push_back(Lo);
1477           NewValues.push_back(Hi);
1478           break;
1479         }
1480         case Promote:
1481           assert(0 && "Can't promote multiple return value yet!");
1482         }
1483           
1484       if (NewValues.size() == Node->getNumOperands())
1485         Result = DAG.UpdateNodeOperands(Result, NewValues);
1486       else
1487         Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1488       break;
1489     }
1490     }
1491
1492     if (Result.getOpcode() == ISD::RET) {
1493       switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
1494       default: assert(0 && "This action is not supported yet!");
1495       case TargetLowering::Legal: break;
1496       case TargetLowering::Custom:
1497         Tmp1 = TLI.LowerOperation(Result, DAG);
1498         if (Tmp1.Val) Result = Tmp1;
1499         break;
1500       }
1501     }
1502     break;
1503   case ISD::STORE: {
1504     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1505     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1506
1507     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1508     // FIXME: We shouldn't do this for TargetConstantFP's.
1509     // FIXME: move this to the DAG Combiner!
1510     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1511       if (CFP->getValueType(0) == MVT::f32) {
1512         Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
1513       } else {
1514         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1515         Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
1516       }
1517       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Tmp3, Tmp2, 
1518                            Node->getOperand(3));
1519       break;
1520     }
1521
1522     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1523     case Legal: {
1524       Tmp3 = LegalizeOp(Node->getOperand(1));
1525       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1526                                       Node->getOperand(3));
1527
1528       MVT::ValueType VT = Tmp3.getValueType();
1529       switch (TLI.getOperationAction(ISD::STORE, VT)) {
1530       default: assert(0 && "This action is not supported yet!");
1531       case TargetLowering::Legal:  break;
1532       case TargetLowering::Custom:
1533         Tmp1 = TLI.LowerOperation(Result, DAG);
1534         if (Tmp1.Val) Result = Tmp1;
1535         break;
1536       }
1537       break;
1538     }
1539     case Promote:
1540       // Truncate the value and store the result.
1541       Tmp3 = PromoteOp(Node->getOperand(1));
1542       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1543                            Node->getOperand(3),
1544                           DAG.getValueType(Node->getOperand(1).getValueType()));
1545       break;
1546
1547     case Expand:
1548       unsigned IncrementSize = 0;
1549       SDOperand Lo, Hi;
1550       
1551       // If this is a vector type, then we have to calculate the increment as
1552       // the product of the element size in bytes, and the number of elements
1553       // in the high half of the vector.
1554       if (Node->getOperand(1).getValueType() == MVT::Vector) {
1555         SDNode *InVal = Node->getOperand(1).Val;
1556         unsigned NumElems =
1557           cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1558         MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1559
1560         // Figure out if there is a Packed type corresponding to this Vector
1561         // type.  If so, convert to the packed type.
1562         MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1563         if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1564           // Turn this into a normal store of the packed type.
1565           Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
1566           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1567                                           Node->getOperand(3));
1568           break;
1569         } else if (NumElems == 1) {
1570           // Turn this into a normal store of the scalar type.
1571           Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
1572           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1573                                           Node->getOperand(3));
1574           // The scalarized value type may not be legal, e.g. it might require
1575           // promotion or expansion.  Relegalize the scalar store.
1576           Result = LegalizeOp(Result);
1577           break;
1578         } else {
1579           SplitVectorOp(Node->getOperand(1), Lo, Hi);
1580           IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1581         }
1582       } else {
1583         ExpandOp(Node->getOperand(1), Lo, Hi);
1584         IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1585
1586         if (!TLI.isLittleEndian())
1587           std::swap(Lo, Hi);
1588       }
1589
1590       Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1591                        Node->getOperand(3));
1592       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1593                          getIntPtrConstant(IncrementSize));
1594       assert(isTypeLegal(Tmp2.getValueType()) &&
1595              "Pointers must be legal!");
1596       // FIXME: This sets the srcvalue of both halves to be the same, which is
1597       // wrong.
1598       Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1599                        Node->getOperand(3));
1600       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1601       break;
1602     }
1603     break;
1604   }
1605   case ISD::PCMARKER:
1606     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1607     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1608     break;
1609   case ISD::STACKSAVE:
1610     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1611     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1612     Tmp1 = Result.getValue(0);
1613     Tmp2 = Result.getValue(1);
1614     
1615     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
1616     default: assert(0 && "This action is not supported yet!");
1617     case TargetLowering::Legal: break;
1618     case TargetLowering::Custom:
1619       Tmp3 = TLI.LowerOperation(Result, DAG);
1620       if (Tmp3.Val) {
1621         Tmp1 = LegalizeOp(Tmp3);
1622         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1623       }
1624       break;
1625     case TargetLowering::Expand:
1626       // Expand to CopyFromReg if the target set 
1627       // StackPointerRegisterToSaveRestore.
1628       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1629         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
1630                                   Node->getValueType(0));
1631         Tmp2 = Tmp1.getValue(1);
1632       } else {
1633         Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
1634         Tmp2 = Node->getOperand(0);
1635       }
1636       break;
1637     }
1638
1639     // Since stacksave produce two values, make sure to remember that we
1640     // legalized both of them.
1641     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1642     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1643     return Op.ResNo ? Tmp2 : Tmp1;
1644
1645   case ISD::STACKRESTORE:
1646     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1647     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1648     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1649       
1650     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
1651     default: assert(0 && "This action is not supported yet!");
1652     case TargetLowering::Legal: break;
1653     case TargetLowering::Custom:
1654       Tmp1 = TLI.LowerOperation(Result, DAG);
1655       if (Tmp1.Val) Result = Tmp1;
1656       break;
1657     case TargetLowering::Expand:
1658       // Expand to CopyToReg if the target set 
1659       // StackPointerRegisterToSaveRestore.
1660       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1661         Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
1662       } else {
1663         Result = Tmp1;
1664       }
1665       break;
1666     }
1667     break;
1668
1669   case ISD::READCYCLECOUNTER:
1670     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1671     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1672
1673     // Since rdcc produce two values, make sure to remember that we legalized
1674     // both of them.
1675     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1676     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1677     return Result;
1678
1679   case ISD::TRUNCSTORE: {
1680     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1681     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1682
1683     assert(isTypeLegal(Node->getOperand(1).getValueType()) &&
1684            "Cannot handle illegal TRUNCSTORE yet!");
1685     Tmp2 = LegalizeOp(Node->getOperand(1));
1686     
1687     // The only promote case we handle is TRUNCSTORE:i1 X into
1688     //   -> TRUNCSTORE:i8 (and X, 1)
1689     if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1690         TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) == 
1691               TargetLowering::Promote) {
1692       // Promote the bool to a mask then store.
1693       Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1694                          DAG.getConstant(1, Tmp2.getValueType()));
1695       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1696                            Node->getOperand(3), DAG.getValueType(MVT::i8));
1697
1698     } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1699                Tmp3 != Node->getOperand(2)) {
1700       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
1701                                       Node->getOperand(3), Node->getOperand(4));
1702     }
1703
1704     MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
1705     switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
1706     default: assert(0 && "This action is not supported yet!");
1707     case TargetLowering::Legal: break;
1708     case TargetLowering::Custom:
1709       Tmp1 = TLI.LowerOperation(Result, DAG);
1710       if (Tmp1.Val) Result = Tmp1;
1711       break;
1712     }
1713     break;
1714   }
1715   case ISD::SELECT:
1716     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1717     case Expand: assert(0 && "It's impossible to expand bools");
1718     case Legal:
1719       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1720       break;
1721     case Promote:
1722       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1723       break;
1724     }
1725     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1726     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1727
1728     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1729       
1730     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1731     default: assert(0 && "This action is not supported yet!");
1732     case TargetLowering::Legal: break;
1733     case TargetLowering::Custom: {
1734       Tmp1 = TLI.LowerOperation(Result, DAG);
1735       if (Tmp1.Val) Result = Tmp1;
1736       break;
1737     }
1738     case TargetLowering::Expand:
1739       if (Tmp1.getOpcode() == ISD::SETCC) {
1740         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
1741                               Tmp2, Tmp3,
1742                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1743       } else {
1744         // Make sure the condition is either zero or one.  It may have been
1745         // promoted from something else.
1746         unsigned NumBits = MVT::getSizeInBits(Tmp1.getValueType());
1747         if (!TLI.MaskedValueIsZero(Tmp1, (~0ULL >> (64-NumBits))^1))
1748           Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1749         Result = DAG.getSelectCC(Tmp1, 
1750                                  DAG.getConstant(0, Tmp1.getValueType()),
1751                                  Tmp2, Tmp3, ISD::SETNE);
1752       }
1753       break;
1754     case TargetLowering::Promote: {
1755       MVT::ValueType NVT =
1756         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1757       unsigned ExtOp, TruncOp;
1758       if (MVT::isInteger(Tmp2.getValueType())) {
1759         ExtOp   = ISD::ANY_EXTEND;
1760         TruncOp = ISD::TRUNCATE;
1761       } else {
1762         ExtOp   = ISD::FP_EXTEND;
1763         TruncOp = ISD::FP_ROUND;
1764       }
1765       // Promote each of the values to the new type.
1766       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1767       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1768       // Perform the larger operation, then round down.
1769       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1770       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1771       break;
1772     }
1773     }
1774     break;
1775   case ISD::SELECT_CC: {
1776     Tmp1 = Node->getOperand(0);               // LHS
1777     Tmp2 = Node->getOperand(1);               // RHS
1778     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1779     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1780     SDOperand CC = Node->getOperand(4);
1781     
1782     LegalizeSetCCOperands(Tmp1, Tmp2, CC);
1783     
1784     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1785     // the LHS is a legal SETCC itself.  In this case, we need to compare
1786     // the result against zero to select between true and false values.
1787     if (Tmp2.Val == 0) {
1788       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1789       CC = DAG.getCondCode(ISD::SETNE);
1790     }
1791     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
1792
1793     // Everything is legal, see if we should expand this op or something.
1794     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
1795     default: assert(0 && "This action is not supported yet!");
1796     case TargetLowering::Legal: break;
1797     case TargetLowering::Custom:
1798       Tmp1 = TLI.LowerOperation(Result, DAG);
1799       if (Tmp1.Val) Result = Tmp1;
1800       break;
1801     }
1802     break;
1803   }
1804   case ISD::SETCC:
1805     Tmp1 = Node->getOperand(0);
1806     Tmp2 = Node->getOperand(1);
1807     Tmp3 = Node->getOperand(2);
1808     LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
1809     
1810     // If we had to Expand the SetCC operands into a SELECT node, then it may 
1811     // not always be possible to return a true LHS & RHS.  In this case, just 
1812     // return the value we legalized, returned in the LHS
1813     if (Tmp2.Val == 0) {
1814       Result = Tmp1;
1815       break;
1816     }
1817
1818     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
1819     default: assert(0 && "Cannot handle this action for SETCC yet!");
1820     case TargetLowering::Custom:
1821       isCustom = true;
1822       // FALLTHROUGH.
1823     case TargetLowering::Legal:
1824       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1825       if (isCustom) {
1826         Tmp3 = TLI.LowerOperation(Result, DAG);
1827         if (Tmp3.Val) Result = Tmp3;
1828       }
1829       break;
1830     case TargetLowering::Promote: {
1831       // First step, figure out the appropriate operation to use.
1832       // Allow SETCC to not be supported for all legal data types
1833       // Mostly this targets FP
1834       MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1835       MVT::ValueType OldVT = NewInTy;
1836
1837       // Scan for the appropriate larger type to use.
1838       while (1) {
1839         NewInTy = (MVT::ValueType)(NewInTy+1);
1840
1841         assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1842                "Fell off of the edge of the integer world");
1843         assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1844                "Fell off of the edge of the floating point world");
1845           
1846         // If the target supports SETCC of this type, use it.
1847         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
1848           break;
1849       }
1850       if (MVT::isInteger(NewInTy))
1851         assert(0 && "Cannot promote Legal Integer SETCC yet");
1852       else {
1853         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1854         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1855       }
1856       Tmp1 = LegalizeOp(Tmp1);
1857       Tmp2 = LegalizeOp(Tmp2);
1858       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1859       Result = LegalizeOp(Result);
1860       break;
1861     }
1862     case TargetLowering::Expand:
1863       // Expand a setcc node into a select_cc of the same condition, lhs, and
1864       // rhs that selects between const 1 (true) and const 0 (false).
1865       MVT::ValueType VT = Node->getValueType(0);
1866       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
1867                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1868                            Node->getOperand(2));
1869       break;
1870     }
1871     break;
1872   case ISD::MEMSET:
1873   case ISD::MEMCPY:
1874   case ISD::MEMMOVE: {
1875     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1876     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1877
1878     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1879       switch (getTypeAction(Node->getOperand(2).getValueType())) {
1880       case Expand: assert(0 && "Cannot expand a byte!");
1881       case Legal:
1882         Tmp3 = LegalizeOp(Node->getOperand(2));
1883         break;
1884       case Promote:
1885         Tmp3 = PromoteOp(Node->getOperand(2));
1886         break;
1887       }
1888     } else {
1889       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1890     }
1891
1892     SDOperand Tmp4;
1893     switch (getTypeAction(Node->getOperand(3).getValueType())) {
1894     case Expand: {
1895       // Length is too big, just take the lo-part of the length.
1896       SDOperand HiPart;
1897       ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1898       break;
1899     }
1900     case Legal:
1901       Tmp4 = LegalizeOp(Node->getOperand(3));
1902       break;
1903     case Promote:
1904       Tmp4 = PromoteOp(Node->getOperand(3));
1905       break;
1906     }
1907
1908     SDOperand Tmp5;
1909     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1910     case Expand: assert(0 && "Cannot expand this yet!");
1911     case Legal:
1912       Tmp5 = LegalizeOp(Node->getOperand(4));
1913       break;
1914     case Promote:
1915       Tmp5 = PromoteOp(Node->getOperand(4));
1916       break;
1917     }
1918
1919     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1920     default: assert(0 && "This action not implemented for this operation!");
1921     case TargetLowering::Custom:
1922       isCustom = true;
1923       // FALLTHROUGH
1924     case TargetLowering::Legal:
1925       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, Tmp5);
1926       if (isCustom) {
1927         Tmp1 = TLI.LowerOperation(Result, DAG);
1928         if (Tmp1.Val) Result = Tmp1;
1929       }
1930       break;
1931     case TargetLowering::Expand: {
1932       // Otherwise, the target does not support this operation.  Lower the
1933       // operation to an explicit libcall as appropriate.
1934       MVT::ValueType IntPtr = TLI.getPointerTy();
1935       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1936       std::vector<std::pair<SDOperand, const Type*> > Args;
1937
1938       const char *FnName = 0;
1939       if (Node->getOpcode() == ISD::MEMSET) {
1940         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1941         // Extend the (previously legalized) ubyte argument to be an int value
1942         // for the call.
1943         if (Tmp3.getValueType() > MVT::i32)
1944           Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
1945         else
1946           Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1947         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1948         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1949
1950         FnName = "memset";
1951       } else if (Node->getOpcode() == ISD::MEMCPY ||
1952                  Node->getOpcode() == ISD::MEMMOVE) {
1953         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1954         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1955         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1956         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1957       } else {
1958         assert(0 && "Unknown op!");
1959       }
1960
1961       std::pair<SDOperand,SDOperand> CallResult =
1962         TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1963                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1964       Result = CallResult.second;
1965       break;
1966     }
1967     }
1968     break;
1969   }
1970
1971   case ISD::SHL_PARTS:
1972   case ISD::SRA_PARTS:
1973   case ISD::SRL_PARTS: {
1974     std::vector<SDOperand> Ops;
1975     bool Changed = false;
1976     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1977       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1978       Changed |= Ops.back() != Node->getOperand(i);
1979     }
1980     if (Changed)
1981       Result = DAG.UpdateNodeOperands(Result, Ops);
1982
1983     switch (TLI.getOperationAction(Node->getOpcode(),
1984                                    Node->getValueType(0))) {
1985     default: assert(0 && "This action is not supported yet!");
1986     case TargetLowering::Legal: break;
1987     case TargetLowering::Custom:
1988       Tmp1 = TLI.LowerOperation(Result, DAG);
1989       if (Tmp1.Val) {
1990         SDOperand Tmp2, RetVal(0, 0);
1991         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1992           Tmp2 = LegalizeOp(Tmp1.getValue(i));
1993           AddLegalizedOperand(SDOperand(Node, i), Tmp2);
1994           if (i == Op.ResNo)
1995             RetVal = Tmp2;
1996         }
1997         assert(RetVal.Val && "Illegal result number");
1998         return RetVal;
1999       }
2000       break;
2001     }
2002
2003     // Since these produce multiple values, make sure to remember that we
2004     // legalized all of them.
2005     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2006       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
2007     return Result.getValue(Op.ResNo);
2008   }
2009
2010     // Binary operators
2011   case ISD::ADD:
2012   case ISD::SUB:
2013   case ISD::MUL:
2014   case ISD::MULHS:
2015   case ISD::MULHU:
2016   case ISD::UDIV:
2017   case ISD::SDIV:
2018   case ISD::AND:
2019   case ISD::OR:
2020   case ISD::XOR:
2021   case ISD::SHL:
2022   case ISD::SRL:
2023   case ISD::SRA:
2024   case ISD::FADD:
2025   case ISD::FSUB:
2026   case ISD::FMUL:
2027   case ISD::FDIV:
2028     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2029     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2030     case Expand: assert(0 && "Not possible");
2031     case Legal:
2032       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2033       break;
2034     case Promote:
2035       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2036       break;
2037     }
2038     
2039     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2040       
2041     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2042     default: assert(0 && "BinOp legalize operation not supported");
2043     case TargetLowering::Legal: break;
2044     case TargetLowering::Custom:
2045       Tmp1 = TLI.LowerOperation(Result, DAG);
2046       if (Tmp1.Val) Result = Tmp1;
2047       break;
2048     case TargetLowering::Expand: {
2049       assert(MVT::isVector(Node->getValueType(0)) &&
2050              "Cannot expand this binary operator!");
2051       // Expand the operation into a bunch of nasty scalar code.
2052       std::vector<SDOperand> Ops;
2053       MVT::ValueType EltVT = MVT::getVectorBaseType(Node->getValueType(0));
2054       MVT::ValueType PtrVT = TLI.getPointerTy();
2055       for (unsigned i = 0, e = MVT::getVectorNumElements(Node->getValueType(0));
2056            i != e; ++i) {
2057         SDOperand Idx = DAG.getConstant(i, PtrVT);
2058         SDOperand LHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1, Idx);
2059         SDOperand RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2, Idx);
2060         Ops.push_back(DAG.getNode(Node->getOpcode(), EltVT, LHS, RHS));
2061       }
2062       Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), Ops);
2063       break;
2064     }
2065     }
2066     break;
2067     
2068   case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
2069     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2070     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2071       case Expand: assert(0 && "Not possible");
2072       case Legal:
2073         Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2074         break;
2075       case Promote:
2076         Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2077         break;
2078     }
2079       
2080     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2081     
2082     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2083     default: assert(0 && "Operation not supported");
2084     case TargetLowering::Custom:
2085       Tmp1 = TLI.LowerOperation(Result, DAG);
2086       if (Tmp1.Val) Result = Tmp1;
2087       break;
2088     case TargetLowering::Legal: break;
2089     case TargetLowering::Expand:
2090       // If this target supports fabs/fneg natively, do this efficiently.
2091       if (TLI.isOperationLegal(ISD::FABS, Tmp1.getValueType()) &&
2092           TLI.isOperationLegal(ISD::FNEG, Tmp1.getValueType())) {
2093         // Get the sign bit of the RHS.
2094         MVT::ValueType IVT = 
2095           Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
2096         SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
2097         SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
2098                                SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
2099         // Get the absolute value of the result.
2100         SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
2101         // Select between the nabs and abs value based on the sign bit of
2102         // the input.
2103         Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
2104                              DAG.getNode(ISD::FNEG, AbsVal.getValueType(), 
2105                                          AbsVal),
2106                              AbsVal);
2107         Result = LegalizeOp(Result);
2108         break;
2109       }
2110       
2111       // Otherwise, do bitwise ops!
2112       
2113       // copysign -> copysignf/copysign libcall.
2114       const char *FnName;
2115       if (Node->getValueType(0) == MVT::f32) {
2116         FnName = "copysignf";
2117         if (Tmp2.getValueType() != MVT::f32)  // Force operands to match type.
2118           Result = DAG.UpdateNodeOperands(Result, Tmp1, 
2119                                     DAG.getNode(ISD::FP_ROUND, MVT::f32, Tmp2));
2120       } else {
2121         FnName = "copysign";
2122         if (Tmp2.getValueType() != MVT::f64)  // Force operands to match type.
2123           Result = DAG.UpdateNodeOperands(Result, Tmp1, 
2124                                    DAG.getNode(ISD::FP_EXTEND, MVT::f64, Tmp2));
2125       }
2126       SDOperand Dummy;
2127       Result = ExpandLibCall(FnName, Node, Dummy);
2128       break;
2129     }
2130     break;
2131     
2132   case ISD::ADDC:
2133   case ISD::SUBC:
2134     Tmp1 = LegalizeOp(Node->getOperand(0));
2135     Tmp2 = LegalizeOp(Node->getOperand(1));
2136     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2137     // Since this produces two values, make sure to remember that we legalized
2138     // both of them.
2139     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2140     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2141     return Result;
2142
2143   case ISD::ADDE:
2144   case ISD::SUBE:
2145     Tmp1 = LegalizeOp(Node->getOperand(0));
2146     Tmp2 = LegalizeOp(Node->getOperand(1));
2147     Tmp3 = LegalizeOp(Node->getOperand(2));
2148     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2149     // Since this produces two values, make sure to remember that we legalized
2150     // both of them.
2151     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2152     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2153     return Result;
2154     
2155   case ISD::BUILD_PAIR: {
2156     MVT::ValueType PairTy = Node->getValueType(0);
2157     // TODO: handle the case where the Lo and Hi operands are not of legal type
2158     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2159     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2160     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2161     case TargetLowering::Promote:
2162     case TargetLowering::Custom:
2163       assert(0 && "Cannot promote/custom this yet!");
2164     case TargetLowering::Legal:
2165       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2166         Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2167       break;
2168     case TargetLowering::Expand:
2169       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2170       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2171       Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2172                          DAG.getConstant(MVT::getSizeInBits(PairTy)/2, 
2173                                          TLI.getShiftAmountTy()));
2174       Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
2175       break;
2176     }
2177     break;
2178   }
2179
2180   case ISD::UREM:
2181   case ISD::SREM:
2182   case ISD::FREM:
2183     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2184     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2185
2186     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2187     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
2188     case TargetLowering::Custom:
2189       isCustom = true;
2190       // FALLTHROUGH
2191     case TargetLowering::Legal:
2192       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2193       if (isCustom) {
2194         Tmp1 = TLI.LowerOperation(Result, DAG);
2195         if (Tmp1.Val) Result = Tmp1;
2196       }
2197       break;
2198     case TargetLowering::Expand:
2199       if (MVT::isInteger(Node->getValueType(0))) {
2200         // X % Y -> X-X/Y*Y
2201         MVT::ValueType VT = Node->getValueType(0);
2202         unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
2203         Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
2204         Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2205         Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2206       } else {
2207         // Floating point mod -> fmod libcall.
2208         const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
2209         SDOperand Dummy;
2210         Result = ExpandLibCall(FnName, Node, Dummy);
2211       }
2212       break;
2213     }
2214     break;
2215   case ISD::VAARG: {
2216     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2217     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2218
2219     MVT::ValueType VT = Node->getValueType(0);
2220     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2221     default: assert(0 && "This action is not supported yet!");
2222     case TargetLowering::Custom:
2223       isCustom = true;
2224       // FALLTHROUGH
2225     case TargetLowering::Legal:
2226       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2227       Result = Result.getValue(0);
2228       Tmp1 = Result.getValue(1);
2229
2230       if (isCustom) {
2231         Tmp2 = TLI.LowerOperation(Result, DAG);
2232         if (Tmp2.Val) {
2233           Result = LegalizeOp(Tmp2);
2234           Tmp1 = LegalizeOp(Tmp2.getValue(1));
2235         }
2236       }
2237       break;
2238     case TargetLowering::Expand: {
2239       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2240                                      Node->getOperand(2));
2241       // Increment the pointer, VAList, to the next vaarg
2242       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
2243                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
2244                                          TLI.getPointerTy()));
2245       // Store the incremented VAList to the legalized pointer
2246       Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
2247                          Node->getOperand(2));
2248       // Load the actual argument out of the pointer VAList
2249       Result = DAG.getLoad(VT, Tmp3, VAList, DAG.getSrcValue(0));
2250       Tmp1 = LegalizeOp(Result.getValue(1));
2251       Result = LegalizeOp(Result);
2252       break;
2253     }
2254     }
2255     // Since VAARG produces two values, make sure to remember that we 
2256     // legalized both of them.
2257     AddLegalizedOperand(SDOperand(Node, 0), Result);
2258     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
2259     return Op.ResNo ? Tmp1 : Result;
2260   }
2261     
2262   case ISD::VACOPY: 
2263     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2264     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
2265     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
2266
2267     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
2268     default: assert(0 && "This action is not supported yet!");
2269     case TargetLowering::Custom:
2270       isCustom = true;
2271       // FALLTHROUGH
2272     case TargetLowering::Legal:
2273       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
2274                                       Node->getOperand(3), Node->getOperand(4));
2275       if (isCustom) {
2276         Tmp1 = TLI.LowerOperation(Result, DAG);
2277         if (Tmp1.Val) Result = Tmp1;
2278       }
2279       break;
2280     case TargetLowering::Expand:
2281       // This defaults to loading a pointer from the input and storing it to the
2282       // output, returning the chain.
2283       Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, Node->getOperand(3));
2284       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp4.getValue(1), Tmp4, Tmp2,
2285                            Node->getOperand(4));
2286       break;
2287     }
2288     break;
2289
2290   case ISD::VAEND: 
2291     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2292     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2293
2294     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
2295     default: assert(0 && "This action is not supported yet!");
2296     case TargetLowering::Custom:
2297       isCustom = true;
2298       // FALLTHROUGH
2299     case TargetLowering::Legal:
2300       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2301       if (isCustom) {
2302         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
2303         if (Tmp1.Val) Result = Tmp1;
2304       }
2305       break;
2306     case TargetLowering::Expand:
2307       Result = Tmp1; // Default to a no-op, return the chain
2308       break;
2309     }
2310     break;
2311     
2312   case ISD::VASTART: 
2313     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2314     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2315
2316     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2317     
2318     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
2319     default: assert(0 && "This action is not supported yet!");
2320     case TargetLowering::Legal: break;
2321     case TargetLowering::Custom:
2322       Tmp1 = TLI.LowerOperation(Result, DAG);
2323       if (Tmp1.Val) Result = Tmp1;
2324       break;
2325     }
2326     break;
2327     
2328   case ISD::ROTL:
2329   case ISD::ROTR:
2330     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2331     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2332     
2333     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2334            "Cannot handle this yet!");
2335     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2336     break;
2337     
2338   case ISD::BSWAP:
2339     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2340     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2341     case TargetLowering::Custom:
2342       assert(0 && "Cannot custom legalize this yet!");
2343     case TargetLowering::Legal:
2344       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2345       break;
2346     case TargetLowering::Promote: {
2347       MVT::ValueType OVT = Tmp1.getValueType();
2348       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2349       unsigned DiffBits = getSizeInBits(NVT) - getSizeInBits(OVT);
2350
2351       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2352       Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2353       Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2354                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2355       break;
2356     }
2357     case TargetLowering::Expand:
2358       Result = ExpandBSWAP(Tmp1);
2359       break;
2360     }
2361     break;
2362     
2363   case ISD::CTPOP:
2364   case ISD::CTTZ:
2365   case ISD::CTLZ:
2366     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2367     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2368     case TargetLowering::Custom: assert(0 && "Cannot custom handle this yet!");
2369     case TargetLowering::Legal:
2370       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2371       break;
2372     case TargetLowering::Promote: {
2373       MVT::ValueType OVT = Tmp1.getValueType();
2374       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2375
2376       // Zero extend the argument.
2377       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2378       // Perform the larger operation, then subtract if needed.
2379       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2380       switch (Node->getOpcode()) {
2381       case ISD::CTPOP:
2382         Result = Tmp1;
2383         break;
2384       case ISD::CTTZ:
2385         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2386         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2387                             DAG.getConstant(getSizeInBits(NVT), NVT),
2388                             ISD::SETEQ);
2389         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2390                            DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2391         break;
2392       case ISD::CTLZ:
2393         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2394         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2395                              DAG.getConstant(getSizeInBits(NVT) -
2396                                              getSizeInBits(OVT), NVT));
2397         break;
2398       }
2399       break;
2400     }
2401     case TargetLowering::Expand:
2402       Result = ExpandBitCount(Node->getOpcode(), Tmp1);
2403       break;
2404     }
2405     break;
2406
2407     // Unary operators
2408   case ISD::FABS:
2409   case ISD::FNEG:
2410   case ISD::FSQRT:
2411   case ISD::FSIN:
2412   case ISD::FCOS:
2413     Tmp1 = LegalizeOp(Node->getOperand(0));
2414     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2415     case TargetLowering::Promote:
2416     case TargetLowering::Custom:
2417      isCustom = true;
2418      // FALLTHROUGH
2419     case TargetLowering::Legal:
2420       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2421       if (isCustom) {
2422         Tmp1 = TLI.LowerOperation(Result, DAG);
2423         if (Tmp1.Val) Result = Tmp1;
2424       }
2425       break;
2426     case TargetLowering::Expand:
2427       switch (Node->getOpcode()) {
2428       default: assert(0 && "Unreachable!");
2429       case ISD::FNEG:
2430         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2431         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2432         Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
2433         break;
2434       case ISD::FABS: {
2435         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2436         MVT::ValueType VT = Node->getValueType(0);
2437         Tmp2 = DAG.getConstantFP(0.0, VT);
2438         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2439         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2440         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2441         break;
2442       }
2443       case ISD::FSQRT:
2444       case ISD::FSIN:
2445       case ISD::FCOS: {
2446         MVT::ValueType VT = Node->getValueType(0);
2447         const char *FnName = 0;
2448         switch(Node->getOpcode()) {
2449         case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2450         case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2451         case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2452         default: assert(0 && "Unreachable!");
2453         }
2454         SDOperand Dummy;
2455         Result = ExpandLibCall(FnName, Node, Dummy);
2456         break;
2457       }
2458       }
2459       break;
2460     }
2461     break;
2462     
2463   case ISD::BIT_CONVERT:
2464     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
2465       Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2466     } else {
2467       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2468                                      Node->getOperand(0).getValueType())) {
2469       default: assert(0 && "Unknown operation action!");
2470       case TargetLowering::Expand:
2471         Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2472         break;
2473       case TargetLowering::Legal:
2474         Tmp1 = LegalizeOp(Node->getOperand(0));
2475         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2476         break;
2477       }
2478     }
2479     break;
2480   case ISD::VBIT_CONVERT: {
2481     assert(Op.getOperand(0).getValueType() == MVT::Vector &&
2482            "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
2483     
2484     // The input has to be a vector type, we have to either scalarize it, pack
2485     // it, or convert it based on whether the input vector type is legal.
2486     SDNode *InVal = Node->getOperand(0).Val;
2487     unsigned NumElems =
2488       cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
2489     MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
2490     
2491     // Figure out if there is a Packed type corresponding to this Vector
2492     // type.  If so, convert to the packed type.
2493     MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2494     if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
2495       // Turn this into a bit convert of the packed input.
2496       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
2497                            PackVectorOp(Node->getOperand(0), TVT));
2498       break;
2499     } else if (NumElems == 1) {
2500       // Turn this into a bit convert of the scalar input.
2501       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
2502                            PackVectorOp(Node->getOperand(0), EVT));
2503       break;
2504     } else {
2505       // FIXME: UNIMP!  Store then reload
2506       assert(0 && "Cast from unsupported vector type not implemented yet!");
2507     }
2508   }
2509       
2510     // Conversion operators.  The source and destination have different types.
2511   case ISD::SINT_TO_FP:
2512   case ISD::UINT_TO_FP: {
2513     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2514     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2515     case Legal:
2516       switch (TLI.getOperationAction(Node->getOpcode(),
2517                                      Node->getOperand(0).getValueType())) {
2518       default: assert(0 && "Unknown operation action!");
2519       case TargetLowering::Custom:
2520         isCustom = true;
2521         // FALLTHROUGH
2522       case TargetLowering::Legal:
2523         Tmp1 = LegalizeOp(Node->getOperand(0));
2524         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2525         if (isCustom) {
2526           Tmp1 = TLI.LowerOperation(Result, DAG);
2527           if (Tmp1.Val) Result = Tmp1;
2528         }
2529         break;
2530       case TargetLowering::Expand:
2531         Result = ExpandLegalINT_TO_FP(isSigned,
2532                                       LegalizeOp(Node->getOperand(0)),
2533                                       Node->getValueType(0));
2534         break;
2535       case TargetLowering::Promote:
2536         Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2537                                        Node->getValueType(0),
2538                                        isSigned);
2539         break;
2540       }
2541       break;
2542     case Expand:
2543       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2544                              Node->getValueType(0), Node->getOperand(0));
2545       break;
2546     case Promote:
2547       Tmp1 = PromoteOp(Node->getOperand(0));
2548       if (isSigned) {
2549         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
2550                  Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
2551       } else {
2552         Tmp1 = DAG.getZeroExtendInReg(Tmp1,
2553                                       Node->getOperand(0).getValueType());
2554       }
2555       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2556       Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
2557       break;
2558     }
2559     break;
2560   }
2561   case ISD::TRUNCATE:
2562     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2563     case Legal:
2564       Tmp1 = LegalizeOp(Node->getOperand(0));
2565       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2566       break;
2567     case Expand:
2568       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2569
2570       // Since the result is legal, we should just be able to truncate the low
2571       // part of the source.
2572       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2573       break;
2574     case Promote:
2575       Result = PromoteOp(Node->getOperand(0));
2576       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2577       break;
2578     }
2579     break;
2580
2581   case ISD::FP_TO_SINT:
2582   case ISD::FP_TO_UINT:
2583     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2584     case Legal:
2585       Tmp1 = LegalizeOp(Node->getOperand(0));
2586
2587       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2588       default: assert(0 && "Unknown operation action!");
2589       case TargetLowering::Custom:
2590         isCustom = true;
2591         // FALLTHROUGH
2592       case TargetLowering::Legal:
2593         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2594         if (isCustom) {
2595           Tmp1 = TLI.LowerOperation(Result, DAG);
2596           if (Tmp1.Val) Result = Tmp1;
2597         }
2598         break;
2599       case TargetLowering::Promote:
2600         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2601                                        Node->getOpcode() == ISD::FP_TO_SINT);
2602         break;
2603       case TargetLowering::Expand:
2604         if (Node->getOpcode() == ISD::FP_TO_UINT) {
2605           SDOperand True, False;
2606           MVT::ValueType VT =  Node->getOperand(0).getValueType();
2607           MVT::ValueType NVT = Node->getValueType(0);
2608           unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2609           Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2610           Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2611                             Node->getOperand(0), Tmp2, ISD::SETLT);
2612           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2613           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2614                               DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2615                                           Tmp2));
2616           False = DAG.getNode(ISD::XOR, NVT, False, 
2617                               DAG.getConstant(1ULL << ShiftAmt, NVT));
2618           Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
2619           break;
2620         } else {
2621           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2622         }
2623         break;
2624       }
2625       break;
2626     case Expand:
2627       assert(0 && "Shouldn't need to expand other operators here!");
2628     case Promote:
2629       Tmp1 = PromoteOp(Node->getOperand(0));
2630       Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
2631       Result = LegalizeOp(Result);
2632       break;
2633     }
2634     break;
2635
2636   case ISD::ANY_EXTEND:
2637   case ISD::ZERO_EXTEND:
2638   case ISD::SIGN_EXTEND:
2639   case ISD::FP_EXTEND:
2640   case ISD::FP_ROUND:
2641     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2642     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
2643     case Legal:
2644       Tmp1 = LegalizeOp(Node->getOperand(0));
2645       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2646       break;
2647     case Promote:
2648       switch (Node->getOpcode()) {
2649       case ISD::ANY_EXTEND:
2650         Tmp1 = PromoteOp(Node->getOperand(0));
2651         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
2652         break;
2653       case ISD::ZERO_EXTEND:
2654         Result = PromoteOp(Node->getOperand(0));
2655         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2656         Result = DAG.getZeroExtendInReg(Result,
2657                                         Node->getOperand(0).getValueType());
2658         break;
2659       case ISD::SIGN_EXTEND:
2660         Result = PromoteOp(Node->getOperand(0));
2661         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2662         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2663                              Result,
2664                           DAG.getValueType(Node->getOperand(0).getValueType()));
2665         break;
2666       case ISD::FP_EXTEND:
2667         Result = PromoteOp(Node->getOperand(0));
2668         if (Result.getValueType() != Op.getValueType())
2669           // Dynamically dead while we have only 2 FP types.
2670           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2671         break;
2672       case ISD::FP_ROUND:
2673         Result = PromoteOp(Node->getOperand(0));
2674         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2675         break;
2676       }
2677     }
2678     break;
2679   case ISD::FP_ROUND_INREG:
2680   case ISD::SIGN_EXTEND_INREG: {
2681     Tmp1 = LegalizeOp(Node->getOperand(0));
2682     MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2683
2684     // If this operation is not supported, convert it to a shl/shr or load/store
2685     // pair.
2686     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2687     default: assert(0 && "This action not supported for this op yet!");
2688     case TargetLowering::Legal:
2689       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2690       break;
2691     case TargetLowering::Expand:
2692       // If this is an integer extend and shifts are supported, do that.
2693       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2694         // NOTE: we could fall back on load/store here too for targets without
2695         // SAR.  However, it is doubtful that any exist.
2696         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2697                             MVT::getSizeInBits(ExtraVT);
2698         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2699         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2700                              Node->getOperand(0), ShiftCst);
2701         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2702                              Result, ShiftCst);
2703       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2704         // The only way we can lower this is to turn it into a STORETRUNC,
2705         // EXTLOAD pair, targetting a temporary location (a stack slot).
2706
2707         // NOTE: there is a choice here between constantly creating new stack
2708         // slots and always reusing the same one.  We currently always create
2709         // new ones, as reuse may inhibit scheduling.
2710         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2711         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2712         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2713         MachineFunction &MF = DAG.getMachineFunction();
2714         int SSFI =
2715           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2716         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2717         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2718                              Node->getOperand(0), StackSlot,
2719                              DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2720         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2721                                 Result, StackSlot, DAG.getSrcValue(NULL),
2722                                 ExtraVT);
2723       } else {
2724         assert(0 && "Unknown op");
2725       }
2726       break;
2727     }
2728     break;
2729   }
2730   }
2731   
2732   assert(Result.getValueType() == Op.getValueType() &&
2733          "Bad legalization!");
2734   
2735   // Make sure that the generated code is itself legal.
2736   if (Result != Op)
2737     Result = LegalizeOp(Result);
2738
2739   // Note that LegalizeOp may be reentered even from single-use nodes, which
2740   // means that we always must cache transformed nodes.
2741   AddLegalizedOperand(Op, Result);
2742   return Result;
2743 }
2744
2745 /// PromoteOp - Given an operation that produces a value in an invalid type,
2746 /// promote it to compute the value into a larger type.  The produced value will
2747 /// have the correct bits for the low portion of the register, but no guarantee
2748 /// is made about the top bits: it may be zero, sign-extended, or garbage.
2749 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2750   MVT::ValueType VT = Op.getValueType();
2751   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2752   assert(getTypeAction(VT) == Promote &&
2753          "Caller should expand or legalize operands that are not promotable!");
2754   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2755          "Cannot promote to smaller type!");
2756
2757   SDOperand Tmp1, Tmp2, Tmp3;
2758   SDOperand Result;
2759   SDNode *Node = Op.Val;
2760
2761   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2762   if (I != PromotedNodes.end()) return I->second;
2763
2764   switch (Node->getOpcode()) {
2765   case ISD::CopyFromReg:
2766     assert(0 && "CopyFromReg must be legal!");
2767   default:
2768     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2769     assert(0 && "Do not know how to promote this operator!");
2770     abort();
2771   case ISD::UNDEF:
2772     Result = DAG.getNode(ISD::UNDEF, NVT);
2773     break;
2774   case ISD::Constant:
2775     if (VT != MVT::i1)
2776       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2777     else
2778       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2779     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2780     break;
2781   case ISD::ConstantFP:
2782     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2783     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2784     break;
2785
2786   case ISD::SETCC:
2787     assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2788     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2789                          Node->getOperand(1), Node->getOperand(2));
2790     break;
2791     
2792   case ISD::TRUNCATE:
2793     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2794     case Legal:
2795       Result = LegalizeOp(Node->getOperand(0));
2796       assert(Result.getValueType() >= NVT &&
2797              "This truncation doesn't make sense!");
2798       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2799         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2800       break;
2801     case Promote:
2802       // The truncation is not required, because we don't guarantee anything
2803       // about high bits anyway.
2804       Result = PromoteOp(Node->getOperand(0));
2805       break;
2806     case Expand:
2807       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2808       // Truncate the low part of the expanded value to the result type
2809       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2810     }
2811     break;
2812   case ISD::SIGN_EXTEND:
2813   case ISD::ZERO_EXTEND:
2814   case ISD::ANY_EXTEND:
2815     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2816     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2817     case Legal:
2818       // Input is legal?  Just do extend all the way to the larger type.
2819       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2820       break;
2821     case Promote:
2822       // Promote the reg if it's smaller.
2823       Result = PromoteOp(Node->getOperand(0));
2824       // The high bits are not guaranteed to be anything.  Insert an extend.
2825       if (Node->getOpcode() == ISD::SIGN_EXTEND)
2826         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2827                          DAG.getValueType(Node->getOperand(0).getValueType()));
2828       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2829         Result = DAG.getZeroExtendInReg(Result,
2830                                         Node->getOperand(0).getValueType());
2831       break;
2832     }
2833     break;
2834   case ISD::BIT_CONVERT:
2835     Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2836     Result = PromoteOp(Result);
2837     break;
2838     
2839   case ISD::FP_EXTEND:
2840     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2841   case ISD::FP_ROUND:
2842     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2843     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2844     case Promote:  assert(0 && "Unreachable with 2 FP types!");
2845     case Legal:
2846       // Input is legal?  Do an FP_ROUND_INREG.
2847       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
2848                            DAG.getValueType(VT));
2849       break;
2850     }
2851     break;
2852
2853   case ISD::SINT_TO_FP:
2854   case ISD::UINT_TO_FP:
2855     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2856     case Legal:
2857       // No extra round required here.
2858       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2859       break;
2860
2861     case Promote:
2862       Result = PromoteOp(Node->getOperand(0));
2863       if (Node->getOpcode() == ISD::SINT_TO_FP)
2864         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2865                              Result,
2866                          DAG.getValueType(Node->getOperand(0).getValueType()));
2867       else
2868         Result = DAG.getZeroExtendInReg(Result,
2869                                         Node->getOperand(0).getValueType());
2870       // No extra round required here.
2871       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2872       break;
2873     case Expand:
2874       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2875                              Node->getOperand(0));
2876       // Round if we cannot tolerate excess precision.
2877       if (NoExcessFPPrecision)
2878         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2879                              DAG.getValueType(VT));
2880       break;
2881     }
2882     break;
2883
2884   case ISD::SIGN_EXTEND_INREG:
2885     Result = PromoteOp(Node->getOperand(0));
2886     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
2887                          Node->getOperand(1));
2888     break;
2889   case ISD::FP_TO_SINT:
2890   case ISD::FP_TO_UINT:
2891     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2892     case Legal:
2893       Tmp1 = Node->getOperand(0);
2894       break;
2895     case Promote:
2896       // The input result is prerounded, so we don't have to do anything
2897       // special.
2898       Tmp1 = PromoteOp(Node->getOperand(0));
2899       break;
2900     case Expand:
2901       assert(0 && "not implemented");
2902     }
2903     // If we're promoting a UINT to a larger size, check to see if the new node
2904     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2905     // we can use that instead.  This allows us to generate better code for
2906     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2907     // legal, such as PowerPC.
2908     if (Node->getOpcode() == ISD::FP_TO_UINT && 
2909         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2910         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2911          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2912       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2913     } else {
2914       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2915     }
2916     break;
2917
2918   case ISD::FABS:
2919   case ISD::FNEG:
2920     Tmp1 = PromoteOp(Node->getOperand(0));
2921     assert(Tmp1.getValueType() == NVT);
2922     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2923     // NOTE: we do not have to do any extra rounding here for
2924     // NoExcessFPPrecision, because we know the input will have the appropriate
2925     // precision, and these operations don't modify precision at all.
2926     break;
2927
2928   case ISD::FSQRT:
2929   case ISD::FSIN:
2930   case ISD::FCOS:
2931     Tmp1 = PromoteOp(Node->getOperand(0));
2932     assert(Tmp1.getValueType() == NVT);
2933     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2934     if (NoExcessFPPrecision)
2935       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2936                            DAG.getValueType(VT));
2937     break;
2938
2939   case ISD::AND:
2940   case ISD::OR:
2941   case ISD::XOR:
2942   case ISD::ADD:
2943   case ISD::SUB:
2944   case ISD::MUL:
2945     // The input may have strange things in the top bits of the registers, but
2946     // these operations don't care.  They may have weird bits going out, but
2947     // that too is okay if they are integer operations.
2948     Tmp1 = PromoteOp(Node->getOperand(0));
2949     Tmp2 = PromoteOp(Node->getOperand(1));
2950     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2951     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2952     break;
2953   case ISD::FADD:
2954   case ISD::FSUB:
2955   case ISD::FMUL:
2956     Tmp1 = PromoteOp(Node->getOperand(0));
2957     Tmp2 = PromoteOp(Node->getOperand(1));
2958     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2959     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2960     
2961     // Floating point operations will give excess precision that we may not be
2962     // able to tolerate.  If we DO allow excess precision, just leave it,
2963     // otherwise excise it.
2964     // FIXME: Why would we need to round FP ops more than integer ones?
2965     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2966     if (NoExcessFPPrecision)
2967       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2968                            DAG.getValueType(VT));
2969     break;
2970
2971   case ISD::SDIV:
2972   case ISD::SREM:
2973     // These operators require that their input be sign extended.
2974     Tmp1 = PromoteOp(Node->getOperand(0));
2975     Tmp2 = PromoteOp(Node->getOperand(1));
2976     if (MVT::isInteger(NVT)) {
2977       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2978                          DAG.getValueType(VT));
2979       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2980                          DAG.getValueType(VT));
2981     }
2982     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2983
2984     // Perform FP_ROUND: this is probably overly pessimistic.
2985     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2986       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2987                            DAG.getValueType(VT));
2988     break;
2989   case ISD::FDIV:
2990   case ISD::FREM:
2991   case ISD::FCOPYSIGN:
2992     // These operators require that their input be fp extended.
2993     Tmp1 = PromoteOp(Node->getOperand(0));
2994     Tmp2 = PromoteOp(Node->getOperand(1));
2995     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2996     
2997     // Perform FP_ROUND: this is probably overly pessimistic.
2998     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
2999       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3000                            DAG.getValueType(VT));
3001     break;
3002
3003   case ISD::UDIV:
3004   case ISD::UREM:
3005     // These operators require that their input be zero extended.
3006     Tmp1 = PromoteOp(Node->getOperand(0));
3007     Tmp2 = PromoteOp(Node->getOperand(1));
3008     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
3009     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3010     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3011     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3012     break;
3013
3014   case ISD::SHL:
3015     Tmp1 = PromoteOp(Node->getOperand(0));
3016     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
3017     break;
3018   case ISD::SRA:
3019     // The input value must be properly sign extended.
3020     Tmp1 = PromoteOp(Node->getOperand(0));
3021     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3022                        DAG.getValueType(VT));
3023     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
3024     break;
3025   case ISD::SRL:
3026     // The input value must be properly zero extended.
3027     Tmp1 = PromoteOp(Node->getOperand(0));
3028     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3029     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
3030     break;
3031
3032   case ISD::VAARG:
3033     Tmp1 = Node->getOperand(0);   // Get the chain.
3034     Tmp2 = Node->getOperand(1);   // Get the pointer.
3035     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
3036       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
3037       Result = TLI.CustomPromoteOperation(Tmp3, DAG);
3038     } else {
3039       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
3040                                      Node->getOperand(2));
3041       // Increment the pointer, VAList, to the next vaarg
3042       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
3043                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
3044                                          TLI.getPointerTy()));
3045       // Store the incremented VAList to the legalized pointer
3046       Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
3047                          Node->getOperand(2));
3048       // Load the actual argument out of the pointer VAList
3049       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList,
3050                               DAG.getSrcValue(0), VT);
3051     }
3052     // Remember that we legalized the chain.
3053     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3054     break;
3055
3056   case ISD::LOAD:
3057     Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Node->getOperand(0),
3058                             Node->getOperand(1), Node->getOperand(2), VT);
3059     // Remember that we legalized the chain.
3060     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3061     break;
3062   case ISD::SEXTLOAD:
3063   case ISD::ZEXTLOAD:
3064   case ISD::EXTLOAD:
3065     Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
3066                             Node->getOperand(1), Node->getOperand(2),
3067                             cast<VTSDNode>(Node->getOperand(3))->getVT());
3068     // Remember that we legalized the chain.
3069     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3070     break;
3071   case ISD::SELECT:
3072     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
3073     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
3074     Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
3075     break;
3076   case ISD::SELECT_CC:
3077     Tmp2 = PromoteOp(Node->getOperand(2));   // True
3078     Tmp3 = PromoteOp(Node->getOperand(3));   // False
3079     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3080                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
3081     break;
3082   case ISD::BSWAP:
3083     Tmp1 = Node->getOperand(0);
3084     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3085     Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3086     Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3087                          DAG.getConstant(getSizeInBits(NVT) - getSizeInBits(VT),
3088                                          TLI.getShiftAmountTy()));
3089     break;
3090   case ISD::CTPOP:
3091   case ISD::CTTZ:
3092   case ISD::CTLZ:
3093     // Zero extend the argument
3094     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
3095     // Perform the larger operation, then subtract if needed.
3096     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3097     switch(Node->getOpcode()) {
3098     case ISD::CTPOP:
3099       Result = Tmp1;
3100       break;
3101     case ISD::CTTZ:
3102       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3103       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
3104                           DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
3105       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3106                            DAG.getConstant(getSizeInBits(VT), NVT), Tmp1);
3107       break;
3108     case ISD::CTLZ:
3109       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3110       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3111                            DAG.getConstant(getSizeInBits(NVT) -
3112                                            getSizeInBits(VT), NVT));
3113       break;
3114     }
3115     break;
3116   case ISD::VEXTRACT_VECTOR_ELT:
3117     Result = PromoteOp(LowerVEXTRACT_VECTOR_ELT(Op));
3118     break;
3119   case ISD::EXTRACT_VECTOR_ELT:
3120     Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
3121     break;
3122   }
3123
3124   assert(Result.Val && "Didn't set a result!");
3125
3126   // Make sure the result is itself legal.
3127   Result = LegalizeOp(Result);
3128   
3129   // Remember that we promoted this!
3130   AddPromotedOperand(Op, Result);
3131   return Result;
3132 }
3133
3134 /// LowerVEXTRACT_VECTOR_ELT - Lower a VEXTRACT_VECTOR_ELT operation into a
3135 /// EXTRACT_VECTOR_ELT operation, to memory operations, or to scalar code based
3136 /// on the vector type.  The return type of this matches the element type of the
3137 /// vector, which may not be legal for the target.
3138 SDOperand SelectionDAGLegalize::LowerVEXTRACT_VECTOR_ELT(SDOperand Op) {
3139   // We know that operand #0 is the Vec vector.  If the index is a constant
3140   // or if the invec is a supported hardware type, we can use it.  Otherwise,
3141   // lower to a store then an indexed load.
3142   SDOperand Vec = Op.getOperand(0);
3143   SDOperand Idx = LegalizeOp(Op.getOperand(1));
3144   
3145   SDNode *InVal = Vec.Val;
3146   unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
3147   MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
3148   
3149   // Figure out if there is a Packed type corresponding to this Vector
3150   // type.  If so, convert to the packed type.
3151   MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
3152   if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
3153     // Turn this into a packed extract_vector_elt operation.
3154     Vec = PackVectorOp(Vec, TVT);
3155     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Op.getValueType(), Vec, Idx);
3156   } else if (NumElems == 1) {
3157     // This must be an access of the only element.  Return it.
3158     return PackVectorOp(Vec, EVT);
3159   } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3160     SDOperand Lo, Hi;
3161     SplitVectorOp(Vec, Lo, Hi);
3162     if (CIdx->getValue() < NumElems/2) {
3163       Vec = Lo;
3164     } else {
3165       Vec = Hi;
3166       Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
3167     }
3168     
3169     // It's now an extract from the appropriate high or low part.  Recurse.
3170     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
3171     return LowerVEXTRACT_VECTOR_ELT(Op);
3172   } else {
3173     // Variable index case for extract element.
3174     // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
3175     assert(0 && "unimp!");
3176     return SDOperand();
3177   }
3178 }
3179
3180 /// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
3181 /// memory traffic.
3182 SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
3183   SDOperand Vector = Op.getOperand(0);
3184   SDOperand Idx    = Op.getOperand(1);
3185   
3186   // If the target doesn't support this, store the value to a temporary
3187   // stack slot, then LOAD the scalar element back out.
3188   SDOperand StackPtr = CreateStackTemporary(Vector.getValueType());
3189   SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3190                              Vector, StackPtr, DAG.getSrcValue(NULL));
3191   
3192   // Add the offset to the index.
3193   unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
3194   Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
3195                     DAG.getConstant(EltSize, Idx.getValueType()));
3196   StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
3197   
3198   return DAG.getLoad(Op.getValueType(), Ch, StackPtr, DAG.getSrcValue(NULL));
3199 }
3200
3201
3202 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
3203 /// with condition CC on the current target.  This usually involves legalizing
3204 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
3205 /// there may be no choice but to create a new SetCC node to represent the
3206 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
3207 /// LHS, and the SDOperand returned in RHS has a nil SDNode value.
3208 void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
3209                                                  SDOperand &RHS,
3210                                                  SDOperand &CC) {
3211   SDOperand Tmp1, Tmp2, Result;    
3212   
3213   switch (getTypeAction(LHS.getValueType())) {
3214   case Legal:
3215     Tmp1 = LegalizeOp(LHS);   // LHS
3216     Tmp2 = LegalizeOp(RHS);   // RHS
3217     break;
3218   case Promote:
3219     Tmp1 = PromoteOp(LHS);   // LHS
3220     Tmp2 = PromoteOp(RHS);   // RHS
3221
3222     // If this is an FP compare, the operands have already been extended.
3223     if (MVT::isInteger(LHS.getValueType())) {
3224       MVT::ValueType VT = LHS.getValueType();
3225       MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3226
3227       // Otherwise, we have to insert explicit sign or zero extends.  Note
3228       // that we could insert sign extends for ALL conditions, but zero extend
3229       // is cheaper on many machines (an AND instead of two shifts), so prefer
3230       // it.
3231       switch (cast<CondCodeSDNode>(CC)->get()) {
3232       default: assert(0 && "Unknown integer comparison!");
3233       case ISD::SETEQ:
3234       case ISD::SETNE:
3235       case ISD::SETUGE:
3236       case ISD::SETUGT:
3237       case ISD::SETULE:
3238       case ISD::SETULT:
3239         // ALL of these operations will work if we either sign or zero extend
3240         // the operands (including the unsigned comparisons!).  Zero extend is
3241         // usually a simpler/cheaper operation, so prefer it.
3242         Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3243         Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3244         break;
3245       case ISD::SETGE:
3246       case ISD::SETGT:
3247       case ISD::SETLT:
3248       case ISD::SETLE:
3249         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3250                            DAG.getValueType(VT));
3251         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3252                            DAG.getValueType(VT));
3253         break;
3254       }
3255     }
3256     break;
3257   case Expand:
3258     SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
3259     ExpandOp(LHS, LHSLo, LHSHi);
3260     ExpandOp(RHS, RHSLo, RHSHi);
3261     switch (cast<CondCodeSDNode>(CC)->get()) {
3262     case ISD::SETEQ:
3263     case ISD::SETNE:
3264       if (RHSLo == RHSHi)
3265         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
3266           if (RHSCST->isAllOnesValue()) {
3267             // Comparison to -1.
3268             Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
3269             Tmp2 = RHSLo;
3270             break;
3271           }
3272
3273       Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
3274       Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
3275       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
3276       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3277       break;
3278     default:
3279       // If this is a comparison of the sign bit, just look at the top part.
3280       // X > -1,  x < 0
3281       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
3282         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT && 
3283              CST->getValue() == 0) ||             // X < 0
3284             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
3285              CST->isAllOnesValue())) {            // X > -1
3286           Tmp1 = LHSHi;
3287           Tmp2 = RHSHi;
3288           break;
3289         }
3290
3291       // FIXME: This generated code sucks.
3292       ISD::CondCode LowCC;
3293       switch (cast<CondCodeSDNode>(CC)->get()) {
3294       default: assert(0 && "Unknown integer setcc!");
3295       case ISD::SETLT:
3296       case ISD::SETULT: LowCC = ISD::SETULT; break;
3297       case ISD::SETGT:
3298       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
3299       case ISD::SETLE:
3300       case ISD::SETULE: LowCC = ISD::SETULE; break;
3301       case ISD::SETGE:
3302       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
3303       }
3304
3305       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
3306       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
3307       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
3308
3309       // NOTE: on targets without efficient SELECT of bools, we can always use
3310       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
3311       Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
3312       Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi, CC);
3313       Result = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
3314       Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
3315                                       Result, Tmp1, Tmp2));
3316       Tmp1 = Result;
3317       Tmp2 = SDOperand();
3318     }
3319   }
3320   LHS = Tmp1;
3321   RHS = Tmp2;
3322 }
3323
3324 /// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
3325 /// The resultant code need not be legal.  Note that SrcOp is the input operand
3326 /// to the BIT_CONVERT, not the BIT_CONVERT node itself.
3327 SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
3328                                                   SDOperand SrcOp) {
3329   // Create the stack frame object.
3330   SDOperand FIPtr = CreateStackTemporary(DestVT);
3331   
3332   // Emit a store to the stack slot.
3333   SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3334                                 SrcOp, FIPtr, DAG.getSrcValue(NULL));
3335   // Result is a load from the stack slot.
3336   return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
3337 }
3338
3339 SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
3340   // Create a vector sized/aligned stack slot, store the value to element #0,
3341   // then load the whole vector back out.
3342   SDOperand StackPtr = CreateStackTemporary(Node->getValueType(0));
3343   SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3344                              Node->getOperand(0), StackPtr,
3345                              DAG.getSrcValue(NULL));
3346   return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,DAG.getSrcValue(NULL));
3347 }
3348
3349
3350 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
3351 /// support the operation, but do support the resultant packed vector type.
3352 SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
3353   
3354   // If the only non-undef value is the low element, turn this into a 
3355   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
3356   unsigned NumElems = Node->getNumOperands();
3357   bool isOnlyLowElement = true;
3358   SDOperand SplatValue = Node->getOperand(0);
3359   std::map<SDOperand, std::vector<unsigned> > Values;
3360   Values[SplatValue].push_back(0);
3361   bool isConstant = true;
3362   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
3363       SplatValue.getOpcode() != ISD::UNDEF)
3364     isConstant = false;
3365   
3366   for (unsigned i = 1; i < NumElems; ++i) {
3367     SDOperand V = Node->getOperand(i);
3368     std::map<SDOperand, std::vector<unsigned> >::iterator I = Values.find(V);
3369     if (I != Values.end())
3370       I->second.push_back(i);
3371     else
3372       Values[V].push_back(i);
3373     if (V.getOpcode() != ISD::UNDEF)
3374       isOnlyLowElement = false;
3375     if (SplatValue != V)
3376       SplatValue = SDOperand(0,0);
3377
3378     // If this isn't a constant element or an undef, we can't use a constant
3379     // pool load.
3380     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
3381         V.getOpcode() != ISD::UNDEF)
3382       isConstant = false;
3383   }
3384   
3385   if (isOnlyLowElement) {
3386     // If the low element is an undef too, then this whole things is an undef.
3387     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
3388       return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
3389     // Otherwise, turn this into a scalar_to_vector node.
3390     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3391                        Node->getOperand(0));
3392   }
3393   
3394   // If all elements are constants, create a load from the constant pool.
3395   if (isConstant) {
3396     MVT::ValueType VT = Node->getValueType(0);
3397     const Type *OpNTy = 
3398       MVT::getTypeForValueType(Node->getOperand(0).getValueType());
3399     std::vector<Constant*> CV;
3400     for (unsigned i = 0, e = NumElems; i != e; ++i) {
3401       if (ConstantFPSDNode *V = 
3402           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
3403         CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
3404       } else if (ConstantSDNode *V = 
3405                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
3406         CV.push_back(ConstantUInt::get(OpNTy, V->getValue()));
3407       } else {
3408         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
3409         CV.push_back(UndefValue::get(OpNTy));
3410       }
3411     }
3412     Constant *CP = ConstantPacked::get(CV);
3413     SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
3414     return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
3415                        DAG.getSrcValue(NULL));
3416   }
3417   
3418   if (SplatValue.Val) {   // Splat of one value?
3419     // Build the shuffle constant vector: <0, 0, 0, 0>
3420     MVT::ValueType MaskVT = 
3421       MVT::getIntVectorWithNumElements(NumElems);
3422     SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
3423     std::vector<SDOperand> ZeroVec(NumElems, Zero);
3424     SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
3425
3426     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3427     if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
3428       // Get the splatted value into the low element of a vector register.
3429       SDOperand LowValVec = 
3430         DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
3431     
3432       // Return shuffle(LowValVec, undef, <0,0,0,0>)
3433       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
3434                          DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
3435                          SplatMask);
3436     }
3437   }
3438   
3439   // If there are only two unique elements, we may be able to turn this into a
3440   // vector shuffle.
3441   if (Values.size() == 2) {
3442     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
3443     MVT::ValueType MaskVT = 
3444       MVT::getIntVectorWithNumElements(NumElems);
3445     std::vector<SDOperand> MaskVec(NumElems);
3446     unsigned i = 0;
3447     for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3448            E = Values.end(); I != E; ++I) {
3449       for (std::vector<unsigned>::iterator II = I->second.begin(),
3450              EE = I->second.end(); II != EE; ++II)
3451         MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
3452       i += NumElems;
3453     }
3454     SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
3455
3456     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3457     if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
3458         isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
3459       std::vector<SDOperand> Ops;
3460       for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3461             E = Values.end(); I != E; ++I) {
3462         SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3463                                    I->first);
3464         Ops.push_back(Op);
3465       }
3466       Ops.push_back(ShuffleMask);
3467
3468       // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
3469       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops);
3470     }
3471   }
3472   
3473   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
3474   // aligned object on the stack, store each element into it, then load
3475   // the result as a vector.
3476   MVT::ValueType VT = Node->getValueType(0);
3477   // Create the stack frame object.
3478   SDOperand FIPtr = CreateStackTemporary(VT);
3479   
3480   // Emit a store of each element to the stack slot.
3481   std::vector<SDOperand> Stores;
3482   unsigned TypeByteSize = 
3483     MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
3484   unsigned VectorSize = MVT::getSizeInBits(VT)/8;
3485   // Store (in the right endianness) the elements to memory.
3486   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3487     // Ignore undef elements.
3488     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3489     
3490     unsigned Offset = TypeByteSize*i;
3491     
3492     SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
3493     Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
3494     
3495     Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3496                                  Node->getOperand(i), Idx, 
3497                                  DAG.getSrcValue(NULL)));
3498   }
3499   
3500   SDOperand StoreChain;
3501   if (!Stores.empty())    // Not all undef elements?
3502     StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
3503   else
3504     StoreChain = DAG.getEntryNode();
3505   
3506   // Result is a load from the stack slot.
3507   return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
3508 }
3509
3510 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
3511 /// specified value type.
3512 SDOperand SelectionDAGLegalize::CreateStackTemporary(MVT::ValueType VT) {
3513   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3514   unsigned ByteSize = MVT::getSizeInBits(VT)/8;
3515   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
3516   return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
3517 }
3518
3519 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
3520                                             SDOperand Op, SDOperand Amt,
3521                                             SDOperand &Lo, SDOperand &Hi) {
3522   // Expand the subcomponents.
3523   SDOperand LHSL, LHSH;
3524   ExpandOp(Op, LHSL, LHSH);
3525
3526   std::vector<SDOperand> Ops;
3527   Ops.push_back(LHSL);
3528   Ops.push_back(LHSH);
3529   Ops.push_back(Amt);
3530   std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
3531   Lo = DAG.getNode(NodeOp, VTs, Ops);
3532   Hi = Lo.getValue(1);
3533 }
3534
3535
3536 /// ExpandShift - Try to find a clever way to expand this shift operation out to
3537 /// smaller elements.  If we can't find a way that is more efficient than a
3538 /// libcall on this target, return false.  Otherwise, return true with the
3539 /// low-parts expanded into Lo and Hi.
3540 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
3541                                        SDOperand &Lo, SDOperand &Hi) {
3542   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
3543          "This is not a shift!");
3544
3545   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
3546   SDOperand ShAmt = LegalizeOp(Amt);
3547   MVT::ValueType ShTy = ShAmt.getValueType();
3548   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
3549   unsigned NVTBits = MVT::getSizeInBits(NVT);
3550
3551   // Handle the case when Amt is an immediate.  Other cases are currently broken
3552   // and are disabled.
3553   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
3554     unsigned Cst = CN->getValue();
3555     // Expand the incoming operand to be shifted, so that we have its parts
3556     SDOperand InL, InH;
3557     ExpandOp(Op, InL, InH);
3558     switch(Opc) {
3559     case ISD::SHL:
3560       if (Cst > VTBits) {
3561         Lo = DAG.getConstant(0, NVT);
3562         Hi = DAG.getConstant(0, NVT);
3563       } else if (Cst > NVTBits) {
3564         Lo = DAG.getConstant(0, NVT);
3565         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
3566       } else if (Cst == NVTBits) {
3567         Lo = DAG.getConstant(0, NVT);
3568         Hi = InL;
3569       } else {
3570         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
3571         Hi = DAG.getNode(ISD::OR, NVT,
3572            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
3573            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
3574       }
3575       return true;
3576     case ISD::SRL:
3577       if (Cst > VTBits) {
3578         Lo = DAG.getConstant(0, NVT);
3579         Hi = DAG.getConstant(0, NVT);
3580       } else if (Cst > NVTBits) {
3581         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
3582         Hi = DAG.getConstant(0, NVT);
3583       } else if (Cst == NVTBits) {
3584         Lo = InH;
3585         Hi = DAG.getConstant(0, NVT);
3586       } else {
3587         Lo = DAG.getNode(ISD::OR, NVT,
3588            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3589            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3590         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
3591       }
3592       return true;
3593     case ISD::SRA:
3594       if (Cst > VTBits) {
3595         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
3596                               DAG.getConstant(NVTBits-1, ShTy));
3597       } else if (Cst > NVTBits) {
3598         Lo = DAG.getNode(ISD::SRA, NVT, InH,
3599                            DAG.getConstant(Cst-NVTBits, ShTy));
3600         Hi = DAG.getNode(ISD::SRA, NVT, InH,
3601                               DAG.getConstant(NVTBits-1, ShTy));
3602       } else if (Cst == NVTBits) {
3603         Lo = InH;
3604         Hi = DAG.getNode(ISD::SRA, NVT, InH,
3605                               DAG.getConstant(NVTBits-1, ShTy));
3606       } else {
3607         Lo = DAG.getNode(ISD::OR, NVT,
3608            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3609            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3610         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
3611       }
3612       return true;
3613     }
3614   }
3615   return false;
3616 }
3617
3618
3619 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3620 // does not fit into a register, return the lo part and set the hi part to the
3621 // by-reg argument.  If it does fit into a single register, return the result
3622 // and leave the Hi part unset.
3623 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3624                                               SDOperand &Hi) {
3625   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
3626   // The input chain to this libcall is the entry node of the function. 
3627   // Legalizing the call will automatically add the previous call to the
3628   // dependence.
3629   SDOperand InChain = DAG.getEntryNode();
3630   
3631   TargetLowering::ArgListTy Args;
3632   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3633     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3634     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3635     Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3636   }
3637   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3638
3639   // Splice the libcall in wherever FindInputOutputChains tells us to.
3640   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3641   std::pair<SDOperand,SDOperand> CallInfo =
3642     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3643                     Callee, Args, DAG);
3644
3645   // Legalize the call sequence, starting with the chain.  This will advance
3646   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
3647   // was added by LowerCallTo (guaranteeing proper serialization of calls).
3648   LegalizeOp(CallInfo.second);
3649   SDOperand Result;
3650   switch (getTypeAction(CallInfo.first.getValueType())) {
3651   default: assert(0 && "Unknown thing");
3652   case Legal:
3653     Result = CallInfo.first;
3654     break;
3655   case Expand:
3656     ExpandOp(CallInfo.first, Result, Hi);
3657     break;
3658   }
3659   return Result;
3660 }
3661
3662
3663 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3664 /// destination type is legal.
3665 SDOperand SelectionDAGLegalize::
3666 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3667   assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3668   assert(getTypeAction(Source.getValueType()) == Expand &&
3669          "This is not an expansion!");
3670   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3671
3672   if (!isSigned) {
3673     assert(Source.getValueType() == MVT::i64 &&
3674            "This only works for 64-bit -> FP");
3675     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3676     // incoming integer is set.  To handle this, we dynamically test to see if
3677     // it is set, and, if so, add a fudge factor.
3678     SDOperand Lo, Hi;
3679     ExpandOp(Source, Lo, Hi);
3680
3681     // If this is unsigned, and not supported, first perform the conversion to
3682     // signed, then adjust the result if the sign bit is set.
3683     SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3684                    DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3685
3686     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3687                                      DAG.getConstant(0, Hi.getValueType()),
3688                                      ISD::SETLT);
3689     SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3690     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3691                                       SignSet, Four, Zero);
3692     uint64_t FF = 0x5f800000ULL;
3693     if (TLI.isLittleEndian()) FF <<= 32;
3694     static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3695
3696     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3697     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3698     SDOperand FudgeInReg;
3699     if (DestTy == MVT::f32)
3700       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3701                                DAG.getSrcValue(NULL));
3702     else {
3703       assert(DestTy == MVT::f64 && "Unexpected conversion");
3704       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3705                                   CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3706     }
3707     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3708   }
3709
3710   // Check to see if the target has a custom way to lower this.  If so, use it.
3711   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3712   default: assert(0 && "This action not implemented for this operation!");
3713   case TargetLowering::Legal:
3714   case TargetLowering::Expand:
3715     break;   // This case is handled below.
3716   case TargetLowering::Custom: {
3717     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3718                                                   Source), DAG);
3719     if (NV.Val)
3720       return LegalizeOp(NV);
3721     break;   // The target decided this was legal after all
3722   }
3723   }
3724
3725   // Expand the source, then glue it back together for the call.  We must expand
3726   // the source in case it is shared (this pass of legalize must traverse it).
3727   SDOperand SrcLo, SrcHi;
3728   ExpandOp(Source, SrcLo, SrcHi);
3729   Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3730
3731   const char *FnName = 0;
3732   if (DestTy == MVT::f32)
3733     FnName = "__floatdisf";
3734   else {
3735     assert(DestTy == MVT::f64 && "Unknown fp value type!");
3736     FnName = "__floatdidf";
3737   }
3738   
3739   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
3740   SDOperand UnusedHiPart;
3741   return ExpandLibCall(FnName, Source.Val, UnusedHiPart);
3742 }
3743
3744 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
3745 /// INT_TO_FP operation of the specified operand when the target requests that
3746 /// we expand it.  At this point, we know that the result and operand types are
3747 /// legal for the target.
3748 SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
3749                                                      SDOperand Op0,
3750                                                      MVT::ValueType DestVT) {
3751   if (Op0.getValueType() == MVT::i32) {
3752     // simple 32-bit [signed|unsigned] integer to float/double expansion
3753     
3754     // get the stack frame index of a 8 byte buffer
3755     MachineFunction &MF = DAG.getMachineFunction();
3756     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3757     // get address of 8 byte buffer
3758     SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3759     // word offset constant for Hi/Lo address computation
3760     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
3761     // set up Hi and Lo (into buffer) address based on endian
3762     SDOperand Hi = StackSlot;
3763     SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
3764     if (TLI.isLittleEndian())
3765       std::swap(Hi, Lo);
3766     
3767     // if signed map to unsigned space
3768     SDOperand Op0Mapped;
3769     if (isSigned) {
3770       // constant used to invert sign bit (signed to unsigned mapping)
3771       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
3772       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
3773     } else {
3774       Op0Mapped = Op0;
3775     }
3776     // store the lo of the constructed double - based on integer input
3777     SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3778                                    Op0Mapped, Lo, DAG.getSrcValue(NULL));
3779     // initial hi portion of constructed double
3780     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
3781     // store the hi of the constructed double - biased exponent
3782     SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
3783                                    InitialHi, Hi, DAG.getSrcValue(NULL));
3784     // load the constructed double
3785     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
3786                                DAG.getSrcValue(NULL));
3787     // FP constant to bias correct the final result
3788     SDOperand Bias = DAG.getConstantFP(isSigned ?
3789                                             BitsToDouble(0x4330000080000000ULL)
3790                                           : BitsToDouble(0x4330000000000000ULL),
3791                                      MVT::f64);
3792     // subtract the bias
3793     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
3794     // final result
3795     SDOperand Result;
3796     // handle final rounding
3797     if (DestVT == MVT::f64) {
3798       // do nothing
3799       Result = Sub;
3800     } else {
3801      // if f32 then cast to f32
3802       Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
3803     }
3804     return Result;
3805   }
3806   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
3807   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
3808
3809   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
3810                                    DAG.getConstant(0, Op0.getValueType()),
3811                                    ISD::SETLT);
3812   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3813   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3814                                     SignSet, Four, Zero);
3815
3816   // If the sign bit of the integer is set, the large number will be treated
3817   // as a negative number.  To counteract this, the dynamic code adds an
3818   // offset depending on the data type.
3819   uint64_t FF;
3820   switch (Op0.getValueType()) {
3821   default: assert(0 && "Unsupported integer type!");
3822   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
3823   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
3824   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
3825   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
3826   }
3827   if (TLI.isLittleEndian()) FF <<= 32;
3828   static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3829
3830   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3831   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3832   SDOperand FudgeInReg;
3833   if (DestVT == MVT::f32)
3834     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3835                              DAG.getSrcValue(NULL));
3836   else {
3837     assert(DestVT == MVT::f64 && "Unexpected conversion");
3838     FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
3839                                            DAG.getEntryNode(), CPIdx,
3840                                            DAG.getSrcValue(NULL), MVT::f32));
3841   }
3842
3843   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
3844 }
3845
3846 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
3847 /// *INT_TO_FP operation of the specified operand when the target requests that
3848 /// we promote it.  At this point, we know that the result and operand types are
3849 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3850 /// operation that takes a larger input.
3851 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
3852                                                       MVT::ValueType DestVT,
3853                                                       bool isSigned) {
3854   // First step, figure out the appropriate *INT_TO_FP operation to use.
3855   MVT::ValueType NewInTy = LegalOp.getValueType();
3856
3857   unsigned OpToUse = 0;
3858
3859   // Scan for the appropriate larger type to use.
3860   while (1) {
3861     NewInTy = (MVT::ValueType)(NewInTy+1);
3862     assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
3863
3864     // If the target supports SINT_TO_FP of this type, use it.
3865     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
3866       default: break;
3867       case TargetLowering::Legal:
3868         if (!TLI.isTypeLegal(NewInTy))
3869           break;  // Can't use this datatype.
3870         // FALL THROUGH.
3871       case TargetLowering::Custom:
3872         OpToUse = ISD::SINT_TO_FP;
3873         break;
3874     }
3875     if (OpToUse) break;
3876     if (isSigned) continue;
3877
3878     // If the target supports UINT_TO_FP of this type, use it.
3879     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
3880       default: break;
3881       case TargetLowering::Legal:
3882         if (!TLI.isTypeLegal(NewInTy))
3883           break;  // Can't use this datatype.
3884         // FALL THROUGH.
3885       case TargetLowering::Custom:
3886         OpToUse = ISD::UINT_TO_FP;
3887         break;
3888     }
3889     if (OpToUse) break;
3890
3891     // Otherwise, try a larger type.
3892   }
3893
3894   // Okay, we found the operation and type to use.  Zero extend our input to the
3895   // desired type then run the operation on it.
3896   return DAG.getNode(OpToUse, DestVT,
3897                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3898                                  NewInTy, LegalOp));
3899 }
3900
3901 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
3902 /// FP_TO_*INT operation of the specified operand when the target requests that
3903 /// we promote it.  At this point, we know that the result and operand types are
3904 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3905 /// operation that returns a larger result.
3906 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
3907                                                       MVT::ValueType DestVT,
3908                                                       bool isSigned) {
3909   // First step, figure out the appropriate FP_TO*INT operation to use.
3910   MVT::ValueType NewOutTy = DestVT;
3911
3912   unsigned OpToUse = 0;
3913
3914   // Scan for the appropriate larger type to use.
3915   while (1) {
3916     NewOutTy = (MVT::ValueType)(NewOutTy+1);
3917     assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
3918
3919     // If the target supports FP_TO_SINT returning this type, use it.
3920     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
3921     default: break;
3922     case TargetLowering::Legal:
3923       if (!TLI.isTypeLegal(NewOutTy))
3924         break;  // Can't use this datatype.
3925       // FALL THROUGH.
3926     case TargetLowering::Custom:
3927       OpToUse = ISD::FP_TO_SINT;
3928       break;
3929     }
3930     if (OpToUse) break;
3931
3932     // If the target supports FP_TO_UINT of this type, use it.
3933     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
3934     default: break;
3935     case TargetLowering::Legal:
3936       if (!TLI.isTypeLegal(NewOutTy))
3937         break;  // Can't use this datatype.
3938       // FALL THROUGH.
3939     case TargetLowering::Custom:
3940       OpToUse = ISD::FP_TO_UINT;
3941       break;
3942     }
3943     if (OpToUse) break;
3944
3945     // Otherwise, try a larger type.
3946   }
3947
3948   // Okay, we found the operation and type to use.  Truncate the result of the
3949   // extended FP_TO_*INT operation to the desired size.
3950   return DAG.getNode(ISD::TRUNCATE, DestVT,
3951                      DAG.getNode(OpToUse, NewOutTy, LegalOp));
3952 }
3953
3954 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
3955 ///
3956 SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
3957   MVT::ValueType VT = Op.getValueType();
3958   MVT::ValueType SHVT = TLI.getShiftAmountTy();
3959   SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
3960   switch (VT) {
3961   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
3962   case MVT::i16:
3963     Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3964     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3965     return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
3966   case MVT::i32:
3967     Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3968     Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3969     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3970     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3971     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
3972     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
3973     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3974     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3975     return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3976   case MVT::i64:
3977     Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
3978     Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
3979     Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3980     Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3981     Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3982     Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3983     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
3984     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
3985     Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
3986     Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
3987     Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
3988     Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
3989     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
3990     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
3991     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
3992     Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
3993     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3994     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3995     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
3996     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3997     return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
3998   }
3999 }
4000
4001 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
4002 ///
4003 SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
4004   switch (Opc) {
4005   default: assert(0 && "Cannot expand this yet!");
4006   case ISD::CTPOP: {
4007     static const uint64_t mask[6] = {
4008       0x5555555555555555ULL, 0x3333333333333333ULL,
4009       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
4010       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
4011     };
4012     MVT::ValueType VT = Op.getValueType();
4013     MVT::ValueType ShVT = TLI.getShiftAmountTy();
4014     unsigned len = getSizeInBits(VT);
4015     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4016       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
4017       SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
4018       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4019       Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
4020                        DAG.getNode(ISD::AND, VT,
4021                                    DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
4022     }
4023     return Op;
4024   }
4025   case ISD::CTLZ: {
4026     // for now, we do this:
4027     // x = x | (x >> 1);
4028     // x = x | (x >> 2);
4029     // ...
4030     // x = x | (x >>16);
4031     // x = x | (x >>32); // for 64-bit input
4032     // return popcount(~x);
4033     //
4034     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
4035     MVT::ValueType VT = Op.getValueType();
4036     MVT::ValueType ShVT = TLI.getShiftAmountTy();
4037     unsigned len = getSizeInBits(VT);
4038     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4039       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4040       Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
4041     }
4042     Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
4043     return DAG.getNode(ISD::CTPOP, VT, Op);
4044   }
4045   case ISD::CTTZ: {
4046     // for now, we use: { return popcount(~x & (x - 1)); }
4047     // unless the target has ctlz but not ctpop, in which case we use:
4048     // { return 32 - nlz(~x & (x-1)); }
4049     // see also http://www.hackersdelight.org/HDcode/ntz.cc
4050     MVT::ValueType VT = Op.getValueType();
4051     SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
4052     SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
4053                        DAG.getNode(ISD::XOR, VT, Op, Tmp2),
4054                        DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
4055     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
4056     if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
4057         TLI.isOperationLegal(ISD::CTLZ, VT))
4058       return DAG.getNode(ISD::SUB, VT,
4059                          DAG.getConstant(getSizeInBits(VT), VT),
4060                          DAG.getNode(ISD::CTLZ, VT, Tmp3));
4061     return DAG.getNode(ISD::CTPOP, VT, Tmp3);
4062   }
4063   }
4064 }
4065
4066 /// ExpandOp - Expand the specified SDOperand into its two component pieces
4067 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
4068 /// LegalizeNodes map is filled in for any results that are not expanded, the
4069 /// ExpandedNodes map is filled in for any results that are expanded, and the
4070 /// Lo/Hi values are returned.
4071 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
4072   MVT::ValueType VT = Op.getValueType();
4073   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
4074   SDNode *Node = Op.Val;
4075   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
4076   assert((MVT::isInteger(VT) || VT == MVT::Vector) && 
4077          "Cannot expand FP values!");
4078   assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
4079          "Cannot expand to FP value or to larger int value!");
4080
4081   // See if we already expanded it.
4082   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4083     = ExpandedNodes.find(Op);
4084   if (I != ExpandedNodes.end()) {
4085     Lo = I->second.first;
4086     Hi = I->second.second;
4087     return;
4088   }
4089
4090   switch (Node->getOpcode()) {
4091   case ISD::CopyFromReg:
4092     assert(0 && "CopyFromReg must be legal!");
4093   default:
4094     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
4095     assert(0 && "Do not know how to expand this operator!");
4096     abort();
4097   case ISD::UNDEF:
4098     Lo = DAG.getNode(ISD::UNDEF, NVT);
4099     Hi = DAG.getNode(ISD::UNDEF, NVT);
4100     break;
4101   case ISD::Constant: {
4102     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
4103     Lo = DAG.getConstant(Cst, NVT);
4104     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
4105     break;
4106   }
4107   case ISD::BUILD_PAIR:
4108     // Return the operands.
4109     Lo = Node->getOperand(0);
4110     Hi = Node->getOperand(1);
4111     break;
4112     
4113   case ISD::SIGN_EXTEND_INREG:
4114     ExpandOp(Node->getOperand(0), Lo, Hi);
4115     // Sign extend the lo-part.
4116     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4117                      DAG.getConstant(MVT::getSizeInBits(NVT)-1,
4118                                      TLI.getShiftAmountTy()));
4119     // sext_inreg the low part if needed.
4120     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
4121     break;
4122
4123   case ISD::BSWAP: {
4124     ExpandOp(Node->getOperand(0), Lo, Hi);
4125     SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
4126     Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
4127     Lo = TempLo;
4128     break;
4129   }
4130     
4131   case ISD::CTPOP:
4132     ExpandOp(Node->getOperand(0), Lo, Hi);
4133     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
4134                      DAG.getNode(ISD::CTPOP, NVT, Lo),
4135                      DAG.getNode(ISD::CTPOP, NVT, Hi));
4136     Hi = DAG.getConstant(0, NVT);
4137     break;
4138
4139   case ISD::CTLZ: {
4140     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
4141     ExpandOp(Node->getOperand(0), Lo, Hi);
4142     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4143     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
4144     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
4145                                         ISD::SETNE);
4146     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
4147     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
4148
4149     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
4150     Hi = DAG.getConstant(0, NVT);
4151     break;
4152   }
4153
4154   case ISD::CTTZ: {
4155     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
4156     ExpandOp(Node->getOperand(0), Lo, Hi);
4157     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4158     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
4159     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
4160                                         ISD::SETNE);
4161     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
4162     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
4163
4164     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
4165     Hi = DAG.getConstant(0, NVT);
4166     break;
4167   }
4168
4169   case ISD::VAARG: {
4170     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4171     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4172     Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
4173     Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
4174
4175     // Remember that we legalized the chain.
4176     Hi = LegalizeOp(Hi);
4177     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
4178     if (!TLI.isLittleEndian())
4179       std::swap(Lo, Hi);
4180     break;
4181   }
4182     
4183   case ISD::LOAD: {
4184     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4185     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4186     Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4187
4188     // Increment the pointer to the other half.
4189     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
4190     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4191                       getIntPtrConstant(IncrementSize));
4192     // FIXME: This creates a bogus srcvalue!
4193     Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4194
4195     // Build a factor node to remember that this load is independent of the
4196     // other one.
4197     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4198                                Hi.getValue(1));
4199
4200     // Remember that we legalized the chain.
4201     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4202     if (!TLI.isLittleEndian())
4203       std::swap(Lo, Hi);
4204     break;
4205   }
4206   case ISD::AND:
4207   case ISD::OR:
4208   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
4209     SDOperand LL, LH, RL, RH;
4210     ExpandOp(Node->getOperand(0), LL, LH);
4211     ExpandOp(Node->getOperand(1), RL, RH);
4212     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
4213     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
4214     break;
4215   }
4216   case ISD::SELECT: {
4217     SDOperand LL, LH, RL, RH;
4218     ExpandOp(Node->getOperand(1), LL, LH);
4219     ExpandOp(Node->getOperand(2), RL, RH);
4220     Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
4221     Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
4222     break;
4223   }
4224   case ISD::SELECT_CC: {
4225     SDOperand TL, TH, FL, FH;
4226     ExpandOp(Node->getOperand(2), TL, TH);
4227     ExpandOp(Node->getOperand(3), FL, FH);
4228     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4229                      Node->getOperand(1), TL, FL, Node->getOperand(4));
4230     Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4231                      Node->getOperand(1), TH, FH, Node->getOperand(4));
4232     break;
4233   }
4234   case ISD::SEXTLOAD: {
4235     SDOperand Chain = Node->getOperand(0);
4236     SDOperand Ptr   = Node->getOperand(1);
4237     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4238     
4239     if (EVT == NVT)
4240       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4241     else
4242       Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4243                           EVT);
4244     
4245     // Remember that we legalized the chain.
4246     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4247     
4248     // The high part is obtained by SRA'ing all but one of the bits of the lo
4249     // part.
4250     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4251     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
4252                                                        TLI.getShiftAmountTy()));
4253     break;
4254   }
4255   case ISD::ZEXTLOAD: {
4256     SDOperand Chain = Node->getOperand(0);
4257     SDOperand Ptr   = Node->getOperand(1);
4258     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4259     
4260     if (EVT == NVT)
4261       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4262     else
4263       Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4264                           EVT);
4265     
4266     // Remember that we legalized the chain.
4267     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4268
4269     // The high part is just a zero.
4270     Hi = DAG.getConstant(0, NVT);
4271     break;
4272   }
4273   case ISD::EXTLOAD: {
4274     SDOperand Chain = Node->getOperand(0);
4275     SDOperand Ptr   = Node->getOperand(1);
4276     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4277     
4278     if (EVT == NVT)
4279       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4280     else
4281       Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4282                           EVT);
4283     
4284     // Remember that we legalized the chain.
4285     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4286     
4287     // The high part is undefined.
4288     Hi = DAG.getNode(ISD::UNDEF, NVT);
4289     break;
4290   }
4291   case ISD::ANY_EXTEND:
4292     // The low part is any extension of the input (which degenerates to a copy).
4293     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
4294     // The high part is undefined.
4295     Hi = DAG.getNode(ISD::UNDEF, NVT);
4296     break;
4297   case ISD::SIGN_EXTEND: {
4298     // The low part is just a sign extension of the input (which degenerates to
4299     // a copy).
4300     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
4301
4302     // The high part is obtained by SRA'ing all but one of the bits of the lo
4303     // part.
4304     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4305     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4306                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
4307     break;
4308   }
4309   case ISD::ZERO_EXTEND:
4310     // The low part is just a zero extension of the input (which degenerates to
4311     // a copy).
4312     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4313
4314     // The high part is just a zero.
4315     Hi = DAG.getConstant(0, NVT);
4316     break;
4317     
4318   case ISD::BIT_CONVERT: {
4319     SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0), 
4320                                       Node->getOperand(0));
4321     ExpandOp(Tmp, Lo, Hi);
4322     break;
4323   }
4324
4325   case ISD::READCYCLECOUNTER:
4326     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
4327                  TargetLowering::Custom &&
4328            "Must custom expand ReadCycleCounter");
4329     Lo = TLI.LowerOperation(Op, DAG);
4330     assert(Lo.Val && "Node must be custom expanded!");
4331     Hi = Lo.getValue(1);
4332     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
4333                         LegalizeOp(Lo.getValue(2)));
4334     break;
4335
4336     // These operators cannot be expanded directly, emit them as calls to
4337     // library functions.
4338   case ISD::FP_TO_SINT:
4339     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
4340       SDOperand Op;
4341       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4342       case Expand: assert(0 && "cannot expand FP!");
4343       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4344       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4345       }
4346
4347       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
4348
4349       // Now that the custom expander is done, expand the result, which is still
4350       // VT.
4351       if (Op.Val) {
4352         ExpandOp(Op, Lo, Hi);
4353         break;
4354       }
4355     }
4356
4357     if (Node->getOperand(0).getValueType() == MVT::f32)
4358       Lo = ExpandLibCall("__fixsfdi", Node, Hi);
4359     else
4360       Lo = ExpandLibCall("__fixdfdi", Node, Hi);
4361     break;
4362
4363   case ISD::FP_TO_UINT:
4364     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
4365       SDOperand Op;
4366       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4367         case Expand: assert(0 && "cannot expand FP!");
4368         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4369         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4370       }
4371         
4372       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
4373
4374       // Now that the custom expander is done, expand the result.
4375       if (Op.Val) {
4376         ExpandOp(Op, Lo, Hi);
4377         break;
4378       }
4379     }
4380
4381     if (Node->getOperand(0).getValueType() == MVT::f32)
4382       Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
4383     else
4384       Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
4385     break;
4386
4387   case ISD::SHL: {
4388     // If the target wants custom lowering, do so.
4389     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4390     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
4391       SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
4392       Op = TLI.LowerOperation(Op, DAG);
4393       if (Op.Val) {
4394         // Now that the custom expander is done, expand the result, which is
4395         // still VT.
4396         ExpandOp(Op, Lo, Hi);
4397         break;
4398       }
4399     }
4400     
4401     // If we can emit an efficient shift operation, do so now.
4402     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4403       break;
4404
4405     // If this target supports SHL_PARTS, use it.
4406     TargetLowering::LegalizeAction Action =
4407       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
4408     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4409         Action == TargetLowering::Custom) {
4410       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4411       break;
4412     }
4413
4414     // Otherwise, emit a libcall.
4415     Lo = ExpandLibCall("__ashldi3", Node, Hi);
4416     break;
4417   }
4418
4419   case ISD::SRA: {
4420     // If the target wants custom lowering, do so.
4421     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4422     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
4423       SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
4424       Op = TLI.LowerOperation(Op, DAG);
4425       if (Op.Val) {
4426         // Now that the custom expander is done, expand the result, which is
4427         // still VT.
4428         ExpandOp(Op, Lo, Hi);
4429         break;
4430       }
4431     }
4432     
4433     // If we can emit an efficient shift operation, do so now.
4434     if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
4435       break;
4436
4437     // If this target supports SRA_PARTS, use it.
4438     TargetLowering::LegalizeAction Action =
4439       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
4440     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4441         Action == TargetLowering::Custom) {
4442       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4443       break;
4444     }
4445
4446     // Otherwise, emit a libcall.
4447     Lo = ExpandLibCall("__ashrdi3", Node, Hi);
4448     break;
4449   }
4450
4451   case ISD::SRL: {
4452     // If the target wants custom lowering, do so.
4453     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4454     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
4455       SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
4456       Op = TLI.LowerOperation(Op, DAG);
4457       if (Op.Val) {
4458         // Now that the custom expander is done, expand the result, which is
4459         // still VT.
4460         ExpandOp(Op, Lo, Hi);
4461         break;
4462       }
4463     }
4464
4465     // If we can emit an efficient shift operation, do so now.
4466     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4467       break;
4468
4469     // If this target supports SRL_PARTS, use it.
4470     TargetLowering::LegalizeAction Action =
4471       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
4472     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4473         Action == TargetLowering::Custom) {
4474       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4475       break;
4476     }
4477
4478     // Otherwise, emit a libcall.
4479     Lo = ExpandLibCall("__lshrdi3", Node, Hi);
4480     break;
4481   }
4482
4483   case ISD::ADD:
4484   case ISD::SUB: {
4485     // If the target wants to custom expand this, let them.
4486     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
4487             TargetLowering::Custom) {
4488       Op = TLI.LowerOperation(Op, DAG);
4489       if (Op.Val) {
4490         ExpandOp(Op, Lo, Hi);
4491         break;
4492       }
4493     }
4494     
4495     // Expand the subcomponents.
4496     SDOperand LHSL, LHSH, RHSL, RHSH;
4497     ExpandOp(Node->getOperand(0), LHSL, LHSH);
4498     ExpandOp(Node->getOperand(1), RHSL, RHSH);
4499     std::vector<MVT::ValueType> VTs;
4500     std::vector<SDOperand> LoOps, HiOps;
4501     VTs.push_back(LHSL.getValueType());
4502     VTs.push_back(MVT::Flag);
4503     LoOps.push_back(LHSL);
4504     LoOps.push_back(RHSL);
4505     HiOps.push_back(LHSH);
4506     HiOps.push_back(RHSH);
4507     if (Node->getOpcode() == ISD::ADD) {
4508       Lo = DAG.getNode(ISD::ADDC, VTs, LoOps);
4509       HiOps.push_back(Lo.getValue(1));
4510       Hi = DAG.getNode(ISD::ADDE, VTs, HiOps);
4511     } else {
4512       Lo = DAG.getNode(ISD::SUBC, VTs, LoOps);
4513       HiOps.push_back(Lo.getValue(1));
4514       Hi = DAG.getNode(ISD::SUBE, VTs, HiOps);
4515     }
4516     break;
4517   }
4518   case ISD::MUL: {
4519     if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
4520       SDOperand LL, LH, RL, RH;
4521       ExpandOp(Node->getOperand(0), LL, LH);
4522       ExpandOp(Node->getOperand(1), RL, RH);
4523       unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
4524       // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
4525       // extended the sign bit of the low half through the upper half, and if so
4526       // emit a MULHS instead of the alternate sequence that is valid for any
4527       // i64 x i64 multiply.
4528       if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
4529           // is RH an extension of the sign bit of RL?
4530           RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
4531           RH.getOperand(1).getOpcode() == ISD::Constant &&
4532           cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
4533           // is LH an extension of the sign bit of LL?
4534           LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
4535           LH.getOperand(1).getOpcode() == ISD::Constant &&
4536           cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
4537         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
4538       } else {
4539         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
4540         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
4541         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
4542         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
4543         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
4544       }
4545       Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
4546     } else {
4547       Lo = ExpandLibCall("__muldi3" , Node, Hi);
4548     }
4549     break;
4550   }
4551   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
4552   case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
4553   case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
4554   case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
4555   }
4556
4557   // Make sure the resultant values have been legalized themselves, unless this
4558   // is a type that requires multi-step expansion.
4559   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
4560     Lo = LegalizeOp(Lo);
4561     Hi = LegalizeOp(Hi);
4562   }
4563
4564   // Remember in a map if the values will be reused later.
4565   bool isNew =
4566     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4567   assert(isNew && "Value already expanded?!?");
4568 }
4569
4570 /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
4571 /// two smaller values of MVT::Vector type.
4572 void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
4573                                          SDOperand &Hi) {
4574   assert(Op.getValueType() == MVT::Vector && "Cannot split non-vector type!");
4575   SDNode *Node = Op.Val;
4576   unsigned NumElements = cast<ConstantSDNode>(*(Node->op_end()-2))->getValue();
4577   assert(NumElements > 1 && "Cannot split a single element vector!");
4578   unsigned NewNumElts = NumElements/2;
4579   SDOperand NewNumEltsNode = DAG.getConstant(NewNumElts, MVT::i32);
4580   SDOperand TypeNode = *(Node->op_end()-1);
4581   
4582   // See if we already split it.
4583   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4584     = SplitNodes.find(Op);
4585   if (I != SplitNodes.end()) {
4586     Lo = I->second.first;
4587     Hi = I->second.second;
4588     return;
4589   }
4590   
4591   switch (Node->getOpcode()) {
4592   default: Node->dump(); assert(0 && "Unknown vector operation!");
4593   case ISD::VBUILD_VECTOR: {
4594     std::vector<SDOperand> LoOps(Node->op_begin(), Node->op_begin()+NewNumElts);
4595     LoOps.push_back(NewNumEltsNode);
4596     LoOps.push_back(TypeNode);
4597     Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps);
4598
4599     std::vector<SDOperand> HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2);
4600     HiOps.push_back(NewNumEltsNode);
4601     HiOps.push_back(TypeNode);
4602     Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps);
4603     break;
4604   }
4605   case ISD::VADD:
4606   case ISD::VSUB:
4607   case ISD::VMUL:
4608   case ISD::VSDIV:
4609   case ISD::VUDIV:
4610   case ISD::VAND:
4611   case ISD::VOR:
4612   case ISD::VXOR: {
4613     SDOperand LL, LH, RL, RH;
4614     SplitVectorOp(Node->getOperand(0), LL, LH);
4615     SplitVectorOp(Node->getOperand(1), RL, RH);
4616     
4617     Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL,
4618                      NewNumEltsNode, TypeNode);
4619     Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH,
4620                      NewNumEltsNode, TypeNode);
4621     break;
4622   }
4623   case ISD::VLOAD: {
4624     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4625     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4626     MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4627     
4628     Lo = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4629     unsigned IncrementSize = NewNumElts * MVT::getSizeInBits(EVT)/8;
4630     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4631                       getIntPtrConstant(IncrementSize));
4632     // FIXME: This creates a bogus srcvalue!
4633     Hi = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4634     
4635     // Build a factor node to remember that this load is independent of the
4636     // other one.
4637     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4638                                Hi.getValue(1));
4639     
4640     // Remember that we legalized the chain.
4641     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4642     break;
4643   }
4644   case ISD::VBIT_CONVERT: {
4645     // We know the result is a vector.  The input may be either a vector or a
4646     // scalar value.
4647     if (Op.getOperand(0).getValueType() != MVT::Vector) {
4648       // Lower to a store/load.  FIXME: this could be improved probably.
4649       SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
4650
4651       SDOperand St = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
4652                                  Op.getOperand(0), Ptr, DAG.getSrcValue(0));
4653       MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4654       St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
4655       SplitVectorOp(St, Lo, Hi);
4656     } else {
4657       // If the input is a vector type, we have to either scalarize it, pack it
4658       // or convert it based on whether the input vector type is legal.
4659       SDNode *InVal = Node->getOperand(0).Val;
4660       unsigned NumElems =
4661         cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4662       MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4663
4664       // If the input is from a single element vector, scalarize the vector,
4665       // then treat like a scalar.
4666       if (NumElems == 1) {
4667         SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
4668         Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
4669                              Op.getOperand(1), Op.getOperand(2));
4670         SplitVectorOp(Scalar, Lo, Hi);
4671       } else {
4672         // Split the input vector.
4673         SplitVectorOp(Op.getOperand(0), Lo, Hi);
4674
4675         // Convert each of the pieces now.
4676         Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
4677                          NewNumEltsNode, TypeNode);
4678         Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
4679                          NewNumEltsNode, TypeNode);
4680       }
4681       break;
4682     }
4683   }
4684   }
4685       
4686   // Remember in a map if the values will be reused later.
4687   bool isNew =
4688     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4689   assert(isNew && "Value already expanded?!?");
4690 }
4691
4692
4693 /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
4694 /// equivalent operation that returns a scalar (e.g. F32) or packed value
4695 /// (e.g. MVT::V4F32).  When this is called, we know that PackedVT is the right
4696 /// type for the result.
4697 SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op, 
4698                                              MVT::ValueType NewVT) {
4699   assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
4700   SDNode *Node = Op.Val;
4701   
4702   // See if we already packed it.
4703   std::map<SDOperand, SDOperand>::iterator I = PackedNodes.find(Op);
4704   if (I != PackedNodes.end()) return I->second;
4705   
4706   SDOperand Result;
4707   switch (Node->getOpcode()) {
4708   default: 
4709     Node->dump(); std::cerr << "\n";
4710     assert(0 && "Unknown vector operation in PackVectorOp!");
4711   case ISD::VADD:
4712   case ISD::VSUB:
4713   case ISD::VMUL:
4714   case ISD::VSDIV:
4715   case ISD::VUDIV:
4716   case ISD::VAND:
4717   case ISD::VOR:
4718   case ISD::VXOR:
4719     Result = DAG.getNode(getScalarizedOpcode(Node->getOpcode(), NewVT),
4720                          NewVT, 
4721                          PackVectorOp(Node->getOperand(0), NewVT),
4722                          PackVectorOp(Node->getOperand(1), NewVT));
4723     break;
4724   case ISD::VLOAD: {
4725     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
4726     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
4727     
4728     Result = DAG.getLoad(NewVT, Ch, Ptr, Node->getOperand(2));
4729     
4730     // Remember that we legalized the chain.
4731     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4732     break;
4733   }
4734   case ISD::VBUILD_VECTOR:
4735     if (Node->getOperand(0).getValueType() == NewVT) {
4736       // Returning a scalar?
4737       Result = Node->getOperand(0);
4738     } else {
4739       // Returning a BUILD_VECTOR?
4740       
4741       // If all elements of the build_vector are undefs, return an undef.
4742       bool AllUndef = true;
4743       for (unsigned i = 0, e = Node->getNumOperands()-2; i != e; ++i)
4744         if (Node->getOperand(i).getOpcode() != ISD::UNDEF) {
4745           AllUndef = false;
4746           break;
4747         }
4748       if (AllUndef) {
4749         Result = DAG.getNode(ISD::UNDEF, NewVT);
4750       } else {
4751         std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end()-2);
4752         Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops);
4753       }
4754     }
4755     break;
4756   case ISD::VINSERT_VECTOR_ELT:
4757     if (!MVT::isVector(NewVT)) {
4758       // Returning a scalar?  Must be the inserted element.
4759       Result = Node->getOperand(1);
4760     } else {
4761       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT,
4762                            PackVectorOp(Node->getOperand(0), NewVT),
4763                            Node->getOperand(1), Node->getOperand(2));
4764     }
4765     break;
4766   case ISD::VVECTOR_SHUFFLE:
4767     if (!MVT::isVector(NewVT)) {
4768       // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
4769       SDOperand EltNum = Node->getOperand(2).getOperand(0);
4770       if (cast<ConstantSDNode>(EltNum)->getValue())
4771         Result = PackVectorOp(Node->getOperand(1), NewVT);
4772       else
4773         Result = PackVectorOp(Node->getOperand(0), NewVT);
4774     } else {
4775       // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
4776       // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
4777       std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
4778                                          Node->getOperand(2).Val->op_end()-2);
4779       MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
4780       SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, BuildVecIdx);
4781       
4782       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
4783                            PackVectorOp(Node->getOperand(0), NewVT),
4784                            PackVectorOp(Node->getOperand(1), NewVT), BV);
4785     }
4786     break;
4787   case ISD::VBIT_CONVERT:
4788     if (Op.getOperand(0).getValueType() != MVT::Vector)
4789       Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
4790     else {
4791       // If the input is a vector type, we have to either scalarize it, pack it
4792       // or convert it based on whether the input vector type is legal.
4793       SDNode *InVal = Node->getOperand(0).Val;
4794       unsigned NumElems =
4795         cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4796       MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4797         
4798       // Figure out if there is a Packed type corresponding to this Vector
4799       // type.  If so, convert to the packed type.
4800       MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
4801       if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
4802         // Turn this into a bit convert of the packed input.
4803         Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
4804                              PackVectorOp(Node->getOperand(0), TVT));
4805         break;
4806       } else if (NumElems == 1) {
4807         // Turn this into a bit convert of the scalar input.
4808         Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
4809                              PackVectorOp(Node->getOperand(0), EVT));
4810         break;
4811       } else {
4812         // FIXME: UNIMP!
4813         assert(0 && "Cast from unsupported vector type not implemented yet!");
4814       }
4815     }
4816     break;
4817   case ISD::VSELECT:
4818     Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
4819                          PackVectorOp(Op.getOperand(1), NewVT),
4820                          PackVectorOp(Op.getOperand(2), NewVT));
4821     break;
4822   }
4823
4824   if (TLI.isTypeLegal(NewVT))
4825     Result = LegalizeOp(Result);
4826   bool isNew = PackedNodes.insert(std::make_pair(Op, Result)).second;
4827   assert(isNew && "Value already packed?");
4828   return Result;
4829 }
4830
4831
4832 // SelectionDAG::Legalize - This is the entry point for the file.
4833 //
4834 void SelectionDAG::Legalize() {
4835   if (ViewLegalizeDAGs) viewGraph();
4836
4837   /// run - This is the main entry point to this class.
4838   ///
4839   SelectionDAGLegalize(*this).LegalizeDAG();
4840 }
4841