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