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/SmallPtrSet.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().getSDValue().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())
112 if (I->getNodeId() != Processed) {
114 cerr << "Unprocessed value in a map!";
117 } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
119 cerr << "Value with legal type was transformed!";
124 cerr << "Processed value not in any map!";
126 } else if (Mapped & (Mapped - 1)) {
127 cerr << "Value in multiple maps!";
134 cerr << " ReplacedValues";
136 cerr << " PromotedIntegers";
138 cerr << " SoftenedFloats";
140 cerr << " ScalarizedVectors";
142 cerr << " ExpandedIntegers";
144 cerr << " ExpandedFloats";
146 cerr << " SplitVectors";
153 // Checked that NewNodes are only used by other NewNodes.
154 for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
155 SDNode *N = NewNodes[i];
156 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
158 assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
162 /// run - This is the main entry point for the type legalizer. This does a
163 /// top-down traversal of the dag, legalizing types as it goes. Returns "true"
164 /// if it made any changes.
165 bool DAGTypeLegalizer::run() {
166 bool Changed = false;
168 // Create a dummy node (which is not added to allnodes), that adds a reference
169 // to the root node, preventing it from being deleted, and tracking any
170 // changes of the root.
171 HandleSDNode Dummy(DAG.getRoot());
172 Dummy.setNodeId(Unanalyzed);
174 // The root of the dag may dangle to deleted nodes until the type legalizer is
175 // done. Set it to null to avoid confusion.
176 DAG.setRoot(SDValue());
178 // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
179 // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
181 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
182 E = DAG.allnodes_end(); I != E; ++I) {
183 if (I->getNumOperands() == 0) {
184 I->setNodeId(ReadyToProcess);
185 Worklist.push_back(I);
187 I->setNodeId(Unanalyzed);
191 // Now that we have a set of nodes to process, handle them all.
192 while (!Worklist.empty()) {
194 if (EnableExpensiveChecks)
196 PerformExpensiveChecks();
198 SDNode *N = Worklist.back();
200 assert(N->getNodeId() == ReadyToProcess &&
201 "Node should be ready if on worklist!");
203 if (IgnoreNodeResults(N))
206 // Scan the values produced by the node, checking to see if any result
207 // types are illegal.
208 for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
209 MVT ResultVT = N->getValueType(i);
210 switch (getTypeAction(ResultVT)) {
212 assert(false && "Unknown action!");
215 // The following calls must take care of *all* of the node's results,
216 // not just the illegal result they were passed (this includes results
217 // with a legal type). Results can be remapped using ReplaceValueWith,
218 // or their promoted/expanded/etc values registered in PromotedIntegers,
219 // ExpandedIntegers etc.
221 PromoteIntegerResult(N, i);
225 ExpandIntegerResult(N, i);
229 SoftenFloatResult(N, i);
233 ExpandFloatResult(N, i);
236 case ScalarizeVector:
237 ScalarizeVectorResult(N, i);
241 SplitVectorResult(N, i);
248 // Scan the operand list for the node, handling any nodes with operands that
251 unsigned NumOperands = N->getNumOperands();
252 bool NeedsReanalyzing = false;
254 for (i = 0; i != NumOperands; ++i) {
255 if (IgnoreNodeResults(N->getOperand(i).getNode()))
258 MVT OpVT = N->getOperand(i).getValueType();
259 switch (getTypeAction(OpVT)) {
261 assert(false && "Unknown action!");
264 // The following calls must either replace all of the node's results
265 // using ReplaceValueWith, and return "false"; or update the node's
266 // operands in place, and return "true".
268 NeedsReanalyzing = PromoteIntegerOperand(N, i);
272 NeedsReanalyzing = ExpandIntegerOperand(N, i);
276 NeedsReanalyzing = SoftenFloatOperand(N, i);
280 NeedsReanalyzing = ExpandFloatOperand(N, i);
283 case ScalarizeVector:
284 NeedsReanalyzing = ScalarizeVectorOperand(N, i);
288 NeedsReanalyzing = SplitVectorOperand(N, i);
295 // The sub-method updated N in place. Check to see if any operands are new,
296 // and if so, mark them. If the node needs revisiting, don't add all users
297 // to the worklist etc.
298 if (NeedsReanalyzing) {
299 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
300 N->setNodeId(NewNode);
301 // Recompute the NodeId and correct processed operands, adding the node to
302 // the worklist if ready.
303 SDNode *M = AnalyzeNewNode(N);
305 // The node didn't morph - nothing special to do, it will be revisited.
308 // The node morphed - this is equivalent to legalizing by replacing every
309 // value of N with the corresponding value of M. So do that now.
310 N->setNodeId(ReadyToProcess);
311 assert(N->getNumValues() == M->getNumValues() &&
312 "Node morphing changed the number of results!");
313 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
314 // Replacing the value takes care of remapping the new value.
315 ReplaceValueWith(SDValue(N, i), SDValue(M, i));
319 if (i == NumOperands) {
320 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
325 // If we reach here, the node was processed, potentially creating new nodes.
326 // Mark it as processed and add its users to the worklist as appropriate.
327 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
328 N->setNodeId(Processed);
330 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
333 int NodeId = User->getNodeId();
335 // This node has two options: it can either be a new node or its Node ID
336 // may be a count of the number of operands it has that are not ready.
338 User->setNodeId(NodeId-1);
340 // If this was the last use it was waiting on, add it to the ready list.
341 if (NodeId-1 == ReadyToProcess)
342 Worklist.push_back(User);
346 // If this is an unreachable new node, then ignore it. If it ever becomes
347 // reachable by being used by a newly created node then it will be handled
348 // by AnalyzeNewNode.
349 if (NodeId == NewNode)
352 // Otherwise, this node is new: this is the first operand of it that
353 // became ready. Its new NodeId is the number of operands it has minus 1
354 // (as this node is now processed).
355 assert(NodeId == Unanalyzed && "Unknown node ID!");
356 User->setNodeId(User->getNumOperands() - 1);
358 // If the node only has a single operand, it is now ready.
359 if (User->getNumOperands() == 1)
360 Worklist.push_back(User);
365 if (EnableExpensiveChecks)
367 PerformExpensiveChecks();
369 // If the root changed (e.g. it was a dead load) update the root.
370 DAG.setRoot(Dummy.getValue());
372 // Remove dead nodes. This is important to do for cleanliness but also before
373 // the checking loop below. Implicit folding by the DAG.getNode operators and
374 // node morphing can cause unreachable nodes to be around with their flags set
376 DAG.RemoveDeadNodes();
378 // In a debug build, scan all the nodes to make sure we found them all. This
379 // ensures that there are no cycles and that everything got processed.
381 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
382 E = DAG.allnodes_end(); I != E; ++I) {
385 // Check that all result types are legal.
386 if (!IgnoreNodeResults(I))
387 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
388 if (!isTypeLegal(I->getValueType(i))) {
389 cerr << "Result type " << i << " illegal!\n";
393 // Check that all operand types are legal.
394 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
395 if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
396 !isTypeLegal(I->getOperand(i).getValueType())) {
397 cerr << "Operand type " << i << " illegal!\n";
401 if (I->getNodeId() != Processed) {
402 if (I->getNodeId() == NewNode)
403 cerr << "New node not analyzed?\n";
404 else if (I->getNodeId() == Unanalyzed)
405 cerr << "Unanalyzed node not noticed?\n";
406 else if (I->getNodeId() > 0)
407 cerr << "Operand not processed?\n";
408 else if (I->getNodeId() == ReadyToProcess)
409 cerr << "Not added to worklist?\n";
414 I->dump(&DAG); cerr << "\n";
423 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
424 /// new nodes. Correct any processed operands (this may change the node) and
425 /// calculate the NodeId. If the node itself changes to a processed node, it
426 /// is not remapped - the caller needs to take care of this.
427 /// Returns the potentially changed node.
428 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
429 // If this was an existing node that is already done, we're done.
430 if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
433 // Remove any stale map entries.
436 // Okay, we know that this node is new. Recursively walk all of its operands
437 // to see if they are new also. The depth of this walk is bounded by the size
438 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
439 // about revisiting of nodes.
441 // As we walk the operands, keep track of the number of nodes that are
442 // processed. If non-zero, this will become the new nodeid of this node.
443 // Operands may morph when they are analyzed. If so, the node will be
444 // updated after all operands have been analyzed. Since this is rare,
445 // the code tries to minimize overhead in the non-morphing case.
447 SmallVector<SDValue, 8> NewOps;
448 unsigned NumProcessed = 0;
449 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
450 SDValue OrigOp = N->getOperand(i);
453 AnalyzeNewValue(Op); // Op may morph.
455 if (Op.getNode()->getNodeId() == Processed)
458 if (!NewOps.empty()) {
459 // Some previous operand changed. Add this one to the list.
460 NewOps.push_back(Op);
461 } else if (Op != OrigOp) {
462 // This is the first operand to change - add all operands so far.
463 for (unsigned j = 0; j < i; ++j)
464 NewOps.push_back(N->getOperand(j));
465 NewOps.push_back(Op);
469 // Some operands changed - update the node.
470 if (!NewOps.empty()) {
471 SDNode *M = DAG.UpdateNodeOperands(SDValue(N, 0), &NewOps[0],
472 NewOps.size()).getNode();
474 // The node morphed into a different node. Normally for this to happen
475 // the original node would have to be marked NewNode. However this can
476 // in theory momentarily not be the case while ReplaceValueWith is doing
477 // its stuff. Mark the original node NewNode to help sanity checking.
478 N->setNodeId(NewNode);
479 if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
480 // It morphed into a previously analyzed node - nothing more to do.
483 // It morphed into a different new node. Do the equivalent of passing
484 // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
485 // to remap the operands, since they are the same as the operands we
492 // Calculate the NodeId.
493 N->setNodeId(N->getNumOperands() - NumProcessed);
494 if (N->getNodeId() == ReadyToProcess)
495 Worklist.push_back(N);
500 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
501 /// If the node changes to a processed node, then remap it.
502 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
503 Val.setNode(AnalyzeNewNode(Val.getNode()));
504 if (Val.getNode()->getNodeId() == Processed)
505 // We were passed a processed node, or it morphed into one - remap it.
509 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
510 /// This can occur when a node is deleted then reallocated as a new node -
511 /// the mapping in ReplacedValues applies to the deleted node, not the new
513 /// The only map that can have a deleted node as a source is ReplacedValues.
514 /// Other maps can have deleted nodes as targets, but since their looked-up
515 /// values are always immediately remapped using RemapValue, resulting in a
516 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
517 /// always performs correct mappings. In order to keep the mapping correct,
518 /// ExpungeNode should be called on any new nodes *before* adding them as
519 /// either source or target to ReplacedValues (which typically means calling
520 /// Expunge when a new node is first seen, since it may no longer be marked
521 /// NewNode by the time it is added to ReplacedValues).
522 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
523 if (N->getNodeId() != NewNode)
526 // If N is not remapped by ReplacedValues then there is nothing to do.
528 for (i = 0, e = N->getNumValues(); i != e; ++i)
529 if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
535 // Remove N from all maps - this is expensive but rare.
537 for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
538 E = PromotedIntegers.end(); I != E; ++I) {
539 assert(I->first.getNode() != N);
540 RemapValue(I->second);
543 for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
544 E = SoftenedFloats.end(); I != E; ++I) {
545 assert(I->first.getNode() != N);
546 RemapValue(I->second);
549 for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
550 E = ScalarizedVectors.end(); I != E; ++I) {
551 assert(I->first.getNode() != N);
552 RemapValue(I->second);
555 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
556 I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
557 assert(I->first.getNode() != N);
558 RemapValue(I->second.first);
559 RemapValue(I->second.second);
562 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
563 I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
564 assert(I->first.getNode() != N);
565 RemapValue(I->second.first);
566 RemapValue(I->second.second);
569 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
570 I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
571 assert(I->first.getNode() != N);
572 RemapValue(I->second.first);
573 RemapValue(I->second.second);
576 for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
577 E = ReplacedValues.end(); I != E; ++I)
578 RemapValue(I->second);
580 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
581 ReplacedValues.erase(SDValue(N, i));
584 /// RemapValue - If the specified value was already legalized to another value,
585 /// replace it by that value.
586 void DAGTypeLegalizer::RemapValue(SDValue &N) {
587 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
588 if (I != ReplacedValues.end()) {
589 // Use path compression to speed up future lookups if values get multiply
590 // replaced with other values.
591 RemapValue(I->second);
593 assert(N.getNode()->getNodeId() != NewNode && "Mapped to new node!");
598 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
599 /// updates to nodes and recomputes their ready state.
600 class VISIBILITY_HIDDEN NodeUpdateListener :
601 public SelectionDAG::DAGUpdateListener {
602 DAGTypeLegalizer &DTL;
603 SmallVectorImpl<SDNode*> &NodesToAnalyze;
604 SmallPtrSet<SDNode*, 16> &NodesDeleted;
606 explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
607 SmallVectorImpl<SDNode*> &nta,
608 SmallPtrSet<SDNode*, 16> &nd)
609 : DTL(dtl), NodesToAnalyze(nta), NodesDeleted(nd) {}
611 virtual void NodeDeleted(SDNode *N, SDNode *E) {
612 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
613 N->getNodeId() != DAGTypeLegalizer::Processed &&
614 "Invalid node ID for RAUW deletion!");
615 // It is possible, though rare, for the deleted node N to occur as a
616 // target in a map, so note the replacement N -> E in ReplacedValues.
617 assert(E && "Node not replaced?");
618 DTL.NoteDeletion(N, E);
620 // In theory the deleted node could also have been scheduled for analysis.
621 // So add it to the set of nodes which will not be analyzed.
622 NodesDeleted.insert(N);
624 // In general nothing needs to be done for E, since it didn't change but
625 // only gained new uses. However N -> E was just added to ReplacedValues,
626 // and the result of a ReplacedValues mapping is not allowed to be marked
627 // NewNode. So if E is marked NewNode, then it needs to be analyzed.
628 if (E->getNodeId() == DAGTypeLegalizer::NewNode)
629 NodesToAnalyze.push_back(E);
632 virtual void NodeUpdated(SDNode *N) {
633 // Node updates can mean pretty much anything. It is possible that an
634 // operand was set to something already processed (f.e.) in which case
635 // this node could become ready. Recompute its flags.
636 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
637 N->getNodeId() != DAGTypeLegalizer::Processed &&
638 "Invalid node ID for RAUW deletion!");
639 NodesToAnalyze.push_back(N);
645 /// ReplaceValueWith - The specified value was legalized to the specified other
646 /// value. Update the DAG and NodeIds replacing any uses of From to use To
648 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
649 assert(From.getNode()->getNodeId() == ReadyToProcess &&
650 "Only the node being processed may be remapped!");
651 assert(From.getNode() != To.getNode() && "Potential legalization loop!");
653 // If expansion produced new nodes, make sure they are properly marked.
654 ExpungeNode(From.getNode());
655 AnalyzeNewValue(To); // Expunges To.
657 // Anything that used the old node should now use the new one. Note that this
658 // can potentially cause recursive merging.
659 SmallVector<SDNode*, 16> NodesToAnalyze;
660 SmallPtrSet<SDNode*, 16> NodesDeleted;
661 NodeUpdateListener NUL(*this, NodesToAnalyze, NodesDeleted);
662 DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
664 // The old node may still be present in a map like ExpandedIntegers or
665 // PromotedIntegers. Inform maps about the replacement.
666 ReplacedValues[From] = To;
668 // Process the list of nodes that need to be reanalyzed.
669 while (!NodesToAnalyze.empty()) {
670 SDNode *N = NodesToAnalyze.back();
671 NodesToAnalyze.pop_back();
673 // Do not analyze deleted nodes!
674 if (NodesDeleted.count(N))
677 // Analyze the node's operands and recalculate the node ID.
678 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
679 N->getNodeId() != DAGTypeLegalizer::Processed &&
680 "Invalid node ID for RAUW analysis!");
681 N->setNodeId(NewNode);
682 SDNode *M = AnalyzeNewNode(N);
684 // The node morphed into a different node. Make everyone use the new node
686 assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
687 assert(N->getNumValues() == M->getNumValues() &&
688 "Node morphing changed the number of results!");
689 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
690 SDValue OldVal(N, i);
691 SDValue NewVal(M, i);
692 if (M->getNodeId() == Processed)
694 DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal, &NUL);
696 // The original node continues to exist in the DAG, marked NewNode.
701 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
702 AnalyzeNewValue(Result);
704 SDValue &OpEntry = PromotedIntegers[Op];
705 assert(OpEntry.getNode() == 0 && "Node is already promoted!");
709 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
710 AnalyzeNewValue(Result);
712 SDValue &OpEntry = SoftenedFloats[Op];
713 assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
717 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
718 AnalyzeNewValue(Result);
720 SDValue &OpEntry = ScalarizedVectors[Op];
721 assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
725 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
727 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
728 RemapValue(Entry.first);
729 RemapValue(Entry.second);
730 assert(Entry.first.getNode() && "Operand isn't expanded");
735 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
737 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
741 // Remember that this is the result of the node.
742 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
743 assert(Entry.first.getNode() == 0 && "Node already expanded");
748 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
750 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
751 RemapValue(Entry.first);
752 RemapValue(Entry.second);
753 assert(Entry.first.getNode() && "Operand isn't expanded");
758 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
760 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
764 // Remember that this is the result of the node.
765 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
766 assert(Entry.first.getNode() == 0 && "Node already expanded");
771 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
773 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
774 RemapValue(Entry.first);
775 RemapValue(Entry.second);
776 assert(Entry.first.getNode() && "Operand isn't split");
781 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
783 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
787 // Remember that this is the result of the node.
788 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
789 assert(Entry.first.getNode() == 0 && "Node already split");
795 //===----------------------------------------------------------------------===//
797 //===----------------------------------------------------------------------===//
799 /// BitConvertToInteger - Convert to an integer of the same size.
800 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
801 unsigned BitWidth = Op.getValueType().getSizeInBits();
802 return DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerVT(BitWidth), Op);
805 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
807 // Create the stack frame object. Make sure it is aligned for both
808 // the source and destination types.
809 SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
810 // Emit a store to the stack slot.
811 SDValue Store = DAG.getStore(DAG.getEntryNode(), Op, StackPtr, NULL, 0);
812 // Result is a load from the stack slot.
813 return DAG.getLoad(DestVT, Store, StackPtr, NULL, 0);
816 /// CustomLowerResults - Replace the node's results with custom code provided
817 /// by the target and return "true", or do nothing and return "false".
818 bool DAGTypeLegalizer::CustomLowerResults(SDNode *N, unsigned ResNo) {
819 // See if the target wants to custom lower this node.
820 if (TLI.getOperationAction(N->getOpcode(), N->getValueType(ResNo)) !=
821 TargetLowering::Custom)
824 SmallVector<SDValue, 8> Results;
825 TLI.ReplaceNodeResults(N, Results, DAG);
827 // The target didn't want to custom lower it after all.
830 // Make everything that once used N's values now use those in Results instead.
831 assert(Results.size() == N->getNumValues() &&
832 "Custom lowering returned the wrong number of results!");
833 for (unsigned i = 0, e = Results.size(); i != e; ++i)
834 ReplaceValueWith(SDValue(N, i), Results[i]);
838 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
839 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
840 MVT LVT = Lo.getValueType();
841 MVT HVT = Hi.getValueType();
842 MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
844 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
845 Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
846 Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(LVT.getSizeInBits(),
847 TLI.getShiftAmountTy()));
848 return DAG.getNode(ISD::OR, NVT, Lo, Hi);
851 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
853 void DAGTypeLegalizer::SplitInteger(SDValue Op,
855 SDValue &Lo, SDValue &Hi) {
856 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
857 Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
858 Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
859 Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
860 DAG.getConstant(LoVT.getSizeInBits(),
861 TLI.getShiftAmountTy()));
862 Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
865 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
866 /// type half the size of Op's.
867 void DAGTypeLegalizer::SplitInteger(SDValue Op,
868 SDValue &Lo, SDValue &Hi) {
869 MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
870 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
873 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
874 /// returning a result of type RetVT.
875 SDValue DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
876 const SDValue *Ops, unsigned NumOps,
878 TargetLowering::ArgListTy Args;
879 Args.reserve(NumOps);
881 TargetLowering::ArgListEntry Entry;
882 for (unsigned i = 0; i != NumOps; ++i) {
884 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
885 Entry.isSExt = isSigned;
886 Entry.isZExt = !isSigned;
887 Args.push_back(Entry);
889 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
892 const Type *RetTy = RetVT.getTypeForMVT();
893 std::pair<SDValue,SDValue> CallInfo =
894 TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
895 false, CallingConv::C, false, Callee, Args, DAG);
896 return CallInfo.first;
899 /// LibCallify - Convert the node into a libcall with the same prototype.
900 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
902 unsigned NumOps = N->getNumOperands();
904 return MakeLibCall(LC, N->getValueType(0), 0, 0, isSigned);
905 } else if (NumOps == 1) {
906 SDValue Op = N->getOperand(0);
907 return MakeLibCall(LC, N->getValueType(0), &Op, 1, isSigned);
908 } else if (NumOps == 2) {
909 SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
910 return MakeLibCall(LC, N->getValueType(0), Ops, 2, isSigned);
912 SmallVector<SDValue, 8> Ops(NumOps);
913 for (unsigned i = 0; i < NumOps; ++i)
914 Ops[i] = N->getOperand(i);
916 return MakeLibCall(LC, N->getValueType(0), &Ops[0], NumOps, isSigned);
919 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, MVT EltVT,
921 // Make sure the index type is big enough to compute in.
922 if (Index.getValueType().bitsGT(TLI.getPointerTy()))
923 Index = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Index);
925 Index = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Index);
927 // Calculate the element offset and add it to the pointer.
928 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
930 Index = DAG.getNode(ISD::MUL, Index.getValueType(), Index,
931 DAG.getConstant(EltSize, Index.getValueType()));
932 return DAG.getNode(ISD::ADD, Index.getValueType(), Index, VecPtr);
935 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
936 /// which is split into two not necessarily identical pieces.
937 void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT, MVT &LoVT, MVT &HiVT) {
938 if (!InVT.isVector()) {
939 LoVT = HiVT = TLI.getTypeToTransformTo(InVT);
941 MVT NewEltVT = InVT.getVectorElementType();
942 unsigned NumElements = InVT.getVectorNumElements();
943 if ((NumElements & (NumElements-1)) == 0) { // Simple power of two vector.
945 LoVT = HiVT = MVT::getVectorVT(NewEltVT, NumElements);
946 } else { // Non-power-of-two vectors.
947 unsigned NewNumElts_Lo = 1 << Log2_32(NumElements);
948 unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
949 LoVT = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
950 HiVT = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
956 //===----------------------------------------------------------------------===//
958 //===----------------------------------------------------------------------===//
960 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
961 /// only uses types natively supported by the target. Returns "true" if it made
964 /// Note that this is an involved process that may invalidate pointers into
966 bool SelectionDAG::LegalizeTypes() {
967 return DAGTypeLegalizer(*this).run();