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