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!");
84 FloatToIntResult(N, i);
87 ScalarizeResult(N, i);
93 } while (++i < NumResults);
95 // Scan the operand list for the node, handling any nodes with operands that
98 unsigned NumOperands = N->getNumOperands();
99 bool NeedsRevisit = false;
100 for (i = 0; i != NumOperands; ++i) {
101 MVT OpVT = N->getOperand(i).getValueType();
102 switch (getTypeAction(OpVT)) {
104 assert(false && "Unknown action!");
108 NeedsRevisit = PromoteOperand(N, i);
111 NeedsRevisit = ExpandOperand(N, i);
114 NeedsRevisit = FloatToIntOperand(N, i);
117 NeedsRevisit = ScalarizeOperand(N, i);
120 NeedsRevisit = SplitOperand(N, i);
126 // If the node needs revisiting, don't add all users to the worklist etc.
130 if (i == NumOperands)
131 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
135 // If we reach here, the node was processed, potentially creating new nodes.
136 // Mark it as processed and add its users to the worklist as appropriate.
137 N->setNodeId(Processed);
139 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
141 SDNode *User = UI->getUser();
142 int NodeID = User->getNodeId();
143 assert(NodeID != ReadyToProcess && NodeID != Processed &&
144 "Invalid node id for user of unprocessed node!");
146 // This node has two options: it can either be a new node or its Node ID
147 // may be a count of the number of operands it has that are not ready.
149 User->setNodeId(NodeID-1);
151 // If this was the last use it was waiting on, add it to the ready list.
152 if (NodeID-1 == ReadyToProcess)
153 Worklist.push_back(User);
157 // Otherwise, this node is new: this is the first operand of it that
158 // became ready. Its new NodeID is the number of operands it has minus 1
159 // (as this node is now processed).
160 assert(NodeID == NewNode && "Unknown node ID!");
161 User->setNodeId(User->getNumOperands()-1);
163 // If the node only has a single operand, it is now ready.
164 if (User->getNumOperands() == 1)
165 Worklist.push_back(User);
169 // If the root changed (e.g. it was a dead load, update the root).
170 DAG.setRoot(Dummy.getValue());
174 // Remove dead nodes. This is important to do for cleanliness but also before
175 // the checking loop below. Implicit folding by the DAG.getNode operators can
176 // cause unreachable nodes to be around with their flags set to new.
177 DAG.RemoveDeadNodes();
179 // In a debug build, scan all the nodes to make sure we found them all. This
180 // ensures that there are no cycles and that everything got processed.
182 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
183 E = DAG.allnodes_end(); I != E; ++I) {
186 // Check that all result types are legal.
187 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
188 if (!isTypeLegal(I->getValueType(i))) {
189 cerr << "Result type " << i << " illegal!\n";
193 // Check that all operand types are legal.
194 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
195 if (!isTypeLegal(I->getOperand(i).getValueType())) {
196 cerr << "Operand type " << i << " illegal!\n";
200 if (I->getNodeId() != Processed) {
201 if (I->getNodeId() == NewNode)
202 cerr << "New node not 'noticed'?\n";
203 else if (I->getNodeId() > 0)
204 cerr << "Operand not processed?\n";
205 else if (I->getNodeId() == ReadyToProcess)
206 cerr << "Not added to worklist?\n";
211 I->dump(&DAG); cerr << "\n";
218 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
219 /// new nodes. Correct any processed operands (this may change the node) and
220 /// calculate the NodeId.
221 void DAGTypeLegalizer::AnalyzeNewNode(SDNode *&N) {
222 // If this was an existing node that is already done, we're done.
223 if (N->getNodeId() != NewNode)
226 // Okay, we know that this node is new. Recursively walk all of its operands
227 // to see if they are new also. The depth of this walk is bounded by the size
228 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
229 // about revisiting of nodes.
231 // As we walk the operands, keep track of the number of nodes that are
232 // processed. If non-zero, this will become the new nodeid of this node.
233 // Already processed operands may need to be remapped to the node that
234 // replaced them, which can result in our node changing. Since remapping
235 // is rare, the code tries to minimize overhead in the non-remapping case.
237 SmallVector<SDOperand, 8> NewOps;
238 unsigned NumProcessed = 0;
239 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
240 SDOperand OrigOp = N->getOperand(i);
241 SDOperand Op = OrigOp;
243 if (Op.Val->getNodeId() == Processed)
246 if (Op.Val->getNodeId() == NewNode)
247 AnalyzeNewNode(Op.Val);
248 else if (Op.Val->getNodeId() == Processed)
251 if (!NewOps.empty()) {
252 // Some previous operand changed. Add this one to the list.
253 NewOps.push_back(Op);
254 } else if (Op != OrigOp) {
255 // This is the first operand to change - add all operands so far.
256 for (unsigned j = 0; j < i; ++j)
257 NewOps.push_back(N->getOperand(j));
258 NewOps.push_back(Op);
262 // Some operands changed - update the node.
264 N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
266 N->setNodeId(N->getNumOperands()-NumProcessed);
267 if (N->getNodeId() == ReadyToProcess)
268 Worklist.push_back(N);
272 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
273 /// updates to nodes and recomputes their ready state.
274 class VISIBILITY_HIDDEN NodeUpdateListener :
275 public SelectionDAG::DAGUpdateListener {
276 DAGTypeLegalizer &DTL;
278 NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
280 virtual void NodeDeleted(SDNode *N, SDNode *E) {
281 assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
282 N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
283 "RAUW deleted processed node!");
284 // It is possible, though rare, for the deleted node N to occur as a
285 // target in a map, so note the replacement N -> E in ReplacedNodes.
286 assert(E && "Node not replaced?");
287 for (unsigned i = 0, e = E->getNumValues(); i != e; ++i)
288 DTL.NoteReplacement(SDOperand(N, i), SDOperand(E, i));
291 virtual void NodeUpdated(SDNode *N) {
292 // Node updates can mean pretty much anything. It is possible that an
293 // operand was set to something already processed (f.e.) in which case
294 // this node could become ready. Recompute its flags.
295 assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
296 N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
297 "RAUW updated processed node!");
298 DTL.ReanalyzeNode(N);
304 /// ReplaceValueWith - The specified value was legalized to the specified other
305 /// value. If they are different, update the DAG and NodeIDs replacing any uses
306 /// of From to use To instead.
307 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
308 if (From == To) return;
310 // If expansion produced new nodes, make sure they are properly marked.
311 AnalyzeNewNode(To.Val);
313 // Anything that used the old node should now use the new one. Note that this
314 // can potentially cause recursive merging.
315 NodeUpdateListener NUL(*this);
316 DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
318 // The old node may still be present in a map like ExpandedNodes or
319 // PromotedNodes. Inform maps about the replacement.
320 NoteReplacement(From, To);
323 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
324 /// node's results. The from and to node must define identical result types.
325 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
326 if (From == To) return;
328 // If expansion produced new nodes, make sure they are properly marked.
331 assert(From->getNumValues() == To->getNumValues() &&
332 "Node results don't match");
334 // Anything that used the old node should now use the new one. Note that this
335 // can potentially cause recursive merging.
336 NodeUpdateListener NUL(*this);
337 DAG.ReplaceAllUsesWith(From, To, &NUL);
339 // The old node may still be present in a map like ExpandedNodes or
340 // PromotedNodes. Inform maps about the replacement.
341 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
342 assert(From->getValueType(i) == To->getValueType(i) &&
343 "Node results don't match");
344 NoteReplacement(SDOperand(From, i), SDOperand(To, i));
349 /// RemapNode - If the specified value was already legalized to another value,
350 /// replace it by that value.
351 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
352 DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
353 if (I != ReplacedNodes.end()) {
354 // Use path compression to speed up future lookups if values get multiply
355 // replaced with other values.
356 RemapNode(I->second);
361 /// ExpungeNode - If this is a deleted value that was kept around to speed up
362 /// remapping, remove it globally now. The only map that can have a deleted
363 /// node as a source is ReplacedNodes. Other maps can have deleted nodes as
364 /// targets, but since their looked-up values are always immediately remapped
365 /// using RemapNode, resulting in a not-deleted node, this is harmless as long
366 /// as ReplacedNodes/RemapNode always performs correct mappings. The mapping
367 /// will always be correct as long as ExpungeNode is called on the source when
368 /// adding a new node to ReplacedNodes, and called on the target when adding
369 /// a new node to any map.
370 void DAGTypeLegalizer::ExpungeNode(SDOperand N) {
371 SDOperand Replacement = N;
372 RemapNode(Replacement);
373 if (Replacement != N) {
374 // Remove N from all maps - this is expensive but extremely rare.
375 ReplacedNodes.erase(N);
377 for (DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.begin(),
378 E = ReplacedNodes.end(); I != E; ++I) {
380 I->second = Replacement;
383 for (DenseMap<SDOperand, SDOperand>::iterator I = PromotedNodes.begin(),
384 E = PromotedNodes.end(); I != E; ++I) {
385 assert(I->first != N);
387 I->second = Replacement;
390 for (DenseMap<SDOperand, SDOperand>::iterator I = FloatToIntedNodes.begin(),
391 E = FloatToIntedNodes.end(); I != E; ++I) {
392 assert(I->first != N);
394 I->second = Replacement;
397 for (DenseMap<SDOperand, SDOperand>::iterator I = ScalarizedNodes.begin(),
398 E = ScalarizedNodes.end(); I != E; ++I) {
399 assert(I->first != N);
401 I->second = Replacement;
404 for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
405 I = ExpandedNodes.begin(), E = ExpandedNodes.end(); I != E; ++I) {
406 assert(I->first != N);
407 if (I->second.first == N)
408 I->second.first = Replacement;
409 if (I->second.second == N)
410 I->second.second = Replacement;
413 for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
414 I = SplitNodes.begin(), E = SplitNodes.end(); I != E; ++I) {
415 assert(I->first != N);
416 if (I->second.first == N)
417 I->second.first = Replacement;
418 if (I->second.second == N)
419 I->second.second = Replacement;
425 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
427 AnalyzeNewNode(Result.Val);
429 SDOperand &OpEntry = PromotedNodes[Op];
430 assert(OpEntry.Val == 0 && "Node is already promoted!");
434 void DAGTypeLegalizer::SetIntegerOp(SDOperand Op, SDOperand Result) {
436 AnalyzeNewNode(Result.Val);
438 SDOperand &OpEntry = FloatToIntedNodes[Op];
439 assert(OpEntry.Val == 0 && "Node is already converted to integer!");
443 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
445 AnalyzeNewNode(Result.Val);
447 SDOperand &OpEntry = ScalarizedNodes[Op];
448 assert(OpEntry.Val == 0 && "Node is already scalarized!");
452 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo,
454 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
455 RemapNode(Entry.first);
456 RemapNode(Entry.second);
457 assert(Entry.first.Val && "Operand isn't expanded");
462 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
466 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
467 AnalyzeNewNode(Lo.Val);
468 AnalyzeNewNode(Hi.Val);
470 // Remember that this is the result of the node.
471 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
472 assert(Entry.first.Val == 0 && "Node already expanded");
477 void DAGTypeLegalizer::GetSplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
478 std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
479 RemapNode(Entry.first);
480 RemapNode(Entry.second);
481 assert(Entry.first.Val && "Operand isn't split");
486 void DAGTypeLegalizer::SetSplitOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
490 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
491 AnalyzeNewNode(Lo.Val);
492 AnalyzeNewNode(Hi.Val);
494 // Remember that this is the result of the node.
495 std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
496 assert(Entry.first.Val == 0 && "Node already split");
502 /// BitConvertToInteger - Convert to an integer of the same size.
503 SDOperand DAGTypeLegalizer::BitConvertToInteger(SDOperand Op) {
504 unsigned BitWidth = Op.getValueType().getSizeInBits();
505 return DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerVT(BitWidth), Op);
508 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
510 // Create the stack frame object.
511 SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
513 // Emit a store to the stack slot.
514 SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
515 // Result is a load from the stack slot.
516 return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
519 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
520 SDOperand DAGTypeLegalizer::JoinIntegers(SDOperand Lo, SDOperand Hi) {
521 MVT LVT = Lo.getValueType();
522 MVT HVT = Hi.getValueType();
523 MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
525 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
526 Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
527 Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(LVT.getSizeInBits(),
528 TLI.getShiftAmountTy()));
529 return DAG.getNode(ISD::OR, NVT, Lo, Hi);
532 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
534 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
536 SDOperand &Lo, SDOperand &Hi) {
537 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
538 Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
539 Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
540 Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
541 DAG.getConstant(LoVT.getSizeInBits(),
542 TLI.getShiftAmountTy()));
543 Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
546 /// SplitInteger - Return the lower and upper halves of Op's bits in a value type
547 /// half the size of Op's.
548 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
549 SDOperand &Lo, SDOperand &Hi) {
550 MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
551 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
554 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
555 /// returning a result of type RetVT.
556 SDOperand DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
557 const SDOperand *Ops, unsigned NumOps,
559 TargetLowering::ArgListTy Args;
560 Args.reserve(NumOps);
562 TargetLowering::ArgListEntry Entry;
563 for (unsigned i = 0; i != NumOps; ++i) {
565 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
566 Entry.isSExt = isSigned;
567 Entry.isZExt = !isSigned;
568 Args.push_back(Entry);
570 SDOperand Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
573 const Type *RetTy = RetVT.getTypeForMVT();
574 std::pair<SDOperand,SDOperand> CallInfo =
575 TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
576 CallingConv::C, false, Callee, Args, DAG);
577 return CallInfo.first;
580 //===----------------------------------------------------------------------===//
582 //===----------------------------------------------------------------------===//
584 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
585 /// only uses types natively supported by the target.
587 /// Note that this is an involved process that may invalidate pointers into
589 void SelectionDAG::LegalizeTypes() {
590 if (ViewLegalizeTypesDAGs) viewGraph();
592 DAGTypeLegalizer(*this).run();