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/ADT/SetVector.h"
18 #include "llvm/IR/CallingConv.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
25 #define DEBUG_TYPE "legalize-types"
28 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
30 /// Do extensive, expensive, sanity checking.
31 void DAGTypeLegalizer::PerformExpensiveChecks() {
32 // If a node is not processed, then none of its values should be mapped by any
33 // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
35 // If a node is processed, then each value with an illegal type must be mapped
36 // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
37 // Values with a legal type may be mapped by ReplacedValues, but not by any of
40 // Note that these invariants may not hold momentarily when processing a node:
41 // the node being processed may be put in a map before being marked Processed.
43 // Note that it is possible to have nodes marked NewNode in the DAG. This can
44 // occur in two ways. Firstly, a node may be created during legalization but
45 // never passed to the legalization core. This is usually due to the implicit
46 // folding that occurs when using the DAG.getNode operators. Secondly, a new
47 // node may be passed to the legalization core, but when analyzed may morph
48 // into a different node, leaving the original node as a NewNode in the DAG.
49 // A node may morph if one of its operands changes during analysis. Whether
50 // it actually morphs or not depends on whether, after updating its operands,
51 // it is equivalent to an existing node: if so, it morphs into that existing
52 // node (CSE). An operand can change during analysis if the operand is a new
53 // node that morphs, or it is a processed value that was mapped to some other
54 // value (as recorded in ReplacedValues) in which case the operand is turned
55 // into that other value. If a node morphs then the node it morphed into will
56 // be used instead of it for legalization, however the original node continues
57 // to live on in the DAG.
58 // The conclusion is that though there may be nodes marked NewNode in the DAG,
59 // all uses of such nodes are also marked NewNode: the result is a fungus of
60 // NewNodes growing on top of the useful nodes, and perhaps using them, but
63 // If a value is mapped by ReplacedValues, then it must have no uses, except
64 // by nodes marked NewNode (see above).
66 // The final node obtained by mapping by ReplacedValues is not marked NewNode.
67 // Note that ReplacedValues should be applied iteratively.
69 // Note that the ReplacedValues map may also map deleted nodes (by iterating
70 // over the DAG we never dereference deleted nodes). This means that it may
71 // also map nodes marked NewNode if the deallocated memory was reallocated as
72 // another node, and that new node was not seen by the LegalizeTypes machinery
73 // (for example because it was created but not used). In general, we cannot
74 // distinguish between new nodes and deleted nodes.
75 SmallVector<SDNode*, 16> NewNodes;
76 for (SDNode &Node : DAG.allnodes()) {
77 // Remember nodes marked NewNode - they are subject to extra checking below.
78 if (Node.getNodeId() == NewNode)
79 NewNodes.push_back(&Node);
81 for (unsigned i = 0, e = Node.getNumValues(); i != e; ++i) {
82 SDValue Res(&Node, i);
86 if (ReplacedValues.find(Res) != ReplacedValues.end()) {
88 // Check that remapped values are only used by nodes marked NewNode.
89 for (SDNode::use_iterator UI = Node.use_begin(), UE = Node.use_end();
91 if (UI.getUse().getResNo() == i)
92 assert(UI->getNodeId() == NewNode &&
93 "Remapped value has non-trivial use!");
95 // Check that the final result of applying ReplacedValues is not
97 SDValue NewVal = ReplacedValues[Res];
98 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
99 while (I != ReplacedValues.end()) {
101 I = ReplacedValues.find(NewVal);
103 assert(NewVal.getNode()->getNodeId() != NewNode &&
104 "ReplacedValues maps to a new node!");
106 if (PromotedIntegers.find(Res) != PromotedIntegers.end())
108 if (SoftenedFloats.find(Res) != SoftenedFloats.end())
110 if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
112 if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
114 if (ExpandedFloats.find(Res) != ExpandedFloats.end())
116 if (SplitVectors.find(Res) != SplitVectors.end())
118 if (WidenedVectors.find(Res) != WidenedVectors.end())
120 if (PromotedFloats.find(Res) != PromotedFloats.end())
123 if (Node.getNodeId() != Processed) {
124 // Since we allow ReplacedValues to map deleted nodes, it may map nodes
125 // marked NewNode too, since a deleted node may have been reallocated as
126 // another node that has not been seen by the LegalizeTypes machinery.
127 if ((Node.getNodeId() == NewNode && Mapped > 1) ||
128 (Node.getNodeId() != NewNode && Mapped != 0)) {
129 dbgs() << "Unprocessed value in a map!";
132 } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(&Node)) {
134 dbgs() << "Value with legal type was transformed!";
139 dbgs() << "Processed value not in any map!";
141 } else if (Mapped & (Mapped - 1)) {
142 dbgs() << "Value in multiple maps!";
149 dbgs() << " ReplacedValues";
151 dbgs() << " PromotedIntegers";
153 dbgs() << " SoftenedFloats";
155 dbgs() << " ScalarizedVectors";
157 dbgs() << " ExpandedIntegers";
159 dbgs() << " ExpandedFloats";
161 dbgs() << " SplitVectors";
163 dbgs() << " WidenedVectors";
165 dbgs() << " PromotedFloats";
167 llvm_unreachable(nullptr);
172 // Checked that NewNodes are only used by other NewNodes.
173 for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
174 SDNode *N = NewNodes[i];
175 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
177 assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
181 /// This is the main entry point for the type legalizer. This does a top-down
182 /// traversal of the dag, legalizing types as it goes. Returns "true" if it made
184 bool DAGTypeLegalizer::run() {
185 bool Changed = false;
187 // Create a dummy node (which is not added to allnodes), that adds a reference
188 // to the root node, preventing it from being deleted, and tracking any
189 // changes of the root.
190 HandleSDNode Dummy(DAG.getRoot());
191 Dummy.setNodeId(Unanalyzed);
193 // The root of the dag may dangle to deleted nodes until the type legalizer is
194 // done. Set it to null to avoid confusion.
195 DAG.setRoot(SDValue());
197 // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
198 // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
200 for (SDNode &Node : DAG.allnodes()) {
201 if (Node.getNumOperands() == 0) {
202 Node.setNodeId(ReadyToProcess);
203 Worklist.push_back(&Node);
205 Node.setNodeId(Unanalyzed);
209 // Now that we have a set of nodes to process, handle them all.
210 while (!Worklist.empty()) {
211 #ifndef EXPENSIVE_CHECKS
212 if (EnableExpensiveChecks)
214 PerformExpensiveChecks();
216 SDNode *N = Worklist.back();
218 assert(N->getNodeId() == ReadyToProcess &&
219 "Node should be ready if on worklist!");
221 if (IgnoreNodeResults(N))
224 // Scan the values produced by the node, checking to see if any result
225 // types are illegal.
226 for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
227 EVT ResultVT = N->getValueType(i);
228 switch (getTypeAction(ResultVT)) {
229 case TargetLowering::TypeLegal:
231 // The following calls must take care of *all* of the node's results,
232 // not just the illegal result they were passed (this includes results
233 // with a legal type). Results can be remapped using ReplaceValueWith,
234 // or their promoted/expanded/etc values registered in PromotedIntegers,
235 // ExpandedIntegers etc.
236 case TargetLowering::TypePromoteInteger:
237 PromoteIntegerResult(N, i);
240 case TargetLowering::TypeExpandInteger:
241 ExpandIntegerResult(N, i);
244 case TargetLowering::TypeSoftenFloat:
245 Changed = SoftenFloatResult(N, i);
248 // If not changed, the result type should be legally in register.
249 assert(isLegalInHWReg(ResultVT) &&
250 "Unchanged SoftenFloatResult should be legal in register!");
252 case TargetLowering::TypeExpandFloat:
253 ExpandFloatResult(N, i);
256 case TargetLowering::TypeScalarizeVector:
257 ScalarizeVectorResult(N, i);
260 case TargetLowering::TypeSplitVector:
261 SplitVectorResult(N, i);
264 case TargetLowering::TypeWidenVector:
265 WidenVectorResult(N, i);
268 case TargetLowering::TypePromoteFloat:
269 PromoteFloatResult(N, i);
276 // Scan the operand list for the node, handling any nodes with operands that
279 unsigned NumOperands = N->getNumOperands();
280 bool NeedsReanalyzing = false;
282 for (i = 0; i != NumOperands; ++i) {
283 if (IgnoreNodeResults(N->getOperand(i).getNode()))
286 EVT OpVT = N->getOperand(i).getValueType();
287 switch (getTypeAction(OpVT)) {
288 case TargetLowering::TypeLegal:
290 // The following calls must either replace all of the node's results
291 // using ReplaceValueWith, and return "false"; or update the node's
292 // operands in place, and return "true".
293 case TargetLowering::TypePromoteInteger:
294 NeedsReanalyzing = PromoteIntegerOperand(N, i);
297 case TargetLowering::TypeExpandInteger:
298 NeedsReanalyzing = ExpandIntegerOperand(N, i);
301 case TargetLowering::TypeSoftenFloat:
302 NeedsReanalyzing = SoftenFloatOperand(N, i);
305 case TargetLowering::TypeExpandFloat:
306 NeedsReanalyzing = ExpandFloatOperand(N, i);
309 case TargetLowering::TypeScalarizeVector:
310 NeedsReanalyzing = ScalarizeVectorOperand(N, i);
313 case TargetLowering::TypeSplitVector:
314 NeedsReanalyzing = SplitVectorOperand(N, i);
317 case TargetLowering::TypeWidenVector:
318 NeedsReanalyzing = WidenVectorOperand(N, i);
321 case TargetLowering::TypePromoteFloat:
322 NeedsReanalyzing = PromoteFloatOperand(N, i);
329 // The sub-method updated N in place. Check to see if any operands are new,
330 // and if so, mark them. If the node needs revisiting, don't add all users
331 // to the worklist etc.
332 if (NeedsReanalyzing) {
333 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
334 N->setNodeId(NewNode);
335 // Recompute the NodeId and correct processed operands, adding the node to
336 // the worklist if ready.
337 SDNode *M = AnalyzeNewNode(N);
339 // The node didn't morph - nothing special to do, it will be revisited.
342 // The node morphed - this is equivalent to legalizing by replacing every
343 // value of N with the corresponding value of M. So do that now.
344 assert(N->getNumValues() == M->getNumValues() &&
345 "Node morphing changed the number of results!");
346 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
347 // Replacing the value takes care of remapping the new value.
348 ReplaceValueWith(SDValue(N, i), SDValue(M, i));
349 assert(N->getNodeId() == NewNode && "Unexpected node state!");
350 // The node continues to live on as part of the NewNode fungus that
351 // grows on top of the useful nodes. Nothing more needs to be done
352 // with it - move on to the next node.
356 if (i == NumOperands) {
357 DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG); dbgs() << "\n");
362 // If we reach here, the node was processed, potentially creating new nodes.
363 // Mark it as processed and add its users to the worklist as appropriate.
364 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
365 N->setNodeId(Processed);
367 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
370 int NodeId = User->getNodeId();
372 // This node has two options: it can either be a new node or its Node ID
373 // may be a count of the number of operands it has that are not ready.
375 User->setNodeId(NodeId-1);
377 // If this was the last use it was waiting on, add it to the ready list.
378 if (NodeId-1 == ReadyToProcess)
379 Worklist.push_back(User);
383 // If this is an unreachable new node, then ignore it. If it ever becomes
384 // reachable by being used by a newly created node then it will be handled
385 // by AnalyzeNewNode.
386 if (NodeId == NewNode)
389 // Otherwise, this node is new: this is the first operand of it that
390 // became ready. Its new NodeId is the number of operands it has minus 1
391 // (as this node is now processed).
392 assert(NodeId == Unanalyzed && "Unknown node ID!");
393 User->setNodeId(User->getNumOperands() - 1);
395 // If the node only has a single operand, it is now ready.
396 if (User->getNumOperands() == 1)
397 Worklist.push_back(User);
401 #ifndef EXPENSIVE_CHECKS
402 if (EnableExpensiveChecks)
404 PerformExpensiveChecks();
406 // If the root changed (e.g. it was a dead load) update the root.
407 DAG.setRoot(Dummy.getValue());
409 // Remove dead nodes. This is important to do for cleanliness but also before
410 // the checking loop below. Implicit folding by the DAG.getNode operators and
411 // node morphing can cause unreachable nodes to be around with their flags set
413 DAG.RemoveDeadNodes();
415 // In a debug build, scan all the nodes to make sure we found them all. This
416 // ensures that there are no cycles and that everything got processed.
418 for (SDNode &Node : DAG.allnodes()) {
421 // Check that all result types are legal.
422 // A value type is illegal if its TypeAction is not TypeLegal,
423 // and TLI.RegClassForVT does not have a register class for this type.
424 // For example, the x86_64 target has f128 that is not TypeLegal,
425 // to have softened operators, but it also has FR128 register class to
426 // pass and return f128 values. Hence a legalized node can have f128 type.
427 if (!IgnoreNodeResults(&Node))
428 for (unsigned i = 0, NumVals = Node.getNumValues(); i < NumVals; ++i)
429 if (!isTypeLegal(Node.getValueType(i)) &&
430 !TLI.isTypeLegal(Node.getValueType(i))) {
431 dbgs() << "Result type " << i << " illegal: ";
436 // Check that all operand types are legal.
437 for (unsigned i = 0, NumOps = Node.getNumOperands(); i < NumOps; ++i)
438 if (!IgnoreNodeResults(Node.getOperand(i).getNode()) &&
439 !isTypeLegal(Node.getOperand(i).getValueType()) &&
440 !TLI.isTypeLegal(Node.getOperand(i).getValueType())) {
441 dbgs() << "Operand type " << i << " illegal: ";
442 Node.getOperand(i).dump();
446 if (Node.getNodeId() != Processed) {
447 if (Node.getNodeId() == NewNode)
448 dbgs() << "New node not analyzed?\n";
449 else if (Node.getNodeId() == Unanalyzed)
450 dbgs() << "Unanalyzed node not noticed?\n";
451 else if (Node.getNodeId() > 0)
452 dbgs() << "Operand not processed?\n";
453 else if (Node.getNodeId() == ReadyToProcess)
454 dbgs() << "Not added to worklist?\n";
459 Node.dump(&DAG); dbgs() << "\n";
460 llvm_unreachable(nullptr);
468 /// The specified node is the root of a subtree of potentially new nodes.
469 /// Correct any processed operands (this may change the node) and calculate the
470 /// NodeId. If the node itself changes to a processed node, it is not remapped -
471 /// the caller needs to take care of this. Returns the potentially changed node.
472 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
473 // If this was an existing node that is already done, we're done.
474 if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
477 // Remove any stale map entries.
480 // Okay, we know that this node is new. Recursively walk all of its operands
481 // to see if they are new also. The depth of this walk is bounded by the size
482 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
483 // about revisiting of nodes.
485 // As we walk the operands, keep track of the number of nodes that are
486 // processed. If non-zero, this will become the new nodeid of this node.
487 // Operands may morph when they are analyzed. If so, the node will be
488 // updated after all operands have been analyzed. Since this is rare,
489 // the code tries to minimize overhead in the non-morphing case.
491 std::vector<SDValue> NewOps;
492 unsigned NumProcessed = 0;
493 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
494 SDValue OrigOp = N->getOperand(i);
497 AnalyzeNewValue(Op); // Op may morph.
499 if (Op.getNode()->getNodeId() == Processed)
502 if (!NewOps.empty()) {
503 // Some previous operand changed. Add this one to the list.
504 NewOps.push_back(Op);
505 } else if (Op != OrigOp) {
506 // This is the first operand to change - add all operands so far.
507 NewOps.insert(NewOps.end(), N->op_begin(), N->op_begin() + i);
508 NewOps.push_back(Op);
512 // Some operands changed - update the node.
513 if (!NewOps.empty()) {
514 SDNode *M = DAG.UpdateNodeOperands(N, NewOps);
516 // The node morphed into a different node. Normally for this to happen
517 // the original node would have to be marked NewNode. However this can
518 // in theory momentarily not be the case while ReplaceValueWith is doing
519 // its stuff. Mark the original node NewNode to help sanity checking.
520 N->setNodeId(NewNode);
521 if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
522 // It morphed into a previously analyzed node - nothing more to do.
525 // It morphed into a different new node. Do the equivalent of passing
526 // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
527 // to remap the operands, since they are the same as the operands we
534 // Calculate the NodeId.
535 N->setNodeId(N->getNumOperands() - NumProcessed);
536 if (N->getNodeId() == ReadyToProcess)
537 Worklist.push_back(N);
542 /// Call AnalyzeNewNode, updating the node in Val if needed.
543 /// If the node changes to a processed node, then remap it.
544 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
545 Val.setNode(AnalyzeNewNode(Val.getNode()));
546 if (Val.getNode()->getNodeId() == Processed)
547 // We were passed a processed node, or it morphed into one - remap it.
551 /// If N has a bogus mapping in ReplacedValues, eliminate it.
552 /// This can occur when a node is deleted then reallocated as a new node -
553 /// the mapping in ReplacedValues applies to the deleted node, not the new
555 /// The only map that can have a deleted node as a source is ReplacedValues.
556 /// Other maps can have deleted nodes as targets, but since their looked-up
557 /// values are always immediately remapped using RemapValue, resulting in a
558 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
559 /// always performs correct mappings. In order to keep the mapping correct,
560 /// ExpungeNode should be called on any new nodes *before* adding them as
561 /// either source or target to ReplacedValues (which typically means calling
562 /// Expunge when a new node is first seen, since it may no longer be marked
563 /// NewNode by the time it is added to ReplacedValues).
564 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
565 if (N->getNodeId() != NewNode)
568 // If N is not remapped by ReplacedValues then there is nothing to do.
570 for (i = 0, e = N->getNumValues(); i != e; ++i)
571 if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
577 // Remove N from all maps - this is expensive but rare.
579 for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
580 E = PromotedIntegers.end(); I != E; ++I) {
581 assert(I->first.getNode() != N);
582 RemapValue(I->second);
585 for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
586 E = SoftenedFloats.end(); I != E; ++I) {
587 assert(I->first.getNode() != N);
588 RemapValue(I->second);
591 for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
592 E = ScalarizedVectors.end(); I != E; ++I) {
593 assert(I->first.getNode() != N);
594 RemapValue(I->second);
597 for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
598 E = WidenedVectors.end(); I != E; ++I) {
599 assert(I->first.getNode() != N);
600 RemapValue(I->second);
603 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
604 I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
605 assert(I->first.getNode() != N);
606 RemapValue(I->second.first);
607 RemapValue(I->second.second);
610 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
611 I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
612 assert(I->first.getNode() != N);
613 RemapValue(I->second.first);
614 RemapValue(I->second.second);
617 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
618 I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
619 assert(I->first.getNode() != N);
620 RemapValue(I->second.first);
621 RemapValue(I->second.second);
624 for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
625 E = ReplacedValues.end(); I != E; ++I)
626 RemapValue(I->second);
628 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
629 ReplacedValues.erase(SDValue(N, i));
632 /// If the specified value was already legalized to another value,
633 /// replace it by that value.
634 void DAGTypeLegalizer::RemapValue(SDValue &N) {
635 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
636 if (I != ReplacedValues.end()) {
637 // Use path compression to speed up future lookups if values get multiply
638 // replaced with other values.
639 RemapValue(I->second);
642 // Note that it is possible to have N.getNode()->getNodeId() == NewNode at
643 // this point because it is possible for a node to be put in the map before
649 /// This class is a DAGUpdateListener that listens for updates to nodes and
650 /// recomputes their ready state.
651 class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
652 DAGTypeLegalizer &DTL;
653 SmallSetVector<SDNode*, 16> &NodesToAnalyze;
655 explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
656 SmallSetVector<SDNode*, 16> &nta)
657 : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
658 DTL(dtl), NodesToAnalyze(nta) {}
660 void NodeDeleted(SDNode *N, SDNode *E) override {
661 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
662 N->getNodeId() != DAGTypeLegalizer::Processed &&
663 "Invalid node ID for RAUW deletion!");
664 // It is possible, though rare, for the deleted node N to occur as a
665 // target in a map, so note the replacement N -> E in ReplacedValues.
666 assert(E && "Node not replaced?");
667 DTL.NoteDeletion(N, E);
669 // In theory the deleted node could also have been scheduled for analysis.
670 // So remove it from the set of nodes which will be analyzed.
671 NodesToAnalyze.remove(N);
673 // In general nothing needs to be done for E, since it didn't change but
674 // only gained new uses. However N -> E was just added to ReplacedValues,
675 // and the result of a ReplacedValues mapping is not allowed to be marked
676 // NewNode. So if E is marked NewNode, then it needs to be analyzed.
677 if (E->getNodeId() == DAGTypeLegalizer::NewNode)
678 NodesToAnalyze.insert(E);
681 void NodeUpdated(SDNode *N) override {
682 // Node updates can mean pretty much anything. It is possible that an
683 // operand was set to something already processed (f.e.) in which case
684 // this node could become ready. Recompute its flags.
685 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
686 N->getNodeId() != DAGTypeLegalizer::Processed &&
687 "Invalid node ID for RAUW deletion!");
688 N->setNodeId(DAGTypeLegalizer::NewNode);
689 NodesToAnalyze.insert(N);
695 /// The specified value was legalized to the specified other value.
696 /// Update the DAG and NodeIds replacing any uses of From to use To instead.
697 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
698 assert(From.getNode() != To.getNode() && "Potential legalization loop!");
700 // If expansion produced new nodes, make sure they are properly marked.
701 ExpungeNode(From.getNode());
702 AnalyzeNewValue(To); // Expunges To.
704 // Anything that used the old node should now use the new one. Note that this
705 // can potentially cause recursive merging.
706 SmallSetVector<SDNode*, 16> NodesToAnalyze;
707 NodeUpdateListener NUL(*this, NodesToAnalyze);
709 DAG.ReplaceAllUsesOfValueWith(From, To);
711 // The old node may still be present in a map like ExpandedIntegers or
712 // PromotedIntegers. Inform maps about the replacement.
713 ReplacedValues[From] = To;
715 // Process the list of nodes that need to be reanalyzed.
716 while (!NodesToAnalyze.empty()) {
717 SDNode *N = NodesToAnalyze.back();
718 NodesToAnalyze.pop_back();
719 if (N->getNodeId() != DAGTypeLegalizer::NewNode)
720 // The node was analyzed while reanalyzing an earlier node - it is safe
721 // to skip. Note that this is not a morphing node - otherwise it would
722 // still be marked NewNode.
725 // Analyze the node's operands and recalculate the node ID.
726 SDNode *M = AnalyzeNewNode(N);
728 // The node morphed into a different node. Make everyone use the new
730 assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
731 assert(N->getNumValues() == M->getNumValues() &&
732 "Node morphing changed the number of results!");
733 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
734 SDValue OldVal(N, i);
735 SDValue NewVal(M, i);
736 if (M->getNodeId() == Processed)
738 DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
739 // OldVal may be a target of the ReplacedValues map which was marked
740 // NewNode to force reanalysis because it was updated. Ensure that
741 // anything that ReplacedValues mapped to OldVal will now be mapped
742 // all the way to NewVal.
743 ReplacedValues[OldVal] = NewVal;
745 // The original node continues to exist in the DAG, marked NewNode.
748 // When recursively update nodes with new nodes, it is possible to have
749 // new uses of From due to CSE. If this happens, replace the new uses of
751 } while (!From.use_empty());
754 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
755 assert(Result.getValueType() ==
756 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
757 "Invalid type for promoted integer");
758 AnalyzeNewValue(Result);
760 SDValue &OpEntry = PromotedIntegers[Op];
761 assert(!OpEntry.getNode() && "Node is already promoted!");
765 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
766 // f128 of x86_64 could be kept in SSE registers,
767 // but sometimes softened to i128.
768 assert((Result.getValueType() ==
769 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) ||
771 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType())) &&
772 "Invalid type for softened float");
773 AnalyzeNewValue(Result);
775 SDValue &OpEntry = SoftenedFloats[Op];
776 // Allow repeated calls to save f128 type nodes
777 // or any node with type that transforms to itself.
778 // Many operations on these types are not softened.
779 assert((!OpEntry.getNode()||
781 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType())) &&
782 "Node is already converted to integer!");
786 void DAGTypeLegalizer::SetPromotedFloat(SDValue Op, SDValue Result) {
787 assert(Result.getValueType() ==
788 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
789 "Invalid type for promoted float");
790 AnalyzeNewValue(Result);
792 SDValue &OpEntry = PromotedFloats[Op];
793 assert(!OpEntry.getNode() && "Node is already promoted!");
797 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
798 // Note that in some cases vector operation operands may be greater than
799 // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
800 // a constant i8 operand.
801 assert(Result.getValueSizeInBits() >= Op.getScalarValueSizeInBits() &&
802 "Invalid type for scalarized vector");
803 AnalyzeNewValue(Result);
805 SDValue &OpEntry = ScalarizedVectors[Op];
806 assert(!OpEntry.getNode() && "Node is already scalarized!");
810 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
812 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
813 RemapValue(Entry.first);
814 RemapValue(Entry.second);
815 assert(Entry.first.getNode() && "Operand isn't expanded");
820 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
822 assert(Lo.getValueType() ==
823 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
824 Hi.getValueType() == Lo.getValueType() &&
825 "Invalid type for expanded integer");
826 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
830 // Remember that this is the result of the node.
831 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
832 assert(!Entry.first.getNode() && "Node already expanded");
837 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
839 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
840 RemapValue(Entry.first);
841 RemapValue(Entry.second);
842 assert(Entry.first.getNode() && "Operand isn't expanded");
847 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
849 assert(Lo.getValueType() ==
850 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
851 Hi.getValueType() == Lo.getValueType() &&
852 "Invalid type for expanded float");
853 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
857 // Remember that this is the result of the node.
858 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
859 assert(!Entry.first.getNode() && "Node already expanded");
864 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
866 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
867 RemapValue(Entry.first);
868 RemapValue(Entry.second);
869 assert(Entry.first.getNode() && "Operand isn't split");
874 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
876 assert(Lo.getValueType().getVectorElementType() ==
877 Op.getValueType().getVectorElementType() &&
878 2*Lo.getValueType().getVectorNumElements() ==
879 Op.getValueType().getVectorNumElements() &&
880 Hi.getValueType() == Lo.getValueType() &&
881 "Invalid type for split vector");
882 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
886 // Remember that this is the result of the node.
887 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
888 assert(!Entry.first.getNode() && "Node already split");
893 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
894 assert(Result.getValueType() ==
895 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
896 "Invalid type for widened vector");
897 AnalyzeNewValue(Result);
899 SDValue &OpEntry = WidenedVectors[Op];
900 assert(!OpEntry.getNode() && "Node already widened!");
905 //===----------------------------------------------------------------------===//
907 //===----------------------------------------------------------------------===//
909 /// Convert to an integer of the same size.
910 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
911 unsigned BitWidth = Op.getValueSizeInBits();
912 return DAG.getNode(ISD::BITCAST, SDLoc(Op),
913 EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
916 /// Convert to a vector of integers of the same size.
917 SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
918 assert(Op.getValueType().isVector() && "Only applies to vectors!");
919 unsigned EltWidth = Op.getScalarValueSizeInBits();
920 EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
921 unsigned NumElts = Op.getValueType().getVectorNumElements();
922 return DAG.getNode(ISD::BITCAST, SDLoc(Op),
923 EVT::getVectorVT(*DAG.getContext(), EltNVT, NumElts), Op);
926 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
929 // Create the stack frame object. Make sure it is aligned for both
930 // the source and destination types.
931 SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
932 // Emit a store to the stack slot.
934 DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr, MachinePointerInfo());
935 // Result is a load from the stack slot.
936 return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo());
939 /// Replace the node's results with custom code provided by the target and
940 /// return "true", or do nothing and return "false".
941 /// The last parameter is FALSE if we are dealing with a node with legal
942 /// result types and illegal operand. The second parameter denotes the type of
943 /// illegal OperandNo in that case.
944 /// The last parameter being TRUE means we are dealing with a
945 /// node with illegal result types. The second parameter denotes the type of
946 /// illegal ResNo in that case.
947 bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
948 // See if the target wants to custom lower this node.
949 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
952 SmallVector<SDValue, 8> Results;
954 TLI.ReplaceNodeResults(N, Results, DAG);
956 TLI.LowerOperationWrapper(N, Results, DAG);
959 // The target didn't want to custom lower it after all.
962 // When called from DAGTypeLegalizer::ExpandIntegerResult, we might need to
963 // provide the same kind of custom splitting behavior.
964 if (Results.size() == N->getNumValues() + 1 && LegalizeResult) {
965 // We've legalized a return type by splitting it. If there is a chain,
967 SetExpandedInteger(SDValue(N, 0), Results[0], Results[1]);
968 if (N->getNumValues() > 1)
969 ReplaceValueWith(SDValue(N, 1), Results[2]);
973 // Make everything that once used N's values now use those in Results instead.
974 assert(Results.size() == N->getNumValues() &&
975 "Custom lowering returned the wrong number of results!");
976 for (unsigned i = 0, e = Results.size(); i != e; ++i) {
977 ReplaceValueWith(SDValue(N, i), Results[i]);
983 /// Widen the node's results with custom code provided by the target and return
984 /// "true", or do nothing and return "false".
985 bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
986 // See if the target wants to custom lower this node.
987 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
990 SmallVector<SDValue, 8> Results;
991 TLI.ReplaceNodeResults(N, Results, DAG);
994 // The target didn't want to custom widen lower its result after all.
997 // Update the widening map.
998 assert(Results.size() == N->getNumValues() &&
999 "Custom lowering returned the wrong number of results!");
1000 for (unsigned i = 0, e = Results.size(); i != e; ++i)
1001 SetWidenedVector(SDValue(N, i), Results[i]);
1005 SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
1006 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
1008 ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
1009 return SDValue(N->getOperand(ResNo));
1012 /// Use ISD::EXTRACT_ELEMENT nodes to extract the low and high parts of the
1014 void DAGTypeLegalizer::GetPairElements(SDValue Pair,
1015 SDValue &Lo, SDValue &Hi) {
1017 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
1018 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
1019 DAG.getIntPtrConstant(0, dl));
1020 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
1021 DAG.getIntPtrConstant(1, dl));
1024 /// Build an integer with low bits Lo and high bits Hi.
1025 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
1026 // Arbitrarily use dlHi for result SDLoc
1029 EVT LVT = Lo.getValueType();
1030 EVT HVT = Hi.getValueType();
1031 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1032 LVT.getSizeInBits() + HVT.getSizeInBits());
1034 Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
1035 Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
1036 Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
1037 DAG.getConstant(LVT.getSizeInBits(), dlHi,
1038 TLI.getPointerTy(DAG.getDataLayout())));
1039 return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
1042 /// Convert the node into a libcall with the same prototype.
1043 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
1045 unsigned NumOps = N->getNumOperands();
1048 return TLI.makeLibCall(DAG, LC, N->getValueType(0), None, isSigned,
1050 } else if (NumOps == 1) {
1051 SDValue Op = N->getOperand(0);
1052 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Op, isSigned,
1054 } else if (NumOps == 2) {
1055 SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1056 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, isSigned,
1059 SmallVector<SDValue, 8> Ops(NumOps);
1060 for (unsigned i = 0; i < NumOps; ++i)
1061 Ops[i] = N->getOperand(i);
1063 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, isSigned, dl).first;
1066 /// Expand a node into a call to a libcall. Similar to ExpandLibCall except that
1067 /// the first operand is the in-chain.
1068 std::pair<SDValue, SDValue>
1069 DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC, SDNode *Node,
1071 SDValue InChain = Node->getOperand(0);
1073 TargetLowering::ArgListTy Args;
1074 TargetLowering::ArgListEntry Entry;
1075 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
1076 EVT ArgVT = Node->getOperand(i).getValueType();
1077 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1078 Entry.Node = Node->getOperand(i);
1080 Entry.isSExt = isSigned;
1081 Entry.isZExt = !isSigned;
1082 Args.push_back(Entry);
1084 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1085 TLI.getPointerTy(DAG.getDataLayout()));
1087 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1089 TargetLowering::CallLoweringInfo CLI(DAG);
1090 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
1091 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
1092 .setSExtResult(isSigned).setZExtResult(!isSigned);
1094 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
1099 /// Promote the given target boolean to a target boolean of the given type.
1100 /// A target boolean is an integer value, not necessarily of type i1, the bits
1101 /// of which conform to getBooleanContents.
1103 /// ValVT is the type of values that produced the boolean.
1104 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT ValVT) {
1106 EVT BoolVT = getSetCCResultType(ValVT);
1107 ISD::NodeType ExtendCode =
1108 TargetLowering::getExtendForContent(TLI.getBooleanContents(ValVT));
1109 return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
1112 /// Widen the given target boolean to a target boolean of the given type.
1113 /// The boolean vector is widened and then promoted to match the target boolean
1114 /// type of the given ValVT.
1115 SDValue DAGTypeLegalizer::WidenTargetBoolean(SDValue Bool, EVT ValVT,
1118 EVT BoolVT = Bool.getValueType();
1120 assert(ValVT.getVectorNumElements() > BoolVT.getVectorNumElements() &&
1121 TLI.isTypeLegal(ValVT) &&
1122 "Unexpected types in WidenTargetBoolean");
1123 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), BoolVT.getScalarType(),
1124 ValVT.getVectorNumElements());
1125 Bool = ModifyToType(Bool, WideVT, WithZeroes);
1126 return PromoteTargetBoolean(Bool, ValVT);
1129 /// Return the lower LoVT bits of Op in Lo and the upper HiVT bits in Hi.
1130 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1132 SDValue &Lo, SDValue &Hi) {
1134 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1135 Op.getValueSizeInBits() && "Invalid integer splitting!");
1136 Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
1137 Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
1138 DAG.getConstant(LoVT.getSizeInBits(), dl,
1139 TLI.getPointerTy(DAG.getDataLayout())));
1140 Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
1143 /// Return the lower and upper halves of Op's bits in a value type half the
1145 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1146 SDValue &Lo, SDValue &Hi) {
1148 EVT::getIntegerVT(*DAG.getContext(), Op.getValueSizeInBits() / 2);
1149 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1153 //===----------------------------------------------------------------------===//
1155 //===----------------------------------------------------------------------===//
1157 /// This transforms the SelectionDAG into a SelectionDAG that only uses types
1158 /// natively supported by the target. Returns "true" if it made any changes.
1160 /// Note that this is an involved process that may invalidate pointers into
1162 bool SelectionDAG::LegalizeTypes() {
1163 return DAGTypeLegalizer(*this).run();