Support for expanding ADDE and SUBE.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAGTypes.cpp
1 //===-- LegalizeDAGTypes.cpp - Implement SelectionDAG::LegalizeTypes ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::LegalizeTypes method.  It transforms
11 // an arbitrary well-formed SelectionDAG to only consist of legal types.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "legalize-types"
16 #include "llvm/CodeGen/SelectionDAG.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Target/TargetLowering.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 /// DAGTypeLegalizer - This takes an arbitrary SelectionDAG as input and
27 /// hacks on it until the target machine can handle it.  This involves
28 /// eliminating value sizes the machine cannot handle (promoting small sizes to
29 /// large sizes or splitting up large values into small values) as well as
30 /// eliminating operations the machine cannot handle.
31 ///
32 /// This code also does a small amount of optimization and recognition of idioms
33 /// as part of its processing.  For example, if a target does not support a
34 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
35 /// will attempt merge setcc and brc instructions into brcc's.
36 ///
37 namespace {
38 class VISIBILITY_HIDDEN DAGTypeLegalizer {
39   TargetLowering &TLI;
40   SelectionDAG &DAG;
41   
42   // NodeIDFlags - This pass uses the NodeID on the SDNodes to hold information
43   // about the state of the node.  The enum has all the values.
44   enum NodeIDFlags {
45     /// ReadyToProcess - All operands have been processed, so this node is ready
46     /// to be handled.
47     ReadyToProcess = 0,
48     
49     /// NewNode - This is a new node that was created in the process of
50     /// legalizing some other node.
51     NewNode = -1,
52     
53     /// Processed - This is a node that has already been processed.
54     Processed = -2
55     
56     // 1+ - This is a node which has this many unlegalized operands.
57   };
58   
59   enum LegalizeAction {
60     Legal,      // The target natively supports this type.
61     Promote,    // This type should be executed in a larger type.
62     Expand      // This type should be split into two types of half the size.
63   };
64   
65   /// ValueTypeActions - This is a bitvector that contains two bits for each
66   /// simple value type, where the two bits correspond to the LegalizeAction
67   /// enum.  This can be queried with "getTypeAction(VT)".
68   TargetLowering::ValueTypeActionImpl ValueTypeActions;
69   
70   /// getTypeAction - Return how we should legalize values of this type, either
71   /// it is already legal or we need to expand it into multiple registers of
72   /// smaller integer type, or we need to promote it to a larger type.
73   LegalizeAction getTypeAction(MVT::ValueType VT) const {
74     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
75   }
76   
77   /// isTypeLegal - Return true if this type is legal on this target.
78   ///
79   bool isTypeLegal(MVT::ValueType VT) const {
80     return getTypeAction(VT) == Legal;
81   }
82   
83   SDOperand getIntPtrConstant(uint64_t Val) {
84     return DAG.getConstant(Val, TLI.getPointerTy());
85   }
86   
87   /// PromotedNodes - For nodes that are below legal width, and that have more
88   /// than one use, this map indicates what promoted value to use.
89   DenseMap<SDOperand, SDOperand> PromotedNodes;
90   
91   /// ExpandedNodes - For nodes that need to be expanded this map indicates
92   /// which operands are the expanded version of the input.
93   DenseMap<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
94   
95   /// Worklist - This defines a worklist of nodes to process.  In order to be
96   /// pushed onto this worklist, all operands of a node must have already been
97   /// processed.
98   SmallVector<SDNode*, 128> Worklist;
99   
100 public:
101   DAGTypeLegalizer(SelectionDAG &dag)
102     : TLI(dag.getTargetLoweringInfo()), DAG(dag),
103     ValueTypeActions(TLI.getValueTypeActions()) {
104     assert(MVT::LAST_VALUETYPE <= 32 &&
105            "Too many value types for ValueTypeActions to hold!");
106   }      
107   
108   void run();
109   
110 private:
111   void MarkNewNodes(SDNode *N);
112   
113   void ReplaceLegalValueWith(SDOperand From, SDOperand To);
114   
115   SDOperand GetPromotedOp(SDOperand Op) {
116     Op = PromotedNodes[Op];
117     assert(Op.Val && "Operand wasn't promoted?");
118     return Op;
119   }    
120   void SetPromotedOp(SDOperand Op, SDOperand Result);
121
122   void GetExpandedOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi);
123   void SetExpandedOp(SDOperand Op, SDOperand Lo, SDOperand Hi);
124   
125   SDOperand CreateStackStoreLoad(SDOperand Op, MVT::ValueType DestVT);
126   
127   // Result Promotion.
128   void PromoteResult(SDNode *N, unsigned ResNo);
129   SDOperand PromoteResult_UNDEF(SDNode *N);
130   SDOperand PromoteResult_Constant(SDNode *N);
131   SDOperand PromoteResult_TRUNCATE(SDNode *N);
132   SDOperand PromoteResult_INT_EXTEND(SDNode *N);
133   SDOperand PromoteResult_FP_ROUND(SDNode *N);
134   SDOperand PromoteResult_SETCC(SDNode *N);
135   SDOperand PromoteResult_LOAD(LoadSDNode *N);
136   SDOperand PromoteResult_SimpleIntBinOp(SDNode *N);
137   SDOperand PromoteResult_SELECT   (SDNode *N);
138   SDOperand PromoteResult_SELECT_CC(SDNode *N);
139   
140   // Result Expansion.
141   void ExpandResult(SDNode *N, unsigned ResNo);
142   void ExpandResult_UNDEF      (SDNode *N, SDOperand &Lo, SDOperand &Hi);
143   void ExpandResult_Constant   (SDNode *N, SDOperand &Lo, SDOperand &Hi);
144   void ExpandResult_BUILD_PAIR (SDNode *N, SDOperand &Lo, SDOperand &Hi);
145   void ExpandResult_ANY_EXTEND (SDNode *N, SDOperand &Lo, SDOperand &Hi);
146   void ExpandResult_ZERO_EXTEND(SDNode *N, SDOperand &Lo, SDOperand &Hi);
147   void ExpandResult_SIGN_EXTEND(SDNode *N, SDOperand &Lo, SDOperand &Hi);
148   void ExpandResult_BIT_CONVERT(SDNode *N, SDOperand &Lo, SDOperand &Hi);
149   void ExpandResult_SIGN_EXTEND_INREG(SDNode *N, SDOperand &Lo, SDOperand &Hi);
150   void ExpandResult_LOAD       (LoadSDNode *N, SDOperand &Lo, SDOperand &Hi);
151
152   void ExpandResult_Logical    (SDNode *N, SDOperand &Lo, SDOperand &Hi);
153   void ExpandResult_BSWAP      (SDNode *N, SDOperand &Lo, SDOperand &Hi);
154   void ExpandResult_ADDSUB     (SDNode *N, SDOperand &Lo, SDOperand &Hi);
155   void ExpandResult_ADDSUBC    (SDNode *N, SDOperand &Lo, SDOperand &Hi);
156   void ExpandResult_ADDSUBE    (SDNode *N, SDOperand &Lo, SDOperand &Hi);
157   void ExpandResult_SELECT     (SDNode *N, SDOperand &Lo, SDOperand &Hi);
158   void ExpandResult_SELECT_CC  (SDNode *N, SDOperand &Lo, SDOperand &Hi);
159   void ExpandResult_MUL        (SDNode *N, SDOperand &Lo, SDOperand &Hi);
160   void ExpandResult_Shift      (SDNode *N, SDOperand &Lo, SDOperand &Hi);
161   
162   void ExpandShiftByConstant(SDNode *N, unsigned Amt, 
163                              SDOperand &Lo, SDOperand &Hi);
164   bool ExpandShiftWithKnownAmountBit(SDNode *N, SDOperand &Lo, SDOperand &Hi);
165
166   // Operand Promotion.
167   bool PromoteOperand(SDNode *N, unsigned OperandNo);
168   SDOperand PromoteOperand_ANY_EXTEND(SDNode *N);
169   SDOperand PromoteOperand_ZERO_EXTEND(SDNode *N);
170   SDOperand PromoteOperand_SIGN_EXTEND(SDNode *N);
171   SDOperand PromoteOperand_FP_EXTEND(SDNode *N);
172   SDOperand PromoteOperand_FP_ROUND(SDNode *N);
173   SDOperand PromoteOperand_SELECT(SDNode *N, unsigned OpNo);
174   SDOperand PromoteOperand_BRCOND(SDNode *N, unsigned OpNo);
175   SDOperand PromoteOperand_BR_CC(SDNode *N, unsigned OpNo);
176   SDOperand PromoteOperand_STORE(StoreSDNode *N, unsigned OpNo);
177   
178   void PromoteSetCCOperands(SDOperand &LHS,SDOperand &RHS, ISD::CondCode Code);
179
180   // Operand Expansion.
181   bool ExpandOperand(SDNode *N, unsigned OperandNo);
182   SDOperand ExpandOperand_TRUNCATE(SDNode *N);
183   SDOperand ExpandOperand_BIT_CONVERT(SDNode *N);
184   SDOperand ExpandOperand_UINT_TO_FP(SDOperand Source, MVT::ValueType DestTy);
185   SDOperand ExpandOperand_SINT_TO_FP(SDOperand Source, MVT::ValueType DestTy);
186   SDOperand ExpandOperand_EXTRACT_ELEMENT(SDNode *N);
187   SDOperand ExpandOperand_SETCC(SDNode *N);
188   SDOperand ExpandOperand_STORE(StoreSDNode *N, unsigned OpNo);
189
190   void ExpandSetCCOperands(SDOperand &NewLHS, SDOperand &NewRHS,
191                            ISD::CondCode &CCCode);
192 };
193 }  // end anonymous namespace
194
195
196
197 /// run - This is the main entry point for the type legalizer.  This does a
198 /// top-down traversal of the dag, legalizing types as it goes.
199 void DAGTypeLegalizer::run() {
200   // Create a dummy node (which is not added to allnodes), that adds a reference
201   // to the root node, preventing it from being deleted, and tracking any
202   // changes of the root.
203   HandleSDNode Dummy(DAG.getRoot());
204
205   // The root of the dag may dangle to deleted nodes until the type legalizer is
206   // done.  Set it to null to avoid confusion.
207   DAG.setRoot(SDOperand());
208   
209   // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
210   // (and remembering them) if they are leaves and assigning 'NewNode' if
211   // non-leaves.
212   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
213        E = DAG.allnodes_end(); I != E; ++I) {
214     if (I->getNumOperands() == 0) {
215       I->setNodeId(ReadyToProcess);
216       Worklist.push_back(I);
217     } else {
218       I->setNodeId(NewNode);
219     }
220   }
221   
222   // Now that we have a set of nodes to process, handle them all.
223   while (!Worklist.empty()) {
224     SDNode *N = Worklist.back();
225     Worklist.pop_back();
226     assert(N->getNodeId() == ReadyToProcess &&
227            "Node should be ready if on worklist!");
228     
229     // Scan the values produced by the node, checking to see if any result
230     // types are illegal.
231     unsigned i = 0;
232     unsigned NumResults = N->getNumValues();
233     do {
234       LegalizeAction Action = getTypeAction(N->getValueType(i));
235       if (Action == Promote) {
236         PromoteResult(N, i);
237         goto NodeDone;
238       } else if (Action == Expand) {
239         ExpandResult(N, i);
240         goto NodeDone;
241       } else {
242         assert(Action == Legal && "Unknown action!");
243       }
244     } while (++i < NumResults);
245     
246     // Scan the operand list for the node, handling any nodes with operands that
247     // are illegal.
248     {
249     unsigned NumOperands = N->getNumOperands();
250     bool NeedsRevisit = false;
251     for (i = 0; i != NumOperands; ++i) {
252       LegalizeAction Action = getTypeAction(N->getOperand(i).getValueType());
253       if (Action == Promote) {
254         NeedsRevisit = PromoteOperand(N, i);
255         break;
256       } else if (Action == Expand) {
257         NeedsRevisit = ExpandOperand(N, i);
258         break;
259       } else {
260         assert(Action == Legal && "Unknown action!");
261       }
262     }
263
264     // If the node needs revisiting, don't add all users to the worklist etc.
265     if (NeedsRevisit)
266       continue;
267     
268     if (i == NumOperands)
269       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
270     }
271 NodeDone:
272
273     // If we reach here, the node was processed, potentially creating new nodes.
274     // Mark it as processed and add its users to the worklist as appropriate.
275     N->setNodeId(Processed);
276     
277     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
278          UI != E; ++UI) {
279       SDNode *User = *UI;
280       int NodeID = User->getNodeId();
281       assert(NodeID != ReadyToProcess && NodeID != Processed &&
282              "Invalid node id for user of unprocessed node!");
283       
284       // This node has two options: it can either be a new node or its Node ID
285       // may be a count of the number of operands it has that are not ready.
286       if (NodeID > 0) {
287         User->setNodeId(NodeID-1);
288         
289         // If this was the last use it was waiting on, add it to the ready list.
290         if (NodeID-1 == ReadyToProcess)
291           Worklist.push_back(User);
292         continue;
293       }
294       
295       // Otherwise, this node is new: this is the first operand of it that
296       // became ready.  Its new NodeID is the number of operands it has minus 1
297       // (as this node is now processed).
298       assert(NodeID == NewNode && "Unknown node ID!");
299       User->setNodeId(User->getNumOperands()-1);
300       
301       // If the node only has a single operand, it is now ready.
302       if (User->getNumOperands() == 1)
303         Worklist.push_back(User);
304     }
305   }
306   
307   // If the root changed (e.g. it was a dead load, update the root).
308   DAG.setRoot(Dummy.getValue());
309
310   //DAG.viewGraph();
311
312   // Remove dead nodes.  This is important to do for cleanliness but also before
313   // the checking loop below.  Implicit folding by the DAG.getNode operators can
314   // cause unreachable nodes to be around with their flags set to new.
315   DAG.RemoveDeadNodes();
316
317   // In a debug build, scan all the nodes to make sure we found them all.  This
318   // ensures that there are no cycles and that everything got processed.
319 #ifndef NDEBUG
320   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
321        E = DAG.allnodes_end(); I != E; ++I) {
322     if (I->getNodeId() == Processed)
323       continue;
324     cerr << "Unprocessed node: ";
325     I->dump(&DAG); cerr << "\n";
326
327     if (I->getNodeId() == NewNode)
328       cerr << "New node not 'noticed'?\n";
329     else if (I->getNodeId() > 0)
330       cerr << "Operand not processed?\n";
331     else if (I->getNodeId() == ReadyToProcess)
332       cerr << "Not added to worklist?\n";
333     abort();
334   }
335 #endif
336 }
337
338 /// MarkNewNodes - The specified node is the root of a subtree of potentially
339 /// new nodes.  Add the correct NodeId to mark it.
340 void DAGTypeLegalizer::MarkNewNodes(SDNode *N) {
341   // If this was an existing node that is already done, we're done.
342   if (N->getNodeId() != NewNode)
343     return;
344
345   // Okay, we know that this node is new.  Recursively walk all of its operands
346   // to see if they are new also.  The depth of this walk is bounded by the size
347   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
348   // about revisiting of nodes.
349   //
350   // As we walk the operands, keep track of the number of nodes that are
351   // processed.  If non-zero, this will become the new nodeid of this node.
352   unsigned NumProcessed = 0;
353   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
354     int OpId = N->getOperand(i).Val->getNodeId();
355     if (OpId == NewNode)
356       MarkNewNodes(N->getOperand(i).Val);
357     else if (OpId == Processed)
358       ++NumProcessed;
359   }
360   
361   N->setNodeId(N->getNumOperands()-NumProcessed);
362   if (N->getNodeId() == ReadyToProcess)
363     Worklist.push_back(N);
364 }
365
366 /// ReplaceLegalValueWith - The specified value with a legal type was legalized
367 /// to the specified other value.  If they are different, update the DAG and
368 /// NodeIDs replacing any uses of From to use To instead.
369 void DAGTypeLegalizer::ReplaceLegalValueWith(SDOperand From, SDOperand To) {
370   if (From == To) return;
371   
372   // If expansion produced new nodes, make sure they are properly marked.
373   if (To.Val->getNodeId() == NewNode)
374     MarkNewNodes(To.Val);
375   
376   // Anything that used the old node should now use the new one.  Note that this
377   // can potentially cause recursive merging.
378   DAG.ReplaceAllUsesOfValueWith(From, To);
379   
380   // Since we just made an unstructured update to the DAG, which could wreak
381   // general havoc on anything that once used N and now uses Res, walk all users
382   // of the result, updating their flags.
383   for (SDNode::use_iterator I = To.Val->use_begin(), E = To.Val->use_end();
384        I != E; ++I) {
385     SDNode *User = *I;
386     // If the node isn't already processed or in the worklist, mark it as new,
387     // then use MarkNewNodes to recompute its ID.
388     int NodeId = User->getNodeId();
389     if (NodeId != ReadyToProcess && NodeId != Processed) {
390       User->setNodeId(NewNode);
391       MarkNewNodes(User);
392     }
393   }
394 }
395
396 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
397   if (Result.Val->getNodeId() == NewNode) 
398     MarkNewNodes(Result.Val);
399
400   SDOperand &OpEntry = PromotedNodes[Op];
401   assert(OpEntry.Val == 0 && "Node is already promoted!");
402   OpEntry = Result;
403 }
404
405 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo, 
406                                      SDOperand &Hi) {
407   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
408   assert(Entry.first.Val && "Operand isn't expanded");
409   Lo = Entry.first;
410   Hi = Entry.second;
411 }
412
413 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, 
414                                      SDOperand Hi) {
415   // Remember that this is the result of the node.
416   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
417   assert(Entry.first.Val == 0 && "Node already expanded");
418   Entry.first = Lo;
419   Entry.second = Hi;
420   
421   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
422   if (Lo.Val->getNodeId() == NewNode) 
423     MarkNewNodes(Lo.Val);
424   if (Hi.Val->getNodeId() == NewNode) 
425     MarkNewNodes(Hi.Val);
426 }
427
428 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op, 
429                                                  MVT::ValueType DestVT) {
430   // Create the stack frame object.
431   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
432   
433   // Emit a store to the stack slot.
434   SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
435   // Result is a load from the stack slot.
436   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
437 }
438
439 //===----------------------------------------------------------------------===//
440 //  Result Promotion
441 //===----------------------------------------------------------------------===//
442
443 /// PromoteResult - This method is called when a result of a node is found to be
444 /// in need of promotion to a larger type.  At this point, the node may also
445 /// have invalid operands or may have other results that need expansion, we just
446 /// know that (at least) one result needs promotion.
447 void DAGTypeLegalizer::PromoteResult(SDNode *N, unsigned ResNo) {
448   DEBUG(cerr << "Promote node result: "; N->dump(&DAG); cerr << "\n");
449   SDOperand Result = SDOperand();
450   
451   switch (N->getOpcode()) {
452   default:
453 #ifndef NDEBUG
454     cerr << "PromoteResult #" << ResNo << ": ";
455     N->dump(&DAG); cerr << "\n";
456 #endif
457     assert(0 && "Do not know how to promote this operator!");
458     abort();
459   case ISD::UNDEF:    Result = PromoteResult_UNDEF(N); break;
460   case ISD::Constant: Result = PromoteResult_Constant(N); break;
461     
462   case ISD::TRUNCATE:    Result = PromoteResult_TRUNCATE(N); break;
463   case ISD::SIGN_EXTEND:
464   case ISD::ZERO_EXTEND:
465   case ISD::ANY_EXTEND:  Result = PromoteResult_INT_EXTEND(N); break;
466   case ISD::FP_ROUND:    Result = PromoteResult_FP_ROUND(N); break;
467     
468   case ISD::SETCC:    Result = PromoteResult_SETCC(N); break;
469   case ISD::LOAD:     Result = PromoteResult_LOAD(cast<LoadSDNode>(N)); break;
470     
471   case ISD::AND:
472   case ISD::OR:
473   case ISD::XOR:
474   case ISD::ADD:
475   case ISD::SUB:
476   case ISD::MUL:      Result = PromoteResult_SimpleIntBinOp(N); break;
477     
478   case ISD::SELECT:    Result = PromoteResult_SELECT(N); break;
479   case ISD::SELECT_CC: Result = PromoteResult_SELECT_CC(N); break;
480
481   }      
482   
483   // If Result is null, the sub-method took care of registering the result.
484   if (Result.Val)
485     SetPromotedOp(SDOperand(N, ResNo), Result);
486 }
487
488 SDOperand DAGTypeLegalizer::PromoteResult_UNDEF(SDNode *N) {
489   return DAG.getNode(ISD::UNDEF, TLI.getTypeToTransformTo(N->getValueType(0)));
490 }
491
492 SDOperand DAGTypeLegalizer::PromoteResult_Constant(SDNode *N) {
493   MVT::ValueType VT = N->getValueType(0);
494   // Zero extend things like i1, sign extend everything else.  It shouldn't
495   // matter in theory which one we pick, but this tends to give better code?
496   unsigned Opc = VT != MVT::i1 ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
497   SDOperand Result = DAG.getNode(Opc, TLI.getTypeToTransformTo(VT),
498                                  SDOperand(N, 0));
499   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
500   return Result;
501 }
502
503 SDOperand DAGTypeLegalizer::PromoteResult_TRUNCATE(SDNode *N) {
504   SDOperand Res;
505
506   switch (getTypeAction(N->getOperand(0).getValueType())) {
507   default: assert(0 && "Unknown type action!");
508   case Legal:
509   case Expand:
510     Res = N->getOperand(0);
511     break;
512   case Promote:
513     Res = GetPromotedOp(N->getOperand(0));
514     break;
515   }
516
517   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
518   assert(MVT::getSizeInBits(Res.getValueType()) >= MVT::getSizeInBits(NVT) &&
519          "Truncation doesn't make sense!");
520   if (Res.getValueType() == NVT)
521     return Res;
522
523   // Truncate to NVT instead of VT
524   return DAG.getNode(ISD::TRUNCATE, NVT, Res);
525 }
526
527 SDOperand DAGTypeLegalizer::PromoteResult_INT_EXTEND(SDNode *N) {
528   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
529
530   if (getTypeAction(N->getOperand(0).getValueType()) == Promote) {
531     SDOperand Res = GetPromotedOp(N->getOperand(0));
532     assert(MVT::getSizeInBits(Res.getValueType()) <= MVT::getSizeInBits(NVT) &&
533            "Extension doesn't make sense!");
534
535     // If the result and operand types are the same after promotion, simplify
536     // to an in-register extension.
537     if (NVT == Res.getValueType()) {
538       // The high bits are not guaranteed to be anything.  Insert an extend.
539       if (N->getOpcode() == ISD::SIGN_EXTEND)
540         return DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Res,
541                            DAG.getValueType(N->getOperand(0).getValueType()));
542       if (N->getOpcode() == ISD::ZERO_EXTEND)
543         return DAG.getZeroExtendInReg(Res, N->getOperand(0).getValueType());
544       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
545       return Res;
546     }
547   }
548
549   // Otherwise, just extend the original operand all the way to the larger type.
550   return DAG.getNode(N->getOpcode(), NVT, N->getOperand(0));
551 }
552
553 SDOperand DAGTypeLegalizer::PromoteResult_FP_ROUND(SDNode *N) {
554   // NOTE: Assumes input is legal.
555   return DAG.getNode(ISD::FP_ROUND_INREG, N->getOperand(0).getValueType(),
556                      N->getOperand(0), DAG.getValueType(N->getValueType(0)));
557 }
558
559 SDOperand DAGTypeLegalizer::PromoteResult_SETCC(SDNode *N) {
560   assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
561   return DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), N->getOperand(0),
562                      N->getOperand(1), N->getOperand(2));
563 }
564
565 SDOperand DAGTypeLegalizer::PromoteResult_LOAD(LoadSDNode *N) {
566   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
567   ISD::LoadExtType ExtType =
568     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
569   SDOperand Res = DAG.getExtLoad(ExtType, NVT, N->getChain(), N->getBasePtr(),
570                                  N->getSrcValue(), N->getSrcValueOffset(),
571                                  N->getLoadedVT(), N->isVolatile(),
572                                  N->getAlignment());
573
574   // Legalized the chain result - switch anything that used the old chain to
575   // use the new one.
576   ReplaceLegalValueWith(SDOperand(N, 1), Res.getValue(1));
577   return Res;
578 }
579
580 SDOperand DAGTypeLegalizer::PromoteResult_SimpleIntBinOp(SDNode *N) {
581   // The input may have strange things in the top bits of the registers, but
582   // these operations don't care.  They may have weird bits going out, but
583   // that too is okay if they are integer operations.
584   SDOperand LHS = GetPromotedOp(N->getOperand(0));
585   SDOperand RHS = GetPromotedOp(N->getOperand(1));
586   return DAG.getNode(N->getOpcode(), LHS.getValueType(), LHS, RHS);
587 }
588
589 SDOperand DAGTypeLegalizer::PromoteResult_SELECT(SDNode *N) {
590   SDOperand LHS = GetPromotedOp(N->getOperand(1));
591   SDOperand RHS = GetPromotedOp(N->getOperand(2));
592   return DAG.getNode(ISD::SELECT, LHS.getValueType(), N->getOperand(0),LHS,RHS);
593 }
594
595 SDOperand DAGTypeLegalizer::PromoteResult_SELECT_CC(SDNode *N) {
596   SDOperand LHS = GetPromotedOp(N->getOperand(2));
597   SDOperand RHS = GetPromotedOp(N->getOperand(3));
598   return DAG.getNode(ISD::SELECT_CC, LHS.getValueType(), N->getOperand(0),
599                      N->getOperand(1), LHS, RHS, N->getOperand(4));
600 }
601
602 //===----------------------------------------------------------------------===//
603 //  Result Expansion
604 //===----------------------------------------------------------------------===//
605
606 /// ExpandResult - This method is called when the specified result of the
607 /// specified node is found to need expansion.  At this point, the node may also
608 /// have invalid operands or may have other results that need promotion, we just
609 /// know that (at least) one result needs expansion.
610 void DAGTypeLegalizer::ExpandResult(SDNode *N, unsigned ResNo) {
611   DEBUG(cerr << "Expand node result: "; N->dump(&DAG); cerr << "\n");
612   SDOperand Lo, Hi;
613   Lo = Hi = SDOperand();
614
615   // If this is a single-result node, see if the target wants to custom expand
616   // it.
617   if (N->getNumValues() == 1 &&
618       TLI.getOperationAction(N->getOpcode(),
619                              N->getValueType(0)) == TargetLowering::Custom) {
620     // If the target wants to, allow it to lower this itself.
621     std::pair<SDOperand,SDOperand> P =
622       TLI.ExpandOperation(SDOperand(N, 0), DAG);
623     if (P.first.Val) {
624       Lo = P.first;
625       Hi = P.second;
626       return;
627     }
628   }
629   
630   switch (N->getOpcode()) {
631   default:
632 #ifndef NDEBUG
633     cerr << "ExpandResult #" << ResNo << ": ";
634     N->dump(&DAG); cerr << "\n";
635 #endif
636     assert(0 && "Do not know how to expand this operator!");
637     abort();
638       
639   case ISD::UNDEF:       ExpandResult_UNDEF(N, Lo, Hi); break;
640   case ISD::Constant:    ExpandResult_Constant(N, Lo, Hi); break;
641   case ISD::BUILD_PAIR:  ExpandResult_BUILD_PAIR(N, Lo, Hi); break;
642   case ISD::ANY_EXTEND:  ExpandResult_ANY_EXTEND(N, Lo, Hi); break;
643   case ISD::ZERO_EXTEND: ExpandResult_ZERO_EXTEND(N, Lo, Hi); break;
644   case ISD::SIGN_EXTEND: ExpandResult_SIGN_EXTEND(N, Lo, Hi); break;
645   case ISD::BIT_CONVERT: ExpandResult_BIT_CONVERT(N, Lo, Hi); break;
646   case ISD::SIGN_EXTEND_INREG: ExpandResult_SIGN_EXTEND_INREG(N, Lo, Hi); break;
647   case ISD::LOAD:        ExpandResult_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
648     
649   case ISD::AND:
650   case ISD::OR:
651   case ISD::XOR:         ExpandResult_Logical(N, Lo, Hi); break;
652   case ISD::BSWAP:       ExpandResult_BSWAP(N, Lo, Hi); break;
653   case ISD::ADD:
654   case ISD::SUB:         ExpandResult_ADDSUB(N, Lo, Hi); break;
655   case ISD::ADDC:
656   case ISD::SUBC:        ExpandResult_ADDSUBC(N, Lo, Hi); break;
657   case ISD::ADDE:
658   case ISD::SUBE:        ExpandResult_ADDSUBE(N, Lo, Hi); break;
659   case ISD::SELECT:      ExpandResult_SELECT(N, Lo, Hi); break;
660   case ISD::SELECT_CC:   ExpandResult_SELECT_CC(N, Lo, Hi); break;
661   case ISD::MUL:         ExpandResult_MUL(N, Lo, Hi); break;
662   case ISD::SHL:
663   case ISD::SRA:
664   case ISD::SRL:         ExpandResult_Shift(N, Lo, Hi); break;
665
666   }
667   
668   // If Lo/Hi is null, the sub-method took care of registering results etc.
669   if (Lo.Val)
670     SetExpandedOp(SDOperand(N, ResNo), Lo, Hi);
671 }
672
673 void DAGTypeLegalizer::ExpandResult_UNDEF(SDNode *N,
674                                           SDOperand &Lo, SDOperand &Hi) {
675   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
676   Lo = Hi = DAG.getNode(ISD::UNDEF, NVT);
677 }
678
679 void DAGTypeLegalizer::ExpandResult_Constant(SDNode *N,
680                                              SDOperand &Lo, SDOperand &Hi) {
681   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
682   uint64_t Cst = cast<ConstantSDNode>(N)->getValue();
683   Lo = DAG.getConstant(Cst, NVT);
684   Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
685 }
686
687 void DAGTypeLegalizer::ExpandResult_BUILD_PAIR(SDNode *N,
688                                                SDOperand &Lo, SDOperand &Hi) {
689   // Return the operands.
690   Lo = N->getOperand(0);
691   Hi = N->getOperand(1);
692 }
693
694 void DAGTypeLegalizer::ExpandResult_ANY_EXTEND(SDNode *N, 
695                                                SDOperand &Lo, SDOperand &Hi) {
696   
697   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
698   // The low part is any extension of the input (which degenerates to a copy).
699   Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, N->getOperand(0));
700   Hi = DAG.getNode(ISD::UNDEF, NVT);   // The high part is undefined.
701 }
702
703 void DAGTypeLegalizer::ExpandResult_ZERO_EXTEND(SDNode *N,
704                                                 SDOperand &Lo, SDOperand &Hi) {
705   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
706   // The low part is zero extension of the input (which degenerates to a copy).
707   Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, N->getOperand(0));
708   Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
709 }
710
711 void DAGTypeLegalizer::ExpandResult_SIGN_EXTEND(SDNode *N,
712                                                 SDOperand &Lo, SDOperand &Hi) {
713   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
714   // The low part is sign extension of the input (which degenerates to a copy).
715   Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, N->getOperand(0));
716
717   // The high part is obtained by SRA'ing all but one of the bits of low part.
718   unsigned LoSize = MVT::getSizeInBits(NVT);
719   Hi = DAG.getNode(ISD::SRA, NVT, Lo,
720                    DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
721 }
722
723 void DAGTypeLegalizer::ExpandResult_BIT_CONVERT(SDNode *N,
724                                                 SDOperand &Lo, SDOperand &Hi) {
725   // Lower the bit-convert to a store/load from the stack, then expand the load.
726   SDOperand Op = CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
727   ExpandResult_LOAD(cast<LoadSDNode>(Op.Val), Lo, Hi);
728 }
729
730 void DAGTypeLegalizer::
731 ExpandResult_SIGN_EXTEND_INREG(SDNode *N, SDOperand &Lo, SDOperand &Hi) {
732   GetExpandedOp(N->getOperand(0), Lo, Hi);
733   
734   // sext_inreg the low part if needed.
735   Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, Lo.getValueType(), Lo,
736                    N->getOperand(1));
737   
738   // The high part gets the sign extension from the lo-part.  This handles
739   // things like sextinreg V:i64 from i8.
740   Hi = DAG.getNode(ISD::SRA, Hi.getValueType(), Lo,
741                    DAG.getConstant(MVT::getSizeInBits(Hi.getValueType())-1,
742                                    TLI.getShiftAmountTy()));
743 }
744
745
746 void DAGTypeLegalizer::ExpandResult_LOAD(LoadSDNode *N,
747                                          SDOperand &Lo, SDOperand &Hi) {
748   MVT::ValueType VT = N->getValueType(0);
749   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
750   SDOperand Ch  = N->getChain();    // Legalize the chain.
751   SDOperand Ptr = N->getBasePtr();  // Legalize the pointer.
752   ISD::LoadExtType ExtType = N->getExtensionType();
753   int SVOffset = N->getSrcValueOffset();
754   unsigned Alignment = N->getAlignment();
755   bool isVolatile = N->isVolatile();
756   
757   if (ExtType == ISD::NON_EXTLOAD) {
758     Lo = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(), SVOffset,
759                      isVolatile, Alignment);
760     // Increment the pointer to the other half.
761     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
762     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
763                       getIntPtrConstant(IncrementSize));
764     Hi = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
765                      isVolatile, std::max(Alignment, IncrementSize));
766     
767     // Build a factor node to remember that this load is independent of the
768     // other one.
769     Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
770                      Hi.getValue(1));
771
772     // Handle endianness of the load.
773     if (!TLI.isLittleEndian())
774       std::swap(Lo, Hi);
775   } else {
776     MVT::ValueType EVT = N->getLoadedVT();
777     
778     if (EVT == NVT)
779       Lo = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(),
780                        SVOffset, isVolatile, Alignment);
781     else
782       Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(),
783                           SVOffset, EVT, isVolatile,
784                           Alignment);
785     // Remember the chain.
786     Ch = Lo.getValue(1);
787     
788     if (ExtType == ISD::SEXTLOAD) {
789       // The high part is obtained by SRA'ing all but one of the bits of the
790       // lo part.
791       unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
792       Hi = DAG.getNode(ISD::SRA, NVT, Lo,
793                        DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
794     } else if (ExtType == ISD::ZEXTLOAD) {
795       // The high part is just a zero.
796       Hi = DAG.getConstant(0, NVT);
797     } else {
798       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
799       // The high part is undefined.
800       Hi = DAG.getNode(ISD::UNDEF, NVT);
801     }
802   }
803   
804   // Legalized the chain result - switch anything that used the old chain to
805   // use the new one.
806   ReplaceLegalValueWith(SDOperand(N, 1), Ch);
807 }  
808
809
810 void DAGTypeLegalizer::ExpandResult_Logical(SDNode *N,
811                                             SDOperand &Lo, SDOperand &Hi) {
812   SDOperand LL, LH, RL, RH;
813   GetExpandedOp(N->getOperand(0), LL, LH);
814   GetExpandedOp(N->getOperand(1), RL, RH);
815   Lo = DAG.getNode(N->getOpcode(), LL.getValueType(), LL, RL);
816   Hi = DAG.getNode(N->getOpcode(), LL.getValueType(), LH, RH);
817 }
818
819 void DAGTypeLegalizer::ExpandResult_BSWAP(SDNode *N,
820                                           SDOperand &Lo, SDOperand &Hi) {
821   GetExpandedOp(N->getOperand(0), Hi, Lo);  // Note swapped operands.
822   Lo = DAG.getNode(ISD::BSWAP, Lo.getValueType(), Lo);
823   Hi = DAG.getNode(ISD::BSWAP, Hi.getValueType(), Hi);
824 }
825
826
827 void DAGTypeLegalizer::ExpandResult_SELECT(SDNode *N,
828                                            SDOperand &Lo, SDOperand &Hi) {
829   SDOperand LL, LH, RL, RH;
830   GetExpandedOp(N->getOperand(1), LL, LH);
831   GetExpandedOp(N->getOperand(2), RL, RH);
832   Lo = DAG.getNode(ISD::SELECT, LL.getValueType(), N->getOperand(0), LL, RL);
833   
834   assert(N->getOperand(0).getValueType() != MVT::f32 &&
835          "FIXME: softfp shouldn't use expand!");
836   Hi = DAG.getNode(ISD::SELECT, LL.getValueType(), N->getOperand(0), LH, RH);
837 }
838
839 void DAGTypeLegalizer::ExpandResult_SELECT_CC(SDNode *N,
840                                               SDOperand &Lo, SDOperand &Hi) {
841   SDOperand LL, LH, RL, RH;
842   GetExpandedOp(N->getOperand(2), LL, LH);
843   GetExpandedOp(N->getOperand(3), RL, RH);
844   Lo = DAG.getNode(ISD::SELECT_CC, LL.getValueType(), N->getOperand(0), 
845                    N->getOperand(1), LL, RL, N->getOperand(4));
846   
847   assert(N->getOperand(0).getValueType() != MVT::f32 &&
848          "FIXME: softfp shouldn't use expand!");
849   Hi = DAG.getNode(ISD::SELECT_CC, LL.getValueType(), N->getOperand(0), 
850                    N->getOperand(1), LH, RH, N->getOperand(4));
851 }
852
853 void DAGTypeLegalizer::ExpandResult_ADDSUB(SDNode *N,
854                                            SDOperand &Lo, SDOperand &Hi) {
855   MVT::ValueType VT = N->getValueType(0);
856   
857   // If the target wants to custom expand this, let them.
858   if (TLI.getOperationAction(N->getOpcode(), VT) ==
859       TargetLowering::Custom) {
860     std::pair<SDOperand,SDOperand> Ret = 
861       TLI.ExpandOperation(SDOperand(N, 0), DAG);
862     if (Ret.first.Val) {
863       Lo = Ret.first;
864       Hi = Ret.second;
865       return;
866     }
867   }
868   
869   // Expand the subcomponents.
870   SDOperand LHSL, LHSH, RHSL, RHSH;
871   GetExpandedOp(N->getOperand(0), LHSL, LHSH);
872   GetExpandedOp(N->getOperand(1), RHSL, RHSH);
873   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
874   SDOperand LoOps[2] = { LHSL, RHSL };
875   SDOperand HiOps[3] = { LHSH, RHSH };
876
877   if (N->getOpcode() == ISD::ADD) {
878     Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
879     HiOps[2] = Lo.getValue(1);
880     Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
881   } else {
882     Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
883     HiOps[2] = Lo.getValue(1);
884     Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
885   }
886 }
887
888 void DAGTypeLegalizer::ExpandResult_ADDSUBC(SDNode *N,
889                                             SDOperand &Lo, SDOperand &Hi) {
890   // Expand the subcomponents.
891   SDOperand LHSL, LHSH, RHSL, RHSH;
892   GetExpandedOp(N->getOperand(0), LHSL, LHSH);
893   GetExpandedOp(N->getOperand(1), RHSL, RHSH);
894   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
895   SDOperand LoOps[2] = { LHSL, RHSL };
896   SDOperand HiOps[3] = { LHSH, RHSH };
897
898   if (N->getOpcode() == ISD::ADDC) {
899     Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
900     HiOps[2] = Lo.getValue(1);
901     Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
902   } else {
903     Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
904     HiOps[2] = Lo.getValue(1);
905     Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
906   }
907
908   // Legalized the flag result - switch anything that used the old flag to
909   // use the new one.
910   ReplaceLegalValueWith(SDOperand(N, 1), Hi.getValue(1));
911 }
912
913 void DAGTypeLegalizer::ExpandResult_ADDSUBE(SDNode *N,
914                                             SDOperand &Lo, SDOperand &Hi) {
915   // Expand the subcomponents.
916   SDOperand LHSL, LHSH, RHSL, RHSH;
917   GetExpandedOp(N->getOperand(0), LHSL, LHSH);
918   GetExpandedOp(N->getOperand(1), RHSL, RHSH);
919   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
920   SDOperand LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
921   SDOperand HiOps[3] = { LHSH, RHSH };
922
923   Lo = DAG.getNode(N->getOpcode(), VTList, LoOps, 3);
924   HiOps[2] = Lo.getValue(1);
925   Hi = DAG.getNode(N->getOpcode(), VTList, HiOps, 3);
926
927   // Legalized the flag result - switch anything that used the old flag to
928   // use the new one.
929   ReplaceLegalValueWith(SDOperand(N, 1), Hi.getValue(1));
930 }
931
932 void DAGTypeLegalizer::ExpandResult_MUL(SDNode *N,
933                                         SDOperand &Lo, SDOperand &Hi) {
934   MVT::ValueType VT = N->getValueType(0);
935   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
936   
937   bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
938   bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
939   bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
940   bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
941   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
942     SDOperand LL, LH, RL, RH;
943     GetExpandedOp(N->getOperand(0), LL, LH);
944     GetExpandedOp(N->getOperand(1), RL, RH);
945     unsigned BitSize = MVT::getSizeInBits(RH.getValueType());
946     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
947     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
948     
949     // FIXME: generalize this to handle other bit sizes
950     if (LHSSB == 32 && RHSSB == 32 &&
951         DAG.MaskedValueIsZero(N->getOperand(0), 0xFFFFFFFF00000000ULL) &&
952         DAG.MaskedValueIsZero(N->getOperand(1), 0xFFFFFFFF00000000ULL)) {
953       // The inputs are both zero-extended.
954       if (HasUMUL_LOHI) {
955         // We can emit a umul_lohi.
956         Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
957         Hi = SDOperand(Lo.Val, 1);
958         return;
959       }
960       if (HasMULHU) {
961         // We can emit a mulhu+mul.
962         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
963         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
964         return;
965       }
966     }
967     if (LHSSB > BitSize && RHSSB > BitSize) {
968       // The input values are both sign-extended.
969       if (HasSMUL_LOHI) {
970         // We can emit a smul_lohi.
971         Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
972         Hi = SDOperand(Lo.Val, 1);
973         return;
974       }
975       if (HasMULHS) {
976         // We can emit a mulhs+mul.
977         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
978         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
979         return;
980       }
981     }
982     if (HasUMUL_LOHI) {
983       // Lo,Hi = umul LHS, RHS.
984       SDOperand UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
985                                        DAG.getVTList(NVT, NVT), LL, RL);
986       Lo = UMulLOHI;
987       Hi = UMulLOHI.getValue(1);
988       RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
989       LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
990       Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
991       Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
992       return;
993     }
994   }
995   
996   abort();
997 #if 0 // FIXME!
998   // If nothing else, we can make a libcall.
999   Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::MUL_I64), N,
1000                      false/*sign irrelevant*/, Hi);
1001 #endif
1002 }  
1003
1004
1005 void DAGTypeLegalizer::ExpandResult_Shift(SDNode *N,
1006                                           SDOperand &Lo, SDOperand &Hi) {
1007   MVT::ValueType VT = N->getValueType(0);
1008   
1009   // If we can emit an efficient shift operation, do so now.  Check to see if 
1010   // the RHS is a constant.
1011   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1012     return ExpandShiftByConstant(N, CN->getValue(), Lo, Hi);
1013
1014   // If we can determine that the high bit of the shift is zero or one, even if
1015   // the low bits are variable, emit this shift in an optimized form.
1016   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
1017     return;
1018   
1019   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
1020   unsigned PartsOpc;
1021   if (N->getOpcode() == ISD::SHL)
1022     PartsOpc = ISD::SHL_PARTS;
1023   else if (N->getOpcode() == ISD::SRL)
1024     PartsOpc = ISD::SRL_PARTS;
1025   else {
1026     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1027     PartsOpc = ISD::SRA_PARTS;
1028   }
1029   
1030   // Next check to see if the target supports this SHL_PARTS operation or if it
1031   // will custom expand it.
1032   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1033   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
1034   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
1035       Action == TargetLowering::Custom) {
1036     // Expand the subcomponents.
1037     SDOperand LHSL, LHSH;
1038     GetExpandedOp(N->getOperand(0), LHSL, LHSH);
1039     
1040     SDOperand Ops[] = { LHSL, LHSH, N->getOperand(1) };
1041     MVT::ValueType VT = LHSL.getValueType();
1042     Lo = DAG.getNode(PartsOpc, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
1043     Hi = Lo.getValue(1);
1044     return;
1045   }
1046   
1047   abort();
1048 #if 0 // FIXME!
1049   // Otherwise, emit a libcall.
1050   unsigned RuntimeCode = ; // SRL -> SRL_I64 etc.
1051   bool Signed = ;
1052   Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRL_I64), N,
1053                      false/*lshr is unsigned*/, Hi);
1054 #endif
1055 }  
1056
1057
1058 /// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1059 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1060 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt, 
1061                                              SDOperand &Lo, SDOperand &Hi) {
1062   // Expand the incoming operand to be shifted, so that we have its parts
1063   SDOperand InL, InH;
1064   GetExpandedOp(N->getOperand(0), InL, InH);
1065   
1066   MVT::ValueType NVT = InL.getValueType();
1067   unsigned VTBits = MVT::getSizeInBits(N->getValueType(0));
1068   unsigned NVTBits = MVT::getSizeInBits(NVT);
1069   MVT::ValueType ShTy = N->getOperand(1).getValueType();
1070
1071   if (N->getOpcode() == ISD::SHL) {
1072     if (Amt > VTBits) {
1073       Lo = Hi = DAG.getConstant(0, NVT);
1074     } else if (Amt > NVTBits) {
1075       Lo = DAG.getConstant(0, NVT);
1076       Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt-NVTBits,ShTy));
1077     } else if (Amt == NVTBits) {
1078       Lo = DAG.getConstant(0, NVT);
1079       Hi = InL;
1080     } else {
1081       Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt, ShTy));
1082       Hi = DAG.getNode(ISD::OR, NVT,
1083                        DAG.getNode(ISD::SHL, NVT, InH,
1084                                    DAG.getConstant(Amt, ShTy)),
1085                        DAG.getNode(ISD::SRL, NVT, InL,
1086                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1087     }
1088     return;
1089   }
1090   
1091   if (N->getOpcode() == ISD::SRL) {
1092     if (Amt > VTBits) {
1093       Lo = DAG.getConstant(0, NVT);
1094       Hi = DAG.getConstant(0, NVT);
1095     } else if (Amt > NVTBits) {
1096       Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1097       Hi = DAG.getConstant(0, NVT);
1098     } else if (Amt == NVTBits) {
1099       Lo = InH;
1100       Hi = DAG.getConstant(0, NVT);
1101     } else {
1102       Lo = DAG.getNode(ISD::OR, NVT,
1103                        DAG.getNode(ISD::SRL, NVT, InL,
1104                                    DAG.getConstant(Amt, ShTy)),
1105                        DAG.getNode(ISD::SHL, NVT, InH,
1106                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1107       Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt, ShTy));
1108     }
1109     return;
1110   }
1111   
1112   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1113   if (Amt > VTBits) {
1114     Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
1115                           DAG.getConstant(NVTBits-1, ShTy));
1116   } else if (Amt > NVTBits) {
1117     Lo = DAG.getNode(ISD::SRA, NVT, InH,
1118                      DAG.getConstant(Amt-NVTBits, ShTy));
1119     Hi = DAG.getNode(ISD::SRA, NVT, InH,
1120                      DAG.getConstant(NVTBits-1, ShTy));
1121   } else if (Amt == NVTBits) {
1122     Lo = InH;
1123     Hi = DAG.getNode(ISD::SRA, NVT, InH,
1124                      DAG.getConstant(NVTBits-1, ShTy));
1125   } else {
1126     Lo = DAG.getNode(ISD::OR, NVT,
1127                      DAG.getNode(ISD::SRL, NVT, InL,
1128                                  DAG.getConstant(Amt, ShTy)),
1129                      DAG.getNode(ISD::SHL, NVT, InH,
1130                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1131     Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Amt, ShTy));
1132   }
1133 }
1134
1135 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1136 /// this shift based on knowledge of the high bit of the shift amount.  If we
1137 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1138 /// shift amount.
1139 bool DAGTypeLegalizer::
1140 ExpandShiftWithKnownAmountBit(SDNode *N, SDOperand &Lo, SDOperand &Hi) {
1141   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1142   unsigned NVTBits = MVT::getSizeInBits(NVT);
1143
1144   uint64_t HighBitMask = NVTBits, KnownZero, KnownOne;
1145   DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1146   
1147   // If we don't know anything about the high bit, exit.
1148   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1149     return false;
1150
1151   // Get the incoming operand to be shifted.
1152   SDOperand InL, InH;
1153   GetExpandedOp(N->getOperand(0), InL, InH);
1154   SDOperand Amt = N->getOperand(1);
1155
1156   // If we know that the high bit of the shift amount is one, then we can do
1157   // this as a couple of simple shifts.
1158   if (KnownOne & HighBitMask) {
1159     // Mask out the high bit, which we know is set.
1160     Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
1161                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
1162     
1163     switch (N->getOpcode()) {
1164     default: assert(0 && "Unknown shift");
1165     case ISD::SHL:
1166       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1167       Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
1168       return true;
1169     case ISD::SRL:
1170       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1171       Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
1172       return true;
1173     case ISD::SRA:
1174       Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
1175                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
1176       Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
1177       return true;
1178     }
1179   }
1180   
1181   // If we know that the high bit of the shift amount is zero, then we can do
1182   // this as a couple of simple shifts.
1183   assert((KnownZero & HighBitMask) && "Bad mask computation above");
1184
1185   // Compute 32-amt.
1186   SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
1187                                DAG.getConstant(NVTBits, Amt.getValueType()),
1188                                Amt);
1189   unsigned Op1, Op2;
1190   switch (N->getOpcode()) {
1191   default: assert(0 && "Unknown shift");
1192   case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1193   case ISD::SRL:
1194   case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1195   }
1196     
1197   Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1198   Hi = DAG.getNode(ISD::OR, NVT,
1199                    DAG.getNode(Op1, NVT, InH, Amt),
1200                    DAG.getNode(Op2, NVT, InL, Amt2));
1201   return true;
1202 }
1203
1204 //===----------------------------------------------------------------------===//
1205 //  Operand Promotion
1206 //===----------------------------------------------------------------------===//
1207
1208 /// PromoteOperand - This method is called when the specified operand of the
1209 /// specified node is found to need promotion.  At this point, all of the result
1210 /// types of the node are known to be legal, but other operands of the node may
1211 /// need promotion or expansion as well as the specified one.
1212 bool DAGTypeLegalizer::PromoteOperand(SDNode *N, unsigned OpNo) {
1213   DEBUG(cerr << "Promote node operand: "; N->dump(&DAG); cerr << "\n");
1214   SDOperand Res;
1215   switch (N->getOpcode()) {
1216     default:
1217 #ifndef NDEBUG
1218     cerr << "PromoteOperand Op #" << OpNo << ": ";
1219     N->dump(&DAG); cerr << "\n";
1220 #endif
1221     assert(0 && "Do not know how to promote this operator's operand!");
1222     abort();
1223     
1224   case ISD::ANY_EXTEND:  Res = PromoteOperand_ANY_EXTEND(N); break;
1225   case ISD::ZERO_EXTEND: Res = PromoteOperand_ZERO_EXTEND(N); break;
1226   case ISD::SIGN_EXTEND: Res = PromoteOperand_SIGN_EXTEND(N); break;
1227   case ISD::FP_EXTEND:   Res = PromoteOperand_FP_EXTEND(N); break;
1228   case ISD::FP_ROUND:    Res = PromoteOperand_FP_ROUND(N); break;
1229     
1230   case ISD::SELECT:      Res = PromoteOperand_SELECT(N, OpNo); break;
1231   case ISD::BRCOND:      Res = PromoteOperand_BRCOND(N, OpNo); break;
1232   case ISD::BR_CC:       Res = PromoteOperand_BR_CC(N, OpNo); break;
1233
1234   case ISD::STORE:       Res = PromoteOperand_STORE(cast<StoreSDNode>(N),
1235                                                     OpNo); break;
1236   }
1237   
1238   // If the result is null, the sub-method took care of registering results etc.
1239   if (!Res.Val) return false;
1240   // If the result is N, the sub-method updated N in place.
1241   if (Res.Val == N) {
1242     // Mark N as new and remark N and its operands.  This allows us to correctly
1243     // revisit N if it needs another step of promotion and allows us to visit
1244     // any new operands to N.
1245     N->setNodeId(NewNode);
1246     MarkNewNodes(N);
1247     return true;
1248   }
1249   
1250   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1251          "Invalid operand expansion");
1252   
1253   ReplaceLegalValueWith(SDOperand(N, 0), Res);
1254   return false;
1255 }
1256
1257 SDOperand DAGTypeLegalizer::PromoteOperand_ANY_EXTEND(SDNode *N) {
1258   SDOperand Op = GetPromotedOp(N->getOperand(0));
1259   return DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1260 }
1261
1262 SDOperand DAGTypeLegalizer::PromoteOperand_ZERO_EXTEND(SDNode *N) {
1263   SDOperand Op = GetPromotedOp(N->getOperand(0));
1264   Op = DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1265   return DAG.getZeroExtendInReg(Op, N->getOperand(0).getValueType());
1266 }
1267
1268 SDOperand DAGTypeLegalizer::PromoteOperand_SIGN_EXTEND(SDNode *N) {
1269   SDOperand Op = GetPromotedOp(N->getOperand(0));
1270   Op = DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1271   return DAG.getNode(ISD::SIGN_EXTEND_INREG, Op.getValueType(),
1272                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
1273 }
1274
1275 SDOperand DAGTypeLegalizer::PromoteOperand_FP_EXTEND(SDNode *N) {
1276   SDOperand Op = GetPromotedOp(N->getOperand(0));
1277   return DAG.getNode(ISD::FP_EXTEND, N->getValueType(0), Op);
1278 }
1279 SDOperand DAGTypeLegalizer::PromoteOperand_FP_ROUND(SDNode *N) {
1280   SDOperand Op = GetPromotedOp(N->getOperand(0));
1281   return DAG.getNode(ISD::FP_ROUND, N->getValueType(0), Op);
1282 }
1283
1284
1285 SDOperand DAGTypeLegalizer::PromoteOperand_SELECT(SDNode *N, unsigned OpNo) {
1286   assert(OpNo == 0 && "Only know how to promote condition");
1287   SDOperand Cond = GetPromotedOp(N->getOperand(0));  // Promote the condition.
1288
1289   // The top bits of the promoted condition are not necessarily zero, ensure
1290   // that the value is properly zero extended.
1291   if (!DAG.MaskedValueIsZero(Cond, 
1292                              MVT::getIntVTBitMask(Cond.getValueType())^1)) {
1293     Cond = DAG.getZeroExtendInReg(Cond, MVT::i1);
1294     MarkNewNodes(Cond.Val); 
1295   }
1296
1297   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1298   return DAG.UpdateNodeOperands(SDOperand(N, 0), Cond, N->getOperand(1),
1299                                 N->getOperand(2));
1300 }
1301
1302
1303 SDOperand DAGTypeLegalizer::PromoteOperand_BRCOND(SDNode *N, unsigned OpNo) {
1304   assert(OpNo == 1 && "only know how to promote condition");
1305   SDOperand Cond = GetPromotedOp(N->getOperand(1));  // Promote the condition.
1306   
1307   // The top bits of the promoted condition are not necessarily zero, ensure
1308   // that the value is properly zero extended.
1309   if (!DAG.MaskedValueIsZero(Cond, 
1310                              MVT::getIntVTBitMask(Cond.getValueType())^1)) {
1311     Cond = DAG.getZeroExtendInReg(Cond, MVT::i1);
1312     MarkNewNodes(Cond.Val); 
1313   }
1314   
1315   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1316   return DAG.UpdateNodeOperands(SDOperand(N, 0), N->getOperand(0), Cond,
1317                                 N->getOperand(2));
1318 }
1319
1320 SDOperand DAGTypeLegalizer::PromoteOperand_BR_CC(SDNode *N, unsigned OpNo) {
1321   assert(OpNo == 2 && "Don't know how to promote this operand");
1322   
1323   SDOperand LHS = N->getOperand(2);
1324   SDOperand RHS = N->getOperand(3);
1325   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
1326   
1327   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
1328   // legal types.
1329   return DAG.UpdateNodeOperands(SDOperand(N, 0), N->getOperand(0),
1330                                 N->getOperand(1), LHS, RHS, N->getOperand(4));
1331 }
1332
1333 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
1334 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
1335 void DAGTypeLegalizer::PromoteSetCCOperands(SDOperand &NewLHS,SDOperand &NewRHS,
1336                                             ISD::CondCode CCCode) {
1337   MVT::ValueType VT = NewLHS.getValueType();
1338   
1339   // Get the promoted values.
1340   NewLHS = GetPromotedOp(NewLHS);
1341   NewRHS = GetPromotedOp(NewRHS);
1342   
1343   // If this is an FP compare, the operands have already been extended.
1344   if (!MVT::isInteger(NewLHS.getValueType()))
1345     return;
1346   
1347   // Otherwise, we have to insert explicit sign or zero extends.  Note
1348   // that we could insert sign extends for ALL conditions, but zero extend
1349   // is cheaper on many machines (an AND instead of two shifts), so prefer
1350   // it.
1351   switch (CCCode) {
1352   default: assert(0 && "Unknown integer comparison!");
1353   case ISD::SETEQ:
1354   case ISD::SETNE:
1355   case ISD::SETUGE:
1356   case ISD::SETUGT:
1357   case ISD::SETULE:
1358   case ISD::SETULT:
1359     // ALL of these operations will work if we either sign or zero extend
1360     // the operands (including the unsigned comparisons!).  Zero extend is
1361     // usually a simpler/cheaper operation, so prefer it.
1362     NewLHS = DAG.getZeroExtendInReg(NewLHS, VT);
1363     NewRHS = DAG.getZeroExtendInReg(NewRHS, VT);
1364     return;
1365   case ISD::SETGE:
1366   case ISD::SETGT:
1367   case ISD::SETLT:
1368   case ISD::SETLE:
1369     NewLHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, NewLHS.getValueType(), NewLHS,
1370                          DAG.getValueType(VT));
1371     NewRHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, NewRHS.getValueType(), NewRHS,
1372                          DAG.getValueType(VT));
1373     return;
1374   }
1375 }
1376   
1377
1378 SDOperand DAGTypeLegalizer::PromoteOperand_STORE(StoreSDNode *N, unsigned OpNo){
1379   SDOperand Ch = N->getChain(), Ptr = N->getBasePtr();
1380   int SVOffset = N->getSrcValueOffset();
1381   unsigned Alignment = N->getAlignment();
1382   bool isVolatile = N->isVolatile();
1383   
1384   SDOperand Val = GetPromotedOp(N->getValue());  // Get promoted value.
1385
1386   assert(!N->isTruncatingStore() && "Cannot promote this store operand!");
1387   
1388   // Truncate the value and store the result.
1389   return DAG.getTruncStore(Ch, Val, Ptr, N->getSrcValue(),
1390                            SVOffset, N->getStoredVT(),
1391                            isVolatile, Alignment);
1392 }
1393
1394
1395 //===----------------------------------------------------------------------===//
1396 //  Operand Expansion
1397 //===----------------------------------------------------------------------===//
1398
1399 /// ExpandOperand - This method is called when the specified operand of the
1400 /// specified node is found to need expansion.  At this point, all of the result
1401 /// types of the node are known to be legal, but other operands of the node may
1402 /// need promotion or expansion as well as the specified one.
1403 bool DAGTypeLegalizer::ExpandOperand(SDNode *N, unsigned OpNo) {
1404   DEBUG(cerr << "Expand node operand: "; N->dump(&DAG); cerr << "\n");
1405   SDOperand Res;
1406   switch (N->getOpcode()) {
1407   default:
1408 #ifndef NDEBUG
1409     cerr << "ExpandOperand Op #" << OpNo << ": ";
1410     N->dump(&DAG); cerr << "\n";
1411 #endif
1412     assert(0 && "Do not know how to expand this operator's operand!");
1413     abort();
1414     
1415   case ISD::TRUNCATE:        Res = ExpandOperand_TRUNCATE(N); break;
1416   case ISD::BIT_CONVERT:     Res = ExpandOperand_BIT_CONVERT(N); break;
1417
1418   case ISD::SINT_TO_FP:
1419     Res = ExpandOperand_SINT_TO_FP(N->getOperand(0), N->getValueType(0));
1420     break;
1421   case ISD::UINT_TO_FP:
1422     Res = ExpandOperand_UINT_TO_FP(N->getOperand(0), N->getValueType(0)); 
1423     break;
1424   case ISD::EXTRACT_ELEMENT: Res = ExpandOperand_EXTRACT_ELEMENT(N); break;
1425   case ISD::SETCC:           Res = ExpandOperand_SETCC(N); break;
1426
1427   case ISD::STORE: Res = ExpandOperand_STORE(cast<StoreSDNode>(N), OpNo); break;
1428   }
1429   
1430   // If the result is null, the sub-method took care of registering results etc.
1431   if (!Res.Val) return false;
1432   // If the result is N, the sub-method updated N in place.  Check to see if any
1433   // operands are new, and if so, mark them.
1434   if (Res.Val == N) {
1435     // Mark N as new and remark N and its operands.  This allows us to correctly
1436     // revisit N if it needs another step of promotion and allows us to visit
1437     // any new operands to N.
1438     N->setNodeId(NewNode);
1439     MarkNewNodes(N);
1440     return true;
1441   }
1442
1443   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1444          "Invalid operand expansion");
1445   
1446   ReplaceLegalValueWith(SDOperand(N, 0), Res);
1447   return false;
1448 }
1449
1450 SDOperand DAGTypeLegalizer::ExpandOperand_TRUNCATE(SDNode *N) {
1451   SDOperand InL, InH;
1452   GetExpandedOp(N->getOperand(0), InL, InH);
1453   // Just truncate the low part of the source.
1454   return DAG.getNode(ISD::TRUNCATE, N->getValueType(0), InL);
1455 }
1456
1457 SDOperand DAGTypeLegalizer::ExpandOperand_BIT_CONVERT(SDNode *N) {
1458   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
1459 }
1460
1461 SDOperand DAGTypeLegalizer::ExpandOperand_SINT_TO_FP(SDOperand Source, 
1462                                                      MVT::ValueType DestTy) {
1463   // We know the destination is legal, but that the input needs to be expanded.
1464   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1465   
1466   // Check to see if the target has a custom way to lower this.  If so, use it.
1467   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
1468   default: assert(0 && "This action not implemented for this operation!");
1469   case TargetLowering::Legal:
1470   case TargetLowering::Expand:
1471     break;   // This case is handled below.
1472   case TargetLowering::Custom:
1473     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
1474                                                   Source), DAG);
1475     if (NV.Val) return NV;
1476     break;   // The target lowered this.
1477   }
1478   
1479   RTLIB::Libcall LC;
1480   if (DestTy == MVT::f32)
1481     LC = RTLIB::SINTTOFP_I64_F32;
1482   else {
1483     assert(DestTy == MVT::f64 && "Unknown fp value type!");
1484     LC = RTLIB::SINTTOFP_I64_F64;
1485   }
1486   
1487   assert(0 && "FIXME: no libcalls yet!");
1488   abort();
1489 #if 0
1490   assert(TLI.getLibcallName(LC) && "Don't know how to expand this SINT_TO_FP!");
1491   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
1492   SDOperand UnusedHiPart;
1493   return ExpandLibCall(TLI.getLibcallName(LC), Source.Val, true, UnusedHiPart);
1494 #endif
1495 }
1496
1497 SDOperand DAGTypeLegalizer::ExpandOperand_UINT_TO_FP(SDOperand Source, 
1498                                                      MVT::ValueType DestTy) {
1499   // We know the destination is legal, but that the input needs to be expanded.
1500   assert(getTypeAction(Source.getValueType()) == Expand &&
1501          "This is not an expansion!");
1502   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1503   
1504   // If this is unsigned, and not supported, first perform the conversion to
1505   // signed, then adjust the result if the sign bit is set.
1506   SDOperand SignedConv = ExpandOperand_SINT_TO_FP(Source, DestTy);
1507
1508   // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
1509   // incoming integer is set.  To handle this, we dynamically test to see if
1510   // it is set, and, if so, add a fudge factor.
1511   SDOperand Lo, Hi;
1512   GetExpandedOp(Source, Lo, Hi);
1513   
1514   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
1515                                    DAG.getConstant(0, Hi.getValueType()),
1516                                    ISD::SETLT);
1517   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
1518   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
1519                                     SignSet, Four, Zero);
1520   uint64_t FF = 0x5f800000ULL;
1521   if (TLI.isLittleEndian()) FF <<= 32;
1522   Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
1523   
1524   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
1525   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
1526   SDOperand FudgeInReg;
1527   if (DestTy == MVT::f32)
1528     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
1529   else if (MVT::getSizeInBits(DestTy) > MVT::getSizeInBits(MVT::f32))
1530     // FIXME: Avoid the extend by construction the right constantpool?
1531     FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestTy, DAG.getEntryNode(),
1532                                 CPIdx, NULL, 0, MVT::f32);
1533   else 
1534     assert(0 && "Unexpected conversion");
1535   
1536   return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
1537 }
1538
1539
1540 SDOperand DAGTypeLegalizer::ExpandOperand_EXTRACT_ELEMENT(SDNode *N) {
1541   SDOperand Lo, Hi;
1542   GetExpandedOp(N->getOperand(0), Lo, Hi);
1543   return cast<ConstantSDNode>(N->getOperand(1))->getValue() ? Hi : Lo;
1544 }
1545
1546 SDOperand DAGTypeLegalizer::ExpandOperand_SETCC(SDNode *N) {
1547   SDOperand NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
1548   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
1549   ExpandSetCCOperands(NewLHS, NewRHS, CCCode);
1550   
1551   // If ExpandSetCCOperands returned a scalar, use it.
1552   if (NewRHS.Val == 0) return NewLHS;
1553
1554   // Otherwise, update N to have the operands specified.
1555   return DAG.UpdateNodeOperands(SDOperand(N, 0), NewLHS, NewRHS,
1556                                 DAG.getCondCode(CCCode));
1557 }
1558
1559 /// ExpandSetCCOperands - Expand the operands of a comparison.  This code is
1560 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
1561 void DAGTypeLegalizer::ExpandSetCCOperands(SDOperand &NewLHS, SDOperand &NewRHS,
1562                                            ISD::CondCode &CCCode) {
1563   SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
1564   GetExpandedOp(NewLHS, LHSLo, LHSHi);
1565   GetExpandedOp(NewRHS, RHSLo, RHSHi);
1566   
1567   MVT::ValueType VT = NewLHS.getValueType();
1568   if (VT == MVT::f32 || VT == MVT::f64) {
1569     assert(0 && "FIXME: softfp not implemented yet! should be promote not exp");
1570   }
1571   
1572   if (VT == MVT::ppcf128) {
1573     // FIXME:  This generated code sucks.  We want to generate
1574     //         FCMP crN, hi1, hi2
1575     //         BNE crN, L:
1576     //         FCMP crN, lo1, lo2
1577     // The following can be improved, but not that much.
1578     SDOperand Tmp1, Tmp2, Tmp3;
1579     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
1580     Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, CCCode);
1581     Tmp3 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
1582     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETNE);
1583     Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, CCCode);
1584     Tmp1 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
1585     NewLHS = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp3);
1586     NewRHS = SDOperand();   // LHS is the result, not a compare.
1587     return;
1588   }
1589   
1590   
1591   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
1592     if (RHSLo == RHSHi)
1593       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
1594         if (RHSCST->isAllOnesValue()) {
1595           // Equality comparison to -1.
1596           NewLHS = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1597           NewRHS = RHSLo;
1598           return;
1599         }
1600           
1601     NewLHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1602     NewRHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1603     NewLHS = DAG.getNode(ISD::OR, NewLHS.getValueType(), NewLHS, NewRHS);
1604     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
1605     return;
1606   }
1607   
1608   // If this is a comparison of the sign bit, just look at the top part.
1609   // X > -1,  x < 0
1610   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
1611     if ((CCCode == ISD::SETLT && CST->getValue() == 0) ||   // X < 0
1612         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
1613       NewLHS = LHSHi;
1614       NewRHS = RHSHi;
1615       return;
1616     }
1617       
1618   // FIXME: This generated code sucks.
1619   ISD::CondCode LowCC;
1620   switch (CCCode) {
1621   default: assert(0 && "Unknown integer setcc!");
1622   case ISD::SETLT:
1623   case ISD::SETULT: LowCC = ISD::SETULT; break;
1624   case ISD::SETGT:
1625   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1626   case ISD::SETLE:
1627   case ISD::SETULE: LowCC = ISD::SETULE; break;
1628   case ISD::SETGE:
1629   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1630   }
1631   
1632   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1633   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1634   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1635   
1636   // NOTE: on targets without efficient SELECT of bools, we can always use
1637   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1638   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
1639   SDOperand Tmp1, Tmp2;
1640   Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC,
1641                            false, DagCombineInfo);
1642   if (!Tmp1.Val)
1643     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
1644   Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
1645                            CCCode, false, DagCombineInfo);
1646   if (!Tmp2.Val)
1647     Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi,
1648                        DAG.getCondCode(CCCode));
1649   
1650   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.Val);
1651   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.Val);
1652   if ((Tmp1C && Tmp1C->getValue() == 0) ||
1653       (Tmp2C && Tmp2C->getValue() == 0 &&
1654        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
1655         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
1656       (Tmp2C && Tmp2C->getValue() == 1 &&
1657        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
1658         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
1659     // low part is known false, returns high part.
1660     // For LE / GE, if high part is known false, ignore the low part.
1661     // For LT / GT, if high part is known true, ignore the low part.
1662     NewLHS = Tmp2;
1663     NewRHS = SDOperand();
1664     return;
1665   }
1666   
1667   NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
1668                              ISD::SETEQ, false, DagCombineInfo);
1669   if (!NewLHS.Val)
1670     NewLHS = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
1671   NewLHS = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1672                        NewLHS, Tmp1, Tmp2);
1673   NewRHS = SDOperand();
1674 }
1675
1676
1677 SDOperand DAGTypeLegalizer::ExpandOperand_STORE(StoreSDNode *N, unsigned OpNo) {
1678   assert(OpNo == 1 && "Can only expand the stored value so far");
1679   assert(!N->isTruncatingStore() && "Can't expand truncstore!");
1680
1681   unsigned IncrementSize = 0;
1682   SDOperand Lo, Hi;
1683   
1684   // If this is a vector type, then we have to calculate the increment as
1685   // the product of the element size in bytes, and the number of elements
1686   // in the high half of the vector.
1687   if (MVT::isVector(N->getValue().getValueType())) {
1688     assert(0 && "Vectors not supported yet");
1689 #if 0
1690     SDNode *InVal = ST->getValue().Val;
1691     unsigned NumElems = MVT::getVectorNumElements(InVal->getValueType(0));
1692     MVT::ValueType EVT = MVT::getVectorElementType(InVal->getValueType(0));
1693     
1694     // Figure out if there is a simple type corresponding to this Vector
1695     // type.  If so, convert to the vector type.
1696     MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1697     if (TLI.isTypeLegal(TVT)) {
1698       // Turn this into a normal store of the vector type.
1699       Tmp3 = LegalizeOp(Node->getOperand(1));
1700       Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1701                             SVOffset, isVolatile, Alignment);
1702       Result = LegalizeOp(Result);
1703       break;
1704     } else if (NumElems == 1) {
1705       // Turn this into a normal store of the scalar type.
1706       Tmp3 = ScalarizeVectorOp(Node->getOperand(1));
1707       Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1708                             SVOffset, isVolatile, Alignment);
1709       // The scalarized value type may not be legal, e.g. it might require
1710       // promotion or expansion.  Relegalize the scalar store.
1711       return LegalizeOp(Result);
1712     } else {
1713       SplitVectorOp(Node->getOperand(1), Lo, Hi);
1714       IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1715     }
1716 #endif
1717   } else {
1718     GetExpandedOp(N->getValue(), Lo, Hi);
1719     IncrementSize = Hi.Val ? MVT::getSizeInBits(Hi.getValueType())/8 : 0;
1720     
1721     if (!TLI.isLittleEndian())
1722       std::swap(Lo, Hi);
1723   }
1724   
1725   SDOperand Chain    = N->getChain();
1726   SDOperand Ptr      = N->getBasePtr();
1727   int SVOffset       = N->getSrcValueOffset();
1728   unsigned Alignment = N->getAlignment();
1729   bool isVolatile    = N->isVolatile();
1730   
1731   Lo = DAG.getStore(Chain, Lo, Ptr, N->getSrcValue(),
1732                     SVOffset, isVolatile, Alignment);
1733   
1734   assert(Hi.Val && "FIXME: int <-> float should be handled with promote!");
1735 #if 0
1736   if (Hi.Val == NULL) {
1737     // Must be int <-> float one-to-one expansion.
1738     return Lo;
1739   }
1740 #endif
1741   
1742   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1743                     getIntPtrConstant(IncrementSize));
1744   assert(isTypeLegal(Ptr.getValueType()) && "Pointers must be legal!");
1745   Hi = DAG.getStore(Chain, Hi, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
1746                     isVolatile, std::max(Alignment, IncrementSize));
1747   return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1748 }
1749
1750 //===----------------------------------------------------------------------===//
1751 //  Entry Point
1752 //===----------------------------------------------------------------------===//
1753
1754 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1755 /// only uses types natively supported by the target.
1756 ///
1757 /// Note that this is an involved process that may invalidate pointers into
1758 /// the graph.
1759 void SelectionDAG::LegalizeTypes() {
1760   DAGTypeLegalizer(*this).run();
1761 }
1762