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