14#ifndef MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
15#define MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
28#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/IR/FPEnv.h"
31#include "llvm/IR/Module.h"
32#include "llvm/Support/VirtualFileSystemFwd.h"
56class AliasScopeDomainAttr;
59class ComdatSelectorOp;
66class ModuleTranslation {
67 friend std::unique_ptr<llvm::Module>
69 bool, llvm::vfs::FileSystem *);
74 auto result = functionMapping.try_emplace(name,
func);
77 "attempting to map a function that is already mapped");
82 return functionMapping.lookup(name);
91 llvm::Value *&
llvm = valueMapping[value];
92 assert(
llvm ==
nullptr &&
93 "attempting to map a value that is already mapped");
99 return valueMapping.lookup(value);
114 assert(
result.second &&
"attempting to map a block that is already mapped");
119 return blockMapping.lookup(block);
128 "attempting to map a branch that is already mapped");
134 return branchMapping.lookup(op);
142 assert(
result.second &&
"attempting to map a call that is already mapped");
148 return callMapping.lookup(op);
154 auto result = unresolvedBlockAddressMapping.try_emplace(op, cst);
157 "attempting to map a blockaddress operation that is already mapped");
162 auto result = blockAddressToLLVMMapping.try_emplace(attr, block);
165 "attempting to map a blockaddress attribute that is already mapped");
170 return blockAddressToLLVMMapping.lookup(attr);
192 llvm::Instruction *inst);
196 llvm::Instruction *inst);
199 void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst);
208 llvm::Instruction *inst);
235 return globalsMapping.lookup(op);
240 return globalsByNameMapping.lookup(name);
246 return aliasesMapping.lookup(op);
252 return ifuncMapping.lookup(op);
269 llvm::DIGlobalVariableExpression *
279 llvm::fp::ExceptionBehavior
290 llvm::IRBuilderBase &builder) {
291 return convertBlockImpl(bb, ignoreArguments, builder,
299 return convertOperationImpl(op, builder,
false);
310 llvm::CallBase *call,
320 FailureOr<llvm::Metadata *>
329 template <
typename T,
typename... Args>
331 stack.stackPush<T>(std::forward<Args>(args)...);
339 template <
typename T>
341 return stack.stackWalk(callback);
345 template <
typename T>
364 template <
typename T,
typename... Args>
366 static_assert(std::is_base_of<Extension, T>::value,
367 "expected T derived from ModuleTranslation::Extension");
369 auto it = extensions.find(
id);
370 if (it != extensions.end())
371 return static_cast<T &
>(*it->second);
373 auto extension = std::make_unique<T>(std::forward<Args>(args)...);
375 extensions.insert({id, std::move(extension)});
383 static std::optional<llvm::Attribute>
convertNoBuiltin(llvm::LLVMContext &ctx,
386 static std::optional<llvm::Attribute>
393 template <
typename AttrsTy,
typename Operation,
typename Converter>
395 const Converter &conv) {
398 for (
auto elt : attrs) {
409 llvm::vfs::FileSystem *fs =
nullptr);
414 llvm::IRBuilderBase &builder,
415 bool recordInsertions =
false);
416 LogicalResult convertFunctionSignatures();
417 LogicalResult convertFunctionMetadata();
418 LogicalResult convertFunctions();
419 LogicalResult convertIFuncs();
420 LogicalResult convertComdats();
422 LogicalResult convertUnresolvedBlockAddress();
431 LogicalResult convertGlobalsAndAliases();
436 LogicalResult convertGlobalMetadata();
438 FailureOr<llvm::Metadata *>
441 LogicalResult convertOneFunction(LLVMFuncOp
func);
442 LogicalResult convertBlockImpl(
Block &bb,
bool ignoreArguments,
443 llvm::IRBuilderBase &builder,
444 bool recordInsertions);
448 llvm::MDNode *getTBAANode(TBAATagAttr tbaaAttr)
const;
452 LogicalResult createTBAAMetadata();
455 LogicalResult createIdentMetadata();
458 LogicalResult createCommandlineMetadata();
461 LogicalResult createDependentLibrariesMetadata();
470 FailureOr<llvm::AttrBuilder> convertParameterAttrs(
mlir::Location loc,
471 DictionaryAttr paramAttrs);
475 FailureOr<llvm::AttrBuilder>
476 convertParameterAttrs(LLVMFuncOp
func,
int argIdx, DictionaryAttr paramAttrs);
480 std::unique_ptr<llvm::Module> llvmModule;
482 std::unique_ptr<detail::DebugTranslation> debugTranslation;
485 std::unique_ptr<detail::LoopAnnotationTranslation> loopAnnotationTranslation;
492 llvm::vfs::FileSystem *fileSystem =
nullptr;
501 llvm::StringMap<llvm::GlobalValue *> globalsByNameMapping;
519 llvm::StringMap<llvm::Function *> functionMapping;
579 const ModuleTranslation &moduleTranslation);
583 llvm::Intrinsic::ID intrinsic,
585 ArrayRef<llvm::Type *> tys = {});
592 llvm::Intrinsic::ID intrinsic,
594 ArrayRef<llvm::Value *> args);
600 llvm::IRBuilderBase &builder, ModuleTranslation &moduleTranslation,
601 Operation *intrOp, llvm::Intrinsic::ID intrinsic,
unsigned numResults,
602 ArrayRef<unsigned> overloadedResults, ArrayRef<unsigned> overloadedOperands,
603 ArrayRef<unsigned> immArgPositions,
604 ArrayRef<StringLiteral> immArgAttrNames);
static LogicalResult convertOperationImpl(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
A symbol reference with a reference path containing a single element.
This class represents a diagnostic that is inflight and set to be reported.
Interface collection for translation to LLVM IR, dispatches to a concrete interface implementation ba...
This class represents the base attribute for all debug info attributes.
Base class for state that lives as long as the module translation.
virtual LogicalResult finalize()
Called once after all operations have been translated and before the LLVM module is verified.
Implementation class for module translation.
void mapUnresolvedBlockAddress(BlockAddressOp op, llvm::Value *cst)
Maps a blockaddress operation to its corresponding placeholder LLVM value.
llvm::fp::ExceptionBehavior translateFPExceptionBehavior(LLVM::FPExceptionBehavior exceptionBehavior)
Translates the given LLVM FP exception behavior metadata.
llvm::CallInst * lookupCall(Operation *op) const
Finds an LLVM call instruction that corresponds to the given MLIR call operation.
void mapCall(Operation *mlir, llvm::CallInst *llvm)
Stores a mapping between an MLIR call operation and a corresponding LLVM call instruction.
llvm::BasicBlock * lookupBlock(Block *block) const
Finds an LLVM IR basic block that corresponds to the given MLIR block.
llvm::DIGlobalVariableExpression * translateGlobalVariableExpression(LLVM::DIGlobalVariableExpressionAttr attr)
Translates the given LLVM global variable expression metadata.
llvm::Attribute convertAllocsizeAttr(DenseI32ArrayAttr allocsizeAttr)
MLIRContext & getContext()
Returns the MLIR context of the module being translated.
WalkResult stackWalk(llvm::function_ref< WalkResult(T &)> callback)
Calls callback for every ModuleTranslation stack frame of type T starting from the top of the stack.
void stackPush(Args &&...args)
Creates a stack frame of type T on ModuleTranslation stack.
llvm::NamedMDNode * getOrInsertNamedModuleMetadata(StringRef name)
Gets the named metadata in the LLVM IR module being constructed, creating it if it does not exist.
LogicalResult convertBlock(Block &bb, bool ignoreArguments, llvm::IRBuilderBase &builder)
Translates the contents of the given block to LLVM IR using this translator.
void mapBranch(Operation *mlir, llvm::Instruction *llvm)
Stores the mapping between an MLIR operation with successors and a corresponding LLVM IR instruction.
SmallVector< llvm::Value * > lookupValues(ValueRange values)
Looks up remapped a list of remapped values.
void mapFunction(StringRef name, llvm::Function *func)
Stores the mapping between a function name and its LLVM IR representation.
void convertFunctionAttrCollection(AttrsTy attrs, Operation *op, const Converter &conv)
A template that takes a collection-like attribute, and converts it via a user provided callback,...
llvm::DILocation * translateLoc(Location loc, llvm::DILocalScope *scope)
Translates the given location.
void setDereferenceableMetadata(DereferenceableOpInterface op, llvm::Instruction *inst)
Sets LLVM dereferenceable metadata for operations that have dereferenceable attributes.
void setBranchWeightsMetadata(WeightedBranchOpInterface op)
Sets LLVM profiling metadata for operations that have branch weights.
llvm::Instruction * lookupBranch(Operation *op) const
Finds an LLVM IR instruction that corresponds to the given MLIR operation with successors.
T & getOrCreateExtension(Args &&...args)
Returns the extension of type T, constructing it from args on first use.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
LogicalResult convertArgAndResultAttrs(ArgAndResultAttrsOpInterface attrsOp, llvm::CallBase *call, ArrayRef< unsigned > immArgPositions={})
Converts argument and result attributes from attrsOp to LLVM IR attributes on the call instruction.
static std::optional< llvm::Attribute > convertNoBuiltin(llvm::LLVMContext &ctx, mlir::Attribute a)
SymbolTableCollection & symbolTable()
llvm::Type * convertType(Type type)
Converts the type from MLIR LLVM dialect to LLVM.
llvm::Value *& mapValue(Value value)
Provides write-once access to store the LLVM IR value corresponding to the given MLIR value.
llvm::RoundingMode translateRoundingMode(LLVM::RoundingMode rounding)
Translates the given LLVM rounding mode metadata.
void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
llvm::DIExpression * translateExpression(LLVM::DIExpressionAttr attr)
Translates the given LLVM DWARF expression metadata.
llvm::vfs::FileSystem & getFileSystem()
Returns the virtual filesystem to use for file operations.
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
llvm::GlobalValue * lookupGlobal(StringRef name) const
Finds an LLVM IR global value by the mlir.global symbol name.
void forgetMapping(Value value)
Removes the mapping for the given value.
FailureOr< llvm::Metadata * > convertMetadataAttr(Attribute attr, function_ref< InFlightDiagnostic()> emitError)
Converts an LLVM dialect metadata attribute to LLVM IR metadata.
SaveStateStack< T, ModuleTranslation > SaveStack
RAII object calling stackPush/stackPop on construction/destruction.
llvm::BasicBlock * lookupBlockAddress(BlockAddressAttr attr) const
Finds the LLVM basic block that corresponds to the given BlockAddressAttr.
void remapAllValuesWith(llvm::Value *oldValue, llvm::Value *newValue)
Remap old value with new value in the MLIR-to-LLVM value map so later translations use the replacemen...
void setTBAAStructMetadata(ArrayAttr fields, llvm::Instruction *inst)
Sets LLVM tbaa.struct metadata on an aggregate copy, describing which fields of the aggregate the cop...
llvm::GlobalValue * lookupIFunc(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining an IFunc.
llvm::Metadata * translateDebugInfo(LLVM::DINodeAttr attr)
Translates the given LLVM debug info metadata.
void setDisjointFlag(Operation *op, llvm::Value *value)
Sets the disjoint flag attribute for the exported instruction value given the original operation op.
llvm::GlobalValue * lookupAlias(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global alias va...
LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder)
Converts the given MLIR operation into LLVM IR using this translator.
llvm::Function * lookupFunction(StringRef name) const
Finds an LLVM IR function by its name.
llvm::MDNode * getOrCreateAliasScopes(ArrayRef< AliasScopeAttr > aliasScopeAttrs)
Returns the LLVM metadata corresponding to an array of mlir LLVM dialect alias scope attributes.
void mapBlock(Block *mlir, llvm::BasicBlock *llvm)
Stores the mapping between an MLIR block and LLVM IR basic block.
llvm::MDNode * getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr)
Returns the LLVM metadata corresponding to a mlir LLVM dialect alias scope attribute.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
static std::optional< llvm::Attribute > convertDefaultFuncAttr(llvm::LLVMContext &ctx, mlir::NamedAttribute namedAttr)
void stackPop()
Pops the last element from the ModuleTranslation stack.
void forgetMapping(Region ®ion)
Removes the mapping for blocks contained in the region and values defined in these blocks.
void setAliasScopeMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
void setAccessGroupsMetadata(AccessGroupOpInterface op, llvm::Instruction *inst)
void mapValue(Value mlir, llvm::Value *llvm)
Stores the mapping between an MLIR value and its LLVM IR counterpart.
llvm::LLVMContext & getLLVMContext() const
Returns the LLVM context in which the IR is being constructed.
void mapBlockAddress(BlockAddressAttr attr, llvm::BasicBlock *block)
Maps a BlockAddressAttr to its corresponding LLVM basic block.
void setLoopMetadata(Operation *op, llvm::Instruction *inst)
Sets LLVM loop metadata for branch operations that have a loop annotation attribute.
Utility class to translate MLIR LLVM dialect types to LLVM IR.
A helper class that converts LoopAnnotationAttrs and AccessGroupAttrs into corresponding llvm::MDNode...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttribute represents a combination of a name and an Attribute value.
Operation is the basic unit of execution within MLIR.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
This class represents a collection of SymbolTables.
This class provides an efficient unique identifier for a specific C++ type.
static TypeID get()
Construct a type info object for the given type T.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
A utility result that is used to signal how to proceed with an ongoing walk:
The OpAsmOpInterface, see OpAsmInterface.td for more details.
void connectPHINodes(Region ®ion, const ModuleTranslation &state)
For all blocks in the region that were converted to LLVM IR using the given ModuleTranslation,...
llvm::CallInst * createIntrinsicCall(llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, ArrayRef< llvm::Value * > args={}, ArrayRef< llvm::Type * > tys={})
Creates a call to an LLVM IR intrinsic function with the given arguments.
llvm::Constant * getLLVMConstant(llvm::Type *llvmType, Attribute attr, Location loc, const ModuleTranslation &moduleTranslation)
Create an LLVM IR constant of llvmType from the MLIR attribute attr.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
std::unique_ptr< llvm::Module > translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, llvm::StringRef name="LLVMDialectModule", bool disableVerification=false, llvm::vfs::FileSystem *fs=nullptr)
Translates a given LLVM dialect module into an LLVM IR module living in the given context.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
llvm::function_ref< Fn > function_ref
RAII object calling stackPush/stackPop on construction/destruction.