Update comments.
[llvm/msp430.git] / lib / CodeGen / SelectionDAG / LegalizeTypes.cpp
blob985d345956710662cc5ca19106977c1b395370da
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.
14 //===----------------------------------------------------------------------===//
16 #include "LegalizeTypes.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Target/TargetData.h"
21 using namespace llvm;
23 static cl::opt<bool>
24 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
26 /// PerformExpensiveChecks - Do extensive, expensive, sanity checking.
27 void DAGTypeLegalizer::PerformExpensiveChecks() {
28 // If a node is not processed, then none of its values should be mapped by any
29 // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
31 // If a node is processed, then each value with an illegal type must be mapped
32 // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
33 // Values with a legal type may be mapped by ReplacedValues, but not by any of
34 // the other maps.
36 // Note that these invariants may not hold momentarily when processing a node:
37 // the node being processed may be put in a map before being marked Processed.
39 // Note that it is possible to have nodes marked NewNode in the DAG. This can
40 // occur in two ways. Firstly, a node may be created during legalization but
41 // never passed to the legalization core. This is usually due to the implicit
42 // folding that occurs when using the DAG.getNode operators. Secondly, a new
43 // node may be passed to the legalization core, but when analyzed may morph
44 // into a different node, leaving the original node as a NewNode in the DAG.
45 // A node may morph if one of its operands changes during analysis. Whether
46 // it actually morphs or not depends on whether, after updating its operands,
47 // it is equivalent to an existing node: if so, it morphs into that existing
48 // node (CSE). An operand can change during analysis if the operand is a new
49 // node that morphs, or it is a processed value that was mapped to some other
50 // value (as recorded in ReplacedValues) in which case the operand is turned
51 // into that other value. If a node morphs then the node it morphed into will
52 // be used instead of it for legalization, however the original node continues
53 // to live on in the DAG.
54 // The conclusion is that though there may be nodes marked NewNode in the DAG,
55 // all uses of such nodes are also marked NewNode: the result is a fungus of
56 // NewNodes growing on top of the useful nodes, and perhaps using them, but
57 // not used by them.
59 // If a value is mapped by ReplacedValues, then it must have no uses, except
60 // by nodes marked NewNode (see above).
62 // The final node obtained by mapping by ReplacedValues is not marked NewNode.
63 // Note that ReplacedValues should be applied iteratively.
65 // Note that the ReplacedValues map may also map deleted nodes. By iterating
66 // over the DAG we only consider non-deleted nodes.
67 SmallVector<SDNode*, 16> NewNodes;
68 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
69 E = DAG.allnodes_end(); I != E; ++I) {
70 // Remember nodes marked NewNode - they are subject to extra checking below.
71 if (I->getNodeId() == NewNode)
72 NewNodes.push_back(I);
74 for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
75 SDValue Res(I, i);
76 bool Failed = false;
78 unsigned Mapped = 0;
79 if (ReplacedValues.find(Res) != ReplacedValues.end()) {
80 Mapped |= 1;
81 // Check that remapped values are only used by nodes marked NewNode.
82 for (SDNode::use_iterator UI = I->use_begin(), UE = I->use_end();
83 UI != UE; ++UI)
84 if (UI.getUse().getResNo() == i)
85 assert(UI->getNodeId() == NewNode &&
86 "Remapped value has non-trivial use!");
88 // Check that the final result of applying ReplacedValues is not
89 // marked NewNode.
90 SDValue NewVal = ReplacedValues[Res];
91 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
92 while (I != ReplacedValues.end()) {
93 NewVal = I->second;
94 I = ReplacedValues.find(NewVal);
96 assert(NewVal.getNode()->getNodeId() != NewNode &&
97 "ReplacedValues maps to a new node!");
99 if (PromotedIntegers.find(Res) != PromotedIntegers.end())
100 Mapped |= 2;
101 if (SoftenedFloats.find(Res) != SoftenedFloats.end())
102 Mapped |= 4;
103 if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
104 Mapped |= 8;
105 if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
106 Mapped |= 16;
107 if (ExpandedFloats.find(Res) != ExpandedFloats.end())
108 Mapped |= 32;
109 if (SplitVectors.find(Res) != SplitVectors.end())
110 Mapped |= 64;
111 if (WidenedVectors.find(Res) != WidenedVectors.end())
112 Mapped |= 128;
114 if (I->getNodeId() != Processed) {
115 if (Mapped != 0) {
116 cerr << "Unprocessed value in a map!";
117 Failed = true;
119 } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
120 // FIXME: Because of PR2957, the build vector can be placed on this
121 // list but if the associated vector shuffle is split, the build vector
122 // can also be split so we allow this to go through for now.
123 if (Mapped > 1 && Res.getOpcode() != ISD::BUILD_VECTOR) {
124 cerr << "Value with legal type was transformed!";
125 Failed = true;
127 } else {
128 if (Mapped == 0) {
129 cerr << "Processed value not in any map!";
130 Failed = true;
131 } else if (Mapped & (Mapped - 1)) {
132 cerr << "Value in multiple maps!";
133 Failed = true;
137 if (Failed) {
138 if (Mapped & 1)
139 cerr << " ReplacedValues";
140 if (Mapped & 2)
141 cerr << " PromotedIntegers";
142 if (Mapped & 4)
143 cerr << " SoftenedFloats";
144 if (Mapped & 8)
145 cerr << " ScalarizedVectors";
146 if (Mapped & 16)
147 cerr << " ExpandedIntegers";
148 if (Mapped & 32)
149 cerr << " ExpandedFloats";
150 if (Mapped & 64)
151 cerr << " SplitVectors";
152 if (Mapped & 128)
153 cerr << " WidenedVectors";
154 cerr << "\n";
155 abort();
160 // Checked that NewNodes are only used by other NewNodes.
161 for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
162 SDNode *N = NewNodes[i];
163 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
164 UI != UE; ++UI)
165 assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
169 /// run - This is the main entry point for the type legalizer. This does a
170 /// top-down traversal of the dag, legalizing types as it goes. Returns "true"
171 /// if it made any changes.
172 bool DAGTypeLegalizer::run() {
173 bool Changed = false;
175 // Create a dummy node (which is not added to allnodes), that adds a reference
176 // to the root node, preventing it from being deleted, and tracking any
177 // changes of the root.
178 HandleSDNode Dummy(DAG.getRoot());
179 Dummy.setNodeId(Unanalyzed);
181 // The root of the dag may dangle to deleted nodes until the type legalizer is
182 // done. Set it to null to avoid confusion.
183 DAG.setRoot(SDValue());
185 // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
186 // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
187 // non-leaves.
188 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
189 E = DAG.allnodes_end(); I != E; ++I) {
190 if (I->getNumOperands() == 0) {
191 I->setNodeId(ReadyToProcess);
192 Worklist.push_back(I);
193 } else {
194 I->setNodeId(Unanalyzed);
198 // Now that we have a set of nodes to process, handle them all.
199 while (!Worklist.empty()) {
200 #ifndef XDEBUG
201 if (EnableExpensiveChecks)
202 #endif
203 PerformExpensiveChecks();
205 SDNode *N = Worklist.back();
206 Worklist.pop_back();
207 assert(N->getNodeId() == ReadyToProcess &&
208 "Node should be ready if on worklist!");
210 if (IgnoreNodeResults(N))
211 goto ScanOperands;
213 // Scan the values produced by the node, checking to see if any result
214 // types are illegal.
215 for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
216 MVT ResultVT = N->getValueType(i);
217 switch (getTypeAction(ResultVT)) {
218 default:
219 assert(false && "Unknown action!");
220 case Legal:
221 break;
222 // The following calls must take care of *all* of the node's results,
223 // not just the illegal result they were passed (this includes results
224 // with a legal type). Results can be remapped using ReplaceValueWith,
225 // or their promoted/expanded/etc values registered in PromotedIntegers,
226 // ExpandedIntegers etc.
227 case PromoteInteger:
228 PromoteIntegerResult(N, i);
229 Changed = true;
230 goto NodeDone;
231 case ExpandInteger:
232 ExpandIntegerResult(N, i);
233 Changed = true;
234 goto NodeDone;
235 case SoftenFloat:
236 SoftenFloatResult(N, i);
237 Changed = true;
238 goto NodeDone;
239 case ExpandFloat:
240 ExpandFloatResult(N, i);
241 Changed = true;
242 goto NodeDone;
243 case ScalarizeVector:
244 ScalarizeVectorResult(N, i);
245 Changed = true;
246 goto NodeDone;
247 case SplitVector:
248 SplitVectorResult(N, i);
249 Changed = true;
250 goto NodeDone;
251 case WidenVector:
252 WidenVectorResult(N, i);
253 Changed = true;
254 goto NodeDone;
258 ScanOperands:
259 // Scan the operand list for the node, handling any nodes with operands that
260 // are illegal.
262 unsigned NumOperands = N->getNumOperands();
263 bool NeedsReanalyzing = false;
264 unsigned i;
265 for (i = 0; i != NumOperands; ++i) {
266 if (IgnoreNodeResults(N->getOperand(i).getNode()))
267 continue;
269 if (N->getOpcode() == ISD::VECTOR_SHUFFLE && i == 2) {
270 // The shuffle mask doesn't need to be a legal vector type.
271 // FIXME: We can remove this once we fix PR2957.
272 SetIgnoredNodeResult(N->getOperand(2).getNode());
273 continue;
276 MVT OpVT = N->getOperand(i).getValueType();
277 switch (getTypeAction(OpVT)) {
278 default:
279 assert(false && "Unknown action!");
280 case Legal:
281 continue;
282 // The following calls must either replace all of the node's results
283 // using ReplaceValueWith, and return "false"; or update the node's
284 // operands in place, and return "true".
285 case PromoteInteger:
286 NeedsReanalyzing = PromoteIntegerOperand(N, i);
287 Changed = true;
288 break;
289 case ExpandInteger:
290 NeedsReanalyzing = ExpandIntegerOperand(N, i);
291 Changed = true;
292 break;
293 case SoftenFloat:
294 NeedsReanalyzing = SoftenFloatOperand(N, i);
295 Changed = true;
296 break;
297 case ExpandFloat:
298 NeedsReanalyzing = ExpandFloatOperand(N, i);
299 Changed = true;
300 break;
301 case ScalarizeVector:
302 NeedsReanalyzing = ScalarizeVectorOperand(N, i);
303 Changed = true;
304 break;
305 case SplitVector:
306 NeedsReanalyzing = SplitVectorOperand(N, i);
307 Changed = true;
308 break;
309 case WidenVector:
310 NeedsReanalyzing = WidenVectorOperand(N, i);
311 Changed = true;
312 break;
314 break;
317 // The sub-method updated N in place. Check to see if any operands are new,
318 // and if so, mark them. If the node needs revisiting, don't add all users
319 // to the worklist etc.
320 if (NeedsReanalyzing) {
321 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
322 N->setNodeId(NewNode);
323 // Recompute the NodeId and correct processed operands, adding the node to
324 // the worklist if ready.
325 SDNode *M = AnalyzeNewNode(N);
326 if (M == N)
327 // The node didn't morph - nothing special to do, it will be revisited.
328 continue;
330 // The node morphed - this is equivalent to legalizing by replacing every
331 // value of N with the corresponding value of M. So do that now. However
332 // there is no need to remember the replacement - morphing will make sure
333 // it is never used non-trivially.
334 assert(N->getNumValues() == M->getNumValues() &&
335 "Node morphing changed the number of results!");
336 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
337 // Replacing the value takes care of remapping the new value. Do the
338 // replacement without recording it in ReplacedValues. This does not
339 // expunge From but that is fine - it is not really a new node.
340 ReplaceValueWithHelper(SDValue(N, i), SDValue(M, i));
341 assert(N->getNodeId() == NewNode && "Unexpected node state!");
342 // The node continues to live on as part of the NewNode fungus that
343 // grows on top of the useful nodes. Nothing more needs to be done
344 // with it - move on to the next node.
345 continue;
348 if (i == NumOperands) {
349 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
352 NodeDone:
354 // If we reach here, the node was processed, potentially creating new nodes.
355 // Mark it as processed and add its users to the worklist as appropriate.
356 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
357 N->setNodeId(Processed);
359 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
360 UI != E; ++UI) {
361 SDNode *User = *UI;
362 int NodeId = User->getNodeId();
364 // This node has two options: it can either be a new node or its Node ID
365 // may be a count of the number of operands it has that are not ready.
366 if (NodeId > 0) {
367 User->setNodeId(NodeId-1);
369 // If this was the last use it was waiting on, add it to the ready list.
370 if (NodeId-1 == ReadyToProcess)
371 Worklist.push_back(User);
372 continue;
375 // If this is an unreachable new node, then ignore it. If it ever becomes
376 // reachable by being used by a newly created node then it will be handled
377 // by AnalyzeNewNode.
378 if (NodeId == NewNode)
379 continue;
381 // Otherwise, this node is new: this is the first operand of it that
382 // became ready. Its new NodeId is the number of operands it has minus 1
383 // (as this node is now processed).
384 assert(NodeId == Unanalyzed && "Unknown node ID!");
385 User->setNodeId(User->getNumOperands() - 1);
387 // If the node only has a single operand, it is now ready.
388 if (User->getNumOperands() == 1)
389 Worklist.push_back(User);
393 #ifndef XDEBUG
394 if (EnableExpensiveChecks)
395 #endif
396 PerformExpensiveChecks();
398 // If the root changed (e.g. it was a dead load) update the root.
399 DAG.setRoot(Dummy.getValue());
401 // Remove dead nodes. This is important to do for cleanliness but also before
402 // the checking loop below. Implicit folding by the DAG.getNode operators and
403 // node morphing can cause unreachable nodes to be around with their flags set
404 // to new.
405 DAG.RemoveDeadNodes();
407 // In a debug build, scan all the nodes to make sure we found them all. This
408 // ensures that there are no cycles and that everything got processed.
409 #ifndef NDEBUG
410 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
411 E = DAG.allnodes_end(); I != E; ++I) {
412 bool Failed = false;
414 // Check that all result types are legal.
415 if (!IgnoreNodeResults(I))
416 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
417 if (!isTypeLegal(I->getValueType(i))) {
418 cerr << "Result type " << i << " illegal!\n";
419 Failed = true;
422 // Check that all operand types are legal.
423 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
424 if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
425 !isTypeLegal(I->getOperand(i).getValueType())) {
426 cerr << "Operand type " << i << " illegal!\n";
427 Failed = true;
430 if (I->getNodeId() != Processed) {
431 if (I->getNodeId() == NewNode)
432 cerr << "New node not analyzed?\n";
433 else if (I->getNodeId() == Unanalyzed)
434 cerr << "Unanalyzed node not noticed?\n";
435 else if (I->getNodeId() > 0)
436 cerr << "Operand not processed?\n";
437 else if (I->getNodeId() == ReadyToProcess)
438 cerr << "Not added to worklist?\n";
439 Failed = true;
442 if (Failed) {
443 I->dump(&DAG); cerr << "\n";
444 abort();
447 #endif
449 return Changed;
452 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
453 /// new nodes. Correct any processed operands (this may change the node) and
454 /// calculate the NodeId. If the node itself changes to a processed node, it
455 /// is not remapped - the caller needs to take care of this.
456 /// Returns the potentially changed node.
457 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
458 // If this was an existing node that is already done, we're done.
459 if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
460 return N;
462 // Remove any stale map entries.
463 ExpungeNode(N);
465 // Okay, we know that this node is new. Recursively walk all of its operands
466 // to see if they are new also. The depth of this walk is bounded by the size
467 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
468 // about revisiting of nodes.
470 // As we walk the operands, keep track of the number of nodes that are
471 // processed. If non-zero, this will become the new nodeid of this node.
472 // Operands may morph when they are analyzed. If so, the node will be
473 // updated after all operands have been analyzed. Since this is rare,
474 // the code tries to minimize overhead in the non-morphing case.
476 SmallVector<SDValue, 8> NewOps;
477 unsigned NumProcessed = 0;
478 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
479 SDValue OrigOp = N->getOperand(i);
480 SDValue Op = OrigOp;
482 AnalyzeNewValue(Op); // Op may morph.
484 if (Op.getNode()->getNodeId() == Processed)
485 ++NumProcessed;
487 if (!NewOps.empty()) {
488 // Some previous operand changed. Add this one to the list.
489 NewOps.push_back(Op);
490 } else if (Op != OrigOp) {
491 // This is the first operand to change - add all operands so far.
492 for (unsigned j = 0; j < i; ++j)
493 NewOps.push_back(N->getOperand(j));
494 NewOps.push_back(Op);
498 // Some operands changed - update the node.
499 if (!NewOps.empty()) {
500 SDNode *M = DAG.UpdateNodeOperands(SDValue(N, 0), &NewOps[0],
501 NewOps.size()).getNode();
502 if (M != N) {
503 // The node morphed into a different node. Normally for this to happen
504 // the original node would have to be marked NewNode. However this can
505 // in theory momentarily not be the case while ReplaceValueWith is doing
506 // its stuff. Mark the original node NewNode to help sanity checking.
507 N->setNodeId(NewNode);
508 if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
509 // It morphed into a previously analyzed node - nothing more to do.
510 return M;
512 // It morphed into a different new node. Do the equivalent of passing
513 // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
514 // to remap the operands, since they are the same as the operands we
515 // remapped above.
516 N = M;
517 ExpungeNode(N);
521 // Calculate the NodeId.
522 N->setNodeId(N->getNumOperands() - NumProcessed);
523 if (N->getNodeId() == ReadyToProcess)
524 Worklist.push_back(N);
526 return N;
529 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
530 /// If the node changes to a processed node, then remap it.
531 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
532 Val.setNode(AnalyzeNewNode(Val.getNode()));
533 if (Val.getNode()->getNodeId() == Processed)
534 // We were passed a processed node, or it morphed into one - remap it.
535 RemapValue(Val);
538 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
539 /// This can occur when a node is deleted then reallocated as a new node -
540 /// the mapping in ReplacedValues applies to the deleted node, not the new
541 /// one.
542 /// The only map that can have a deleted node as a source is ReplacedValues.
543 /// Other maps can have deleted nodes as targets, but since their looked-up
544 /// values are always immediately remapped using RemapValue, resulting in a
545 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
546 /// always performs correct mappings. In order to keep the mapping correct,
547 /// ExpungeNode should be called on any new nodes *before* adding them as
548 /// either source or target to ReplacedValues (which typically means calling
549 /// Expunge when a new node is first seen, since it may no longer be marked
550 /// NewNode by the time it is added to ReplacedValues).
551 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
552 if (N->getNodeId() != NewNode)
553 return;
555 // If N is not remapped by ReplacedValues then there is nothing to do.
556 unsigned i, e;
557 for (i = 0, e = N->getNumValues(); i != e; ++i)
558 if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
559 break;
561 if (i == e)
562 return;
564 // Remove N from all maps - this is expensive but rare.
566 for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
567 E = PromotedIntegers.end(); I != E; ++I) {
568 assert(I->first.getNode() != N);
569 RemapValue(I->second);
572 for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
573 E = SoftenedFloats.end(); I != E; ++I) {
574 assert(I->first.getNode() != N);
575 RemapValue(I->second);
578 for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
579 E = ScalarizedVectors.end(); I != E; ++I) {
580 assert(I->first.getNode() != N);
581 RemapValue(I->second);
584 for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
585 E = WidenedVectors.end(); I != E; ++I) {
586 assert(I->first.getNode() != N);
587 RemapValue(I->second);
590 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
591 I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
592 assert(I->first.getNode() != N);
593 RemapValue(I->second.first);
594 RemapValue(I->second.second);
597 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
598 I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
599 assert(I->first.getNode() != N);
600 RemapValue(I->second.first);
601 RemapValue(I->second.second);
604 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
605 I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
606 assert(I->first.getNode() != N);
607 RemapValue(I->second.first);
608 RemapValue(I->second.second);
611 for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
612 E = ReplacedValues.end(); I != E; ++I)
613 RemapValue(I->second);
615 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
616 ReplacedValues.erase(SDValue(N, i));
619 /// RemapValue - If the specified value was already legalized to another value,
620 /// replace it by that value.
621 void DAGTypeLegalizer::RemapValue(SDValue &N) {
622 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
623 if (I != ReplacedValues.end()) {
624 // Use path compression to speed up future lookups if values get multiply
625 // replaced with other values.
626 RemapValue(I->second);
627 N = I->second;
628 assert(N.getNode()->getNodeId() != NewNode && "Mapped to new node!");
632 namespace {
633 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
634 /// updates to nodes and recomputes their ready state.
635 class VISIBILITY_HIDDEN NodeUpdateListener :
636 public SelectionDAG::DAGUpdateListener {
637 DAGTypeLegalizer &DTL;
638 SmallSetVector<SDNode*, 16> &NodesToAnalyze;
639 public:
640 explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
641 SmallSetVector<SDNode*, 16> &nta)
642 : DTL(dtl), NodesToAnalyze(nta) {}
644 virtual void NodeDeleted(SDNode *N, SDNode *E) {
645 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
646 N->getNodeId() != DAGTypeLegalizer::Processed &&
647 "Invalid node ID for RAUW deletion!");
648 // It is possible, though rare, for the deleted node N to occur as a
649 // target in a map, so note the replacement N -> E in ReplacedValues.
650 assert(E && "Node not replaced?");
651 DTL.NoteDeletion(N, E);
653 // In theory the deleted node could also have been scheduled for analysis.
654 // So remove it from the set of nodes which will be analyzed.
655 NodesToAnalyze.remove(N);
657 // In general nothing needs to be done for E, since it didn't change but
658 // only gained new uses. However N -> E was just added to ReplacedValues,
659 // and the result of a ReplacedValues mapping is not allowed to be marked
660 // NewNode. So if E is marked NewNode, then it needs to be analyzed.
661 if (E->getNodeId() == DAGTypeLegalizer::NewNode)
662 NodesToAnalyze.insert(E);
665 virtual void NodeUpdated(SDNode *N) {
666 // Node updates can mean pretty much anything. It is possible that an
667 // operand was set to something already processed (f.e.) in which case
668 // this node could become ready. Recompute its flags.
669 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
670 N->getNodeId() != DAGTypeLegalizer::Processed &&
671 "Invalid node ID for RAUW deletion!");
672 N->setNodeId(DAGTypeLegalizer::NewNode);
673 NodesToAnalyze.insert(N);
679 /// ReplaceValueWithHelper - Internal helper for ReplaceValueWith. Updates the
680 /// DAG causing any uses of From to use To instead, but without expunging From
681 /// or recording the replacement in ReplacedValues. Do not call directly unless
682 /// you really know what you are doing!
683 void DAGTypeLegalizer::ReplaceValueWithHelper(SDValue From, SDValue To) {
684 assert(From.getNode() != To.getNode() && "Potential legalization loop!");
686 // If expansion produced new nodes, make sure they are properly marked.
687 AnalyzeNewValue(To); // Expunges To.
689 // Anything that used the old node should now use the new one. Note that this
690 // can potentially cause recursive merging.
691 SmallSetVector<SDNode*, 16> NodesToAnalyze;
692 NodeUpdateListener NUL(*this, NodesToAnalyze);
693 DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
695 // Process the list of nodes that need to be reanalyzed.
696 while (!NodesToAnalyze.empty()) {
697 SDNode *N = NodesToAnalyze.back();
698 NodesToAnalyze.pop_back();
699 if (N->getNodeId() != DAGTypeLegalizer::NewNode)
700 // The node was analyzed while reanalyzing an earlier node - it is safe to
701 // skip. Note that this is not a morphing node - otherwise it would still
702 // be marked NewNode.
703 continue;
705 // Analyze the node's operands and recalculate the node ID.
706 SDNode *M = AnalyzeNewNode(N);
707 if (M != N) {
708 // The node morphed into a different node. Make everyone use the new node
709 // instead.
710 assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
711 assert(N->getNumValues() == M->getNumValues() &&
712 "Node morphing changed the number of results!");
713 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
714 SDValue OldVal(N, i);
715 SDValue NewVal(M, i);
716 if (M->getNodeId() == Processed)
717 RemapValue(NewVal);
718 DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal, &NUL);
720 // The original node continues to exist in the DAG, marked NewNode.
725 /// ReplaceValueWith - The specified value was legalized to the specified other
726 /// value. Update the DAG and NodeIds replacing any uses of From to use To
727 /// instead.
728 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
729 assert(From.getNode()->getNodeId() == ReadyToProcess &&
730 "Only the node being processed may be remapped!");
732 // If expansion produced new nodes, make sure they are properly marked.
733 ExpungeNode(From.getNode());
734 AnalyzeNewValue(To); // Expunges To.
736 // The old node may still be present in a map like ExpandedIntegers or
737 // PromotedIntegers. Inform maps about the replacement.
738 ReplacedValues[From] = To;
740 // Do the replacement.
741 ReplaceValueWithHelper(From, To);
744 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
745 AnalyzeNewValue(Result);
747 SDValue &OpEntry = PromotedIntegers[Op];
748 assert(OpEntry.getNode() == 0 && "Node is already promoted!");
749 OpEntry = Result;
752 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
753 AnalyzeNewValue(Result);
755 SDValue &OpEntry = SoftenedFloats[Op];
756 assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
757 OpEntry = Result;
760 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
761 AnalyzeNewValue(Result);
763 SDValue &OpEntry = ScalarizedVectors[Op];
764 assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
765 OpEntry = Result;
768 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
769 SDValue &Hi) {
770 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
771 RemapValue(Entry.first);
772 RemapValue(Entry.second);
773 assert(Entry.first.getNode() && "Operand isn't expanded");
774 Lo = Entry.first;
775 Hi = Entry.second;
778 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
779 SDValue Hi) {
780 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
781 AnalyzeNewValue(Lo);
782 AnalyzeNewValue(Hi);
784 // Remember that this is the result of the node.
785 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
786 assert(Entry.first.getNode() == 0 && "Node already expanded");
787 Entry.first = Lo;
788 Entry.second = Hi;
791 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
792 SDValue &Hi) {
793 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
794 RemapValue(Entry.first);
795 RemapValue(Entry.second);
796 assert(Entry.first.getNode() && "Operand isn't expanded");
797 Lo = Entry.first;
798 Hi = Entry.second;
801 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
802 SDValue Hi) {
803 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
804 AnalyzeNewValue(Lo);
805 AnalyzeNewValue(Hi);
807 // Remember that this is the result of the node.
808 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
809 assert(Entry.first.getNode() == 0 && "Node already expanded");
810 Entry.first = Lo;
811 Entry.second = Hi;
814 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
815 SDValue &Hi) {
816 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
817 RemapValue(Entry.first);
818 RemapValue(Entry.second);
819 assert(Entry.first.getNode() && "Operand isn't split");
820 Lo = Entry.first;
821 Hi = Entry.second;
824 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
825 SDValue Hi) {
826 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
827 AnalyzeNewValue(Lo);
828 AnalyzeNewValue(Hi);
830 // Remember that this is the result of the node.
831 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
832 assert(Entry.first.getNode() == 0 && "Node already split");
833 Entry.first = Lo;
834 Entry.second = Hi;
837 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
838 AnalyzeNewValue(Result);
840 SDValue &OpEntry = WidenedVectors[Op];
841 assert(OpEntry.getNode() == 0 && "Node already widened!");
842 OpEntry = Result;
845 // Set to ignore result
846 void DAGTypeLegalizer::SetIgnoredNodeResult(SDNode* N) {
847 IgnoredNodesResultsSet.insert(N);
850 //===----------------------------------------------------------------------===//
851 // Utilities.
852 //===----------------------------------------------------------------------===//
854 /// BitConvertToInteger - Convert to an integer of the same size.
855 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
856 unsigned BitWidth = Op.getValueType().getSizeInBits();
857 return DAG.getNode(ISD::BIT_CONVERT, Op.getDebugLoc(),
858 MVT::getIntegerVT(BitWidth), Op);
861 /// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
862 /// same size.
863 SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
864 assert(Op.getValueType().isVector() && "Only applies to vectors!");
865 unsigned EltWidth = Op.getValueType().getVectorElementType().getSizeInBits();
866 MVT EltNVT = MVT::getIntegerVT(EltWidth);
867 unsigned NumElts = Op.getValueType().getVectorNumElements();
868 return DAG.getNode(ISD::BIT_CONVERT, Op.getDebugLoc(),
869 MVT::getVectorVT(EltNVT, NumElts), Op);
872 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
873 MVT DestVT) {
874 DebugLoc dl = Op.getDebugLoc();
875 // Create the stack frame object. Make sure it is aligned for both
876 // the source and destination types.
877 SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
878 // Emit a store to the stack slot.
879 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr, NULL, 0);
880 // Result is a load from the stack slot.
881 return DAG.getLoad(DestVT, dl, Store, StackPtr, NULL, 0);
884 /// CustomLowerResults - Replace the node's results with custom code provided
885 /// by the target and return "true", or do nothing and return "false".
886 /// The last parameter is FALSE if we are dealing with a node with legal
887 /// result types and illegal operand. The second parameter denotes the type of
888 /// illegal OperandNo in that case.
889 /// The last parameter being TRUE means we are dealing with a
890 /// node with illegal result types. The second parameter denotes the type of
891 /// illegal ResNo in that case.
892 bool DAGTypeLegalizer::CustomLowerResults(SDNode *N, MVT VT,
893 bool LegalizeResult) {
894 // See if the target wants to custom lower this node.
895 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
896 return false;
898 SmallVector<SDValue, 8> Results;
899 if (LegalizeResult)
900 TLI.ReplaceNodeResults(N, Results, DAG);
901 else
902 TLI.LowerOperationWrapper(N, Results, DAG);
904 if (Results.empty())
905 // The target didn't want to custom lower it after all.
906 return false;
908 // Make everything that once used N's values now use those in Results instead.
909 assert(Results.size() == N->getNumValues() &&
910 "Custom lowering returned the wrong number of results!");
911 for (unsigned i = 0, e = Results.size(); i != e; ++i)
912 ReplaceValueWith(SDValue(N, i), Results[i]);
913 return true;
916 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
917 /// which is split into two not necessarily identical pieces.
918 void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT, MVT &LoVT, MVT &HiVT) {
919 if (!InVT.isVector()) {
920 LoVT = HiVT = TLI.getTypeToTransformTo(InVT);
921 } else {
922 MVT NewEltVT = InVT.getVectorElementType();
923 unsigned NumElements = InVT.getVectorNumElements();
924 if ((NumElements & (NumElements-1)) == 0) { // Simple power of two vector.
925 NumElements >>= 1;
926 LoVT = HiVT = MVT::getVectorVT(NewEltVT, NumElements);
927 } else { // Non-power-of-two vectors.
928 unsigned NewNumElts_Lo = 1 << Log2_32(NumElements);
929 unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
930 LoVT = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
931 HiVT = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
936 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, MVT EltVT,
937 SDValue Index) {
938 DebugLoc dl = Index.getDebugLoc();
939 // Make sure the index type is big enough to compute in.
940 if (Index.getValueType().bitsGT(TLI.getPointerTy()))
941 Index = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Index);
942 else
943 Index = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Index);
945 // Calculate the element offset and add it to the pointer.
946 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
948 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
949 DAG.getConstant(EltSize, Index.getValueType()));
950 return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr);
953 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
954 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
955 // Arbitrarily use dlHi for result DebugLoc
956 DebugLoc dlHi = Hi.getDebugLoc();
957 DebugLoc dlLo = Lo.getDebugLoc();
958 MVT LVT = Lo.getValueType();
959 MVT HVT = Hi.getValueType();
960 MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
962 Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
963 Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
964 Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
965 DAG.getConstant(LVT.getSizeInBits(), TLI.getPointerTy()));
966 return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
969 /// LibCallify - Convert the node into a libcall with the same prototype.
970 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
971 bool isSigned) {
972 unsigned NumOps = N->getNumOperands();
973 DebugLoc dl = N->getDebugLoc();
974 if (NumOps == 0) {
975 return MakeLibCall(LC, N->getValueType(0), 0, 0, isSigned, dl);
976 } else if (NumOps == 1) {
977 SDValue Op = N->getOperand(0);
978 return MakeLibCall(LC, N->getValueType(0), &Op, 1, isSigned, dl);
979 } else if (NumOps == 2) {
980 SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
981 return MakeLibCall(LC, N->getValueType(0), Ops, 2, isSigned, dl);
983 SmallVector<SDValue, 8> Ops(NumOps);
984 for (unsigned i = 0; i < NumOps; ++i)
985 Ops[i] = N->getOperand(i);
987 return MakeLibCall(LC, N->getValueType(0), &Ops[0], NumOps, isSigned, dl);
990 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
991 /// returning a result of type RetVT.
992 SDValue DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
993 const SDValue *Ops, unsigned NumOps,
994 bool isSigned, DebugLoc dl) {
995 TargetLowering::ArgListTy Args;
996 Args.reserve(NumOps);
998 TargetLowering::ArgListEntry Entry;
999 for (unsigned i = 0; i != NumOps; ++i) {
1000 Entry.Node = Ops[i];
1001 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
1002 Entry.isSExt = isSigned;
1003 Entry.isZExt = !isSigned;
1004 Args.push_back(Entry);
1006 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1007 TLI.getPointerTy());
1009 const Type *RetTy = RetVT.getTypeForMVT();
1010 std::pair<SDValue,SDValue> CallInfo =
1011 TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
1012 false, CallingConv::C, false, Callee, Args, DAG, dl);
1013 return CallInfo.first;
1016 /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
1017 /// of the given type. A target boolean is an integer value, not necessarily of
1018 /// type i1, the bits of which conform to getBooleanContents.
1019 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, MVT VT) {
1020 DebugLoc dl = Bool.getDebugLoc();
1021 ISD::NodeType ExtendCode;
1022 switch (TLI.getBooleanContents()) {
1023 default:
1024 assert(false && "Unknown BooleanContent!");
1025 case TargetLowering::UndefinedBooleanContent:
1026 // Extend to VT by adding rubbish bits.
1027 ExtendCode = ISD::ANY_EXTEND;
1028 break;
1029 case TargetLowering::ZeroOrOneBooleanContent:
1030 // Extend to VT by adding zero bits.
1031 ExtendCode = ISD::ZERO_EXTEND;
1032 break;
1033 case TargetLowering::ZeroOrNegativeOneBooleanContent: {
1034 // Extend to VT by copying the sign bit.
1035 ExtendCode = ISD::SIGN_EXTEND;
1036 break;
1039 return DAG.getNode(ExtendCode, dl, VT, Bool);
1042 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
1043 /// bits in Hi.
1044 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1045 MVT LoVT, MVT HiVT,
1046 SDValue &Lo, SDValue &Hi) {
1047 DebugLoc dl = Op.getDebugLoc();
1048 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1049 Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
1050 Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
1051 Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
1052 DAG.getConstant(LoVT.getSizeInBits(), TLI.getPointerTy()));
1053 Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
1056 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
1057 /// type half the size of Op's.
1058 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1059 SDValue &Lo, SDValue &Hi) {
1060 MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
1061 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1065 //===----------------------------------------------------------------------===//
1066 // Entry Point
1067 //===----------------------------------------------------------------------===//
1069 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1070 /// only uses types natively supported by the target. Returns "true" if it made
1071 /// any changes.
1073 /// Note that this is an involved process that may invalidate pointers into
1074 /// the graph.
1075 bool SelectionDAG::LegalizeTypes() {
1076 return DAGTypeLegalizer(*this).run();