1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "LegalizeTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Support/MathExtras.h"
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());
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());
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
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);
43 I->setNodeId(NewNode);
47 // Now that we have a set of nodes to process, handle them all.
48 while (!Worklist.empty()) {
49 SDNode *N = Worklist.back();
51 assert(N->getNodeId() == ReadyToProcess &&
52 "Node should be ready if on worklist!");
54 // Scan the values produced by the node, checking to see if any result
57 unsigned NumResults = N->getNumValues();
59 MVT::ValueType ResultVT = N->getValueType(i);
60 LegalizeAction Action = getTypeAction(ResultVT);
61 if (Action == Promote) {
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))
69 else if (MVT::getVectorNumElements(ResultVT) == 1)
70 ScalarizeResult(N, i); // Scalarize the single-element vector.
71 else // Split the vector in half.
72 assert(0 && "Vector splitting not implemented");
75 assert(Action == Legal && "Unknown action!");
77 } while (++i < NumResults);
79 // Scan the operand list for the node, handling any nodes with operands that
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);
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);
99 // Split the vector in half.
100 assert(0 && "Vector splitting not implemented");
104 assert(Action == Legal && "Unknown action!");
108 // If the node needs revisiting, don't add all users to the worklist etc.
112 if (i == NumOperands)
113 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
117 // If we reach here, the node was processed, potentially creating new nodes.
118 // Mark it as processed and add its users to the worklist as appropriate.
119 N->setNodeId(Processed);
121 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
124 int NodeID = User->getNodeId();
125 assert(NodeID != ReadyToProcess && NodeID != Processed &&
126 "Invalid node id for user of unprocessed node!");
128 // This node has two options: it can either be a new node or its Node ID
129 // may be a count of the number of operands it has that are not ready.
131 User->setNodeId(NodeID-1);
133 // If this was the last use it was waiting on, add it to the ready list.
134 if (NodeID-1 == ReadyToProcess)
135 Worklist.push_back(User);
139 // Otherwise, this node is new: this is the first operand of it that
140 // became ready. Its new NodeID is the number of operands it has minus 1
141 // (as this node is now processed).
142 assert(NodeID == NewNode && "Unknown node ID!");
143 User->setNodeId(User->getNumOperands()-1);
145 // If the node only has a single operand, it is now ready.
146 if (User->getNumOperands() == 1)
147 Worklist.push_back(User);
151 // If the root changed (e.g. it was a dead load, update the root).
152 DAG.setRoot(Dummy.getValue());
156 // Remove dead nodes. This is important to do for cleanliness but also before
157 // the checking loop below. Implicit folding by the DAG.getNode operators can
158 // cause unreachable nodes to be around with their flags set to new.
159 DAG.RemoveDeadNodes();
161 // In a debug build, scan all the nodes to make sure we found them all. This
162 // ensures that there are no cycles and that everything got processed.
164 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
165 E = DAG.allnodes_end(); I != E; ++I) {
166 if (I->getNodeId() == Processed)
168 cerr << "Unprocessed node: ";
169 I->dump(&DAG); cerr << "\n";
171 if (I->getNodeId() == NewNode)
172 cerr << "New node not 'noticed'?\n";
173 else if (I->getNodeId() > 0)
174 cerr << "Operand not processed?\n";
175 else if (I->getNodeId() == ReadyToProcess)
176 cerr << "Not added to worklist?\n";
182 /// MarkNewNodes - The specified node is the root of a subtree of potentially
183 /// new nodes. Add the correct NodeId to mark it.
184 void DAGTypeLegalizer::MarkNewNodes(SDNode *N) {
185 // If this was an existing node that is already done, we're done.
186 if (N->getNodeId() != NewNode)
189 // Okay, we know that this node is new. Recursively walk all of its operands
190 // to see if they are new also. The depth of this walk is bounded by the size
191 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
192 // about revisiting of nodes.
194 // As we walk the operands, keep track of the number of nodes that are
195 // processed. If non-zero, this will become the new nodeid of this node.
196 unsigned NumProcessed = 0;
197 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
198 int OpId = N->getOperand(i).Val->getNodeId();
200 MarkNewNodes(N->getOperand(i).Val);
201 else if (OpId == Processed)
205 N->setNodeId(N->getNumOperands()-NumProcessed);
206 if (N->getNodeId() == ReadyToProcess)
207 Worklist.push_back(N);
210 /// ReplaceValueWith - The specified value was legalized to the specified other
211 /// value. If they are different, update the DAG and NodeIDs replacing any uses
212 /// of From to use To instead.
213 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
214 if (From == To) return;
216 // If expansion produced new nodes, make sure they are properly marked.
217 if (To.Val->getNodeId() == NewNode)
218 MarkNewNodes(To.Val);
220 // Anything that used the old node should now use the new one. Note that this
221 // can potentially cause recursive merging.
222 DAG.ReplaceAllUsesOfValueWith(From, To);
224 // The old node may still be present in ExpandedNodes or PromotedNodes.
225 // Inform them about the replacement.
226 ReplacedNodes[From] = To;
228 // Since we just made an unstructured update to the DAG, which could wreak
229 // general havoc on anything that once used From and now uses To, walk all
230 // users of the result, updating their flags.
231 for (SDNode::use_iterator I = To.Val->use_begin(), E = To.Val->use_end();
234 // If the node isn't already processed or in the worklist, mark it as new,
235 // then use MarkNewNodes to recompute its ID.
236 int NodeId = User->getNodeId();
237 if (NodeId != ReadyToProcess && NodeId != Processed) {
238 User->setNodeId(NewNode);
244 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
245 /// node's results. The from and to node must define identical result types.
246 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
247 if (From == To) return;
248 assert(From->getNumValues() == To->getNumValues() &&
249 "Node results don't match");
251 // If expansion produced new nodes, make sure they are properly marked.
252 if (To->getNodeId() == NewNode)
255 // Anything that used the old node should now use the new one. Note that this
256 // can potentially cause recursive merging.
257 DAG.ReplaceAllUsesWith(From, To);
259 // The old node may still be present in ExpandedNodes or PromotedNodes.
260 // Inform them about the replacement.
261 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
262 assert(From->getValueType(i) == To->getValueType(i) &&
263 "Node results don't match");
264 ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
267 // Since we just made an unstructured update to the DAG, which could wreak
268 // general havoc on anything that once used From and now uses To, walk all
269 // users of the result, updating their flags.
270 for (SDNode::use_iterator I = To->use_begin(), E = To->use_end();I != E; ++I){
272 // If the node isn't already processed or in the worklist, mark it as new,
273 // then use MarkNewNodes to recompute its ID.
274 int NodeId = User->getNodeId();
275 if (NodeId != ReadyToProcess && NodeId != Processed) {
276 User->setNodeId(NewNode);
283 /// RemapNode - If the specified value was already legalized to another value,
284 /// replace it by that value.
285 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
286 DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
287 if (I != ReplacedNodes.end()) {
288 // Use path compression to speed up future lookups if values get multiply
289 // replaced with other values.
290 RemapNode(I->second);
295 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
296 if (Result.Val->getNodeId() == NewNode)
297 MarkNewNodes(Result.Val);
299 SDOperand &OpEntry = PromotedNodes[Op];
300 assert(OpEntry.Val == 0 && "Node is already promoted!");
304 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
305 if (Result.Val->getNodeId() == NewNode)
306 MarkNewNodes(Result.Val);
308 SDOperand &OpEntry = ScalarizedNodes[Op];
309 assert(OpEntry.Val == 0 && "Node is already scalarized!");
314 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo,
316 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
317 RemapNode(Entry.first);
318 RemapNode(Entry.second);
319 assert(Entry.first.Val && "Operand isn't expanded");
324 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo,
326 // Remember that this is the result of the node.
327 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
328 assert(Entry.first.Val == 0 && "Node already expanded");
332 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
333 if (Lo.Val->getNodeId() == NewNode)
334 MarkNewNodes(Lo.Val);
335 if (Hi.Val->getNodeId() == NewNode)
336 MarkNewNodes(Hi.Val);
339 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
340 MVT::ValueType DestVT) {
341 // Create the stack frame object.
342 SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
344 // Emit a store to the stack slot.
345 SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
346 // Result is a load from the stack slot.
347 return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
350 /// HandleMemIntrinsic - This handles memcpy/memset/memmove with invalid
351 /// operands. This promotes or expands the operands as required.
352 SDOperand DAGTypeLegalizer::HandleMemIntrinsic(SDNode *N) {
353 // The chain and pointer [operands #0 and #1] are always valid types.
354 SDOperand Chain = N->getOperand(0);
355 SDOperand Ptr = N->getOperand(1);
356 SDOperand Op2 = N->getOperand(2);
358 // Op #2 is either a value (memset) or a pointer. Promote it if required.
359 switch (getTypeAction(Op2.getValueType())) {
360 default: assert(0 && "Unknown action for pointer/value operand");
362 case Promote: Op2 = GetPromotedOp(Op2); break;
365 // The length could have any action required.
366 SDOperand Length = N->getOperand(3);
367 switch (getTypeAction(Length.getValueType())) {
368 default: assert(0 && "Unknown action for memop operand");
370 case Promote: Length = GetPromotedZExtOp(Length); break;
372 SDOperand Dummy; // discard the high part.
373 GetExpandedOp(Length, Length, Dummy);
377 SDOperand Align = N->getOperand(4);
378 switch (getTypeAction(Align.getValueType())) {
379 default: assert(0 && "Unknown action for memop operand");
381 case Promote: Align = GetPromotedZExtOp(Align); break;
384 SDOperand AlwaysInline = N->getOperand(5);
385 switch (getTypeAction(AlwaysInline.getValueType())) {
386 default: assert(0 && "Unknown action for memop operand");
388 case Promote: AlwaysInline = GetPromotedZExtOp(AlwaysInline); break;
391 SDOperand Ops[] = { Chain, Ptr, Op2, Length, Align, AlwaysInline };
392 return DAG.UpdateNodeOperands(SDOperand(N, 0), Ops, 6);
395 /// SplitOp - Return the lower and upper halves of Op's bits in a value type
396 /// half the size of Op's.
397 void DAGTypeLegalizer::SplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
398 unsigned NVTBits = MVT::getSizeInBits(Op.getValueType())/2;
399 assert(MVT::getSizeInBits(Op.getValueType()) == 2*NVTBits &&
400 "Cannot split odd sized integer type");
401 MVT::ValueType NVT = MVT::getIntegerType(NVTBits);
402 Lo = DAG.getNode(ISD::TRUNCATE, NVT, Op);
403 Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
404 DAG.getConstant(NVTBits, TLI.getShiftAmountTy()));
405 Hi = DAG.getNode(ISD::TRUNCATE, NVT, Hi);
409 //===----------------------------------------------------------------------===//
410 // Result Vector Scalarization: <1 x ty> -> ty.
411 //===----------------------------------------------------------------------===//
414 void DAGTypeLegalizer::ScalarizeResult(SDNode *N, unsigned ResNo) {
415 DEBUG(cerr << "Scalarize node result " << ResNo << ": "; N->dump(&DAG);
417 SDOperand R = SDOperand();
419 // FIXME: Custom lowering for scalarization?
421 // See if the target wants to custom expand this node.
422 if (TLI.getOperationAction(N->getOpcode(), N->getValueType(0)) ==
423 TargetLowering::Custom) {
424 // If the target wants to, allow it to lower this itself.
425 if (SDNode *P = TLI.ExpandOperationResult(N, DAG)) {
426 // Everything that once used N now uses P. We are guaranteed that the
427 // result value types of N and the result value types of P match.
428 ReplaceNodeWith(N, P);
434 switch (N->getOpcode()) {
437 cerr << "ScalarizeResult #" << ResNo << ": ";
438 N->dump(&DAG); cerr << "\n";
440 assert(0 && "Do not know how to scalarize the result of this operator!");
443 case ISD::UNDEF: R = ScalarizeRes_UNDEF(N); break;
444 case ISD::LOAD: R = ScalarizeRes_LOAD(cast<LoadSDNode>(N)); break;
460 case ISD::XOR: R = ScalarizeRes_BinOp(N); break;
465 case ISD::FCOS: R = ScalarizeRes_UnaryOp(N); break;
466 case ISD::FPOWI: R = ScalarizeRes_FPOWI(N); break;
467 case ISD::BUILD_VECTOR: R = N->getOperand(0); break;
468 case ISD::INSERT_VECTOR_ELT: R = N->getOperand(1); break;
469 case ISD::VECTOR_SHUFFLE: R = ScalarizeRes_VECTOR_SHUFFLE(N); break;
470 case ISD::BIT_CONVERT: R = ScalarizeRes_BIT_CONVERT(N); break;
471 case ISD::SELECT: R = ScalarizeRes_SELECT(N); break;
474 // If R is null, the sub-method took care of registering the resul.
476 SetScalarizedOp(SDOperand(N, ResNo), R);
479 SDOperand DAGTypeLegalizer::ScalarizeRes_UNDEF(SDNode *N) {
480 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(N->getValueType(0)));
483 SDOperand DAGTypeLegalizer::ScalarizeRes_LOAD(LoadSDNode *N) {
484 SDOperand Result = DAG.getLoad(MVT::getVectorElementType(N->getValueType(0)),
485 N->getChain(), N->getBasePtr(),
486 N->getSrcValue(), N->getSrcValueOffset(),
487 N->isVolatile(), N->getAlignment());
489 // Legalized the chain result - switch anything that used the old chain to
491 ReplaceValueWith(SDOperand(N, 1), Result.getValue(1));
495 SDOperand DAGTypeLegalizer::ScalarizeRes_BinOp(SDNode *N) {
496 SDOperand LHS = GetScalarizedOp(N->getOperand(0));
497 SDOperand RHS = GetScalarizedOp(N->getOperand(1));
498 return DAG.getNode(N->getOpcode(), LHS.getValueType(), LHS, RHS);
501 SDOperand DAGTypeLegalizer::ScalarizeRes_UnaryOp(SDNode *N) {
502 SDOperand Op = GetScalarizedOp(N->getOperand(0));
503 return DAG.getNode(N->getOpcode(), Op.getValueType(), Op);
506 SDOperand DAGTypeLegalizer::ScalarizeRes_FPOWI(SDNode *N) {
507 SDOperand Op = GetScalarizedOp(N->getOperand(0));
508 return DAG.getNode(ISD::FPOWI, Op.getValueType(), Op, N->getOperand(1));
511 SDOperand DAGTypeLegalizer::ScalarizeRes_VECTOR_SHUFFLE(SDNode *N) {
512 // Figure out if the scalar is the LHS or RHS and return it.
513 SDOperand EltNum = N->getOperand(2).getOperand(0);
514 unsigned Op = cast<ConstantSDNode>(EltNum)->getValue() != 0;
515 return GetScalarizedOp(N->getOperand(Op));
518 SDOperand DAGTypeLegalizer::ScalarizeRes_BIT_CONVERT(SDNode *N) {
519 MVT::ValueType NewVT = MVT::getVectorElementType(N->getValueType(0));
520 return DAG.getNode(ISD::BIT_CONVERT, NewVT, N->getOperand(0));
523 SDOperand DAGTypeLegalizer::ScalarizeRes_SELECT(SDNode *N) {
524 SDOperand LHS = GetScalarizedOp(N->getOperand(1));
525 return DAG.getNode(ISD::SELECT, LHS.getValueType(), N->getOperand(0), LHS,
526 GetScalarizedOp(N->getOperand(2)));
530 //===----------------------------------------------------------------------===//
531 // Operand Vector Scalarization <1 x ty> -> ty.
532 //===----------------------------------------------------------------------===//
534 bool DAGTypeLegalizer::ScalarizeOperand(SDNode *N, unsigned OpNo) {
535 DEBUG(cerr << "Scalarize node operand " << OpNo << ": "; N->dump(&DAG);
539 // FIXME: Should we support custom lowering for scalarization?
541 if (TLI.getOperationAction(N->getOpcode(), N->getValueType(0)) ==
542 TargetLowering::Custom)
543 Res = TLI.LowerOperation(SDOperand(N, 0), DAG);
547 switch (N->getOpcode()) {
550 cerr << "ScalarizeOperand Op #" << OpNo << ": ";
551 N->dump(&DAG); cerr << "\n";
553 assert(0 && "Do not know how to scalarize this operator's operand!");
556 case ISD::EXTRACT_VECTOR_ELT:
557 Res = ScalarizeOp_EXTRACT_VECTOR_ELT(N, OpNo);
562 // If the result is null, the sub-method took care of registering results etc.
563 if (!Res.Val) return false;
565 // If the result is N, the sub-method updated N in place. Check to see if any
566 // operands are new, and if so, mark them.
568 // Mark N as new and remark N and its operands. This allows us to correctly
569 // revisit N if it needs another step of promotion and allows us to visit
570 // any new operands to N.
571 N->setNodeId(NewNode);
576 assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
577 "Invalid operand expansion");
579 ReplaceValueWith(SDOperand(N, 0), Res);
583 /// ScalarizeOp_EXTRACT_VECTOR_ELT - If the input is a vector that needs to be
584 /// scalarized, it must be <1 x ty>, just return the operand, ignoring the
586 SDOperand DAGTypeLegalizer::ScalarizeOp_EXTRACT_VECTOR_ELT(SDNode *N,
588 return GetScalarizedOp(N->getOperand(0));
592 //===----------------------------------------------------------------------===//
594 //===----------------------------------------------------------------------===//
596 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
597 /// only uses types natively supported by the target.
599 /// Note that this is an involved process that may invalidate pointers into
601 void SelectionDAG::LegalizeTypes() {
602 DAGTypeLegalizer(*this).run();