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