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