Make sure the alignment of the temporary created
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeTypes.cpp
1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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.  This
12 // is common code shared among the LegalizeTypes*.cpp files.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "LegalizeTypes.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Target/TargetData.h"
20 using namespace llvm;
21
22 #ifndef NDEBUG
23 static cl::opt<bool>
24 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
25                 cl::desc("Pop up a window to show dags before legalize types"));
26 #else
27 static const bool ViewLegalizeTypesDAGs = 0;
28 #endif
29
30
31
32 /// run - This is the main entry point for the type legalizer.  This does a
33 /// top-down traversal of the dag, legalizing types as it goes.
34 void DAGTypeLegalizer::run() {
35   // Create a dummy node (which is not added to allnodes), that adds a reference
36   // to the root node, preventing it from being deleted, and tracking any
37   // changes of the root.
38   HandleSDNode Dummy(DAG.getRoot());
39
40   // The root of the dag may dangle to deleted nodes until the type legalizer is
41   // done.  Set it to null to avoid confusion.
42   DAG.setRoot(SDOperand());
43
44   // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
45   // (and remembering them) if they are leaves and assigning 'NewNode' if
46   // non-leaves.
47   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
48        E = DAG.allnodes_end(); I != E; ++I) {
49     if (I->getNumOperands() == 0) {
50       I->setNodeId(ReadyToProcess);
51       Worklist.push_back(I);
52     } else {
53       I->setNodeId(NewNode);
54     }
55   }
56
57   // Now that we have a set of nodes to process, handle them all.
58   while (!Worklist.empty()) {
59     SDNode *N = Worklist.back();
60     Worklist.pop_back();
61     assert(N->getNodeId() == ReadyToProcess &&
62            "Node should be ready if on worklist!");
63
64     // Scan the values produced by the node, checking to see if any result
65     // types are illegal.
66     unsigned i = 0;
67     unsigned NumResults = N->getNumValues();
68     do {
69       MVT ResultVT = N->getValueType(i);
70       switch (getTypeAction(ResultVT)) {
71       default:
72         assert(false && "Unknown action!");
73       case Legal:
74         break;
75       case PromoteInteger:
76         PromoteIntegerResult(N, i);
77         goto NodeDone;
78       case ExpandInteger:
79         ExpandIntegerResult(N, i);
80         goto NodeDone;
81       case SoftenFloat:
82         SoftenFloatResult(N, i);
83         goto NodeDone;
84       case ExpandFloat:
85         ExpandFloatResult(N, i);
86         goto NodeDone;
87       case ScalarizeVector:
88         ScalarizeVectorResult(N, i);
89         goto NodeDone;
90       case SplitVector:
91         SplitVectorResult(N, i);
92         goto NodeDone;
93       }
94     } while (++i < NumResults);
95
96     // Scan the operand list for the node, handling any nodes with operands that
97     // are illegal.
98     {
99     unsigned NumOperands = N->getNumOperands();
100     bool NeedsRevisit = false;
101     for (i = 0; i != NumOperands; ++i) {
102       MVT OpVT = N->getOperand(i).getValueType();
103       switch (getTypeAction(OpVT)) {
104       default:
105         assert(false && "Unknown action!");
106       case Legal:
107         continue;
108       case PromoteInteger:
109         NeedsRevisit = PromoteIntegerOperand(N, i);
110         break;
111       case ExpandInteger:
112         NeedsRevisit = ExpandIntegerOperand(N, i);
113         break;
114       case SoftenFloat:
115         NeedsRevisit = SoftenFloatOperand(N, i);
116         break;
117       case ExpandFloat:
118         NeedsRevisit = ExpandFloatOperand(N, i);
119         break;
120       case ScalarizeVector:
121         NeedsRevisit = ScalarizeVectorOperand(N, i);
122         break;
123       case SplitVector:
124         NeedsRevisit = SplitVectorOperand(N, i);
125         break;
126       }
127       break;
128     }
129
130     // If the node needs revisiting, don't add all users to the worklist etc.
131     if (NeedsRevisit)
132       continue;
133
134     if (i == NumOperands)
135       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
136     }
137 NodeDone:
138
139     // If we reach here, the node was processed, potentially creating new nodes.
140     // Mark it as processed and add its users to the worklist as appropriate.
141     N->setNodeId(Processed);
142
143     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
144          UI != E; ++UI) {
145       SDNode *User = UI->getUser();
146       int NodeID = User->getNodeId();
147       assert(NodeID != ReadyToProcess && NodeID != Processed &&
148              "Invalid node id for user of unprocessed node!");
149
150       // This node has two options: it can either be a new node or its Node ID
151       // may be a count of the number of operands it has that are not ready.
152       if (NodeID > 0) {
153         User->setNodeId(NodeID-1);
154
155         // If this was the last use it was waiting on, add it to the ready list.
156         if (NodeID-1 == ReadyToProcess)
157           Worklist.push_back(User);
158         continue;
159       }
160
161       // Otherwise, this node is new: this is the first operand of it that
162       // became ready.  Its new NodeID is the number of operands it has minus 1
163       // (as this node is now processed).
164       assert(NodeID == NewNode && "Unknown node ID!");
165       User->setNodeId(User->getNumOperands()-1);
166
167       // If the node only has a single operand, it is now ready.
168       if (User->getNumOperands() == 1)
169         Worklist.push_back(User);
170     }
171   }
172
173   // If the root changed (e.g. it was a dead load, update the root).
174   DAG.setRoot(Dummy.getValue());
175
176   //DAG.viewGraph();
177
178   // Remove dead nodes.  This is important to do for cleanliness but also before
179   // the checking loop below.  Implicit folding by the DAG.getNode operators can
180   // cause unreachable nodes to be around with their flags set to new.
181   DAG.RemoveDeadNodes();
182
183   // In a debug build, scan all the nodes to make sure we found them all.  This
184   // ensures that there are no cycles and that everything got processed.
185 #ifndef NDEBUG
186   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
187        E = DAG.allnodes_end(); I != E; ++I) {
188     bool Failed = false;
189
190     // Check that all result types are legal.
191     for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
192       if (!isTypeLegal(I->getValueType(i))) {
193         cerr << "Result type " << i << " illegal!\n";
194         Failed = true;
195       }
196
197     // Check that all operand types are legal.
198     for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
199       if (!isTypeLegal(I->getOperand(i).getValueType())) {
200         cerr << "Operand type " << i << " illegal!\n";
201         Failed = true;
202       }
203
204     if (I->getNodeId() != Processed) {
205        if (I->getNodeId() == NewNode)
206          cerr << "New node not 'noticed'?\n";
207        else if (I->getNodeId() > 0)
208          cerr << "Operand not processed?\n";
209        else if (I->getNodeId() == ReadyToProcess)
210          cerr << "Not added to worklist?\n";
211        Failed = true;
212     }
213
214     if (Failed) {
215       I->dump(&DAG); cerr << "\n";
216       abort();
217     }
218   }
219 #endif
220 }
221
222 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
223 /// new nodes.  Correct any processed operands (this may change the node) and
224 /// calculate the NodeId.
225 void DAGTypeLegalizer::AnalyzeNewNode(SDNode *&N) {
226   // If this was an existing node that is already done, we're done.
227   if (N->getNodeId() != NewNode)
228     return;
229
230   // Remove any stale map entries.
231   ExpungeNode(N);
232
233   // Okay, we know that this node is new.  Recursively walk all of its operands
234   // to see if they are new also.  The depth of this walk is bounded by the size
235   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
236   // about revisiting of nodes.
237   //
238   // As we walk the operands, keep track of the number of nodes that are
239   // processed.  If non-zero, this will become the new nodeid of this node.
240   // Already processed operands may need to be remapped to the node that
241   // replaced them, which can result in our node changing.  Since remapping
242   // is rare, the code tries to minimize overhead in the non-remapping case.
243
244   SmallVector<SDOperand, 8> NewOps;
245   unsigned NumProcessed = 0;
246   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
247     SDOperand OrigOp = N->getOperand(i);
248     SDOperand Op = OrigOp;
249
250     if (Op.Val->getNodeId() == Processed)
251       RemapNode(Op);
252
253     if (Op.Val->getNodeId() == NewNode)
254       AnalyzeNewNode(Op.Val);
255     else if (Op.Val->getNodeId() == Processed)
256       ++NumProcessed;
257
258     if (!NewOps.empty()) {
259       // Some previous operand changed.  Add this one to the list.
260       NewOps.push_back(Op);
261     } else if (Op != OrigOp) {
262       // This is the first operand to change - add all operands so far.
263       for (unsigned j = 0; j < i; ++j)
264         NewOps.push_back(N->getOperand(j));
265       NewOps.push_back(Op);
266     }
267   }
268
269   // Some operands changed - update the node.
270   if (!NewOps.empty())
271     N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
272
273   N->setNodeId(N->getNumOperands()-NumProcessed);
274   if (N->getNodeId() == ReadyToProcess)
275     Worklist.push_back(N);
276 }
277
278 namespace {
279   /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
280   /// updates to nodes and recomputes their ready state.
281   class VISIBILITY_HIDDEN NodeUpdateListener :
282     public SelectionDAG::DAGUpdateListener {
283     DAGTypeLegalizer &DTL;
284   public:
285     explicit NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
286
287     virtual void NodeDeleted(SDNode *N, SDNode *E) {
288       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
289              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
290              "RAUW deleted processed node!");
291       // It is possible, though rare, for the deleted node N to occur as a
292       // target in a map, so note the replacement N -> E in ReplacedNodes.
293       assert(E && "Node not replaced?");
294       DTL.NoteDeletion(N, E);
295     }
296
297     virtual void NodeUpdated(SDNode *N) {
298       // Node updates can mean pretty much anything.  It is possible that an
299       // operand was set to something already processed (f.e.) in which case
300       // this node could become ready.  Recompute its flags.
301       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
302              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
303              "RAUW updated processed node!");
304       DTL.ReanalyzeNode(N);
305     }
306   };
307 }
308
309
310 /// ReplaceValueWith - The specified value was legalized to the specified other
311 /// value.  If they are different, update the DAG and NodeIDs replacing any uses
312 /// of From to use To instead.
313 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
314   if (From == To) return;
315
316   // If expansion produced new nodes, make sure they are properly marked.
317   ExpungeNode(From.Val);
318   AnalyzeNewNode(To.Val); // Expunges To.
319
320   // Anything that used the old node should now use the new one.  Note that this
321   // can potentially cause recursive merging.
322   NodeUpdateListener NUL(*this);
323   DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
324
325   // The old node may still be present in a map like ExpandedIntegers or
326   // PromotedIntegers.  Inform maps about the replacement.
327   ReplacedNodes[From] = To;
328 }
329
330 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
331 /// node's results.  The from and to node must define identical result types.
332 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
333   if (From == To) return;
334
335   // If expansion produced new nodes, make sure they are properly marked.
336   ExpungeNode(From);
337   AnalyzeNewNode(To); // Expunges To.
338
339   assert(From->getNumValues() == To->getNumValues() &&
340          "Node results don't match");
341
342   // Anything that used the old node should now use the new one.  Note that this
343   // can potentially cause recursive merging.
344   NodeUpdateListener NUL(*this);
345   DAG.ReplaceAllUsesWith(From, To, &NUL);
346
347   // The old node may still be present in a map like ExpandedIntegers or
348   // PromotedIntegers.  Inform maps about the replacement.
349   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
350     assert(From->getValueType(i) == To->getValueType(i) &&
351            "Node results don't match");
352     ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
353   }
354 }
355
356
357 /// RemapNode - If the specified value was already legalized to another value,
358 /// replace it by that value.
359 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
360   DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
361   if (I != ReplacedNodes.end()) {
362     // Use path compression to speed up future lookups if values get multiply
363     // replaced with other values.
364     RemapNode(I->second);
365     N = I->second;
366   }
367 }
368
369 /// ExpungeNode - If N has a bogus mapping in ReplacedNodes, eliminate it.
370 /// This can occur when a node is deleted then reallocated as a new node -
371 /// the mapping in ReplacedNodes applies to the deleted node, not the new
372 /// one.
373 /// The only map that can have a deleted node as a source is ReplacedNodes.
374 /// Other maps can have deleted nodes as targets, but since their looked-up
375 /// values are always immediately remapped using RemapNode, resulting in a
376 /// not-deleted node, this is harmless as long as ReplacedNodes/RemapNode
377 /// always performs correct mappings.  In order to keep the mapping correct,
378 /// ExpungeNode should be called on any new nodes *before* adding them as
379 /// either source or target to ReplacedNodes (which typically means calling
380 /// Expunge when a new node is first seen, since it may no longer be marked
381 /// NewNode by the time it is added to ReplacedNodes).
382 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
383   if (N->getNodeId() != NewNode)
384     return;
385
386   // If N is not remapped by ReplacedNodes then there is nothing to do.
387   unsigned i, e;
388   for (i = 0, e = N->getNumValues(); i != e; ++i)
389     if (ReplacedNodes.find(SDOperand(N, i)) != ReplacedNodes.end())
390       break;
391
392   if (i == e)
393     return;
394
395   // Remove N from all maps - this is expensive but rare.
396
397   for (DenseMap<SDOperand, SDOperand>::iterator I = PromotedIntegers.begin(),
398        E = PromotedIntegers.end(); I != E; ++I) {
399     assert(I->first.Val != N);
400     RemapNode(I->second);
401   }
402
403   for (DenseMap<SDOperand, SDOperand>::iterator I = SoftenedFloats.begin(),
404        E = SoftenedFloats.end(); I != E; ++I) {
405     assert(I->first.Val != N);
406     RemapNode(I->second);
407   }
408
409   for (DenseMap<SDOperand, SDOperand>::iterator I = ScalarizedVectors.begin(),
410        E = ScalarizedVectors.end(); I != E; ++I) {
411     assert(I->first.Val != N);
412     RemapNode(I->second);
413   }
414
415   for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
416        I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
417     assert(I->first.Val != N);
418     RemapNode(I->second.first);
419     RemapNode(I->second.second);
420   }
421
422   for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
423        I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
424     assert(I->first.Val != N);
425     RemapNode(I->second.first);
426     RemapNode(I->second.second);
427   }
428
429   for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
430        I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
431     assert(I->first.Val != N);
432     RemapNode(I->second.first);
433     RemapNode(I->second.second);
434   }
435
436   for (DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.begin(),
437        E = ReplacedNodes.end(); I != E; ++I)
438     RemapNode(I->second);
439
440   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
441     ReplacedNodes.erase(SDOperand(N, i));
442 }
443
444
445 void DAGTypeLegalizer::SetPromotedInteger(SDOperand Op, SDOperand Result) {
446   AnalyzeNewNode(Result.Val);
447
448   SDOperand &OpEntry = PromotedIntegers[Op];
449   assert(OpEntry.Val == 0 && "Node is already promoted!");
450   OpEntry = Result;
451 }
452
453 void DAGTypeLegalizer::SetSoftenedFloat(SDOperand Op, SDOperand Result) {
454   AnalyzeNewNode(Result.Val);
455
456   SDOperand &OpEntry = SoftenedFloats[Op];
457   assert(OpEntry.Val == 0 && "Node is already converted to integer!");
458   OpEntry = Result;
459 }
460
461 void DAGTypeLegalizer::SetScalarizedVector(SDOperand Op, SDOperand Result) {
462   AnalyzeNewNode(Result.Val);
463
464   SDOperand &OpEntry = ScalarizedVectors[Op];
465   assert(OpEntry.Val == 0 && "Node is already scalarized!");
466   OpEntry = Result;
467 }
468
469 void DAGTypeLegalizer::GetExpandedInteger(SDOperand Op, SDOperand &Lo,
470                                           SDOperand &Hi) {
471   std::pair<SDOperand, SDOperand> &Entry = ExpandedIntegers[Op];
472   RemapNode(Entry.first);
473   RemapNode(Entry.second);
474   assert(Entry.first.Val && "Operand isn't expanded");
475   Lo = Entry.first;
476   Hi = Entry.second;
477 }
478
479 void DAGTypeLegalizer::SetExpandedInteger(SDOperand Op, SDOperand Lo,
480                                           SDOperand Hi) {
481   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
482   AnalyzeNewNode(Lo.Val);
483   AnalyzeNewNode(Hi.Val);
484
485   // Remember that this is the result of the node.
486   std::pair<SDOperand, SDOperand> &Entry = ExpandedIntegers[Op];
487   assert(Entry.first.Val == 0 && "Node already expanded");
488   Entry.first = Lo;
489   Entry.second = Hi;
490 }
491
492 void DAGTypeLegalizer::GetExpandedFloat(SDOperand Op, SDOperand &Lo,
493                                         SDOperand &Hi) {
494   std::pair<SDOperand, SDOperand> &Entry = ExpandedFloats[Op];
495   RemapNode(Entry.first);
496   RemapNode(Entry.second);
497   assert(Entry.first.Val && "Operand isn't expanded");
498   Lo = Entry.first;
499   Hi = Entry.second;
500 }
501
502 void DAGTypeLegalizer::SetExpandedFloat(SDOperand Op, SDOperand Lo,
503                                         SDOperand Hi) {
504   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
505   AnalyzeNewNode(Lo.Val);
506   AnalyzeNewNode(Hi.Val);
507
508   // Remember that this is the result of the node.
509   std::pair<SDOperand, SDOperand> &Entry = ExpandedFloats[Op];
510   assert(Entry.first.Val == 0 && "Node already expanded");
511   Entry.first = Lo;
512   Entry.second = Hi;
513 }
514
515 void DAGTypeLegalizer::GetSplitVector(SDOperand Op, SDOperand &Lo,
516                                       SDOperand &Hi) {
517   std::pair<SDOperand, SDOperand> &Entry = SplitVectors[Op];
518   RemapNode(Entry.first);
519   RemapNode(Entry.second);
520   assert(Entry.first.Val && "Operand isn't split");
521   Lo = Entry.first;
522   Hi = Entry.second;
523 }
524
525 void DAGTypeLegalizer::SetSplitVector(SDOperand Op, SDOperand Lo,
526                                       SDOperand Hi) {
527   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
528   AnalyzeNewNode(Lo.Val);
529   AnalyzeNewNode(Hi.Val);
530
531   // Remember that this is the result of the node.
532   std::pair<SDOperand, SDOperand> &Entry = SplitVectors[Op];
533   assert(Entry.first.Val == 0 && "Node already split");
534   Entry.first = Lo;
535   Entry.second = Hi;
536 }
537
538
539 //===----------------------------------------------------------------------===//
540 // Utilities.
541 //===----------------------------------------------------------------------===//
542
543 /// BitConvertToInteger - Convert to an integer of the same size.
544 SDOperand DAGTypeLegalizer::BitConvertToInteger(SDOperand Op) {
545   unsigned BitWidth = Op.getValueType().getSizeInBits();
546   return DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerVT(BitWidth), Op);
547 }
548
549 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
550                                                  MVT DestVT) {
551   // Create the stack frame object.  Make sure it is aligned for both
552   // the source and destination types.
553   unsigned SrcAlign =
554    TLI.getTargetData()->getPrefTypeAlignment(Op.getValueType().getTypeForMVT());
555   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT, SrcAlign);
556
557   // Emit a store to the stack slot.
558   SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
559   // Result is a load from the stack slot.
560   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
561 }
562
563 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
564 SDOperand DAGTypeLegalizer::JoinIntegers(SDOperand Lo, SDOperand Hi) {
565   MVT LVT = Lo.getValueType();
566   MVT HVT = Hi.getValueType();
567   MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
568
569   Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
570   Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
571   Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(LVT.getSizeInBits(),
572                                                       TLI.getShiftAmountTy()));
573   return DAG.getNode(ISD::OR, NVT, Lo, Hi);
574 }
575
576 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
577 /// bits in Hi.
578 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
579                                     MVT LoVT, MVT HiVT,
580                                     SDOperand &Lo, SDOperand &Hi) {
581   assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
582          Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
583   Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
584   Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
585                    DAG.getConstant(LoVT.getSizeInBits(),
586                                    TLI.getShiftAmountTy()));
587   Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
588 }
589
590 /// SplitInteger - Return the lower and upper halves of Op's bits in a value type
591 /// half the size of Op's.
592 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
593                                     SDOperand &Lo, SDOperand &Hi) {
594   MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
595   SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
596 }
597
598 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
599 /// returning a result of type RetVT.
600 SDOperand DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
601                                         const SDOperand *Ops, unsigned NumOps,
602                                         bool isSigned) {
603   TargetLowering::ArgListTy Args;
604   Args.reserve(NumOps);
605
606   TargetLowering::ArgListEntry Entry;
607   for (unsigned i = 0; i != NumOps; ++i) {
608     Entry.Node = Ops[i];
609     Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
610     Entry.isSExt = isSigned;
611     Entry.isZExt = !isSigned;
612     Args.push_back(Entry);
613   }
614   SDOperand Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
615                                            TLI.getPointerTy());
616
617   const Type *RetTy = RetVT.getTypeForMVT();
618   std::pair<SDOperand,SDOperand> CallInfo =
619     TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
620                     CallingConv::C, false, Callee, Args, DAG);
621   return CallInfo.first;
622 }
623
624 SDOperand DAGTypeLegalizer::GetVectorElementPointer(SDOperand VecPtr, MVT EltVT,
625                                                     SDOperand Index) {
626   // Make sure the index type is big enough to compute in.
627   if (Index.getValueType().bitsGT(TLI.getPointerTy()))
628     Index = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Index);
629   else
630     Index = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Index);
631
632   // Calculate the element offset and add it to the pointer.
633   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
634
635   Index = DAG.getNode(ISD::MUL, Index.getValueType(), Index,
636                       DAG.getConstant(EltSize, Index.getValueType()));
637   return DAG.getNode(ISD::ADD, Index.getValueType(), Index, VecPtr);
638 }
639
640 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
641 /// which is split into two not necessarily identical pieces.
642 void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT, MVT &LoVT, MVT &HiVT) {
643   if (!InVT.isVector()) {
644     LoVT = HiVT = TLI.getTypeToTransformTo(InVT);
645   } else {
646     MVT NewEltVT = InVT.getVectorElementType();
647     unsigned NumElements = InVT.getVectorNumElements();
648     if ((NumElements & (NumElements-1)) == 0) {  // Simple power of two vector.
649       NumElements >>= 1;
650       LoVT = HiVT =  MVT::getVectorVT(NewEltVT, NumElements);
651     } else {                                     // Non-power-of-two vectors.
652       unsigned NewNumElts_Lo = 1 << Log2_32(NumElements);
653       unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
654       LoVT = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
655       HiVT = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
656     }
657   }
658 }
659
660
661 //===----------------------------------------------------------------------===//
662 //  Entry Point
663 //===----------------------------------------------------------------------===//
664
665 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
666 /// only uses types natively supported by the target.
667 ///
668 /// Note that this is an involved process that may invalidate pointers into
669 /// the graph.
670 void SelectionDAG::LegalizeTypes() {
671   if (ViewLegalizeTypesDAGs) viewGraph();
672
673   DAGTypeLegalizer(*this).run();
674 }