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