20#include "llvm/Support/Debug.h"
21#include "llvm/Support/DebugLog.h"
22#include "llvm/Support/raw_ostream.h"
25#define DEBUG_TYPE "inlining"
39 while (
auto nextCallSite = dyn_cast<CallSiteLoc>(lastCallee)) {
40 calleeInliningStack.push_back(nextCallSite);
41 lastCallee = nextCallSite.getCaller();
44 CallSiteLoc firstCallSite = CallSiteLoc::get(lastCallee, caller);
45 for (CallSiteLoc currentCallSite : reverse(calleeInliningStack))
47 CallSiteLoc::get(currentCallSite.getCallee(), firstCallSite);
59 auto [it,
inserted] = mappedLocations.try_emplace(loc);
63 it->getSecond() = newLoc;
70 [&](
LocationAttr loc) -> std::pair<LocationAttr, WalkResult> {
74 for (
Block &block : inlinedBlocks) {
88 for (
auto &operand : op->getOpOperands())
90 operand.set(mappedOp);
92 for (
auto &block : inlinedBlocks)
93 block.walk(remapOperands);
101 bool wouldBeCloned)
const {
103 return handler->isLegalToInline(call, callable, wouldBeCloned);
111 return handler->isLegalToInline(dest, src, wouldBeCloned, valueMapping);
119 return handler->isLegalToInline(op, dest, wouldBeCloned, valueMapping);
125 return handler ? handler->shouldAnalyzeRecursively(op) :
true;
132 assert(handler &&
"expected valid dialect handler");
133 handler->handleTerminator(op, newDest);
141 assert(handler &&
"expected valid dialect handler");
142 handler->handleTerminator(op, valuesToRepl);
152 assert(handler &&
"expected valid dialect handler");
153 return handler->allowSingleBlockOptimization(inlinedBlock);
158 DictionaryAttr argumentAttrs)
const {
160 assert(handler &&
"expected valid dialect handler");
161 return handler->handleArgument(builder, call, callable, argument,
167 DictionaryAttr resultAttrs)
const {
169 assert(handler &&
"expected valid dialect handler");
170 return handler->handleResult(builder, call, callable,
result, resultAttrs);
176 assert(handler &&
"expected valid dialect handler");
177 handler->processInlinedCallBlocks(call, inlinedBlocks);
182 Region *insertRegion,
bool shouldCloneInlinedRegion,
184 for (
auto &block : *src) {
185 for (
auto &op : block) {
188 if (isa<UnrealizedConversionCastOp>(op))
193 shouldCloneInlinedRegion, valueMapping)) {
194 LDBG() <<
"* Illegal to inline because of op: "
200 llvm::any_of(op.getRegions(), [&](
Region ®ion) {
201 return !isLegalToInline(interface, ®ion, insertRegion,
202 shouldCloneInlinedRegion, valueMapping);
215 CallOpInterface call,
216 CallableOpInterface callable,
220 callable.getCallableRegion()->getNumArguments(),
222 if (
ArrayAttr arrayAttr = callable.getArgAttrsAttr()) {
223 assert(arrayAttr.size() == argAttrs.size());
224 for (
auto [idx, attr] : llvm::enumerate(arrayAttr))
225 argAttrs[idx] = cast<DictionaryAttr>(attr);
229 for (
auto [blockArg, argAttr] :
230 llvm::zip(callable.getCallableRegion()->getArguments(), argAttrs)) {
232 builder, call, callable, mapper.
lookup(blockArg), argAttr);
233 assert(newArgument.
getType() == mapper.
lookup(blockArg).getType() &&
234 "expected the argument type to not change");
237 mapper.
map(blockArg, newArgument);
242 CallOpInterface call, CallableOpInterface callable,
247 if (
ArrayAttr arrayAttr = callable.getResAttrsAttr()) {
248 assert(arrayAttr.size() == resAttrs.size());
249 for (
auto [idx, attr] : llvm::enumerate(arrayAttr))
250 resAttrs[idx] = cast<DictionaryAttr>(attr);
254 for (
auto [
result, resAttr] : llvm::zip(results, resAttrs)) {
261 "expected the result type to not change");
265 return resultUsers.count(operand.
getOwner());
275 std::optional<Location> inlineLoc,
bool shouldCloneInlinedRegion,
276 CallOpInterface call = {}) {
277 assert(resultsToReplace.size() == regionResultTypes.size());
283 auto *srcEntryBlock = &src->
front();
284 if (llvm::any_of(srcEntryBlock->getArguments(),
290 if (!interface.
isLegalToInline(insertRegion, src, shouldCloneInlinedRegion,
292 !
isLegalToInline(interface, src, insertRegion, shouldCloneInlinedRegion,
297 OpBuilder builder(inlineBlock, inlinePoint);
298 auto callable = dyn_cast<CallableOpInterface>(src->
getParentOp());
299 if (call && callable)
304 cloneCallback(builder, src, inlineBlock, postInsertBlock, mapper,
305 shouldCloneInlinedRegion);
308 auto newBlocks = llvm::make_range(std::next(inlineBlock->getIterator()),
309 postInsertBlock->getIterator());
314 if (inlineLoc && !llvm::isa<UnknownLoc>(*inlineLoc))
319 if (!shouldCloneInlinedRegion)
328 if (llvm::hasSingleElement(newBlocks) &&
332 builder.setInsertionPoint(firstBlockTerminator);
333 if (call && callable)
339 firstBlockTerminator->
erase();
344 postInsertBlock->
erase();
348 for (
const auto &resultToRepl : llvm::enumerate(resultsToReplace)) {
349 resultToRepl.value().replaceAllUsesWith(
350 postInsertBlock->
addArgument(regionResultTypes[resultToRepl.index()],
351 resultToRepl.value().getLoc()));
355 builder.setInsertionPointToStart(postInsertBlock);
356 if (call && callable)
361 for (
auto &newBlock : newBlocks)
368 firstNewBlock->
erase();
377 std::optional<Location> inlineLoc,
bool shouldCloneInlinedRegion,
378 CallOpInterface call = {}) {
383 auto *entryBlock = &src->
front();
384 if (inlinedOperands.size() != entryBlock->getNumArguments())
389 for (
unsigned i = 0, e = inlinedOperands.size(); i != e; ++i) {
395 mapper.
map(regionArg, inlinedOperands[i]);
400 inlinePoint, mapper, resultsToReplace,
401 resultsToReplace.
getTypes(), inlineLoc,
402 shouldCloneInlinedRegion, call);
410 std::optional<Location> inlineLoc,
bool shouldCloneInlinedRegion) {
412 ++inlinePoint->getIterator(), mapper, resultsToReplace,
413 regionResultTypes, inlineLoc, shouldCloneInlinedRegion);
421 std::optional<Location> inlineLoc,
bool shouldCloneInlinedRegion) {
423 interface, cloneCallback, src, inlineBlock, inlinePoint, mapper,
424 resultsToReplace, regionResultTypes, inlineLoc, shouldCloneInlinedRegion);
431 ValueRange resultsToReplace, std::optional<Location> inlineLoc,
432 bool shouldCloneInlinedRegion) {
434 ++inlinePoint->getIterator(), inlinedOperands,
435 resultsToReplace, inlineLoc, shouldCloneInlinedRegion);
443 std::optional<Location> inlineLoc,
bool shouldCloneInlinedRegion) {
445 inlinePoint, inlinedOperands, resultsToReplace,
446 inlineLoc, shouldCloneInlinedRegion);
459 Operation *castOp = interface->materializeCallConversion(castBuilder, arg,
460 type, conversionLoc);
463 castOps.push_back(castOp);
480 CallOpInterface call, CallableOpInterface callable,
Region *src,
481 bool shouldCloneInlinedRegion) {
485 auto *entryBlock = &src->
front();
491 if (call.getForwardedResults().size() != call->getNumResults())
498 if (callOperands.size() != entryBlock->getNumArguments() ||
499 callResults.size() != callableResultTypes.size())
505 castOps.reserve(callOperands.size() + callResults.size());
508 auto cleanupState = [&] {
509 for (
auto *op : castOps) {
510 op->getResult(0).replaceAllUsesWith(op->getOperand(0));
519 const auto *callInterface = interface.
getInterfaceFor(call->getDialect());
523 for (
unsigned i = 0, e = callOperands.size(); i != e; ++i) {
525 Value operand = callOperands[i];
530 if (operand.
getType() != regionArgType) {
532 operand, regionArgType, castLoc)))
533 return cleanupState();
535 mapper.
map(regionArg, operand);
540 for (
unsigned i = 0, e = callResults.size(); i != e; ++i) {
541 Value callResult = callResults[i];
542 if (callResult.
getType() == callableResultTypes[i])
549 callResult.
getType(), castLoc);
551 return cleanupState();
557 if (!interface.
isLegalToInline(call, callable, shouldCloneInlinedRegion))
558 return cleanupState();
561 if (failed(
inlineRegionImpl(interface, cloneCallback, src, call->getBlock(),
562 ++call->getIterator(), mapper, callResults,
563 callableResultTypes, call.getLoc(),
564 shouldCloneInlinedRegion, call)))
565 return cleanupState();
static void remapInlinedOperands(iterator_range< Region::iterator > inlinedBlocks, IRMapping &mapper)
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
static void handleResultImpl(InlinerInterface &interface, OpBuilder &builder, CallOpInterface call, CallableOpInterface callable, ValueRange results)
static LocationAttr stackLocations(Location callee, Location caller)
Combine callee location with caller location to create a stack that represents the call chain.
static LogicalResult inlineRegionImpl(InlinerInterface &interface, function_ref< InlinerInterface::CloneCallbackSigTy > cloneCallback, Region *src, Block *inlineBlock, Block::iterator inlinePoint, IRMapping &mapper, ValueRange resultsToReplace, TypeRange regionResultTypes, std::optional< Location > inlineLoc, bool shouldCloneInlinedRegion, CallOpInterface call={})
static Value materializeConversion(const DialectInlinerInterface *interface, SmallVectorImpl< Operation * > &castOps, OpBuilder &castBuilder, Value arg, Type type, Location conversionLoc)
Utility function used to generate a cast operation from the given interface, or return nullptr if a c...
static void remapInlinedLocations(iterator_range< Region::iterator > inlinedBlocks, Location callerLoc)
Remap all locations reachable from the inlined blocks with CallSiteLoc locations with the provided ca...
static void handleArgumentImpl(InlinerInterface &interface, OpBuilder &builder, CallOpInterface call, CallableOpInterface callable, IRMapping &mapper)
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
This is an attribute/type replacer that is naively cached.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
OpListType::iterator iterator
void erase()
Unlink this Block from its parent region and delete it.
Block * splitBlock(iterator splitBefore)
Split the block into two blocks before the specified operation or iterator.
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
OpListType & getOperations()
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
BlockArgListType getArguments()
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
const DialectInlinerInterface * getInterfaceFor(Object *obj) const
This is a utility class for mapping one set of IR entities to another.
auto lookup(T from) const
Lookup a mapped value within the map.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
This interface provides the hooks into the inlining interface.
virtual Value handleResult(OpBuilder &builder, Operation *call, Operation *callable, Value result, DictionaryAttr resultAttrs) const
virtual Value handleArgument(OpBuilder &builder, Operation *call, Operation *callable, Value argument, DictionaryAttr argumentAttrs) const
virtual bool shouldAnalyzeRecursively(Operation *op) const
virtual bool allowSingleBlockOptimization(Block *inlinedBlock) const
Returns true if the inliner can use the fast path for the given inlined block.
virtual void handleTerminator(Operation *op, Block *newDest) const
Handle the given inlined terminator by replacing it with a new operation as necessary.
virtual void processInlinedCallBlocks(Operation *call, iterator_range< Region::iterator > inlinedBlocks) const
virtual void processInlinedBlocks(iterator_range< Region::iterator > inlinedBlocks)
Process a set of blocks that have been inlined.
virtual bool isLegalToInline(Operation *call, Operation *callable, bool wouldBeCloned) const
These hooks mirror the hooks for the DialectInlinerInterface, with default implementations that call ...
Location objects represent source locations information in MLIR.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
This class represents an operand of an operation.
Set of flags used to control the behavior of the various IR print methods (e.g.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Operation is the basic unit of execution within MLIR.
void replaceUsesOfWith(Value from, Value to)
Replace any uses of 'from' with 'to' within this operation.
Value getOperand(unsigned idx)
Block * getBlock()
Returns the operation block that contains this operation.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
unsigned getNumOperands()
result_type_iterator result_type_begin()
operand_range getOperands()
Returns an iterator on the underlying Value's.
void erase()
Remove this operation from its parent block and delete it.
unsigned getNumResults()
Return the number of results held by this operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Operation * getParentOp()
Return the parent operation this region is attached to.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
type_range getTypes() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
void replaceAllUsesWith(Value newValue)
Replace all uses of 'this' value with the new value, updating anything in the IR that uses 'this' to ...
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
void recursivelyReplaceElementsIn(Operation *op, bool replaceAttrs=true, bool replaceLocs=false, bool replaceTypes=false)
Replace the elements within the given operation, and all nested operations.
void addReplacement(ReplaceFn< Attribute > fn)
AttrTypeReplacerBase.
Operation * getOwner() const
Return the owner of this operand.
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
LogicalResult inlineCall(InlinerInterface &interface, function_ref< InlinerInterface::CloneCallbackSigTy > cloneCallback, CallOpInterface call, CallableOpInterface callable, Region *src, bool shouldCloneInlinedRegion=true)
This function inlines a given region, 'src', of a callable operation, 'callable', into the location d...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
LogicalResult inlineRegion(InlinerInterface &interface, function_ref< InlinerInterface::CloneCallbackSigTy > cloneCallback, Region *src, Operation *inlinePoint, IRMapping &mapper, ValueRange resultsToReplace, TypeRange regionResultTypes, std::optional< Location > inlineLoc=std::nullopt, bool shouldCloneInlinedRegion=true)
This function inlines a region, 'src', into another.
llvm::function_ref< Fn > function_ref