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/ADT/SetVector.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Target/TargetData.h"
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
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
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) {
79 if (ReplacedValues.find(Res) != ReplacedValues.end()) {
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();
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
90 SDValue NewVal = ReplacedValues[Res];
91 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
92 while (I != ReplacedValues.end()) {
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())
101 if (SoftenedFloats.find(Res) != SoftenedFloats.end())
103 if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
105 if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
107 if (ExpandedFloats.find(Res) != ExpandedFloats.end())
109 if (SplitVectors.find(Res) != SplitVectors.end())
111 if (WidenedVectors.find(Res) != WidenedVectors.end())
114 if (I->getNodeId() != Processed) {
116 cerr << "Unprocessed value in a map!";
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!";
129 cerr << "Processed value not in any map!";
131 } else if (Mapped & (Mapped - 1)) {
132 cerr << "Value in multiple maps!";
139 cerr << " ReplacedValues";
141 cerr << " PromotedIntegers";
143 cerr << " SoftenedFloats";
145 cerr << " ScalarizedVectors";
147 cerr << " ExpandedIntegers";
149 cerr << " ExpandedFloats";
151 cerr << " SplitVectors";
153 cerr << " WidenedVectors";
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();
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
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);
194 I->setNodeId(Unanalyzed);
198 // Now that we have a set of nodes to process, handle them all.
199 while (!Worklist.empty()) {
201 if (EnableExpensiveChecks)
203 PerformExpensiveChecks();
205 SDNode *N = Worklist.back();
207 assert(N->getNodeId() == ReadyToProcess &&
208 "Node should be ready if on worklist!");
210 if (IgnoreNodeResults(N))
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)) {
219 assert(false && "Unknown action!");
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.
228 PromoteIntegerResult(N, i);
232 ExpandIntegerResult(N, i);
236 SoftenFloatResult(N, i);
240 ExpandFloatResult(N, i);
243 case ScalarizeVector:
244 ScalarizeVectorResult(N, i);
248 SplitVectorResult(N, i);
252 WidenVectorResult(N, i);
259 // Scan the operand list for the node, handling any nodes with operands that
262 unsigned NumOperands = N->getNumOperands();
263 bool NeedsReanalyzing = false;
265 for (i = 0; i != NumOperands; ++i) {
266 if (IgnoreNodeResults(N->getOperand(i).getNode()))
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());
276 MVT OpVT = N->getOperand(i).getValueType();
277 switch (getTypeAction(OpVT)) {
279 assert(false && "Unknown action!");
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".
286 NeedsReanalyzing = PromoteIntegerOperand(N, i);
290 NeedsReanalyzing = ExpandIntegerOperand(N, i);
294 NeedsReanalyzing = SoftenFloatOperand(N, i);
298 NeedsReanalyzing = ExpandFloatOperand(N, i);
301 case ScalarizeVector:
302 NeedsReanalyzing = ScalarizeVectorOperand(N, i);
306 NeedsReanalyzing = SplitVectorOperand(N, i);
310 NeedsReanalyzing = WidenVectorOperand(N, i);
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);
327 // The node didn't morph - nothing special to do, it will be revisited.
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.
332 N->setNodeId(ReadyToProcess);
333 assert(N->getNumValues() == M->getNumValues() &&
334 "Node morphing changed the number of results!");
335 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
336 // Replacing the value takes care of remapping the new value.
337 ReplaceValueWith(SDValue(N, i), SDValue(M, i));
341 if (i == NumOperands) {
342 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
347 // If we reach here, the node was processed, potentially creating new nodes.
348 // Mark it as processed and add its users to the worklist as appropriate.
349 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
350 N->setNodeId(Processed);
352 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
355 int NodeId = User->getNodeId();
357 // This node has two options: it can either be a new node or its Node ID
358 // may be a count of the number of operands it has that are not ready.
360 User->setNodeId(NodeId-1);
362 // If this was the last use it was waiting on, add it to the ready list.
363 if (NodeId-1 == ReadyToProcess)
364 Worklist.push_back(User);
368 // If this is an unreachable new node, then ignore it. If it ever becomes
369 // reachable by being used by a newly created node then it will be handled
370 // by AnalyzeNewNode.
371 if (NodeId == NewNode)
374 // Otherwise, this node is new: this is the first operand of it that
375 // became ready. Its new NodeId is the number of operands it has minus 1
376 // (as this node is now processed).
377 assert(NodeId == Unanalyzed && "Unknown node ID!");
378 User->setNodeId(User->getNumOperands() - 1);
380 // If the node only has a single operand, it is now ready.
381 if (User->getNumOperands() == 1)
382 Worklist.push_back(User);
387 if (EnableExpensiveChecks)
389 PerformExpensiveChecks();
391 // If the root changed (e.g. it was a dead load) update the root.
392 DAG.setRoot(Dummy.getValue());
394 // Remove dead nodes. This is important to do for cleanliness but also before
395 // the checking loop below. Implicit folding by the DAG.getNode operators and
396 // node morphing can cause unreachable nodes to be around with their flags set
398 DAG.RemoveDeadNodes();
400 // In a debug build, scan all the nodes to make sure we found them all. This
401 // ensures that there are no cycles and that everything got processed.
403 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
404 E = DAG.allnodes_end(); I != E; ++I) {
407 // Check that all result types are legal.
408 if (!IgnoreNodeResults(I))
409 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
410 if (!isTypeLegal(I->getValueType(i))) {
411 cerr << "Result type " << i << " illegal!\n";
415 // Check that all operand types are legal.
416 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
417 if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
418 !isTypeLegal(I->getOperand(i).getValueType())) {
419 cerr << "Operand type " << i << " illegal!\n";
423 if (I->getNodeId() != Processed) {
424 if (I->getNodeId() == NewNode)
425 cerr << "New node not analyzed?\n";
426 else if (I->getNodeId() == Unanalyzed)
427 cerr << "Unanalyzed node not noticed?\n";
428 else if (I->getNodeId() > 0)
429 cerr << "Operand not processed?\n";
430 else if (I->getNodeId() == ReadyToProcess)
431 cerr << "Not added to worklist?\n";
436 I->dump(&DAG); cerr << "\n";
445 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
446 /// new nodes. Correct any processed operands (this may change the node) and
447 /// calculate the NodeId. If the node itself changes to a processed node, it
448 /// is not remapped - the caller needs to take care of this.
449 /// Returns the potentially changed node.
450 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
451 // If this was an existing node that is already done, we're done.
452 if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
455 // Remove any stale map entries.
458 // Okay, we know that this node is new. Recursively walk all of its operands
459 // to see if they are new also. The depth of this walk is bounded by the size
460 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
461 // about revisiting of nodes.
463 // As we walk the operands, keep track of the number of nodes that are
464 // processed. If non-zero, this will become the new nodeid of this node.
465 // Operands may morph when they are analyzed. If so, the node will be
466 // updated after all operands have been analyzed. Since this is rare,
467 // the code tries to minimize overhead in the non-morphing case.
469 SmallVector<SDValue, 8> NewOps;
470 unsigned NumProcessed = 0;
471 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
472 SDValue OrigOp = N->getOperand(i);
475 AnalyzeNewValue(Op); // Op may morph.
477 if (Op.getNode()->getNodeId() == Processed)
480 if (!NewOps.empty()) {
481 // Some previous operand changed. Add this one to the list.
482 NewOps.push_back(Op);
483 } else if (Op != OrigOp) {
484 // This is the first operand to change - add all operands so far.
485 for (unsigned j = 0; j < i; ++j)
486 NewOps.push_back(N->getOperand(j));
487 NewOps.push_back(Op);
491 // Some operands changed - update the node.
492 if (!NewOps.empty()) {
493 SDNode *M = DAG.UpdateNodeOperands(SDValue(N, 0), &NewOps[0],
494 NewOps.size()).getNode();
496 // The node morphed into a different node. Normally for this to happen
497 // the original node would have to be marked NewNode. However this can
498 // in theory momentarily not be the case while ReplaceValueWith is doing
499 // its stuff. Mark the original node NewNode to help sanity checking.
500 N->setNodeId(NewNode);
501 if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
502 // It morphed into a previously analyzed node - nothing more to do.
505 // It morphed into a different new node. Do the equivalent of passing
506 // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
507 // to remap the operands, since they are the same as the operands we
514 // Calculate the NodeId.
515 N->setNodeId(N->getNumOperands() - NumProcessed);
516 if (N->getNodeId() == ReadyToProcess)
517 Worklist.push_back(N);
522 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
523 /// If the node changes to a processed node, then remap it.
524 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
525 Val.setNode(AnalyzeNewNode(Val.getNode()));
526 if (Val.getNode()->getNodeId() == Processed)
527 // We were passed a processed node, or it morphed into one - remap it.
531 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
532 /// This can occur when a node is deleted then reallocated as a new node -
533 /// the mapping in ReplacedValues applies to the deleted node, not the new
535 /// The only map that can have a deleted node as a source is ReplacedValues.
536 /// Other maps can have deleted nodes as targets, but since their looked-up
537 /// values are always immediately remapped using RemapValue, resulting in a
538 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
539 /// always performs correct mappings. In order to keep the mapping correct,
540 /// ExpungeNode should be called on any new nodes *before* adding them as
541 /// either source or target to ReplacedValues (which typically means calling
542 /// Expunge when a new node is first seen, since it may no longer be marked
543 /// NewNode by the time it is added to ReplacedValues).
544 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
545 if (N->getNodeId() != NewNode)
548 // If N is not remapped by ReplacedValues then there is nothing to do.
550 for (i = 0, e = N->getNumValues(); i != e; ++i)
551 if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
557 // Remove N from all maps - this is expensive but rare.
559 for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
560 E = PromotedIntegers.end(); I != E; ++I) {
561 assert(I->first.getNode() != N);
562 RemapValue(I->second);
565 for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
566 E = SoftenedFloats.end(); I != E; ++I) {
567 assert(I->first.getNode() != N);
568 RemapValue(I->second);
571 for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
572 E = ScalarizedVectors.end(); I != E; ++I) {
573 assert(I->first.getNode() != N);
574 RemapValue(I->second);
577 for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
578 E = WidenedVectors.end(); I != E; ++I) {
579 assert(I->first.getNode() != N);
580 RemapValue(I->second);
583 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
584 I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
585 assert(I->first.getNode() != N);
586 RemapValue(I->second.first);
587 RemapValue(I->second.second);
590 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
591 I = ExpandedFloats.begin(), E = ExpandedFloats.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 = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
599 assert(I->first.getNode() != N);
600 RemapValue(I->second.first);
601 RemapValue(I->second.second);
604 for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
605 E = ReplacedValues.end(); I != E; ++I)
606 RemapValue(I->second);
608 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
609 ReplacedValues.erase(SDValue(N, i));
612 /// RemapValue - If the specified value was already legalized to another value,
613 /// replace it by that value.
614 void DAGTypeLegalizer::RemapValue(SDValue &N) {
615 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
616 if (I != ReplacedValues.end()) {
617 // Use path compression to speed up future lookups if values get multiply
618 // replaced with other values.
619 RemapValue(I->second);
621 assert(N.getNode()->getNodeId() != NewNode && "Mapped to new node!");
626 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
627 /// updates to nodes and recomputes their ready state.
628 class VISIBILITY_HIDDEN NodeUpdateListener :
629 public SelectionDAG::DAGUpdateListener {
630 DAGTypeLegalizer &DTL;
631 SmallSetVector<SDNode*, 16> &NodesToAnalyze;
633 explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
634 SmallSetVector<SDNode*, 16> &nta)
635 : DTL(dtl), NodesToAnalyze(nta) {}
637 virtual void NodeDeleted(SDNode *N, SDNode *E) {
638 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
639 N->getNodeId() != DAGTypeLegalizer::Processed &&
640 "Invalid node ID for RAUW deletion!");
641 // It is possible, though rare, for the deleted node N to occur as a
642 // target in a map, so note the replacement N -> E in ReplacedValues.
643 assert(E && "Node not replaced?");
644 DTL.NoteDeletion(N, E);
646 // In theory the deleted node could also have been scheduled for analysis.
647 // So add it to the set of nodes which will not be analyzed.
648 NodesToAnalyze.remove(N);
650 // In general nothing needs to be done for E, since it didn't change but
651 // only gained new uses. However N -> E was just added to ReplacedValues,
652 // and the result of a ReplacedValues mapping is not allowed to be marked
653 // NewNode. So if E is marked NewNode, then it needs to be analyzed.
654 if (E->getNodeId() == DAGTypeLegalizer::NewNode)
655 NodesToAnalyze.insert(E);
658 virtual void NodeUpdated(SDNode *N) {
659 // Node updates can mean pretty much anything. It is possible that an
660 // operand was set to something already processed (f.e.) in which case
661 // this node could become ready. Recompute its flags.
662 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
663 N->getNodeId() != DAGTypeLegalizer::Processed &&
664 "Invalid node ID for RAUW deletion!");
665 NodesToAnalyze.insert(N);
671 /// ReplaceValueWith - The specified value was legalized to the specified other
672 /// value. Update the DAG and NodeIds replacing any uses of From to use To
674 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
675 assert(From.getNode()->getNodeId() == ReadyToProcess &&
676 "Only the node being processed may be remapped!");
677 assert(From.getNode() != To.getNode() && "Potential legalization loop!");
679 // If expansion produced new nodes, make sure they are properly marked.
680 ExpungeNode(From.getNode());
681 AnalyzeNewValue(To); // Expunges To.
683 // Anything that used the old node should now use the new one. Note that this
684 // can potentially cause recursive merging.
685 SmallSetVector<SDNode*, 16> NodesToAnalyze;
686 NodeUpdateListener NUL(*this, NodesToAnalyze);
687 DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
689 // The old node may still be present in a map like ExpandedIntegers or
690 // PromotedIntegers. Inform maps about the replacement.
691 ReplacedValues[From] = To;
693 // Process the list of nodes that need to be reanalyzed.
694 while (!NodesToAnalyze.empty()) {
695 SDNode *N = NodesToAnalyze.back();
696 NodesToAnalyze.pop_back();
698 // Analyze the node's operands and recalculate the node ID.
699 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
700 N->getNodeId() != DAGTypeLegalizer::Processed &&
701 "Invalid node ID for RAUW analysis!");
702 N->setNodeId(NewNode);
703 SDNode *M = AnalyzeNewNode(N);
705 // The node morphed into a different node. Make everyone use the new node
707 assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
708 assert(N->getNumValues() == M->getNumValues() &&
709 "Node morphing changed the number of results!");
710 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
711 SDValue OldVal(N, i);
712 SDValue NewVal(M, i);
713 if (M->getNodeId() == Processed)
715 DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal, &NUL);
717 // The original node continues to exist in the DAG, marked NewNode.
722 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
723 AnalyzeNewValue(Result);
725 SDValue &OpEntry = PromotedIntegers[Op];
726 assert(OpEntry.getNode() == 0 && "Node is already promoted!");
730 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
731 AnalyzeNewValue(Result);
733 SDValue &OpEntry = SoftenedFloats[Op];
734 assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
738 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
739 AnalyzeNewValue(Result);
741 SDValue &OpEntry = ScalarizedVectors[Op];
742 assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
746 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
748 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
749 RemapValue(Entry.first);
750 RemapValue(Entry.second);
751 assert(Entry.first.getNode() && "Operand isn't expanded");
756 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
758 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
762 // Remember that this is the result of the node.
763 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
764 assert(Entry.first.getNode() == 0 && "Node already expanded");
769 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
771 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
772 RemapValue(Entry.first);
773 RemapValue(Entry.second);
774 assert(Entry.first.getNode() && "Operand isn't expanded");
779 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
781 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
785 // Remember that this is the result of the node.
786 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
787 assert(Entry.first.getNode() == 0 && "Node already expanded");
792 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
794 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
795 RemapValue(Entry.first);
796 RemapValue(Entry.second);
797 assert(Entry.first.getNode() && "Operand isn't split");
802 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
804 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
808 // Remember that this is the result of the node.
809 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
810 assert(Entry.first.getNode() == 0 && "Node already split");
815 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
816 AnalyzeNewValue(Result);
818 SDValue &OpEntry = WidenedVectors[Op];
819 assert(OpEntry.getNode() == 0 && "Node already widened!");
823 // Set to ignore result
824 void DAGTypeLegalizer::SetIgnoredNodeResult(SDNode* N) {
825 IgnoredNodesResultsSet.insert(N);
828 //===----------------------------------------------------------------------===//
830 //===----------------------------------------------------------------------===//
832 /// BitConvertToInteger - Convert to an integer of the same size.
833 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
834 unsigned BitWidth = Op.getValueType().getSizeInBits();
835 return DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerVT(BitWidth), Op);
838 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
840 // Create the stack frame object. Make sure it is aligned for both
841 // the source and destination types.
842 SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
843 // Emit a store to the stack slot.
844 SDValue Store = DAG.getStore(DAG.getEntryNode(), Op, StackPtr, NULL, 0);
845 // Result is a load from the stack slot.
846 return DAG.getLoad(DestVT, Store, StackPtr, NULL, 0);
849 /// CustomLowerResults - Replace the node's results with custom code provided
850 /// by the target and return "true", or do nothing and return "false".
851 /// The last parameter is FALSE if we are dealing with a node with legal
852 /// result types and illegal operand. The second parameter denotes the illegal
853 /// OperandNo in that case.
854 /// The last parameter being TRUE means we are dealing with a
855 /// node with illegal result types. The second parameter denotes the illegal
856 /// ResNo in that case.
857 bool DAGTypeLegalizer::CustomLowerResults(SDNode *N, MVT VT,
858 bool LegalizeResult) {
859 // See if the target wants to custom lower this node.
860 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
863 SmallVector<SDValue, 8> Results;
865 TLI.ReplaceNodeResults(N, Results, DAG);
867 TLI.LowerOperationWrapper(N, Results, DAG);
870 // The target didn't want to custom lower it after all.
873 // Make everything that once used N's values now use those in Results instead.
874 assert(Results.size() == N->getNumValues() &&
875 "Custom lowering returned the wrong number of results!");
876 for (unsigned i = 0, e = Results.size(); i != e; ++i)
877 ReplaceValueWith(SDValue(N, i), Results[i]);
881 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
882 /// which is split into two not necessarily identical pieces.
883 void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT, MVT &LoVT, MVT &HiVT) {
884 if (!InVT.isVector()) {
885 LoVT = HiVT = TLI.getTypeToTransformTo(InVT);
887 MVT NewEltVT = InVT.getVectorElementType();
888 unsigned NumElements = InVT.getVectorNumElements();
889 if ((NumElements & (NumElements-1)) == 0) { // Simple power of two vector.
891 LoVT = HiVT = MVT::getVectorVT(NewEltVT, NumElements);
892 } else { // Non-power-of-two vectors.
893 unsigned NewNumElts_Lo = 1 << Log2_32(NumElements);
894 unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
895 LoVT = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
896 HiVT = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
901 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, MVT EltVT,
903 // Make sure the index type is big enough to compute in.
904 if (Index.getValueType().bitsGT(TLI.getPointerTy()))
905 Index = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Index);
907 Index = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Index);
909 // Calculate the element offset and add it to the pointer.
910 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
912 Index = DAG.getNode(ISD::MUL, Index.getValueType(), Index,
913 DAG.getConstant(EltSize, Index.getValueType()));
914 return DAG.getNode(ISD::ADD, Index.getValueType(), Index, VecPtr);
917 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
918 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
919 MVT LVT = Lo.getValueType();
920 MVT HVT = Hi.getValueType();
921 MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
923 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
924 Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
925 Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(LVT.getSizeInBits(),
926 TLI.getShiftAmountTy()));
927 return DAG.getNode(ISD::OR, NVT, Lo, Hi);
930 /// LibCallify - Convert the node into a libcall with the same prototype.
931 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
933 unsigned NumOps = N->getNumOperands();
935 return MakeLibCall(LC, N->getValueType(0), 0, 0, isSigned);
936 } else if (NumOps == 1) {
937 SDValue Op = N->getOperand(0);
938 return MakeLibCall(LC, N->getValueType(0), &Op, 1, isSigned);
939 } else if (NumOps == 2) {
940 SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
941 return MakeLibCall(LC, N->getValueType(0), Ops, 2, isSigned);
943 SmallVector<SDValue, 8> Ops(NumOps);
944 for (unsigned i = 0; i < NumOps; ++i)
945 Ops[i] = N->getOperand(i);
947 return MakeLibCall(LC, N->getValueType(0), &Ops[0], NumOps, isSigned);
950 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
951 /// returning a result of type RetVT.
952 SDValue DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
953 const SDValue *Ops, unsigned NumOps,
955 TargetLowering::ArgListTy Args;
956 Args.reserve(NumOps);
958 TargetLowering::ArgListEntry Entry;
959 for (unsigned i = 0; i != NumOps; ++i) {
961 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
962 Entry.isSExt = isSigned;
963 Entry.isZExt = !isSigned;
964 Args.push_back(Entry);
966 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
969 const Type *RetTy = RetVT.getTypeForMVT();
970 std::pair<SDValue,SDValue> CallInfo =
971 TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
972 false, CallingConv::C, false, Callee, Args, DAG);
973 return CallInfo.first;
976 /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
977 /// of the given type. A target boolean is an integer value, not necessarily of
978 /// type i1, the bits of which conform to getBooleanContents.
979 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, MVT VT) {
980 ISD::NodeType ExtendCode;
981 switch (TLI.getBooleanContents()) {
983 assert(false && "Unknown BooleanContent!");
984 case TargetLowering::UndefinedBooleanContent:
985 // Extend to VT by adding rubbish bits.
986 ExtendCode = ISD::ANY_EXTEND;
988 case TargetLowering::ZeroOrOneBooleanContent:
989 // Extend to VT by adding zero bits.
990 ExtendCode = ISD::ZERO_EXTEND;
992 case TargetLowering::ZeroOrNegativeOneBooleanContent: {
993 // Extend to VT by copying the sign bit.
994 ExtendCode = ISD::SIGN_EXTEND;
998 return DAG.getNode(ExtendCode, VT, Bool);
1001 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
1003 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1005 SDValue &Lo, SDValue &Hi) {
1006 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1007 Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
1008 Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
1009 Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
1010 DAG.getConstant(LoVT.getSizeInBits(),
1011 TLI.getShiftAmountTy()));
1012 Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
1015 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
1016 /// type half the size of Op's.
1017 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1018 SDValue &Lo, SDValue &Hi) {
1019 MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
1020 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1024 //===----------------------------------------------------------------------===//
1026 //===----------------------------------------------------------------------===//
1028 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1029 /// only uses types natively supported by the target. Returns "true" if it made
1032 /// Note that this is an involved process that may invalidate pointers into
1034 bool SelectionDAG::LegalizeTypes() {
1035 return DAGTypeLegalizer(*this).run();