LLVM API Documentation
00001 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the SelectionDAG::LegalizeTypes method. It transforms 00011 // an arbitrary well-formed SelectionDAG to only consist of legal types. This 00012 // is common code shared among the LegalizeTypes*.cpp files. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "LegalizeTypes.h" 00017 #include "llvm/CallingConv.h" 00018 #include "llvm/ADT/SetVector.h" 00019 #include "llvm/Support/CommandLine.h" 00020 #include "llvm/Target/TargetData.h" 00021 using namespace llvm; 00022 00023 static cl::opt<bool> 00024 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden); 00025 00026 /// PerformExpensiveChecks - Do extensive, expensive, sanity checking. 00027 void DAGTypeLegalizer::PerformExpensiveChecks() { 00028 // If a node is not processed, then none of its values should be mapped by any 00029 // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues. 00030 00031 // If a node is processed, then each value with an illegal type must be mapped 00032 // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues. 00033 // Values with a legal type may be mapped by ReplacedValues, but not by any of 00034 // the other maps. 00035 00036 // Note that these invariants may not hold momentarily when processing a node: 00037 // the node being processed may be put in a map before being marked Processed. 00038 00039 // Note that it is possible to have nodes marked NewNode in the DAG. This can 00040 // occur in two ways. Firstly, a node may be created during legalization but 00041 // never passed to the legalization core. This is usually due to the implicit 00042 // folding that occurs when using the DAG.getNode operators. Secondly, a new 00043 // node may be passed to the legalization core, but when analyzed may morph 00044 // into a different node, leaving the original node as a NewNode in the DAG. 00045 // A node may morph if one of its operands changes during analysis. Whether 00046 // it actually morphs or not depends on whether, after updating its operands, 00047 // it is equivalent to an existing node: if so, it morphs into that existing 00048 // node (CSE). An operand can change during analysis if the operand is a new 00049 // node that morphs, or it is a processed value that was mapped to some other 00050 // value (as recorded in ReplacedValues) in which case the operand is turned 00051 // into that other value. If a node morphs then the node it morphed into will 00052 // be used instead of it for legalization, however the original node continues 00053 // to live on in the DAG. 00054 // The conclusion is that though there may be nodes marked NewNode in the DAG, 00055 // all uses of such nodes are also marked NewNode: the result is a fungus of 00056 // NewNodes growing on top of the useful nodes, and perhaps using them, but 00057 // not used by them. 00058 00059 // If a value is mapped by ReplacedValues, then it must have no uses, except 00060 // by nodes marked NewNode (see above). 00061 00062 // The final node obtained by mapping by ReplacedValues is not marked NewNode. 00063 // Note that ReplacedValues should be applied iteratively. 00064 00065 // Note that the ReplacedValues map may also map deleted nodes. By iterating 00066 // over the DAG we only consider non-deleted nodes. 00067 SmallVector<SDNode*, 16> NewNodes; 00068 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 00069 E = DAG.allnodes_end(); I != E; ++I) { 00070 // Remember nodes marked NewNode - they are subject to extra checking below. 00071 if (I->getNodeId() == NewNode) 00072 NewNodes.push_back(I); 00073 00074 for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) { 00075 SDValue Res(I, i); 00076 bool Failed = false; 00077 00078 unsigned Mapped = 0; 00079 if (ReplacedValues.find(Res) != ReplacedValues.end()) { 00080 Mapped |= 1; 00081 // Check that remapped values are only used by nodes marked NewNode. 00082 for (SDNode::use_iterator UI = I->use_begin(), UE = I->use_end(); 00083 UI != UE; ++UI) 00084 if (UI.getUse().getResNo() == i) 00085 assert(UI->getNodeId() == NewNode && 00086 "Remapped value has non-trivial use!"); 00087 00088 // Check that the final result of applying ReplacedValues is not 00089 // marked NewNode. 00090 SDValue NewVal = ReplacedValues[Res]; 00091 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal); 00092 while (I != ReplacedValues.end()) { 00093 NewVal = I->second; 00094 I = ReplacedValues.find(NewVal); 00095 } 00096 assert(NewVal.getNode()->getNodeId() != NewNode && 00097 "ReplacedValues maps to a new node!"); 00098 } 00099 if (PromotedIntegers.find(Res) != PromotedIntegers.end()) 00100 Mapped |= 2; 00101 if (SoftenedFloats.find(Res) != SoftenedFloats.end()) 00102 Mapped |= 4; 00103 if (ScalarizedVectors.find(Res) != ScalarizedVectors.end()) 00104 Mapped |= 8; 00105 if (ExpandedIntegers.find(Res) != ExpandedIntegers.end()) 00106 Mapped |= 16; 00107 if (ExpandedFloats.find(Res) != ExpandedFloats.end()) 00108 Mapped |= 32; 00109 if (SplitVectors.find(Res) != SplitVectors.end()) 00110 Mapped |= 64; 00111 if (WidenedVectors.find(Res) != WidenedVectors.end()) 00112 Mapped |= 128; 00113 00114 if (I->getNodeId() != Processed) { 00115 if (Mapped != 0) { 00116 cerr << "Unprocessed value in a map!"; 00117 Failed = true; 00118 } 00119 } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) { 00120 // FIXME: Because of PR2957, the build vector can be placed on this 00121 // list but if the associated vector shuffle is split, the build vector 00122 // can also be split so we allow this to go through for now. 00123 if (Mapped > 1 && Res.getOpcode() != ISD::BUILD_VECTOR) { 00124 cerr << "Value with legal type was transformed!"; 00125 Failed = true; 00126 } 00127 } else { 00128 if (Mapped == 0) { 00129 cerr << "Processed value not in any map!"; 00130 Failed = true; 00131 } else if (Mapped & (Mapped - 1)) { 00132 cerr << "Value in multiple maps!"; 00133 Failed = true; 00134 } 00135 } 00136 00137 if (Failed) { 00138 if (Mapped & 1) 00139 cerr << " ReplacedValues"; 00140 if (Mapped & 2) 00141 cerr << " PromotedIntegers"; 00142 if (Mapped & 4) 00143 cerr << " SoftenedFloats"; 00144 if (Mapped & 8) 00145 cerr << " ScalarizedVectors"; 00146 if (Mapped & 16) 00147 cerr << " ExpandedIntegers"; 00148 if (Mapped & 32) 00149 cerr << " ExpandedFloats"; 00150 if (Mapped & 64) 00151 cerr << " SplitVectors"; 00152 if (Mapped & 128) 00153 cerr << " WidenedVectors"; 00154 cerr << "\n"; 00155 abort(); 00156 } 00157 } 00158 } 00159 00160 // Checked that NewNodes are only used by other NewNodes. 00161 for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) { 00162 SDNode *N = NewNodes[i]; 00163 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 00164 UI != UE; ++UI) 00165 assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!"); 00166 } 00167 } 00168 00169 /// run - This is the main entry point for the type legalizer. This does a 00170 /// top-down traversal of the dag, legalizing types as it goes. Returns "true" 00171 /// if it made any changes. 00172 bool DAGTypeLegalizer::run() { 00173 bool Changed = false; 00174 00175 // Create a dummy node (which is not added to allnodes), that adds a reference 00176 // to the root node, preventing it from being deleted, and tracking any 00177 // changes of the root. 00178 HandleSDNode Dummy(DAG.getRoot()); 00179 Dummy.setNodeId(Unanalyzed); 00180 00181 // The root of the dag may dangle to deleted nodes until the type legalizer is 00182 // done. Set it to null to avoid confusion. 00183 DAG.setRoot(SDValue()); 00184 00185 // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess' 00186 // (and remembering them) if they are leaves and assigning 'Unanalyzed' if 00187 // non-leaves. 00188 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 00189 E = DAG.allnodes_end(); I != E; ++I) { 00190 if (I->getNumOperands() == 0) { 00191 I->setNodeId(ReadyToProcess); 00192 Worklist.push_back(I); 00193 } else { 00194 I->setNodeId(Unanalyzed); 00195 } 00196 } 00197 00198 // Now that we have a set of nodes to process, handle them all. 00199 while (!Worklist.empty()) { 00200 #ifndef XDEBUG 00201 if (EnableExpensiveChecks) 00202 #endif 00203 PerformExpensiveChecks(); 00204 00205 SDNode *N = Worklist.back(); 00206 Worklist.pop_back(); 00207 assert(N->getNodeId() == ReadyToProcess && 00208 "Node should be ready if on worklist!"); 00209 00210 if (IgnoreNodeResults(N)) 00211 goto ScanOperands; 00212 00213 // Scan the values produced by the node, checking to see if any result 00214 // types are illegal. 00215 for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) { 00216 MVT ResultVT = N->getValueType(i); 00217 switch (getTypeAction(ResultVT)) { 00218 default: 00219 assert(false && "Unknown action!"); 00220 case Legal: 00221 break; 00222 // The following calls must take care of *all* of the node's results, 00223 // not just the illegal result they were passed (this includes results 00224 // with a legal type). Results can be remapped using ReplaceValueWith, 00225 // or their promoted/expanded/etc values registered in PromotedIntegers, 00226 // ExpandedIntegers etc. 00227 case PromoteInteger: 00228 PromoteIntegerResult(N, i); 00229 Changed = true; 00230 goto NodeDone; 00231 case ExpandInteger: 00232 ExpandIntegerResult(N, i); 00233 Changed = true; 00234 goto NodeDone; 00235 case SoftenFloat: 00236 SoftenFloatResult(N, i); 00237 Changed = true; 00238 goto NodeDone; 00239 case ExpandFloat: 00240 ExpandFloatResult(N, i); 00241 Changed = true; 00242 goto NodeDone; 00243 case ScalarizeVector: 00244 ScalarizeVectorResult(N, i); 00245 Changed = true; 00246 goto NodeDone; 00247 case SplitVector: 00248 SplitVectorResult(N, i); 00249 Changed = true; 00250 goto NodeDone; 00251 case WidenVector: 00252 WidenVectorResult(N, i); 00253 Changed = true; 00254 goto NodeDone; 00255 } 00256 } 00257 00258 ScanOperands: 00259 // Scan the operand list for the node, handling any nodes with operands that 00260 // are illegal. 00261 { 00262 unsigned NumOperands = N->getNumOperands(); 00263 bool NeedsReanalyzing = false; 00264 unsigned i; 00265 for (i = 0; i != NumOperands; ++i) { 00266 if (IgnoreNodeResults(N->getOperand(i).getNode())) 00267 continue; 00268 00269 if (N->getOpcode() == ISD::VECTOR_SHUFFLE && i == 2) { 00270 // The shuffle mask doesn't need to be a legal vector type. 00271 // FIXME: We can remove this once we fix PR2957. 00272 SetIgnoredNodeResult(N->getOperand(2).getNode()); 00273 continue; 00274 } 00275 00276 MVT OpVT = N->getOperand(i).getValueType(); 00277 switch (getTypeAction(OpVT)) { 00278 default: 00279 assert(false && "Unknown action!"); 00280 case Legal: 00281 continue; 00282 // The following calls must either replace all of the node's results 00283 // using ReplaceValueWith, and return "false"; or update the node's 00284 // operands in place, and return "true". 00285 case PromoteInteger: 00286 NeedsReanalyzing = PromoteIntegerOperand(N, i); 00287 Changed = true; 00288 break; 00289 case ExpandInteger: 00290 NeedsReanalyzing = ExpandIntegerOperand(N, i); 00291 Changed = true; 00292 break; 00293 case SoftenFloat: 00294 NeedsReanalyzing = SoftenFloatOperand(N, i); 00295 Changed = true; 00296 break; 00297 case ExpandFloat: 00298 NeedsReanalyzing = ExpandFloatOperand(N, i); 00299 Changed = true; 00300 break; 00301 case ScalarizeVector: 00302 NeedsReanalyzing = ScalarizeVectorOperand(N, i); 00303 Changed = true; 00304 break; 00305 case SplitVector: 00306 NeedsReanalyzing = SplitVectorOperand(N, i); 00307 Changed = true; 00308 break; 00309 case WidenVector: 00310 NeedsReanalyzing = WidenVectorOperand(N, i); 00311 Changed = true; 00312 break; 00313 } 00314 break; 00315 } 00316 00317 // The sub-method updated N in place. Check to see if any operands are new, 00318 // and if so, mark them. If the node needs revisiting, don't add all users 00319 // to the worklist etc. 00320 if (NeedsReanalyzing) { 00321 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?"); 00322 N->setNodeId(NewNode); 00323 // Recompute the NodeId and correct processed operands, adding the node to 00324 // the worklist if ready. 00325 SDNode *M = AnalyzeNewNode(N); 00326 if (M == N) 00327 // The node didn't morph - nothing special to do, it will be revisited. 00328 continue; 00329 00330 // The node morphed - this is equivalent to legalizing by replacing every 00331 // value of N with the corresponding value of M. So do that now. However 00332 // there is no need to remember the replacement - morphing will make sure 00333 // it is never used non-trivially. 00334 assert(N->getNumValues() == M->getNumValues() && 00335 "Node morphing changed the number of results!"); 00336 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) 00337 // Replacing the value takes care of remapping the new value. Do the 00338 // replacement without recording it in ReplacedValues. This does not 00339 // expunge From but that is fine - it is not really a new node. 00340 ReplaceValueWithHelper(SDValue(N, i), SDValue(M, i)); 00341 assert(N->getNodeId() == NewNode && "Unexpected node state!"); 00342 // The node continues to live on as part of the NewNode fungus that 00343 // grows on top of the useful nodes. Nothing more needs to be done 00344 // with it - move on to the next node. 00345 continue; 00346 } 00347 00348 if (i == NumOperands) { 00349 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n"); 00350 } 00351 } 00352 NodeDone: 00353 00354 // If we reach here, the node was processed, potentially creating new nodes. 00355 // Mark it as processed and add its users to the worklist as appropriate. 00356 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?"); 00357 N->setNodeId(Processed); 00358 00359 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 00360 UI != E; ++UI) { 00361 SDNode *User = *UI; 00362 int NodeId = User->getNodeId(); 00363 00364 // This node has two options: it can either be a new node or its Node ID 00365 // may be a count of the number of operands it has that are not ready. 00366 if (NodeId > 0) { 00367 User->setNodeId(NodeId-1); 00368 00369 // If this was the last use it was waiting on, add it to the ready list. 00370 if (NodeId-1 == ReadyToProcess) 00371 Worklist.push_back(User); 00372 continue; 00373 } 00374 00375 // If this is an unreachable new node, then ignore it. If it ever becomes 00376 // reachable by being used by a newly created node then it will be handled 00377 // by AnalyzeNewNode. 00378 if (NodeId == NewNode) 00379 continue; 00380 00381 // Otherwise, this node is new: this is the first operand of it that 00382 // became ready. Its new NodeId is the number of operands it has minus 1 00383 // (as this node is now processed). 00384 assert(NodeId == Unanalyzed && "Unknown node ID!"); 00385 User->setNodeId(User->getNumOperands() - 1); 00386 00387 // If the node only has a single operand, it is now ready. 00388 if (User->getNumOperands() == 1) 00389 Worklist.push_back(User); 00390 } 00391 } 00392 00393 #ifndef XDEBUG 00394 if (EnableExpensiveChecks) 00395 #endif 00396 PerformExpensiveChecks(); 00397 00398 // If the root changed (e.g. it was a dead load) update the root. 00399 DAG.setRoot(Dummy.getValue()); 00400 00401 // Remove dead nodes. This is important to do for cleanliness but also before 00402 // the checking loop below. Implicit folding by the DAG.getNode operators and 00403 // node morphing can cause unreachable nodes to be around with their flags set 00404 // to new. 00405 DAG.RemoveDeadNodes(); 00406 00407 // In a debug build, scan all the nodes to make sure we found them all. This 00408 // ensures that there are no cycles and that everything got processed. 00409 #ifndef NDEBUG 00410 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 00411 E = DAG.allnodes_end(); I != E; ++I) { 00412 bool Failed = false; 00413 00414 // Check that all result types are legal. 00415 if (!IgnoreNodeResults(I)) 00416 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i) 00417 if (!isTypeLegal(I->getValueType(i))) { 00418 cerr << "Result type " << i << " illegal!\n"; 00419 Failed = true; 00420 } 00421 00422 // Check that all operand types are legal. 00423 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i) 00424 if (!IgnoreNodeResults(I->getOperand(i).getNode()) && 00425 !isTypeLegal(I->getOperand(i).getValueType())) { 00426 cerr << "Operand type " << i << " illegal!\n"; 00427 Failed = true; 00428 } 00429 00430 if (I->getNodeId() != Processed) { 00431 if (I->getNodeId() == NewNode) 00432 cerr << "New node not analyzed?\n"; 00433 else if (I->getNodeId() == Unanalyzed) 00434 cerr << "Unanalyzed node not noticed?\n"; 00435 else if (I->getNodeId() > 0) 00436 cerr << "Operand not processed?\n"; 00437 else if (I->getNodeId() == ReadyToProcess) 00438 cerr << "Not added to worklist?\n"; 00439 Failed = true; 00440 } 00441 00442 if (Failed) { 00443 I->dump(&DAG); cerr << "\n"; 00444 abort(); 00445 } 00446 } 00447 #endif 00448 00449 return Changed; 00450 } 00451 00452 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially 00453 /// new nodes. Correct any processed operands (this may change the node) and 00454 /// calculate the NodeId. If the node itself changes to a processed node, it 00455 /// is not remapped - the caller needs to take care of this. 00456 /// Returns the potentially changed node. 00457 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) { 00458 // If this was an existing node that is already done, we're done. 00459 if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed) 00460 return N; 00461 00462 // Remove any stale map entries. 00463 ExpungeNode(N); 00464 00465 // Okay, we know that this node is new. Recursively walk all of its operands 00466 // to see if they are new also. The depth of this walk is bounded by the size 00467 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry 00468 // about revisiting of nodes. 00469 // 00470 // As we walk the operands, keep track of the number of nodes that are 00471 // processed. If non-zero, this will become the new nodeid of this node. 00472 // Operands may morph when they are analyzed. If so, the node will be 00473 // updated after all operands have been analyzed. Since this is rare, 00474 // the code tries to minimize overhead in the non-morphing case. 00475 00476 SmallVector<SDValue, 8> NewOps; 00477 unsigned NumProcessed = 0; 00478 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 00479 SDValue OrigOp = N->getOperand(i); 00480 SDValue Op = OrigOp; 00481 00482 AnalyzeNewValue(Op); // Op may morph. 00483 00484 if (Op.getNode()->getNodeId() == Processed) 00485 ++NumProcessed; 00486 00487 if (!NewOps.empty()) { 00488 // Some previous operand changed. Add this one to the list. 00489 NewOps.push_back(Op); 00490 } else if (Op != OrigOp) { 00491 // This is the first operand to change - add all operands so far. 00492 for (unsigned j = 0; j < i; ++j) 00493 NewOps.push_back(N->getOperand(j)); 00494 NewOps.push_back(Op); 00495 } 00496 } 00497 00498 // Some operands changed - update the node. 00499 if (!NewOps.empty()) { 00500 SDNode *M = DAG.UpdateNodeOperands(SDValue(N, 0), &NewOps[0], 00501 NewOps.size()).getNode(); 00502 if (M != N) { 00503 // The node morphed into a different node. Normally for this to happen 00504 // the original node would have to be marked NewNode. However this can 00505 // in theory momentarily not be the case while ReplaceValueWith is doing 00506 // its stuff. Mark the original node NewNode to help sanity checking. 00507 N->setNodeId(NewNode); 00508 if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed) 00509 // It morphed into a previously analyzed node - nothing more to do. 00510 return M; 00511 00512 // It morphed into a different new node. Do the equivalent of passing 00513 // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need 00514 // to remap the operands, since they are the same as the operands we 00515 // remapped above. 00516 N = M; 00517 ExpungeNode(N); 00518 } 00519 } 00520 00521 // Calculate the NodeId. 00522 N->setNodeId(N->getNumOperands() - NumProcessed); 00523 if (N->getNodeId() == ReadyToProcess) 00524 Worklist.push_back(N); 00525 00526 return N; 00527 } 00528 00529 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed. 00530 /// If the node changes to a processed node, then remap it. 00531 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) { 00532 Val.setNode(AnalyzeNewNode(Val.getNode())); 00533 if (Val.getNode()->getNodeId() == Processed) 00534 // We were passed a processed node, or it morphed into one - remap it. 00535 RemapValue(Val); 00536 } 00537 00538 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it. 00539 /// This can occur when a node is deleted then reallocated as a new node - 00540 /// the mapping in ReplacedValues applies to the deleted node, not the new 00541 /// one. 00542 /// The only map that can have a deleted node as a source is ReplacedValues. 00543 /// Other maps can have deleted nodes as targets, but since their looked-up 00544 /// values are always immediately remapped using RemapValue, resulting in a 00545 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue 00546 /// always performs correct mappings. In order to keep the mapping correct, 00547 /// ExpungeNode should be called on any new nodes *before* adding them as 00548 /// either source or target to ReplacedValues (which typically means calling 00549 /// Expunge when a new node is first seen, since it may no longer be marked 00550 /// NewNode by the time it is added to ReplacedValues). 00551 void DAGTypeLegalizer::ExpungeNode(SDNode *N) { 00552 if (N->getNodeId() != NewNode) 00553 return; 00554 00555 // If N is not remapped by ReplacedValues then there is nothing to do. 00556 unsigned i, e; 00557 for (i = 0, e = N->getNumValues(); i != e; ++i) 00558 if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end()) 00559 break; 00560 00561 if (i == e) 00562 return; 00563 00564 // Remove N from all maps - this is expensive but rare. 00565 00566 for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(), 00567 E = PromotedIntegers.end(); I != E; ++I) { 00568 assert(I->first.getNode() != N); 00569 RemapValue(I->second); 00570 } 00571 00572 for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(), 00573 E = SoftenedFloats.end(); I != E; ++I) { 00574 assert(I->first.getNode() != N); 00575 RemapValue(I->second); 00576 } 00577 00578 for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(), 00579 E = ScalarizedVectors.end(); I != E; ++I) { 00580 assert(I->first.getNode() != N); 00581 RemapValue(I->second); 00582 } 00583 00584 for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(), 00585 E = WidenedVectors.end(); I != E; ++I) { 00586 assert(I->first.getNode() != N); 00587 RemapValue(I->second); 00588 } 00589 00590 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator 00591 I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){ 00592 assert(I->first.getNode() != N); 00593 RemapValue(I->second.first); 00594 RemapValue(I->second.second); 00595 } 00596 00597 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator 00598 I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) { 00599 assert(I->first.getNode() != N); 00600 RemapValue(I->second.first); 00601 RemapValue(I->second.second); 00602 } 00603 00604 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator 00605 I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) { 00606 assert(I->first.getNode() != N); 00607 RemapValue(I->second.first); 00608 RemapValue(I->second.second); 00609 } 00610 00611 for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(), 00612 E = ReplacedValues.end(); I != E; ++I) 00613 RemapValue(I->second); 00614 00615 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) 00616 ReplacedValues.erase(SDValue(N, i)); 00617 } 00618 00619 /// RemapValue - If the specified value was already legalized to another value, 00620 /// replace it by that value. 00621 void DAGTypeLegalizer::RemapValue(SDValue &N) { 00622 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N); 00623 if (I != ReplacedValues.end()) { 00624 // Use path compression to speed up future lookups if values get multiply 00625 // replaced with other values. 00626 RemapValue(I->second); 00627 N = I->second; 00628 assert(N.getNode()->getNodeId() != NewNode && "Mapped to new node!"); 00629 } 00630 } 00631 00632 namespace { 00633 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for 00634 /// updates to nodes and recomputes their ready state. 00635 class VISIBILITY_HIDDEN NodeUpdateListener : 00636 public SelectionDAG::DAGUpdateListener { 00637 DAGTypeLegalizer &DTL; 00638 SmallSetVector<SDNode*, 16> &NodesToAnalyze; 00639 public: 00640 explicit NodeUpdateListener(DAGTypeLegalizer &dtl, 00641 SmallSetVector<SDNode*, 16> &nta) 00642 : DTL(dtl), NodesToAnalyze(nta) {} 00643 00644 virtual void NodeDeleted(SDNode *N, SDNode *E) { 00645 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess && 00646 N->getNodeId() != DAGTypeLegalizer::Processed && 00647 "Invalid node ID for RAUW deletion!"); 00648 // It is possible, though rare, for the deleted node N to occur as a 00649 // target in a map, so note the replacement N -> E in ReplacedValues. 00650 assert(E && "Node not replaced?"); 00651 DTL.NoteDeletion(N, E); 00652 00653 // In theory the deleted node could also have been scheduled for analysis. 00654 // So add it to the set of nodes which will not be analyzed. 00655 NodesToAnalyze.remove(N); 00656 00657 // In general nothing needs to be done for E, since it didn't change but 00658 // only gained new uses. However N -> E was just added to ReplacedValues, 00659 // and the result of a ReplacedValues mapping is not allowed to be marked 00660 // NewNode. So if E is marked NewNode, then it needs to be analyzed. 00661 if (E->getNodeId() == DAGTypeLegalizer::NewNode) 00662 NodesToAnalyze.insert(E); 00663 } 00664 00665 virtual void NodeUpdated(SDNode *N) { 00666 // Node updates can mean pretty much anything. It is possible that an 00667 // operand was set to something already processed (f.e.) in which case 00668 // this node could become ready. Recompute its flags. 00669 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess && 00670 N->getNodeId() != DAGTypeLegalizer::Processed && 00671 "Invalid node ID for RAUW deletion!"); 00672 NodesToAnalyze.insert(N); 00673 } 00674 }; 00675 } 00676 00677 00678 /// ReplaceValueWithHelper - Internal helper for ReplaceValueWith. Updates the 00679 /// DAG causing any uses of From to use To instead, but without expunging From 00680 /// or recording the replacement in ReplacedValues. Do not call directly unless 00681 /// you really know what you are doing! 00682 void DAGTypeLegalizer::ReplaceValueWithHelper(SDValue From, SDValue To) { 00683 assert(From.getNode() != To.getNode() && "Potential legalization loop!"); 00684 00685 // If expansion produced new nodes, make sure they are properly marked. 00686 AnalyzeNewValue(To); // Expunges To. 00687 00688 // Anything that used the old node should now use the new one. Note that this 00689 // can potentially cause recursive merging. 00690 SmallSetVector<SDNode*, 16> NodesToAnalyze; 00691 NodeUpdateListener NUL(*this, NodesToAnalyze); 00692 DAG.ReplaceAllUsesOfValueWith(From, To, &NUL); 00693 00694 // Process the list of nodes that need to be reanalyzed. 00695 while (!NodesToAnalyze.empty()) { 00696 SDNode *N = NodesToAnalyze.back(); 00697 NodesToAnalyze.pop_back(); 00698 00699 // Analyze the node's operands and recalculate the node ID. 00700 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess && 00701 N->getNodeId() != DAGTypeLegalizer::Processed && 00702 "Invalid node ID for RAUW analysis!"); 00703 N->setNodeId(NewNode); 00704 SDNode *M = AnalyzeNewNode(N); 00705 if (M != N) { 00706 // The node morphed into a different node. Make everyone use the new node 00707 // instead. 00708 assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!"); 00709 assert(N->getNumValues() == M->getNumValues() && 00710 "Node morphing changed the number of results!"); 00711 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) { 00712 SDValue OldVal(N, i); 00713 SDValue NewVal(M, i); 00714 if (M->getNodeId() == Processed) 00715 RemapValue(NewVal); 00716 DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal, &NUL); 00717 } 00718 // The original node continues to exist in the DAG, marked NewNode. 00719 } 00720 } 00721 } 00722 00723 /// ReplaceValueWith - The specified value was legalized to the specified other 00724 /// value. Update the DAG and NodeIds replacing any uses of From to use To 00725 /// instead. 00726 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) { 00727 assert(From.getNode()->getNodeId() == ReadyToProcess && 00728 "Only the node being processed may be remapped!"); 00729 00730 // If expansion produced new nodes, make sure they are properly marked. 00731 ExpungeNode(From.getNode()); 00732 AnalyzeNewValue(To); // Expunges To. 00733 00734 // The old node may still be present in a map like ExpandedIntegers or 00735 // PromotedIntegers. Inform maps about the replacement. 00736 ReplacedValues[From] = To; 00737 00738 // Do the replacement. 00739 ReplaceValueWithHelper(From, To); 00740 } 00741 00742 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) { 00743 AnalyzeNewValue(Result); 00744 00745 SDValue &OpEntry = PromotedIntegers[Op]; 00746 assert(OpEntry.getNode() == 0 && "Node is already promoted!"); 00747 OpEntry = Result; 00748 } 00749 00750 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) { 00751 AnalyzeNewValue(Result); 00752 00753 SDValue &OpEntry = SoftenedFloats[Op]; 00754 assert(OpEntry.getNode() == 0 && "Node is already converted to integer!"); 00755 OpEntry = Result; 00756 } 00757 00758 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) { 00759 AnalyzeNewValue(Result); 00760 00761 SDValue &OpEntry = ScalarizedVectors[Op]; 00762 assert(OpEntry.getNode() == 0 && "Node is already scalarized!"); 00763 OpEntry = Result; 00764 } 00765 00766 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo, 00767 SDValue &Hi) { 00768 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op]; 00769 RemapValue(Entry.first); 00770 RemapValue(Entry.second); 00771 assert(Entry.first.getNode() && "Operand isn't expanded"); 00772 Lo = Entry.first; 00773 Hi = Entry.second; 00774 } 00775 00776 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo, 00777 SDValue Hi) { 00778 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant. 00779 AnalyzeNewValue(Lo); 00780 AnalyzeNewValue(Hi); 00781 00782 // Remember that this is the result of the node. 00783 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op]; 00784 assert(Entry.first.getNode() == 0 && "Node already expanded"); 00785 Entry.first = Lo; 00786 Entry.second = Hi; 00787 } 00788 00789 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo, 00790 SDValue &Hi) { 00791 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op]; 00792 RemapValue(Entry.first); 00793 RemapValue(Entry.second); 00794 assert(Entry.first.getNode() && "Operand isn't expanded"); 00795 Lo = Entry.first; 00796 Hi = Entry.second; 00797 } 00798 00799 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo, 00800 SDValue Hi) { 00801 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant. 00802 AnalyzeNewValue(Lo); 00803 AnalyzeNewValue(Hi); 00804 00805 // Remember that this is the result of the node. 00806 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op]; 00807 assert(Entry.first.getNode() == 0 && "Node already expanded"); 00808 Entry.first = Lo; 00809 Entry.second = Hi; 00810 } 00811 00812 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo, 00813 SDValue &Hi) { 00814 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op]; 00815 RemapValue(Entry.first); 00816 RemapValue(Entry.second); 00817 assert(Entry.first.getNode() && "Operand isn't split"); 00818 Lo = Entry.first; 00819 Hi = Entry.second; 00820 } 00821 00822 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo, 00823 SDValue Hi) { 00824 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant. 00825 AnalyzeNewValue(Lo); 00826 AnalyzeNewValue(Hi); 00827 00828 // Remember that this is the result of the node. 00829 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op]; 00830 assert(Entry.first.getNode() == 0 && "Node already split"); 00831 Entry.first = Lo; 00832 Entry.second = Hi; 00833 } 00834 00835 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) { 00836 AnalyzeNewValue(Result); 00837 00838 SDValue &OpEntry = WidenedVectors[Op]; 00839 assert(OpEntry.getNode() == 0 && "Node already widened!"); 00840 OpEntry = Result; 00841 } 00842 00843 // Set to ignore result 00844 void DAGTypeLegalizer::SetIgnoredNodeResult(SDNode* N) { 00845 IgnoredNodesResultsSet.insert(N); 00846 } 00847 00848 //===----------------------------------------------------------------------===// 00849 // Utilities. 00850 //===----------------------------------------------------------------------===// 00851 00852 /// BitConvertToInteger - Convert to an integer of the same size. 00853 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) { 00854 unsigned BitWidth = Op.getValueType().getSizeInBits(); 00855 return DAG.getNode(ISD::BIT_CONVERT, Op.getNode()->getDebugLoc(), 00856 MVT::getIntegerVT(BitWidth), Op); 00857 } 00858 00859 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op, 00860 MVT DestVT) { 00861 DebugLoc dl = Op.getNode()->getDebugLoc(); 00862 // Create the stack frame object. Make sure it is aligned for both 00863 // the source and destination types. 00864 SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT); 00865 // Emit a store to the stack slot. 00866 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr, NULL, 0); 00867 // Result is a load from the stack slot. 00868 return DAG.getLoad(DestVT, dl, Store, StackPtr, NULL, 0); 00869 } 00870 00871 /// CustomLowerResults - Replace the node's results with custom code provided 00872 /// by the target and return "true", or do nothing and return "false". 00873 /// The last parameter is FALSE if we are dealing with a node with legal 00874 /// result types and illegal operand. The second parameter denotes the illegal 00875 /// OperandNo in that case. 00876 /// The last parameter being TRUE means we are dealing with a 00877 /// node with illegal result types. The second parameter denotes the illegal 00878 /// ResNo in that case. 00879 bool DAGTypeLegalizer::CustomLowerResults(SDNode *N, MVT VT, 00880 bool LegalizeResult) { 00881 // See if the target wants to custom lower this node. 00882 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom) 00883 return false; 00884 00885 SmallVector<SDValue, 8> Results; 00886 if (LegalizeResult) 00887 TLI.ReplaceNodeResults(N, Results, DAG); 00888 else 00889 TLI.LowerOperationWrapper(N, Results, DAG); 00890 00891 if (Results.empty()) 00892 // The target didn't want to custom lower it after all. 00893 return false; 00894 00895 // Make everything that once used N's values now use those in Results instead. 00896 assert(Results.size() == N->getNumValues() && 00897 "Custom lowering returned the wrong number of results!"); 00898 for (unsigned i = 0, e = Results.size(); i != e; ++i) 00899 ReplaceValueWith(SDValue(N, i), Results[i]); 00900 return true; 00901 } 00902 00903 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 00904 /// which is split into two not necessarily identical pieces. 00905 void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT, MVT &LoVT, MVT &HiVT) { 00906 if (!InVT.isVector()) { 00907 LoVT = HiVT = TLI.getTypeToTransformTo(InVT); 00908 } else { 00909 MVT NewEltVT = InVT.getVectorElementType(); 00910 unsigned NumElements = InVT.getVectorNumElements(); 00911 if ((NumElements & (NumElements-1)) == 0) { // Simple power of two vector. 00912 NumElements >>= 1; 00913 LoVT = HiVT = MVT::getVectorVT(NewEltVT, NumElements); 00914 } else { // Non-power-of-two vectors. 00915 unsigned NewNumElts_Lo = 1 << Log2_32(NumElements); 00916 unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo; 00917 LoVT = MVT::getVectorVT(NewEltVT, NewNumElts_Lo); 00918 HiVT = MVT::getVectorVT(NewEltVT, NewNumElts_Hi); 00919 } 00920 } 00921 } 00922 00923 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, MVT EltVT, 00924 SDValue Index) { 00925 DebugLoc dl = Index.getNode()->getDebugLoc(); 00926 // Make sure the index type is big enough to compute in. 00927 if (Index.getValueType().bitsGT(TLI.getPointerTy())) 00928 Index = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Index); 00929 else 00930 Index = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Index); 00931 00932 // Calculate the element offset and add it to the pointer. 00933 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size. 00934 00935 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index, 00936 DAG.getConstant(EltSize, Index.getValueType())); 00937 return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr); 00938 } 00939 00940 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi. 00941 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) { 00942 // Arbitrarily use dlHi for result DebugLoc 00943 DebugLoc dlHi = Hi.getNode()->getDebugLoc(); 00944 DebugLoc dlLo = Lo.getNode()->getDebugLoc(); 00945 MVT LVT = Lo.getValueType(); 00946 MVT HVT = Hi.getValueType(); 00947 MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits()); 00948 00949 Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo); 00950 Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi); 00951 Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi, 00952 DAG.getConstant(LVT.getSizeInBits(), TLI.getPointerTy())); 00953 return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi); 00954 } 00955 00956 /// LibCallify - Convert the node into a libcall with the same prototype. 00957 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N, 00958 bool isSigned) { 00959 unsigned NumOps = N->getNumOperands(); 00960 DebugLoc dl = N->getDebugLoc(); 00961 if (NumOps == 0) { 00962 return MakeLibCall(LC, N->getValueType(0), 0, 0, isSigned, dl); 00963 } else if (NumOps == 1) { 00964 SDValue Op = N->getOperand(0); 00965 return MakeLibCall(LC, N->getValueType(0), &Op, 1, isSigned, dl); 00966 } else if (NumOps == 2) { 00967 SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) }; 00968 return MakeLibCall(LC, N->getValueType(0), Ops, 2, isSigned, dl); 00969 } 00970 SmallVector<SDValue, 8> Ops(NumOps); 00971 for (unsigned i = 0; i < NumOps; ++i) 00972 Ops[i] = N->getOperand(i); 00973 00974 return MakeLibCall(LC, N->getValueType(0), &Ops[0], NumOps, isSigned, dl); 00975 } 00976 00977 /// MakeLibCall - Generate a libcall taking the given operands as arguments and 00978 /// returning a result of type RetVT. 00979 SDValue DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT, 00980 const SDValue *Ops, unsigned NumOps, 00981 bool isSigned, DebugLoc dl) { 00982 TargetLowering::ArgListTy Args; 00983 Args.reserve(NumOps); 00984 00985 TargetLowering::ArgListEntry Entry; 00986 for (unsigned i = 0; i != NumOps; ++i) { 00987 Entry.Node = Ops[i]; 00988 Entry.Ty = Entry.Node.getValueType().getTypeForMVT(); 00989 Entry.isSExt = isSigned; 00990 Entry.isZExt = !isSigned; 00991 Args.push_back(Entry); 00992 } 00993 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 00994 TLI.getPointerTy()); 00995 00996 const Type *RetTy = RetVT.getTypeForMVT(); 00997 std::pair<SDValue,SDValue> CallInfo = 00998 TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false, 00999 false, CallingConv::C, false, Callee, Args, DAG, dl); 01000 return CallInfo.first; 01001 } 01002 01003 /// PromoteTargetBoolean - Promote the given target boolean to a target boolean 01004 /// of the given type. A target boolean is an integer value, not necessarily of 01005 /// type i1, the bits of which conform to getBooleanContents. 01006 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, MVT VT) { 01007 DebugLoc dl = Bool.getNode()->getDebugLoc(); 01008 ISD::NodeType ExtendCode; 01009 switch (TLI.getBooleanContents()) { 01010 default: 01011 assert(false && "Unknown BooleanContent!"); 01012 case TargetLowering::UndefinedBooleanContent: 01013 // Extend to VT by adding rubbish bits. 01014 ExtendCode = ISD::ANY_EXTEND; 01015 break; 01016 case TargetLowering::ZeroOrOneBooleanContent: 01017 // Extend to VT by adding zero bits. 01018 ExtendCode = ISD::ZERO_EXTEND; 01019 break; 01020 case TargetLowering::ZeroOrNegativeOneBooleanContent: { 01021 // Extend to VT by copying the sign bit. 01022 ExtendCode = ISD::SIGN_EXTEND; 01023 break; 01024 } 01025 } 01026 return DAG.getNode(ExtendCode, dl, VT, Bool); 01027 } 01028 01029 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT 01030 /// bits in Hi. 01031 void DAGTypeLegalizer::SplitInteger(SDValue Op, 01032 MVT LoVT, MVT HiVT, 01033 SDValue &Lo, SDValue &Hi) { 01034 DebugLoc dl = Op.getNode()->getDebugLoc(); 01035 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() == 01036 Op.getValueType().getSizeInBits() && "Invalid integer splitting!"); 01037 Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op); 01038 Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op, 01039 DAG.getConstant(LoVT.getSizeInBits(), TLI.getPointerTy())); 01040 Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi); 01041 } 01042 01043 /// SplitInteger - Return the lower and upper halves of Op's bits in a value 01044 /// type half the size of Op's. 01045 void DAGTypeLegalizer::SplitInteger(SDValue Op, 01046 SDValue &Lo, SDValue &Hi) { 01047 MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2); 01048 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi); 01049 } 01050 01051 01052 //===----------------------------------------------------------------------===// 01053 // Entry Point 01054 //===----------------------------------------------------------------------===// 01055 01056 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that 01057 /// only uses types natively supported by the target. Returns "true" if it made 01058 /// any changes. 01059 /// 01060 /// Note that this is an involved process that may invalidate pointers into 01061 /// the graph. 01062 bool SelectionDAG::LegalizeTypes() { 01063 return DAGTypeLegalizer(*this).run(); 01064 }