1 //===- DialectConversion.cpp - MLIR dialect conversion generic pass -------===//
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 #include "mlir/Transforms/DialectConversion.h"
10 #include "mlir/IR/Block.h"
11 #include "mlir/IR/BlockAndValueMapping.h"
12 #include "mlir/IR/Builders.h"
13 #include "mlir/IR/BuiltinOps.h"
14 #include "mlir/IR/FunctionSupport.h"
15 #include "mlir/Rewrite/PatternApplicator.h"
16 #include "mlir/Transforms/Utils.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/FormatVariadic.h"
22 #include "llvm/Support/SaveAndRestore.h"
23 #include "llvm/Support/ScopedPrinter.h"
24 
25 using namespace mlir;
26 using namespace mlir::detail;
27 
28 #define DEBUG_TYPE "dialect-conversion"
29 
30 /// Recursively collect all of the operations to convert from within 'region'.
31 /// If 'target' is nonnull, operations that are recursively legal have their
32 /// regions pre-filtered to avoid considering them for legalization.
33 static LogicalResult
34 computeConversionSet(iterator_range<Region::iterator> region,
35                      Location regionLoc,
36                      SmallVectorImpl<Operation *> &toConvert,
37                      ConversionTarget *target = nullptr) {
38   if (llvm::empty(region))
39     return success();
40 
41   // Traverse starting from the entry block.
42   SmallVector<Block *, 16> worklist(1, &*region.begin());
43   DenseSet<Block *> visitedBlocks;
44   visitedBlocks.insert(worklist.front());
45   while (!worklist.empty()) {
46     Block *block = worklist.pop_back_val();
47 
48     // Compute the conversion set of each of the nested operations.
49     for (Operation &op : *block) {
50       toConvert.emplace_back(&op);
51 
52       // Don't check this operation's children for conversion if the operation
53       // is recursively legal.
54       auto legalityInfo = target ? target->isLegal(&op)
55                                  : Optional<ConversionTarget::LegalOpDetails>();
56       if (legalityInfo && legalityInfo->isRecursivelyLegal)
57         continue;
58       for (auto &region : op.getRegions()) {
59         if (failed(computeConversionSet(region.getBlocks(), region.getLoc(),
60                                         toConvert, target)))
61           return failure();
62       }
63     }
64 
65     // Recurse to children that haven't been visited.
66     for (Block *succ : block->getSuccessors())
67       if (visitedBlocks.insert(succ).second)
68         worklist.push_back(succ);
69   }
70 
71   // Check that all blocks in the region were visited.
72   if (llvm::any_of(llvm::drop_begin(region, 1),
73                    [&](Block &block) { return !visitedBlocks.count(&block); }))
74     return emitError(regionLoc, "unreachable blocks were not converted");
75   return success();
76 }
77 
78 /// A utility function to log a successful result for the given reason.
79 template <typename... Args>
80 static void logSuccess(llvm::ScopedPrinter &os, StringRef fmt, Args &&...args) {
81   LLVM_DEBUG({
82     os.unindent();
83     os.startLine() << "} -> SUCCESS";
84     if (!fmt.empty())
85       os.getOStream() << " : "
86                       << llvm::formatv(fmt.data(), std::forward<Args>(args)...);
87     os.getOStream() << "\n";
88   });
89 }
90 
91 /// A utility function to log a failure result for the given reason.
92 template <typename... Args>
93 static void logFailure(llvm::ScopedPrinter &os, StringRef fmt, Args &&...args) {
94   LLVM_DEBUG({
95     os.unindent();
96     os.startLine() << "} -> FAILURE : "
97                    << llvm::formatv(fmt.data(), std::forward<Args>(args)...)
98                    << "\n";
99   });
100 }
101 
102 //===----------------------------------------------------------------------===//
103 // ConversionValueMapping
104 //===----------------------------------------------------------------------===//
105 
106 namespace {
107 /// This class wraps a BlockAndValueMapping to provide recursive lookup
108 /// functionality, i.e. we will traverse if the mapped value also has a mapping.
109 struct ConversionValueMapping {
110   /// Lookup a mapped value within the map. If a mapping for the provided value
111   /// does not exist then return the provided value. If `desiredType` is
112   /// non-null, returns the most recently mapped value with that type. If an
113   /// operand of that type does not exist, defaults to normal behavior.
114   Value lookupOrDefault(Value from, Type desiredType = nullptr) const;
115 
116   /// Lookup a mapped value within the map, or return null if a mapping does not
117   /// exist. If a mapping exists, this follows the same behavior of
118   /// `lookupOrDefault`.
119   Value lookupOrNull(Value from, Type desiredType = nullptr) const;
120 
121   /// Map a value to the one provided.
122   void map(Value oldVal, Value newVal) {
123     LLVM_DEBUG({
124       for (Value it = newVal; it; it = mapping.lookupOrNull(it))
125         assert(it != oldVal && "inserting cyclic mapping");
126     });
127     mapping.map(oldVal, newVal);
128   }
129 
130   /// Try to map a value to the one provided. Returns false if a transitive
131   /// mapping from the new value to the old value already exists, true if the
132   /// map was updated.
133   bool tryMap(Value oldVal, Value newVal);
134 
135   /// Drop the last mapping for the given value.
136   void erase(Value value) { mapping.erase(value); }
137 
138   /// Returns the inverse raw value mapping (without recursive query support).
139   DenseMap<Value, SmallVector<Value>> getInverse() const {
140     DenseMap<Value, SmallVector<Value>> inverse;
141     for (auto &it : mapping.getValueMap())
142       inverse[it.second].push_back(it.first);
143     return inverse;
144   }
145 
146 private:
147   /// Current value mappings.
148   BlockAndValueMapping mapping;
149 };
150 } // namespace
151 
152 Value ConversionValueMapping::lookupOrDefault(Value from,
153                                               Type desiredType) const {
154   // If there was no desired type, simply find the leaf value.
155   if (!desiredType) {
156     // If this value had a valid mapping, unmap that value as well in the case
157     // that it was also replaced.
158     while (auto mappedValue = mapping.lookupOrNull(from))
159       from = mappedValue;
160     return from;
161   }
162 
163   // Otherwise, try to find the deepest value that has the desired type.
164   Value desiredValue;
165   do {
166     if (from.getType() == desiredType)
167       desiredValue = from;
168 
169     Value mappedValue = mapping.lookupOrNull(from);
170     if (!mappedValue)
171       break;
172     from = mappedValue;
173   } while (true);
174 
175   // If the desired value was found use it, otherwise default to the leaf value.
176   return desiredValue ? desiredValue : from;
177 }
178 
179 Value ConversionValueMapping::lookupOrNull(Value from, Type desiredType) const {
180   Value result = lookupOrDefault(from, desiredType);
181   if (result == from || (desiredType && result.getType() != desiredType))
182     return nullptr;
183   return result;
184 }
185 
186 bool ConversionValueMapping::tryMap(Value oldVal, Value newVal) {
187   for (Value it = newVal; it; it = mapping.lookupOrNull(it))
188     if (it == oldVal)
189       return false;
190   map(oldVal, newVal);
191   return true;
192 }
193 
194 //===----------------------------------------------------------------------===//
195 // Rewriter and Translation State
196 //===----------------------------------------------------------------------===//
197 namespace {
198 /// This class contains a snapshot of the current conversion rewriter state.
199 /// This is useful when saving and undoing a set of rewrites.
200 struct RewriterState {
201   RewriterState(unsigned numCreatedOps, unsigned numUnresolvedMaterializations,
202                 unsigned numReplacements, unsigned numArgReplacements,
203                 unsigned numBlockActions, unsigned numIgnoredOperations,
204                 unsigned numRootUpdates)
205       : numCreatedOps(numCreatedOps),
206         numUnresolvedMaterializations(numUnresolvedMaterializations),
207         numReplacements(numReplacements),
208         numArgReplacements(numArgReplacements),
209         numBlockActions(numBlockActions),
210         numIgnoredOperations(numIgnoredOperations),
211         numRootUpdates(numRootUpdates) {}
212 
213   /// The current number of created operations.
214   unsigned numCreatedOps;
215 
216   /// The current number of unresolved materializations.
217   unsigned numUnresolvedMaterializations;
218 
219   /// The current number of replacements queued.
220   unsigned numReplacements;
221 
222   /// The current number of argument replacements queued.
223   unsigned numArgReplacements;
224 
225   /// The current number of block actions performed.
226   unsigned numBlockActions;
227 
228   /// The current number of ignored operations.
229   unsigned numIgnoredOperations;
230 
231   /// The current number of operations that were updated in place.
232   unsigned numRootUpdates;
233 };
234 
235 //===----------------------------------------------------------------------===//
236 // OperationTransactionState
237 
238 /// The state of an operation that was updated by a pattern in-place. This
239 /// contains all of the necessary information to reconstruct an operation that
240 /// was updated in place.
241 class OperationTransactionState {
242 public:
243   OperationTransactionState() = default;
244   OperationTransactionState(Operation *op)
245       : op(op), loc(op->getLoc()), attrs(op->getAttrDictionary()),
246         operands(op->operand_begin(), op->operand_end()),
247         successors(op->successor_begin(), op->successor_end()) {}
248 
249   /// Discard the transaction state and reset the state of the original
250   /// operation.
251   void resetOperation() const {
252     op->setLoc(loc);
253     op->setAttrs(attrs);
254     op->setOperands(operands);
255     for (auto it : llvm::enumerate(successors))
256       op->setSuccessor(it.value(), it.index());
257   }
258 
259   /// Return the original operation of this state.
260   Operation *getOperation() const { return op; }
261 
262 private:
263   Operation *op;
264   LocationAttr loc;
265   DictionaryAttr attrs;
266   SmallVector<Value, 8> operands;
267   SmallVector<Block *, 2> successors;
268 };
269 
270 //===----------------------------------------------------------------------===//
271 // OpReplacement
272 
273 /// This class represents one requested operation replacement via 'replaceOp' or
274 /// 'eraseOp`.
275 struct OpReplacement {
276   OpReplacement(TypeConverter *converter = nullptr) : converter(converter) {}
277 
278   /// An optional type converter that can be used to materialize conversions
279   /// between the new and old values if necessary.
280   TypeConverter *converter;
281 };
282 
283 //===----------------------------------------------------------------------===//
284 // BlockAction
285 
286 /// The kind of the block action performed during the rewrite.  Actions can be
287 /// undone if the conversion fails.
288 enum class BlockActionKind {
289   Create,
290   Erase,
291   Merge,
292   Move,
293   Split,
294   TypeConversion
295 };
296 
297 /// Original position of the given block in its parent region. During undo
298 /// actions, the block needs to be placed after `insertAfterBlock`.
299 struct BlockPosition {
300   Region *region;
301   Block *insertAfterBlock;
302 };
303 
304 /// Information needed to undo the merge actions.
305 /// - the source block, and
306 /// - the Operation that was the last operation in the dest block before the
307 ///   merge (could be null if the dest block was empty).
308 struct MergeInfo {
309   Block *sourceBlock;
310   Operation *destBlockLastInst;
311 };
312 
313 /// The storage class for an undoable block action (one of BlockActionKind),
314 /// contains the information necessary to undo this action.
315 struct BlockAction {
316   static BlockAction getCreate(Block *block) {
317     return {BlockActionKind::Create, block, {}};
318   }
319   static BlockAction getErase(Block *block, BlockPosition originalPosition) {
320     return {BlockActionKind::Erase, block, {originalPosition}};
321   }
322   static BlockAction getMerge(Block *block, Block *sourceBlock) {
323     BlockAction action{BlockActionKind::Merge, block, {}};
324     action.mergeInfo = {sourceBlock, block->empty() ? nullptr : &block->back()};
325     return action;
326   }
327   static BlockAction getMove(Block *block, BlockPosition originalPosition) {
328     return {BlockActionKind::Move, block, {originalPosition}};
329   }
330   static BlockAction getSplit(Block *block, Block *originalBlock) {
331     BlockAction action{BlockActionKind::Split, block, {}};
332     action.originalBlock = originalBlock;
333     return action;
334   }
335   static BlockAction getTypeConversion(Block *block) {
336     return BlockAction{BlockActionKind::TypeConversion, block, {}};
337   }
338 
339   // The action kind.
340   BlockActionKind kind;
341 
342   // A pointer to the block that was created by the action.
343   Block *block;
344 
345   union {
346     // In use if kind == BlockActionKind::Move or BlockActionKind::Erase, and
347     // contains a pointer to the region that originally contained the block as
348     // well as the position of the block in that region.
349     BlockPosition originalPosition;
350     // In use if kind == BlockActionKind::Split and contains a pointer to the
351     // block that was split into two parts.
352     Block *originalBlock;
353     // In use if kind == BlockActionKind::Merge, and contains the information
354     // needed to undo the merge.
355     MergeInfo mergeInfo;
356   };
357 };
358 
359 //===----------------------------------------------------------------------===//
360 // UnresolvedMaterialization
361 
362 /// This class represents an unresolved materialization, i.e. a materialization
363 /// that was inserted during conversion that needs to be legalized at the end of
364 /// the conversion process.
365 class UnresolvedMaterialization {
366 public:
367   /// The type of materialization.
368   enum Kind {
369     /// This materialization materializes a conversion for an illegal block
370     /// argument type, to a legal one.
371     Argument,
372 
373     /// This materialization materializes a conversion from an illegal type to a
374     /// legal one.
375     Target
376   };
377 
378   UnresolvedMaterialization(UnrealizedConversionCastOp op = nullptr,
379                             TypeConverter *converter = nullptr,
380                             Kind kind = Target, Type origOutputType = nullptr)
381       : op(op), converterAndKind(converter, kind),
382         origOutputType(origOutputType) {}
383 
384   /// Return the temporary conversion operation inserted for this
385   /// materialization.
386   UnrealizedConversionCastOp getOp() const { return op; }
387 
388   /// Return the type converter of this materialization (which may be null).
389   TypeConverter *getConverter() const { return converterAndKind.getPointer(); }
390 
391   /// Return the kind of this materialization.
392   Kind getKind() const { return converterAndKind.getInt(); }
393 
394   /// Set the kind of this materialization.
395   void setKind(Kind kind) { converterAndKind.setInt(kind); }
396 
397   /// Return the original illegal output type of the input values.
398   Type getOrigOutputType() const { return origOutputType; }
399 
400 private:
401   /// The unresolved materialization operation created during conversion.
402   UnrealizedConversionCastOp op;
403 
404   /// The corresponding type converter to use when resolving this
405   /// materialization, and the kind of this materialization.
406   llvm::PointerIntPair<TypeConverter *, 1, Kind> converterAndKind;
407 
408   /// The original output type. This is only used for argument conversions.
409   Type origOutputType;
410 };
411 } // namespace
412 
413 /// Build an unresolved materialization operation given an output type and set
414 /// of input operands.
415 static Value buildUnresolvedMaterialization(
416     UnresolvedMaterialization::Kind kind, Block *insertBlock,
417     Block::iterator insertPt, Location loc, ValueRange inputs, Type outputType,
418     Type origOutputType, TypeConverter *converter,
419     SmallVectorImpl<UnresolvedMaterialization> &unresolvedMaterializations) {
420   // Avoid materializing an unnecessary cast.
421   if (inputs.size() == 1 && inputs.front().getType() == outputType)
422     return inputs.front();
423 
424   // Create an unresolved materialization. We use a new OpBuilder to avoid
425   // tracking the materialization like we do for other operations.
426   OpBuilder builder(insertBlock, insertPt);
427   auto convertOp =
428       builder.create<UnrealizedConversionCastOp>(loc, outputType, inputs);
429   unresolvedMaterializations.emplace_back(convertOp, converter, kind,
430                                           origOutputType);
431   return convertOp.getResult(0);
432 }
433 static Value buildUnresolvedArgumentMaterialization(
434     PatternRewriter &rewriter, Location loc, ValueRange inputs,
435     Type origOutputType, Type outputType, TypeConverter *converter,
436     SmallVectorImpl<UnresolvedMaterialization> &unresolvedMaterializations) {
437   return buildUnresolvedMaterialization(
438       UnresolvedMaterialization::Argument, rewriter.getInsertionBlock(),
439       rewriter.getInsertionPoint(), loc, inputs, outputType, origOutputType,
440       converter, unresolvedMaterializations);
441 }
442 static Value buildUnresolvedTargetMaterialization(
443     Location loc, Value input, Type outputType, TypeConverter *converter,
444     SmallVectorImpl<UnresolvedMaterialization> &unresolvedMaterializations) {
445   Block *insertBlock = input.getParentBlock();
446   Block::iterator insertPt = insertBlock->begin();
447   if (OpResult inputRes = input.dyn_cast<OpResult>())
448     insertPt = ++inputRes.getOwner()->getIterator();
449 
450   return buildUnresolvedMaterialization(
451       UnresolvedMaterialization::Target, insertBlock, insertPt, loc, input,
452       outputType, outputType, converter, unresolvedMaterializations);
453 }
454 
455 //===----------------------------------------------------------------------===//
456 // ArgConverter
457 //===----------------------------------------------------------------------===//
458 namespace {
459 /// This class provides a simple interface for converting the types of block
460 /// arguments. This is done by creating a new block that contains the new legal
461 /// types and extracting the block that contains the old illegal types to allow
462 /// for undoing pending rewrites in the case of failure.
463 struct ArgConverter {
464   ArgConverter(
465       PatternRewriter &rewriter,
466       SmallVectorImpl<UnresolvedMaterialization> &unresolvedMaterializations)
467       : rewriter(rewriter),
468         unresolvedMaterializations(unresolvedMaterializations) {}
469 
470   /// This structure contains the information pertaining to an argument that has
471   /// been converted.
472   struct ConvertedArgInfo {
473     ConvertedArgInfo(unsigned newArgIdx, unsigned newArgSize,
474                      Value castValue = nullptr)
475         : newArgIdx(newArgIdx), newArgSize(newArgSize), castValue(castValue) {}
476 
477     /// The start index of in the new argument list that contains arguments that
478     /// replace the original.
479     unsigned newArgIdx;
480 
481     /// The number of arguments that replaced the original argument.
482     unsigned newArgSize;
483 
484     /// The cast value that was created to cast from the new arguments to the
485     /// old. This only used if 'newArgSize' > 1.
486     Value castValue;
487   };
488 
489   /// This structure contains information pertaining to a block that has had its
490   /// signature converted.
491   struct ConvertedBlockInfo {
492     ConvertedBlockInfo(Block *origBlock, TypeConverter *converter)
493         : origBlock(origBlock), converter(converter) {}
494 
495     /// The original block that was requested to have its signature converted.
496     Block *origBlock;
497 
498     /// The conversion information for each of the arguments. The information is
499     /// None if the argument was dropped during conversion.
500     SmallVector<Optional<ConvertedArgInfo>, 1> argInfo;
501 
502     /// The type converter used to convert the arguments.
503     TypeConverter *converter;
504   };
505 
506   /// Return if the signature of the given block has already been converted.
507   bool hasBeenConverted(Block *block) const {
508     return conversionInfo.count(block) || convertedBlocks.count(block);
509   }
510 
511   /// Set the type converter to use for the given region.
512   void setConverter(Region *region, TypeConverter *typeConverter) {
513     assert(typeConverter && "expected valid type converter");
514     regionToConverter[region] = typeConverter;
515   }
516 
517   /// Return the type converter to use for the given region, or null if there
518   /// isn't one.
519   TypeConverter *getConverter(Region *region) {
520     return regionToConverter.lookup(region);
521   }
522 
523   //===--------------------------------------------------------------------===//
524   // Rewrite Application
525   //===--------------------------------------------------------------------===//
526 
527   /// Erase any rewrites registered for the blocks within the given operation
528   /// which is about to be removed. This merely drops the rewrites without
529   /// undoing them.
530   void notifyOpRemoved(Operation *op);
531 
532   /// Cleanup and undo any generated conversions for the arguments of block.
533   /// This method replaces the new block with the original, reverting the IR to
534   /// its original state.
535   void discardRewrites(Block *block);
536 
537   /// Fully replace uses of the old arguments with the new.
538   void applyRewrites(ConversionValueMapping &mapping);
539 
540   /// Materialize any necessary conversions for converted arguments that have
541   /// live users, using the provided `findLiveUser` to search for a user that
542   /// survives the conversion process.
543   LogicalResult
544   materializeLiveConversions(ConversionValueMapping &mapping,
545                              OpBuilder &builder,
546                              function_ref<Operation *(Value)> findLiveUser);
547 
548   //===--------------------------------------------------------------------===//
549   // Conversion
550   //===--------------------------------------------------------------------===//
551 
552   /// Attempt to convert the signature of the given block, if successful a new
553   /// block is returned containing the new arguments. Returns `block` if it did
554   /// not require conversion.
555   FailureOr<Block *>
556   convertSignature(Block *block, TypeConverter *converter,
557                    ConversionValueMapping &mapping,
558                    SmallVectorImpl<BlockArgument> &argReplacements);
559 
560   /// Apply the given signature conversion on the given block. The new block
561   /// containing the updated signature is returned. If no conversions were
562   /// necessary, e.g. if the block has no arguments, `block` is returned.
563   /// `converter` is used to generate any necessary cast operations that
564   /// translate between the origin argument types and those specified in the
565   /// signature conversion.
566   Block *applySignatureConversion(
567       Block *block, TypeConverter *converter,
568       TypeConverter::SignatureConversion &signatureConversion,
569       ConversionValueMapping &mapping,
570       SmallVectorImpl<BlockArgument> &argReplacements);
571 
572   /// Insert a new conversion into the cache.
573   void insertConversion(Block *newBlock, ConvertedBlockInfo &&info);
574 
575   /// A collection of blocks that have had their arguments converted. This is a
576   /// map from the new replacement block, back to the original block.
577   llvm::MapVector<Block *, ConvertedBlockInfo> conversionInfo;
578 
579   /// The set of original blocks that were converted.
580   DenseSet<Block *> convertedBlocks;
581 
582   /// A mapping from valid regions, to those containing the original blocks of a
583   /// conversion.
584   DenseMap<Region *, std::unique_ptr<Region>> regionMapping;
585 
586   /// A mapping of regions to type converters that should be used when
587   /// converting the arguments of blocks within that region.
588   DenseMap<Region *, TypeConverter *> regionToConverter;
589 
590   /// The pattern rewriter to use when materializing conversions.
591   PatternRewriter &rewriter;
592 
593   /// An ordered set of unresolved materializations during conversion.
594   SmallVectorImpl<UnresolvedMaterialization> &unresolvedMaterializations;
595 };
596 } // namespace
597 
598 //===----------------------------------------------------------------------===//
599 // Rewrite Application
600 
601 void ArgConverter::notifyOpRemoved(Operation *op) {
602   if (conversionInfo.empty())
603     return;
604 
605   for (Region &region : op->getRegions()) {
606     for (Block &block : region) {
607       // Drop any rewrites from within.
608       for (Operation &nestedOp : block)
609         if (nestedOp.getNumRegions())
610           notifyOpRemoved(&nestedOp);
611 
612       // Check if this block was converted.
613       auto it = conversionInfo.find(&block);
614       if (it == conversionInfo.end())
615         continue;
616 
617       // Drop all uses of the original arguments and delete the original block.
618       Block *origBlock = it->second.origBlock;
619       for (BlockArgument arg : origBlock->getArguments())
620         arg.dropAllUses();
621       conversionInfo.erase(it);
622     }
623   }
624 }
625 
626 void ArgConverter::discardRewrites(Block *block) {
627   auto it = conversionInfo.find(block);
628   if (it == conversionInfo.end())
629     return;
630   Block *origBlock = it->second.origBlock;
631 
632   // Drop all uses of the new block arguments and replace uses of the new block.
633   for (int i = block->getNumArguments() - 1; i >= 0; --i)
634     block->getArgument(i).dropAllUses();
635   block->replaceAllUsesWith(origBlock);
636 
637   // Move the operations back the original block and the delete the new block.
638   origBlock->getOperations().splice(origBlock->end(), block->getOperations());
639   origBlock->moveBefore(block);
640   block->erase();
641 
642   convertedBlocks.erase(origBlock);
643   conversionInfo.erase(it);
644 }
645 
646 void ArgConverter::applyRewrites(ConversionValueMapping &mapping) {
647   for (auto &info : conversionInfo) {
648     ConvertedBlockInfo &blockInfo = info.second;
649     Block *origBlock = blockInfo.origBlock;
650 
651     // Process the remapping for each of the original arguments.
652     for (unsigned i = 0, e = origBlock->getNumArguments(); i != e; ++i) {
653       Optional<ConvertedArgInfo> &argInfo = blockInfo.argInfo[i];
654       BlockArgument origArg = origBlock->getArgument(i);
655 
656       // Handle the case of a 1->0 value mapping.
657       if (!argInfo) {
658         if (Value newArg = mapping.lookupOrNull(origArg, origArg.getType()))
659           origArg.replaceAllUsesWith(newArg);
660         continue;
661       }
662 
663       // Otherwise this is a 1->1+ value mapping.
664       Value castValue = argInfo->castValue;
665       assert(argInfo->newArgSize >= 1 && castValue && "expected 1->1+ mapping");
666 
667       // If the argument is still used, replace it with the generated cast.
668       if (!origArg.use_empty()) {
669         origArg.replaceAllUsesWith(
670             mapping.lookupOrDefault(castValue, origArg.getType()));
671       }
672     }
673   }
674 }
675 
676 LogicalResult ArgConverter::materializeLiveConversions(
677     ConversionValueMapping &mapping, OpBuilder &builder,
678     function_ref<Operation *(Value)> findLiveUser) {
679   for (auto &info : conversionInfo) {
680     Block *newBlock = info.first;
681     ConvertedBlockInfo &blockInfo = info.second;
682     Block *origBlock = blockInfo.origBlock;
683 
684     // Process the remapping for each of the original arguments.
685     for (unsigned i = 0, e = origBlock->getNumArguments(); i != e; ++i) {
686       // If the type of this argument changed and the argument is still live, we
687       // need to materialize a conversion.
688       BlockArgument origArg = origBlock->getArgument(i);
689       if (mapping.lookupOrNull(origArg, origArg.getType()))
690         continue;
691       Operation *liveUser = findLiveUser(origArg);
692       if (!liveUser)
693         continue;
694 
695       Value replacementValue = mapping.lookupOrDefault(origArg);
696       bool isDroppedArg = replacementValue == origArg;
697       if (isDroppedArg)
698         rewriter.setInsertionPointToStart(newBlock);
699       else
700         rewriter.setInsertionPointAfterValue(replacementValue);
701       Value newArg;
702       if (blockInfo.converter) {
703         newArg = blockInfo.converter->materializeSourceConversion(
704             rewriter, origArg.getLoc(), origArg.getType(),
705             isDroppedArg ? ValueRange() : ValueRange(replacementValue));
706         assert((!newArg || newArg.getType() == origArg.getType()) &&
707                "materialization hook did not provide a value of the expected "
708                "type");
709       }
710       if (!newArg) {
711         InFlightDiagnostic diag =
712             emitError(origArg.getLoc())
713             << "failed to materialize conversion for block argument #" << i
714             << " that remained live after conversion, type was "
715             << origArg.getType();
716         if (!isDroppedArg)
717           diag << ", with target type " << replacementValue.getType();
718         diag.attachNote(liveUser->getLoc())
719             << "see existing live user here: " << *liveUser;
720         return failure();
721       }
722       mapping.map(origArg, newArg);
723     }
724   }
725   return success();
726 }
727 
728 //===----------------------------------------------------------------------===//
729 // Conversion
730 
731 FailureOr<Block *> ArgConverter::convertSignature(
732     Block *block, TypeConverter *converter, ConversionValueMapping &mapping,
733     SmallVectorImpl<BlockArgument> &argReplacements) {
734   // Check if the block was already converted. If the block is detached,
735   // conservatively assume it is going to be deleted.
736   if (hasBeenConverted(block) || !block->getParent())
737     return block;
738   // If a converter wasn't provided, and the block wasn't already converted,
739   // there is nothing we can do.
740   if (!converter)
741     return failure();
742 
743   // Try to convert the signature for the block with the provided converter.
744   if (auto conversion = converter->convertBlockSignature(block))
745     return applySignatureConversion(block, converter, *conversion, mapping,
746                                     argReplacements);
747   return failure();
748 }
749 
750 Block *ArgConverter::applySignatureConversion(
751     Block *block, TypeConverter *converter,
752     TypeConverter::SignatureConversion &signatureConversion,
753     ConversionValueMapping &mapping,
754     SmallVectorImpl<BlockArgument> &argReplacements) {
755   // If no arguments are being changed or added, there is nothing to do.
756   unsigned origArgCount = block->getNumArguments();
757   auto convertedTypes = signatureConversion.getConvertedTypes();
758   if (origArgCount == 0 && convertedTypes.empty())
759     return block;
760 
761   // Split the block at the beginning to get a new block to use for the updated
762   // signature.
763   Block *newBlock = block->splitBlock(block->begin());
764   block->replaceAllUsesWith(newBlock);
765 
766   SmallVector<Value, 4> newArgRange(newBlock->addArguments(convertedTypes));
767   ArrayRef<Value> newArgs(newArgRange);
768 
769   // Remap each of the original arguments as determined by the signature
770   // conversion.
771   ConvertedBlockInfo info(block, converter);
772   info.argInfo.resize(origArgCount);
773 
774   OpBuilder::InsertionGuard guard(rewriter);
775   rewriter.setInsertionPointToStart(newBlock);
776   for (unsigned i = 0; i != origArgCount; ++i) {
777     auto inputMap = signatureConversion.getInputMapping(i);
778     if (!inputMap)
779       continue;
780     BlockArgument origArg = block->getArgument(i);
781 
782     // If inputMap->replacementValue is not nullptr, then the argument is
783     // dropped and a replacement value is provided to be the remappedValue.
784     if (inputMap->replacementValue) {
785       assert(inputMap->size == 0 &&
786              "invalid to provide a replacement value when the argument isn't "
787              "dropped");
788       mapping.map(origArg, inputMap->replacementValue);
789       argReplacements.push_back(origArg);
790       continue;
791     }
792 
793     // Otherwise, this is a 1->1+ mapping.
794     auto replArgs = newArgs.slice(inputMap->inputNo, inputMap->size);
795     Value newArg;
796 
797     // If this is a 1->1 mapping and the types of new and replacement arguments
798     // match (i.e. it's an identity map), then the argument is mapped to its
799     // original type.
800     // FIXME: We simply pass through the replacement argument if there wasn't a
801     // converter, which isn't great as it allows implicit type conversions to
802     // appear. We should properly restructure this code to handle cases where a
803     // converter isn't provided and also to properly handle the case where an
804     // argument materialization is actually a temporary source materialization
805     // (e.g. in the case of 1->N).
806     if (replArgs.size() == 1 &&
807         (!converter || replArgs[0].getType() == origArg.getType())) {
808       newArg = replArgs.front();
809     } else {
810       Type origOutputType = origArg.getType();
811 
812       // Legalize the argument output type.
813       Type outputType = origOutputType;
814       if (Type legalOutputType = converter->convertType(outputType))
815         outputType = legalOutputType;
816 
817       newArg = buildUnresolvedArgumentMaterialization(
818           rewriter, origArg.getLoc(), replArgs, origOutputType, outputType,
819           converter, unresolvedMaterializations);
820     }
821 
822     mapping.map(origArg, newArg);
823     argReplacements.push_back(origArg);
824     info.argInfo[i] =
825         ConvertedArgInfo(inputMap->inputNo, inputMap->size, newArg);
826   }
827 
828   // Remove the original block from the region and return the new one.
829   insertConversion(newBlock, std::move(info));
830   return newBlock;
831 }
832 
833 void ArgConverter::insertConversion(Block *newBlock,
834                                     ConvertedBlockInfo &&info) {
835   // Get a region to insert the old block.
836   Region *region = newBlock->getParent();
837   std::unique_ptr<Region> &mappedRegion = regionMapping[region];
838   if (!mappedRegion)
839     mappedRegion = std::make_unique<Region>(region->getParentOp());
840 
841   // Move the original block to the mapped region and emplace the conversion.
842   mappedRegion->getBlocks().splice(mappedRegion->end(), region->getBlocks(),
843                                    info.origBlock->getIterator());
844   convertedBlocks.insert(info.origBlock);
845   conversionInfo.insert({newBlock, std::move(info)});
846 }
847 
848 //===----------------------------------------------------------------------===//
849 // ConversionPatternRewriterImpl
850 //===----------------------------------------------------------------------===//
851 namespace mlir {
852 namespace detail {
853 struct ConversionPatternRewriterImpl {
854   explicit ConversionPatternRewriterImpl(PatternRewriter &rewriter)
855       : argConverter(rewriter, unresolvedMaterializations),
856         notifyCallback(nullptr) {}
857 
858   /// Cleanup and destroy any generated rewrite operations. This method is
859   /// invoked when the conversion process fails.
860   void discardRewrites();
861 
862   /// Apply all requested operation rewrites. This method is invoked when the
863   /// conversion process succeeds.
864   void applyRewrites();
865 
866   //===--------------------------------------------------------------------===//
867   // State Management
868   //===--------------------------------------------------------------------===//
869 
870   /// Return the current state of the rewriter.
871   RewriterState getCurrentState();
872 
873   /// Reset the state of the rewriter to a previously saved point.
874   void resetState(RewriterState state);
875 
876   /// Erase any blocks that were unlinked from their regions and stored in block
877   /// actions.
878   void eraseDanglingBlocks();
879 
880   /// Undo the block actions (motions, splits) one by one in reverse order until
881   /// "numActionsToKeep" actions remains.
882   void undoBlockActions(unsigned numActionsToKeep = 0);
883 
884   /// Remap the given values to those with potentially different types. Returns
885   /// success if the values could be remapped, failure otherwise. `valueDiagTag`
886   /// is the tag used when describing a value within a diagnostic, e.g.
887   /// "operand".
888   LogicalResult remapValues(StringRef valueDiagTag, Optional<Location> inputLoc,
889                             PatternRewriter &rewriter, ValueRange values,
890                             SmallVectorImpl<Value> &remapped);
891 
892   /// Returns true if the given operation is ignored, and does not need to be
893   /// converted.
894   bool isOpIgnored(Operation *op) const;
895 
896   /// Recursively marks the nested operations under 'op' as ignored. This
897   /// removes them from being considered for legalization.
898   void markNestedOpsIgnored(Operation *op);
899 
900   //===--------------------------------------------------------------------===//
901   // Type Conversion
902   //===--------------------------------------------------------------------===//
903 
904   /// Convert the signature of the given block.
905   FailureOr<Block *> convertBlockSignature(
906       Block *block, TypeConverter *converter,
907       TypeConverter::SignatureConversion *conversion = nullptr);
908 
909   /// Apply a signature conversion on the given region, using `converter` for
910   /// materializations if not null.
911   Block *
912   applySignatureConversion(Region *region,
913                            TypeConverter::SignatureConversion &conversion,
914                            TypeConverter *converter);
915 
916   /// Convert the types of block arguments within the given region.
917   FailureOr<Block *>
918   convertRegionTypes(Region *region, TypeConverter &converter,
919                      TypeConverter::SignatureConversion *entryConversion);
920 
921   /// Convert the types of non-entry block arguments within the given region.
922   LogicalResult convertNonEntryRegionTypes(
923       Region *region, TypeConverter &converter,
924       ArrayRef<TypeConverter::SignatureConversion> blockConversions = {});
925 
926   //===--------------------------------------------------------------------===//
927   // Rewriter Notification Hooks
928   //===--------------------------------------------------------------------===//
929 
930   /// PatternRewriter hook for replacing the results of an operation.
931   void notifyOpReplaced(Operation *op, ValueRange newValues);
932 
933   /// Notifies that a block is about to be erased.
934   void notifyBlockIsBeingErased(Block *block);
935 
936   /// Notifies that a block was created.
937   void notifyCreatedBlock(Block *block);
938 
939   /// Notifies that a block was split.
940   void notifySplitBlock(Block *block, Block *continuation);
941 
942   /// Notifies that `block` is being merged with `srcBlock`.
943   void notifyBlocksBeingMerged(Block *block, Block *srcBlock);
944 
945   /// Notifies that the blocks of a region are about to be moved.
946   void notifyRegionIsBeingInlinedBefore(Region &region, Region &parent,
947                                         Region::iterator before);
948 
949   /// Notifies that the blocks of a region were cloned into another.
950   void notifyRegionWasClonedBefore(iterator_range<Region::iterator> &blocks,
951                                    Location origRegionLoc);
952 
953   /// Notifies that a pattern match failed for the given reason.
954   LogicalResult
955   notifyMatchFailure(Location loc,
956                      function_ref<void(Diagnostic &)> reasonCallback);
957 
958   //===--------------------------------------------------------------------===//
959   // State
960   //===--------------------------------------------------------------------===//
961 
962   // Mapping between replaced values that differ in type. This happens when
963   // replacing a value with one of a different type.
964   ConversionValueMapping mapping;
965 
966   /// Utility used to convert block arguments.
967   ArgConverter argConverter;
968 
969   /// Ordered vector of all of the newly created operations during conversion.
970   SmallVector<Operation *> createdOps;
971 
972   /// Ordered vector of all unresolved type conversion materializations during
973   /// conversion.
974   SmallVector<UnresolvedMaterialization> unresolvedMaterializations;
975 
976   /// Ordered map of requested operation replacements.
977   llvm::MapVector<Operation *, OpReplacement> replacements;
978 
979   /// Ordered vector of any requested block argument replacements.
980   SmallVector<BlockArgument, 4> argReplacements;
981 
982   /// Ordered list of block operations (creations, splits, motions).
983   SmallVector<BlockAction, 4> blockActions;
984 
985   /// A set of operations that should no longer be considered for legalization,
986   /// but were not directly replace/erased/etc. by a pattern. These are
987   /// generally child operations of other operations who were
988   /// replaced/erased/etc. This is not meant to be an exhaustive list of all
989   /// operations, but the minimal set that can be used to detect if a given
990   /// operation should be `ignored`. For example, we may add the operations that
991   /// define non-empty regions to the set, but not any of the others. This
992   /// simplifies the amount of memory needed as we can query if the parent
993   /// operation was ignored.
994   SetVector<Operation *> ignoredOps;
995 
996   /// A transaction state for each of operations that were updated in-place.
997   SmallVector<OperationTransactionState, 4> rootUpdates;
998 
999   /// A vector of indices into `replacements` of operations that were replaced
1000   /// with values with different result types than the original operation, e.g.
1001   /// 1->N conversion of some kind.
1002   SmallVector<unsigned, 4> operationsWithChangedResults;
1003 
1004   /// The current type converter, or nullptr if no type converter is currently
1005   /// active.
1006   TypeConverter *currentTypeConverter = nullptr;
1007 
1008   /// This allows the user to collect the match failure message.
1009   function_ref<void(Diagnostic &)> notifyCallback;
1010 
1011 #ifndef NDEBUG
1012   /// A set of operations that have pending updates. This tracking isn't
1013   /// strictly necessary, and is thus only active during debug builds for extra
1014   /// verification.
1015   SmallPtrSet<Operation *, 1> pendingRootUpdates;
1016 
1017   /// A logger used to emit diagnostics during the conversion process.
1018   llvm::ScopedPrinter logger{llvm::dbgs()};
1019 #endif
1020 };
1021 } // namespace detail
1022 } // namespace mlir
1023 
1024 /// Detach any operations nested in the given operation from their parent
1025 /// blocks, and erase the given operation. This can be used when the nested
1026 /// operations are scheduled for erasure themselves, so deleting the regions of
1027 /// the given operation together with their content would result in double-free.
1028 /// This happens, for example, when rolling back op creation in the reverse
1029 /// order and if the nested ops were created before the parent op. This function
1030 /// does not need to collect nested ops recursively because it is expected to
1031 /// also be called for each nested op when it is about to be deleted.
1032 static void detachNestedAndErase(Operation *op) {
1033   for (Region &region : op->getRegions()) {
1034     for (Block &block : region.getBlocks()) {
1035       while (!block.getOperations().empty())
1036         block.getOperations().remove(block.getOperations().begin());
1037       block.dropAllDefinedValueUses();
1038     }
1039   }
1040   op->dropAllUses();
1041   op->erase();
1042 }
1043 
1044 void ConversionPatternRewriterImpl::discardRewrites() {
1045   // Reset any operations that were updated in place.
1046   for (auto &state : rootUpdates)
1047     state.resetOperation();
1048 
1049   undoBlockActions();
1050 
1051   // Remove any newly created ops.
1052   for (UnresolvedMaterialization &materialization : unresolvedMaterializations)
1053     detachNestedAndErase(materialization.getOp());
1054   for (auto *op : llvm::reverse(createdOps))
1055     detachNestedAndErase(op);
1056 }
1057 
1058 void ConversionPatternRewriterImpl::applyRewrites() {
1059   // Apply all of the rewrites replacements requested during conversion.
1060   for (auto &repl : replacements) {
1061     for (OpResult result : repl.first->getResults())
1062       if (Value newValue = mapping.lookupOrNull(result, result.getType()))
1063         result.replaceAllUsesWith(newValue);
1064 
1065     // If this operation defines any regions, drop any pending argument
1066     // rewrites.
1067     if (repl.first->getNumRegions())
1068       argConverter.notifyOpRemoved(repl.first);
1069   }
1070 
1071   // Apply all of the requested argument replacements.
1072   for (BlockArgument arg : argReplacements) {
1073     Value repl = mapping.lookupOrNull(arg, arg.getType());
1074     if (!repl)
1075       continue;
1076 
1077     if (repl.isa<BlockArgument>()) {
1078       arg.replaceAllUsesWith(repl);
1079       continue;
1080     }
1081 
1082     // If the replacement value is an operation, we check to make sure that we
1083     // don't replace uses that are within the parent operation of the
1084     // replacement value.
1085     Operation *replOp = repl.cast<OpResult>().getOwner();
1086     Block *replBlock = replOp->getBlock();
1087     arg.replaceUsesWithIf(repl, [&](OpOperand &operand) {
1088       Operation *user = operand.getOwner();
1089       return user->getBlock() != replBlock || replOp->isBeforeInBlock(user);
1090     });
1091   }
1092 
1093   // Drop all of the unresolved materialization operations created during
1094   // conversion.
1095   for (auto &mat : unresolvedMaterializations) {
1096     mat.getOp()->dropAllUses();
1097     mat.getOp()->erase();
1098   }
1099 
1100   // In a second pass, erase all of the replaced operations in reverse. This
1101   // allows processing nested operations before their parent region is
1102   // destroyed. Because we process in reverse order, producers may be deleted
1103   // before their users (a pattern deleting a producer and then the consumer)
1104   // so we first drop all uses explicitly.
1105   for (auto &repl : llvm::reverse(replacements)) {
1106     repl.first->dropAllUses();
1107     repl.first->erase();
1108   }
1109 
1110   argConverter.applyRewrites(mapping);
1111 
1112   // Now that the ops have been erased, also erase dangling blocks.
1113   eraseDanglingBlocks();
1114 }
1115 
1116 //===----------------------------------------------------------------------===//
1117 // State Management
1118 
1119 RewriterState ConversionPatternRewriterImpl::getCurrentState() {
1120   return RewriterState(createdOps.size(), unresolvedMaterializations.size(),
1121                        replacements.size(), argReplacements.size(),
1122                        blockActions.size(), ignoredOps.size(),
1123                        rootUpdates.size());
1124 }
1125 
1126 void ConversionPatternRewriterImpl::resetState(RewriterState state) {
1127   // Reset any operations that were updated in place.
1128   for (unsigned i = state.numRootUpdates, e = rootUpdates.size(); i != e; ++i)
1129     rootUpdates[i].resetOperation();
1130   rootUpdates.resize(state.numRootUpdates);
1131 
1132   // Reset any replaced arguments.
1133   for (BlockArgument replacedArg :
1134        llvm::drop_begin(argReplacements, state.numArgReplacements))
1135     mapping.erase(replacedArg);
1136   argReplacements.resize(state.numArgReplacements);
1137 
1138   // Undo any block actions.
1139   undoBlockActions(state.numBlockActions);
1140 
1141   // Reset any replaced operations and undo any saved mappings.
1142   for (auto &repl : llvm::drop_begin(replacements, state.numReplacements))
1143     for (auto result : repl.first->getResults())
1144       mapping.erase(result);
1145   while (replacements.size() != state.numReplacements)
1146     replacements.pop_back();
1147 
1148   // Pop all of the newly inserted materializations.
1149   while (unresolvedMaterializations.size() !=
1150          state.numUnresolvedMaterializations) {
1151     UnresolvedMaterialization mat = unresolvedMaterializations.pop_back_val();
1152     UnrealizedConversionCastOp op = mat.getOp();
1153 
1154     // If this was a target materialization, drop the mapping that was inserted.
1155     if (mat.getKind() == UnresolvedMaterialization::Target) {
1156       for (Value input : op->getOperands())
1157         mapping.erase(input);
1158     }
1159     detachNestedAndErase(op);
1160   }
1161 
1162   // Pop all of the newly created operations.
1163   while (createdOps.size() != state.numCreatedOps) {
1164     detachNestedAndErase(createdOps.back());
1165     createdOps.pop_back();
1166   }
1167 
1168   // Pop all of the recorded ignored operations that are no longer valid.
1169   while (ignoredOps.size() != state.numIgnoredOperations)
1170     ignoredOps.pop_back();
1171 
1172   // Reset operations with changed results.
1173   while (!operationsWithChangedResults.empty() &&
1174          operationsWithChangedResults.back() >= state.numReplacements)
1175     operationsWithChangedResults.pop_back();
1176 }
1177 
1178 void ConversionPatternRewriterImpl::eraseDanglingBlocks() {
1179   for (auto &action : blockActions)
1180     if (action.kind == BlockActionKind::Erase)
1181       delete action.block;
1182 }
1183 
1184 void ConversionPatternRewriterImpl::undoBlockActions(
1185     unsigned numActionsToKeep) {
1186   for (auto &action :
1187        llvm::reverse(llvm::drop_begin(blockActions, numActionsToKeep))) {
1188     switch (action.kind) {
1189     // Delete the created block.
1190     case BlockActionKind::Create: {
1191       // Unlink all of the operations within this block, they will be deleted
1192       // separately.
1193       auto &blockOps = action.block->getOperations();
1194       while (!blockOps.empty())
1195         blockOps.remove(blockOps.begin());
1196       action.block->dropAllDefinedValueUses();
1197       action.block->erase();
1198       break;
1199     }
1200     // Put the block (owned by action) back into its original position.
1201     case BlockActionKind::Erase: {
1202       auto &blockList = action.originalPosition.region->getBlocks();
1203       Block *insertAfterBlock = action.originalPosition.insertAfterBlock;
1204       blockList.insert((insertAfterBlock
1205                             ? std::next(Region::iterator(insertAfterBlock))
1206                             : blockList.begin()),
1207                        action.block);
1208       break;
1209     }
1210     // Split the block at the position which was originally the end of the
1211     // destination block (owned by action), and put the instructions back into
1212     // the block used before the merge.
1213     case BlockActionKind::Merge: {
1214       Block *sourceBlock = action.mergeInfo.sourceBlock;
1215       Block::iterator splitPoint =
1216           (action.mergeInfo.destBlockLastInst
1217                ? ++Block::iterator(action.mergeInfo.destBlockLastInst)
1218                : action.block->begin());
1219       sourceBlock->getOperations().splice(sourceBlock->begin(),
1220                                           action.block->getOperations(),
1221                                           splitPoint, action.block->end());
1222       break;
1223     }
1224     // Move the block back to its original position.
1225     case BlockActionKind::Move: {
1226       Region *originalRegion = action.originalPosition.region;
1227       Block *insertAfterBlock = action.originalPosition.insertAfterBlock;
1228       originalRegion->getBlocks().splice(
1229           (insertAfterBlock ? std::next(Region::iterator(insertAfterBlock))
1230                             : originalRegion->end()),
1231           action.block->getParent()->getBlocks(), action.block);
1232       break;
1233     }
1234     // Merge back the block that was split out.
1235     case BlockActionKind::Split: {
1236       action.originalBlock->getOperations().splice(
1237           action.originalBlock->end(), action.block->getOperations());
1238       action.block->dropAllDefinedValueUses();
1239       action.block->erase();
1240       break;
1241     }
1242     // Undo the type conversion.
1243     case BlockActionKind::TypeConversion: {
1244       argConverter.discardRewrites(action.block);
1245       break;
1246     }
1247     }
1248   }
1249   blockActions.resize(numActionsToKeep);
1250 }
1251 
1252 LogicalResult ConversionPatternRewriterImpl::remapValues(
1253     StringRef valueDiagTag, Optional<Location> inputLoc,
1254     PatternRewriter &rewriter, ValueRange values,
1255     SmallVectorImpl<Value> &remapped) {
1256   remapped.reserve(llvm::size(values));
1257 
1258   SmallVector<Type, 1> legalTypes;
1259   for (auto it : llvm::enumerate(values)) {
1260     Value operand = it.value();
1261     Type origType = operand.getType();
1262 
1263     // If a converter was provided, get the desired legal types for this
1264     // operand.
1265     Type desiredType;
1266     if (currentTypeConverter) {
1267       // If there is no legal conversion, fail to match this pattern.
1268       legalTypes.clear();
1269       if (failed(currentTypeConverter->convertType(origType, legalTypes))) {
1270         Location operandLoc = inputLoc ? *inputLoc : operand.getLoc();
1271         return notifyMatchFailure(operandLoc, [=](Diagnostic &diag) {
1272           diag << "unable to convert type for " << valueDiagTag << " #"
1273                << it.index() << ", type was " << origType;
1274         });
1275       }
1276       // TODO: There currently isn't any mechanism to do 1->N type conversion
1277       // via the PatternRewriter replacement API, so for now we just ignore it.
1278       if (legalTypes.size() == 1)
1279         desiredType = legalTypes.front();
1280     } else {
1281       // TODO: What we should do here is just set `desiredType` to `origType`
1282       // and then handle the necessary type conversions after the conversion
1283       // process has finished. Unfortunately a lot of patterns currently rely on
1284       // receiving the new operands even if the types change, so we keep the
1285       // original behavior here for now until all of the patterns relying on
1286       // this get updated.
1287     }
1288     Value newOperand = mapping.lookupOrDefault(operand, desiredType);
1289 
1290     // Handle the case where the conversion was 1->1 and the new operand type
1291     // isn't legal.
1292     Type newOperandType = newOperand.getType();
1293     if (currentTypeConverter && desiredType && newOperandType != desiredType) {
1294       Location operandLoc = inputLoc ? *inputLoc : operand.getLoc();
1295       Value castValue = buildUnresolvedTargetMaterialization(
1296           operandLoc, newOperand, desiredType, currentTypeConverter,
1297           unresolvedMaterializations);
1298       mapping.map(mapping.lookupOrDefault(newOperand), castValue);
1299       newOperand = castValue;
1300     }
1301     remapped.push_back(newOperand);
1302   }
1303   return success();
1304 }
1305 
1306 bool ConversionPatternRewriterImpl::isOpIgnored(Operation *op) const {
1307   // Check to see if this operation was replaced or its parent ignored.
1308   return replacements.count(op) || ignoredOps.count(op->getParentOp());
1309 }
1310 
1311 void ConversionPatternRewriterImpl::markNestedOpsIgnored(Operation *op) {
1312   // Walk this operation and collect nested operations that define non-empty
1313   // regions. We mark such operations as 'ignored' so that we know we don't have
1314   // to convert them, or their nested ops.
1315   if (op->getNumRegions() == 0)
1316     return;
1317   op->walk([&](Operation *op) {
1318     if (llvm::any_of(op->getRegions(),
1319                      [](Region &region) { return !region.empty(); }))
1320       ignoredOps.insert(op);
1321   });
1322 }
1323 
1324 //===----------------------------------------------------------------------===//
1325 // Type Conversion
1326 
1327 FailureOr<Block *> ConversionPatternRewriterImpl::convertBlockSignature(
1328     Block *block, TypeConverter *converter,
1329     TypeConverter::SignatureConversion *conversion) {
1330   FailureOr<Block *> result =
1331       conversion ? argConverter.applySignatureConversion(
1332                        block, converter, *conversion, mapping, argReplacements)
1333                  : argConverter.convertSignature(block, converter, mapping,
1334                                                  argReplacements);
1335   if (failed(result))
1336     return failure();
1337   if (Block *newBlock = result.getValue()) {
1338     if (newBlock != block)
1339       blockActions.push_back(BlockAction::getTypeConversion(newBlock));
1340   }
1341   return result;
1342 }
1343 
1344 Block *ConversionPatternRewriterImpl::applySignatureConversion(
1345     Region *region, TypeConverter::SignatureConversion &conversion,
1346     TypeConverter *converter) {
1347   if (!region->empty())
1348     return *convertBlockSignature(&region->front(), converter, &conversion);
1349   return nullptr;
1350 }
1351 
1352 FailureOr<Block *> ConversionPatternRewriterImpl::convertRegionTypes(
1353     Region *region, TypeConverter &converter,
1354     TypeConverter::SignatureConversion *entryConversion) {
1355   argConverter.setConverter(region, &converter);
1356   if (region->empty())
1357     return nullptr;
1358 
1359   if (failed(convertNonEntryRegionTypes(region, converter)))
1360     return failure();
1361 
1362   FailureOr<Block *> newEntry =
1363       convertBlockSignature(&region->front(), &converter, entryConversion);
1364   return newEntry;
1365 }
1366 
1367 LogicalResult ConversionPatternRewriterImpl::convertNonEntryRegionTypes(
1368     Region *region, TypeConverter &converter,
1369     ArrayRef<TypeConverter::SignatureConversion> blockConversions) {
1370   argConverter.setConverter(region, &converter);
1371   if (region->empty())
1372     return success();
1373 
1374   // Convert the arguments of each block within the region.
1375   int blockIdx = 0;
1376   assert((blockConversions.empty() ||
1377           blockConversions.size() == region->getBlocks().size() - 1) &&
1378          "expected either to provide no SignatureConversions at all or to "
1379          "provide a SignatureConversion for each non-entry block");
1380 
1381   for (Block &block :
1382        llvm::make_early_inc_range(llvm::drop_begin(*region, 1))) {
1383     TypeConverter::SignatureConversion *blockConversion =
1384         blockConversions.empty()
1385             ? nullptr
1386             : const_cast<TypeConverter::SignatureConversion *>(
1387                   &blockConversions[blockIdx++]);
1388 
1389     if (failed(convertBlockSignature(&block, &converter, blockConversion)))
1390       return failure();
1391   }
1392   return success();
1393 }
1394 
1395 //===----------------------------------------------------------------------===//
1396 // Rewriter Notification Hooks
1397 
1398 void ConversionPatternRewriterImpl::notifyOpReplaced(Operation *op,
1399                                                      ValueRange newValues) {
1400   assert(newValues.size() == op->getNumResults());
1401   assert(!replacements.count(op) && "operation was already replaced");
1402 
1403   // Track if any of the results changed, e.g. erased and replaced with null.
1404   bool resultChanged = false;
1405 
1406   // Create mappings for each of the new result values.
1407   Value newValue, result;
1408   for (auto it : llvm::zip(newValues, op->getResults())) {
1409     std::tie(newValue, result) = it;
1410     if (!newValue) {
1411       resultChanged = true;
1412       continue;
1413     }
1414     // Remap, and check for any result type changes.
1415     mapping.map(result, newValue);
1416     resultChanged |= (newValue.getType() != result.getType());
1417   }
1418   if (resultChanged)
1419     operationsWithChangedResults.push_back(replacements.size());
1420 
1421   // Record the requested operation replacement.
1422   replacements.insert(std::make_pair(op, OpReplacement(currentTypeConverter)));
1423 
1424   // Mark this operation as recursively ignored so that we don't need to
1425   // convert any nested operations.
1426   markNestedOpsIgnored(op);
1427 }
1428 
1429 void ConversionPatternRewriterImpl::notifyBlockIsBeingErased(Block *block) {
1430   Region *region = block->getParent();
1431   Block *origPrevBlock = block->getPrevNode();
1432   blockActions.push_back(BlockAction::getErase(block, {region, origPrevBlock}));
1433 }
1434 
1435 void ConversionPatternRewriterImpl::notifyCreatedBlock(Block *block) {
1436   blockActions.push_back(BlockAction::getCreate(block));
1437 }
1438 
1439 void ConversionPatternRewriterImpl::notifySplitBlock(Block *block,
1440                                                      Block *continuation) {
1441   blockActions.push_back(BlockAction::getSplit(continuation, block));
1442 }
1443 
1444 void ConversionPatternRewriterImpl::notifyBlocksBeingMerged(Block *block,
1445                                                             Block *srcBlock) {
1446   blockActions.push_back(BlockAction::getMerge(block, srcBlock));
1447 }
1448 
1449 void ConversionPatternRewriterImpl::notifyRegionIsBeingInlinedBefore(
1450     Region &region, Region &parent, Region::iterator before) {
1451   if (region.empty())
1452     return;
1453   Block *laterBlock = &region.back();
1454   for (auto &earlierBlock : llvm::drop_begin(llvm::reverse(region), 1)) {
1455     blockActions.push_back(
1456         BlockAction::getMove(laterBlock, {&region, &earlierBlock}));
1457     laterBlock = &earlierBlock;
1458   }
1459   blockActions.push_back(BlockAction::getMove(laterBlock, {&region, nullptr}));
1460 }
1461 
1462 void ConversionPatternRewriterImpl::notifyRegionWasClonedBefore(
1463     iterator_range<Region::iterator> &blocks, Location origRegionLoc) {
1464   for (Block &block : blocks)
1465     blockActions.push_back(BlockAction::getCreate(&block));
1466 
1467   // Compute the conversion set for the inlined region.
1468   auto result = computeConversionSet(blocks, origRegionLoc, createdOps);
1469 
1470   // This original region has already had its conversion set computed, so there
1471   // shouldn't be any new failures.
1472   (void)result;
1473   assert(succeeded(result) && "expected region to have no unreachable blocks");
1474 }
1475 
1476 LogicalResult ConversionPatternRewriterImpl::notifyMatchFailure(
1477     Location loc, function_ref<void(Diagnostic &)> reasonCallback) {
1478   LLVM_DEBUG({
1479     Diagnostic diag(loc, DiagnosticSeverity::Remark);
1480     reasonCallback(diag);
1481     logger.startLine() << "** Failure : " << diag.str() << "\n";
1482     if (notifyCallback)
1483       notifyCallback(diag);
1484   });
1485   return failure();
1486 }
1487 
1488 //===----------------------------------------------------------------------===//
1489 // ConversionPatternRewriter
1490 //===----------------------------------------------------------------------===//
1491 
1492 ConversionPatternRewriter::ConversionPatternRewriter(MLIRContext *ctx)
1493     : PatternRewriter(ctx),
1494       impl(new detail::ConversionPatternRewriterImpl(*this)) {}
1495 ConversionPatternRewriter::~ConversionPatternRewriter() = default;
1496 
1497 void ConversionPatternRewriter::replaceOpWithIf(
1498     Operation *op, ValueRange newValues, bool *allUsesReplaced,
1499     llvm::unique_function<bool(OpOperand &) const> functor) {
1500   // TODO: To support this we will need to rework a bit of how replacements are
1501   // tracked, given that this isn't guranteed to replace all of the uses of an
1502   // operation. The main change is that now an operation can be replaced
1503   // multiple times, in parts. The current "set" based tracking is mainly useful
1504   // for tracking if a replaced operation should be ignored, i.e. if all of the
1505   // uses will be replaced.
1506   llvm_unreachable(
1507       "replaceOpWithIf is currently not supported by DialectConversion");
1508 }
1509 
1510 void ConversionPatternRewriter::replaceOp(Operation *op, ValueRange newValues) {
1511   LLVM_DEBUG({
1512     impl->logger.startLine()
1513         << "** Replace : '" << op->getName() << "'(" << op << ")\n";
1514   });
1515   impl->notifyOpReplaced(op, newValues);
1516 }
1517 
1518 void ConversionPatternRewriter::eraseOp(Operation *op) {
1519   LLVM_DEBUG({
1520     impl->logger.startLine()
1521         << "** Erase   : '" << op->getName() << "'(" << op << ")\n";
1522   });
1523   SmallVector<Value, 1> nullRepls(op->getNumResults(), nullptr);
1524   impl->notifyOpReplaced(op, nullRepls);
1525 }
1526 
1527 void ConversionPatternRewriter::eraseBlock(Block *block) {
1528   impl->notifyBlockIsBeingErased(block);
1529 
1530   // Mark all ops for erasure.
1531   for (Operation &op : *block)
1532     eraseOp(&op);
1533 
1534   // Unlink the block from its parent region. The block is kept in the block
1535   // action and will be actually destroyed when rewrites are applied. This
1536   // allows us to keep the operations in the block live and undo the removal by
1537   // re-inserting the block.
1538   block->getParent()->getBlocks().remove(block);
1539 }
1540 
1541 Block *ConversionPatternRewriter::applySignatureConversion(
1542     Region *region, TypeConverter::SignatureConversion &conversion,
1543     TypeConverter *converter) {
1544   return impl->applySignatureConversion(region, conversion, converter);
1545 }
1546 
1547 FailureOr<Block *> ConversionPatternRewriter::convertRegionTypes(
1548     Region *region, TypeConverter &converter,
1549     TypeConverter::SignatureConversion *entryConversion) {
1550   return impl->convertRegionTypes(region, converter, entryConversion);
1551 }
1552 
1553 LogicalResult ConversionPatternRewriter::convertNonEntryRegionTypes(
1554     Region *region, TypeConverter &converter,
1555     ArrayRef<TypeConverter::SignatureConversion> blockConversions) {
1556   return impl->convertNonEntryRegionTypes(region, converter, blockConversions);
1557 }
1558 
1559 void ConversionPatternRewriter::replaceUsesOfBlockArgument(BlockArgument from,
1560                                                            Value to) {
1561   LLVM_DEBUG({
1562     Operation *parentOp = from.getOwner()->getParentOp();
1563     impl->logger.startLine() << "** Replace Argument : '" << from
1564                              << "'(in region of '" << parentOp->getName()
1565                              << "'(" << from.getOwner()->getParentOp() << ")\n";
1566   });
1567   impl->argReplacements.push_back(from);
1568   impl->mapping.map(impl->mapping.lookupOrDefault(from), to);
1569 }
1570 
1571 Value ConversionPatternRewriter::getRemappedValue(Value key) {
1572   SmallVector<Value> remappedValues;
1573   if (failed(impl->remapValues("value", /*inputLoc=*/llvm::None, *this, key,
1574                                remappedValues)))
1575     return nullptr;
1576   return remappedValues.front();
1577 }
1578 
1579 LogicalResult
1580 ConversionPatternRewriter::getRemappedValues(ValueRange keys,
1581                                              SmallVectorImpl<Value> &results) {
1582   if (keys.empty())
1583     return success();
1584   return impl->remapValues("value", /*inputLoc=*/llvm::None, *this, keys,
1585                            results);
1586 }
1587 
1588 void ConversionPatternRewriter::notifyBlockCreated(Block *block) {
1589   impl->notifyCreatedBlock(block);
1590 }
1591 
1592 Block *ConversionPatternRewriter::splitBlock(Block *block,
1593                                              Block::iterator before) {
1594   auto *continuation = PatternRewriter::splitBlock(block, before);
1595   impl->notifySplitBlock(block, continuation);
1596   return continuation;
1597 }
1598 
1599 void ConversionPatternRewriter::mergeBlocks(Block *source, Block *dest,
1600                                             ValueRange argValues) {
1601   impl->notifyBlocksBeingMerged(dest, source);
1602   assert(llvm::all_of(source->getPredecessors(),
1603                       [dest](Block *succ) { return succ == dest; }) &&
1604          "expected 'source' to have no predecessors or only 'dest'");
1605   assert(argValues.size() == source->getNumArguments() &&
1606          "incorrect # of argument replacement values");
1607   for (auto it : llvm::zip(source->getArguments(), argValues))
1608     replaceUsesOfBlockArgument(std::get<0>(it), std::get<1>(it));
1609   dest->getOperations().splice(dest->end(), source->getOperations());
1610   eraseBlock(source);
1611 }
1612 
1613 void ConversionPatternRewriter::inlineRegionBefore(Region &region,
1614                                                    Region &parent,
1615                                                    Region::iterator before) {
1616   impl->notifyRegionIsBeingInlinedBefore(region, parent, before);
1617   PatternRewriter::inlineRegionBefore(region, parent, before);
1618 }
1619 
1620 void ConversionPatternRewriter::cloneRegionBefore(
1621     Region &region, Region &parent, Region::iterator before,
1622     BlockAndValueMapping &mapping) {
1623   if (region.empty())
1624     return;
1625   PatternRewriter::cloneRegionBefore(region, parent, before, mapping);
1626 
1627   // Collect the range of the cloned blocks.
1628   auto clonedBeginIt = mapping.lookup(&region.front())->getIterator();
1629   auto clonedBlocks = llvm::make_range(clonedBeginIt, before);
1630   impl->notifyRegionWasClonedBefore(clonedBlocks, region.getLoc());
1631 }
1632 
1633 void ConversionPatternRewriter::notifyOperationInserted(Operation *op) {
1634   LLVM_DEBUG({
1635     impl->logger.startLine()
1636         << "** Insert  : '" << op->getName() << "'(" << op << ")\n";
1637   });
1638   impl->createdOps.push_back(op);
1639 }
1640 
1641 void ConversionPatternRewriter::startRootUpdate(Operation *op) {
1642 #ifndef NDEBUG
1643   impl->pendingRootUpdates.insert(op);
1644 #endif
1645   impl->rootUpdates.emplace_back(op);
1646 }
1647 
1648 void ConversionPatternRewriter::finalizeRootUpdate(Operation *op) {
1649   // There is nothing to do here, we only need to track the operation at the
1650   // start of the update.
1651 #ifndef NDEBUG
1652   assert(impl->pendingRootUpdates.erase(op) &&
1653          "operation did not have a pending in-place update");
1654 #endif
1655 }
1656 
1657 void ConversionPatternRewriter::cancelRootUpdate(Operation *op) {
1658 #ifndef NDEBUG
1659   assert(impl->pendingRootUpdates.erase(op) &&
1660          "operation did not have a pending in-place update");
1661 #endif
1662   // Erase the last update for this operation.
1663   auto stateHasOp = [op](const auto &it) { return it.getOperation() == op; };
1664   auto &rootUpdates = impl->rootUpdates;
1665   auto it = llvm::find_if(llvm::reverse(rootUpdates), stateHasOp);
1666   assert(it != rootUpdates.rend() && "no root update started on op");
1667   (*it).resetOperation();
1668   int updateIdx = std::prev(rootUpdates.rend()) - it;
1669   rootUpdates.erase(rootUpdates.begin() + updateIdx);
1670 }
1671 
1672 LogicalResult ConversionPatternRewriter::notifyMatchFailure(
1673     Operation *op, function_ref<void(Diagnostic &)> reasonCallback) {
1674   return impl->notifyMatchFailure(op->getLoc(), reasonCallback);
1675 }
1676 
1677 detail::ConversionPatternRewriterImpl &ConversionPatternRewriter::getImpl() {
1678   return *impl;
1679 }
1680 
1681 //===----------------------------------------------------------------------===//
1682 // ConversionPattern
1683 //===----------------------------------------------------------------------===//
1684 
1685 LogicalResult
1686 ConversionPattern::matchAndRewrite(Operation *op,
1687                                    PatternRewriter &rewriter) const {
1688   auto &dialectRewriter = static_cast<ConversionPatternRewriter &>(rewriter);
1689   auto &rewriterImpl = dialectRewriter.getImpl();
1690 
1691   // Track the current conversion pattern type converter in the rewriter.
1692   llvm::SaveAndRestore<TypeConverter *> currentConverterGuard(
1693       rewriterImpl.currentTypeConverter, getTypeConverter());
1694 
1695   // Remap the operands of the operation.
1696   SmallVector<Value, 4> operands;
1697   if (failed(rewriterImpl.remapValues("operand", op->getLoc(), rewriter,
1698                                       op->getOperands(), operands))) {
1699     return failure();
1700   }
1701   return matchAndRewrite(op, operands, dialectRewriter);
1702 }
1703 
1704 //===----------------------------------------------------------------------===//
1705 // OperationLegalizer
1706 //===----------------------------------------------------------------------===//
1707 
1708 namespace {
1709 /// A set of rewrite patterns that can be used to legalize a given operation.
1710 using LegalizationPatterns = SmallVector<const Pattern *, 1>;
1711 
1712 /// This class defines a recursive operation legalizer.
1713 class OperationLegalizer {
1714 public:
1715   using LegalizationAction = ConversionTarget::LegalizationAction;
1716 
1717   OperationLegalizer(ConversionTarget &targetInfo,
1718                      const FrozenRewritePatternSet &patterns);
1719 
1720   /// Returns true if the given operation is known to be illegal on the target.
1721   bool isIllegal(Operation *op) const;
1722 
1723   /// Attempt to legalize the given operation. Returns success if the operation
1724   /// was legalized, failure otherwise.
1725   LogicalResult legalize(Operation *op, ConversionPatternRewriter &rewriter);
1726 
1727   /// Returns the conversion target in use by the legalizer.
1728   ConversionTarget &getTarget() { return target; }
1729 
1730 private:
1731   /// Attempt to legalize the given operation by folding it.
1732   LogicalResult legalizeWithFold(Operation *op,
1733                                  ConversionPatternRewriter &rewriter);
1734 
1735   /// Attempt to legalize the given operation by applying a pattern. Returns
1736   /// success if the operation was legalized, failure otherwise.
1737   LogicalResult legalizeWithPattern(Operation *op,
1738                                     ConversionPatternRewriter &rewriter);
1739 
1740   /// Return true if the given pattern may be applied to the given operation,
1741   /// false otherwise.
1742   bool canApplyPattern(Operation *op, const Pattern &pattern,
1743                        ConversionPatternRewriter &rewriter);
1744 
1745   /// Legalize the resultant IR after successfully applying the given pattern.
1746   LogicalResult legalizePatternResult(Operation *op, const Pattern &pattern,
1747                                       ConversionPatternRewriter &rewriter,
1748                                       RewriterState &curState);
1749 
1750   /// Legalizes the actions registered during the execution of a pattern.
1751   LogicalResult legalizePatternBlockActions(Operation *op,
1752                                             ConversionPatternRewriter &rewriter,
1753                                             ConversionPatternRewriterImpl &impl,
1754                                             RewriterState &state,
1755                                             RewriterState &newState);
1756   LogicalResult legalizePatternCreatedOperations(
1757       ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl,
1758       RewriterState &state, RewriterState &newState);
1759   LogicalResult legalizePatternRootUpdates(ConversionPatternRewriter &rewriter,
1760                                            ConversionPatternRewriterImpl &impl,
1761                                            RewriterState &state,
1762                                            RewriterState &newState);
1763 
1764   //===--------------------------------------------------------------------===//
1765   // Cost Model
1766   //===--------------------------------------------------------------------===//
1767 
1768   /// Build an optimistic legalization graph given the provided patterns. This
1769   /// function populates 'anyOpLegalizerPatterns' and 'legalizerPatterns' with
1770   /// patterns for operations that are not directly legal, but may be
1771   /// transitively legal for the current target given the provided patterns.
1772   void buildLegalizationGraph(
1773       LegalizationPatterns &anyOpLegalizerPatterns,
1774       DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns);
1775 
1776   /// Compute the benefit of each node within the computed legalization graph.
1777   /// This orders the patterns within 'legalizerPatterns' based upon two
1778   /// criteria:
1779   ///  1) Prefer patterns that have the lowest legalization depth, i.e.
1780   ///     represent the more direct mapping to the target.
1781   ///  2) When comparing patterns with the same legalization depth, prefer the
1782   ///     pattern with the highest PatternBenefit. This allows for users to
1783   ///     prefer specific legalizations over others.
1784   void computeLegalizationGraphBenefit(
1785       LegalizationPatterns &anyOpLegalizerPatterns,
1786       DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns);
1787 
1788   /// Compute the legalization depth when legalizing an operation of the given
1789   /// type.
1790   unsigned computeOpLegalizationDepth(
1791       OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth,
1792       DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns);
1793 
1794   /// Apply the conversion cost model to the given set of patterns, and return
1795   /// the smallest legalization depth of any of the patterns. See
1796   /// `computeLegalizationGraphBenefit` for the breakdown of the cost model.
1797   unsigned applyCostModelToPatterns(
1798       LegalizationPatterns &patterns,
1799       DenseMap<OperationName, unsigned> &minOpPatternDepth,
1800       DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns);
1801 
1802   /// The current set of patterns that have been applied.
1803   SmallPtrSet<const Pattern *, 8> appliedPatterns;
1804 
1805   /// The legalization information provided by the target.
1806   ConversionTarget &target;
1807 
1808   /// The pattern applicator to use for conversions.
1809   PatternApplicator applicator;
1810 };
1811 } // namespace
1812 
1813 OperationLegalizer::OperationLegalizer(ConversionTarget &targetInfo,
1814                                        const FrozenRewritePatternSet &patterns)
1815     : target(targetInfo), applicator(patterns) {
1816   // The set of patterns that can be applied to illegal operations to transform
1817   // them into legal ones.
1818   DenseMap<OperationName, LegalizationPatterns> legalizerPatterns;
1819   LegalizationPatterns anyOpLegalizerPatterns;
1820 
1821   buildLegalizationGraph(anyOpLegalizerPatterns, legalizerPatterns);
1822   computeLegalizationGraphBenefit(anyOpLegalizerPatterns, legalizerPatterns);
1823 }
1824 
1825 bool OperationLegalizer::isIllegal(Operation *op) const {
1826   return target.isIllegal(op);
1827 }
1828 
1829 LogicalResult
1830 OperationLegalizer::legalize(Operation *op,
1831                              ConversionPatternRewriter &rewriter) {
1832 #ifndef NDEBUG
1833   const char *logLineComment =
1834       "//===-------------------------------------------===//\n";
1835 
1836   auto &logger = rewriter.getImpl().logger;
1837 #endif
1838   LLVM_DEBUG({
1839     logger.getOStream() << "\n";
1840     logger.startLine() << logLineComment;
1841     logger.startLine() << "Legalizing operation : '" << op->getName() << "'("
1842                        << op << ") {\n";
1843     logger.indent();
1844 
1845     // If the operation has no regions, just print it here.
1846     if (op->getNumRegions() == 0) {
1847       op->print(logger.startLine(), OpPrintingFlags().printGenericOpForm());
1848       logger.getOStream() << "\n\n";
1849     }
1850   });
1851 
1852   // Check if this operation is legal on the target.
1853   if (auto legalityInfo = target.isLegal(op)) {
1854     LLVM_DEBUG({
1855       logSuccess(
1856           logger, "operation marked legal by the target{0}",
1857           legalityInfo->isRecursivelyLegal
1858               ? "; NOTE: operation is recursively legal; skipping internals"
1859               : "");
1860       logger.startLine() << logLineComment;
1861     });
1862 
1863     // If this operation is recursively legal, mark its children as ignored so
1864     // that we don't consider them for legalization.
1865     if (legalityInfo->isRecursivelyLegal)
1866       rewriter.getImpl().markNestedOpsIgnored(op);
1867     return success();
1868   }
1869 
1870   // Check to see if the operation is ignored and doesn't need to be converted.
1871   if (rewriter.getImpl().isOpIgnored(op)) {
1872     LLVM_DEBUG({
1873       logSuccess(logger, "operation marked 'ignored' during conversion");
1874       logger.startLine() << logLineComment;
1875     });
1876     return success();
1877   }
1878 
1879   // If the operation isn't legal, try to fold it in-place.
1880   // TODO: Should we always try to do this, even if the op is
1881   // already legal?
1882   if (succeeded(legalizeWithFold(op, rewriter))) {
1883     LLVM_DEBUG({
1884       logSuccess(logger, "operation was folded");
1885       logger.startLine() << logLineComment;
1886     });
1887     return success();
1888   }
1889 
1890   // Otherwise, we need to apply a legalization pattern to this operation.
1891   if (succeeded(legalizeWithPattern(op, rewriter))) {
1892     LLVM_DEBUG({
1893       logSuccess(logger, "");
1894       logger.startLine() << logLineComment;
1895     });
1896     return success();
1897   }
1898 
1899   LLVM_DEBUG({
1900     logFailure(logger, "no matched legalization pattern");
1901     logger.startLine() << logLineComment;
1902   });
1903   return failure();
1904 }
1905 
1906 LogicalResult
1907 OperationLegalizer::legalizeWithFold(Operation *op,
1908                                      ConversionPatternRewriter &rewriter) {
1909   auto &rewriterImpl = rewriter.getImpl();
1910   RewriterState curState = rewriterImpl.getCurrentState();
1911 
1912   LLVM_DEBUG({
1913     rewriterImpl.logger.startLine() << "* Fold {\n";
1914     rewriterImpl.logger.indent();
1915   });
1916 
1917   // Try to fold the operation.
1918   SmallVector<Value, 2> replacementValues;
1919   rewriter.setInsertionPoint(op);
1920   if (failed(rewriter.tryFold(op, replacementValues))) {
1921     LLVM_DEBUG(logFailure(rewriterImpl.logger, "unable to fold"));
1922     return failure();
1923   }
1924 
1925   // Insert a replacement for 'op' with the folded replacement values.
1926   rewriter.replaceOp(op, replacementValues);
1927 
1928   // Recursively legalize any new constant operations.
1929   for (unsigned i = curState.numCreatedOps, e = rewriterImpl.createdOps.size();
1930        i != e; ++i) {
1931     Operation *cstOp = rewriterImpl.createdOps[i];
1932     if (failed(legalize(cstOp, rewriter))) {
1933       LLVM_DEBUG(logFailure(rewriterImpl.logger,
1934                             "generated constant '{0}' was illegal",
1935                             cstOp->getName()));
1936       rewriterImpl.resetState(curState);
1937       return failure();
1938     }
1939   }
1940 
1941   LLVM_DEBUG(logSuccess(rewriterImpl.logger, ""));
1942   return success();
1943 }
1944 
1945 LogicalResult
1946 OperationLegalizer::legalizeWithPattern(Operation *op,
1947                                         ConversionPatternRewriter &rewriter) {
1948   auto &rewriterImpl = rewriter.getImpl();
1949 
1950   // Functor that returns if the given pattern may be applied.
1951   auto canApply = [&](const Pattern &pattern) {
1952     return canApplyPattern(op, pattern, rewriter);
1953   };
1954 
1955   // Functor that cleans up the rewriter state after a pattern failed to match.
1956   RewriterState curState = rewriterImpl.getCurrentState();
1957   auto onFailure = [&](const Pattern &pattern) {
1958     LLVM_DEBUG({
1959       logFailure(rewriterImpl.logger, "pattern failed to match");
1960       if (rewriterImpl.notifyCallback) {
1961         Diagnostic diag(op->getLoc(), DiagnosticSeverity::Remark);
1962         diag << "Failed to apply pattern \"" << pattern.getDebugName()
1963              << "\" on op:\n"
1964              << *op;
1965         rewriterImpl.notifyCallback(diag);
1966       }
1967     });
1968     rewriterImpl.resetState(curState);
1969     appliedPatterns.erase(&pattern);
1970   };
1971 
1972   // Functor that performs additional legalization when a pattern is
1973   // successfully applied.
1974   auto onSuccess = [&](const Pattern &pattern) {
1975     auto result = legalizePatternResult(op, pattern, rewriter, curState);
1976     appliedPatterns.erase(&pattern);
1977     if (failed(result))
1978       rewriterImpl.resetState(curState);
1979     return result;
1980   };
1981 
1982   // Try to match and rewrite a pattern on this operation.
1983   return applicator.matchAndRewrite(op, rewriter, canApply, onFailure,
1984                                     onSuccess);
1985 }
1986 
1987 bool OperationLegalizer::canApplyPattern(Operation *op, const Pattern &pattern,
1988                                          ConversionPatternRewriter &rewriter) {
1989   LLVM_DEBUG({
1990     auto &os = rewriter.getImpl().logger;
1991     os.getOStream() << "\n";
1992     os.startLine() << "* Pattern : '" << op->getName() << " -> (";
1993     llvm::interleaveComma(pattern.getGeneratedOps(), os.getOStream());
1994     os.getOStream() << ")' {\n";
1995     os.indent();
1996   });
1997 
1998   // Ensure that we don't cycle by not allowing the same pattern to be
1999   // applied twice in the same recursion stack if it is not known to be safe.
2000   if (!pattern.hasBoundedRewriteRecursion() &&
2001       !appliedPatterns.insert(&pattern).second) {
2002     LLVM_DEBUG(
2003         logFailure(rewriter.getImpl().logger, "pattern was already applied"));
2004     return false;
2005   }
2006   return true;
2007 }
2008 
2009 LogicalResult
2010 OperationLegalizer::legalizePatternResult(Operation *op, const Pattern &pattern,
2011                                           ConversionPatternRewriter &rewriter,
2012                                           RewriterState &curState) {
2013   auto &impl = rewriter.getImpl();
2014 
2015 #ifndef NDEBUG
2016   assert(impl.pendingRootUpdates.empty() && "dangling root updates");
2017 #endif
2018 
2019   // Check that the root was either replaced or updated in place.
2020   auto replacedRoot = [&] {
2021     return llvm::any_of(
2022         llvm::drop_begin(impl.replacements, curState.numReplacements),
2023         [op](auto &it) { return it.first == op; });
2024   };
2025   auto updatedRootInPlace = [&] {
2026     return llvm::any_of(
2027         llvm::drop_begin(impl.rootUpdates, curState.numRootUpdates),
2028         [op](auto &state) { return state.getOperation() == op; });
2029   };
2030   (void)replacedRoot;
2031   (void)updatedRootInPlace;
2032   assert((replacedRoot() || updatedRootInPlace()) &&
2033          "expected pattern to replace the root operation");
2034 
2035   // Legalize each of the actions registered during application.
2036   RewriterState newState = impl.getCurrentState();
2037   if (failed(legalizePatternBlockActions(op, rewriter, impl, curState,
2038                                          newState)) ||
2039       failed(legalizePatternRootUpdates(rewriter, impl, curState, newState)) ||
2040       failed(legalizePatternCreatedOperations(rewriter, impl, curState,
2041                                               newState))) {
2042     return failure();
2043   }
2044 
2045   LLVM_DEBUG(logSuccess(impl.logger, "pattern applied successfully"));
2046   return success();
2047 }
2048 
2049 LogicalResult OperationLegalizer::legalizePatternBlockActions(
2050     Operation *op, ConversionPatternRewriter &rewriter,
2051     ConversionPatternRewriterImpl &impl, RewriterState &state,
2052     RewriterState &newState) {
2053   SmallPtrSet<Operation *, 16> operationsToIgnore;
2054 
2055   // If the pattern moved or created any blocks, make sure the types of block
2056   // arguments get legalized.
2057   for (int i = state.numBlockActions, e = newState.numBlockActions; i != e;
2058        ++i) {
2059     auto &action = impl.blockActions[i];
2060     if (action.kind == BlockActionKind::TypeConversion ||
2061         action.kind == BlockActionKind::Erase)
2062       continue;
2063     // Only check blocks outside of the current operation.
2064     Operation *parentOp = action.block->getParentOp();
2065     if (!parentOp || parentOp == op || action.block->getNumArguments() == 0)
2066       continue;
2067 
2068     // If the region of the block has a type converter, try to convert the block
2069     // directly.
2070     if (auto *converter =
2071             impl.argConverter.getConverter(action.block->getParent())) {
2072       if (failed(impl.convertBlockSignature(action.block, converter))) {
2073         LLVM_DEBUG(logFailure(impl.logger, "failed to convert types of moved "
2074                                            "block"));
2075         return failure();
2076       }
2077       continue;
2078     }
2079 
2080     // Otherwise, check that this operation isn't one generated by this pattern.
2081     // This is because we will attempt to legalize the parent operation, and
2082     // blocks in regions created by this pattern will already be legalized later
2083     // on. If we haven't built the set yet, build it now.
2084     if (operationsToIgnore.empty()) {
2085       auto createdOps = ArrayRef<Operation *>(impl.createdOps)
2086                             .drop_front(state.numCreatedOps);
2087       operationsToIgnore.insert(createdOps.begin(), createdOps.end());
2088     }
2089 
2090     // If this operation should be considered for re-legalization, try it.
2091     if (operationsToIgnore.insert(parentOp).second &&
2092         failed(legalize(parentOp, rewriter))) {
2093       LLVM_DEBUG(logFailure(
2094           impl.logger, "operation '{0}'({1}) became illegal after block action",
2095           parentOp->getName(), parentOp));
2096       return failure();
2097     }
2098   }
2099   return success();
2100 }
2101 
2102 LogicalResult OperationLegalizer::legalizePatternCreatedOperations(
2103     ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl,
2104     RewriterState &state, RewriterState &newState) {
2105   for (int i = state.numCreatedOps, e = newState.numCreatedOps; i != e; ++i) {
2106     Operation *op = impl.createdOps[i];
2107     if (failed(legalize(op, rewriter))) {
2108       LLVM_DEBUG(logFailure(impl.logger,
2109                             "generated operation '{0}'({1}) was illegal",
2110                             op->getName(), op));
2111       return failure();
2112     }
2113   }
2114   return success();
2115 }
2116 
2117 LogicalResult OperationLegalizer::legalizePatternRootUpdates(
2118     ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl,
2119     RewriterState &state, RewriterState &newState) {
2120   for (int i = state.numRootUpdates, e = newState.numRootUpdates; i != e; ++i) {
2121     Operation *op = impl.rootUpdates[i].getOperation();
2122     if (failed(legalize(op, rewriter))) {
2123       LLVM_DEBUG(logFailure(impl.logger,
2124                             "operation updated in-place '{0}' was illegal",
2125                             op->getName()));
2126       return failure();
2127     }
2128   }
2129   return success();
2130 }
2131 
2132 //===----------------------------------------------------------------------===//
2133 // Cost Model
2134 
2135 void OperationLegalizer::buildLegalizationGraph(
2136     LegalizationPatterns &anyOpLegalizerPatterns,
2137     DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) {
2138   // A mapping between an operation and a set of operations that can be used to
2139   // generate it.
2140   DenseMap<OperationName, SmallPtrSet<OperationName, 2>> parentOps;
2141   // A mapping between an operation and any currently invalid patterns it has.
2142   DenseMap<OperationName, SmallPtrSet<const Pattern *, 2>> invalidPatterns;
2143   // A worklist of patterns to consider for legality.
2144   SetVector<const Pattern *> patternWorklist;
2145 
2146   // Build the mapping from operations to the parent ops that may generate them.
2147   applicator.walkAllPatterns([&](const Pattern &pattern) {
2148     Optional<OperationName> root = pattern.getRootKind();
2149 
2150     // If the pattern has no specific root, we can't analyze the relationship
2151     // between the root op and generated operations. Given that, add all such
2152     // patterns to the legalization set.
2153     if (!root) {
2154       anyOpLegalizerPatterns.push_back(&pattern);
2155       return;
2156     }
2157 
2158     // Skip operations that are always known to be legal.
2159     if (target.getOpAction(*root) == LegalizationAction::Legal)
2160       return;
2161 
2162     // Add this pattern to the invalid set for the root op and record this root
2163     // as a parent for any generated operations.
2164     invalidPatterns[*root].insert(&pattern);
2165     for (auto op : pattern.getGeneratedOps())
2166       parentOps[op].insert(*root);
2167 
2168     // Add this pattern to the worklist.
2169     patternWorklist.insert(&pattern);
2170   });
2171 
2172   // If there are any patterns that don't have a specific root kind, we can't
2173   // make direct assumptions about what operations will never be legalized.
2174   // Note: Technically we could, but it would require an analysis that may
2175   // recurse into itself. It would be better to perform this kind of filtering
2176   // at a higher level than here anyways.
2177   if (!anyOpLegalizerPatterns.empty()) {
2178     for (const Pattern *pattern : patternWorklist)
2179       legalizerPatterns[*pattern->getRootKind()].push_back(pattern);
2180     return;
2181   }
2182 
2183   while (!patternWorklist.empty()) {
2184     auto *pattern = patternWorklist.pop_back_val();
2185 
2186     // Check to see if any of the generated operations are invalid.
2187     if (llvm::any_of(pattern->getGeneratedOps(), [&](OperationName op) {
2188           Optional<LegalizationAction> action = target.getOpAction(op);
2189           return !legalizerPatterns.count(op) &&
2190                  (!action || action == LegalizationAction::Illegal);
2191         }))
2192       continue;
2193 
2194     // Otherwise, if all of the generated operation are valid, this op is now
2195     // legal so add all of the child patterns to the worklist.
2196     legalizerPatterns[*pattern->getRootKind()].push_back(pattern);
2197     invalidPatterns[*pattern->getRootKind()].erase(pattern);
2198 
2199     // Add any invalid patterns of the parent operations to see if they have now
2200     // become legal.
2201     for (auto op : parentOps[*pattern->getRootKind()])
2202       patternWorklist.set_union(invalidPatterns[op]);
2203   }
2204 }
2205 
2206 void OperationLegalizer::computeLegalizationGraphBenefit(
2207     LegalizationPatterns &anyOpLegalizerPatterns,
2208     DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) {
2209   // The smallest pattern depth, when legalizing an operation.
2210   DenseMap<OperationName, unsigned> minOpPatternDepth;
2211 
2212   // For each operation that is transitively legal, compute a cost for it.
2213   for (auto &opIt : legalizerPatterns)
2214     if (!minOpPatternDepth.count(opIt.first))
2215       computeOpLegalizationDepth(opIt.first, minOpPatternDepth,
2216                                  legalizerPatterns);
2217 
2218   // Apply the cost model to the patterns that can match any operation. Those
2219   // with a specific operation type are already resolved when computing the op
2220   // legalization depth.
2221   if (!anyOpLegalizerPatterns.empty())
2222     applyCostModelToPatterns(anyOpLegalizerPatterns, minOpPatternDepth,
2223                              legalizerPatterns);
2224 
2225   // Apply a cost model to the pattern applicator. We order patterns first by
2226   // depth then benefit. `legalizerPatterns` contains per-op patterns by
2227   // decreasing benefit.
2228   applicator.applyCostModel([&](const Pattern &pattern) {
2229     ArrayRef<const Pattern *> orderedPatternList;
2230     if (Optional<OperationName> rootName = pattern.getRootKind())
2231       orderedPatternList = legalizerPatterns[*rootName];
2232     else
2233       orderedPatternList = anyOpLegalizerPatterns;
2234 
2235     // If the pattern is not found, then it was removed and cannot be matched.
2236     auto *it = llvm::find(orderedPatternList, &pattern);
2237     if (it == orderedPatternList.end())
2238       return PatternBenefit::impossibleToMatch();
2239 
2240     // Patterns found earlier in the list have higher benefit.
2241     return PatternBenefit(std::distance(it, orderedPatternList.end()));
2242   });
2243 }
2244 
2245 unsigned OperationLegalizer::computeOpLegalizationDepth(
2246     OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth,
2247     DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) {
2248   // Check for existing depth.
2249   auto depthIt = minOpPatternDepth.find(op);
2250   if (depthIt != minOpPatternDepth.end())
2251     return depthIt->second;
2252 
2253   // If a mapping for this operation does not exist, then this operation
2254   // is always legal. Return 0 as the depth for a directly legal operation.
2255   auto opPatternsIt = legalizerPatterns.find(op);
2256   if (opPatternsIt == legalizerPatterns.end() || opPatternsIt->second.empty())
2257     return 0u;
2258 
2259   // Record this initial depth in case we encounter this op again when
2260   // recursively computing the depth.
2261   minOpPatternDepth.try_emplace(op, std::numeric_limits<unsigned>::max());
2262 
2263   // Apply the cost model to the operation patterns, and update the minimum
2264   // depth.
2265   unsigned minDepth = applyCostModelToPatterns(
2266       opPatternsIt->second, minOpPatternDepth, legalizerPatterns);
2267   minOpPatternDepth[op] = minDepth;
2268   return minDepth;
2269 }
2270 
2271 unsigned OperationLegalizer::applyCostModelToPatterns(
2272     LegalizationPatterns &patterns,
2273     DenseMap<OperationName, unsigned> &minOpPatternDepth,
2274     DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) {
2275   unsigned minDepth = std::numeric_limits<unsigned>::max();
2276 
2277   // Compute the depth for each pattern within the set.
2278   SmallVector<std::pair<const Pattern *, unsigned>, 4> patternsByDepth;
2279   patternsByDepth.reserve(patterns.size());
2280   for (const Pattern *pattern : patterns) {
2281     unsigned depth = 1;
2282     for (auto generatedOp : pattern->getGeneratedOps()) {
2283       unsigned generatedOpDepth = computeOpLegalizationDepth(
2284           generatedOp, minOpPatternDepth, legalizerPatterns);
2285       depth = std::max(depth, generatedOpDepth + 1);
2286     }
2287     patternsByDepth.emplace_back(pattern, depth);
2288 
2289     // Update the minimum depth of the pattern list.
2290     minDepth = std::min(minDepth, depth);
2291   }
2292 
2293   // If the operation only has one legalization pattern, there is no need to
2294   // sort them.
2295   if (patternsByDepth.size() == 1)
2296     return minDepth;
2297 
2298   // Sort the patterns by those likely to be the most beneficial.
2299   llvm::array_pod_sort(patternsByDepth.begin(), patternsByDepth.end(),
2300                        [](const std::pair<const Pattern *, unsigned> *lhs,
2301                           const std::pair<const Pattern *, unsigned> *rhs) {
2302                          // First sort by the smaller pattern legalization
2303                          // depth.
2304                          if (lhs->second != rhs->second)
2305                            return llvm::array_pod_sort_comparator<unsigned>(
2306                                &lhs->second, &rhs->second);
2307 
2308                          // Then sort by the larger pattern benefit.
2309                          auto lhsBenefit = lhs->first->getBenefit();
2310                          auto rhsBenefit = rhs->first->getBenefit();
2311                          return llvm::array_pod_sort_comparator<PatternBenefit>(
2312                              &rhsBenefit, &lhsBenefit);
2313                        });
2314 
2315   // Update the legalization pattern to use the new sorted list.
2316   patterns.clear();
2317   for (auto &patternIt : patternsByDepth)
2318     patterns.push_back(patternIt.first);
2319   return minDepth;
2320 }
2321 
2322 //===----------------------------------------------------------------------===//
2323 // OperationConverter
2324 //===----------------------------------------------------------------------===//
2325 namespace {
2326 enum OpConversionMode {
2327   /// In this mode, the conversion will ignore failed conversions to allow
2328   /// illegal operations to co-exist in the IR.
2329   Partial,
2330 
2331   /// In this mode, all operations must be legal for the given target for the
2332   /// conversion to succeed.
2333   Full,
2334 
2335   /// In this mode, operations are analyzed for legality. No actual rewrites are
2336   /// applied to the operations on success.
2337   Analysis,
2338 };
2339 
2340 // This class converts operations to a given conversion target via a set of
2341 // rewrite patterns. The conversion behaves differently depending on the
2342 // conversion mode.
2343 struct OperationConverter {
2344   explicit OperationConverter(ConversionTarget &target,
2345                               const FrozenRewritePatternSet &patterns,
2346                               OpConversionMode mode,
2347                               DenseSet<Operation *> *trackedOps = nullptr)
2348       : opLegalizer(target, patterns), mode(mode), trackedOps(trackedOps) {}
2349 
2350   /// Converts the given operations to the conversion target.
2351   LogicalResult
2352   convertOperations(ArrayRef<Operation *> ops,
2353                     function_ref<void(Diagnostic &)> notifyCallback = nullptr);
2354 
2355 private:
2356   /// Converts an operation with the given rewriter.
2357   LogicalResult convert(ConversionPatternRewriter &rewriter, Operation *op);
2358 
2359   /// This method is called after the conversion process to legalize any
2360   /// remaining artifacts and complete the conversion.
2361   LogicalResult finalize(ConversionPatternRewriter &rewriter);
2362 
2363   /// Legalize the types of converted block arguments.
2364   LogicalResult
2365   legalizeConvertedArgumentTypes(ConversionPatternRewriter &rewriter,
2366                                  ConversionPatternRewriterImpl &rewriterImpl);
2367 
2368   /// Legalize any unresolved type materializations.
2369   LogicalResult legalizeUnresolvedMaterializations(
2370       ConversionPatternRewriter &rewriter,
2371       ConversionPatternRewriterImpl &rewriterImpl,
2372       Optional<DenseMap<Value, SmallVector<Value>>> &inverseMapping);
2373 
2374   /// Legalize an operation result that was marked as "erased".
2375   LogicalResult
2376   legalizeErasedResult(Operation *op, OpResult result,
2377                        ConversionPatternRewriterImpl &rewriterImpl);
2378 
2379   /// Legalize an operation result that was replaced with a value of a different
2380   /// type.
2381   LogicalResult legalizeChangedResultType(
2382       Operation *op, OpResult result, Value newValue,
2383       TypeConverter *replConverter, ConversionPatternRewriter &rewriter,
2384       ConversionPatternRewriterImpl &rewriterImpl,
2385       const DenseMap<Value, SmallVector<Value>> &inverseMapping);
2386 
2387   /// The legalizer to use when converting operations.
2388   OperationLegalizer opLegalizer;
2389 
2390   /// The conversion mode to use when legalizing operations.
2391   OpConversionMode mode;
2392 
2393   /// A set of pre-existing operations. When mode == OpConversionMode::Analysis,
2394   /// this is populated with ops found to be legalizable to the target.
2395   /// When mode == OpConversionMode::Partial, this is populated with ops found
2396   /// *not* to be legalizable to the target.
2397   DenseSet<Operation *> *trackedOps;
2398 };
2399 } // namespace
2400 
2401 LogicalResult OperationConverter::convert(ConversionPatternRewriter &rewriter,
2402                                           Operation *op) {
2403   // Legalize the given operation.
2404   if (failed(opLegalizer.legalize(op, rewriter))) {
2405     // Handle the case of a failed conversion for each of the different modes.
2406     // Full conversions expect all operations to be converted.
2407     if (mode == OpConversionMode::Full)
2408       return op->emitError()
2409              << "failed to legalize operation '" << op->getName() << "'";
2410     // Partial conversions allow conversions to fail iff the operation was not
2411     // explicitly marked as illegal. If the user provided a nonlegalizableOps
2412     // set, non-legalizable ops are included.
2413     if (mode == OpConversionMode::Partial) {
2414       if (opLegalizer.isIllegal(op))
2415         return op->emitError()
2416                << "failed to legalize operation '" << op->getName()
2417                << "' that was explicitly marked illegal";
2418       if (trackedOps)
2419         trackedOps->insert(op);
2420     }
2421   } else if (mode == OpConversionMode::Analysis) {
2422     // Analysis conversions don't fail if any operations fail to legalize,
2423     // they are only interested in the operations that were successfully
2424     // legalized.
2425     trackedOps->insert(op);
2426   }
2427   return success();
2428 }
2429 
2430 LogicalResult OperationConverter::convertOperations(
2431     ArrayRef<Operation *> ops,
2432     function_ref<void(Diagnostic &)> notifyCallback) {
2433   if (ops.empty())
2434     return success();
2435   ConversionTarget &target = opLegalizer.getTarget();
2436 
2437   // Compute the set of operations and blocks to convert.
2438   SmallVector<Operation *> toConvert;
2439   for (auto *op : ops) {
2440     toConvert.emplace_back(op);
2441     for (auto &region : op->getRegions())
2442       if (failed(computeConversionSet(region.getBlocks(), region.getLoc(),
2443                                       toConvert, &target)))
2444         return failure();
2445   }
2446 
2447   // Convert each operation and discard rewrites on failure.
2448   ConversionPatternRewriter rewriter(ops.front()->getContext());
2449   ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl();
2450   rewriterImpl.notifyCallback = notifyCallback;
2451 
2452   for (auto *op : toConvert)
2453     if (failed(convert(rewriter, op)))
2454       return rewriterImpl.discardRewrites(), failure();
2455 
2456   // Now that all of the operations have been converted, finalize the conversion
2457   // process to ensure any lingering conversion artifacts are cleaned up and
2458   // legalized.
2459   if (failed(finalize(rewriter)))
2460     return rewriterImpl.discardRewrites(), failure();
2461 
2462   // After a successful conversion, apply rewrites if this is not an analysis
2463   // conversion.
2464   if (mode == OpConversionMode::Analysis) {
2465     rewriterImpl.discardRewrites();
2466   } else {
2467     rewriterImpl.applyRewrites();
2468 
2469     // It is possible for a later pattern to erase an op that was originally
2470     // identified as illegal and added to the trackedOps, remove it now after
2471     // replacements have been computed.
2472     if (trackedOps)
2473       for (auto &repl : rewriterImpl.replacements)
2474         trackedOps->erase(repl.first);
2475   }
2476   return success();
2477 }
2478 
2479 LogicalResult
2480 OperationConverter::finalize(ConversionPatternRewriter &rewriter) {
2481   Optional<DenseMap<Value, SmallVector<Value>>> inverseMapping;
2482   ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl();
2483   if (failed(legalizeUnresolvedMaterializations(rewriter, rewriterImpl,
2484                                                 inverseMapping)) ||
2485       failed(legalizeConvertedArgumentTypes(rewriter, rewriterImpl)))
2486     return failure();
2487 
2488   if (rewriterImpl.operationsWithChangedResults.empty())
2489     return success();
2490 
2491   // Process requested operation replacements.
2492   for (unsigned i = 0, e = rewriterImpl.operationsWithChangedResults.size();
2493        i != e; ++i) {
2494     unsigned replIdx = rewriterImpl.operationsWithChangedResults[i];
2495     auto &repl = *(rewriterImpl.replacements.begin() + replIdx);
2496     for (OpResult result : repl.first->getResults()) {
2497       Value newValue = rewriterImpl.mapping.lookupOrNull(result);
2498 
2499       // If the operation result was replaced with null, all of the uses of this
2500       // value should be replaced.
2501       if (!newValue) {
2502         if (failed(legalizeErasedResult(repl.first, result, rewriterImpl)))
2503           return failure();
2504         continue;
2505       }
2506 
2507       // Otherwise, check to see if the type of the result changed.
2508       if (result.getType() == newValue.getType())
2509         continue;
2510 
2511       // Compute the inverse mapping only if it is really needed.
2512       if (!inverseMapping)
2513         inverseMapping = rewriterImpl.mapping.getInverse();
2514 
2515       // Legalize this result.
2516       rewriter.setInsertionPoint(repl.first);
2517       if (failed(legalizeChangedResultType(repl.first, result, newValue,
2518                                            repl.second.converter, rewriter,
2519                                            rewriterImpl, *inverseMapping)))
2520         return failure();
2521 
2522       // Update the end iterator for this loop in the case it was updated
2523       // when legalizing generated conversion operations.
2524       e = rewriterImpl.operationsWithChangedResults.size();
2525     }
2526   }
2527   return success();
2528 }
2529 
2530 LogicalResult OperationConverter::legalizeConvertedArgumentTypes(
2531     ConversionPatternRewriter &rewriter,
2532     ConversionPatternRewriterImpl &rewriterImpl) {
2533   // Functor used to check if all users of a value will be dead after
2534   // conversion.
2535   auto findLiveUser = [&](Value val) {
2536     auto liveUserIt = llvm::find_if_not(val.getUsers(), [&](Operation *user) {
2537       return rewriterImpl.isOpIgnored(user);
2538     });
2539     return liveUserIt == val.user_end() ? nullptr : *liveUserIt;
2540   };
2541   return rewriterImpl.argConverter.materializeLiveConversions(
2542       rewriterImpl.mapping, rewriter, findLiveUser);
2543 }
2544 
2545 /// Replace the results of a materialization operation with the given values.
2546 static void
2547 replaceMaterialization(ConversionPatternRewriterImpl &rewriterImpl,
2548                        ResultRange matResults, ValueRange values,
2549                        DenseMap<Value, SmallVector<Value>> &inverseMapping) {
2550   matResults.replaceAllUsesWith(values);
2551 
2552   // For each of the materialization results, update the inverse mappings to
2553   // point to the replacement values.
2554   for (auto it : llvm::zip(matResults, values)) {
2555     Value matResult, newValue;
2556     std::tie(matResult, newValue) = it;
2557     auto inverseMapIt = inverseMapping.find(matResult);
2558     if (inverseMapIt == inverseMapping.end())
2559       continue;
2560 
2561     // Update the reverse mapping, or remove the mapping if we couldn't update
2562     // it. Not being able to update signals that the mapping would have become
2563     // circular (i.e. %foo -> newValue -> %foo), which may occur as values are
2564     // propagated through temporary materializations. We simply drop the
2565     // mapping, and let the post-conversion replacement logic handle updating
2566     // uses.
2567     for (Value inverseMapVal : inverseMapIt->second)
2568       if (!rewriterImpl.mapping.tryMap(inverseMapVal, newValue))
2569         rewriterImpl.mapping.erase(inverseMapVal);
2570   }
2571 }
2572 
2573 /// Compute all of the unresolved materializations that will persist beyond the
2574 /// conversion process, and require inserting a proper user materialization for.
2575 static void computeNecessaryMaterializations(
2576     DenseMap<Operation *, UnresolvedMaterialization *> &materializationOps,
2577     ConversionPatternRewriter &rewriter,
2578     ConversionPatternRewriterImpl &rewriterImpl,
2579     DenseMap<Value, SmallVector<Value>> &inverseMapping,
2580     SetVector<UnresolvedMaterialization *> &necessaryMaterializations) {
2581   auto isLive = [&](Value value) {
2582     auto findFn = [&](Operation *user) {
2583       auto matIt = materializationOps.find(user);
2584       if (matIt != materializationOps.end())
2585         return !necessaryMaterializations.count(matIt->second);
2586       return rewriterImpl.isOpIgnored(user);
2587     };
2588     return llvm::find_if_not(value.getUsers(), findFn) != value.user_end();
2589   };
2590 
2591   llvm::unique_function<Value(Value, Value, Type)> lookupRemappedValue =
2592       [&](Value invalidRoot, Value value, Type type) {
2593         // Check to see if the input operation was remapped to a variant of the
2594         // output.
2595         Value remappedValue = rewriterImpl.mapping.lookupOrDefault(value, type);
2596         if (remappedValue.getType() == type && remappedValue != invalidRoot)
2597           return remappedValue;
2598 
2599         // Check to see if the input is a materialization operation that
2600         // provides an inverse conversion. We just check blindly for
2601         // UnrealizedConversionCastOp here, but it has no effect on correctness.
2602         auto inputCastOp = value.getDefiningOp<UnrealizedConversionCastOp>();
2603         if (inputCastOp && inputCastOp->getNumOperands() == 1)
2604           return lookupRemappedValue(invalidRoot, inputCastOp->getOperand(0),
2605                                      type);
2606 
2607         return Value();
2608       };
2609 
2610   SetVector<UnresolvedMaterialization *> worklist;
2611   for (auto &mat : rewriterImpl.unresolvedMaterializations) {
2612     materializationOps.try_emplace(mat.getOp(), &mat);
2613     worklist.insert(&mat);
2614   }
2615   while (!worklist.empty()) {
2616     UnresolvedMaterialization *mat = worklist.pop_back_val();
2617     UnrealizedConversionCastOp op = mat->getOp();
2618 
2619     // We currently only handle target materializations here.
2620     assert(op->getNumResults() == 1 && "unexpected materialization type");
2621     OpResult opResult = op->getOpResult(0);
2622     Type outputType = opResult.getType();
2623     Operation::operand_range inputOperands = op.getOperands();
2624 
2625     // Try to forward propagate operands for user conversion casts that result
2626     // in the input types of the current cast.
2627     for (Operation *user : llvm::make_early_inc_range(opResult.getUsers())) {
2628       auto castOp = dyn_cast<UnrealizedConversionCastOp>(user);
2629       if (!castOp)
2630         continue;
2631       if (castOp->getResultTypes() == inputOperands.getTypes()) {
2632         replaceMaterialization(rewriterImpl, opResult, inputOperands,
2633                                inverseMapping);
2634         necessaryMaterializations.remove(materializationOps.lookup(user));
2635       }
2636     }
2637 
2638     // Try to avoid materializing a resolved materialization if possible.
2639     // Handle the case of a 1-1 materialization.
2640     if (inputOperands.size() == 1) {
2641       // Check to see if the input operation was remapped to a variant of the
2642       // output.
2643       Value remappedValue =
2644           lookupRemappedValue(opResult, inputOperands[0], outputType);
2645       if (remappedValue && remappedValue != opResult) {
2646         replaceMaterialization(rewriterImpl, opResult, remappedValue,
2647                                inverseMapping);
2648         necessaryMaterializations.remove(mat);
2649         continue;
2650       }
2651     } else {
2652       // TODO: Avoid materializing other types of conversions here.
2653     }
2654 
2655     // Check to see if this is an argument materialization.
2656     auto isBlockArg = [](Value v) { return v.isa<BlockArgument>(); };
2657     if (llvm::any_of(op->getOperands(), isBlockArg) ||
2658         llvm::any_of(inverseMapping[op->getResult(0)], isBlockArg)) {
2659       mat->setKind(UnresolvedMaterialization::Argument);
2660     }
2661 
2662     // If the materialization does not have any live users, we don't need to
2663     // generate a user materialization for it.
2664     // FIXME: For argument materializations, we currently need to check if any
2665     // of the inverse mapped values are used because some patterns expect blind
2666     // value replacement even if the types differ in some cases. When those
2667     // patterns are fixed, we can drop the argument special case here.
2668     bool isMaterializationLive = isLive(opResult);
2669     if (mat->getKind() == UnresolvedMaterialization::Argument)
2670       isMaterializationLive |= llvm::any_of(inverseMapping[opResult], isLive);
2671     if (!isMaterializationLive)
2672       continue;
2673     if (!necessaryMaterializations.insert(mat))
2674       continue;
2675 
2676     // Reprocess input materializations to see if they have an updated status.
2677     for (Value input : inputOperands) {
2678       if (auto parentOp = input.getDefiningOp<UnrealizedConversionCastOp>()) {
2679         if (auto *mat = materializationOps.lookup(parentOp))
2680           worklist.insert(mat);
2681       }
2682     }
2683   }
2684 }
2685 
2686 /// Legalize the given unresolved materialization. Returns success if the
2687 /// materialization was legalized, failure otherise.
2688 static LogicalResult legalizeUnresolvedMaterialization(
2689     UnresolvedMaterialization &mat,
2690     DenseMap<Operation *, UnresolvedMaterialization *> &materializationOps,
2691     ConversionPatternRewriter &rewriter,
2692     ConversionPatternRewriterImpl &rewriterImpl,
2693     DenseMap<Value, SmallVector<Value>> &inverseMapping) {
2694   auto findLiveUser = [&](auto &&users) {
2695     auto liveUserIt = llvm::find_if_not(
2696         users, [&](Operation *user) { return rewriterImpl.isOpIgnored(user); });
2697     return liveUserIt == users.end() ? nullptr : *liveUserIt;
2698   };
2699 
2700   llvm::unique_function<Value(Value, Type)> lookupRemappedValue =
2701       [&](Value value, Type type) {
2702         // Check to see if the input operation was remapped to a variant of the
2703         // output.
2704         Value remappedValue = rewriterImpl.mapping.lookupOrDefault(value, type);
2705         if (remappedValue.getType() == type)
2706           return remappedValue;
2707         return Value();
2708       };
2709 
2710   UnrealizedConversionCastOp op = mat.getOp();
2711   if (!rewriterImpl.ignoredOps.insert(op))
2712     return success();
2713 
2714   // We currently only handle target materializations here.
2715   OpResult opResult = op->getOpResult(0);
2716   Operation::operand_range inputOperands = op.getOperands();
2717   Type outputType = opResult.getType();
2718 
2719   // If any input to this materialization is another materialization, resolve
2720   // the input first.
2721   for (Value value : op->getOperands()) {
2722     auto valueCast = value.getDefiningOp<UnrealizedConversionCastOp>();
2723     if (!valueCast)
2724       continue;
2725 
2726     auto matIt = materializationOps.find(valueCast);
2727     if (matIt != materializationOps.end())
2728       if (failed(legalizeUnresolvedMaterialization(
2729               *matIt->second, materializationOps, rewriter, rewriterImpl,
2730               inverseMapping)))
2731         return failure();
2732   }
2733 
2734   // Perform a last ditch attempt to avoid materializing a resolved
2735   // materialization if possible.
2736   // Handle the case of a 1-1 materialization.
2737   if (inputOperands.size() == 1) {
2738     // Check to see if the input operation was remapped to a variant of the
2739     // output.
2740     Value remappedValue = lookupRemappedValue(inputOperands[0], outputType);
2741     if (remappedValue && remappedValue != opResult) {
2742       replaceMaterialization(rewriterImpl, opResult, remappedValue,
2743                              inverseMapping);
2744       return success();
2745     }
2746   } else {
2747     // TODO: Avoid materializing other types of conversions here.
2748   }
2749 
2750   // Try to materialize the conversion.
2751   if (TypeConverter *converter = mat.getConverter()) {
2752     // FIXME: Determine a suitable insertion location when there are multiple
2753     // inputs.
2754     if (inputOperands.size() == 1)
2755       rewriter.setInsertionPointAfterValue(inputOperands.front());
2756     else
2757       rewriter.setInsertionPoint(op);
2758 
2759     Value newMaterialization;
2760     switch (mat.getKind()) {
2761     case UnresolvedMaterialization::Argument:
2762       // Try to materialize an argument conversion.
2763       // FIXME: The current argument materialization hook expects the original
2764       // output type, even though it doesn't use that as the actual output type
2765       // of the generated IR. The output type is just used as an indicator of
2766       // the type of materialization to do. This behavior is really awkward in
2767       // that it diverges from the behavior of the other hooks, and can be
2768       // easily misunderstood. We should clean up the argument hooks to better
2769       // represent the desired invariants we actually care about.
2770       newMaterialization = converter->materializeArgumentConversion(
2771           rewriter, op->getLoc(), mat.getOrigOutputType(), inputOperands);
2772       if (newMaterialization)
2773         break;
2774 
2775       // If an argument materialization failed, fallback to trying a target
2776       // materialization.
2777       LLVM_FALLTHROUGH;
2778     case UnresolvedMaterialization::Target:
2779       newMaterialization = converter->materializeTargetConversion(
2780           rewriter, op->getLoc(), outputType, inputOperands);
2781       break;
2782     }
2783     if (newMaterialization) {
2784       replaceMaterialization(rewriterImpl, opResult, newMaterialization,
2785                              inverseMapping);
2786       return success();
2787     }
2788   }
2789 
2790   InFlightDiagnostic diag = op->emitError()
2791                             << "failed to legalize unresolved materialization "
2792                                "from "
2793                             << inputOperands.getTypes() << " to " << outputType
2794                             << " that remained live after conversion";
2795   if (Operation *liveUser = findLiveUser(op->getUsers())) {
2796     diag.attachNote(liveUser->getLoc())
2797         << "see existing live user here: " << *liveUser;
2798   }
2799   return failure();
2800 }
2801 
2802 LogicalResult OperationConverter::legalizeUnresolvedMaterializations(
2803     ConversionPatternRewriter &rewriter,
2804     ConversionPatternRewriterImpl &rewriterImpl,
2805     Optional<DenseMap<Value, SmallVector<Value>>> &inverseMapping) {
2806   if (rewriterImpl.unresolvedMaterializations.empty())
2807     return success();
2808   inverseMapping = rewriterImpl.mapping.getInverse();
2809 
2810   // As an initial step, compute all of the inserted materializations that we
2811   // expect to persist beyond the conversion process.
2812   DenseMap<Operation *, UnresolvedMaterialization *> materializationOps;
2813   SetVector<UnresolvedMaterialization *> necessaryMaterializations;
2814   computeNecessaryMaterializations(materializationOps, rewriter, rewriterImpl,
2815                                    *inverseMapping, necessaryMaterializations);
2816 
2817   // Once computed, legalize any necessary materializations.
2818   for (auto *mat : necessaryMaterializations) {
2819     if (failed(legalizeUnresolvedMaterialization(
2820             *mat, materializationOps, rewriter, rewriterImpl, *inverseMapping)))
2821       return failure();
2822   }
2823   return success();
2824 }
2825 
2826 LogicalResult OperationConverter::legalizeErasedResult(
2827     Operation *op, OpResult result,
2828     ConversionPatternRewriterImpl &rewriterImpl) {
2829   // If the operation result was replaced with null, all of the uses of this
2830   // value should be replaced.
2831   auto liveUserIt = llvm::find_if_not(result.getUsers(), [&](Operation *user) {
2832     return rewriterImpl.isOpIgnored(user);
2833   });
2834   if (liveUserIt != result.user_end()) {
2835     InFlightDiagnostic diag = op->emitError("failed to legalize operation '")
2836                               << op->getName() << "' marked as erased";
2837     diag.attachNote(liveUserIt->getLoc())
2838         << "found live user of result #" << result.getResultNumber() << ": "
2839         << *liveUserIt;
2840     return failure();
2841   }
2842   return success();
2843 }
2844 
2845 /// Finds a user of the given value, or of any other value that the given value
2846 /// replaced, that was not replaced in the conversion process.
2847 static Operation *findLiveUserOfReplaced(
2848     Value initialValue, ConversionPatternRewriterImpl &rewriterImpl,
2849     const DenseMap<Value, SmallVector<Value>> &inverseMapping) {
2850   SmallVector<Value> worklist(1, initialValue);
2851   while (!worklist.empty()) {
2852     Value value = worklist.pop_back_val();
2853 
2854     // Walk the users of this value to see if there are any live users that
2855     // weren't replaced during conversion.
2856     auto liveUserIt = llvm::find_if_not(value.getUsers(), [&](Operation *user) {
2857       return rewriterImpl.isOpIgnored(user);
2858     });
2859     if (liveUserIt != value.user_end())
2860       return *liveUserIt;
2861     auto mapIt = inverseMapping.find(value);
2862     if (mapIt != inverseMapping.end())
2863       worklist.append(mapIt->second);
2864   }
2865   return nullptr;
2866 }
2867 
2868 LogicalResult OperationConverter::legalizeChangedResultType(
2869     Operation *op, OpResult result, Value newValue,
2870     TypeConverter *replConverter, ConversionPatternRewriter &rewriter,
2871     ConversionPatternRewriterImpl &rewriterImpl,
2872     const DenseMap<Value, SmallVector<Value>> &inverseMapping) {
2873   Operation *liveUser =
2874       findLiveUserOfReplaced(result, rewriterImpl, inverseMapping);
2875   if (!liveUser)
2876     return success();
2877 
2878   // Functor used to emit a conversion error for a failed materialization.
2879   auto emitConversionError = [&] {
2880     InFlightDiagnostic diag = op->emitError()
2881                               << "failed to materialize conversion for result #"
2882                               << result.getResultNumber() << " of operation '"
2883                               << op->getName()
2884                               << "' that remained live after conversion";
2885     diag.attachNote(liveUser->getLoc())
2886         << "see existing live user here: " << *liveUser;
2887     return failure();
2888   };
2889 
2890   // If the replacement has a type converter, attempt to materialize a
2891   // conversion back to the original type.
2892   if (!replConverter)
2893     return emitConversionError();
2894 
2895   // Materialize a conversion for this live result value.
2896   Type resultType = result.getType();
2897   Value convertedValue = replConverter->materializeSourceConversion(
2898       rewriter, op->getLoc(), resultType, newValue);
2899   if (!convertedValue)
2900     return emitConversionError();
2901 
2902   rewriterImpl.mapping.map(result, convertedValue);
2903   return success();
2904 }
2905 
2906 //===----------------------------------------------------------------------===//
2907 // Type Conversion
2908 //===----------------------------------------------------------------------===//
2909 
2910 void TypeConverter::SignatureConversion::addInputs(unsigned origInputNo,
2911                                                    ArrayRef<Type> types) {
2912   assert(!types.empty() && "expected valid types");
2913   remapInput(origInputNo, /*newInputNo=*/argTypes.size(), types.size());
2914   addInputs(types);
2915 }
2916 
2917 void TypeConverter::SignatureConversion::addInputs(ArrayRef<Type> types) {
2918   assert(!types.empty() &&
2919          "1->0 type remappings don't need to be added explicitly");
2920   argTypes.append(types.begin(), types.end());
2921 }
2922 
2923 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo,
2924                                                     unsigned newInputNo,
2925                                                     unsigned newInputCount) {
2926   assert(!remappedInputs[origInputNo] && "input has already been remapped");
2927   assert(newInputCount != 0 && "expected valid input count");
2928   remappedInputs[origInputNo] =
2929       InputMapping{newInputNo, newInputCount, /*replacementValue=*/nullptr};
2930 }
2931 
2932 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo,
2933                                                     Value replacementValue) {
2934   assert(!remappedInputs[origInputNo] && "input has already been remapped");
2935   remappedInputs[origInputNo] =
2936       InputMapping{origInputNo, /*size=*/0, replacementValue};
2937 }
2938 
2939 LogicalResult TypeConverter::convertType(Type t,
2940                                          SmallVectorImpl<Type> &results) {
2941   auto existingIt = cachedDirectConversions.find(t);
2942   if (existingIt != cachedDirectConversions.end()) {
2943     if (existingIt->second)
2944       results.push_back(existingIt->second);
2945     return success(existingIt->second != nullptr);
2946   }
2947   auto multiIt = cachedMultiConversions.find(t);
2948   if (multiIt != cachedMultiConversions.end()) {
2949     results.append(multiIt->second.begin(), multiIt->second.end());
2950     return success();
2951   }
2952 
2953   // Walk the added converters in reverse order to apply the most recently
2954   // registered first.
2955   size_t currentCount = results.size();
2956   conversionCallStack.push_back(t);
2957   auto popConversionCallStack =
2958       llvm::make_scope_exit([this]() { conversionCallStack.pop_back(); });
2959   for (ConversionCallbackFn &converter : llvm::reverse(conversions)) {
2960     if (Optional<LogicalResult> result =
2961             converter(t, results, conversionCallStack)) {
2962       if (!succeeded(*result)) {
2963         cachedDirectConversions.try_emplace(t, nullptr);
2964         return failure();
2965       }
2966       auto newTypes = ArrayRef<Type>(results).drop_front(currentCount);
2967       if (newTypes.size() == 1)
2968         cachedDirectConversions.try_emplace(t, newTypes.front());
2969       else
2970         cachedMultiConversions.try_emplace(t, llvm::to_vector<2>(newTypes));
2971       return success();
2972     }
2973   }
2974   return failure();
2975 }
2976 
2977 Type TypeConverter::convertType(Type t) {
2978   // Use the multi-type result version to convert the type.
2979   SmallVector<Type, 1> results;
2980   if (failed(convertType(t, results)))
2981     return nullptr;
2982 
2983   // Check to ensure that only one type was produced.
2984   return results.size() == 1 ? results.front() : nullptr;
2985 }
2986 
2987 LogicalResult TypeConverter::convertTypes(TypeRange types,
2988                                           SmallVectorImpl<Type> &results) {
2989   for (Type type : types)
2990     if (failed(convertType(type, results)))
2991       return failure();
2992   return success();
2993 }
2994 
2995 bool TypeConverter::isLegal(Type type) { return convertType(type) == type; }
2996 bool TypeConverter::isLegal(Operation *op) {
2997   return isLegal(op->getOperandTypes()) && isLegal(op->getResultTypes());
2998 }
2999 
3000 bool TypeConverter::isLegal(Region *region) {
3001   return llvm::all_of(*region, [this](Block &block) {
3002     return isLegal(block.getArgumentTypes());
3003   });
3004 }
3005 
3006 bool TypeConverter::isSignatureLegal(FunctionType ty) {
3007   return isLegal(llvm::concat<const Type>(ty.getInputs(), ty.getResults()));
3008 }
3009 
3010 LogicalResult TypeConverter::convertSignatureArg(unsigned inputNo, Type type,
3011                                                  SignatureConversion &result) {
3012   // Try to convert the given input type.
3013   SmallVector<Type, 1> convertedTypes;
3014   if (failed(convertType(type, convertedTypes)))
3015     return failure();
3016 
3017   // If this argument is being dropped, there is nothing left to do.
3018   if (convertedTypes.empty())
3019     return success();
3020 
3021   // Otherwise, add the new inputs.
3022   result.addInputs(inputNo, convertedTypes);
3023   return success();
3024 }
3025 LogicalResult TypeConverter::convertSignatureArgs(TypeRange types,
3026                                                   SignatureConversion &result,
3027                                                   unsigned origInputOffset) {
3028   for (unsigned i = 0, e = types.size(); i != e; ++i)
3029     if (failed(convertSignatureArg(origInputOffset + i, types[i], result)))
3030       return failure();
3031   return success();
3032 }
3033 
3034 Value TypeConverter::materializeConversion(
3035     MutableArrayRef<MaterializationCallbackFn> materializations,
3036     OpBuilder &builder, Location loc, Type resultType, ValueRange inputs) {
3037   for (MaterializationCallbackFn &fn : llvm::reverse(materializations))
3038     if (Optional<Value> result = fn(builder, resultType, inputs, loc))
3039       return result.getValue();
3040   return nullptr;
3041 }
3042 
3043 auto TypeConverter::convertBlockSignature(Block *block)
3044     -> Optional<SignatureConversion> {
3045   SignatureConversion conversion(block->getNumArguments());
3046   if (failed(convertSignatureArgs(block->getArgumentTypes(), conversion)))
3047     return llvm::None;
3048   return conversion;
3049 }
3050 
3051 //===----------------------------------------------------------------------===//
3052 // FunctionLikeSignatureConversion
3053 //===----------------------------------------------------------------------===//
3054 
3055 /// Create a default conversion pattern that rewrites the type signature of a
3056 /// FunctionLike op. This only supports FunctionLike ops which use FunctionType
3057 /// to represent their type.
3058 namespace {
3059 struct FunctionLikeSignatureConversion : public ConversionPattern {
3060   FunctionLikeSignatureConversion(StringRef functionLikeOpName,
3061                                   MLIRContext *ctx, TypeConverter &converter)
3062       : ConversionPattern(converter, functionLikeOpName, /*benefit=*/1, ctx) {}
3063 
3064   /// Hook to implement combined matching and rewriting for FunctionLike ops.
3065   LogicalResult
3066   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
3067                   ConversionPatternRewriter &rewriter) const override {
3068     FunctionType type = function_like_impl::getFunctionType(op);
3069 
3070     // Convert the original function types.
3071     TypeConverter::SignatureConversion result(type.getNumInputs());
3072     SmallVector<Type, 1> newResults;
3073     if (failed(typeConverter->convertSignatureArgs(type.getInputs(), result)) ||
3074         failed(typeConverter->convertTypes(type.getResults(), newResults)) ||
3075         failed(rewriter.convertRegionTypes(
3076             &function_like_impl::getFunctionBody(op), *typeConverter, &result)))
3077       return failure();
3078 
3079     // Update the function signature in-place.
3080     auto newType = FunctionType::get(rewriter.getContext(),
3081                                      result.getConvertedTypes(), newResults);
3082 
3083     rewriter.updateRootInPlace(
3084         op, [&] { function_like_impl::setFunctionType(op, newType); });
3085 
3086     return success();
3087   }
3088 };
3089 } // namespace
3090 
3091 void mlir::populateFunctionLikeTypeConversionPattern(
3092     StringRef functionLikeOpName, RewritePatternSet &patterns,
3093     TypeConverter &converter) {
3094   patterns.add<FunctionLikeSignatureConversion>(
3095       functionLikeOpName, patterns.getContext(), converter);
3096 }
3097 
3098 void mlir::populateFuncOpTypeConversionPattern(RewritePatternSet &patterns,
3099                                                TypeConverter &converter) {
3100   populateFunctionLikeTypeConversionPattern<FuncOp>(patterns, converter);
3101 }
3102 
3103 //===----------------------------------------------------------------------===//
3104 // ConversionTarget
3105 //===----------------------------------------------------------------------===//
3106 
3107 void ConversionTarget::setOpAction(OperationName op,
3108                                    LegalizationAction action) {
3109   legalOperations[op].action = action;
3110 }
3111 
3112 void ConversionTarget::setDialectAction(ArrayRef<StringRef> dialectNames,
3113                                         LegalizationAction action) {
3114   for (StringRef dialect : dialectNames)
3115     legalDialects[dialect] = action;
3116 }
3117 
3118 auto ConversionTarget::getOpAction(OperationName op) const
3119     -> Optional<LegalizationAction> {
3120   Optional<LegalizationInfo> info = getOpInfo(op);
3121   return info ? info->action : Optional<LegalizationAction>();
3122 }
3123 
3124 auto ConversionTarget::isLegal(Operation *op) const
3125     -> Optional<LegalOpDetails> {
3126   Optional<LegalizationInfo> info = getOpInfo(op->getName());
3127   if (!info)
3128     return llvm::None;
3129 
3130   // Returns true if this operation instance is known to be legal.
3131   auto isOpLegal = [&] {
3132     // Handle dynamic legality either with the provided legality function.
3133     if (info->action == LegalizationAction::Dynamic) {
3134       Optional<bool> result = info->legalityFn(op);
3135       if (result)
3136         return *result;
3137     }
3138 
3139     // Otherwise, the operation is only legal if it was marked 'Legal'.
3140     return info->action == LegalizationAction::Legal;
3141   };
3142   if (!isOpLegal())
3143     return llvm::None;
3144 
3145   // This operation is legal, compute any additional legality information.
3146   LegalOpDetails legalityDetails;
3147   if (info->isRecursivelyLegal) {
3148     auto legalityFnIt = opRecursiveLegalityFns.find(op->getName());
3149     if (legalityFnIt != opRecursiveLegalityFns.end()) {
3150       legalityDetails.isRecursivelyLegal =
3151           legalityFnIt->second(op).getValueOr(true);
3152     } else {
3153       legalityDetails.isRecursivelyLegal = true;
3154     }
3155   }
3156   return legalityDetails;
3157 }
3158 
3159 bool ConversionTarget::isIllegal(Operation *op) const {
3160   Optional<LegalizationInfo> info = getOpInfo(op->getName());
3161   if (!info)
3162     return false;
3163 
3164   if (info->action == LegalizationAction::Dynamic) {
3165     Optional<bool> result = info->legalityFn(op);
3166     if (!result)
3167       return false;
3168 
3169     return !(*result);
3170   }
3171 
3172   return info->action == LegalizationAction::Illegal;
3173 }
3174 
3175 static ConversionTarget::DynamicLegalityCallbackFn composeLegalityCallbacks(
3176     ConversionTarget::DynamicLegalityCallbackFn oldCallback,
3177     ConversionTarget::DynamicLegalityCallbackFn newCallback) {
3178   if (!oldCallback)
3179     return newCallback;
3180 
3181   auto chain = [oldCl = std::move(oldCallback), newCl = std::move(newCallback)](
3182                    Operation *op) -> Optional<bool> {
3183     if (Optional<bool> result = newCl(op))
3184       return *result;
3185 
3186     return oldCl(op);
3187   };
3188   return chain;
3189 }
3190 
3191 void ConversionTarget::setLegalityCallback(
3192     OperationName name, const DynamicLegalityCallbackFn &callback) {
3193   assert(callback && "expected valid legality callback");
3194   auto infoIt = legalOperations.find(name);
3195   assert(infoIt != legalOperations.end() &&
3196          infoIt->second.action == LegalizationAction::Dynamic &&
3197          "expected operation to already be marked as dynamically legal");
3198   infoIt->second.legalityFn =
3199       composeLegalityCallbacks(std::move(infoIt->second.legalityFn), callback);
3200 }
3201 
3202 void ConversionTarget::markOpRecursivelyLegal(
3203     OperationName name, const DynamicLegalityCallbackFn &callback) {
3204   auto infoIt = legalOperations.find(name);
3205   assert(infoIt != legalOperations.end() &&
3206          infoIt->second.action != LegalizationAction::Illegal &&
3207          "expected operation to already be marked as legal");
3208   infoIt->second.isRecursivelyLegal = true;
3209   if (callback)
3210     opRecursiveLegalityFns[name] = composeLegalityCallbacks(
3211         std::move(opRecursiveLegalityFns[name]), callback);
3212   else
3213     opRecursiveLegalityFns.erase(name);
3214 }
3215 
3216 void ConversionTarget::setLegalityCallback(
3217     ArrayRef<StringRef> dialects, const DynamicLegalityCallbackFn &callback) {
3218   assert(callback && "expected valid legality callback");
3219   for (StringRef dialect : dialects)
3220     dialectLegalityFns[dialect] = composeLegalityCallbacks(
3221         std::move(dialectLegalityFns[dialect]), callback);
3222 }
3223 
3224 void ConversionTarget::setLegalityCallback(
3225     const DynamicLegalityCallbackFn &callback) {
3226   assert(callback && "expected valid legality callback");
3227   unknownLegalityFn = composeLegalityCallbacks(unknownLegalityFn, callback);
3228 }
3229 
3230 auto ConversionTarget::getOpInfo(OperationName op) const
3231     -> Optional<LegalizationInfo> {
3232   // Check for info for this specific operation.
3233   auto it = legalOperations.find(op);
3234   if (it != legalOperations.end())
3235     return it->second;
3236   // Check for info for the parent dialect.
3237   auto dialectIt = legalDialects.find(op.getDialectNamespace());
3238   if (dialectIt != legalDialects.end()) {
3239     DynamicLegalityCallbackFn callback;
3240     auto dialectFn = dialectLegalityFns.find(op.getDialectNamespace());
3241     if (dialectFn != dialectLegalityFns.end())
3242       callback = dialectFn->second;
3243     return LegalizationInfo{dialectIt->second, /*isRecursivelyLegal=*/false,
3244                             callback};
3245   }
3246   // Otherwise, check if we mark unknown operations as dynamic.
3247   if (unknownLegalityFn)
3248     return LegalizationInfo{LegalizationAction::Dynamic,
3249                             /*isRecursivelyLegal=*/false, unknownLegalityFn};
3250   return llvm::None;
3251 }
3252 
3253 //===----------------------------------------------------------------------===//
3254 // Op Conversion Entry Points
3255 //===----------------------------------------------------------------------===//
3256 
3257 //===----------------------------------------------------------------------===//
3258 // Partial Conversion
3259 
3260 LogicalResult
3261 mlir::applyPartialConversion(ArrayRef<Operation *> ops,
3262                              ConversionTarget &target,
3263                              const FrozenRewritePatternSet &patterns,
3264                              DenseSet<Operation *> *unconvertedOps) {
3265   OperationConverter opConverter(target, patterns, OpConversionMode::Partial,
3266                                  unconvertedOps);
3267   return opConverter.convertOperations(ops);
3268 }
3269 LogicalResult
3270 mlir::applyPartialConversion(Operation *op, ConversionTarget &target,
3271                              const FrozenRewritePatternSet &patterns,
3272                              DenseSet<Operation *> *unconvertedOps) {
3273   return applyPartialConversion(llvm::makeArrayRef(op), target, patterns,
3274                                 unconvertedOps);
3275 }
3276 
3277 //===----------------------------------------------------------------------===//
3278 // Full Conversion
3279 
3280 LogicalResult
3281 mlir::applyFullConversion(ArrayRef<Operation *> ops, ConversionTarget &target,
3282                           const FrozenRewritePatternSet &patterns) {
3283   OperationConverter opConverter(target, patterns, OpConversionMode::Full);
3284   return opConverter.convertOperations(ops);
3285 }
3286 LogicalResult
3287 mlir::applyFullConversion(Operation *op, ConversionTarget &target,
3288                           const FrozenRewritePatternSet &patterns) {
3289   return applyFullConversion(llvm::makeArrayRef(op), target, patterns);
3290 }
3291 
3292 //===----------------------------------------------------------------------===//
3293 // Analysis Conversion
3294 
3295 LogicalResult
3296 mlir::applyAnalysisConversion(ArrayRef<Operation *> ops,
3297                               ConversionTarget &target,
3298                               const FrozenRewritePatternSet &patterns,
3299                               DenseSet<Operation *> &convertedOps,
3300                               function_ref<void(Diagnostic &)> notifyCallback) {
3301   OperationConverter opConverter(target, patterns, OpConversionMode::Analysis,
3302                                  &convertedOps);
3303   return opConverter.convertOperations(ops, notifyCallback);
3304 }
3305 LogicalResult
3306 mlir::applyAnalysisConversion(Operation *op, ConversionTarget &target,
3307                               const FrozenRewritePatternSet &patterns,
3308                               DenseSet<Operation *> &convertedOps,
3309                               function_ref<void(Diagnostic &)> notifyCallback) {
3310   return applyAnalysisConversion(llvm::makeArrayRef(op), target, patterns,
3311                                  convertedOps, notifyCallback);
3312 }
3313