1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This transformation pass performs a sparse conditional constant propagation 10 // in MLIR. It identifies values known to be constant, propagates that 11 // information throughout the IR, and replaces them. This is done with an 12 // optimisitic dataflow analysis that assumes that all values are constant until 13 // proven otherwise. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "PassDetail.h" 18 #include "mlir/IR/Builders.h" 19 #include "mlir/IR/Dialect.h" 20 #include "mlir/Interfaces/ControlFlowInterfaces.h" 21 #include "mlir/Interfaces/SideEffectInterfaces.h" 22 #include "mlir/Pass/Pass.h" 23 #include "mlir/Transforms/FoldUtils.h" 24 #include "mlir/Transforms/Passes.h" 25 26 using namespace mlir; 27 28 namespace { 29 /// This class represents a single lattice value. A lattive value corresponds to 30 /// the various different states that a value in the SCCP dataflow anaylsis can 31 /// take. See 'Kind' below for more details on the different states a value can 32 /// take. 33 class LatticeValue { 34 enum Kind { 35 /// A value with a yet to be determined value. This state may be changed to 36 /// anything. 37 Unknown, 38 39 /// A value that is known to be a constant. This state may be changed to 40 /// overdefined. 41 Constant, 42 43 /// A value that cannot statically be determined to be a constant. This 44 /// state cannot be changed. 45 Overdefined 46 }; 47 48 public: 49 /// Initialize a lattice value with "Unknown". 50 LatticeValue() 51 : constantAndTag(nullptr, Kind::Unknown), constantDialect(nullptr) {} 52 /// Initialize a lattice value with a constant. 53 LatticeValue(Attribute attr, Dialect *dialect) 54 : constantAndTag(attr, Kind::Constant), constantDialect(dialect) {} 55 56 /// Returns true if this lattice value is unknown. 57 bool isUnknown() const { return constantAndTag.getInt() == Kind::Unknown; } 58 59 /// Mark the lattice value as overdefined. 60 void markOverdefined() { 61 constantAndTag.setPointerAndInt(nullptr, Kind::Overdefined); 62 constantDialect = nullptr; 63 } 64 65 /// Returns true if the lattice is overdefined. 66 bool isOverdefined() const { 67 return constantAndTag.getInt() == Kind::Overdefined; 68 } 69 70 /// Mark the lattice value as constant. 71 void markConstant(Attribute value, Dialect *dialect) { 72 constantAndTag.setPointerAndInt(value, Kind::Constant); 73 constantDialect = dialect; 74 } 75 76 /// If this lattice is constant, return the constant. Returns nullptr 77 /// otherwise. 78 Attribute getConstant() const { return constantAndTag.getPointer(); } 79 80 /// If this lattice is constant, return the dialect to use when materializing 81 /// the constant. 82 Dialect *getConstantDialect() const { 83 assert(getConstant() && "expected valid constant"); 84 return constantDialect; 85 } 86 87 /// Merge in the value of the 'rhs' lattice into this one. Returns true if the 88 /// lattice value changed. 89 bool meet(const LatticeValue &rhs) { 90 // If we are already overdefined, or rhs is unknown, there is nothing to do. 91 if (isOverdefined() || rhs.isUnknown()) 92 return false; 93 // If we are unknown, just take the value of rhs. 94 if (isUnknown()) { 95 constantAndTag = rhs.constantAndTag; 96 constantDialect = rhs.constantDialect; 97 return true; 98 } 99 100 // Otherwise, if this value doesn't match rhs go straight to overdefined. 101 if (constantAndTag != rhs.constantAndTag) { 102 markOverdefined(); 103 return true; 104 } 105 return false; 106 } 107 108 private: 109 /// The attribute value if this is a constant and the tag for the element 110 /// kind. 111 llvm::PointerIntPair<Attribute, 2, Kind> constantAndTag; 112 113 /// The dialect the constant originated from. This is only valid if the 114 /// lattice is a constant. This is not used as part of the key, and is only 115 /// needed to materialize the held constant if necessary. 116 Dialect *constantDialect; 117 }; 118 119 /// This class contains various state used when computing the lattice of a 120 /// callable operation. 121 class CallableLatticeState { 122 public: 123 /// Build a lattice state with a given callable region, and a specified number 124 /// of results to be initialized to the default lattice value (Unknown). 125 CallableLatticeState(Region *callableRegion, unsigned numResults) 126 : callableArguments(callableRegion->getArguments()), 127 resultLatticeValues(numResults) {} 128 129 /// Returns the arguments to the callable region. 130 Block::BlockArgListType getCallableArguments() const { 131 return callableArguments; 132 } 133 134 /// Returns the lattice value for the results of the callable region. 135 MutableArrayRef<LatticeValue> getResultLatticeValues() { 136 return resultLatticeValues; 137 } 138 139 /// Add a call to this callable. This is only used if the callable defines a 140 /// symbol. 141 void addSymbolCall(Operation *op) { symbolCalls.push_back(op); } 142 143 /// Return the calls that reference this callable. This is only used 144 /// if the callable defines a symbol. 145 ArrayRef<Operation *> getSymbolCalls() const { return symbolCalls; } 146 147 private: 148 /// The arguments of the callable region. 149 Block::BlockArgListType callableArguments; 150 151 /// The lattice state for each of the results of this region. The return 152 /// values of the callable aren't SSA values, so we need to track them 153 /// separately. 154 SmallVector<LatticeValue, 4> resultLatticeValues; 155 156 /// The calls referencing this callable if this callable defines a symbol. 157 /// This removes the need to recompute symbol references during propagation. 158 /// Value based references are trivial to resolve, so they can be done 159 /// in-place. 160 SmallVector<Operation *, 4> symbolCalls; 161 }; 162 163 /// This class represents the solver for the SCCP analysis. This class acts as 164 /// the propagation engine for computing which values form constants. 165 class SCCPSolver { 166 public: 167 /// Initialize the solver with the given top-level operation. 168 SCCPSolver(Operation *op); 169 170 /// Run the solver until it converges. 171 void solve(); 172 173 /// Rewrite the given regions using the computing analysis. This replaces the 174 /// uses of all values that have been computed to be constant, and erases as 175 /// many newly dead operations. 176 void rewrite(MLIRContext *context, MutableArrayRef<Region> regions); 177 178 private: 179 /// Initialize the set of symbol defining callables that can have their 180 /// arguments and results tracked. 'op' is the top-level operation that SCCP 181 /// is operating on. 182 void initializeSymbolCallables(Operation *op); 183 184 /// Replace the given value with a constant if the corresponding lattice 185 /// represents a constant. Returns success if the value was replaced, failure 186 /// otherwise. 187 LogicalResult replaceWithConstant(OpBuilder &builder, OperationFolder &folder, 188 Value value); 189 190 /// Visit the users of the given IR that reside within executable blocks. 191 template <typename T> 192 void visitUsers(T &value) { 193 for (Operation *user : value.getUsers()) 194 if (isBlockExecutable(user->getBlock())) 195 visitOperation(user); 196 } 197 198 /// Visit the given operation and compute any necessary lattice state. 199 void visitOperation(Operation *op); 200 201 /// Visit the given call operation and compute any necessary lattice state. 202 void visitCallOperation(CallOpInterface op); 203 204 /// Visit the given callable operation and compute any necessary lattice 205 /// state. 206 void visitCallableOperation(Operation *op); 207 208 /// Visit the given operation, which defines regions, and compute any 209 /// necessary lattice state. This also resolves the lattice state of both the 210 /// operation results and any nested regions. 211 void visitRegionOperation(Operation *op, 212 ArrayRef<Attribute> constantOperands); 213 214 /// Visit the given set of region successors, computing any necessary lattice 215 /// state. The provided function returns the input operands to the region at 216 /// the given index. If the index is 'None', the input operands correspond to 217 /// the parent operation results. 218 void visitRegionSuccessors( 219 Operation *parentOp, ArrayRef<RegionSuccessor> regionSuccessors, 220 function_ref<OperandRange(Optional<unsigned>)> getInputsForRegion); 221 222 /// Visit the given terminator operation and compute any necessary lattice 223 /// state. 224 void visitTerminatorOperation(Operation *op, 225 ArrayRef<Attribute> constantOperands); 226 227 /// Visit the given terminator operation that exits a callable region. These 228 /// are terminators with no CFG successors. 229 void visitCallableTerminatorOperation(Operation *callable, 230 Operation *terminator); 231 232 /// Visit the given block and compute any necessary lattice state. 233 void visitBlock(Block *block); 234 235 /// Visit argument #'i' of the given block and compute any necessary lattice 236 /// state. 237 void visitBlockArgument(Block *block, int i); 238 239 /// Mark the given block as executable. Returns false if the block was already 240 /// marked executable. 241 bool markBlockExecutable(Block *block); 242 243 /// Returns true if the given block is executable. 244 bool isBlockExecutable(Block *block) const; 245 246 /// Mark the edge between 'from' and 'to' as executable. 247 void markEdgeExecutable(Block *from, Block *to); 248 249 /// Return true if the edge between 'from' and 'to' is executable. 250 bool isEdgeExecutable(Block *from, Block *to) const; 251 252 /// Mark the given value as overdefined. This means that we cannot refine a 253 /// specific constant for this value. 254 void markOverdefined(Value value); 255 256 /// Mark all of the given values as overdefined. 257 template <typename ValuesT> 258 void markAllOverdefined(ValuesT values) { 259 for (auto value : values) 260 markOverdefined(value); 261 } 262 template <typename ValuesT> 263 void markAllOverdefined(Operation *op, ValuesT values) { 264 markAllOverdefined(values); 265 opWorklist.push_back(op); 266 } 267 template <typename ValuesT> 268 void markAllOverdefinedAndVisitUsers(ValuesT values) { 269 for (auto value : values) { 270 auto &lattice = latticeValues[value]; 271 if (!lattice.isOverdefined()) { 272 lattice.markOverdefined(); 273 visitUsers(value); 274 } 275 } 276 } 277 278 /// Returns true if the given value was marked as overdefined. 279 bool isOverdefined(Value value) const; 280 281 /// Merge in the given lattice 'from' into the lattice 'to'. 'owner' 282 /// corresponds to the parent operation of 'to'. 283 void meet(Operation *owner, LatticeValue &to, const LatticeValue &from); 284 285 /// The lattice for each SSA value. 286 DenseMap<Value, LatticeValue> latticeValues; 287 288 /// The set of blocks that are known to execute, or are intrinsically live. 289 SmallPtrSet<Block *, 16> executableBlocks; 290 291 /// The set of control flow edges that are known to execute. 292 DenseSet<std::pair<Block *, Block *>> executableEdges; 293 294 /// A worklist containing blocks that need to be processed. 295 SmallVector<Block *, 64> blockWorklist; 296 297 /// A worklist of operations that need to be processed. 298 SmallVector<Operation *, 64> opWorklist; 299 300 /// The callable operations that have their argument/result state tracked. 301 DenseMap<Operation *, CallableLatticeState> callableLatticeState; 302 303 /// A map between a call operation and the resolved symbol callable. This 304 /// avoids re-resolving symbol references during propagation. Value based 305 /// callables are trivial to resolve, so they can be done in-place. 306 DenseMap<Operation *, Operation *> callToSymbolCallable; 307 }; 308 } // end anonymous namespace 309 310 SCCPSolver::SCCPSolver(Operation *op) { 311 /// Initialize the solver with the regions within this operation. 312 for (Region ®ion : op->getRegions()) { 313 if (region.empty()) 314 continue; 315 Block *entryBlock = ®ion.front(); 316 317 // Mark the entry block as executable. 318 markBlockExecutable(entryBlock); 319 320 // The values passed to these regions are invisible, so mark any arguments 321 // as overdefined. 322 markAllOverdefined(entryBlock->getArguments()); 323 } 324 initializeSymbolCallables(op); 325 } 326 327 void SCCPSolver::solve() { 328 while (!blockWorklist.empty() || !opWorklist.empty()) { 329 // Process any operations in the op worklist. 330 while (!opWorklist.empty()) 331 visitUsers(*opWorklist.pop_back_val()); 332 333 // Process any blocks in the block worklist. 334 while (!blockWorklist.empty()) 335 visitBlock(blockWorklist.pop_back_val()); 336 } 337 } 338 339 void SCCPSolver::rewrite(MLIRContext *context, 340 MutableArrayRef<Region> initialRegions) { 341 SmallVector<Block *, 8> worklist; 342 auto addToWorklist = [&](MutableArrayRef<Region> regions) { 343 for (Region ®ion : regions) 344 for (Block &block : region) 345 if (isBlockExecutable(&block)) 346 worklist.push_back(&block); 347 }; 348 349 // An operation folder used to create and unique constants. 350 OperationFolder folder(context); 351 OpBuilder builder(context); 352 353 addToWorklist(initialRegions); 354 while (!worklist.empty()) { 355 Block *block = worklist.pop_back_val(); 356 357 // Replace any block arguments with constants. 358 builder.setInsertionPointToStart(block); 359 for (BlockArgument arg : block->getArguments()) 360 replaceWithConstant(builder, folder, arg); 361 362 for (Operation &op : llvm::make_early_inc_range(*block)) { 363 builder.setInsertionPoint(&op); 364 365 // Replace any result with constants. 366 bool replacedAll = op.getNumResults() != 0; 367 for (Value res : op.getResults()) 368 replacedAll &= succeeded(replaceWithConstant(builder, folder, res)); 369 370 // If all of the results of the operation were replaced, try to erase 371 // the operation completely. 372 if (replacedAll && wouldOpBeTriviallyDead(&op)) { 373 assert(op.use_empty() && "expected all uses to be replaced"); 374 op.erase(); 375 continue; 376 } 377 378 // Add any the regions of this operation to the worklist. 379 addToWorklist(op.getRegions()); 380 } 381 } 382 } 383 384 void SCCPSolver::initializeSymbolCallables(Operation *op) { 385 // Initialize the set of symbol callables that can have their state tracked. 386 // This tracks which symbol callable operations we can propagate within and 387 // out of. 388 auto walkFn = [&](Operation *symTable, bool allUsesVisible) { 389 Region &symbolTableRegion = symTable->getRegion(0); 390 Block *symbolTableBlock = &symbolTableRegion.front(); 391 for (auto callable : symbolTableBlock->getOps<CallableOpInterface>()) { 392 // We won't be able to track external callables. 393 Region *callableRegion = callable.getCallableRegion(); 394 if (!callableRegion) 395 continue; 396 // We only care about symbol defining callables here. 397 auto symbol = dyn_cast<SymbolOpInterface>(callable.getOperation()); 398 if (!symbol) 399 continue; 400 callableLatticeState.try_emplace(callable, callableRegion, 401 callable.getCallableResults().size()); 402 403 // If not all of the uses of this symbol are visible, we can't track the 404 // state of the arguments. 405 if (symbol.isPublic() || (!allUsesVisible && symbol.isNested())) 406 markAllOverdefined(callableRegion->getArguments()); 407 } 408 if (callableLatticeState.empty()) 409 return; 410 411 // After computing the valid callables, walk any symbol uses to check 412 // for non-call references. We won't be able to track the lattice state 413 // for arguments to these callables, as we can't guarantee that we can see 414 // all of its calls. 415 Optional<SymbolTable::UseRange> uses = 416 SymbolTable::getSymbolUses(&symbolTableRegion); 417 if (!uses) { 418 // If we couldn't gather the symbol uses, conservatively assume that 419 // we can't track information for any nested symbols. 420 op->walk([&](CallableOpInterface op) { callableLatticeState.erase(op); }); 421 return; 422 } 423 424 for (const SymbolTable::SymbolUse &use : *uses) { 425 // If the use is a call, track it to avoid the need to recompute the 426 // reference later. 427 if (auto callOp = dyn_cast<CallOpInterface>(use.getUser())) { 428 Operation *symCallable = callOp.resolveCallable(); 429 auto callableLatticeIt = callableLatticeState.find(symCallable); 430 if (callableLatticeIt != callableLatticeState.end()) { 431 callToSymbolCallable.try_emplace(callOp, symCallable); 432 433 // We only need to record the call in the lattice if it produces any 434 // values. 435 if (callOp.getOperation()->getNumResults()) 436 callableLatticeIt->second.addSymbolCall(callOp); 437 } 438 continue; 439 } 440 // This use isn't a call, so don't we know all of the callers. 441 auto *symbol = SymbolTable::lookupSymbolIn(op, use.getSymbolRef()); 442 auto it = callableLatticeState.find(symbol); 443 if (it != callableLatticeState.end()) 444 markAllOverdefined(it->second.getCallableArguments()); 445 } 446 }; 447 SymbolTable::walkSymbolTables(op, /*allSymUsesVisible=*/!op->getBlock(), 448 walkFn); 449 } 450 451 LogicalResult SCCPSolver::replaceWithConstant(OpBuilder &builder, 452 OperationFolder &folder, 453 Value value) { 454 auto it = latticeValues.find(value); 455 auto attr = it == latticeValues.end() ? nullptr : it->second.getConstant(); 456 if (!attr) 457 return failure(); 458 459 // Attempt to materialize a constant for the given value. 460 Dialect *dialect = it->second.getConstantDialect(); 461 Value constant = folder.getOrCreateConstant(builder, dialect, attr, 462 value.getType(), value.getLoc()); 463 if (!constant) 464 return failure(); 465 466 value.replaceAllUsesWith(constant); 467 latticeValues.erase(it); 468 return success(); 469 } 470 471 void SCCPSolver::visitOperation(Operation *op) { 472 // Collect all of the constant operands feeding into this operation. If any 473 // are not ready to be resolved, bail out and wait for them to resolve. 474 SmallVector<Attribute, 8> operandConstants; 475 operandConstants.reserve(op->getNumOperands()); 476 for (Value operand : op->getOperands()) { 477 // Make sure all of the operands are resolved first. 478 auto &operandLattice = latticeValues[operand]; 479 if (operandLattice.isUnknown()) 480 return; 481 operandConstants.push_back(operandLattice.getConstant()); 482 } 483 484 // If this is a terminator operation, process any control flow lattice state. 485 if (op->isKnownTerminator()) 486 visitTerminatorOperation(op, operandConstants); 487 488 // Process call operations. The call visitor processes result values, so we 489 // can exit afterwards. 490 if (CallOpInterface call = dyn_cast<CallOpInterface>(op)) 491 return visitCallOperation(call); 492 493 // Process callable operations. These are specially handled region operations 494 // that track dataflow via calls. 495 if (isa<CallableOpInterface>(op)) 496 return visitCallableOperation(op); 497 498 // Process region holding operations. The region visitor processes result 499 // values, so we can exit afterwards. 500 if (op->getNumRegions()) 501 return visitRegionOperation(op, operandConstants); 502 503 // If this op produces no results, it can't produce any constants. 504 if (op->getNumResults() == 0) 505 return; 506 507 // If all of the results of this operation are already overdefined, bail out 508 // early. 509 auto isOverdefinedFn = [&](Value value) { return isOverdefined(value); }; 510 if (llvm::all_of(op->getResults(), isOverdefinedFn)) 511 return; 512 513 // Save the original operands and attributes just in case the operation folds 514 // in-place. The constant passed in may not correspond to the real runtime 515 // value, so in-place updates are not allowed. 516 SmallVector<Value, 8> originalOperands(op->getOperands()); 517 MutableDictionaryAttr originalAttrs = op->getMutableAttrDict(); 518 519 // Simulate the result of folding this operation to a constant. If folding 520 // fails or was an in-place fold, mark the results as overdefined. 521 SmallVector<OpFoldResult, 8> foldResults; 522 foldResults.reserve(op->getNumResults()); 523 if (failed(op->fold(operandConstants, foldResults))) 524 return markAllOverdefined(op, op->getResults()); 525 526 // If the folding was in-place, mark the results as overdefined and reset the 527 // operation. We don't allow in-place folds as the desire here is for 528 // simulated execution, and not general folding. 529 if (foldResults.empty()) { 530 op->setOperands(originalOperands); 531 op->setAttrs(originalAttrs); 532 return markAllOverdefined(op, op->getResults()); 533 } 534 535 // Merge the fold results into the lattice for this operation. 536 assert(foldResults.size() == op->getNumResults() && "invalid result size"); 537 Dialect *opDialect = op->getDialect(); 538 for (unsigned i = 0, e = foldResults.size(); i != e; ++i) { 539 LatticeValue &resultLattice = latticeValues[op->getResult(i)]; 540 541 // Merge in the result of the fold, either a constant or a value. 542 OpFoldResult foldResult = foldResults[i]; 543 if (Attribute foldAttr = foldResult.dyn_cast<Attribute>()) 544 meet(op, resultLattice, LatticeValue(foldAttr, opDialect)); 545 else 546 meet(op, resultLattice, latticeValues[foldResult.get<Value>()]); 547 } 548 } 549 550 void SCCPSolver::visitCallableOperation(Operation *op) { 551 // Mark the regions as executable. 552 bool isTrackingLatticeState = callableLatticeState.count(op); 553 for (Region ®ion : op->getRegions()) { 554 if (region.empty()) 555 continue; 556 Block *entryBlock = ®ion.front(); 557 markBlockExecutable(entryBlock); 558 559 // If we aren't tracking lattice state for this callable, mark all of the 560 // region arguments as overdefined. 561 if (!isTrackingLatticeState) 562 markAllOverdefined(entryBlock->getArguments()); 563 } 564 565 // TODO: Add support for non-symbol callables when necessary. If the callable 566 // has non-call uses we would mark overdefined, otherwise allow for 567 // propagating the return values out. 568 markAllOverdefined(op, op->getResults()); 569 } 570 571 void SCCPSolver::visitCallOperation(CallOpInterface op) { 572 ResultRange callResults = op.getOperation()->getResults(); 573 574 // Resolve the callable operation for this call. 575 Operation *callableOp = nullptr; 576 if (Value callableValue = op.getCallableForCallee().dyn_cast<Value>()) 577 callableOp = callableValue.getDefiningOp(); 578 else 579 callableOp = callToSymbolCallable.lookup(op); 580 581 // The callable of this call can't be resolved, mark any results overdefined. 582 if (!callableOp) 583 return markAllOverdefined(op, callResults); 584 585 // If this callable is tracking state, merge the argument operands with the 586 // arguments of the callable. 587 auto callableLatticeIt = callableLatticeState.find(callableOp); 588 if (callableLatticeIt == callableLatticeState.end()) 589 return markAllOverdefined(op, callResults); 590 591 OperandRange callOperands = op.getArgOperands(); 592 auto callableArgs = callableLatticeIt->second.getCallableArguments(); 593 for (auto it : llvm::zip(callOperands, callableArgs)) { 594 BlockArgument callableArg = std::get<1>(it); 595 if (latticeValues[callableArg].meet(latticeValues[std::get<0>(it)])) 596 visitUsers(callableArg); 597 } 598 599 // Merge in the lattice state for the callable results as well. 600 auto callableResults = callableLatticeIt->second.getResultLatticeValues(); 601 for (auto it : llvm::zip(callResults, callableResults)) 602 meet(/*owner=*/op, /*to=*/latticeValues[std::get<0>(it)], 603 /*from=*/std::get<1>(it)); 604 } 605 606 void SCCPSolver::visitRegionOperation(Operation *op, 607 ArrayRef<Attribute> constantOperands) { 608 // Check to see if we can reason about the internal control flow of this 609 // region operation. 610 auto regionInterface = dyn_cast<RegionBranchOpInterface>(op); 611 if (!regionInterface) { 612 // If we can't, conservatively mark all regions as executable. 613 for (Region ®ion : op->getRegions()) { 614 if (region.empty()) 615 continue; 616 Block *entryBlock = ®ion.front(); 617 markBlockExecutable(entryBlock); 618 markAllOverdefined(entryBlock->getArguments()); 619 } 620 621 // Don't try to simulate the results of a region operation as we can't 622 // guarantee that folding will be out-of-place. We don't allow in-place 623 // folds as the desire here is for simulated execution, and not general 624 // folding. 625 return markAllOverdefined(op, op->getResults()); 626 } 627 628 // Check to see which regions are executable. 629 SmallVector<RegionSuccessor, 1> successors; 630 regionInterface.getSuccessorRegions(/*index=*/llvm::None, constantOperands, 631 successors); 632 633 // If the interface identified that no region will be executed. Mark 634 // any results of this operation as overdefined, as we can't reason about 635 // them. 636 // TODO: If we had an interface to detect pass through operands, we could 637 // resolve some results based on the lattice state of the operands. We could 638 // also allow for the parent operation to have itself as a region successor. 639 if (successors.empty()) 640 return markAllOverdefined(op, op->getResults()); 641 return visitRegionSuccessors(op, successors, [&](Optional<unsigned> index) { 642 assert(index && "expected valid region index"); 643 return regionInterface.getSuccessorEntryOperands(*index); 644 }); 645 } 646 647 void SCCPSolver::visitRegionSuccessors( 648 Operation *parentOp, ArrayRef<RegionSuccessor> regionSuccessors, 649 function_ref<OperandRange(Optional<unsigned>)> getInputsForRegion) { 650 for (const RegionSuccessor &it : regionSuccessors) { 651 Region *region = it.getSuccessor(); 652 ValueRange succArgs = it.getSuccessorInputs(); 653 654 // Check to see if this is the parent operation. 655 if (!region) { 656 ResultRange results = parentOp->getResults(); 657 if (llvm::all_of(results, [&](Value res) { return isOverdefined(res); })) 658 continue; 659 660 // Mark the results outside of the input range as overdefined. 661 if (succArgs.size() != results.size()) { 662 opWorklist.push_back(parentOp); 663 if (succArgs.empty()) 664 return markAllOverdefined(results); 665 666 unsigned firstResIdx = succArgs[0].cast<OpResult>().getResultNumber(); 667 markAllOverdefined(results.take_front(firstResIdx)); 668 markAllOverdefined(results.drop_front(firstResIdx + succArgs.size())); 669 } 670 671 // Update the lattice for any operation results. 672 OperandRange operands = getInputsForRegion(/*index=*/llvm::None); 673 for (auto it : llvm::zip(succArgs, operands)) 674 meet(parentOp, latticeValues[std::get<0>(it)], 675 latticeValues[std::get<1>(it)]); 676 return; 677 } 678 assert(!region->empty() && "expected region to be non-empty"); 679 Block *entryBlock = ®ion->front(); 680 markBlockExecutable(entryBlock); 681 682 // If all of the arguments are already overdefined, the arguments have 683 // already been fully resolved. 684 auto arguments = entryBlock->getArguments(); 685 if (llvm::all_of(arguments, [&](Value arg) { return isOverdefined(arg); })) 686 continue; 687 688 // Mark any arguments that do not receive inputs as overdefined, we won't be 689 // able to discern if they are constant. 690 if (succArgs.size() != arguments.size()) { 691 if (succArgs.empty()) { 692 markAllOverdefined(arguments); 693 continue; 694 } 695 696 unsigned firstArgIdx = succArgs[0].cast<BlockArgument>().getArgNumber(); 697 markAllOverdefinedAndVisitUsers(arguments.take_front(firstArgIdx)); 698 markAllOverdefinedAndVisitUsers( 699 arguments.drop_front(firstArgIdx + succArgs.size())); 700 } 701 702 // Update the lattice for arguments that have inputs from the predecessor. 703 OperandRange succOperands = getInputsForRegion(region->getRegionNumber()); 704 for (auto it : llvm::zip(succArgs, succOperands)) { 705 LatticeValue &argLattice = latticeValues[std::get<0>(it)]; 706 if (argLattice.meet(latticeValues[std::get<1>(it)])) 707 visitUsers(std::get<0>(it)); 708 } 709 } 710 } 711 712 void SCCPSolver::visitTerminatorOperation( 713 Operation *op, ArrayRef<Attribute> constantOperands) { 714 // If this operation has no successors, we treat it as an exiting terminator. 715 if (op->getNumSuccessors() == 0) { 716 Region *parentRegion = op->getParentRegion(); 717 Operation *parentOp = parentRegion->getParentOp(); 718 719 // Check to see if this is a terminator for a callable region. 720 if (isa<CallableOpInterface>(parentOp)) 721 return visitCallableTerminatorOperation(parentOp, op); 722 723 // Otherwise, check to see if the parent tracks region control flow. 724 auto regionInterface = dyn_cast<RegionBranchOpInterface>(parentOp); 725 if (!regionInterface || !isBlockExecutable(parentOp->getBlock())) 726 return; 727 728 // Query the set of successors from the current region. 729 SmallVector<RegionSuccessor, 1> regionSuccessors; 730 regionInterface.getSuccessorRegions(parentRegion->getRegionNumber(), 731 constantOperands, regionSuccessors); 732 if (regionSuccessors.empty()) 733 return; 734 735 // If this terminator is not "region-like", conservatively mark all of the 736 // successor values as overdefined. 737 if (!op->hasTrait<OpTrait::ReturnLike>()) { 738 for (auto &it : regionSuccessors) 739 markAllOverdefinedAndVisitUsers(it.getSuccessorInputs()); 740 return; 741 } 742 743 // Otherwise, propagate the operand lattice states to each of the 744 // successors. 745 OperandRange operands = op->getOperands(); 746 return visitRegionSuccessors(parentOp, regionSuccessors, 747 [&](Optional<unsigned>) { return operands; }); 748 } 749 750 // Try to resolve to a specific successor with the constant operands. 751 if (auto branch = dyn_cast<BranchOpInterface>(op)) { 752 if (Block *singleSucc = branch.getSuccessorForOperands(constantOperands)) { 753 markEdgeExecutable(op->getBlock(), singleSucc); 754 return; 755 } 756 } 757 758 // Otherwise, conservatively treat all edges as executable. 759 Block *block = op->getBlock(); 760 for (Block *succ : op->getSuccessors()) 761 markEdgeExecutable(block, succ); 762 } 763 764 void SCCPSolver::visitCallableTerminatorOperation(Operation *callable, 765 Operation *terminator) { 766 // If there are no exiting values, we have nothing to track. 767 if (terminator->getNumOperands() == 0) 768 return; 769 770 // If this callable isn't tracking any lattice state there is nothing to do. 771 auto latticeIt = callableLatticeState.find(callable); 772 if (latticeIt == callableLatticeState.end()) 773 return; 774 assert(callable->getNumResults() == 0 && "expected symbol callable"); 775 776 // If this terminator is not "return-like", conservatively mark all of the 777 // call-site results as overdefined. 778 auto callableResultLattices = latticeIt->second.getResultLatticeValues(); 779 if (!terminator->hasTrait<OpTrait::ReturnLike>()) { 780 for (auto &it : callableResultLattices) 781 it.markOverdefined(); 782 for (Operation *call : latticeIt->second.getSymbolCalls()) 783 markAllOverdefined(call, call->getResults()); 784 return; 785 } 786 787 // Merge the terminator operands into the results. 788 bool anyChanged = false; 789 for (auto it : llvm::zip(terminator->getOperands(), callableResultLattices)) 790 anyChanged |= std::get<1>(it).meet(latticeValues[std::get<0>(it)]); 791 if (!anyChanged) 792 return; 793 794 // If any of the result lattices changed, update the callers. 795 for (Operation *call : latticeIt->second.getSymbolCalls()) 796 for (auto it : llvm::zip(call->getResults(), callableResultLattices)) 797 meet(call, latticeValues[std::get<0>(it)], std::get<1>(it)); 798 } 799 800 void SCCPSolver::visitBlock(Block *block) { 801 // If the block is not the entry block we need to compute the lattice state 802 // for the block arguments. Entry block argument lattices are computed 803 // elsewhere, such as when visiting the parent operation. 804 if (!block->isEntryBlock()) { 805 for (int i : llvm::seq<int>(0, block->getNumArguments())) 806 visitBlockArgument(block, i); 807 } 808 809 // Visit all of the operations within the block. 810 for (Operation &op : *block) 811 visitOperation(&op); 812 } 813 814 void SCCPSolver::visitBlockArgument(Block *block, int i) { 815 BlockArgument arg = block->getArgument(i); 816 LatticeValue &argLattice = latticeValues[arg]; 817 if (argLattice.isOverdefined()) 818 return; 819 820 bool updatedLattice = false; 821 for (auto it = block->pred_begin(), e = block->pred_end(); it != e; ++it) { 822 Block *pred = *it; 823 824 // We only care about this predecessor if it is going to execute. 825 if (!isEdgeExecutable(pred, block)) 826 continue; 827 828 // Try to get the operand forwarded by the predecessor. If we can't reason 829 // about the terminator of the predecessor, mark overdefined. 830 Optional<OperandRange> branchOperands; 831 if (auto branch = dyn_cast<BranchOpInterface>(pred->getTerminator())) 832 branchOperands = branch.getSuccessorOperands(it.getSuccessorIndex()); 833 if (!branchOperands) { 834 updatedLattice = true; 835 argLattice.markOverdefined(); 836 break; 837 } 838 839 // If the operand hasn't been resolved, it is unknown which can merge with 840 // anything. 841 auto operandLattice = latticeValues.find((*branchOperands)[i]); 842 if (operandLattice == latticeValues.end()) 843 continue; 844 845 // Otherwise, meet the two lattice values. 846 updatedLattice |= argLattice.meet(operandLattice->second); 847 if (argLattice.isOverdefined()) 848 break; 849 } 850 851 // If the lattice was updated, visit any executable users of the argument. 852 if (updatedLattice) 853 visitUsers(arg); 854 } 855 856 bool SCCPSolver::markBlockExecutable(Block *block) { 857 bool marked = executableBlocks.insert(block).second; 858 if (marked) 859 blockWorklist.push_back(block); 860 return marked; 861 } 862 863 bool SCCPSolver::isBlockExecutable(Block *block) const { 864 return executableBlocks.count(block); 865 } 866 867 void SCCPSolver::markEdgeExecutable(Block *from, Block *to) { 868 if (!executableEdges.insert(std::make_pair(from, to)).second) 869 return; 870 // Mark the destination as executable, and reprocess its arguments if it was 871 // already executable. 872 if (!markBlockExecutable(to)) { 873 for (int i : llvm::seq<int>(0, to->getNumArguments())) 874 visitBlockArgument(to, i); 875 } 876 } 877 878 bool SCCPSolver::isEdgeExecutable(Block *from, Block *to) const { 879 return executableEdges.count(std::make_pair(from, to)); 880 } 881 882 void SCCPSolver::markOverdefined(Value value) { 883 latticeValues[value].markOverdefined(); 884 } 885 886 bool SCCPSolver::isOverdefined(Value value) const { 887 auto it = latticeValues.find(value); 888 return it != latticeValues.end() && it->second.isOverdefined(); 889 } 890 891 void SCCPSolver::meet(Operation *owner, LatticeValue &to, 892 const LatticeValue &from) { 893 if (to.meet(from)) 894 opWorklist.push_back(owner); 895 } 896 897 //===----------------------------------------------------------------------===// 898 // SCCP Pass 899 //===----------------------------------------------------------------------===// 900 901 namespace { 902 struct SCCP : public SCCPBase<SCCP> { 903 void runOnOperation() override; 904 }; 905 } // end anonymous namespace 906 907 void SCCP::runOnOperation() { 908 Operation *op = getOperation(); 909 910 // Solve for SCCP constraints within nested regions. 911 SCCPSolver solver(op); 912 solver.solve(); 913 914 // Cleanup any operations using the solver analysis. 915 solver.rewrite(&getContext(), op->getRegions()); 916 } 917 918 std::unique_ptr<Pass> mlir::createSCCPPass() { 919 return std::make_unique<SCCP>(); 920 } 921