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