MLIR  21.0.0git
InliningUtils.cpp
Go to the documentation of this file.
1 //===- InliningUtils.cpp ---- Misc utilities for inlining -----------------===//
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 file implements miscellaneous inlining utilities.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 
15 #include "mlir/IR/Builders.h"
16 #include "mlir/IR/IRMapping.h"
17 #include "mlir/IR/Operation.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <optional>
23 
24 #define DEBUG_TYPE "inlining"
25 
26 using namespace mlir;
27 
28 /// Combine `callee` location with `caller` location to create a stack that
29 /// represents the call chain.
30 /// If `callee` location is a `CallSiteLoc`, indicating an existing stack of
31 /// locations, the `caller` location is appended to the end of it, extending
32 /// the chain.
33 /// Otherwise, a single `CallSiteLoc` is created, representing a direct call
34 /// from `caller` to `callee`.
35 static LocationAttr stackLocations(Location callee, Location caller) {
36  Location lastCallee = callee;
37  SmallVector<CallSiteLoc> calleeInliningStack;
38  while (auto nextCallSite = dyn_cast<CallSiteLoc>(lastCallee)) {
39  calleeInliningStack.push_back(nextCallSite);
40  lastCallee = nextCallSite.getCaller();
41  }
42 
43  CallSiteLoc firstCallSite = CallSiteLoc::get(lastCallee, caller);
44  for (CallSiteLoc currentCallSite : reverse(calleeInliningStack))
45  firstCallSite =
46  CallSiteLoc::get(currentCallSite.getCallee(), firstCallSite);
47 
48  return firstCallSite;
49 }
50 
51 /// Remap all locations reachable from the inlined blocks with CallSiteLoc
52 /// locations with the provided caller location.
53 static void
55  Location callerLoc) {
56  DenseMap<Location, LocationAttr> mappedLocations;
57  auto remapLoc = [&](Location loc) {
58  auto [it, inserted] = mappedLocations.try_emplace(loc);
59  // Only query the attribute uniquer once per callsite attribute.
60  if (inserted) {
61  LocationAttr newLoc = stackLocations(loc, callerLoc);
62  it->getSecond() = newLoc;
63  }
64  return it->second;
65  };
66 
67  AttrTypeReplacer attrReplacer;
68  attrReplacer.addReplacement(
69  [&](LocationAttr loc) -> std::pair<LocationAttr, WalkResult> {
70  return {remapLoc(loc), WalkResult::skip()};
71  });
72 
73  for (Block &block : inlinedBlocks) {
74  for (BlockArgument &arg : block.getArguments())
75  if (LocationAttr newLoc = remapLoc(arg.getLoc()))
76  arg.setLoc(newLoc);
77 
78  for (Operation &op : block)
79  attrReplacer.recursivelyReplaceElementsIn(&op, /*replaceAttrs=*/false,
80  /*replaceLocs=*/true);
81  }
82 }
83 
85  IRMapping &mapper) {
86  auto remapOperands = [&](Operation *op) {
87  for (auto &operand : op->getOpOperands())
88  if (auto mappedOp = mapper.lookupOrNull(operand.get()))
89  operand.set(mappedOp);
90  };
91  for (auto &block : inlinedBlocks)
92  block.walk(remapOperands);
93 }
94 
95 //===----------------------------------------------------------------------===//
96 // InlinerInterface
97 //===----------------------------------------------------------------------===//
98 
100  bool wouldBeCloned) const {
101  if (auto *handler = getInterfaceFor(call))
102  return handler->isLegalToInline(call, callable, wouldBeCloned);
103  return false;
104 }
105 
107  bool wouldBeCloned,
108  IRMapping &valueMapping) const {
109  if (auto *handler = getInterfaceFor(dest->getParentOp()))
110  return handler->isLegalToInline(dest, src, wouldBeCloned, valueMapping);
111  return false;
112 }
113 
115  bool wouldBeCloned,
116  IRMapping &valueMapping) const {
117  if (auto *handler = getInterfaceFor(op))
118  return handler->isLegalToInline(op, dest, wouldBeCloned, valueMapping);
119  return false;
120 }
121 
123  auto *handler = getInterfaceFor(op);
124  return handler ? handler->shouldAnalyzeRecursively(op) : true;
125 }
126 
127 /// Handle the given inlined terminator by replacing it with a new operation
128 /// as necessary.
130  auto *handler = getInterfaceFor(op);
131  assert(handler && "expected valid dialect handler");
132  handler->handleTerminator(op, newDest);
133 }
134 
135 /// Handle the given inlined terminator by replacing it with a new operation
136 /// as necessary.
138  ValueRange valuesToRepl) const {
139  auto *handler = getInterfaceFor(op);
140  assert(handler && "expected valid dialect handler");
141  handler->handleTerminator(op, valuesToRepl);
142 }
143 
144 /// Returns true if the inliner can assume a fast path of not creating a
145 /// new block, if there is only one block.
147  iterator_range<Region::iterator> inlinedBlocks) const {
148  if (inlinedBlocks.empty()) {
149  return true;
150  }
151  auto *handler = getInterfaceFor(inlinedBlocks.begin()->getParentOp());
152  assert(handler && "expected valid dialect handler");
153  return handler->allowSingleBlockOptimization(inlinedBlocks);
154 }
155 
157  Operation *callable, Value argument,
158  DictionaryAttr argumentAttrs) const {
159  auto *handler = getInterfaceFor(callable);
160  assert(handler && "expected valid dialect handler");
161  return handler->handleArgument(builder, call, callable, argument,
162  argumentAttrs);
163 }
164 
166  Operation *callable, Value result,
167  DictionaryAttr resultAttrs) const {
168  auto *handler = getInterfaceFor(callable);
169  assert(handler && "expected valid dialect handler");
170  return handler->handleResult(builder, call, callable, result, resultAttrs);
171 }
172 
174  Operation *call, iterator_range<Region::iterator> inlinedBlocks) const {
175  auto *handler = getInterfaceFor(call);
176  assert(handler && "expected valid dialect handler");
177  handler->processInlinedCallBlocks(call, inlinedBlocks);
178 }
179 
180 /// Utility to check that all of the operations within 'src' can be inlined.
181 static bool isLegalToInline(InlinerInterface &interface, Region *src,
182  Region *insertRegion, bool shouldCloneInlinedRegion,
183  IRMapping &valueMapping) {
184  for (auto &block : *src) {
185  for (auto &op : block) {
186  // Check this operation.
187  if (!interface.isLegalToInline(&op, insertRegion,
188  shouldCloneInlinedRegion, valueMapping)) {
189  LLVM_DEBUG({
190  llvm::dbgs() << "* Illegal to inline because of op: ";
191  op.dump();
192  });
193  return false;
194  }
195  // Check any nested regions.
196  if (interface.shouldAnalyzeRecursively(&op) &&
197  llvm::any_of(op.getRegions(), [&](Region &region) {
198  return !isLegalToInline(interface, &region, insertRegion,
199  shouldCloneInlinedRegion, valueMapping);
200  }))
201  return false;
202  }
203  }
204  return true;
205 }
206 
207 //===----------------------------------------------------------------------===//
208 // Inline Methods
209 //===----------------------------------------------------------------------===//
210 
211 static void handleArgumentImpl(InlinerInterface &interface, OpBuilder &builder,
212  CallOpInterface call,
213  CallableOpInterface callable,
214  IRMapping &mapper) {
215  // Unpack the argument attributes if there are any.
217  callable.getCallableRegion()->getNumArguments(),
218  builder.getDictionaryAttr({}));
219  if (ArrayAttr arrayAttr = callable.getArgAttrsAttr()) {
220  assert(arrayAttr.size() == argAttrs.size());
221  for (auto [idx, attr] : llvm::enumerate(arrayAttr))
222  argAttrs[idx] = cast<DictionaryAttr>(attr);
223  }
224 
225  // Run the argument attribute handler for the given argument and attribute.
226  for (auto [blockArg, argAttr] :
227  llvm::zip(callable.getCallableRegion()->getArguments(), argAttrs)) {
228  Value newArgument = interface.handleArgument(
229  builder, call, callable, mapper.lookup(blockArg), argAttr);
230  assert(newArgument.getType() == mapper.lookup(blockArg).getType() &&
231  "expected the argument type to not change");
232 
233  // Update the mapping to point the new argument returned by the handler.
234  mapper.map(blockArg, newArgument);
235  }
236 }
237 
238 static void handleResultImpl(InlinerInterface &interface, OpBuilder &builder,
239  CallOpInterface call, CallableOpInterface callable,
240  ValueRange results) {
241  // Unpack the result attributes if there are any.
242  SmallVector<DictionaryAttr> resAttrs(results.size(),
243  builder.getDictionaryAttr({}));
244  if (ArrayAttr arrayAttr = callable.getResAttrsAttr()) {
245  assert(arrayAttr.size() == resAttrs.size());
246  for (auto [idx, attr] : llvm::enumerate(arrayAttr))
247  resAttrs[idx] = cast<DictionaryAttr>(attr);
248  }
249 
250  // Run the result attribute handler for the given result and attribute.
251  for (auto [result, resAttr] : llvm::zip(results, resAttrs)) {
252  // Store the original result users before running the handler.
253  DenseSet<Operation *> resultUsers(llvm::from_range, result.getUsers());
254 
255  Value newResult =
256  interface.handleResult(builder, call, callable, result, resAttr);
257  assert(newResult.getType() == result.getType() &&
258  "expected the result type to not change");
259 
260  // Replace the result uses except for the ones introduce by the handler.
261  result.replaceUsesWithIf(newResult, [&](OpOperand &operand) {
262  return resultUsers.count(operand.getOwner());
263  });
264  }
265 }
266 
267 static LogicalResult inlineRegionImpl(
268  InlinerInterface &interface,
270  Region *src, Block *inlineBlock, Block::iterator inlinePoint,
271  IRMapping &mapper, ValueRange resultsToReplace, TypeRange regionResultTypes,
272  std::optional<Location> inlineLoc, bool shouldCloneInlinedRegion,
273  CallOpInterface call = {}) {
274  assert(resultsToReplace.size() == regionResultTypes.size());
275  // We expect the region to have at least one block.
276  if (src->empty())
277  return failure();
278 
279  // Check that all of the region arguments have been mapped.
280  auto *srcEntryBlock = &src->front();
281  if (llvm::any_of(srcEntryBlock->getArguments(),
282  [&](BlockArgument arg) { return !mapper.contains(arg); }))
283  return failure();
284 
285  // Check that the operations within the source region are valid to inline.
286  Region *insertRegion = inlineBlock->getParent();
287  if (!interface.isLegalToInline(insertRegion, src, shouldCloneInlinedRegion,
288  mapper) ||
289  !isLegalToInline(interface, src, insertRegion, shouldCloneInlinedRegion,
290  mapper))
291  return failure();
292 
293  // Run the argument attribute handler before inlining the callable region.
294  OpBuilder builder(inlineBlock, inlinePoint);
295  auto callable = dyn_cast<CallableOpInterface>(src->getParentOp());
296  if (call && callable)
297  handleArgumentImpl(interface, builder, call, callable, mapper);
298 
299  // Clone the callee's source into the caller.
300  Block *postInsertBlock = inlineBlock->splitBlock(inlinePoint);
301  cloneCallback(builder, src, inlineBlock, postInsertBlock, mapper,
302  shouldCloneInlinedRegion);
303 
304  // Get the range of newly inserted blocks.
305  auto newBlocks = llvm::make_range(std::next(inlineBlock->getIterator()),
306  postInsertBlock->getIterator());
307  Block *firstNewBlock = &*newBlocks.begin();
308 
309  // Remap the locations of the inlined operations if a valid source location
310  // was provided.
311  if (inlineLoc && !llvm::isa<UnknownLoc>(*inlineLoc))
312  remapInlinedLocations(newBlocks, *inlineLoc);
313 
314  // If the blocks were moved in-place, make sure to remap any necessary
315  // operands.
316  if (!shouldCloneInlinedRegion)
317  remapInlinedOperands(newBlocks, mapper);
318 
319  // Process the newly inlined blocks.
320  if (call)
321  interface.processInlinedCallBlocks(call, newBlocks);
322  interface.processInlinedBlocks(newBlocks);
323 
324  bool singleBlockFastPath = interface.allowSingleBlockOptimization(newBlocks);
325 
326  // Handle the case where only a single block was inlined.
327  if (singleBlockFastPath && llvm::hasSingleElement(newBlocks)) {
328  // Run the result attribute handler on the terminator operands.
329  Operation *firstBlockTerminator = firstNewBlock->getTerminator();
330  builder.setInsertionPoint(firstBlockTerminator);
331  if (call && callable)
332  handleResultImpl(interface, builder, call, callable,
333  firstBlockTerminator->getOperands());
334 
335  // Have the interface handle the terminator of this block.
336  interface.handleTerminator(firstBlockTerminator, resultsToReplace);
337  firstBlockTerminator->erase();
338 
339  // Merge the post insert block into the cloned entry block.
340  firstNewBlock->getOperations().splice(firstNewBlock->end(),
341  postInsertBlock->getOperations());
342  postInsertBlock->erase();
343  } else {
344  // Otherwise, there were multiple blocks inlined. Add arguments to the post
345  // insertion block to represent the results to replace.
346  for (const auto &resultToRepl : llvm::enumerate(resultsToReplace)) {
347  resultToRepl.value().replaceAllUsesWith(
348  postInsertBlock->addArgument(regionResultTypes[resultToRepl.index()],
349  resultToRepl.value().getLoc()));
350  }
351 
352  // Run the result attribute handler on the post insertion block arguments.
353  builder.setInsertionPointToStart(postInsertBlock);
354  if (call && callable)
355  handleResultImpl(interface, builder, call, callable,
356  postInsertBlock->getArguments());
357 
358  /// Handle the terminators for each of the new blocks.
359  for (auto &newBlock : newBlocks)
360  interface.handleTerminator(newBlock.getTerminator(), postInsertBlock);
361  }
362 
363  // Splice the instructions of the inlined entry block into the insert block.
364  inlineBlock->getOperations().splice(inlineBlock->end(),
365  firstNewBlock->getOperations());
366  firstNewBlock->erase();
367  return success();
368 }
369 
370 static LogicalResult inlineRegionImpl(
371  InlinerInterface &interface,
373  Region *src, Block *inlineBlock, Block::iterator inlinePoint,
374  ValueRange inlinedOperands, ValueRange resultsToReplace,
375  std::optional<Location> inlineLoc, bool shouldCloneInlinedRegion,
376  CallOpInterface call = {}) {
377  // We expect the region to have at least one block.
378  if (src->empty())
379  return failure();
380 
381  auto *entryBlock = &src->front();
382  if (inlinedOperands.size() != entryBlock->getNumArguments())
383  return failure();
384 
385  // Map the provided call operands to the arguments of the region.
386  IRMapping mapper;
387  for (unsigned i = 0, e = inlinedOperands.size(); i != e; ++i) {
388  // Verify that the types of the provided values match the function argument
389  // types.
390  BlockArgument regionArg = entryBlock->getArgument(i);
391  if (inlinedOperands[i].getType() != regionArg.getType())
392  return failure();
393  mapper.map(regionArg, inlinedOperands[i]);
394  }
395 
396  // Call into the main region inliner function.
397  return inlineRegionImpl(interface, cloneCallback, src, inlineBlock,
398  inlinePoint, mapper, resultsToReplace,
399  resultsToReplace.getTypes(), inlineLoc,
400  shouldCloneInlinedRegion, call);
401 }
402 
403 LogicalResult mlir::inlineRegion(
404  InlinerInterface &interface,
406  Region *src, Operation *inlinePoint, IRMapping &mapper,
407  ValueRange resultsToReplace, TypeRange regionResultTypes,
408  std::optional<Location> inlineLoc, bool shouldCloneInlinedRegion) {
409  return inlineRegion(interface, cloneCallback, src, inlinePoint->getBlock(),
410  ++inlinePoint->getIterator(), mapper, resultsToReplace,
411  regionResultTypes, inlineLoc, shouldCloneInlinedRegion);
412 }
413 
414 LogicalResult mlir::inlineRegion(
415  InlinerInterface &interface,
417  Region *src, Block *inlineBlock, Block::iterator inlinePoint,
418  IRMapping &mapper, ValueRange resultsToReplace, TypeRange regionResultTypes,
419  std::optional<Location> inlineLoc, bool shouldCloneInlinedRegion) {
420  return inlineRegionImpl(
421  interface, cloneCallback, src, inlineBlock, inlinePoint, mapper,
422  resultsToReplace, regionResultTypes, inlineLoc, shouldCloneInlinedRegion);
423 }
424 
425 LogicalResult mlir::inlineRegion(
426  InlinerInterface &interface,
428  Region *src, Operation *inlinePoint, ValueRange inlinedOperands,
429  ValueRange resultsToReplace, std::optional<Location> inlineLoc,
430  bool shouldCloneInlinedRegion) {
431  return inlineRegion(interface, cloneCallback, src, inlinePoint->getBlock(),
432  ++inlinePoint->getIterator(), inlinedOperands,
433  resultsToReplace, inlineLoc, shouldCloneInlinedRegion);
434 }
435 
436 LogicalResult mlir::inlineRegion(
437  InlinerInterface &interface,
439  Region *src, Block *inlineBlock, Block::iterator inlinePoint,
440  ValueRange inlinedOperands, ValueRange resultsToReplace,
441  std::optional<Location> inlineLoc, bool shouldCloneInlinedRegion) {
442  return inlineRegionImpl(interface, cloneCallback, src, inlineBlock,
443  inlinePoint, inlinedOperands, resultsToReplace,
444  inlineLoc, shouldCloneInlinedRegion);
445 }
446 
447 /// Utility function used to generate a cast operation from the given interface,
448 /// or return nullptr if a cast could not be generated.
451  OpBuilder &castBuilder, Value arg, Type type,
452  Location conversionLoc) {
453  if (!interface)
454  return nullptr;
455 
456  // Check to see if the interface for the call can materialize a conversion.
457  Operation *castOp = interface->materializeCallConversion(castBuilder, arg,
458  type, conversionLoc);
459  if (!castOp)
460  return nullptr;
461  castOps.push_back(castOp);
462 
463  // Ensure that the generated cast is correct.
464  assert(castOp->getNumOperands() == 1 && castOp->getOperand(0) == arg &&
465  castOp->getNumResults() == 1 && *castOp->result_type_begin() == type);
466  return castOp->getResult(0);
467 }
468 
469 /// This function inlines a given region, 'src', of a callable operation,
470 /// 'callable', into the location defined by the given call operation. This
471 /// function returns failure if inlining is not possible, success otherwise. On
472 /// failure, no changes are made to the module. 'shouldCloneInlinedRegion'
473 /// corresponds to whether the source region should be cloned into the 'call' or
474 /// spliced directly.
475 LogicalResult mlir::inlineCall(
476  InlinerInterface &interface,
478  CallOpInterface call, CallableOpInterface callable, Region *src,
479  bool shouldCloneInlinedRegion) {
480  // We expect the region to have at least one block.
481  if (src->empty())
482  return failure();
483  auto *entryBlock = &src->front();
484  ArrayRef<Type> callableResultTypes = callable.getResultTypes();
485 
486  // Make sure that the number of arguments and results matchup between the call
487  // and the region.
488  SmallVector<Value, 8> callOperands(call.getArgOperands());
489  SmallVector<Value, 8> callResults(call->getResults());
490  if (callOperands.size() != entryBlock->getNumArguments() ||
491  callResults.size() != callableResultTypes.size())
492  return failure();
493 
494  // A set of cast operations generated to matchup the signature of the region
495  // with the signature of the call.
497  castOps.reserve(callOperands.size() + callResults.size());
498 
499  // Functor used to cleanup generated state on failure.
500  auto cleanupState = [&] {
501  for (auto *op : castOps) {
502  op->getResult(0).replaceAllUsesWith(op->getOperand(0));
503  op->erase();
504  }
505  return failure();
506  };
507 
508  // Builder used for any conversion operations that need to be materialized.
509  OpBuilder castBuilder(call);
510  Location castLoc = call.getLoc();
511  const auto *callInterface = interface.getInterfaceFor(call->getDialect());
512 
513  // Map the provided call operands to the arguments of the region.
514  IRMapping mapper;
515  for (unsigned i = 0, e = callOperands.size(); i != e; ++i) {
516  BlockArgument regionArg = entryBlock->getArgument(i);
517  Value operand = callOperands[i];
518 
519  // If the call operand doesn't match the expected region argument, try to
520  // generate a cast.
521  Type regionArgType = regionArg.getType();
522  if (operand.getType() != regionArgType) {
523  if (!(operand = materializeConversion(callInterface, castOps, castBuilder,
524  operand, regionArgType, castLoc)))
525  return cleanupState();
526  }
527  mapper.map(regionArg, operand);
528  }
529 
530  // Ensure that the resultant values of the call match the callable.
531  castBuilder.setInsertionPointAfter(call);
532  for (unsigned i = 0, e = callResults.size(); i != e; ++i) {
533  Value callResult = callResults[i];
534  if (callResult.getType() == callableResultTypes[i])
535  continue;
536 
537  // Generate a conversion that will produce the original type, so that the IR
538  // is still valid after the original call gets replaced.
539  Value castResult =
540  materializeConversion(callInterface, castOps, castBuilder, callResult,
541  callResult.getType(), castLoc);
542  if (!castResult)
543  return cleanupState();
544  callResult.replaceAllUsesWith(castResult);
545  castResult.getDefiningOp()->replaceUsesOfWith(castResult, callResult);
546  }
547 
548  // Check that it is legal to inline the callable into the call.
549  if (!interface.isLegalToInline(call, callable, shouldCloneInlinedRegion))
550  return cleanupState();
551 
552  // Attempt to inline the call.
553  if (failed(inlineRegionImpl(interface, cloneCallback, src, call->getBlock(),
554  ++call->getIterator(), mapper, callResults,
555  callableResultTypes, call.getLoc(),
556  shouldCloneInlinedRegion, call)))
557  return cleanupState();
558  return success();
559 }
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)
This is an attribute/type replacer that is naively cached.
This class represents an argument of a Block.
Definition: Value.h:309
Block represents an ordered list of Operations.
Definition: Block.h:33
OpListType::iterator iterator
Definition: Block.h:140
void erase()
Unlink this Block from its parent region and delete it.
Definition: Block.cpp:68
Block * splitBlock(iterator splitBefore)
Split the block into two blocks before the specified operation or iterator.
Definition: Block.cpp:310
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition: Block.cpp:29
Operation * getTerminator()
Get the terminator operation of this block.
Definition: Block.cpp:246
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition: Block.cpp:155
OpListType & getOperations()
Definition: Block.h:137
BlockArgListType getArguments()
Definition: Block.h:87
iterator end()
Definition: Block.h:144
iterator begin()
Definition: Block.h:143
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
Definition: Builders.cpp:100
This is the interface that must be implemented by the dialects of operations to be inlined.
Definition: InliningUtils.h:44
virtual Operation * materializeCallConversion(OpBuilder &builder, Value input, Type resultType, Location conversionLoc) const
Attempt to materialize a conversion for a type mismatch between a call from this dialect,...
const DialectInlinerInterface * getInterfaceFor(Object *obj) const
Get the interface for a given object, or null if one is not registered.
This is a utility class for mapping one set of IR entities to another.
Definition: IRMapping.h:26
auto lookup(T from) const
Lookup a mapped value within the map.
Definition: IRMapping.h:72
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition: IRMapping.h:30
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
Definition: IRMapping.h:58
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(iterator_range< Region::iterator > inlinedBlocks) const
Returns true if the inliner can assume a fast path of not creating a new block, if there is only one ...
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.
Definition: Location.h:32
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:76
This class helps build Operations.
Definition: Builders.h:204
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition: Builders.h:409
This class represents an operand of an operation.
Definition: Value.h:257
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
void replaceUsesOfWith(Value from, Value to)
Replace any uses of 'from' with 'to' within this operation.
Definition: Operation.cpp:227
Value getOperand(unsigned idx)
Definition: Operation.h:350
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition: Operation.h:407
unsigned getNumOperands()
Definition: Operation.h:346
Block * getBlock()
Returns the operation block that contains this operation.
Definition: Operation.h:213
result_type_iterator result_type_begin()
Definition: Operation.h:426
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition: Operation.h:378
void erase()
Remove this operation from its parent block and delete it.
Definition: Operation.cpp:539
unsigned getNumResults()
Return the number of results held by this operation.
Definition: Operation.h:404
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition: Region.h:200
bool empty()
Definition: Region.h:60
Block & front()
Definition: Region.h:65
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:37
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:387
type_range getTypes() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:105
void replaceAllUsesWith(Value newValue)
Replace all uses of 'this' value with the new value, updating anything in the IR that uses 'this' to ...
Definition: Value.h:149
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:20
static WalkResult skip()
Definition: Visitors.h:52
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)
Register a replacement function for mapping a given attribute or type.
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:344
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition: Utils.cpp:305
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...
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
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.