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 
13 #include "mlir/Transforms/InliningUtils.h"
14 
15 #include "mlir/IR/BlockAndValueMapping.h"
16 #include "mlir/IR/Builders.h"
17 #include "mlir/IR/Function.h"
18 #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 
23 #define DEBUG_TYPE "inlining"
24 
25 using namespace mlir;
26 
27 /// Remap locations from the inlined blocks with CallSiteLoc locations with the
28 /// provided caller location.
29 static void
30 remapInlinedLocations(iterator_range<Region::iterator> inlinedBlocks,
31                       Location callerLoc) {
32   DenseMap<Location, Location> mappedLocations;
33   auto remapOpLoc = [&](Operation *op) {
34     auto it = mappedLocations.find(op->getLoc());
35     if (it == mappedLocations.end()) {
36       auto newLoc = CallSiteLoc::get(op->getLoc(), callerLoc);
37       it = mappedLocations.try_emplace(op->getLoc(), newLoc).first;
38     }
39     op->setLoc(it->second);
40   };
41   for (auto &block : inlinedBlocks)
42     block.walk(remapOpLoc);
43 }
44 
45 static void remapInlinedOperands(iterator_range<Region::iterator> inlinedBlocks,
46                                  BlockAndValueMapping &mapper) {
47   auto remapOperands = [&](Operation *op) {
48     for (auto &operand : op->getOpOperands())
49       if (auto mappedOp = mapper.lookupOrNull(operand.get()))
50         operand.set(mappedOp);
51   };
52   for (auto &block : inlinedBlocks)
53     block.walk(remapOperands);
54 }
55 
56 //===----------------------------------------------------------------------===//
57 // InlinerInterface
58 //===----------------------------------------------------------------------===//
59 
60 bool InlinerInterface::isLegalToInline(
61     Region *dest, Region *src, BlockAndValueMapping &valueMapping) const {
62   // Regions can always be inlined into functions.
63   if (isa<FuncOp>(dest->getParentOp()))
64     return true;
65 
66   auto *handler = getInterfaceFor(dest->getParentOp());
67   return handler ? handler->isLegalToInline(dest, src, valueMapping) : false;
68 }
69 
70 bool InlinerInterface::isLegalToInline(
71     Operation *op, Region *dest, BlockAndValueMapping &valueMapping) const {
72   auto *handler = getInterfaceFor(op);
73   return handler ? handler->isLegalToInline(op, dest, valueMapping) : false;
74 }
75 
76 bool InlinerInterface::shouldAnalyzeRecursively(Operation *op) const {
77   auto *handler = getInterfaceFor(op);
78   return handler ? handler->shouldAnalyzeRecursively(op) : true;
79 }
80 
81 /// Handle the given inlined terminator by replacing it with a new operation
82 /// as necessary.
83 void InlinerInterface::handleTerminator(Operation *op, Block *newDest) const {
84   auto *handler = getInterfaceFor(op);
85   assert(handler && "expected valid dialect handler");
86   handler->handleTerminator(op, newDest);
87 }
88 
89 /// Handle the given inlined terminator by replacing it with a new operation
90 /// as necessary.
91 void InlinerInterface::handleTerminator(Operation *op,
92                                         ArrayRef<Value> valuesToRepl) const {
93   auto *handler = getInterfaceFor(op);
94   assert(handler && "expected valid dialect handler");
95   handler->handleTerminator(op, valuesToRepl);
96 }
97 
98 /// Utility to check that all of the operations within 'src' can be inlined.
99 static bool isLegalToInline(InlinerInterface &interface, Region *src,
100                             Region *insertRegion,
101                             BlockAndValueMapping &valueMapping) {
102   for (auto &block : *src) {
103     for (auto &op : block) {
104       // Check this operation.
105       if (!interface.isLegalToInline(&op, insertRegion, valueMapping)) {
106         LLVM_DEBUG({
107           llvm::dbgs() << "* Illegal to inline because of op: ";
108           op.dump();
109         });
110         return false;
111       }
112       // Check any nested regions.
113       if (interface.shouldAnalyzeRecursively(&op) &&
114           llvm::any_of(op.getRegions(), [&](Region &region) {
115             return !isLegalToInline(interface, &region, insertRegion,
116                                     valueMapping);
117           }))
118         return false;
119     }
120   }
121   return true;
122 }
123 
124 //===----------------------------------------------------------------------===//
125 // Inline Methods
126 //===----------------------------------------------------------------------===//
127 
128 LogicalResult mlir::inlineRegion(InlinerInterface &interface, Region *src,
129                                  Operation *inlinePoint,
130                                  BlockAndValueMapping &mapper,
131                                  ValueRange resultsToReplace,
132                                  TypeRange regionResultTypes,
133                                  Optional<Location> inlineLoc,
134                                  bool shouldCloneInlinedRegion) {
135   assert(resultsToReplace.size() == regionResultTypes.size());
136   // We expect the region to have at least one block.
137   if (src->empty())
138     return failure();
139 
140   // Check that all of the region arguments have been mapped.
141   auto *srcEntryBlock = &src->front();
142   if (llvm::any_of(srcEntryBlock->getArguments(),
143                    [&](BlockArgument arg) { return !mapper.contains(arg); }))
144     return failure();
145 
146   // The insertion point must be within a block.
147   Block *insertBlock = inlinePoint->getBlock();
148   if (!insertBlock)
149     return failure();
150   Region *insertRegion = insertBlock->getParent();
151 
152   // Check that the operations within the source region are valid to inline.
153   if (!interface.isLegalToInline(insertRegion, src, mapper) ||
154       !isLegalToInline(interface, src, insertRegion, mapper))
155     return failure();
156 
157   // Split the insertion block.
158   Block *postInsertBlock =
159       insertBlock->splitBlock(++inlinePoint->getIterator());
160 
161   // Check to see if the region is being cloned, or moved inline. In either
162   // case, move the new blocks after the 'insertBlock' to improve IR
163   // readability.
164   if (shouldCloneInlinedRegion)
165     src->cloneInto(insertRegion, postInsertBlock->getIterator(), mapper);
166   else
167     insertRegion->getBlocks().splice(postInsertBlock->getIterator(),
168                                      src->getBlocks(), src->begin(),
169                                      src->end());
170 
171   // Get the range of newly inserted blocks.
172   auto newBlocks = llvm::make_range(std::next(insertBlock->getIterator()),
173                                     postInsertBlock->getIterator());
174   Block *firstNewBlock = &*newBlocks.begin();
175 
176   // Remap the locations of the inlined operations if a valid source location
177   // was provided.
178   if (inlineLoc && !inlineLoc->isa<UnknownLoc>())
179     remapInlinedLocations(newBlocks, *inlineLoc);
180 
181   // If the blocks were moved in-place, make sure to remap any necessary
182   // operands.
183   if (!shouldCloneInlinedRegion)
184     remapInlinedOperands(newBlocks, mapper);
185 
186   // Process the newly inlined blocks.
187   interface.processInlinedBlocks(newBlocks);
188 
189   // Handle the case where only a single block was inlined.
190   if (std::next(newBlocks.begin()) == newBlocks.end()) {
191     // Have the interface handle the terminator of this block.
192     auto *firstBlockTerminator = firstNewBlock->getTerminator();
193     interface.handleTerminator(firstBlockTerminator,
194                                llvm::to_vector<6>(resultsToReplace));
195     firstBlockTerminator->erase();
196 
197     // Merge the post insert block into the cloned entry block.
198     firstNewBlock->getOperations().splice(firstNewBlock->end(),
199                                           postInsertBlock->getOperations());
200     postInsertBlock->erase();
201   } else {
202     // Otherwise, there were multiple blocks inlined. Add arguments to the post
203     // insertion block to represent the results to replace.
204     for (auto resultToRepl : llvm::enumerate(resultsToReplace)) {
205       resultToRepl.value().replaceAllUsesWith(postInsertBlock->addArgument(
206           regionResultTypes[resultToRepl.index()]));
207     }
208 
209     /// Handle the terminators for each of the new blocks.
210     for (auto &newBlock : newBlocks)
211       interface.handleTerminator(newBlock.getTerminator(), postInsertBlock);
212   }
213 
214   // Splice the instructions of the inlined entry block into the insert block.
215   insertBlock->getOperations().splice(insertBlock->end(),
216                                       firstNewBlock->getOperations());
217   firstNewBlock->erase();
218   return success();
219 }
220 
221 /// This function is an overload of the above 'inlineRegion' that allows for
222 /// providing the set of operands ('inlinedOperands') that should be used
223 /// in-favor of the region arguments when inlining.
224 LogicalResult mlir::inlineRegion(InlinerInterface &interface, Region *src,
225                                  Operation *inlinePoint,
226                                  ValueRange inlinedOperands,
227                                  ValueRange resultsToReplace,
228                                  Optional<Location> inlineLoc,
229                                  bool shouldCloneInlinedRegion) {
230   // We expect the region to have at least one block.
231   if (src->empty())
232     return failure();
233 
234   auto *entryBlock = &src->front();
235   if (inlinedOperands.size() != entryBlock->getNumArguments())
236     return failure();
237 
238   // Map the provided call operands to the arguments of the region.
239   BlockAndValueMapping mapper;
240   for (unsigned i = 0, e = inlinedOperands.size(); i != e; ++i) {
241     // Verify that the types of the provided values match the function argument
242     // types.
243     BlockArgument regionArg = entryBlock->getArgument(i);
244     if (inlinedOperands[i].getType() != regionArg.getType())
245       return failure();
246     mapper.map(regionArg, inlinedOperands[i]);
247   }
248 
249   // Call into the main region inliner function.
250   return inlineRegion(interface, src, inlinePoint, mapper, resultsToReplace,
251                       resultsToReplace.getTypes(), inlineLoc,
252                       shouldCloneInlinedRegion);
253 }
254 
255 /// Utility function used to generate a cast operation from the given interface,
256 /// or return nullptr if a cast could not be generated.
257 static Value materializeConversion(const DialectInlinerInterface *interface,
258                                    SmallVectorImpl<Operation *> &castOps,
259                                    OpBuilder &castBuilder, Value arg, Type type,
260                                    Location conversionLoc) {
261   if (!interface)
262     return nullptr;
263 
264   // Check to see if the interface for the call can materialize a conversion.
265   Operation *castOp = interface->materializeCallConversion(castBuilder, arg,
266                                                            type, conversionLoc);
267   if (!castOp)
268     return nullptr;
269   castOps.push_back(castOp);
270 
271   // Ensure that the generated cast is correct.
272   assert(castOp->getNumOperands() == 1 && castOp->getOperand(0) == arg &&
273          castOp->getNumResults() == 1 && *castOp->result_type_begin() == type);
274   return castOp->getResult(0);
275 }
276 
277 /// This function inlines a given region, 'src', of a callable operation,
278 /// 'callable', into the location defined by the given call operation. This
279 /// function returns failure if inlining is not possible, success otherwise. On
280 /// failure, no changes are made to the module. 'shouldCloneInlinedRegion'
281 /// corresponds to whether the source region should be cloned into the 'call' or
282 /// spliced directly.
283 LogicalResult mlir::inlineCall(InlinerInterface &interface,
284                                CallOpInterface call,
285                                CallableOpInterface callable, Region *src,
286                                bool shouldCloneInlinedRegion) {
287   // We expect the region to have at least one block.
288   if (src->empty())
289     return failure();
290   auto *entryBlock = &src->front();
291   ArrayRef<Type> callableResultTypes = callable.getCallableResults();
292 
293   // Make sure that the number of arguments and results matchup between the call
294   // and the region.
295   SmallVector<Value, 8> callOperands(call.getArgOperands());
296   SmallVector<Value, 8> callResults(call.getOperation()->getResults());
297   if (callOperands.size() != entryBlock->getNumArguments() ||
298       callResults.size() != callableResultTypes.size())
299     return failure();
300 
301   // A set of cast operations generated to matchup the signature of the region
302   // with the signature of the call.
303   SmallVector<Operation *, 4> castOps;
304   castOps.reserve(callOperands.size() + callResults.size());
305 
306   // Functor used to cleanup generated state on failure.
307   auto cleanupState = [&] {
308     for (auto *op : castOps) {
309       op->getResult(0).replaceAllUsesWith(op->getOperand(0));
310       op->erase();
311     }
312     return failure();
313   };
314 
315   // Builder used for any conversion operations that need to be materialized.
316   OpBuilder castBuilder(call);
317   Location castLoc = call.getLoc();
318   auto *callInterface = interface.getInterfaceFor(call.getDialect());
319 
320   // Map the provided call operands to the arguments of the region.
321   BlockAndValueMapping mapper;
322   for (unsigned i = 0, e = callOperands.size(); i != e; ++i) {
323     BlockArgument regionArg = entryBlock->getArgument(i);
324     Value operand = callOperands[i];
325 
326     // If the call operand doesn't match the expected region argument, try to
327     // generate a cast.
328     Type regionArgType = regionArg.getType();
329     if (operand.getType() != regionArgType) {
330       if (!(operand = materializeConversion(callInterface, castOps, castBuilder,
331                                             operand, regionArgType, castLoc)))
332         return cleanupState();
333     }
334     mapper.map(regionArg, operand);
335   }
336 
337   // Ensure that the resultant values of the call match the callable.
338   castBuilder.setInsertionPointAfter(call);
339   for (unsigned i = 0, e = callResults.size(); i != e; ++i) {
340     Value callResult = callResults[i];
341     if (callResult.getType() == callableResultTypes[i])
342       continue;
343 
344     // Generate a conversion that will produce the original type, so that the IR
345     // is still valid after the original call gets replaced.
346     Value castResult =
347         materializeConversion(callInterface, castOps, castBuilder, callResult,
348                               callResult.getType(), castLoc);
349     if (!castResult)
350       return cleanupState();
351     callResult.replaceAllUsesWith(castResult);
352     castResult.getDefiningOp()->replaceUsesOfWith(castResult, callResult);
353   }
354 
355   // Attempt to inline the call.
356   if (failed(inlineRegion(interface, src, call, mapper, callResults,
357                           callableResultTypes, call.getLoc(),
358                           shouldCloneInlinedRegion)))
359     return cleanupState();
360   return success();
361 }
362