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