1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "LegalizeTypes.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/MathExtras.h"
26 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
27 cl::desc("Pop up a window to show dags before legalize types"));
29 static const bool ViewLegalizeTypesDAGs = 0;
34 /// run - This is the main entry point for the type legalizer. This does a
35 /// top-down traversal of the dag, legalizing types as it goes.
36 void DAGTypeLegalizer::run() {
37 // Create a dummy node (which is not added to allnodes), that adds a reference
38 // to the root node, preventing it from being deleted, and tracking any
39 // changes of the root.
40 HandleSDNode Dummy(DAG.getRoot());
42 // The root of the dag may dangle to deleted nodes until the type legalizer is
43 // done. Set it to null to avoid confusion.
44 DAG.setRoot(SDOperand());
46 // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
47 // (and remembering them) if they are leaves and assigning 'NewNode' if
49 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
50 E = DAG.allnodes_end(); I != E; ++I) {
51 if (I->getNumOperands() == 0) {
52 I->setNodeId(ReadyToProcess);
53 Worklist.push_back(I);
55 I->setNodeId(NewNode);
59 // Now that we have a set of nodes to process, handle them all.
60 while (!Worklist.empty()) {
61 SDNode *N = Worklist.back();
63 assert(N->getNodeId() == ReadyToProcess &&
64 "Node should be ready if on worklist!");
66 // Scan the values produced by the node, checking to see if any result
69 unsigned NumResults = N->getNumValues();
71 MVT ResultVT = N->getValueType(i);
72 switch (getTypeAction(ResultVT)) {
74 assert(false && "Unknown action!");
78 PromoteIntegerResult(N, i);
81 ExpandIntegerResult(N, i);
84 PromoteFloatResult(N, i);
87 ExpandFloatResult(N, i);
90 ScalarizeResult(N, i);
96 } while (++i < NumResults);
98 // Scan the operand list for the node, handling any nodes with operands that
101 unsigned NumOperands = N->getNumOperands();
102 bool NeedsRevisit = false;
103 for (i = 0; i != NumOperands; ++i) {
104 MVT OpVT = N->getOperand(i).getValueType();
105 switch (getTypeAction(OpVT)) {
107 assert(false && "Unknown action!");
111 NeedsRevisit = PromoteIntegerOperand(N, i);
114 NeedsRevisit = ExpandIntegerOperand(N, i);
117 NeedsRevisit = PromoteFloatOperand(N, i);
120 NeedsRevisit = ExpandFloatOperand(N, i);
123 NeedsRevisit = ScalarizeOperand(N, i);
126 NeedsRevisit = SplitOperand(N, i);
132 // If the node needs revisiting, don't add all users to the worklist etc.
136 if (i == NumOperands)
137 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
141 // If we reach here, the node was processed, potentially creating new nodes.
142 // Mark it as processed and add its users to the worklist as appropriate.
143 N->setNodeId(Processed);
145 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
147 SDNode *User = UI->getUser();
148 int NodeID = User->getNodeId();
149 assert(NodeID != ReadyToProcess && NodeID != Processed &&
150 "Invalid node id for user of unprocessed node!");
152 // This node has two options: it can either be a new node or its Node ID
153 // may be a count of the number of operands it has that are not ready.
155 User->setNodeId(NodeID-1);
157 // If this was the last use it was waiting on, add it to the ready list.
158 if (NodeID-1 == ReadyToProcess)
159 Worklist.push_back(User);
163 // Otherwise, this node is new: this is the first operand of it that
164 // became ready. Its new NodeID is the number of operands it has minus 1
165 // (as this node is now processed).
166 assert(NodeID == NewNode && "Unknown node ID!");
167 User->setNodeId(User->getNumOperands()-1);
169 // If the node only has a single operand, it is now ready.
170 if (User->getNumOperands() == 1)
171 Worklist.push_back(User);
175 // If the root changed (e.g. it was a dead load, update the root).
176 DAG.setRoot(Dummy.getValue());
180 // Remove dead nodes. This is important to do for cleanliness but also before
181 // the checking loop below. Implicit folding by the DAG.getNode operators can
182 // cause unreachable nodes to be around with their flags set to new.
183 DAG.RemoveDeadNodes();
185 // In a debug build, scan all the nodes to make sure we found them all. This
186 // ensures that there are no cycles and that everything got processed.
188 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
189 E = DAG.allnodes_end(); I != E; ++I) {
192 // Check that all result types are legal.
193 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
194 if (!isTypeLegal(I->getValueType(i))) {
195 cerr << "Result type " << i << " illegal!\n";
199 // Check that all operand types are legal.
200 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
201 if (!isTypeLegal(I->getOperand(i).getValueType())) {
202 cerr << "Operand type " << i << " illegal!\n";
206 if (I->getNodeId() != Processed) {
207 if (I->getNodeId() == NewNode)
208 cerr << "New node not 'noticed'?\n";
209 else if (I->getNodeId() > 0)
210 cerr << "Operand not processed?\n";
211 else if (I->getNodeId() == ReadyToProcess)
212 cerr << "Not added to worklist?\n";
217 I->dump(&DAG); cerr << "\n";
224 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
225 /// new nodes. Correct any processed operands (this may change the node) and
226 /// calculate the NodeId.
227 void DAGTypeLegalizer::AnalyzeNewNode(SDNode *&N) {
228 // If this was an existing node that is already done, we're done.
229 if (N->getNodeId() != NewNode)
232 // Okay, we know that this node is new. Recursively walk all of its operands
233 // to see if they are new also. The depth of this walk is bounded by the size
234 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
235 // about revisiting of nodes.
237 // As we walk the operands, keep track of the number of nodes that are
238 // processed. If non-zero, this will become the new nodeid of this node.
239 // Already processed operands may need to be remapped to the node that
240 // replaced them, which can result in our node changing. Since remapping
241 // is rare, the code tries to minimize overhead in the non-remapping case.
243 SmallVector<SDOperand, 8> NewOps;
244 unsigned NumProcessed = 0;
245 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
246 SDOperand OrigOp = N->getOperand(i);
247 SDOperand Op = OrigOp;
249 if (Op.Val->getNodeId() == Processed)
252 if (Op.Val->getNodeId() == NewNode)
253 AnalyzeNewNode(Op.Val);
254 else if (Op.Val->getNodeId() == Processed)
257 if (!NewOps.empty()) {
258 // Some previous operand changed. Add this one to the list.
259 NewOps.push_back(Op);
260 } else if (Op != OrigOp) {
261 // This is the first operand to change - add all operands so far.
262 for (unsigned j = 0; j < i; ++j)
263 NewOps.push_back(N->getOperand(j));
264 NewOps.push_back(Op);
268 // Some operands changed - update the node.
270 N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
272 N->setNodeId(N->getNumOperands()-NumProcessed);
273 if (N->getNodeId() == ReadyToProcess)
274 Worklist.push_back(N);
278 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
279 /// updates to nodes and recomputes their ready state.
280 class VISIBILITY_HIDDEN NodeUpdateListener :
281 public SelectionDAG::DAGUpdateListener {
282 DAGTypeLegalizer &DTL;
284 NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
286 virtual void NodeDeleted(SDNode *N, SDNode *E) {
287 assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
288 N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
289 "RAUW deleted processed node!");
290 // It is possible, though rare, for the deleted node N to occur as a
291 // target in a map, so note the replacement N -> E in ReplacedNodes.
292 assert(E && "Node not replaced?");
293 for (unsigned i = 0, e = E->getNumValues(); i != e; ++i)
294 DTL.NoteReplacement(SDOperand(N, i), SDOperand(E, i));
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);
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;
316 // If expansion produced new nodes, make sure they are properly marked.
317 AnalyzeNewNode(To.Val);
319 // Anything that used the old node should now use the new one. Note that this
320 // can potentially cause recursive merging.
321 NodeUpdateListener NUL(*this);
322 DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
324 // The old node may still be present in a map like ExpandedIntegers or
325 // PromotedIntegers. Inform maps about the replacement.
326 NoteReplacement(From, To);
329 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
330 /// node's results. The from and to node must define identical result types.
331 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
332 if (From == To) return;
334 // If expansion produced new nodes, make sure they are properly marked.
337 assert(From->getNumValues() == To->getNumValues() &&
338 "Node results don't match");
340 // Anything that used the old node should now use the new one. Note that this
341 // can potentially cause recursive merging.
342 NodeUpdateListener NUL(*this);
343 DAG.ReplaceAllUsesWith(From, To, &NUL);
345 // The old node may still be present in a map like ExpandedIntegers or
346 // PromotedIntegers. Inform maps about the replacement.
347 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
348 assert(From->getValueType(i) == To->getValueType(i) &&
349 "Node results don't match");
350 NoteReplacement(SDOperand(From, i), SDOperand(To, i));
355 /// RemapNode - If the specified value was already legalized to another value,
356 /// replace it by that value.
357 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
358 DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
359 if (I != ReplacedNodes.end()) {
360 // Use path compression to speed up future lookups if values get multiply
361 // replaced with other values.
362 RemapNode(I->second);
367 /// ExpungeNode - If this is a deleted value that was kept around to speed up
368 /// remapping, remove it globally now. The only map that can have a deleted
369 /// node as a source is ReplacedNodes. Other maps can have deleted nodes as
370 /// targets, but since their looked-up values are always immediately remapped
371 /// using RemapNode, resulting in a not-deleted node, this is harmless as long
372 /// as ReplacedNodes/RemapNode always performs correct mappings. The mapping
373 /// will always be correct as long as ExpungeNode is called on the source when
374 /// adding a new node to ReplacedNodes, and called on the target when adding
375 /// a new node to any map.
376 void DAGTypeLegalizer::ExpungeNode(SDOperand N) {
377 SDOperand Replacement = N;
378 RemapNode(Replacement);
379 if (Replacement != N) {
380 // Remove N from all maps - this is expensive but extremely rare.
381 ReplacedNodes.erase(N);
383 for (DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.begin(),
384 E = ReplacedNodes.end(); I != E; ++I) {
386 I->second = Replacement;
389 for (DenseMap<SDOperand, SDOperand>::iterator I = PromotedIntegers.begin(),
390 E = PromotedIntegers.end(); I != E; ++I) {
391 assert(I->first != N);
393 I->second = Replacement;
396 for (DenseMap<SDOperand, SDOperand>::iterator I = PromotedFloats.begin(),
397 E = PromotedFloats.end(); I != E; ++I) {
398 assert(I->first != N);
400 I->second = Replacement;
403 for (DenseMap<SDOperand, SDOperand>::iterator I = ScalarizedVectors.begin(),
404 E = ScalarizedVectors.end(); I != E; ++I) {
405 assert(I->first != N);
407 I->second = Replacement;
410 for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
411 I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
412 assert(I->first != N);
413 if (I->second.first == N)
414 I->second.first = Replacement;
415 if (I->second.second == N)
416 I->second.second = Replacement;
419 for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
420 I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
421 assert(I->first != N);
422 if (I->second.first == N)
423 I->second.first = Replacement;
424 if (I->second.second == N)
425 I->second.second = Replacement;
428 for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
429 I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
430 assert(I->first != N);
431 if (I->second.first == N)
432 I->second.first = Replacement;
433 if (I->second.second == N)
434 I->second.second = Replacement;
440 void DAGTypeLegalizer::SetPromotedInteger(SDOperand Op, SDOperand Result) {
442 AnalyzeNewNode(Result.Val);
444 SDOperand &OpEntry = PromotedIntegers[Op];
445 assert(OpEntry.Val == 0 && "Node is already promoted!");
449 void DAGTypeLegalizer::SetPromotedFloat(SDOperand Op, SDOperand Result) {
451 AnalyzeNewNode(Result.Val);
453 SDOperand &OpEntry = PromotedFloats[Op];
454 assert(OpEntry.Val == 0 && "Node is already converted to integer!");
458 void DAGTypeLegalizer::SetScalarizedVector(SDOperand Op, SDOperand Result) {
460 AnalyzeNewNode(Result.Val);
462 SDOperand &OpEntry = ScalarizedVectors[Op];
463 assert(OpEntry.Val == 0 && "Node is already scalarized!");
467 void DAGTypeLegalizer::GetExpandedInteger(SDOperand Op, SDOperand &Lo,
469 std::pair<SDOperand, SDOperand> &Entry = ExpandedIntegers[Op];
470 RemapNode(Entry.first);
471 RemapNode(Entry.second);
472 assert(Entry.first.Val && "Operand isn't expanded");
477 void DAGTypeLegalizer::SetExpandedInteger(SDOperand Op, SDOperand Lo,
482 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
483 AnalyzeNewNode(Lo.Val);
484 AnalyzeNewNode(Hi.Val);
486 // Remember that this is the result of the node.
487 std::pair<SDOperand, SDOperand> &Entry = ExpandedIntegers[Op];
488 assert(Entry.first.Val == 0 && "Node already expanded");
493 void DAGTypeLegalizer::GetExpandedFloat(SDOperand Op, SDOperand &Lo,
495 std::pair<SDOperand, SDOperand> &Entry = ExpandedFloats[Op];
496 RemapNode(Entry.first);
497 RemapNode(Entry.second);
498 assert(Entry.first.Val && "Operand isn't expanded");
503 void DAGTypeLegalizer::SetExpandedFloat(SDOperand Op, SDOperand Lo,
508 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
509 AnalyzeNewNode(Lo.Val);
510 AnalyzeNewNode(Hi.Val);
512 // Remember that this is the result of the node.
513 std::pair<SDOperand, SDOperand> &Entry = ExpandedFloats[Op];
514 assert(Entry.first.Val == 0 && "Node already expanded");
519 void DAGTypeLegalizer::GetSplitVector(SDOperand Op, SDOperand &Lo,
521 std::pair<SDOperand, SDOperand> &Entry = SplitVectors[Op];
522 RemapNode(Entry.first);
523 RemapNode(Entry.second);
524 assert(Entry.first.Val && "Operand isn't split");
529 void DAGTypeLegalizer::SetSplitVector(SDOperand Op, SDOperand Lo,
534 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
535 AnalyzeNewNode(Lo.Val);
536 AnalyzeNewNode(Hi.Val);
538 // Remember that this is the result of the node.
539 std::pair<SDOperand, SDOperand> &Entry = SplitVectors[Op];
540 assert(Entry.first.Val == 0 && "Node already split");
546 /// BitConvertToInteger - Convert to an integer of the same size.
547 SDOperand DAGTypeLegalizer::BitConvertToInteger(SDOperand Op) {
548 unsigned BitWidth = Op.getValueType().getSizeInBits();
549 return DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerVT(BitWidth), Op);
552 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
554 // Create the stack frame object.
555 SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
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);
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());
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);
576 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
578 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
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);
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);
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,
603 TargetLowering::ArgListTy Args;
604 Args.reserve(NumOps);
606 TargetLowering::ArgListEntry Entry;
607 for (unsigned i = 0; i != NumOps; ++i) {
609 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
610 Entry.isSExt = isSigned;
611 Entry.isZExt = !isSigned;
612 Args.push_back(Entry);
614 SDOperand Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
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;
624 SDOperand DAGTypeLegalizer::GetVectorElementPointer(SDOperand VecPtr, MVT EltVT,
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);
630 Index = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Index);
632 // Calculate the element offset and add it to the pointer.
633 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
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);
641 //===----------------------------------------------------------------------===//
643 //===----------------------------------------------------------------------===//
645 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
646 /// only uses types natively supported by the target.
648 /// Note that this is an involved process that may invalidate pointers into
650 void SelectionDAG::LegalizeTypes() {
651 if (ViewLegalizeTypesDAGs) viewGraph();
653 DAGTypeLegalizer(*this).run();