Remove attribution from file headers, per discussion on llvmdev.
[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/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Support/MathExtras.h"
20 using namespace llvm;
21
22 /// run - This is the main entry point for the type legalizer.  This does a
23 /// top-down traversal of the dag, legalizing types as it goes.
24 void DAGTypeLegalizer::run() {
25   // Create a dummy node (which is not added to allnodes), that adds a reference
26   // to the root node, preventing it from being deleted, and tracking any
27   // changes of the root.
28   HandleSDNode Dummy(DAG.getRoot());
29
30   // The root of the dag may dangle to deleted nodes until the type legalizer is
31   // done.  Set it to null to avoid confusion.
32   DAG.setRoot(SDOperand());
33   
34   // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
35   // (and remembering them) if they are leaves and assigning 'NewNode' if
36   // non-leaves.
37   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
38        E = DAG.allnodes_end(); I != E; ++I) {
39     if (I->getNumOperands() == 0) {
40       I->setNodeId(ReadyToProcess);
41       Worklist.push_back(I);
42     } else {
43       I->setNodeId(NewNode);
44     }
45   }
46   
47   // Now that we have a set of nodes to process, handle them all.
48   while (!Worklist.empty()) {
49     SDNode *N = Worklist.back();
50     Worklist.pop_back();
51     assert(N->getNodeId() == ReadyToProcess &&
52            "Node should be ready if on worklist!");
53     
54     // Scan the values produced by the node, checking to see if any result
55     // types are illegal.
56     unsigned i = 0;
57     unsigned NumResults = N->getNumValues();
58     do {
59       MVT::ValueType ResultVT = N->getValueType(i);
60       LegalizeAction Action = getTypeAction(ResultVT);
61       if (Action == Promote) {
62         PromoteResult(N, i);
63         goto NodeDone;
64       } else if (Action == Expand) {
65         // Expand can mean 1) split integer in half 2) scalarize single-element
66         // vector 3) split vector in half.
67         if (!MVT::isVector(ResultVT))
68           ExpandResult(N, i);
69         else if (MVT::getVectorNumElements(ResultVT) == 1)
70           ScalarizeResult(N, i);     // Scalarize the single-element vector.
71         else
72           SplitResult(N, i);         // Split the vector in half.
73         goto NodeDone;
74       } else {
75         assert(Action == Legal && "Unknown action!");
76       }
77     } while (++i < NumResults);
78     
79     // Scan the operand list for the node, handling any nodes with operands that
80     // are illegal.
81     {
82     unsigned NumOperands = N->getNumOperands();
83     bool NeedsRevisit = false;
84     for (i = 0; i != NumOperands; ++i) {
85       MVT::ValueType OpVT = N->getOperand(i).getValueType();
86       LegalizeAction Action = getTypeAction(OpVT);
87       if (Action == Promote) {
88         NeedsRevisit = PromoteOperand(N, i);
89         break;
90       } else if (Action == Expand) {
91         // Expand can mean 1) split integer in half 2) scalarize single-element
92         // vector 3) split vector in half.
93         if (!MVT::isVector(OpVT)) {
94           NeedsRevisit = ExpandOperand(N, i);
95         } else if (MVT::getVectorNumElements(OpVT) == 1) {
96           // Scalarize the single-element vector.
97           NeedsRevisit = ScalarizeOperand(N, i);
98         } else {
99           NeedsRevisit = SplitOperand(N, i); // Split the vector in half.
100         }
101         break;
102       } else {
103         assert(Action == Legal && "Unknown action!");
104       }
105     }
106
107     // If the node needs revisiting, don't add all users to the worklist etc.
108     if (NeedsRevisit)
109       continue;
110     
111     if (i == NumOperands)
112       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
113     }
114 NodeDone:
115
116     // If we reach here, the node was processed, potentially creating new nodes.
117     // Mark it as processed and add its users to the worklist as appropriate.
118     N->setNodeId(Processed);
119     
120     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
121          UI != E; ++UI) {
122       SDNode *User = *UI;
123       int NodeID = User->getNodeId();
124       assert(NodeID != ReadyToProcess && NodeID != Processed &&
125              "Invalid node id for user of unprocessed node!");
126       
127       // This node has two options: it can either be a new node or its Node ID
128       // may be a count of the number of operands it has that are not ready.
129       if (NodeID > 0) {
130         User->setNodeId(NodeID-1);
131         
132         // If this was the last use it was waiting on, add it to the ready list.
133         if (NodeID-1 == ReadyToProcess)
134           Worklist.push_back(User);
135         continue;
136       }
137       
138       // Otherwise, this node is new: this is the first operand of it that
139       // became ready.  Its new NodeID is the number of operands it has minus 1
140       // (as this node is now processed).
141       assert(NodeID == NewNode && "Unknown node ID!");
142       User->setNodeId(User->getNumOperands()-1);
143       
144       // If the node only has a single operand, it is now ready.
145       if (User->getNumOperands() == 1)
146         Worklist.push_back(User);
147     }
148   }
149   
150   // If the root changed (e.g. it was a dead load, update the root).
151   DAG.setRoot(Dummy.getValue());
152
153   //DAG.viewGraph();
154
155   // Remove dead nodes.  This is important to do for cleanliness but also before
156   // the checking loop below.  Implicit folding by the DAG.getNode operators can
157   // cause unreachable nodes to be around with their flags set to new.
158   DAG.RemoveDeadNodes();
159
160   // In a debug build, scan all the nodes to make sure we found them all.  This
161   // ensures that there are no cycles and that everything got processed.
162 #ifndef NDEBUG
163   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
164        E = DAG.allnodes_end(); I != E; ++I) {
165     if (I->getNodeId() == Processed)
166       continue;
167     cerr << "Unprocessed node: ";
168     I->dump(&DAG); cerr << "\n";
169
170     if (I->getNodeId() == NewNode)
171       cerr << "New node not 'noticed'?\n";
172     else if (I->getNodeId() > 0)
173       cerr << "Operand not processed?\n";
174     else if (I->getNodeId() == ReadyToProcess)
175       cerr << "Not added to worklist?\n";
176     abort();
177   }
178 #endif
179 }
180
181 /// MarkNewNodes - The specified node is the root of a subtree of potentially
182 /// new nodes.  Add the correct NodeId to mark it.
183 void DAGTypeLegalizer::MarkNewNodes(SDNode *N) {
184   // If this was an existing node that is already done, we're done.
185   if (N->getNodeId() != NewNode)
186     return;
187
188   // Okay, we know that this node is new.  Recursively walk all of its operands
189   // to see if they are new also.  The depth of this walk is bounded by the size
190   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
191   // about revisiting of nodes.
192   //
193   // As we walk the operands, keep track of the number of nodes that are
194   // processed.  If non-zero, this will become the new nodeid of this node.
195   unsigned NumProcessed = 0;
196   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
197     int OpId = N->getOperand(i).Val->getNodeId();
198     if (OpId == NewNode)
199       MarkNewNodes(N->getOperand(i).Val);
200     else if (OpId == Processed)
201       ++NumProcessed;
202   }
203   
204   N->setNodeId(N->getNumOperands()-NumProcessed);
205   if (N->getNodeId() == ReadyToProcess)
206     Worklist.push_back(N);
207 }
208
209 /// ReplaceValueWith - The specified value was legalized to the specified other
210 /// value.  If they are different, update the DAG and NodeIDs replacing any uses
211 /// of From to use To instead.
212 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
213   if (From == To) return;
214   
215   // If expansion produced new nodes, make sure they are properly marked.
216   if (To.Val->getNodeId() == NewNode)
217     MarkNewNodes(To.Val);
218   
219   // Anything that used the old node should now use the new one.  Note that this
220   // can potentially cause recursive merging.
221   DAG.ReplaceAllUsesOfValueWith(From, To);
222
223   // The old node may still be present in ExpandedNodes or PromotedNodes.
224   // Inform them about the replacement.
225   ReplacedNodes[From] = To;
226
227   // Since we just made an unstructured update to the DAG, which could wreak
228   // general havoc on anything that once used From and now uses To, walk all
229   // users of the result, updating their flags.
230   for (SDNode::use_iterator I = To.Val->use_begin(), E = To.Val->use_end();
231        I != E; ++I) {
232     SDNode *User = *I;
233     // If the node isn't already processed or in the worklist, mark it as new,
234     // then use MarkNewNodes to recompute its ID.
235     int NodeId = User->getNodeId();
236     if (NodeId != ReadyToProcess && NodeId != Processed) {
237       User->setNodeId(NewNode);
238       MarkNewNodes(User);
239     }
240   }
241 }
242
243 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
244 /// node's results.  The from and to node must define identical result types.
245 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
246   if (From == To) return;
247   assert(From->getNumValues() == To->getNumValues() &&
248          "Node results don't match");
249   
250   // If expansion produced new nodes, make sure they are properly marked.
251   if (To->getNodeId() == NewNode)
252     MarkNewNodes(To);
253   
254   // Anything that used the old node should now use the new one.  Note that this
255   // can potentially cause recursive merging.
256   DAG.ReplaceAllUsesWith(From, To);
257   
258   // The old node may still be present in ExpandedNodes or PromotedNodes.
259   // Inform them about the replacement.
260   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
261     assert(From->getValueType(i) == To->getValueType(i) &&
262            "Node results don't match");
263     ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
264   }
265   
266   // Since we just made an unstructured update to the DAG, which could wreak
267   // general havoc on anything that once used From and now uses To, walk all
268   // users of the result, updating their flags.
269   for (SDNode::use_iterator I = To->use_begin(), E = To->use_end();I != E; ++I){
270     SDNode *User = *I;
271     // If the node isn't already processed or in the worklist, mark it as new,
272     // then use MarkNewNodes to recompute its ID.
273     int NodeId = User->getNodeId();
274     if (NodeId != ReadyToProcess && NodeId != Processed) {
275       User->setNodeId(NewNode);
276       MarkNewNodes(User);
277     }
278   }
279 }
280
281
282 /// RemapNode - If the specified value was already legalized to another value,
283 /// replace it by that value.
284 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
285   DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
286   if (I != ReplacedNodes.end()) {
287     // Use path compression to speed up future lookups if values get multiply
288     // replaced with other values.
289     RemapNode(I->second);
290     N = I->second;
291   }
292 }
293
294 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
295   if (Result.Val->getNodeId() == NewNode) 
296     MarkNewNodes(Result.Val);
297
298   SDOperand &OpEntry = PromotedNodes[Op];
299   assert(OpEntry.Val == 0 && "Node is already promoted!");
300   OpEntry = Result;
301 }
302
303 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
304   if (Result.Val->getNodeId() == NewNode) 
305     MarkNewNodes(Result.Val);
306   
307   SDOperand &OpEntry = ScalarizedNodes[Op];
308   assert(OpEntry.Val == 0 && "Node is already scalarized!");
309   OpEntry = Result;
310 }
311
312
313 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo, 
314                                      SDOperand &Hi) {
315   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
316   RemapNode(Entry.first);
317   RemapNode(Entry.second);
318   assert(Entry.first.Val && "Operand isn't expanded");
319   Lo = Entry.first;
320   Hi = Entry.second;
321 }
322
323 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
324   // Remember that this is the result of the node.
325   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
326   assert(Entry.first.Val == 0 && "Node already expanded");
327   Entry.first = Lo;
328   Entry.second = Hi;
329   
330   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
331   if (Lo.Val->getNodeId() == NewNode) 
332     MarkNewNodes(Lo.Val);
333   if (Hi.Val->getNodeId() == NewNode) 
334     MarkNewNodes(Hi.Val);
335 }
336
337 void DAGTypeLegalizer::GetSplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
338   std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
339   RemapNode(Entry.first);
340   RemapNode(Entry.second);
341   assert(Entry.first.Val && "Operand isn't split");
342   Lo = Entry.first;
343   Hi = Entry.second;
344 }
345
346 void DAGTypeLegalizer::SetSplitOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
347   // Remember that this is the result of the node.
348   std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
349   assert(Entry.first.Val == 0 && "Node already split");
350   Entry.first = Lo;
351   Entry.second = Hi;
352   
353   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
354   if (Lo.Val->getNodeId() == NewNode) 
355     MarkNewNodes(Lo.Val);
356   if (Hi.Val->getNodeId() == NewNode) 
357     MarkNewNodes(Hi.Val);
358 }
359
360
361 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op, 
362                                                  MVT::ValueType DestVT) {
363   // Create the stack frame object.
364   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
365   
366   // Emit a store to the stack slot.
367   SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
368   // Result is a load from the stack slot.
369   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
370 }
371
372 /// HandleMemIntrinsic - This handles memcpy/memset/memmove with invalid
373 /// operands.  This promotes or expands the operands as required.
374 SDOperand DAGTypeLegalizer::HandleMemIntrinsic(SDNode *N) {
375   // The chain and pointer [operands #0 and #1] are always valid types.
376   SDOperand Chain = N->getOperand(0);
377   SDOperand Ptr   = N->getOperand(1);
378   SDOperand Op2   = N->getOperand(2);
379   
380   // Op #2 is either a value (memset) or a pointer.  Promote it if required.
381   switch (getTypeAction(Op2.getValueType())) {
382   default: assert(0 && "Unknown action for pointer/value operand");
383   case Legal: break;
384   case Promote: Op2 = GetPromotedOp(Op2); break;
385   }
386   
387   // The length could have any action required.
388   SDOperand Length = N->getOperand(3);
389   switch (getTypeAction(Length.getValueType())) {
390   default: assert(0 && "Unknown action for memop operand");
391   case Legal: break;
392   case Promote: Length = GetPromotedZExtOp(Length); break;
393   case Expand:
394     SDOperand Dummy;  // discard the high part.
395     GetExpandedOp(Length, Length, Dummy);
396     break;
397   }
398   
399   SDOperand Align = N->getOperand(4);
400   switch (getTypeAction(Align.getValueType())) {
401   default: assert(0 && "Unknown action for memop operand");
402   case Legal: break;
403   case Promote: Align = GetPromotedZExtOp(Align); break;
404   }
405   
406   SDOperand AlwaysInline = N->getOperand(5);
407   switch (getTypeAction(AlwaysInline.getValueType())) {
408   default: assert(0 && "Unknown action for memop operand");
409   case Legal: break;
410   case Promote: AlwaysInline = GetPromotedZExtOp(AlwaysInline); break;
411   }
412   
413   SDOperand Ops[] = { Chain, Ptr, Op2, Length, Align, AlwaysInline };
414   return DAG.UpdateNodeOperands(SDOperand(N, 0), Ops, 6);
415 }
416
417 /// SplitOp - Return the lower and upper halves of Op's bits in a value type
418 /// half the size of Op's.
419 void DAGTypeLegalizer::SplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
420   unsigned NVTBits = MVT::getSizeInBits(Op.getValueType())/2;
421   assert(MVT::getSizeInBits(Op.getValueType()) == 2*NVTBits &&
422          "Cannot split odd sized integer type");
423   MVT::ValueType NVT = MVT::getIntegerType(NVTBits);
424   Lo = DAG.getNode(ISD::TRUNCATE, NVT, Op);
425   Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
426                    DAG.getConstant(NVTBits, TLI.getShiftAmountTy()));
427   Hi = DAG.getNode(ISD::TRUNCATE, NVT, Hi);
428 }
429
430
431 //===----------------------------------------------------------------------===//
432 //  Entry Point
433 //===----------------------------------------------------------------------===//
434
435 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
436 /// only uses types natively supported by the target.
437 ///
438 /// Note that this is an involved process that may invalidate pointers into
439 /// the graph.
440 void SelectionDAG::LegalizeTypes() {
441   DAGTypeLegalizer(*this).run();
442 }