1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::LegalizeTypes method. It transforms
11 // an arbitrary well-formed SelectionDAG to only consist of legal types. This
12 // is common code shared among the LegalizeTypes*.cpp files.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
23 using namespace llvm;
24
25 #define DEBUG_TYPE "legalize-types"
26
27 static cl::opt<bool>
28 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
29
30 /// PerformExpensiveChecks - Do extensive, expensive, sanity checking.
PerformExpensiveChecks()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.
34
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
38 // the other maps.
39
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.
42
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
61 // not used by them.
62
63 // If a value is mapped by ReplacedValues, then it must have no uses, except
64 // by nodes marked NewNode (see above).
65
66 // The final node obtained by mapping by ReplacedValues is not marked NewNode.
67 // Note that ReplacedValues should be applied iteratively.
68
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);
80
81 for (unsigned i = 0, e = Node.getNumValues(); i != e; ++i) {
82 SDValue Res(&Node, i);
83 bool Failed = false;
84
85 unsigned Mapped = 0;
86 if (ReplacedValues.find(Res) != ReplacedValues.end()) {
87 Mapped |= 1;
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();
90 UI != UE; ++UI)
91 if (UI.getUse().getResNo() == i)
92 assert(UI->getNodeId() == NewNode &&
93 "Remapped value has non-trivial use!");
94
95 // Check that the final result of applying ReplacedValues is not
96 // marked NewNode.
97 SDValue NewVal = ReplacedValues[Res];
98 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
99 while (I != ReplacedValues.end()) {
100 NewVal = I->second;
101 I = ReplacedValues.find(NewVal);
102 }
103 assert(NewVal.getNode()->getNodeId() != NewNode &&
104 "ReplacedValues maps to a new node!");
105 }
106 if (PromotedIntegers.find(Res) != PromotedIntegers.end())
107 Mapped |= 2;
108 if (SoftenedFloats.find(Res) != SoftenedFloats.end())
109 Mapped |= 4;
110 if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
111 Mapped |= 8;
112 if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
113 Mapped |= 16;
114 if (ExpandedFloats.find(Res) != ExpandedFloats.end())
115 Mapped |= 32;
116 if (SplitVectors.find(Res) != SplitVectors.end())
117 Mapped |= 64;
118 if (WidenedVectors.find(Res) != WidenedVectors.end())
119 Mapped |= 128;
120
121 if (Node.getNodeId() != Processed) {
122 // Since we allow ReplacedValues to map deleted nodes, it may map nodes
123 // marked NewNode too, since a deleted node may have been reallocated as
124 // another node that has not been seen by the LegalizeTypes machinery.
125 if ((Node.getNodeId() == NewNode && Mapped > 1) ||
126 (Node.getNodeId() != NewNode && Mapped != 0)) {
127 dbgs() << "Unprocessed value in a map!";
128 Failed = true;
129 }
130 } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(&Node)) {
131 if (Mapped > 1) {
132 dbgs() << "Value with legal type was transformed!";
133 Failed = true;
134 }
135 } else {
136 if (Mapped == 0) {
137 dbgs() << "Processed value not in any map!";
138 Failed = true;
139 } else if (Mapped & (Mapped - 1)) {
140 dbgs() << "Value in multiple maps!";
141 Failed = true;
142 }
143 }
144
145 if (Failed) {
146 if (Mapped & 1)
147 dbgs() << " ReplacedValues";
148 if (Mapped & 2)
149 dbgs() << " PromotedIntegers";
150 if (Mapped & 4)
151 dbgs() << " SoftenedFloats";
152 if (Mapped & 8)
153 dbgs() << " ScalarizedVectors";
154 if (Mapped & 16)
155 dbgs() << " ExpandedIntegers";
156 if (Mapped & 32)
157 dbgs() << " ExpandedFloats";
158 if (Mapped & 64)
159 dbgs() << " SplitVectors";
160 if (Mapped & 128)
161 dbgs() << " WidenedVectors";
162 dbgs() << "\n";
163 llvm_unreachable(nullptr);
164 }
165 }
166 }
167
168 // Checked that NewNodes are only used by other NewNodes.
169 for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
170 SDNode *N = NewNodes[i];
171 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
172 UI != UE; ++UI)
173 assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
174 }
175 }
176
177 /// run - This is the main entry point for the type legalizer. This does a
178 /// top-down traversal of the dag, legalizing types as it goes. Returns "true"
179 /// if it made any changes.
run()180 bool DAGTypeLegalizer::run() {
181 bool Changed = false;
182
183 // Create a dummy node (which is not added to allnodes), that adds a reference
184 // to the root node, preventing it from being deleted, and tracking any
185 // changes of the root.
186 HandleSDNode Dummy(DAG.getRoot());
187 Dummy.setNodeId(Unanalyzed);
188
189 // The root of the dag may dangle to deleted nodes until the type legalizer is
190 // done. Set it to null to avoid confusion.
191 DAG.setRoot(SDValue());
192
193 // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
194 // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
195 // non-leaves.
196 for (SDNode &Node : DAG.allnodes()) {
197 if (Node.getNumOperands() == 0) {
198 Node.setNodeId(ReadyToProcess);
199 Worklist.push_back(&Node);
200 } else {
201 Node.setNodeId(Unanalyzed);
202 }
203 }
204
205 // Now that we have a set of nodes to process, handle them all.
206 while (!Worklist.empty()) {
207 #ifndef XDEBUG
208 if (EnableExpensiveChecks)
209 #endif
210 PerformExpensiveChecks();
211
212 SDNode *N = Worklist.back();
213 Worklist.pop_back();
214 assert(N->getNodeId() == ReadyToProcess &&
215 "Node should be ready if on worklist!");
216
217 if (IgnoreNodeResults(N))
218 goto ScanOperands;
219
220 // Scan the values produced by the node, checking to see if any result
221 // types are illegal.
222 for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
223 EVT ResultVT = N->getValueType(i);
224 switch (getTypeAction(ResultVT)) {
225 case TargetLowering::TypeLegal:
226 break;
227 // The following calls must take care of *all* of the node's results,
228 // not just the illegal result they were passed (this includes results
229 // with a legal type). Results can be remapped using ReplaceValueWith,
230 // or their promoted/expanded/etc values registered in PromotedIntegers,
231 // ExpandedIntegers etc.
232 case TargetLowering::TypePromoteInteger:
233 PromoteIntegerResult(N, i);
234 Changed = true;
235 goto NodeDone;
236 case TargetLowering::TypeExpandInteger:
237 ExpandIntegerResult(N, i);
238 Changed = true;
239 goto NodeDone;
240 case TargetLowering::TypeSoftenFloat:
241 Changed = SoftenFloatResult(N, i);
242 if (Changed)
243 goto NodeDone;
244 // If not changed, the result type should be legally in register.
245 assert(isLegalInHWReg(ResultVT) &&
246 "Unchanged SoftenFloatResult should be legal in register!");
247 goto ScanOperands;
248 case TargetLowering::TypeExpandFloat:
249 ExpandFloatResult(N, i);
250 Changed = true;
251 goto NodeDone;
252 case TargetLowering::TypeScalarizeVector:
253 ScalarizeVectorResult(N, i);
254 Changed = true;
255 goto NodeDone;
256 case TargetLowering::TypeSplitVector:
257 SplitVectorResult(N, i);
258 Changed = true;
259 goto NodeDone;
260 case TargetLowering::TypeWidenVector:
261 WidenVectorResult(N, i);
262 Changed = true;
263 goto NodeDone;
264 case TargetLowering::TypePromoteFloat:
265 PromoteFloatResult(N, i);
266 Changed = true;
267 goto NodeDone;
268 }
269 }
270
271 ScanOperands:
272 // Scan the operand list for the node, handling any nodes with operands that
273 // are illegal.
274 {
275 unsigned NumOperands = N->getNumOperands();
276 bool NeedsReanalyzing = false;
277 unsigned i;
278 for (i = 0; i != NumOperands; ++i) {
279 if (IgnoreNodeResults(N->getOperand(i).getNode()))
280 continue;
281
282 EVT OpVT = N->getOperand(i).getValueType();
283 switch (getTypeAction(OpVT)) {
284 case TargetLowering::TypeLegal:
285 continue;
286 // The following calls must either replace all of the node's results
287 // using ReplaceValueWith, and return "false"; or update the node's
288 // operands in place, and return "true".
289 case TargetLowering::TypePromoteInteger:
290 NeedsReanalyzing = PromoteIntegerOperand(N, i);
291 Changed = true;
292 break;
293 case TargetLowering::TypeExpandInteger:
294 NeedsReanalyzing = ExpandIntegerOperand(N, i);
295 Changed = true;
296 break;
297 case TargetLowering::TypeSoftenFloat:
298 NeedsReanalyzing = SoftenFloatOperand(N, i);
299 Changed = true;
300 break;
301 case TargetLowering::TypeExpandFloat:
302 NeedsReanalyzing = ExpandFloatOperand(N, i);
303 Changed = true;
304 break;
305 case TargetLowering::TypeScalarizeVector:
306 NeedsReanalyzing = ScalarizeVectorOperand(N, i);
307 Changed = true;
308 break;
309 case TargetLowering::TypeSplitVector:
310 NeedsReanalyzing = SplitVectorOperand(N, i);
311 Changed = true;
312 break;
313 case TargetLowering::TypeWidenVector:
314 NeedsReanalyzing = WidenVectorOperand(N, i);
315 Changed = true;
316 break;
317 case TargetLowering::TypePromoteFloat:
318 NeedsReanalyzing = PromoteFloatOperand(N, i);
319 Changed = true;
320 break;
321 }
322 break;
323 }
324
325 // The sub-method updated N in place. Check to see if any operands are new,
326 // and if so, mark them. If the node needs revisiting, don't add all users
327 // to the worklist etc.
328 if (NeedsReanalyzing) {
329 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
330 N->setNodeId(NewNode);
331 // Recompute the NodeId and correct processed operands, adding the node to
332 // the worklist if ready.
333 SDNode *M = AnalyzeNewNode(N);
334 if (M == N)
335 // The node didn't morph - nothing special to do, it will be revisited.
336 continue;
337
338 // The node morphed - this is equivalent to legalizing by replacing every
339 // value of N with the corresponding value of M. So do that now.
340 assert(N->getNumValues() == M->getNumValues() &&
341 "Node morphing changed the number of results!");
342 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
343 // Replacing the value takes care of remapping the new value.
344 ReplaceValueWith(SDValue(N, i), SDValue(M, i));
345 assert(N->getNodeId() == NewNode && "Unexpected node state!");
346 // The node continues to live on as part of the NewNode fungus that
347 // grows on top of the useful nodes. Nothing more needs to be done
348 // with it - move on to the next node.
349 continue;
350 }
351
352 if (i == NumOperands) {
353 DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG); dbgs() << "\n");
354 }
355 }
356 NodeDone:
357
358 // If we reach here, the node was processed, potentially creating new nodes.
359 // Mark it as processed and add its users to the worklist as appropriate.
360 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
361 N->setNodeId(Processed);
362
363 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
364 UI != E; ++UI) {
365 SDNode *User = *UI;
366 int NodeId = User->getNodeId();
367
368 // This node has two options: it can either be a new node or its Node ID
369 // may be a count of the number of operands it has that are not ready.
370 if (NodeId > 0) {
371 User->setNodeId(NodeId-1);
372
373 // If this was the last use it was waiting on, add it to the ready list.
374 if (NodeId-1 == ReadyToProcess)
375 Worklist.push_back(User);
376 continue;
377 }
378
379 // If this is an unreachable new node, then ignore it. If it ever becomes
380 // reachable by being used by a newly created node then it will be handled
381 // by AnalyzeNewNode.
382 if (NodeId == NewNode)
383 continue;
384
385 // Otherwise, this node is new: this is the first operand of it that
386 // became ready. Its new NodeId is the number of operands it has minus 1
387 // (as this node is now processed).
388 assert(NodeId == Unanalyzed && "Unknown node ID!");
389 User->setNodeId(User->getNumOperands() - 1);
390
391 // If the node only has a single operand, it is now ready.
392 if (User->getNumOperands() == 1)
393 Worklist.push_back(User);
394 }
395 }
396
397 #ifndef XDEBUG
398 if (EnableExpensiveChecks)
399 #endif
400 PerformExpensiveChecks();
401
402 // If the root changed (e.g. it was a dead load) update the root.
403 DAG.setRoot(Dummy.getValue());
404
405 // Remove dead nodes. This is important to do for cleanliness but also before
406 // the checking loop below. Implicit folding by the DAG.getNode operators and
407 // node morphing can cause unreachable nodes to be around with their flags set
408 // to new.
409 DAG.RemoveDeadNodes();
410
411 // In a debug build, scan all the nodes to make sure we found them all. This
412 // ensures that there are no cycles and that everything got processed.
413 #ifndef NDEBUG
414 for (SDNode &Node : DAG.allnodes()) {
415 bool Failed = false;
416
417 // Check that all result types are legal.
418 // A value type is illegal if its TypeAction is not TypeLegal,
419 // and TLI.RegClassForVT does not have a register class for this type.
420 // For example, the x86_64 target has f128 that is not TypeLegal,
421 // to have softened operators, but it also has FR128 register class to
422 // pass and return f128 values. Hence a legalized node can have f128 type.
423 if (!IgnoreNodeResults(&Node))
424 for (unsigned i = 0, NumVals = Node.getNumValues(); i < NumVals; ++i)
425 if (!isTypeLegal(Node.getValueType(i)) &&
426 !TLI.isTypeLegal(Node.getValueType(i))) {
427 dbgs() << "Result type " << i << " illegal: ";
428 Node.dump();
429 Failed = true;
430 }
431
432 // Check that all operand types are legal.
433 for (unsigned i = 0, NumOps = Node.getNumOperands(); i < NumOps; ++i)
434 if (!IgnoreNodeResults(Node.getOperand(i).getNode()) &&
435 !isTypeLegal(Node.getOperand(i).getValueType()) &&
436 !TLI.isTypeLegal(Node.getOperand(i).getValueType())) {
437 dbgs() << "Operand type " << i << " illegal: ";
438 Node.getOperand(i).dump();
439 Failed = true;
440 }
441
442 if (Node.getNodeId() != Processed) {
443 if (Node.getNodeId() == NewNode)
444 dbgs() << "New node not analyzed?\n";
445 else if (Node.getNodeId() == Unanalyzed)
446 dbgs() << "Unanalyzed node not noticed?\n";
447 else if (Node.getNodeId() > 0)
448 dbgs() << "Operand not processed?\n";
449 else if (Node.getNodeId() == ReadyToProcess)
450 dbgs() << "Not added to worklist?\n";
451 Failed = true;
452 }
453
454 if (Failed) {
455 Node.dump(&DAG); dbgs() << "\n";
456 llvm_unreachable(nullptr);
457 }
458 }
459 #endif
460
461 return Changed;
462 }
463
464 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
465 /// new nodes. Correct any processed operands (this may change the node) and
466 /// calculate the NodeId. If the node itself changes to a processed node, it
467 /// is not remapped - the caller needs to take care of this.
468 /// Returns the potentially changed node.
AnalyzeNewNode(SDNode * N)469 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
470 // If this was an existing node that is already done, we're done.
471 if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
472 return N;
473
474 // Remove any stale map entries.
475 ExpungeNode(N);
476
477 // Okay, we know that this node is new. Recursively walk all of its operands
478 // to see if they are new also. The depth of this walk is bounded by the size
479 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
480 // about revisiting of nodes.
481 //
482 // As we walk the operands, keep track of the number of nodes that are
483 // processed. If non-zero, this will become the new nodeid of this node.
484 // Operands may morph when they are analyzed. If so, the node will be
485 // updated after all operands have been analyzed. Since this is rare,
486 // the code tries to minimize overhead in the non-morphing case.
487
488 SmallVector<SDValue, 8> NewOps;
489 unsigned NumProcessed = 0;
490 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
491 SDValue OrigOp = N->getOperand(i);
492 SDValue Op = OrigOp;
493
494 AnalyzeNewValue(Op); // Op may morph.
495
496 if (Op.getNode()->getNodeId() == Processed)
497 ++NumProcessed;
498
499 if (!NewOps.empty()) {
500 // Some previous operand changed. Add this one to the list.
501 NewOps.push_back(Op);
502 } else if (Op != OrigOp) {
503 // This is the first operand to change - add all operands so far.
504 NewOps.append(N->op_begin(), N->op_begin() + i);
505 NewOps.push_back(Op);
506 }
507 }
508
509 // Some operands changed - update the node.
510 if (!NewOps.empty()) {
511 SDNode *M = DAG.UpdateNodeOperands(N, NewOps);
512 if (M != N) {
513 // The node morphed into a different node. Normally for this to happen
514 // the original node would have to be marked NewNode. However this can
515 // in theory momentarily not be the case while ReplaceValueWith is doing
516 // its stuff. Mark the original node NewNode to help sanity checking.
517 N->setNodeId(NewNode);
518 if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
519 // It morphed into a previously analyzed node - nothing more to do.
520 return M;
521
522 // It morphed into a different new node. Do the equivalent of passing
523 // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
524 // to remap the operands, since they are the same as the operands we
525 // remapped above.
526 N = M;
527 ExpungeNode(N);
528 }
529 }
530
531 // Calculate the NodeId.
532 N->setNodeId(N->getNumOperands() - NumProcessed);
533 if (N->getNodeId() == ReadyToProcess)
534 Worklist.push_back(N);
535
536 return N;
537 }
538
539 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
540 /// If the node changes to a processed node, then remap it.
AnalyzeNewValue(SDValue & Val)541 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
542 Val.setNode(AnalyzeNewNode(Val.getNode()));
543 if (Val.getNode()->getNodeId() == Processed)
544 // We were passed a processed node, or it morphed into one - remap it.
545 RemapValue(Val);
546 }
547
548 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
549 /// This can occur when a node is deleted then reallocated as a new node -
550 /// the mapping in ReplacedValues applies to the deleted node, not the new
551 /// one.
552 /// The only map that can have a deleted node as a source is ReplacedValues.
553 /// Other maps can have deleted nodes as targets, but since their looked-up
554 /// values are always immediately remapped using RemapValue, resulting in a
555 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
556 /// always performs correct mappings. In order to keep the mapping correct,
557 /// ExpungeNode should be called on any new nodes *before* adding them as
558 /// either source or target to ReplacedValues (which typically means calling
559 /// Expunge when a new node is first seen, since it may no longer be marked
560 /// NewNode by the time it is added to ReplacedValues).
ExpungeNode(SDNode * N)561 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
562 if (N->getNodeId() != NewNode)
563 return;
564
565 // If N is not remapped by ReplacedValues then there is nothing to do.
566 unsigned i, e;
567 for (i = 0, e = N->getNumValues(); i != e; ++i)
568 if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
569 break;
570
571 if (i == e)
572 return;
573
574 // Remove N from all maps - this is expensive but rare.
575
576 for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
577 E = PromotedIntegers.end(); I != E; ++I) {
578 assert(I->first.getNode() != N);
579 RemapValue(I->second);
580 }
581
582 for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
583 E = SoftenedFloats.end(); I != E; ++I) {
584 assert(I->first.getNode() != N);
585 RemapValue(I->second);
586 }
587
588 for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
589 E = ScalarizedVectors.end(); I != E; ++I) {
590 assert(I->first.getNode() != N);
591 RemapValue(I->second);
592 }
593
594 for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
595 E = WidenedVectors.end(); I != E; ++I) {
596 assert(I->first.getNode() != N);
597 RemapValue(I->second);
598 }
599
600 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
601 I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
602 assert(I->first.getNode() != N);
603 RemapValue(I->second.first);
604 RemapValue(I->second.second);
605 }
606
607 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
608 I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
609 assert(I->first.getNode() != N);
610 RemapValue(I->second.first);
611 RemapValue(I->second.second);
612 }
613
614 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
615 I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
616 assert(I->first.getNode() != N);
617 RemapValue(I->second.first);
618 RemapValue(I->second.second);
619 }
620
621 for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
622 E = ReplacedValues.end(); I != E; ++I)
623 RemapValue(I->second);
624
625 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
626 ReplacedValues.erase(SDValue(N, i));
627 }
628
629 /// RemapValue - If the specified value was already legalized to another value,
630 /// replace it by that value.
RemapValue(SDValue & N)631 void DAGTypeLegalizer::RemapValue(SDValue &N) {
632 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
633 if (I != ReplacedValues.end()) {
634 // Use path compression to speed up future lookups if values get multiply
635 // replaced with other values.
636 RemapValue(I->second);
637 N = I->second;
638
639 // Note that it is possible to have N.getNode()->getNodeId() == NewNode at
640 // this point because it is possible for a node to be put in the map before
641 // being processed.
642 }
643 }
644
645 namespace {
646 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
647 /// updates to nodes and recomputes their ready state.
648 class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
649 DAGTypeLegalizer &DTL;
650 SmallSetVector<SDNode*, 16> &NodesToAnalyze;
651 public:
NodeUpdateListener(DAGTypeLegalizer & dtl,SmallSetVector<SDNode *,16> & nta)652 explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
653 SmallSetVector<SDNode*, 16> &nta)
654 : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
655 DTL(dtl), NodesToAnalyze(nta) {}
656
NodeDeleted(SDNode * N,SDNode * E)657 void NodeDeleted(SDNode *N, SDNode *E) override {
658 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
659 N->getNodeId() != DAGTypeLegalizer::Processed &&
660 "Invalid node ID for RAUW deletion!");
661 // It is possible, though rare, for the deleted node N to occur as a
662 // target in a map, so note the replacement N -> E in ReplacedValues.
663 assert(E && "Node not replaced?");
664 DTL.NoteDeletion(N, E);
665
666 // In theory the deleted node could also have been scheduled for analysis.
667 // So remove it from the set of nodes which will be analyzed.
668 NodesToAnalyze.remove(N);
669
670 // In general nothing needs to be done for E, since it didn't change but
671 // only gained new uses. However N -> E was just added to ReplacedValues,
672 // and the result of a ReplacedValues mapping is not allowed to be marked
673 // NewNode. So if E is marked NewNode, then it needs to be analyzed.
674 if (E->getNodeId() == DAGTypeLegalizer::NewNode)
675 NodesToAnalyze.insert(E);
676 }
677
NodeUpdated(SDNode * N)678 void NodeUpdated(SDNode *N) override {
679 // Node updates can mean pretty much anything. It is possible that an
680 // operand was set to something already processed (f.e.) in which case
681 // this node could become ready. Recompute its flags.
682 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
683 N->getNodeId() != DAGTypeLegalizer::Processed &&
684 "Invalid node ID for RAUW deletion!");
685 N->setNodeId(DAGTypeLegalizer::NewNode);
686 NodesToAnalyze.insert(N);
687 }
688 };
689 }
690
691
692 /// ReplaceValueWith - The specified value was legalized to the specified other
693 /// value. Update the DAG and NodeIds replacing any uses of From to use To
694 /// instead.
ReplaceValueWith(SDValue From,SDValue To)695 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
696 assert(From.getNode() != To.getNode() && "Potential legalization loop!");
697
698 // If expansion produced new nodes, make sure they are properly marked.
699 ExpungeNode(From.getNode());
700 AnalyzeNewValue(To); // Expunges To.
701
702 // Anything that used the old node should now use the new one. Note that this
703 // can potentially cause recursive merging.
704 SmallSetVector<SDNode*, 16> NodesToAnalyze;
705 NodeUpdateListener NUL(*this, NodesToAnalyze);
706 do {
707 DAG.ReplaceAllUsesOfValueWith(From, To);
708
709 // The old node may still be present in a map like ExpandedIntegers or
710 // PromotedIntegers. Inform maps about the replacement.
711 ReplacedValues[From] = To;
712
713 // Process the list of nodes that need to be reanalyzed.
714 while (!NodesToAnalyze.empty()) {
715 SDNode *N = NodesToAnalyze.back();
716 NodesToAnalyze.pop_back();
717 if (N->getNodeId() != DAGTypeLegalizer::NewNode)
718 // The node was analyzed while reanalyzing an earlier node - it is safe
719 // to skip. Note that this is not a morphing node - otherwise it would
720 // still be marked NewNode.
721 continue;
722
723 // Analyze the node's operands and recalculate the node ID.
724 SDNode *M = AnalyzeNewNode(N);
725 if (M != N) {
726 // The node morphed into a different node. Make everyone use the new
727 // node instead.
728 assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
729 assert(N->getNumValues() == M->getNumValues() &&
730 "Node morphing changed the number of results!");
731 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
732 SDValue OldVal(N, i);
733 SDValue NewVal(M, i);
734 if (M->getNodeId() == Processed)
735 RemapValue(NewVal);
736 DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
737 // OldVal may be a target of the ReplacedValues map which was marked
738 // NewNode to force reanalysis because it was updated. Ensure that
739 // anything that ReplacedValues mapped to OldVal will now be mapped
740 // all the way to NewVal.
741 ReplacedValues[OldVal] = NewVal;
742 }
743 // The original node continues to exist in the DAG, marked NewNode.
744 }
745 }
746 // When recursively update nodes with new nodes, it is possible to have
747 // new uses of From due to CSE. If this happens, replace the new uses of
748 // From with To.
749 } while (!From.use_empty());
750 }
751
SetPromotedInteger(SDValue Op,SDValue Result)752 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
753 assert(Result.getValueType() ==
754 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
755 "Invalid type for promoted integer");
756 AnalyzeNewValue(Result);
757
758 SDValue &OpEntry = PromotedIntegers[Op];
759 assert(!OpEntry.getNode() && "Node is already promoted!");
760 OpEntry = Result;
761 }
762
SetSoftenedFloat(SDValue Op,SDValue Result)763 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
764 // f128 of x86_64 could be kept in SSE registers,
765 // but sometimes softened to i128.
766 assert((Result.getValueType() ==
767 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) ||
768 Op.getValueType() ==
769 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType())) &&
770 "Invalid type for softened float");
771 AnalyzeNewValue(Result);
772
773 SDValue &OpEntry = SoftenedFloats[Op];
774 // Allow repeated calls to save f128 type nodes
775 // or any node with type that transforms to itself.
776 // Many operations on these types are not softened.
777 assert((!OpEntry.getNode()||
778 Op.getValueType() ==
779 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType())) &&
780 "Node is already converted to integer!");
781 OpEntry = Result;
782 }
783
SetPromotedFloat(SDValue Op,SDValue Result)784 void DAGTypeLegalizer::SetPromotedFloat(SDValue Op, SDValue Result) {
785 assert(Result.getValueType() ==
786 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
787 "Invalid type for promoted float");
788 AnalyzeNewValue(Result);
789
790 SDValue &OpEntry = PromotedFloats[Op];
791 assert(!OpEntry.getNode() && "Node is already promoted!");
792 OpEntry = Result;
793 }
794
SetScalarizedVector(SDValue Op,SDValue Result)795 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
796 // Note that in some cases vector operation operands may be greater than
797 // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
798 // a constant i8 operand.
799 assert(Result.getValueType().getSizeInBits() >=
800 Op.getValueType().getVectorElementType().getSizeInBits() &&
801 "Invalid type for scalarized vector");
802 AnalyzeNewValue(Result);
803
804 SDValue &OpEntry = ScalarizedVectors[Op];
805 assert(!OpEntry.getNode() && "Node is already scalarized!");
806 OpEntry = Result;
807 }
808
GetExpandedInteger(SDValue Op,SDValue & Lo,SDValue & Hi)809 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
810 SDValue &Hi) {
811 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
812 RemapValue(Entry.first);
813 RemapValue(Entry.second);
814 assert(Entry.first.getNode() && "Operand isn't expanded");
815 Lo = Entry.first;
816 Hi = Entry.second;
817 }
818
SetExpandedInteger(SDValue Op,SDValue Lo,SDValue Hi)819 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
820 SDValue Hi) {
821 assert(Lo.getValueType() ==
822 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
823 Hi.getValueType() == Lo.getValueType() &&
824 "Invalid type for expanded integer");
825 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
826 AnalyzeNewValue(Lo);
827 AnalyzeNewValue(Hi);
828
829 // Remember that this is the result of the node.
830 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
831 assert(!Entry.first.getNode() && "Node already expanded");
832 Entry.first = Lo;
833 Entry.second = Hi;
834 }
835
GetExpandedFloat(SDValue Op,SDValue & Lo,SDValue & Hi)836 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
837 SDValue &Hi) {
838 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
839 RemapValue(Entry.first);
840 RemapValue(Entry.second);
841 assert(Entry.first.getNode() && "Operand isn't expanded");
842 Lo = Entry.first;
843 Hi = Entry.second;
844 }
845
SetExpandedFloat(SDValue Op,SDValue Lo,SDValue Hi)846 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
847 SDValue Hi) {
848 assert(Lo.getValueType() ==
849 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
850 Hi.getValueType() == Lo.getValueType() &&
851 "Invalid type for expanded float");
852 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
853 AnalyzeNewValue(Lo);
854 AnalyzeNewValue(Hi);
855
856 // Remember that this is the result of the node.
857 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
858 assert(!Entry.first.getNode() && "Node already expanded");
859 Entry.first = Lo;
860 Entry.second = Hi;
861 }
862
GetSplitVector(SDValue Op,SDValue & Lo,SDValue & Hi)863 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
864 SDValue &Hi) {
865 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
866 RemapValue(Entry.first);
867 RemapValue(Entry.second);
868 assert(Entry.first.getNode() && "Operand isn't split");
869 Lo = Entry.first;
870 Hi = Entry.second;
871 }
872
SetSplitVector(SDValue Op,SDValue Lo,SDValue Hi)873 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
874 SDValue Hi) {
875 assert(Lo.getValueType().getVectorElementType() ==
876 Op.getValueType().getVectorElementType() &&
877 2*Lo.getValueType().getVectorNumElements() ==
878 Op.getValueType().getVectorNumElements() &&
879 Hi.getValueType() == Lo.getValueType() &&
880 "Invalid type for split vector");
881 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
882 AnalyzeNewValue(Lo);
883 AnalyzeNewValue(Hi);
884
885 // Remember that this is the result of the node.
886 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
887 assert(!Entry.first.getNode() && "Node already split");
888 Entry.first = Lo;
889 Entry.second = Hi;
890 }
891
SetWidenedVector(SDValue Op,SDValue Result)892 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
893 assert(Result.getValueType() ==
894 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
895 "Invalid type for widened vector");
896 AnalyzeNewValue(Result);
897
898 SDValue &OpEntry = WidenedVectors[Op];
899 assert(!OpEntry.getNode() && "Node already widened!");
900 OpEntry = Result;
901 }
902
903
904 //===----------------------------------------------------------------------===//
905 // Utilities.
906 //===----------------------------------------------------------------------===//
907
908 /// BitConvertToInteger - Convert to an integer of the same size.
BitConvertToInteger(SDValue Op)909 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
910 unsigned BitWidth = Op.getValueType().getSizeInBits();
911 return DAG.getNode(ISD::BITCAST, SDLoc(Op),
912 EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
913 }
914
915 /// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
916 /// same size.
BitConvertVectorToIntegerVector(SDValue Op)917 SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
918 assert(Op.getValueType().isVector() && "Only applies to vectors!");
919 unsigned EltWidth = Op.getValueType().getVectorElementType().getSizeInBits();
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);
924 }
925
CreateStackStoreLoad(SDValue Op,EVT DestVT)926 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
927 EVT DestVT) {
928 SDLoc dl(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.
933 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr,
934 MachinePointerInfo(), false, false, 0);
935 // Result is a load from the stack slot.
936 return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo(),
937 false, false, false, 0);
938 }
939
940 /// CustomLowerNode - Replace the node's results with custom code provided
941 /// by the target and return "true", or do nothing and return "false".
942 /// The last parameter is FALSE if we are dealing with a node with legal
943 /// result types and illegal operand. The second parameter denotes the type of
944 /// illegal OperandNo in that case.
945 /// The last parameter being TRUE means we are dealing with a
946 /// node with illegal result types. The second parameter denotes the type of
947 /// illegal ResNo in that case.
CustomLowerNode(SDNode * N,EVT VT,bool LegalizeResult)948 bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
949 // See if the target wants to custom lower this node.
950 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
951 return false;
952
953 SmallVector<SDValue, 8> Results;
954 if (LegalizeResult)
955 TLI.ReplaceNodeResults(N, Results, DAG);
956 else
957 TLI.LowerOperationWrapper(N, Results, DAG);
958
959 if (Results.empty())
960 // The target didn't want to custom lower it after all.
961 return false;
962
963 // When called from DAGTypeLegalizer::ExpandIntegerResult, we might need to
964 // provide the same kind of custom splitting behavior.
965 if (Results.size() == N->getNumValues() + 1 && LegalizeResult) {
966 // We've legalized a return type by splitting it. If there is a chain,
967 // replace that too.
968 SetExpandedInteger(SDValue(N, 0), Results[0], Results[1]);
969 if (N->getNumValues() > 1)
970 ReplaceValueWith(SDValue(N, 1), Results[2]);
971 return true;
972 }
973
974 // Make everything that once used N's values now use those in Results instead.
975 assert(Results.size() == N->getNumValues() &&
976 "Custom lowering returned the wrong number of results!");
977 for (unsigned i = 0, e = Results.size(); i != e; ++i) {
978 ReplaceValueWith(SDValue(N, i), Results[i]);
979 }
980 return true;
981 }
982
983
984 /// CustomWidenLowerNode - Widen the node's results with custom code provided
985 /// by the target and return "true", or do nothing and return "false".
CustomWidenLowerNode(SDNode * N,EVT VT)986 bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
987 // See if the target wants to custom lower this node.
988 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
989 return false;
990
991 SmallVector<SDValue, 8> Results;
992 TLI.ReplaceNodeResults(N, Results, DAG);
993
994 if (Results.empty())
995 // The target didn't want to custom widen lower its result after all.
996 return false;
997
998 // Update the widening map.
999 assert(Results.size() == N->getNumValues() &&
1000 "Custom lowering returned the wrong number of results!");
1001 for (unsigned i = 0, e = Results.size(); i != e; ++i)
1002 SetWidenedVector(SDValue(N, i), Results[i]);
1003 return true;
1004 }
1005
DisintegrateMERGE_VALUES(SDNode * N,unsigned ResNo)1006 SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
1007 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
1008 if (i != ResNo)
1009 ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
1010 return SDValue(N->getOperand(ResNo));
1011 }
1012
1013 /// GetPairElements - Use ISD::EXTRACT_ELEMENT nodes to extract the low and
1014 /// high parts of the given value.
GetPairElements(SDValue Pair,SDValue & Lo,SDValue & Hi)1015 void DAGTypeLegalizer::GetPairElements(SDValue Pair,
1016 SDValue &Lo, SDValue &Hi) {
1017 SDLoc dl(Pair);
1018 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
1019 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
1020 DAG.getIntPtrConstant(0, dl));
1021 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
1022 DAG.getIntPtrConstant(1, dl));
1023 }
1024
GetVectorElementPointer(SDValue VecPtr,EVT EltVT,SDValue Index)1025 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, EVT EltVT,
1026 SDValue Index) {
1027 SDLoc dl(Index);
1028 // Make sure the index type is big enough to compute in.
1029 Index = DAG.getZExtOrTrunc(Index, dl, TLI.getPointerTy(DAG.getDataLayout()));
1030
1031 // Calculate the element offset and add it to the pointer.
1032 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
1033 assert(EltSize * 8 == EltVT.getSizeInBits() &&
1034 "Converting bits to bytes lost precision");
1035
1036 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
1037 DAG.getConstant(EltSize, dl, Index.getValueType()));
1038 return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr);
1039 }
1040
1041 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
JoinIntegers(SDValue Lo,SDValue Hi)1042 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
1043 // Arbitrarily use dlHi for result SDLoc
1044 SDLoc dlHi(Hi);
1045 SDLoc dlLo(Lo);
1046 EVT LVT = Lo.getValueType();
1047 EVT HVT = Hi.getValueType();
1048 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1049 LVT.getSizeInBits() + HVT.getSizeInBits());
1050
1051 Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
1052 Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
1053 Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
1054 DAG.getConstant(LVT.getSizeInBits(), dlHi,
1055 TLI.getPointerTy(DAG.getDataLayout())));
1056 return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
1057 }
1058
1059 /// LibCallify - Convert the node into a libcall with the same prototype.
LibCallify(RTLIB::Libcall LC,SDNode * N,bool isSigned)1060 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
1061 bool isSigned) {
1062 unsigned NumOps = N->getNumOperands();
1063 SDLoc dl(N);
1064 if (NumOps == 0) {
1065 return TLI.makeLibCall(DAG, LC, N->getValueType(0), None, isSigned,
1066 dl).first;
1067 } else if (NumOps == 1) {
1068 SDValue Op = N->getOperand(0);
1069 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Op, isSigned,
1070 dl).first;
1071 } else if (NumOps == 2) {
1072 SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1073 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, isSigned,
1074 dl).first;
1075 }
1076 SmallVector<SDValue, 8> Ops(NumOps);
1077 for (unsigned i = 0; i < NumOps; ++i)
1078 Ops[i] = N->getOperand(i);
1079
1080 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, isSigned, dl).first;
1081 }
1082
1083 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
1084 // ExpandLibCall except that the first operand is the in-chain.
1085 std::pair<SDValue, SDValue>
ExpandChainLibCall(RTLIB::Libcall LC,SDNode * Node,bool isSigned)1086 DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC,
1087 SDNode *Node,
1088 bool isSigned) {
1089 SDValue InChain = Node->getOperand(0);
1090
1091 TargetLowering::ArgListTy Args;
1092 TargetLowering::ArgListEntry Entry;
1093 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
1094 EVT ArgVT = Node->getOperand(i).getValueType();
1095 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1096 Entry.Node = Node->getOperand(i);
1097 Entry.Ty = ArgTy;
1098 Entry.isSExt = isSigned;
1099 Entry.isZExt = !isSigned;
1100 Args.push_back(Entry);
1101 }
1102 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1103 TLI.getPointerTy(DAG.getDataLayout()));
1104
1105 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1106
1107 TargetLowering::CallLoweringInfo CLI(DAG);
1108 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
1109 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
1110 .setSExtResult(isSigned).setZExtResult(!isSigned);
1111
1112 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
1113
1114 return CallInfo;
1115 }
1116
1117 /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
1118 /// of the given type. A target boolean is an integer value, not necessarily of
1119 /// type i1, the bits of which conform to getBooleanContents.
1120 ///
1121 /// ValVT is the type of values that produced the boolean.
PromoteTargetBoolean(SDValue Bool,EVT ValVT)1122 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT ValVT) {
1123 SDLoc dl(Bool);
1124 EVT BoolVT = getSetCCResultType(ValVT);
1125 ISD::NodeType ExtendCode =
1126 TargetLowering::getExtendForContent(TLI.getBooleanContents(ValVT));
1127 return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
1128 }
1129
1130 /// WidenTargetBoolean - Widen the given target boolean to a target boolean
1131 /// of the given type. The boolean vector is widened and then promoted to match
1132 /// the target boolean type of the given ValVT.
WidenTargetBoolean(SDValue Bool,EVT ValVT,bool WithZeroes)1133 SDValue DAGTypeLegalizer::WidenTargetBoolean(SDValue Bool, EVT ValVT,
1134 bool WithZeroes) {
1135 SDLoc dl(Bool);
1136 EVT BoolVT = Bool.getValueType();
1137
1138 assert(ValVT.getVectorNumElements() > BoolVT.getVectorNumElements() &&
1139 TLI.isTypeLegal(ValVT) &&
1140 "Unexpected types in WidenTargetBoolean");
1141 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), BoolVT.getScalarType(),
1142 ValVT.getVectorNumElements());
1143 Bool = ModifyToType(Bool, WideVT, WithZeroes);
1144 return PromoteTargetBoolean(Bool, ValVT);
1145 }
1146
1147 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
1148 /// bits in Hi.
SplitInteger(SDValue Op,EVT LoVT,EVT HiVT,SDValue & Lo,SDValue & Hi)1149 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1150 EVT LoVT, EVT HiVT,
1151 SDValue &Lo, SDValue &Hi) {
1152 SDLoc dl(Op);
1153 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1154 Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
1155 Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
1156 Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
1157 DAG.getConstant(LoVT.getSizeInBits(), dl,
1158 TLI.getPointerTy(DAG.getDataLayout())));
1159 Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
1160 }
1161
1162 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
1163 /// type half the size of Op's.
SplitInteger(SDValue Op,SDValue & Lo,SDValue & Hi)1164 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1165 SDValue &Lo, SDValue &Hi) {
1166 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(),
1167 Op.getValueType().getSizeInBits()/2);
1168 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1169 }
1170
1171
1172 //===----------------------------------------------------------------------===//
1173 // Entry Point
1174 //===----------------------------------------------------------------------===//
1175
1176 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1177 /// only uses types natively supported by the target. Returns "true" if it made
1178 /// any changes.
1179 ///
1180 /// Note that this is an involved process that may invalidate pointers into
1181 /// the graph.
LegalizeTypes()1182 bool SelectionDAG::LegalizeTypes() {
1183 return DAGTypeLegalizer(*this).run();
1184 }
1185