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/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/MathExtras.h"
25 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
26 cl::desc("Pop up a window to show dags before legalize types"));
28 static const bool ViewLegalizeTypesDAGs = 0;
33 /// run - This is the main entry point for the type legalizer. This does a
34 /// top-down traversal of the dag, legalizing types as it goes.
35 void DAGTypeLegalizer::run() {
36 // Create a dummy node (which is not added to allnodes), that adds a reference
37 // to the root node, preventing it from being deleted, and tracking any
38 // changes of the root.
39 HandleSDNode Dummy(DAG.getRoot());
41 // The root of the dag may dangle to deleted nodes until the type legalizer is
42 // done. Set it to null to avoid confusion.
43 DAG.setRoot(SDOperand());
45 // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
46 // (and remembering them) if they are leaves and assigning 'NewNode' if
48 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
49 E = DAG.allnodes_end(); I != E; ++I) {
50 if (I->getNumOperands() == 0) {
51 I->setNodeId(ReadyToProcess);
52 Worklist.push_back(I);
54 I->setNodeId(NewNode);
58 // Now that we have a set of nodes to process, handle them all.
59 while (!Worklist.empty()) {
60 SDNode *N = Worklist.back();
62 assert(N->getNodeId() == ReadyToProcess &&
63 "Node should be ready if on worklist!");
65 // Scan the values produced by the node, checking to see if any result
68 unsigned NumResults = N->getNumValues();
70 MVT::ValueType ResultVT = N->getValueType(i);
71 switch (getTypeAction(ResultVT)) {
73 assert(false && "Unknown action!");
83 FloatToIntResult(N, i);
86 ScalarizeResult(N, i);
92 } while (++i < NumResults);
94 // Scan the operand list for the node, handling any nodes with operands that
97 unsigned NumOperands = N->getNumOperands();
98 bool NeedsRevisit = false;
99 for (i = 0; i != NumOperands; ++i) {
100 MVT::ValueType OpVT = N->getOperand(i).getValueType();
101 switch (getTypeAction(OpVT)) {
103 assert(false && "Unknown action!");
107 NeedsRevisit = PromoteOperand(N, i);
110 NeedsRevisit = ExpandOperand(N, i);
113 NeedsRevisit = FloatToIntOperand(N, i);
116 NeedsRevisit = ScalarizeOperand(N, i);
119 NeedsRevisit = SplitOperand(N, i);
125 // If the node needs revisiting, don't add all users to the worklist etc.
129 if (i == NumOperands)
130 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
134 // If we reach here, the node was processed, potentially creating new nodes.
135 // Mark it as processed and add its users to the worklist as appropriate.
136 N->setNodeId(Processed);
138 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
140 SDNode *User = UI->getUser();
141 int NodeID = User->getNodeId();
142 assert(NodeID != ReadyToProcess && NodeID != Processed &&
143 "Invalid node id for user of unprocessed node!");
145 // This node has two options: it can either be a new node or its Node ID
146 // may be a count of the number of operands it has that are not ready.
148 User->setNodeId(NodeID-1);
150 // If this was the last use it was waiting on, add it to the ready list.
151 if (NodeID-1 == ReadyToProcess)
152 Worklist.push_back(User);
156 // Otherwise, this node is new: this is the first operand of it that
157 // became ready. Its new NodeID is the number of operands it has minus 1
158 // (as this node is now processed).
159 assert(NodeID == NewNode && "Unknown node ID!");
160 User->setNodeId(User->getNumOperands()-1);
162 // If the node only has a single operand, it is now ready.
163 if (User->getNumOperands() == 1)
164 Worklist.push_back(User);
168 // If the root changed (e.g. it was a dead load, update the root).
169 DAG.setRoot(Dummy.getValue());
173 // Remove dead nodes. This is important to do for cleanliness but also before
174 // the checking loop below. Implicit folding by the DAG.getNode operators can
175 // cause unreachable nodes to be around with their flags set to new.
176 DAG.RemoveDeadNodes();
178 // In a debug build, scan all the nodes to make sure we found them all. This
179 // ensures that there are no cycles and that everything got processed.
181 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
182 E = DAG.allnodes_end(); I != E; ++I) {
185 // Check that all result types are legal.
186 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
187 if (!isTypeLegal(I->getValueType(i))) {
188 cerr << "Result type " << i << " illegal!\n";
192 // Check that all operand types are legal.
193 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
194 if (!isTypeLegal(I->getOperand(i).getValueType())) {
195 cerr << "Operand type " << i << " illegal!\n";
199 if (I->getNodeId() != Processed) {
200 if (I->getNodeId() == NewNode)
201 cerr << "New node not 'noticed'?\n";
202 else if (I->getNodeId() > 0)
203 cerr << "Operand not processed?\n";
204 else if (I->getNodeId() == ReadyToProcess)
205 cerr << "Not added to worklist?\n";
210 I->dump(&DAG); cerr << "\n";
217 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
218 /// new nodes. Correct any processed operands (this may change the node) and
219 /// calculate the NodeId.
220 void DAGTypeLegalizer::AnalyzeNewNode(SDNode *&N) {
221 // If this was an existing node that is already done, we're done.
222 if (N->getNodeId() != NewNode)
225 // Okay, we know that this node is new. Recursively walk all of its operands
226 // to see if they are new also. The depth of this walk is bounded by the size
227 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
228 // about revisiting of nodes.
230 // As we walk the operands, keep track of the number of nodes that are
231 // processed. If non-zero, this will become the new nodeid of this node.
232 // Already processed operands may need to be remapped to the node that
233 // replaced them, which can result in our node changing. Since remapping
234 // is rare, the code tries to minimize overhead in the non-remapping case.
236 SmallVector<SDOperand, 8> NewOps;
237 unsigned NumProcessed = 0;
238 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
239 SDOperand OrigOp = N->getOperand(i);
240 SDOperand Op = OrigOp;
242 if (Op.Val->getNodeId() == Processed)
245 if (Op.Val->getNodeId() == NewNode)
246 AnalyzeNewNode(Op.Val);
247 else if (Op.Val->getNodeId() == Processed)
250 if (!NewOps.empty()) {
251 // Some previous operand changed. Add this one to the list.
252 NewOps.push_back(Op);
253 } else if (Op != OrigOp) {
254 // This is the first operand to change - add all operands so far.
255 for (unsigned j = 0; j < i; ++j)
256 NewOps.push_back(N->getOperand(j));
257 NewOps.push_back(Op);
261 // Some operands changed - update the node.
263 N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
265 N->setNodeId(N->getNumOperands()-NumProcessed);
266 if (N->getNodeId() == ReadyToProcess)
267 Worklist.push_back(N);
271 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
272 /// updates to nodes and recomputes their ready state.
273 class VISIBILITY_HIDDEN NodeUpdateListener :
274 public SelectionDAG::DAGUpdateListener {
275 DAGTypeLegalizer &DTL;
277 NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
279 virtual void NodeDeleted(SDNode *N) {
281 assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
282 N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
283 "RAUW deleted processed node!");
286 virtual void NodeUpdated(SDNode *N) {
287 // Node updates can mean pretty much anything. It is possible that an
288 // operand was set to something already processed (f.e.) in which case
289 // this node could become ready. Recompute its flags.
290 assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
291 N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
292 "RAUW updated processed node!");
293 DTL.ReanalyzeNode(N);
299 /// ReplaceValueWith - The specified value was legalized to the specified other
300 /// value. If they are different, update the DAG and NodeIDs replacing any uses
301 /// of From to use To instead.
302 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
303 if (From == To) return;
305 // If expansion produced new nodes, make sure they are properly marked.
306 AnalyzeNewNode(To.Val);
308 // Anything that used the old node should now use the new one. Note that this
309 // can potentially cause recursive merging.
310 NodeUpdateListener NUL(*this);
311 DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
313 // The old node may still be present in ExpandedNodes or PromotedNodes.
314 // Inform them about the replacement.
315 ReplacedNodes[From] = To;
318 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
319 /// node's results. The from and to node must define identical result types.
320 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
321 if (From == To) return;
323 // If expansion produced new nodes, make sure they are properly marked.
326 assert(From->getNumValues() == To->getNumValues() &&
327 "Node results don't match");
329 // Anything that used the old node should now use the new one. Note that this
330 // can potentially cause recursive merging.
331 NodeUpdateListener NUL(*this);
332 DAG.ReplaceAllUsesWith(From, To, &NUL);
334 // The old node may still be present in ExpandedNodes or PromotedNodes.
335 // Inform them about the replacement.
336 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
337 assert(From->getValueType(i) == To->getValueType(i) &&
338 "Node results don't match");
339 ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
344 /// RemapNode - If the specified value was already legalized to another value,
345 /// replace it by that value.
346 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
347 DenseMap<SDOperandImpl, SDOperand>::iterator I = ReplacedNodes.find(N);
348 if (I != ReplacedNodes.end()) {
349 // Use path compression to speed up future lookups if values get multiply
350 // replaced with other values.
351 RemapNode(I->second);
356 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
357 AnalyzeNewNode(Result.Val);
359 SDOperand &OpEntry = PromotedNodes[Op];
360 assert(OpEntry.Val == 0 && "Node is already promoted!");
364 void DAGTypeLegalizer::SetIntegerOp(SDOperand Op, SDOperand Result) {
365 AnalyzeNewNode(Result.Val);
367 SDOperand &OpEntry = FloatToIntedNodes[Op];
368 assert(OpEntry.Val == 0 && "Node is already converted to integer!");
372 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
373 AnalyzeNewNode(Result.Val);
375 SDOperand &OpEntry = ScalarizedNodes[Op];
376 assert(OpEntry.Val == 0 && "Node is already scalarized!");
380 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo,
382 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
383 RemapNode(Entry.first);
384 RemapNode(Entry.second);
385 assert(Entry.first.Val && "Operand isn't expanded");
390 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
391 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
392 AnalyzeNewNode(Lo.Val);
393 AnalyzeNewNode(Hi.Val);
395 // Remember that this is the result of the node.
396 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
397 assert(Entry.first.Val == 0 && "Node already expanded");
402 void DAGTypeLegalizer::GetSplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
403 std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
404 RemapNode(Entry.first);
405 RemapNode(Entry.second);
406 assert(Entry.first.Val && "Operand isn't split");
411 void DAGTypeLegalizer::SetSplitOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
412 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
413 AnalyzeNewNode(Lo.Val);
414 AnalyzeNewNode(Hi.Val);
416 // Remember that this is the result of the node.
417 std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
418 assert(Entry.first.Val == 0 && "Node already split");
424 /// BitConvertToInteger - Convert to an integer of the same size.
425 SDOperand DAGTypeLegalizer::BitConvertToInteger(SDOperand Op) {
426 return DAG.getNode(ISD::BIT_CONVERT,
427 MVT::getIntegerType(MVT::getSizeInBits(Op.getValueType())),
431 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
432 MVT::ValueType DestVT) {
433 // Create the stack frame object.
434 SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
436 // Emit a store to the stack slot.
437 SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
438 // Result is a load from the stack slot.
439 return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
442 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
443 SDOperand DAGTypeLegalizer::JoinIntegers(SDOperand Lo, SDOperand Hi) {
444 MVT::ValueType LVT = Lo.getValueType();
445 MVT::ValueType HVT = Hi.getValueType();
446 MVT::ValueType NVT = MVT::getIntegerType(MVT::getSizeInBits(LVT) +
447 MVT::getSizeInBits(HVT));
449 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
450 Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
451 Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(MVT::getSizeInBits(LVT),
452 TLI.getShiftAmountTy()));
453 return DAG.getNode(ISD::OR, NVT, Lo, Hi);
456 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
458 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
459 MVT::ValueType LoVT, MVT::ValueType HiVT,
460 SDOperand &Lo, SDOperand &Hi) {
461 assert(MVT::getSizeInBits(LoVT) + MVT::getSizeInBits(HiVT) ==
462 MVT::getSizeInBits(Op.getValueType()) && "Invalid integer splitting!");
463 Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
464 Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
465 DAG.getConstant(MVT::getSizeInBits(LoVT),
466 TLI.getShiftAmountTy()));
467 Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
470 /// SplitInteger - Return the lower and upper halves of Op's bits in a value type
471 /// half the size of Op's.
472 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
473 SDOperand &Lo, SDOperand &Hi) {
474 MVT::ValueType HalfVT =
475 MVT::getIntegerType(MVT::getSizeInBits(Op.getValueType())/2);
476 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
479 //===----------------------------------------------------------------------===//
481 //===----------------------------------------------------------------------===//
483 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
484 /// only uses types natively supported by the target.
486 /// Note that this is an involved process that may invalidate pointers into
488 void SelectionDAG::LegalizeTypes() {
489 if (ViewLegalizeTypesDAGs) viewGraph();
491 DAGTypeLegalizer(*this).run();