[InstCombine] Signed saturation tests. NFC
[llvm-complete.git] / lib / CodeGen / SelectionDAG / LegalizeTypes.cpp
blobb596c174a2877404dd990d14641fae687fbbf098
1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the SelectionDAG::LegalizeTypes method. It transforms
10 // an arbitrary well-formed SelectionDAG to only consist of legal types. This
11 // is common code shared among the LegalizeTypes*.cpp files.
13 //===----------------------------------------------------------------------===//
15 #include "LegalizeTypes.h"
16 #include "SDNodeDbgValue.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/IR/CallingConv.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
26 #define DEBUG_TYPE "legalize-types"
28 static cl::opt<bool>
29 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
31 /// Do extensive, expensive, sanity checking.
32 void DAGTypeLegalizer::PerformExpensiveChecks() {
33 // If a node is not processed, then none of its values should be mapped by any
34 // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
36 // If a node is processed, then each value with an illegal type must be mapped
37 // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
38 // Values with a legal type may be mapped by ReplacedValues, but not by any of
39 // the other maps.
41 // Note that these invariants may not hold momentarily when processing a node:
42 // the node being processed may be put in a map before being marked Processed.
44 // Note that it is possible to have nodes marked NewNode in the DAG. This can
45 // occur in two ways. Firstly, a node may be created during legalization but
46 // never passed to the legalization core. This is usually due to the implicit
47 // folding that occurs when using the DAG.getNode operators. Secondly, a new
48 // node may be passed to the legalization core, but when analyzed may morph
49 // into a different node, leaving the original node as a NewNode in the DAG.
50 // A node may morph if one of its operands changes during analysis. Whether
51 // it actually morphs or not depends on whether, after updating its operands,
52 // it is equivalent to an existing node: if so, it morphs into that existing
53 // node (CSE). An operand can change during analysis if the operand is a new
54 // node that morphs, or it is a processed value that was mapped to some other
55 // value (as recorded in ReplacedValues) in which case the operand is turned
56 // into that other value. If a node morphs then the node it morphed into will
57 // be used instead of it for legalization, however the original node continues
58 // to live on in the DAG.
59 // The conclusion is that though there may be nodes marked NewNode in the DAG,
60 // all uses of such nodes are also marked NewNode: the result is a fungus of
61 // NewNodes growing on top of the useful nodes, and perhaps using them, but
62 // not used by them.
64 // If a value is mapped by ReplacedValues, then it must have no uses, except
65 // by nodes marked NewNode (see above).
67 // The final node obtained by mapping by ReplacedValues is not marked NewNode.
68 // Note that ReplacedValues should be applied iteratively.
70 // Note that the ReplacedValues map may also map deleted nodes (by iterating
71 // over the DAG we never dereference deleted nodes). This means that it may
72 // also map nodes marked NewNode if the deallocated memory was reallocated as
73 // another node, and that new node was not seen by the LegalizeTypes machinery
74 // (for example because it was created but not used). In general, we cannot
75 // distinguish between new nodes and deleted nodes.
76 SmallVector<SDNode*, 16> NewNodes;
77 for (SDNode &Node : DAG.allnodes()) {
78 // Remember nodes marked NewNode - they are subject to extra checking below.
79 if (Node.getNodeId() == NewNode)
80 NewNodes.push_back(&Node);
82 for (unsigned i = 0, e = Node.getNumValues(); i != e; ++i) {
83 SDValue Res(&Node, i);
84 bool Failed = false;
85 // Don't create a value in map.
86 auto ResId = (ValueToIdMap.count(Res)) ? ValueToIdMap[Res] : 0;
88 unsigned Mapped = 0;
89 if (ResId && (ReplacedValues.find(ResId) != ReplacedValues.end())) {
90 Mapped |= 1;
91 // Check that remapped values are only used by nodes marked NewNode.
92 for (SDNode::use_iterator UI = Node.use_begin(), UE = Node.use_end();
93 UI != UE; ++UI)
94 if (UI.getUse().getResNo() == i)
95 assert(UI->getNodeId() == NewNode &&
96 "Remapped value has non-trivial use!");
98 // Check that the final result of applying ReplacedValues is not
99 // marked NewNode.
100 auto NewValId = ReplacedValues[ResId];
101 auto I = ReplacedValues.find(NewValId);
102 while (I != ReplacedValues.end()) {
103 NewValId = I->second;
104 I = ReplacedValues.find(NewValId);
106 SDValue NewVal = getSDValue(NewValId);
107 (void)NewVal;
108 assert(NewVal.getNode()->getNodeId() != NewNode &&
109 "ReplacedValues maps to a new node!");
111 if (ResId && PromotedIntegers.find(ResId) != PromotedIntegers.end())
112 Mapped |= 2;
113 if (ResId && SoftenedFloats.find(ResId) != SoftenedFloats.end())
114 Mapped |= 4;
115 if (ResId && ScalarizedVectors.find(ResId) != ScalarizedVectors.end())
116 Mapped |= 8;
117 if (ResId && ExpandedIntegers.find(ResId) != ExpandedIntegers.end())
118 Mapped |= 16;
119 if (ResId && ExpandedFloats.find(ResId) != ExpandedFloats.end())
120 Mapped |= 32;
121 if (ResId && SplitVectors.find(ResId) != SplitVectors.end())
122 Mapped |= 64;
123 if (ResId && WidenedVectors.find(ResId) != WidenedVectors.end())
124 Mapped |= 128;
125 if (ResId && PromotedFloats.find(ResId) != PromotedFloats.end())
126 Mapped |= 256;
128 if (Node.getNodeId() != Processed) {
129 // Since we allow ReplacedValues to map deleted nodes, it may map nodes
130 // marked NewNode too, since a deleted node may have been reallocated as
131 // another node that has not been seen by the LegalizeTypes machinery.
132 if ((Node.getNodeId() == NewNode && Mapped > 1) ||
133 (Node.getNodeId() != NewNode && Mapped != 0)) {
134 dbgs() << "Unprocessed value in a map!";
135 Failed = true;
137 } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(&Node)) {
138 if (Mapped > 1) {
139 dbgs() << "Value with legal type was transformed!";
140 Failed = true;
142 } else {
143 if (Mapped == 0) {
144 dbgs() << "Processed value not in any map!";
145 Failed = true;
146 } else if (Mapped & (Mapped - 1)) {
147 dbgs() << "Value in multiple maps!";
148 Failed = true;
152 if (Failed) {
153 if (Mapped & 1)
154 dbgs() << " ReplacedValues";
155 if (Mapped & 2)
156 dbgs() << " PromotedIntegers";
157 if (Mapped & 4)
158 dbgs() << " SoftenedFloats";
159 if (Mapped & 8)
160 dbgs() << " ScalarizedVectors";
161 if (Mapped & 16)
162 dbgs() << " ExpandedIntegers";
163 if (Mapped & 32)
164 dbgs() << " ExpandedFloats";
165 if (Mapped & 64)
166 dbgs() << " SplitVectors";
167 if (Mapped & 128)
168 dbgs() << " WidenedVectors";
169 if (Mapped & 256)
170 dbgs() << " PromotedFloats";
171 dbgs() << "\n";
172 llvm_unreachable(nullptr);
177 // Checked that NewNodes are only used by other NewNodes.
178 for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
179 SDNode *N = NewNodes[i];
180 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
181 UI != UE; ++UI)
182 assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
186 /// This is the main entry point for the type legalizer. This does a top-down
187 /// traversal of the dag, legalizing types as it goes. Returns "true" if it made
188 /// any changes.
189 bool DAGTypeLegalizer::run() {
190 bool Changed = false;
192 // Create a dummy node (which is not added to allnodes), that adds a reference
193 // to the root node, preventing it from being deleted, and tracking any
194 // changes of the root.
195 HandleSDNode Dummy(DAG.getRoot());
196 Dummy.setNodeId(Unanalyzed);
198 // The root of the dag may dangle to deleted nodes until the type legalizer is
199 // done. Set it to null to avoid confusion.
200 DAG.setRoot(SDValue());
202 // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
203 // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
204 // non-leaves.
205 for (SDNode &Node : DAG.allnodes()) {
206 if (Node.getNumOperands() == 0) {
207 AddToWorklist(&Node);
208 } else {
209 Node.setNodeId(Unanalyzed);
213 // Now that we have a set of nodes to process, handle them all.
214 while (!Worklist.empty()) {
215 #ifndef EXPENSIVE_CHECKS
216 if (EnableExpensiveChecks)
217 #endif
218 PerformExpensiveChecks();
220 SDNode *N = Worklist.back();
221 Worklist.pop_back();
222 assert(N->getNodeId() == ReadyToProcess &&
223 "Node should be ready if on worklist!");
225 LLVM_DEBUG(dbgs() << "Legalizing node: "; N->dump(&DAG));
226 if (IgnoreNodeResults(N)) {
227 LLVM_DEBUG(dbgs() << "Ignoring node results\n");
228 goto ScanOperands;
231 // Scan the values produced by the node, checking to see if any result
232 // types are illegal.
233 for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
234 EVT ResultVT = N->getValueType(i);
235 LLVM_DEBUG(dbgs() << "Analyzing result type: " << ResultVT.getEVTString()
236 << "\n");
237 switch (getTypeAction(ResultVT)) {
238 case TargetLowering::TypeLegal:
239 LLVM_DEBUG(dbgs() << "Legal result type\n");
240 break;
241 // The following calls must take care of *all* of the node's results,
242 // not just the illegal result they were passed (this includes results
243 // with a legal type). Results can be remapped using ReplaceValueWith,
244 // or their promoted/expanded/etc values registered in PromotedIntegers,
245 // ExpandedIntegers etc.
246 case TargetLowering::TypePromoteInteger:
247 PromoteIntegerResult(N, i);
248 Changed = true;
249 goto NodeDone;
250 case TargetLowering::TypeExpandInteger:
251 ExpandIntegerResult(N, i);
252 Changed = true;
253 goto NodeDone;
254 case TargetLowering::TypeSoftenFloat:
255 SoftenFloatResult(N, i);
256 Changed = true;
257 goto NodeDone;
258 case TargetLowering::TypeExpandFloat:
259 ExpandFloatResult(N, i);
260 Changed = true;
261 goto NodeDone;
262 case TargetLowering::TypeScalarizeVector:
263 ScalarizeVectorResult(N, i);
264 Changed = true;
265 goto NodeDone;
266 case TargetLowering::TypeSplitVector:
267 SplitVectorResult(N, i);
268 Changed = true;
269 goto NodeDone;
270 case TargetLowering::TypeWidenVector:
271 WidenVectorResult(N, i);
272 Changed = true;
273 goto NodeDone;
274 case TargetLowering::TypePromoteFloat:
275 PromoteFloatResult(N, i);
276 Changed = true;
277 goto NodeDone;
281 ScanOperands:
282 // Scan the operand list for the node, handling any nodes with operands that
283 // are illegal.
285 unsigned NumOperands = N->getNumOperands();
286 bool NeedsReanalyzing = false;
287 unsigned i;
288 for (i = 0; i != NumOperands; ++i) {
289 if (IgnoreNodeResults(N->getOperand(i).getNode()))
290 continue;
292 const auto Op = N->getOperand(i);
293 LLVM_DEBUG(dbgs() << "Analyzing operand: "; Op.dump(&DAG));
294 EVT OpVT = Op.getValueType();
295 switch (getTypeAction(OpVT)) {
296 case TargetLowering::TypeLegal:
297 LLVM_DEBUG(dbgs() << "Legal operand\n");
298 continue;
299 // The following calls must either replace all of the node's results
300 // using ReplaceValueWith, and return "false"; or update the node's
301 // operands in place, and return "true".
302 case TargetLowering::TypePromoteInteger:
303 NeedsReanalyzing = PromoteIntegerOperand(N, i);
304 Changed = true;
305 break;
306 case TargetLowering::TypeExpandInteger:
307 NeedsReanalyzing = ExpandIntegerOperand(N, i);
308 Changed = true;
309 break;
310 case TargetLowering::TypeSoftenFloat:
311 NeedsReanalyzing = SoftenFloatOperand(N, i);
312 Changed = true;
313 break;
314 case TargetLowering::TypeExpandFloat:
315 NeedsReanalyzing = ExpandFloatOperand(N, i);
316 Changed = true;
317 break;
318 case TargetLowering::TypeScalarizeVector:
319 NeedsReanalyzing = ScalarizeVectorOperand(N, i);
320 Changed = true;
321 break;
322 case TargetLowering::TypeSplitVector:
323 NeedsReanalyzing = SplitVectorOperand(N, i);
324 Changed = true;
325 break;
326 case TargetLowering::TypeWidenVector:
327 NeedsReanalyzing = WidenVectorOperand(N, i);
328 Changed = true;
329 break;
330 case TargetLowering::TypePromoteFloat:
331 NeedsReanalyzing = PromoteFloatOperand(N, i);
332 Changed = true;
333 break;
335 break;
338 // The sub-method updated N in place. Check to see if any operands are new,
339 // and if so, mark them. If the node needs revisiting, don't add all users
340 // to the worklist etc.
341 if (NeedsReanalyzing) {
342 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
344 N->setNodeId(NewNode);
345 // Recompute the NodeId and correct processed operands, adding the node to
346 // the worklist if ready.
347 SDNode *M = AnalyzeNewNode(N);
348 if (M == N)
349 // The node didn't morph - nothing special to do, it will be revisited.
350 continue;
352 // The node morphed - this is equivalent to legalizing by replacing every
353 // value of N with the corresponding value of M. So do that now.
354 assert(N->getNumValues() == M->getNumValues() &&
355 "Node morphing changed the number of results!");
356 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
357 // Replacing the value takes care of remapping the new value.
358 ReplaceValueWith(SDValue(N, i), SDValue(M, i));
359 assert(N->getNodeId() == NewNode && "Unexpected node state!");
360 // The node continues to live on as part of the NewNode fungus that
361 // grows on top of the useful nodes. Nothing more needs to be done
362 // with it - move on to the next node.
363 continue;
366 if (i == NumOperands) {
367 LLVM_DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG);
368 dbgs() << "\n");
371 NodeDone:
373 // If we reach here, the node was processed, potentially creating new nodes.
374 // Mark it as processed and add its users to the worklist as appropriate.
375 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
376 N->setNodeId(Processed);
378 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
379 UI != E; ++UI) {
380 SDNode *User = *UI;
381 int NodeId = User->getNodeId();
383 // This node has two options: it can either be a new node or its Node ID
384 // may be a count of the number of operands it has that are not ready.
385 if (NodeId > 0) {
386 User->setNodeId(NodeId-1);
388 // If this was the last use it was waiting on, add it to the ready list.
389 if (NodeId-1 == ReadyToProcess)
390 Worklist.push_back(User);
391 continue;
394 // If this is an unreachable new node, then ignore it. If it ever becomes
395 // reachable by being used by a newly created node then it will be handled
396 // by AnalyzeNewNode.
397 if (NodeId == NewNode)
398 continue;
400 // Otherwise, this node is new: this is the first operand of it that
401 // became ready. Its new NodeId is the number of operands it has minus 1
402 // (as this node is now processed).
403 assert(NodeId == Unanalyzed && "Unknown node ID!");
404 User->setNodeId(User->getNumOperands() - 1);
406 // If the node only has a single operand, it is now ready.
407 if (User->getNumOperands() == 1)
408 Worklist.push_back(User);
412 #ifndef EXPENSIVE_CHECKS
413 if (EnableExpensiveChecks)
414 #endif
415 PerformExpensiveChecks();
417 // If the root changed (e.g. it was a dead load) update the root.
418 DAG.setRoot(Dummy.getValue());
420 // Remove dead nodes. This is important to do for cleanliness but also before
421 // the checking loop below. Implicit folding by the DAG.getNode operators and
422 // node morphing can cause unreachable nodes to be around with their flags set
423 // to new.
424 DAG.RemoveDeadNodes();
426 // In a debug build, scan all the nodes to make sure we found them all. This
427 // ensures that there are no cycles and that everything got processed.
428 #ifndef NDEBUG
429 for (SDNode &Node : DAG.allnodes()) {
430 bool Failed = false;
432 // Check that all result types are legal.
433 if (!IgnoreNodeResults(&Node))
434 for (unsigned i = 0, NumVals = Node.getNumValues(); i < NumVals; ++i)
435 if (!isTypeLegal(Node.getValueType(i))) {
436 dbgs() << "Result type " << i << " illegal: ";
437 Node.dump(&DAG);
438 Failed = true;
441 // Check that all operand types are legal.
442 for (unsigned i = 0, NumOps = Node.getNumOperands(); i < NumOps; ++i)
443 if (!IgnoreNodeResults(Node.getOperand(i).getNode()) &&
444 !isTypeLegal(Node.getOperand(i).getValueType())) {
445 dbgs() << "Operand type " << i << " illegal: ";
446 Node.getOperand(i).dump(&DAG);
447 Failed = true;
450 if (Node.getNodeId() != Processed) {
451 if (Node.getNodeId() == NewNode)
452 dbgs() << "New node not analyzed?\n";
453 else if (Node.getNodeId() == Unanalyzed)
454 dbgs() << "Unanalyzed node not noticed?\n";
455 else if (Node.getNodeId() > 0)
456 dbgs() << "Operand not processed?\n";
457 else if (Node.getNodeId() == ReadyToProcess)
458 dbgs() << "Not added to worklist?\n";
459 Failed = true;
462 if (Failed) {
463 Node.dump(&DAG); dbgs() << "\n";
464 llvm_unreachable(nullptr);
467 #endif
469 return Changed;
472 /// The specified node is the root of a subtree of potentially new nodes.
473 /// Correct any processed operands (this may change the node) and calculate the
474 /// NodeId. If the node itself changes to a processed node, it is not remapped -
475 /// the caller needs to take care of this. Returns the potentially changed node.
476 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
477 // If this was an existing node that is already done, we're done.
478 if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
479 return N;
481 // Okay, we know that this node is new. Recursively walk all of its operands
482 // to see if they are new also. The depth of this walk is bounded by the size
483 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
484 // about revisiting of nodes.
486 // As we walk the operands, keep track of the number of nodes that are
487 // processed. If non-zero, this will become the new nodeid of this node.
488 // Operands may morph when they are analyzed. If so, the node will be
489 // updated after all operands have been analyzed. Since this is rare,
490 // the code tries to minimize overhead in the non-morphing case.
492 std::vector<SDValue> NewOps;
493 unsigned NumProcessed = 0;
494 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
495 SDValue OrigOp = N->getOperand(i);
496 SDValue Op = OrigOp;
498 AnalyzeNewValue(Op); // Op may morph.
500 if (Op.getNode()->getNodeId() == Processed)
501 ++NumProcessed;
503 if (!NewOps.empty()) {
504 // Some previous operand changed. Add this one to the list.
505 NewOps.push_back(Op);
506 } else if (Op != OrigOp) {
507 // This is the first operand to change - add all operands so far.
508 NewOps.insert(NewOps.end(), N->op_begin(), N->op_begin() + i);
509 NewOps.push_back(Op);
513 // Some operands changed - update the node.
514 if (!NewOps.empty()) {
515 SDNode *M = DAG.UpdateNodeOperands(N, NewOps);
516 if (M != N) {
517 // The node morphed into a different node. Normally for this to happen
518 // the original node would have to be marked NewNode. However this can
519 // in theory momentarily not be the case while ReplaceValueWith is doing
520 // its stuff. Mark the original node NewNode to help sanity checking.
521 N->setNodeId(NewNode);
522 if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
523 // It morphed into a previously analyzed node - nothing more to do.
524 return M;
526 // It morphed into a different new node. Do the equivalent of passing
527 // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
528 // to remap the operands, since they are the same as the operands we
529 // remapped above.
530 N = M;
534 // Calculate the NodeId.
535 N->setNodeId(N->getNumOperands() - NumProcessed);
536 if (N->getNodeId() == ReadyToProcess)
537 Worklist.push_back(N);
539 return 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.
548 RemapValue(Val);
551 /// If the specified value was already legalized to another value,
552 /// replace it by that value.
553 void DAGTypeLegalizer::RemapValue(SDValue &V) {
554 auto Id = getTableId(V);
555 V = getSDValue(Id);
558 void DAGTypeLegalizer::RemapId(TableId &Id) {
559 auto I = ReplacedValues.find(Id);
560 if (I != ReplacedValues.end()) {
561 assert(Id != I->second && "Id is mapped to itself.");
562 // Use path compression to speed up future lookups if values get multiply
563 // replaced with other values.
564 RemapId(I->second);
565 Id = I->second;
567 // Note that N = IdToValueMap[Id] it is possible to have
568 // N.getNode()->getNodeId() == NewNode at this point because it is possible
569 // for a node to be put in the map before being processed.
573 namespace {
574 /// This class is a DAGUpdateListener that listens for updates to nodes and
575 /// recomputes their ready state.
576 class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
577 DAGTypeLegalizer &DTL;
578 SmallSetVector<SDNode*, 16> &NodesToAnalyze;
579 public:
580 explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
581 SmallSetVector<SDNode*, 16> &nta)
582 : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
583 DTL(dtl), NodesToAnalyze(nta) {}
585 void NodeDeleted(SDNode *N, SDNode *E) override {
586 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
587 N->getNodeId() != DAGTypeLegalizer::Processed &&
588 "Invalid node ID for RAUW deletion!");
589 // It is possible, though rare, for the deleted node N to occur as a
590 // target in a map, so note the replacement N -> E in ReplacedValues.
591 assert(E && "Node not replaced?");
592 DTL.NoteDeletion(N, E);
594 // In theory the deleted node could also have been scheduled for analysis.
595 // So remove it from the set of nodes which will be analyzed.
596 NodesToAnalyze.remove(N);
598 // In general nothing needs to be done for E, since it didn't change but
599 // only gained new uses. However N -> E was just added to ReplacedValues,
600 // and the result of a ReplacedValues mapping is not allowed to be marked
601 // NewNode. So if E is marked NewNode, then it needs to be analyzed.
602 if (E->getNodeId() == DAGTypeLegalizer::NewNode)
603 NodesToAnalyze.insert(E);
606 void NodeUpdated(SDNode *N) override {
607 // Node updates can mean pretty much anything. It is possible that an
608 // operand was set to something already processed (f.e.) in which case
609 // this node could become ready. Recompute its flags.
610 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
611 N->getNodeId() != DAGTypeLegalizer::Processed &&
612 "Invalid node ID for RAUW deletion!");
613 N->setNodeId(DAGTypeLegalizer::NewNode);
614 NodesToAnalyze.insert(N);
620 /// The specified value was legalized to the specified other value.
621 /// Update the DAG and NodeIds replacing any uses of From to use To instead.
622 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
623 assert(From.getNode() != To.getNode() && "Potential legalization loop!");
625 // If expansion produced new nodes, make sure they are properly marked.
626 AnalyzeNewValue(To);
628 // Anything that used the old node should now use the new one. Note that this
629 // can potentially cause recursive merging.
630 SmallSetVector<SDNode*, 16> NodesToAnalyze;
631 NodeUpdateListener NUL(*this, NodesToAnalyze);
632 do {
634 // The old node may be present in a map like ExpandedIntegers or
635 // PromotedIntegers. Inform maps about the replacement.
636 auto FromId = getTableId(From);
637 auto ToId = getTableId(To);
639 if (FromId != ToId)
640 ReplacedValues[FromId] = ToId;
641 DAG.ReplaceAllUsesOfValueWith(From, To);
643 // Process the list of nodes that need to be reanalyzed.
644 while (!NodesToAnalyze.empty()) {
645 SDNode *N = NodesToAnalyze.back();
646 NodesToAnalyze.pop_back();
647 if (N->getNodeId() != DAGTypeLegalizer::NewNode)
648 // The node was analyzed while reanalyzing an earlier node - it is safe
649 // to skip. Note that this is not a morphing node - otherwise it would
650 // still be marked NewNode.
651 continue;
653 // Analyze the node's operands and recalculate the node ID.
654 SDNode *M = AnalyzeNewNode(N);
655 if (M != N) {
656 // The node morphed into a different node. Make everyone use the new
657 // node instead.
658 assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
659 assert(N->getNumValues() == M->getNumValues() &&
660 "Node morphing changed the number of results!");
661 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
662 SDValue OldVal(N, i);
663 SDValue NewVal(M, i);
664 if (M->getNodeId() == Processed)
665 RemapValue(NewVal);
666 // OldVal may be a target of the ReplacedValues map which was marked
667 // NewNode to force reanalysis because it was updated. Ensure that
668 // anything that ReplacedValues mapped to OldVal will now be mapped
669 // all the way to NewVal.
670 auto OldValId = getTableId(OldVal);
671 auto NewValId = getTableId(NewVal);
672 DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
673 if (OldValId != NewValId)
674 ReplacedValues[OldValId] = NewValId;
676 // The original node continues to exist in the DAG, marked NewNode.
679 // When recursively update nodes with new nodes, it is possible to have
680 // new uses of From due to CSE. If this happens, replace the new uses of
681 // From with To.
682 } while (!From.use_empty());
685 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
686 assert(Result.getValueType() ==
687 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
688 "Invalid type for promoted integer");
689 AnalyzeNewValue(Result);
691 auto &OpIdEntry = PromotedIntegers[getTableId(Op)];
692 assert((OpIdEntry == 0) && "Node is already promoted!");
693 OpIdEntry = getTableId(Result);
694 Result->setFlags(Op->getFlags());
696 DAG.transferDbgValues(Op, Result);
699 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
700 assert(Result.getValueType() ==
701 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
702 "Invalid type for softened float");
703 AnalyzeNewValue(Result);
705 auto &OpIdEntry = SoftenedFloats[getTableId(Op)];
706 assert((OpIdEntry == 0) && "Node is already converted to integer!");
707 OpIdEntry = getTableId(Result);
710 void DAGTypeLegalizer::SetPromotedFloat(SDValue Op, SDValue Result) {
711 assert(Result.getValueType() ==
712 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
713 "Invalid type for promoted float");
714 AnalyzeNewValue(Result);
716 auto &OpIdEntry = PromotedFloats[getTableId(Op)];
717 assert((OpIdEntry == 0) && "Node is already promoted!");
718 OpIdEntry = getTableId(Result);
721 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
722 // Note that in some cases vector operation operands may be greater than
723 // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
724 // a constant i8 operand.
725 assert(Result.getValueSizeInBits() >= Op.getScalarValueSizeInBits() &&
726 "Invalid type for scalarized vector");
727 AnalyzeNewValue(Result);
729 auto &OpIdEntry = ScalarizedVectors[getTableId(Op)];
730 assert((OpIdEntry == 0) && "Node is already scalarized!");
731 OpIdEntry = getTableId(Result);
734 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
735 SDValue &Hi) {
736 std::pair<TableId, TableId> &Entry = ExpandedIntegers[getTableId(Op)];
737 assert((Entry.first != 0) && "Operand isn't expanded");
738 Lo = getSDValue(Entry.first);
739 Hi = getSDValue(Entry.second);
742 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
743 SDValue Hi) {
744 assert(Lo.getValueType() ==
745 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
746 Hi.getValueType() == Lo.getValueType() &&
747 "Invalid type for expanded integer");
748 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
749 AnalyzeNewValue(Lo);
750 AnalyzeNewValue(Hi);
752 // Transfer debug values. Don't invalidate the source debug value until it's
753 // been transferred to the high and low bits.
754 if (DAG.getDataLayout().isBigEndian()) {
755 DAG.transferDbgValues(Op, Hi, 0, Hi.getValueSizeInBits(), false);
756 DAG.transferDbgValues(Op, Lo, Hi.getValueSizeInBits(),
757 Lo.getValueSizeInBits());
758 } else {
759 DAG.transferDbgValues(Op, Lo, 0, Lo.getValueSizeInBits(), false);
760 DAG.transferDbgValues(Op, Hi, Lo.getValueSizeInBits(),
761 Hi.getValueSizeInBits());
764 // Remember that this is the result of the node.
765 std::pair<TableId, TableId> &Entry = ExpandedIntegers[getTableId(Op)];
766 assert((Entry.first == 0) && "Node already expanded");
767 Entry.first = getTableId(Lo);
768 Entry.second = getTableId(Hi);
771 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
772 SDValue &Hi) {
773 std::pair<TableId, TableId> &Entry = ExpandedFloats[getTableId(Op)];
774 assert((Entry.first != 0) && "Operand isn't expanded");
775 Lo = getSDValue(Entry.first);
776 Hi = getSDValue(Entry.second);
779 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
780 SDValue Hi) {
781 assert(Lo.getValueType() ==
782 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
783 Hi.getValueType() == Lo.getValueType() &&
784 "Invalid type for expanded float");
785 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
786 AnalyzeNewValue(Lo);
787 AnalyzeNewValue(Hi);
789 std::pair<TableId, TableId> &Entry = ExpandedFloats[getTableId(Op)];
790 assert((Entry.first == 0) && "Node already expanded");
791 Entry.first = getTableId(Lo);
792 Entry.second = getTableId(Hi);
795 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
796 SDValue &Hi) {
797 std::pair<TableId, TableId> &Entry = SplitVectors[getTableId(Op)];
798 Lo = getSDValue(Entry.first);
799 Hi = getSDValue(Entry.second);
800 assert(Lo.getNode() && "Operand isn't split");
804 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
805 SDValue Hi) {
806 assert(Lo.getValueType().getVectorElementType() ==
807 Op.getValueType().getVectorElementType() &&
808 2*Lo.getValueType().getVectorNumElements() ==
809 Op.getValueType().getVectorNumElements() &&
810 Hi.getValueType() == Lo.getValueType() &&
811 "Invalid type for split vector");
812 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
813 AnalyzeNewValue(Lo);
814 AnalyzeNewValue(Hi);
816 // Remember that this is the result of the node.
817 std::pair<TableId, TableId> &Entry = SplitVectors[getTableId(Op)];
818 assert((Entry.first == 0) && "Node already split");
819 Entry.first = getTableId(Lo);
820 Entry.second = getTableId(Hi);
823 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
824 assert(Result.getValueType() ==
825 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
826 "Invalid type for widened vector");
827 AnalyzeNewValue(Result);
829 auto &OpIdEntry = WidenedVectors[getTableId(Op)];
830 assert((OpIdEntry == 0) && "Node already widened!");
831 OpIdEntry = getTableId(Result);
835 //===----------------------------------------------------------------------===//
836 // Utilities.
837 //===----------------------------------------------------------------------===//
839 /// Convert to an integer of the same size.
840 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
841 unsigned BitWidth = Op.getValueSizeInBits();
842 return DAG.getNode(ISD::BITCAST, SDLoc(Op),
843 EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
846 /// Convert to a vector of integers of the same size.
847 SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
848 assert(Op.getValueType().isVector() && "Only applies to vectors!");
849 unsigned EltWidth = Op.getScalarValueSizeInBits();
850 EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
851 auto EltCnt = Op.getValueType().getVectorElementCount();
852 return DAG.getNode(ISD::BITCAST, SDLoc(Op),
853 EVT::getVectorVT(*DAG.getContext(), EltNVT, EltCnt), Op);
856 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
857 EVT DestVT) {
858 SDLoc dl(Op);
859 // Create the stack frame object. Make sure it is aligned for both
860 // the source and destination types.
861 SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
862 // Emit a store to the stack slot.
863 SDValue Store =
864 DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr, MachinePointerInfo());
865 // Result is a load from the stack slot.
866 return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo());
869 /// Replace the node's results with custom code provided by the target and
870 /// return "true", or do nothing and return "false".
871 /// The last parameter is FALSE if we are dealing with a node with legal
872 /// result types and illegal operand. The second parameter denotes the type of
873 /// illegal OperandNo in that case.
874 /// The last parameter being TRUE means we are dealing with a
875 /// node with illegal result types. The second parameter denotes the type of
876 /// illegal ResNo in that case.
877 bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
878 // See if the target wants to custom lower this node.
879 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
880 return false;
882 SmallVector<SDValue, 8> Results;
883 if (LegalizeResult)
884 TLI.ReplaceNodeResults(N, Results, DAG);
885 else
886 TLI.LowerOperationWrapper(N, Results, DAG);
888 if (Results.empty())
889 // The target didn't want to custom lower it after all.
890 return false;
892 // When called from DAGTypeLegalizer::ExpandIntegerResult, we might need to
893 // provide the same kind of custom splitting behavior.
894 if (Results.size() == N->getNumValues() + 1 && LegalizeResult) {
895 // We've legalized a return type by splitting it. If there is a chain,
896 // replace that too.
897 SetExpandedInteger(SDValue(N, 0), Results[0], Results[1]);
898 if (N->getNumValues() > 1)
899 ReplaceValueWith(SDValue(N, 1), Results[2]);
900 return true;
903 // Make everything that once used N's values now use those in Results instead.
904 assert(Results.size() == N->getNumValues() &&
905 "Custom lowering returned the wrong number of results!");
906 for (unsigned i = 0, e = Results.size(); i != e; ++i) {
907 ReplaceValueWith(SDValue(N, i), Results[i]);
909 return true;
913 /// Widen the node's results with custom code provided by the target and return
914 /// "true", or do nothing and return "false".
915 bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
916 // See if the target wants to custom lower this node.
917 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
918 return false;
920 SmallVector<SDValue, 8> Results;
921 TLI.ReplaceNodeResults(N, Results, DAG);
923 if (Results.empty())
924 // The target didn't want to custom widen lower its result after all.
925 return false;
927 // Update the widening map.
928 assert(Results.size() == N->getNumValues() &&
929 "Custom lowering returned the wrong number of results!");
930 for (unsigned i = 0, e = Results.size(); i != e; ++i) {
931 // If this is a chain output just replace it.
932 if (Results[i].getValueType() == MVT::Other)
933 ReplaceValueWith(SDValue(N, i), Results[i]);
934 else
935 SetWidenedVector(SDValue(N, i), Results[i]);
937 return true;
940 SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
941 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
942 if (i != ResNo)
943 ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
944 return SDValue(N->getOperand(ResNo));
947 /// Use ISD::EXTRACT_ELEMENT nodes to extract the low and high parts of the
948 /// given value.
949 void DAGTypeLegalizer::GetPairElements(SDValue Pair,
950 SDValue &Lo, SDValue &Hi) {
951 SDLoc dl(Pair);
952 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
953 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
954 DAG.getIntPtrConstant(0, dl));
955 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
956 DAG.getIntPtrConstant(1, dl));
959 /// Build an integer with low bits Lo and high bits Hi.
960 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
961 // Arbitrarily use dlHi for result SDLoc
962 SDLoc dlHi(Hi);
963 SDLoc dlLo(Lo);
964 EVT LVT = Lo.getValueType();
965 EVT HVT = Hi.getValueType();
966 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
967 LVT.getSizeInBits() + HVT.getSizeInBits());
969 EVT ShiftAmtVT = TLI.getShiftAmountTy(NVT, DAG.getDataLayout(), false);
970 Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
971 Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
972 Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
973 DAG.getConstant(LVT.getSizeInBits(), dlHi, ShiftAmtVT));
974 return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
977 /// Convert the node into a libcall with the same prototype.
978 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
979 bool isSigned) {
980 TargetLowering::MakeLibCallOptions CallOptions;
981 CallOptions.setSExt(isSigned);
982 unsigned NumOps = N->getNumOperands();
983 SDLoc dl(N);
984 if (NumOps == 0) {
985 return TLI.makeLibCall(DAG, LC, N->getValueType(0), None, CallOptions,
986 dl).first;
987 } else if (NumOps == 1) {
988 SDValue Op = N->getOperand(0);
989 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Op, CallOptions,
990 dl).first;
991 } else if (NumOps == 2) {
992 SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
993 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, CallOptions,
994 dl).first;
996 SmallVector<SDValue, 8> Ops(NumOps);
997 for (unsigned i = 0; i < NumOps; ++i)
998 Ops[i] = N->getOperand(i);
1000 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, CallOptions, dl).first;
1003 /// Expand a node into a call to a libcall. Similar to ExpandLibCall except that
1004 /// the first operand is the in-chain.
1005 std::pair<SDValue, SDValue>
1006 DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC, SDNode *Node,
1007 bool isSigned) {
1008 SDValue InChain = Node->getOperand(0);
1010 TargetLowering::ArgListTy Args;
1011 TargetLowering::ArgListEntry Entry;
1012 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
1013 EVT ArgVT = Node->getOperand(i).getValueType();
1014 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1015 Entry.Node = Node->getOperand(i);
1016 Entry.Ty = ArgTy;
1017 Entry.IsSExt = isSigned;
1018 Entry.IsZExt = !isSigned;
1019 Args.push_back(Entry);
1021 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1022 TLI.getPointerTy(DAG.getDataLayout()));
1024 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1026 TargetLowering::CallLoweringInfo CLI(DAG);
1027 CLI.setDebugLoc(SDLoc(Node))
1028 .setChain(InChain)
1029 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
1030 std::move(Args))
1031 .setSExtResult(isSigned)
1032 .setZExtResult(!isSigned);
1034 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
1036 return CallInfo;
1039 /// Promote the given target boolean to a target boolean of the given type.
1040 /// A target boolean is an integer value, not necessarily of type i1, the bits
1041 /// of which conform to getBooleanContents.
1043 /// ValVT is the type of values that produced the boolean.
1044 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT ValVT) {
1045 SDLoc dl(Bool);
1046 EVT BoolVT = getSetCCResultType(ValVT);
1047 ISD::NodeType ExtendCode =
1048 TargetLowering::getExtendForContent(TLI.getBooleanContents(ValVT));
1049 return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
1052 /// Return the lower LoVT bits of Op in Lo and the upper HiVT bits in Hi.
1053 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1054 EVT LoVT, EVT HiVT,
1055 SDValue &Lo, SDValue &Hi) {
1056 SDLoc dl(Op);
1057 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1058 Op.getValueSizeInBits() && "Invalid integer splitting!");
1059 Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
1060 unsigned ReqShiftAmountInBits =
1061 Log2_32_Ceil(Op.getValueType().getSizeInBits());
1062 MVT ShiftAmountTy =
1063 TLI.getScalarShiftAmountTy(DAG.getDataLayout(), Op.getValueType());
1064 if (ReqShiftAmountInBits > ShiftAmountTy.getSizeInBits())
1065 ShiftAmountTy = MVT::getIntegerVT(NextPowerOf2(ReqShiftAmountInBits));
1066 Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
1067 DAG.getConstant(LoVT.getSizeInBits(), dl, ShiftAmountTy));
1068 Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
1071 /// Return the lower and upper halves of Op's bits in a value type half the
1072 /// size of Op's.
1073 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1074 SDValue &Lo, SDValue &Hi) {
1075 EVT HalfVT =
1076 EVT::getIntegerVT(*DAG.getContext(), Op.getValueSizeInBits() / 2);
1077 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1081 //===----------------------------------------------------------------------===//
1082 // Entry Point
1083 //===----------------------------------------------------------------------===//
1085 /// This transforms the SelectionDAG into a SelectionDAG that only uses types
1086 /// natively supported by the target. Returns "true" if it made any changes.
1088 /// Note that this is an involved process that may invalidate pointers into
1089 /// the graph.
1090 bool SelectionDAG::LegalizeTypes() {
1091 return DAGTypeLegalizer(*this).run();