rename ExpandOperation to ExpandOperationResult, as suggested
[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 = TLI.ExpandOperationResult(N, DAG);
622     if (P.first.Val) {
623       Lo = P.first;
624       Hi = P.second;
625       return;
626     }
627   }
628   
629   switch (N->getOpcode()) {
630   default:
631 #ifndef NDEBUG
632     cerr << "ExpandResult #" << ResNo << ": ";
633     N->dump(&DAG); cerr << "\n";
634 #endif
635     assert(0 && "Do not know how to expand this operator!");
636     abort();
637       
638   case ISD::UNDEF:       ExpandResult_UNDEF(N, Lo, Hi); break;
639   case ISD::Constant:    ExpandResult_Constant(N, Lo, Hi); break;
640   case ISD::BUILD_PAIR:  ExpandResult_BUILD_PAIR(N, Lo, Hi); break;
641   case ISD::ANY_EXTEND:  ExpandResult_ANY_EXTEND(N, Lo, Hi); break;
642   case ISD::ZERO_EXTEND: ExpandResult_ZERO_EXTEND(N, Lo, Hi); break;
643   case ISD::SIGN_EXTEND: ExpandResult_SIGN_EXTEND(N, Lo, Hi); break;
644   case ISD::BIT_CONVERT: ExpandResult_BIT_CONVERT(N, Lo, Hi); break;
645   case ISD::SIGN_EXTEND_INREG: ExpandResult_SIGN_EXTEND_INREG(N, Lo, Hi); break;
646   case ISD::LOAD:        ExpandResult_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
647     
648   case ISD::AND:
649   case ISD::OR:
650   case ISD::XOR:         ExpandResult_Logical(N, Lo, Hi); break;
651   case ISD::BSWAP:       ExpandResult_BSWAP(N, Lo, Hi); break;
652   case ISD::ADD:
653   case ISD::SUB:         ExpandResult_ADDSUB(N, Lo, Hi); break;
654   case ISD::ADDC:
655   case ISD::SUBC:        ExpandResult_ADDSUBC(N, Lo, Hi); break;
656   case ISD::ADDE:
657   case ISD::SUBE:        ExpandResult_ADDSUBE(N, Lo, Hi); break;
658   case ISD::SELECT:      ExpandResult_SELECT(N, Lo, Hi); break;
659   case ISD::SELECT_CC:   ExpandResult_SELECT_CC(N, Lo, Hi); break;
660   case ISD::MUL:         ExpandResult_MUL(N, Lo, Hi); break;
661   case ISD::SHL:
662   case ISD::SRA:
663   case ISD::SRL:         ExpandResult_Shift(N, Lo, Hi); break;
664
665   }
666   
667   // If Lo/Hi is null, the sub-method took care of registering results etc.
668   if (Lo.Val)
669     SetExpandedOp(SDOperand(N, ResNo), Lo, Hi);
670 }
671
672 void DAGTypeLegalizer::ExpandResult_UNDEF(SDNode *N,
673                                           SDOperand &Lo, SDOperand &Hi) {
674   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
675   Lo = Hi = DAG.getNode(ISD::UNDEF, NVT);
676 }
677
678 void DAGTypeLegalizer::ExpandResult_Constant(SDNode *N,
679                                              SDOperand &Lo, SDOperand &Hi) {
680   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
681   uint64_t Cst = cast<ConstantSDNode>(N)->getValue();
682   Lo = DAG.getConstant(Cst, NVT);
683   Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
684 }
685
686 void DAGTypeLegalizer::ExpandResult_BUILD_PAIR(SDNode *N,
687                                                SDOperand &Lo, SDOperand &Hi) {
688   // Return the operands.
689   Lo = N->getOperand(0);
690   Hi = N->getOperand(1);
691 }
692
693 void DAGTypeLegalizer::ExpandResult_ANY_EXTEND(SDNode *N, 
694                                                SDOperand &Lo, SDOperand &Hi) {
695   
696   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
697   // The low part is any extension of the input (which degenerates to a copy).
698   Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, N->getOperand(0));
699   Hi = DAG.getNode(ISD::UNDEF, NVT);   // The high part is undefined.
700 }
701
702 void DAGTypeLegalizer::ExpandResult_ZERO_EXTEND(SDNode *N,
703                                                 SDOperand &Lo, SDOperand &Hi) {
704   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
705   // The low part is zero extension of the input (which degenerates to a copy).
706   Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, N->getOperand(0));
707   Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
708 }
709
710 void DAGTypeLegalizer::ExpandResult_SIGN_EXTEND(SDNode *N,
711                                                 SDOperand &Lo, SDOperand &Hi) {
712   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
713   // The low part is sign extension of the input (which degenerates to a copy).
714   Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, N->getOperand(0));
715
716   // The high part is obtained by SRA'ing all but one of the bits of low part.
717   unsigned LoSize = MVT::getSizeInBits(NVT);
718   Hi = DAG.getNode(ISD::SRA, NVT, Lo,
719                    DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
720 }
721
722 void DAGTypeLegalizer::ExpandResult_BIT_CONVERT(SDNode *N,
723                                                 SDOperand &Lo, SDOperand &Hi) {
724   // Lower the bit-convert to a store/load from the stack, then expand the load.
725   SDOperand Op = CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
726   ExpandResult_LOAD(cast<LoadSDNode>(Op.Val), Lo, Hi);
727 }
728
729 void DAGTypeLegalizer::
730 ExpandResult_SIGN_EXTEND_INREG(SDNode *N, SDOperand &Lo, SDOperand &Hi) {
731   GetExpandedOp(N->getOperand(0), Lo, Hi);
732   
733   // sext_inreg the low part if needed.
734   Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, Lo.getValueType(), Lo,
735                    N->getOperand(1));
736   
737   // The high part gets the sign extension from the lo-part.  This handles
738   // things like sextinreg V:i64 from i8.
739   Hi = DAG.getNode(ISD::SRA, Hi.getValueType(), Lo,
740                    DAG.getConstant(MVT::getSizeInBits(Hi.getValueType())-1,
741                                    TLI.getShiftAmountTy()));
742 }
743
744
745 void DAGTypeLegalizer::ExpandResult_LOAD(LoadSDNode *N,
746                                          SDOperand &Lo, SDOperand &Hi) {
747   MVT::ValueType VT = N->getValueType(0);
748   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
749   SDOperand Ch  = N->getChain();    // Legalize the chain.
750   SDOperand Ptr = N->getBasePtr();  // Legalize the pointer.
751   ISD::LoadExtType ExtType = N->getExtensionType();
752   int SVOffset = N->getSrcValueOffset();
753   unsigned Alignment = N->getAlignment();
754   bool isVolatile = N->isVolatile();
755   
756   if (ExtType == ISD::NON_EXTLOAD) {
757     Lo = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(), SVOffset,
758                      isVolatile, Alignment);
759     // Increment the pointer to the other half.
760     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
761     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
762                       getIntPtrConstant(IncrementSize));
763     Hi = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
764                      isVolatile, std::max(Alignment, IncrementSize));
765     
766     // Build a factor node to remember that this load is independent of the
767     // other one.
768     Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
769                      Hi.getValue(1));
770
771     // Handle endianness of the load.
772     if (!TLI.isLittleEndian())
773       std::swap(Lo, Hi);
774   } else {
775     MVT::ValueType EVT = N->getLoadedVT();
776     
777     if (EVT == NVT)
778       Lo = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(),
779                        SVOffset, isVolatile, Alignment);
780     else
781       Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(),
782                           SVOffset, EVT, isVolatile,
783                           Alignment);
784     // Remember the chain.
785     Ch = Lo.getValue(1);
786     
787     if (ExtType == ISD::SEXTLOAD) {
788       // The high part is obtained by SRA'ing all but one of the bits of the
789       // lo part.
790       unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
791       Hi = DAG.getNode(ISD::SRA, NVT, Lo,
792                        DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
793     } else if (ExtType == ISD::ZEXTLOAD) {
794       // The high part is just a zero.
795       Hi = DAG.getConstant(0, NVT);
796     } else {
797       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
798       // The high part is undefined.
799       Hi = DAG.getNode(ISD::UNDEF, NVT);
800     }
801   }
802   
803   // Legalized the chain result - switch anything that used the old chain to
804   // use the new one.
805   ReplaceLegalValueWith(SDOperand(N, 1), Ch);
806 }  
807
808
809 void DAGTypeLegalizer::ExpandResult_Logical(SDNode *N,
810                                             SDOperand &Lo, SDOperand &Hi) {
811   SDOperand LL, LH, RL, RH;
812   GetExpandedOp(N->getOperand(0), LL, LH);
813   GetExpandedOp(N->getOperand(1), RL, RH);
814   Lo = DAG.getNode(N->getOpcode(), LL.getValueType(), LL, RL);
815   Hi = DAG.getNode(N->getOpcode(), LL.getValueType(), LH, RH);
816 }
817
818 void DAGTypeLegalizer::ExpandResult_BSWAP(SDNode *N,
819                                           SDOperand &Lo, SDOperand &Hi) {
820   GetExpandedOp(N->getOperand(0), Hi, Lo);  // Note swapped operands.
821   Lo = DAG.getNode(ISD::BSWAP, Lo.getValueType(), Lo);
822   Hi = DAG.getNode(ISD::BSWAP, Hi.getValueType(), Hi);
823 }
824
825
826 void DAGTypeLegalizer::ExpandResult_SELECT(SDNode *N,
827                                            SDOperand &Lo, SDOperand &Hi) {
828   SDOperand LL, LH, RL, RH;
829   GetExpandedOp(N->getOperand(1), LL, LH);
830   GetExpandedOp(N->getOperand(2), RL, RH);
831   Lo = DAG.getNode(ISD::SELECT, LL.getValueType(), N->getOperand(0), LL, RL);
832   
833   assert(N->getOperand(0).getValueType() != MVT::f32 &&
834          "FIXME: softfp shouldn't use expand!");
835   Hi = DAG.getNode(ISD::SELECT, LL.getValueType(), N->getOperand(0), LH, RH);
836 }
837
838 void DAGTypeLegalizer::ExpandResult_SELECT_CC(SDNode *N,
839                                               SDOperand &Lo, SDOperand &Hi) {
840   SDOperand LL, LH, RL, RH;
841   GetExpandedOp(N->getOperand(2), LL, LH);
842   GetExpandedOp(N->getOperand(3), RL, RH);
843   Lo = DAG.getNode(ISD::SELECT_CC, LL.getValueType(), N->getOperand(0), 
844                    N->getOperand(1), LL, RL, N->getOperand(4));
845   
846   assert(N->getOperand(0).getValueType() != MVT::f32 &&
847          "FIXME: softfp shouldn't use expand!");
848   Hi = DAG.getNode(ISD::SELECT_CC, LL.getValueType(), N->getOperand(0), 
849                    N->getOperand(1), LH, RH, N->getOperand(4));
850 }
851
852 void DAGTypeLegalizer::ExpandResult_ADDSUB(SDNode *N,
853                                            SDOperand &Lo, SDOperand &Hi) {
854   // Expand the subcomponents.
855   SDOperand LHSL, LHSH, RHSL, RHSH;
856   GetExpandedOp(N->getOperand(0), LHSL, LHSH);
857   GetExpandedOp(N->getOperand(1), RHSL, RHSH);
858   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
859   SDOperand LoOps[2] = { LHSL, RHSL };
860   SDOperand HiOps[3] = { LHSH, RHSH };
861
862   if (N->getOpcode() == ISD::ADD) {
863     Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
864     HiOps[2] = Lo.getValue(1);
865     Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
866   } else {
867     Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
868     HiOps[2] = Lo.getValue(1);
869     Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
870   }
871 }
872
873 void DAGTypeLegalizer::ExpandResult_ADDSUBC(SDNode *N,
874                                             SDOperand &Lo, SDOperand &Hi) {
875   // Expand the subcomponents.
876   SDOperand LHSL, LHSH, RHSL, RHSH;
877   GetExpandedOp(N->getOperand(0), LHSL, LHSH);
878   GetExpandedOp(N->getOperand(1), RHSL, RHSH);
879   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
880   SDOperand LoOps[2] = { LHSL, RHSL };
881   SDOperand HiOps[3] = { LHSH, RHSH };
882
883   if (N->getOpcode() == ISD::ADDC) {
884     Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
885     HiOps[2] = Lo.getValue(1);
886     Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
887   } else {
888     Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
889     HiOps[2] = Lo.getValue(1);
890     Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
891   }
892
893   // Legalized the flag result - switch anything that used the old flag to
894   // use the new one.
895   ReplaceLegalValueWith(SDOperand(N, 1), Hi.getValue(1));
896 }
897
898 void DAGTypeLegalizer::ExpandResult_ADDSUBE(SDNode *N,
899                                             SDOperand &Lo, SDOperand &Hi) {
900   // Expand the subcomponents.
901   SDOperand LHSL, LHSH, RHSL, RHSH;
902   GetExpandedOp(N->getOperand(0), LHSL, LHSH);
903   GetExpandedOp(N->getOperand(1), RHSL, RHSH);
904   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
905   SDOperand LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
906   SDOperand HiOps[3] = { LHSH, RHSH };
907
908   Lo = DAG.getNode(N->getOpcode(), VTList, LoOps, 3);
909   HiOps[2] = Lo.getValue(1);
910   Hi = DAG.getNode(N->getOpcode(), VTList, HiOps, 3);
911
912   // Legalized the flag result - switch anything that used the old flag to
913   // use the new one.
914   ReplaceLegalValueWith(SDOperand(N, 1), Hi.getValue(1));
915 }
916
917 void DAGTypeLegalizer::ExpandResult_MUL(SDNode *N,
918                                         SDOperand &Lo, SDOperand &Hi) {
919   MVT::ValueType VT = N->getValueType(0);
920   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
921   
922   bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
923   bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
924   bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
925   bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
926   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
927     SDOperand LL, LH, RL, RH;
928     GetExpandedOp(N->getOperand(0), LL, LH);
929     GetExpandedOp(N->getOperand(1), RL, RH);
930     unsigned BitSize = MVT::getSizeInBits(RH.getValueType());
931     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
932     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
933     
934     // FIXME: generalize this to handle other bit sizes
935     if (LHSSB == 32 && RHSSB == 32 &&
936         DAG.MaskedValueIsZero(N->getOperand(0), 0xFFFFFFFF00000000ULL) &&
937         DAG.MaskedValueIsZero(N->getOperand(1), 0xFFFFFFFF00000000ULL)) {
938       // The inputs are both zero-extended.
939       if (HasUMUL_LOHI) {
940         // We can emit a umul_lohi.
941         Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
942         Hi = SDOperand(Lo.Val, 1);
943         return;
944       }
945       if (HasMULHU) {
946         // We can emit a mulhu+mul.
947         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
948         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
949         return;
950       }
951     }
952     if (LHSSB > BitSize && RHSSB > BitSize) {
953       // The input values are both sign-extended.
954       if (HasSMUL_LOHI) {
955         // We can emit a smul_lohi.
956         Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
957         Hi = SDOperand(Lo.Val, 1);
958         return;
959       }
960       if (HasMULHS) {
961         // We can emit a mulhs+mul.
962         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
963         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
964         return;
965       }
966     }
967     if (HasUMUL_LOHI) {
968       // Lo,Hi = umul LHS, RHS.
969       SDOperand UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
970                                        DAG.getVTList(NVT, NVT), LL, RL);
971       Lo = UMulLOHI;
972       Hi = UMulLOHI.getValue(1);
973       RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
974       LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
975       Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
976       Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
977       return;
978     }
979   }
980   
981   abort();
982 #if 0 // FIXME!
983   // If nothing else, we can make a libcall.
984   Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::MUL_I64), N,
985                      false/*sign irrelevant*/, Hi);
986 #endif
987 }  
988
989
990 void DAGTypeLegalizer::ExpandResult_Shift(SDNode *N,
991                                           SDOperand &Lo, SDOperand &Hi) {
992   MVT::ValueType VT = N->getValueType(0);
993   
994   // If we can emit an efficient shift operation, do so now.  Check to see if 
995   // the RHS is a constant.
996   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
997     return ExpandShiftByConstant(N, CN->getValue(), Lo, Hi);
998
999   // If we can determine that the high bit of the shift is zero or one, even if
1000   // the low bits are variable, emit this shift in an optimized form.
1001   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
1002     return;
1003   
1004   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
1005   unsigned PartsOpc;
1006   if (N->getOpcode() == ISD::SHL)
1007     PartsOpc = ISD::SHL_PARTS;
1008   else if (N->getOpcode() == ISD::SRL)
1009     PartsOpc = ISD::SRL_PARTS;
1010   else {
1011     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1012     PartsOpc = ISD::SRA_PARTS;
1013   }
1014   
1015   // Next check to see if the target supports this SHL_PARTS operation or if it
1016   // will custom expand it.
1017   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1018   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
1019   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
1020       Action == TargetLowering::Custom) {
1021     // Expand the subcomponents.
1022     SDOperand LHSL, LHSH;
1023     GetExpandedOp(N->getOperand(0), LHSL, LHSH);
1024     
1025     SDOperand Ops[] = { LHSL, LHSH, N->getOperand(1) };
1026     MVT::ValueType VT = LHSL.getValueType();
1027     Lo = DAG.getNode(PartsOpc, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
1028     Hi = Lo.getValue(1);
1029     return;
1030   }
1031   
1032   abort();
1033 #if 0 // FIXME!
1034   // Otherwise, emit a libcall.
1035   unsigned RuntimeCode = ; // SRL -> SRL_I64 etc.
1036   bool Signed = ;
1037   Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRL_I64), N,
1038                      false/*lshr is unsigned*/, Hi);
1039 #endif
1040 }  
1041
1042
1043 /// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1044 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1045 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt, 
1046                                              SDOperand &Lo, SDOperand &Hi) {
1047   // Expand the incoming operand to be shifted, so that we have its parts
1048   SDOperand InL, InH;
1049   GetExpandedOp(N->getOperand(0), InL, InH);
1050   
1051   MVT::ValueType NVT = InL.getValueType();
1052   unsigned VTBits = MVT::getSizeInBits(N->getValueType(0));
1053   unsigned NVTBits = MVT::getSizeInBits(NVT);
1054   MVT::ValueType ShTy = N->getOperand(1).getValueType();
1055
1056   if (N->getOpcode() == ISD::SHL) {
1057     if (Amt > VTBits) {
1058       Lo = Hi = DAG.getConstant(0, NVT);
1059     } else if (Amt > NVTBits) {
1060       Lo = DAG.getConstant(0, NVT);
1061       Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt-NVTBits,ShTy));
1062     } else if (Amt == NVTBits) {
1063       Lo = DAG.getConstant(0, NVT);
1064       Hi = InL;
1065     } else {
1066       Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt, ShTy));
1067       Hi = DAG.getNode(ISD::OR, NVT,
1068                        DAG.getNode(ISD::SHL, NVT, InH,
1069                                    DAG.getConstant(Amt, ShTy)),
1070                        DAG.getNode(ISD::SRL, NVT, InL,
1071                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1072     }
1073     return;
1074   }
1075   
1076   if (N->getOpcode() == ISD::SRL) {
1077     if (Amt > VTBits) {
1078       Lo = DAG.getConstant(0, NVT);
1079       Hi = DAG.getConstant(0, NVT);
1080     } else if (Amt > NVTBits) {
1081       Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1082       Hi = DAG.getConstant(0, NVT);
1083     } else if (Amt == NVTBits) {
1084       Lo = InH;
1085       Hi = DAG.getConstant(0, NVT);
1086     } else {
1087       Lo = DAG.getNode(ISD::OR, NVT,
1088                        DAG.getNode(ISD::SRL, NVT, InL,
1089                                    DAG.getConstant(Amt, ShTy)),
1090                        DAG.getNode(ISD::SHL, NVT, InH,
1091                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1092       Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt, ShTy));
1093     }
1094     return;
1095   }
1096   
1097   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1098   if (Amt > VTBits) {
1099     Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
1100                           DAG.getConstant(NVTBits-1, ShTy));
1101   } else if (Amt > NVTBits) {
1102     Lo = DAG.getNode(ISD::SRA, NVT, InH,
1103                      DAG.getConstant(Amt-NVTBits, ShTy));
1104     Hi = DAG.getNode(ISD::SRA, NVT, InH,
1105                      DAG.getConstant(NVTBits-1, ShTy));
1106   } else if (Amt == NVTBits) {
1107     Lo = InH;
1108     Hi = DAG.getNode(ISD::SRA, NVT, InH,
1109                      DAG.getConstant(NVTBits-1, ShTy));
1110   } else {
1111     Lo = DAG.getNode(ISD::OR, NVT,
1112                      DAG.getNode(ISD::SRL, NVT, InL,
1113                                  DAG.getConstant(Amt, ShTy)),
1114                      DAG.getNode(ISD::SHL, NVT, InH,
1115                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1116     Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Amt, ShTy));
1117   }
1118 }
1119
1120 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1121 /// this shift based on knowledge of the high bit of the shift amount.  If we
1122 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1123 /// shift amount.
1124 bool DAGTypeLegalizer::
1125 ExpandShiftWithKnownAmountBit(SDNode *N, SDOperand &Lo, SDOperand &Hi) {
1126   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1127   unsigned NVTBits = MVT::getSizeInBits(NVT);
1128
1129   uint64_t HighBitMask = NVTBits, KnownZero, KnownOne;
1130   DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1131   
1132   // If we don't know anything about the high bit, exit.
1133   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1134     return false;
1135
1136   // Get the incoming operand to be shifted.
1137   SDOperand InL, InH;
1138   GetExpandedOp(N->getOperand(0), InL, InH);
1139   SDOperand Amt = N->getOperand(1);
1140
1141   // If we know that the high bit of the shift amount is one, then we can do
1142   // this as a couple of simple shifts.
1143   if (KnownOne & HighBitMask) {
1144     // Mask out the high bit, which we know is set.
1145     Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
1146                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
1147     
1148     switch (N->getOpcode()) {
1149     default: assert(0 && "Unknown shift");
1150     case ISD::SHL:
1151       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1152       Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
1153       return true;
1154     case ISD::SRL:
1155       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1156       Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
1157       return true;
1158     case ISD::SRA:
1159       Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
1160                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
1161       Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
1162       return true;
1163     }
1164   }
1165   
1166   // If we know that the high bit of the shift amount is zero, then we can do
1167   // this as a couple of simple shifts.
1168   assert((KnownZero & HighBitMask) && "Bad mask computation above");
1169
1170   // Compute 32-amt.
1171   SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
1172                                DAG.getConstant(NVTBits, Amt.getValueType()),
1173                                Amt);
1174   unsigned Op1, Op2;
1175   switch (N->getOpcode()) {
1176   default: assert(0 && "Unknown shift");
1177   case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1178   case ISD::SRL:
1179   case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1180   }
1181     
1182   Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1183   Hi = DAG.getNode(ISD::OR, NVT,
1184                    DAG.getNode(Op1, NVT, InH, Amt),
1185                    DAG.getNode(Op2, NVT, InL, Amt2));
1186   return true;
1187 }
1188
1189 //===----------------------------------------------------------------------===//
1190 //  Operand Promotion
1191 //===----------------------------------------------------------------------===//
1192
1193 /// PromoteOperand - This method is called when the specified operand of the
1194 /// specified node is found to need promotion.  At this point, all of the result
1195 /// types of the node are known to be legal, but other operands of the node may
1196 /// need promotion or expansion as well as the specified one.
1197 bool DAGTypeLegalizer::PromoteOperand(SDNode *N, unsigned OpNo) {
1198   DEBUG(cerr << "Promote node operand: "; N->dump(&DAG); cerr << "\n");
1199   SDOperand Res;
1200   switch (N->getOpcode()) {
1201     default:
1202 #ifndef NDEBUG
1203     cerr << "PromoteOperand Op #" << OpNo << ": ";
1204     N->dump(&DAG); cerr << "\n";
1205 #endif
1206     assert(0 && "Do not know how to promote this operator's operand!");
1207     abort();
1208     
1209   case ISD::ANY_EXTEND:  Res = PromoteOperand_ANY_EXTEND(N); break;
1210   case ISD::ZERO_EXTEND: Res = PromoteOperand_ZERO_EXTEND(N); break;
1211   case ISD::SIGN_EXTEND: Res = PromoteOperand_SIGN_EXTEND(N); break;
1212   case ISD::FP_EXTEND:   Res = PromoteOperand_FP_EXTEND(N); break;
1213   case ISD::FP_ROUND:    Res = PromoteOperand_FP_ROUND(N); break;
1214     
1215   case ISD::SELECT:      Res = PromoteOperand_SELECT(N, OpNo); break;
1216   case ISD::BRCOND:      Res = PromoteOperand_BRCOND(N, OpNo); break;
1217   case ISD::BR_CC:       Res = PromoteOperand_BR_CC(N, OpNo); break;
1218
1219   case ISD::STORE:       Res = PromoteOperand_STORE(cast<StoreSDNode>(N),
1220                                                     OpNo); break;
1221   }
1222   
1223   // If the result is null, the sub-method took care of registering results etc.
1224   if (!Res.Val) return false;
1225   // If the result is N, the sub-method updated N in place.
1226   if (Res.Val == N) {
1227     // Mark N as new and remark N and its operands.  This allows us to correctly
1228     // revisit N if it needs another step of promotion and allows us to visit
1229     // any new operands to N.
1230     N->setNodeId(NewNode);
1231     MarkNewNodes(N);
1232     return true;
1233   }
1234   
1235   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1236          "Invalid operand expansion");
1237   
1238   ReplaceLegalValueWith(SDOperand(N, 0), Res);
1239   return false;
1240 }
1241
1242 SDOperand DAGTypeLegalizer::PromoteOperand_ANY_EXTEND(SDNode *N) {
1243   SDOperand Op = GetPromotedOp(N->getOperand(0));
1244   return DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1245 }
1246
1247 SDOperand DAGTypeLegalizer::PromoteOperand_ZERO_EXTEND(SDNode *N) {
1248   SDOperand Op = GetPromotedOp(N->getOperand(0));
1249   Op = DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1250   return DAG.getZeroExtendInReg(Op, N->getOperand(0).getValueType());
1251 }
1252
1253 SDOperand DAGTypeLegalizer::PromoteOperand_SIGN_EXTEND(SDNode *N) {
1254   SDOperand Op = GetPromotedOp(N->getOperand(0));
1255   Op = DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1256   return DAG.getNode(ISD::SIGN_EXTEND_INREG, Op.getValueType(),
1257                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
1258 }
1259
1260 SDOperand DAGTypeLegalizer::PromoteOperand_FP_EXTEND(SDNode *N) {
1261   SDOperand Op = GetPromotedOp(N->getOperand(0));
1262   return DAG.getNode(ISD::FP_EXTEND, N->getValueType(0), Op);
1263 }
1264 SDOperand DAGTypeLegalizer::PromoteOperand_FP_ROUND(SDNode *N) {
1265   SDOperand Op = GetPromotedOp(N->getOperand(0));
1266   return DAG.getNode(ISD::FP_ROUND, N->getValueType(0), Op);
1267 }
1268
1269
1270 SDOperand DAGTypeLegalizer::PromoteOperand_SELECT(SDNode *N, unsigned OpNo) {
1271   assert(OpNo == 0 && "Only know how to promote condition");
1272   SDOperand Cond = GetPromotedOp(N->getOperand(0));  // Promote the condition.
1273
1274   // The top bits of the promoted condition are not necessarily zero, ensure
1275   // that the value is properly zero extended.
1276   if (!DAG.MaskedValueIsZero(Cond, 
1277                              MVT::getIntVTBitMask(Cond.getValueType())^1)) {
1278     Cond = DAG.getZeroExtendInReg(Cond, MVT::i1);
1279     MarkNewNodes(Cond.Val); 
1280   }
1281
1282   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1283   return DAG.UpdateNodeOperands(SDOperand(N, 0), Cond, N->getOperand(1),
1284                                 N->getOperand(2));
1285 }
1286
1287
1288 SDOperand DAGTypeLegalizer::PromoteOperand_BRCOND(SDNode *N, unsigned OpNo) {
1289   assert(OpNo == 1 && "only know how to promote condition");
1290   SDOperand Cond = GetPromotedOp(N->getOperand(1));  // Promote the condition.
1291   
1292   // The top bits of the promoted condition are not necessarily zero, ensure
1293   // that the value is properly zero extended.
1294   if (!DAG.MaskedValueIsZero(Cond, 
1295                              MVT::getIntVTBitMask(Cond.getValueType())^1)) {
1296     Cond = DAG.getZeroExtendInReg(Cond, MVT::i1);
1297     MarkNewNodes(Cond.Val); 
1298   }
1299   
1300   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1301   return DAG.UpdateNodeOperands(SDOperand(N, 0), N->getOperand(0), Cond,
1302                                 N->getOperand(2));
1303 }
1304
1305 SDOperand DAGTypeLegalizer::PromoteOperand_BR_CC(SDNode *N, unsigned OpNo) {
1306   assert(OpNo == 2 && "Don't know how to promote this operand");
1307   
1308   SDOperand LHS = N->getOperand(2);
1309   SDOperand RHS = N->getOperand(3);
1310   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
1311   
1312   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
1313   // legal types.
1314   return DAG.UpdateNodeOperands(SDOperand(N, 0), N->getOperand(0),
1315                                 N->getOperand(1), LHS, RHS, N->getOperand(4));
1316 }
1317
1318 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
1319 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
1320 void DAGTypeLegalizer::PromoteSetCCOperands(SDOperand &NewLHS,SDOperand &NewRHS,
1321                                             ISD::CondCode CCCode) {
1322   MVT::ValueType VT = NewLHS.getValueType();
1323   
1324   // Get the promoted values.
1325   NewLHS = GetPromotedOp(NewLHS);
1326   NewRHS = GetPromotedOp(NewRHS);
1327   
1328   // If this is an FP compare, the operands have already been extended.
1329   if (!MVT::isInteger(NewLHS.getValueType()))
1330     return;
1331   
1332   // Otherwise, we have to insert explicit sign or zero extends.  Note
1333   // that we could insert sign extends for ALL conditions, but zero extend
1334   // is cheaper on many machines (an AND instead of two shifts), so prefer
1335   // it.
1336   switch (CCCode) {
1337   default: assert(0 && "Unknown integer comparison!");
1338   case ISD::SETEQ:
1339   case ISD::SETNE:
1340   case ISD::SETUGE:
1341   case ISD::SETUGT:
1342   case ISD::SETULE:
1343   case ISD::SETULT:
1344     // ALL of these operations will work if we either sign or zero extend
1345     // the operands (including the unsigned comparisons!).  Zero extend is
1346     // usually a simpler/cheaper operation, so prefer it.
1347     NewLHS = DAG.getZeroExtendInReg(NewLHS, VT);
1348     NewRHS = DAG.getZeroExtendInReg(NewRHS, VT);
1349     return;
1350   case ISD::SETGE:
1351   case ISD::SETGT:
1352   case ISD::SETLT:
1353   case ISD::SETLE:
1354     NewLHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, NewLHS.getValueType(), NewLHS,
1355                          DAG.getValueType(VT));
1356     NewRHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, NewRHS.getValueType(), NewRHS,
1357                          DAG.getValueType(VT));
1358     return;
1359   }
1360 }
1361   
1362
1363 SDOperand DAGTypeLegalizer::PromoteOperand_STORE(StoreSDNode *N, unsigned OpNo){
1364   SDOperand Ch = N->getChain(), Ptr = N->getBasePtr();
1365   int SVOffset = N->getSrcValueOffset();
1366   unsigned Alignment = N->getAlignment();
1367   bool isVolatile = N->isVolatile();
1368   
1369   SDOperand Val = GetPromotedOp(N->getValue());  // Get promoted value.
1370
1371   assert(!N->isTruncatingStore() && "Cannot promote this store operand!");
1372   
1373   // Truncate the value and store the result.
1374   return DAG.getTruncStore(Ch, Val, Ptr, N->getSrcValue(),
1375                            SVOffset, N->getStoredVT(),
1376                            isVolatile, Alignment);
1377 }
1378
1379
1380 //===----------------------------------------------------------------------===//
1381 //  Operand Expansion
1382 //===----------------------------------------------------------------------===//
1383
1384 /// ExpandOperand - This method is called when the specified operand of the
1385 /// specified node is found to need expansion.  At this point, all of the result
1386 /// types of the node are known to be legal, but other operands of the node may
1387 /// need promotion or expansion as well as the specified one.
1388 bool DAGTypeLegalizer::ExpandOperand(SDNode *N, unsigned OpNo) {
1389   DEBUG(cerr << "Expand node operand: "; N->dump(&DAG); cerr << "\n");
1390   SDOperand Res;
1391   switch (N->getOpcode()) {
1392   default:
1393 #ifndef NDEBUG
1394     cerr << "ExpandOperand Op #" << OpNo << ": ";
1395     N->dump(&DAG); cerr << "\n";
1396 #endif
1397     assert(0 && "Do not know how to expand this operator's operand!");
1398     abort();
1399     
1400   case ISD::TRUNCATE:        Res = ExpandOperand_TRUNCATE(N); break;
1401   case ISD::BIT_CONVERT:     Res = ExpandOperand_BIT_CONVERT(N); break;
1402
1403   case ISD::SINT_TO_FP:
1404     Res = ExpandOperand_SINT_TO_FP(N->getOperand(0), N->getValueType(0));
1405     break;
1406   case ISD::UINT_TO_FP:
1407     Res = ExpandOperand_UINT_TO_FP(N->getOperand(0), N->getValueType(0)); 
1408     break;
1409   case ISD::EXTRACT_ELEMENT: Res = ExpandOperand_EXTRACT_ELEMENT(N); break;
1410   case ISD::SETCC:           Res = ExpandOperand_SETCC(N); break;
1411
1412   case ISD::STORE: Res = ExpandOperand_STORE(cast<StoreSDNode>(N), OpNo); break;
1413   }
1414   
1415   // If the result is null, the sub-method took care of registering results etc.
1416   if (!Res.Val) return false;
1417   // If the result is N, the sub-method updated N in place.  Check to see if any
1418   // operands are new, and if so, mark them.
1419   if (Res.Val == N) {
1420     // Mark N as new and remark N and its operands.  This allows us to correctly
1421     // revisit N if it needs another step of promotion and allows us to visit
1422     // any new operands to N.
1423     N->setNodeId(NewNode);
1424     MarkNewNodes(N);
1425     return true;
1426   }
1427
1428   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1429          "Invalid operand expansion");
1430   
1431   ReplaceLegalValueWith(SDOperand(N, 0), Res);
1432   return false;
1433 }
1434
1435 SDOperand DAGTypeLegalizer::ExpandOperand_TRUNCATE(SDNode *N) {
1436   SDOperand InL, InH;
1437   GetExpandedOp(N->getOperand(0), InL, InH);
1438   // Just truncate the low part of the source.
1439   return DAG.getNode(ISD::TRUNCATE, N->getValueType(0), InL);
1440 }
1441
1442 SDOperand DAGTypeLegalizer::ExpandOperand_BIT_CONVERT(SDNode *N) {
1443   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
1444 }
1445
1446 SDOperand DAGTypeLegalizer::ExpandOperand_SINT_TO_FP(SDOperand Source, 
1447                                                      MVT::ValueType DestTy) {
1448   // We know the destination is legal, but that the input needs to be expanded.
1449   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1450   
1451   // Check to see if the target has a custom way to lower this.  If so, use it.
1452   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
1453   default: assert(0 && "This action not implemented for this operation!");
1454   case TargetLowering::Legal:
1455   case TargetLowering::Expand:
1456     break;   // This case is handled below.
1457   case TargetLowering::Custom:
1458     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
1459                                                   Source), DAG);
1460     if (NV.Val) return NV;
1461     break;   // The target lowered this.
1462   }
1463   
1464   RTLIB::Libcall LC;
1465   if (DestTy == MVT::f32)
1466     LC = RTLIB::SINTTOFP_I64_F32;
1467   else {
1468     assert(DestTy == MVT::f64 && "Unknown fp value type!");
1469     LC = RTLIB::SINTTOFP_I64_F64;
1470   }
1471   
1472   assert(0 && "FIXME: no libcalls yet!");
1473   abort();
1474 #if 0
1475   assert(TLI.getLibcallName(LC) && "Don't know how to expand this SINT_TO_FP!");
1476   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
1477   SDOperand UnusedHiPart;
1478   return ExpandLibCall(TLI.getLibcallName(LC), Source.Val, true, UnusedHiPart);
1479 #endif
1480 }
1481
1482 SDOperand DAGTypeLegalizer::ExpandOperand_UINT_TO_FP(SDOperand Source, 
1483                                                      MVT::ValueType DestTy) {
1484   // We know the destination is legal, but that the input needs to be expanded.
1485   assert(getTypeAction(Source.getValueType()) == Expand &&
1486          "This is not an expansion!");
1487   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1488   
1489   // If this is unsigned, and not supported, first perform the conversion to
1490   // signed, then adjust the result if the sign bit is set.
1491   SDOperand SignedConv = ExpandOperand_SINT_TO_FP(Source, DestTy);
1492
1493   // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
1494   // incoming integer is set.  To handle this, we dynamically test to see if
1495   // it is set, and, if so, add a fudge factor.
1496   SDOperand Lo, Hi;
1497   GetExpandedOp(Source, Lo, Hi);
1498   
1499   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
1500                                    DAG.getConstant(0, Hi.getValueType()),
1501                                    ISD::SETLT);
1502   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
1503   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
1504                                     SignSet, Four, Zero);
1505   uint64_t FF = 0x5f800000ULL;
1506   if (TLI.isLittleEndian()) FF <<= 32;
1507   Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
1508   
1509   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
1510   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
1511   SDOperand FudgeInReg;
1512   if (DestTy == MVT::f32)
1513     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
1514   else if (MVT::getSizeInBits(DestTy) > MVT::getSizeInBits(MVT::f32))
1515     // FIXME: Avoid the extend by construction the right constantpool?
1516     FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestTy, DAG.getEntryNode(),
1517                                 CPIdx, NULL, 0, MVT::f32);
1518   else 
1519     assert(0 && "Unexpected conversion");
1520   
1521   return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
1522 }
1523
1524
1525 SDOperand DAGTypeLegalizer::ExpandOperand_EXTRACT_ELEMENT(SDNode *N) {
1526   SDOperand Lo, Hi;
1527   GetExpandedOp(N->getOperand(0), Lo, Hi);
1528   return cast<ConstantSDNode>(N->getOperand(1))->getValue() ? Hi : Lo;
1529 }
1530
1531 SDOperand DAGTypeLegalizer::ExpandOperand_SETCC(SDNode *N) {
1532   SDOperand NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
1533   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
1534   ExpandSetCCOperands(NewLHS, NewRHS, CCCode);
1535   
1536   // If ExpandSetCCOperands returned a scalar, use it.
1537   if (NewRHS.Val == 0) return NewLHS;
1538
1539   // Otherwise, update N to have the operands specified.
1540   return DAG.UpdateNodeOperands(SDOperand(N, 0), NewLHS, NewRHS,
1541                                 DAG.getCondCode(CCCode));
1542 }
1543
1544 /// ExpandSetCCOperands - Expand the operands of a comparison.  This code is
1545 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
1546 void DAGTypeLegalizer::ExpandSetCCOperands(SDOperand &NewLHS, SDOperand &NewRHS,
1547                                            ISD::CondCode &CCCode) {
1548   SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
1549   GetExpandedOp(NewLHS, LHSLo, LHSHi);
1550   GetExpandedOp(NewRHS, RHSLo, RHSHi);
1551   
1552   MVT::ValueType VT = NewLHS.getValueType();
1553   if (VT == MVT::f32 || VT == MVT::f64) {
1554     assert(0 && "FIXME: softfp not implemented yet! should be promote not exp");
1555   }
1556   
1557   if (VT == MVT::ppcf128) {
1558     // FIXME:  This generated code sucks.  We want to generate
1559     //         FCMP crN, hi1, hi2
1560     //         BNE crN, L:
1561     //         FCMP crN, lo1, lo2
1562     // The following can be improved, but not that much.
1563     SDOperand Tmp1, Tmp2, Tmp3;
1564     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
1565     Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, CCCode);
1566     Tmp3 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
1567     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETNE);
1568     Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, CCCode);
1569     Tmp1 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
1570     NewLHS = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp3);
1571     NewRHS = SDOperand();   // LHS is the result, not a compare.
1572     return;
1573   }
1574   
1575   
1576   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
1577     if (RHSLo == RHSHi)
1578       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
1579         if (RHSCST->isAllOnesValue()) {
1580           // Equality comparison to -1.
1581           NewLHS = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1582           NewRHS = RHSLo;
1583           return;
1584         }
1585           
1586     NewLHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1587     NewRHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1588     NewLHS = DAG.getNode(ISD::OR, NewLHS.getValueType(), NewLHS, NewRHS);
1589     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
1590     return;
1591   }
1592   
1593   // If this is a comparison of the sign bit, just look at the top part.
1594   // X > -1,  x < 0
1595   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
1596     if ((CCCode == ISD::SETLT && CST->getValue() == 0) ||   // X < 0
1597         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
1598       NewLHS = LHSHi;
1599       NewRHS = RHSHi;
1600       return;
1601     }
1602       
1603   // FIXME: This generated code sucks.
1604   ISD::CondCode LowCC;
1605   switch (CCCode) {
1606   default: assert(0 && "Unknown integer setcc!");
1607   case ISD::SETLT:
1608   case ISD::SETULT: LowCC = ISD::SETULT; break;
1609   case ISD::SETGT:
1610   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1611   case ISD::SETLE:
1612   case ISD::SETULE: LowCC = ISD::SETULE; break;
1613   case ISD::SETGE:
1614   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1615   }
1616   
1617   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1618   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1619   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1620   
1621   // NOTE: on targets without efficient SELECT of bools, we can always use
1622   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1623   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
1624   SDOperand Tmp1, Tmp2;
1625   Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC,
1626                            false, DagCombineInfo);
1627   if (!Tmp1.Val)
1628     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
1629   Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
1630                            CCCode, false, DagCombineInfo);
1631   if (!Tmp2.Val)
1632     Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi,
1633                        DAG.getCondCode(CCCode));
1634   
1635   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.Val);
1636   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.Val);
1637   if ((Tmp1C && Tmp1C->getValue() == 0) ||
1638       (Tmp2C && Tmp2C->getValue() == 0 &&
1639        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
1640         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
1641       (Tmp2C && Tmp2C->getValue() == 1 &&
1642        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
1643         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
1644     // low part is known false, returns high part.
1645     // For LE / GE, if high part is known false, ignore the low part.
1646     // For LT / GT, if high part is known true, ignore the low part.
1647     NewLHS = Tmp2;
1648     NewRHS = SDOperand();
1649     return;
1650   }
1651   
1652   NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
1653                              ISD::SETEQ, false, DagCombineInfo);
1654   if (!NewLHS.Val)
1655     NewLHS = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
1656   NewLHS = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1657                        NewLHS, Tmp1, Tmp2);
1658   NewRHS = SDOperand();
1659 }
1660
1661
1662 SDOperand DAGTypeLegalizer::ExpandOperand_STORE(StoreSDNode *N, unsigned OpNo) {
1663   assert(OpNo == 1 && "Can only expand the stored value so far");
1664   assert(!N->isTruncatingStore() && "Can't expand truncstore!");
1665
1666   unsigned IncrementSize = 0;
1667   SDOperand Lo, Hi;
1668   
1669   // If this is a vector type, then we have to calculate the increment as
1670   // the product of the element size in bytes, and the number of elements
1671   // in the high half of the vector.
1672   if (MVT::isVector(N->getValue().getValueType())) {
1673     assert(0 && "Vectors not supported yet");
1674 #if 0
1675     SDNode *InVal = ST->getValue().Val;
1676     unsigned NumElems = MVT::getVectorNumElements(InVal->getValueType(0));
1677     MVT::ValueType EVT = MVT::getVectorElementType(InVal->getValueType(0));
1678     
1679     // Figure out if there is a simple type corresponding to this Vector
1680     // type.  If so, convert to the vector type.
1681     MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1682     if (TLI.isTypeLegal(TVT)) {
1683       // Turn this into a normal store of the vector type.
1684       Tmp3 = LegalizeOp(Node->getOperand(1));
1685       Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1686                             SVOffset, isVolatile, Alignment);
1687       Result = LegalizeOp(Result);
1688       break;
1689     } else if (NumElems == 1) {
1690       // Turn this into a normal store of the scalar type.
1691       Tmp3 = ScalarizeVectorOp(Node->getOperand(1));
1692       Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1693                             SVOffset, isVolatile, Alignment);
1694       // The scalarized value type may not be legal, e.g. it might require
1695       // promotion or expansion.  Relegalize the scalar store.
1696       return LegalizeOp(Result);
1697     } else {
1698       SplitVectorOp(Node->getOperand(1), Lo, Hi);
1699       IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1700     }
1701 #endif
1702   } else {
1703     GetExpandedOp(N->getValue(), Lo, Hi);
1704     IncrementSize = Hi.Val ? MVT::getSizeInBits(Hi.getValueType())/8 : 0;
1705     
1706     if (!TLI.isLittleEndian())
1707       std::swap(Lo, Hi);
1708   }
1709   
1710   SDOperand Chain    = N->getChain();
1711   SDOperand Ptr      = N->getBasePtr();
1712   int SVOffset       = N->getSrcValueOffset();
1713   unsigned Alignment = N->getAlignment();
1714   bool isVolatile    = N->isVolatile();
1715   
1716   Lo = DAG.getStore(Chain, Lo, Ptr, N->getSrcValue(),
1717                     SVOffset, isVolatile, Alignment);
1718   
1719   assert(Hi.Val && "FIXME: int <-> float should be handled with promote!");
1720 #if 0
1721   if (Hi.Val == NULL) {
1722     // Must be int <-> float one-to-one expansion.
1723     return Lo;
1724   }
1725 #endif
1726   
1727   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1728                     getIntPtrConstant(IncrementSize));
1729   assert(isTypeLegal(Ptr.getValueType()) && "Pointers must be legal!");
1730   Hi = DAG.getStore(Chain, Hi, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
1731                     isVolatile, std::max(Alignment, IncrementSize));
1732   return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1733 }
1734
1735 //===----------------------------------------------------------------------===//
1736 //  Entry Point
1737 //===----------------------------------------------------------------------===//
1738
1739 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1740 /// only uses types natively supported by the target.
1741 ///
1742 /// Note that this is an involved process that may invalidate pointers into
1743 /// the graph.
1744 void SelectionDAG::LegalizeTypes() {
1745   DAGTypeLegalizer(*this).run();
1746 }
1747