MLIR 23.0.0git
ModuleTranslation.h
Go to the documentation of this file.
1//===- ModuleTranslation.h - MLIR to LLVM conversion ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the translation between an MLIR LLVM dialect module and
10// the corresponding LLVMIR module. It only handles core LLVM IR operations.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
15#define MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
16
19#include "mlir/IR/Operation.h"
20#include "mlir/IR/SymbolTable.h"
21#include "mlir/IR/Value.h"
26
27#include "llvm/ADT/SetVector.h"
28#include "llvm/IR/FPEnv.h"
29#include "llvm/IR/Module.h"
30
31namespace llvm {
32class BasicBlock;
33class CallBase;
34class CanonicalLoopInfo;
35class Function;
36class IRBuilderBase;
37class OpenMPIRBuilder;
38class Value;
39namespace vfs {
40class FileSystem;
41} // namespace vfs
42} // namespace llvm
43
44namespace mlir {
45class Attribute;
46class Block;
47class Location;
48
49namespace LLVM {
50
51namespace detail {
54} // namespace detail
55
56class AliasScopeAttr;
57class AliasScopeDomainAttr;
58class DINodeAttr;
59class LLVMFuncOp;
60class ComdatSelectorOp;
61
62/// Implementation class for module translation. Holds a reference to the module
63/// being translated, and the mappings between the original and the translated
64/// functions, basic blocks and values. It is practically easier to hold these
65/// mappings in one class since the conversion of control flow operations
66/// needs to look up block and function mappings.
67class ModuleTranslation {
68 friend std::unique_ptr<llvm::Module>
69 mlir::translateModuleToLLVMIR(Operation *, llvm::LLVMContext &, StringRef,
70 bool, llvm::vfs::FileSystem *);
71
72public:
73 /// Stores the mapping between a function name and its LLVM IR representation.
74 void mapFunction(StringRef name, llvm::Function *func) {
75 auto result = functionMapping.try_emplace(name, func);
76 (void)result;
77 assert(result.second &&
78 "attempting to map a function that is already mapped");
79 }
80
81 /// Finds an LLVM IR function by its name.
82 llvm::Function *lookupFunction(StringRef name) const {
83 return functionMapping.lookup(name);
84 }
85
86 /// Stores the mapping between an MLIR value and its LLVM IR counterpart.
87 void mapValue(Value mlir, llvm::Value *llvm) { mapValue(mlir) = llvm; }
88
89 /// Provides write-once access to store the LLVM IR value corresponding to the
90 /// given MLIR value.
91 llvm::Value *&mapValue(Value value) {
92 llvm::Value *&llvm = valueMapping[value];
93 assert(llvm == nullptr &&
94 "attempting to map a value that is already mapped");
95 return llvm;
96 }
97
98 /// Finds an LLVM IR value corresponding to the given MLIR value.
99 llvm::Value *lookupValue(Value value) const {
100 return valueMapping.lookup(value);
101 }
102
103 /// Looks up remapped a list of remapped values.
105
106 /// Stores the mapping between an MLIR block and LLVM IR basic block.
107 void mapBlock(Block *mlir, llvm::BasicBlock *llvm) {
108 auto result = blockMapping.try_emplace(mlir, llvm);
109 (void)result;
110 assert(result.second && "attempting to map a block that is already mapped");
111 }
112
113 /// Finds an LLVM IR basic block that corresponds to the given MLIR block.
114 llvm::BasicBlock *lookupBlock(Block *block) const {
115 return blockMapping.lookup(block);
116 }
117
118 /// Find the LLVM-IR loop that represents an MLIR loop.
119 llvm::CanonicalLoopInfo *lookupOMPLoop(omp::NewCliOp mlir) const {
120 llvm::CanonicalLoopInfo *result = loopMapping.lookup(mlir);
121 assert(result && "attempt to get non-existing loop");
122 return result;
123 }
124
125 /// Find the LLVM-IR loop that represents an MLIR loop.
126 llvm::CanonicalLoopInfo *lookupOMPLoop(Value mlir) const {
127 return lookupOMPLoop(mlir.getDefiningOp<omp::NewCliOp>());
128 }
129
130 /// Mark an OpenMP loop as having been consumed.
131 void invalidateOmpLoop(omp::NewCliOp mlir) { loopMapping.erase(mlir); }
132
133 /// Mark an OpenMP loop as having been consumed.
135 invalidateOmpLoop(mlir.getDefiningOp<omp::NewCliOp>());
136 }
137
138 /// Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR
139 /// OpenMPIRBuilder CanonicalLoopInfo
140 void mapOmpLoop(omp::NewCliOp mlir, llvm::CanonicalLoopInfo *llvm) {
141 assert(llvm && "argument must be non-null");
142 llvm::CanonicalLoopInfo *&cur = loopMapping[mlir];
143 assert(cur == nullptr && "attempting to map a loop that is already mapped");
144 cur = llvm;
145 }
146
147 /// Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR
148 /// OpenMPIRBuilder CanonicalLoopInfo
149 void mapOmpLoop(Value mlir, llvm::CanonicalLoopInfo *llvm) {
150 mapOmpLoop(mlir.getDefiningOp<omp::NewCliOp>(), llvm);
151 }
152
153 /// Stores the mapping between an MLIR operation with successors and a
154 /// corresponding LLVM IR instruction.
155 void mapBranch(Operation *mlir, llvm::Instruction *llvm) {
156 auto result = branchMapping.try_emplace(mlir, llvm);
157 (void)result;
158 assert(result.second &&
159 "attempting to map a branch that is already mapped");
160 }
161
162 /// Finds an LLVM IR instruction that corresponds to the given MLIR operation
163 /// with successors.
164 llvm::Instruction *lookupBranch(Operation *op) const {
165 return branchMapping.lookup(op);
166 }
167
168 /// Stores a mapping between an MLIR call operation and a corresponding LLVM
169 /// call instruction.
170 void mapCall(Operation *mlir, llvm::CallInst *llvm) {
171 auto result = callMapping.try_emplace(mlir, llvm);
172 (void)result;
173 assert(result.second && "attempting to map a call that is already mapped");
174 }
175
176 /// Finds an LLVM call instruction that corresponds to the given MLIR call
177 /// operation.
178 llvm::CallInst *lookupCall(Operation *op) const {
179 return callMapping.lookup(op);
180 }
181
182 /// Maps a blockaddress operation to its corresponding placeholder LLVM
183 /// value.
184 void mapUnresolvedBlockAddress(BlockAddressOp op, llvm::Value *cst) {
185 auto result = unresolvedBlockAddressMapping.try_emplace(op, cst);
186 (void)result;
187 assert(result.second &&
188 "attempting to map a blockaddress operation that is already mapped");
189 }
190
191 /// Maps a BlockAddressAttr to its corresponding LLVM basic block.
192 void mapBlockAddress(BlockAddressAttr attr, llvm::BasicBlock *block) {
193 auto result = blockAddressToLLVMMapping.try_emplace(attr, block);
194 (void)result;
195 assert(result.second &&
196 "attempting to map a blockaddress attribute that is already mapped");
197 }
198
199 /// Finds the LLVM basic block that corresponds to the given BlockAddressAttr.
200 llvm::BasicBlock *lookupBlockAddress(BlockAddressAttr attr) const {
201 return blockAddressToLLVMMapping.lookup(attr);
202 }
203
204 /// Removes the mapping for blocks contained in the region and values defined
205 /// in these blocks.
206 void forgetMapping(Region &region);
207
208 /// Removes the mapping for the given value.
209 void forgetMapping(Value value) { valueMapping.erase(value); }
210
211 /// Returns the LLVM metadata corresponding to a mlir LLVM dialect alias scope
212 /// attribute. Creates the metadata node if it has not been converted before.
213 llvm::MDNode *getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr);
214
215 /// Returns the LLVM metadata corresponding to an array of mlir LLVM dialect
216 /// alias scope attributes. Creates the metadata nodes if they have not been
217 /// converted before.
218 llvm::MDNode *
220
221 // Sets LLVM metadata for memory operations that are in a parallel loop.
222 void setAccessGroupsMetadata(AccessGroupOpInterface op,
223 llvm::Instruction *inst);
224
225 // Sets LLVM metadata for memory operations that have alias scope information.
226 void setAliasScopeMetadata(AliasAnalysisOpInterface op,
227 llvm::Instruction *inst);
228
229 /// Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
230 void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst);
231
232 /// Sets LLVM dereferenceable metadata for operations that have
233 /// dereferenceable attributes.
234 void setDereferenceableMetadata(DereferenceableOpInterface op,
235 llvm::Instruction *inst);
236
237 /// Sets LLVM profiling metadata for operations that have branch weights.
238 void setBranchWeightsMetadata(WeightedBranchOpInterface op);
239
240 /// Sets LLVM loop metadata for branch operations that have a loop annotation
241 /// attribute.
242 void setLoopMetadata(Operation *op, llvm::Instruction *inst);
243
244 /// Sets the disjoint flag attribute for the exported instruction `value`
245 /// given the original operation `op`. Asserts if the operation does
246 /// not implement the disjoint flag interface, and asserts if the value
247 /// is an instruction that implements the disjoint flag.
248 void setDisjointFlag(Operation *op, llvm::Value *value);
249
250 /// Converts the type from MLIR LLVM dialect to LLVM.
251 llvm::Type *convertType(Type type);
252
253 /// Returns the MLIR context of the module being translated.
254 MLIRContext &getContext() { return *mlirModule->getContext(); }
255
256 /// Returns the LLVM context in which the IR is being constructed.
257 llvm::LLVMContext &getLLVMContext() const { return llvmModule->getContext(); }
258
259 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
260 /// defining a global value.
261 llvm::GlobalValue *lookupGlobal(Operation *op) {
262 return globalsMapping.lookup(op);
263 }
264
265 /// Finds an LLVM IR global value by the mlir.global symbol name.
266 llvm::GlobalValue *lookupGlobal(StringRef name) const {
267 return globalsByNameMapping.lookup(name);
268 }
269
270 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
271 /// defining a global alias value.
272 llvm::GlobalValue *lookupAlias(Operation *op) {
273 return aliasesMapping.lookup(op);
274 }
275
276 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
277 /// defining an IFunc.
278 llvm::GlobalValue *lookupIFunc(Operation *op) {
279 return ifuncMapping.lookup(op);
280 }
281
282 /// Returns the OpenMP IR builder associated with the LLVM IR module being
283 /// constructed.
284 llvm::OpenMPIRBuilder *getOpenMPBuilder();
285
286 /// Returns the virtual filesystem to use for file operations. Falls back to
287 /// the real filesystem if none was provided.
288 llvm::vfs::FileSystem &getFileSystem();
289
290 /// Returns the LLVM module in which the IR is being constructed.
291 llvm::Module *getLLVMModule() { return llvmModule.get(); }
292
293 /// Translates the given location.
294 llvm::DILocation *translateLoc(Location loc, llvm::DILocalScope *scope);
295
296 /// Translates the given LLVM DWARF expression metadata.
297 llvm::DIExpression *translateExpression(LLVM::DIExpressionAttr attr);
298
299 /// Translates the given LLVM global variable expression metadata.
300 llvm::DIGlobalVariableExpression *
301 translateGlobalVariableExpression(LLVM::DIGlobalVariableExpressionAttr attr);
302
303 /// Translates the given LLVM debug info metadata.
304 llvm::Metadata *translateDebugInfo(LLVM::DINodeAttr attr);
305
306 /// Translates the given LLVM rounding mode metadata.
307 llvm::RoundingMode translateRoundingMode(LLVM::RoundingMode rounding);
308
309 /// Translates the given LLVM FP exception behavior metadata.
310 llvm::fp::ExceptionBehavior
311 translateFPExceptionBehavior(LLVM::FPExceptionBehavior exceptionBehavior);
312
313 /// Translates the contents of the given block to LLVM IR using this
314 /// translator. The LLVM IR basic block corresponding to the given block is
315 /// expected to exist in the mapping of this translator. Uses `builder` to
316 /// translate the IR, leaving it at the end of the block. If `ignoreArguments`
317 /// is set, does not produce PHI nodes for the block arguments. Otherwise, the
318 /// PHI nodes are constructed for block arguments but are _not_ connected to
319 /// the predecessors that may not exist yet.
320 LogicalResult convertBlock(Block &bb, bool ignoreArguments,
321 llvm::IRBuilderBase &builder) {
322 return convertBlockImpl(bb, ignoreArguments, builder,
323 /*recordInsertions=*/false);
324 }
325
326 /// Converts the given MLIR operation into LLVM IR using this translator. It
327 /// is up to the caller to ensure that all operands have been mapped before
328 /// calling this function.
329 LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder) {
330 return convertOperationImpl(op, builder, /*recordInsertions=*/false);
331 }
332
333 /// Converts argument and result attributes from `attrsOp` to LLVM IR
334 /// attributes on the `call` instruction. Returns failure if conversion fails.
335 /// The `immArgPositions` parameter is only relevant for intrinsics. It
336 /// specifies the positions of immediate arguments, which do not have
337 /// associated argument attributes in MLIR and should be skipped during
338 /// attribute mapping.
339 LogicalResult
340 convertArgAndResultAttrs(ArgAndResultAttrsOpInterface attrsOp,
341 llvm::CallBase *call,
342 ArrayRef<unsigned> immArgPositions = {});
343
344 /// Gets the named metadata in the LLVM IR module being constructed, creating
345 /// it if it does not exist.
346 llvm::NamedMDNode *getOrInsertNamedModuleMetadata(StringRef name);
347
348 /// Creates a stack frame of type `T` on ModuleTranslation stack. `T` must
349 /// be derived from `StackFrameBase<T>` and constructible from the provided
350 /// arguments. Doing this before entering the region of the op being
351 /// translated makes the frame available when translating ops within that
352 /// region.
353 template <typename T, typename... Args>
354 void stackPush(Args &&...args) {
355 stack.stackPush<T>(std::forward<Args>(args)...);
356 }
357
358 /// Pops the last element from the ModuleTranslation stack.
359 void stackPop() { stack.stackPop(); }
360
361 /// Calls `callback` for every ModuleTranslation stack frame of type `T`
362 /// starting from the top of the stack.
363 template <typename T>
365 return stack.stackWalk(callback);
366 }
367
368 /// RAII object calling stackPush/stackPop on construction/destruction.
369 template <typename T>
371
372 SymbolTableCollection &symbolTable() { return symbolTableCollection; }
373
374 // A helper callback that takes an attribute, and if it is a StringAttr,
375 // properly converts it to the 'no-builtin-VALUE' form.
376 static std::optional<llvm::Attribute> convertNoBuiltin(llvm::LLVMContext &ctx,
378
379 static std::optional<llvm::Attribute>
380 convertDefaultFuncAttr(llvm::LLVMContext &ctx,
381 mlir::NamedAttribute namedAttr);
382
383 /// A template that takes a collection-like attribute, and converts it via a
384 /// user provided callback, then adds each element as function attributes to
385 /// the provided operation.
386 template <typename AttrsTy, typename Operation, typename Converter>
388 const Converter &conv) {
389 if (!attrs)
390 return;
391 for (auto elt : attrs) {
392 std::optional<llvm::Attribute> result = conv(getLLVMContext(), elt);
393 if (result)
394 op->addFnAttr(*result);
395 }
396 }
397
398 llvm::Attribute convertAllocsizeAttr(DenseI32ArrayAttr allocsizeAttr);
399
400private:
401 ModuleTranslation(Operation *module, std::unique_ptr<llvm::Module> llvmModule,
402 llvm::vfs::FileSystem *fs = nullptr);
404
405 /// Converts individual components.
406 LogicalResult convertOperationImpl(Operation &op,
407 llvm::IRBuilderBase &builder,
408 bool recordInsertions = false);
409 LogicalResult convertFunctionSignatures();
410 LogicalResult convertFunctions();
411 LogicalResult convertIFuncs();
412 LogicalResult convertComdats();
413
414 LogicalResult convertUnresolvedBlockAddress();
415
416 /// Handle conversion for both globals and global aliases.
417 ///
418 /// - Create named global variables that correspond to llvm.mlir.global
419 /// definitions, similarly Convert llvm.global_ctors and global_dtors ops.
420 /// - Create global alias that correspond to llvm.mlir.alias.
421 LogicalResult convertGlobalsAndAliases();
422 LogicalResult convertOneFunction(LLVMFuncOp func);
423 LogicalResult convertBlockImpl(Block &bb, bool ignoreArguments,
424 llvm::IRBuilderBase &builder,
425 bool recordInsertions);
426
427 /// Returns the LLVM metadata corresponding to the given mlir LLVM dialect
428 /// TBAATagAttr.
429 llvm::MDNode *getTBAANode(TBAATagAttr tbaaAttr) const;
430
431 /// Process tbaa LLVM Metadata operations and create LLVM
432 /// metadata nodes for them.
433 LogicalResult createTBAAMetadata();
434
435 /// Process the ident LLVM Metadata, if it exists.
436 LogicalResult createIdentMetadata();
437
438 /// Process the llvm.commandline LLVM Metadata, if it exists.
439 LogicalResult createCommandlineMetadata();
440
441 /// Process the llvm.dependent_libraries LLVM Metadata, if it exists.
442 LogicalResult createDependentLibrariesMetadata();
443
444 /// Translates dialect attributes attached to the given operation.
445 LogicalResult
446 convertDialectAttributes(Operation *op,
447 ArrayRef<llvm::Instruction *> instructions);
448
449 /// Translates parameter attributes of a call and adds them to the returned
450 /// AttrBuilder. Returns failure if any of the translations failed.
451 FailureOr<llvm::AttrBuilder> convertParameterAttrs(mlir::Location loc,
452 DictionaryAttr paramAttrs);
453
454 /// Translates parameter attributes of a function and adds them to the
455 /// returned AttrBuilder. Returns failure if any of the translations failed.
456 FailureOr<llvm::AttrBuilder>
457 convertParameterAttrs(LLVMFuncOp func, int argIdx, DictionaryAttr paramAttrs);
458
459 /// Original and translated module.
460 Operation *mlirModule;
461 std::unique_ptr<llvm::Module> llvmModule;
462 /// A converter for translating debug information.
463 std::unique_ptr<detail::DebugTranslation> debugTranslation;
464
465 /// A converter for translating loop annotations.
466 std::unique_ptr<detail::LoopAnnotationTranslation> loopAnnotationTranslation;
467
468 /// Builder for LLVM IR generation of OpenMP constructs.
469 std::unique_ptr<llvm::OpenMPIRBuilder> ompBuilder;
470
471 /// Optional virtual filesystem for file operations. When null, the real
472 /// filesystem is used (via getFileSystem()). Not owned.
473 llvm::vfs::FileSystem *fileSystem = nullptr;
474
475 /// Mappings between llvm.mlir.global definitions and corresponding globals.
477
478 /// Name-keyed mirror of `globalsMapping`, populated alongside it during
479 /// `convertGlobalsAndAliases`. Lets `getLLVMConstant` resolve
480 /// `FlatSymbolRefAttr` leaves of aggregate constants that name a global
481 /// (mirroring how `functionMapping` resolves function names).
482 llvm::StringMap<llvm::GlobalValue *> globalsByNameMapping;
483
484 /// Mappings between llvm.mlir.alias definitions and corresponding global
485 /// aliases.
487
488 /// Mappings between llvm.mlir.ifunc definitions and corresponding global
489 /// ifuncs.
491
492 /// A stateful object used to translate types.
493 TypeToLLVMIRTranslator typeTranslator;
494
495 /// A dialect interface collection used for dispatching the translation to
496 /// specific dialects.
498
499 /// Mappings between original and translated values, used for lookups.
500 llvm::StringMap<llvm::Function *> functionMapping;
503
504 /// List of not yet consumed MLIR loop handles (represented by an omp.new_cli
505 /// operation which creates a value of type CanonicalLoopInfoType) and their
506 /// LLVM-IR representation as CanonicalLoopInfo which is managed by the
507 /// OpenMPIRBuilder.
509
510 /// A mapping between MLIR LLVM dialect terminators and LLVM IR terminators
511 /// they are converted to. This allows for connecting PHI nodes to the source
512 /// values after all operations are converted.
514
515 /// A mapping between MLIR LLVM dialect call operations and LLVM IR call
516 /// instructions. This allows for adding branch weights after the operations
517 /// have been converted.
519
520 /// Mapping from an alias scope attribute to its LLVM metadata.
521 /// This map is populated lazily.
522 DenseMap<AliasScopeAttr, llvm::MDNode *> aliasScopeMetadataMapping;
523
524 /// Mapping from an alias scope domain attribute to its LLVM metadata.
525 /// This map is populated lazily.
526 DenseMap<AliasScopeDomainAttr, llvm::MDNode *> aliasDomainMetadataMapping;
527
528 /// Mapping from a tbaa attribute to its LLVM metadata.
529 /// This map is populated on module entry.
530 DenseMap<Attribute, llvm::MDNode *> tbaaMetadataMapping;
531
532 /// Mapping from a comdat selector operation to its LLVM comdat struct.
533 /// This map is populated on module entry.
535
536 /// Mapping from llvm.blockaddress operations to their corresponding LLVM
537 /// constant placeholders. After all basic blocks are translated, this
538 /// mapping is used to replace the placeholders with the LLVM block addresses.
539 DenseMap<BlockAddressOp, llvm::Value *> unresolvedBlockAddressMapping;
540
541 /// Mapping from a BlockAddressAttr attribute to it's matching LLVM basic
542 /// block.
543 DenseMap<BlockAddressAttr, llvm::BasicBlock *> blockAddressToLLVMMapping;
544
545 /// Stack of user-specified state elements, useful when translating operations
546 /// with regions.
547 StateStack stack;
548
549 /// A cache for the symbol tables constructed during symbols lookup.
550 SymbolTableCollection symbolTableCollection;
551};
552
553namespace detail {
554/// For all blocks in the region that were converted to LLVM IR using the given
555/// ModuleTranslation, connect the PHI nodes of the corresponding LLVM IR blocks
556/// to the results of preceding blocks.
557void connectPHINodes(Region &region, const ModuleTranslation &state);
558
559/// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
560/// This currently supports integer, floating point, splat and dense element
561/// attributes and combinations thereof. Also, an array attribute with two
562/// elements is supported to represent a complex constant. In case of error,
563/// report it to `loc` and return nullptr.
564llvm::Constant *getLLVMConstant(llvm::Type *llvmType, Attribute attr,
565 Location loc,
566 const ModuleTranslation &moduleTranslation);
567
568/// Creates a call to an LLVM IR intrinsic function with the given arguments.
569llvm::CallInst *createIntrinsicCall(llvm::IRBuilderBase &builder,
570 llvm::Intrinsic::ID intrinsic,
571 ArrayRef<llvm::Value *> args = {},
572 ArrayRef<llvm::Type *> tys = {});
573
574/// Creates a call to an LLVM IR intrinsic function with the given return type
575/// and arguments. If the intrinsic is overloaded, the function signature will
576/// be automatically resolved based on the provided return type and argument
577/// types.
578llvm::CallInst *createIntrinsicCall(llvm::IRBuilderBase &builder,
579 llvm::Intrinsic::ID intrinsic,
580 llvm::Type *retTy,
581 ArrayRef<llvm::Value *> args);
582
583/// Creates a call to a LLVM IR intrinsic defined by LLVM_IntrOpBase. This
584/// resolves the overloads, and maps mixed MLIR value and attribute arguments to
585/// LLVM values.
586llvm::CallInst *createIntrinsicCall(
587 llvm::IRBuilderBase &builder, ModuleTranslation &moduleTranslation,
588 Operation *intrOp, llvm::Intrinsic::ID intrinsic, unsigned numResults,
589 ArrayRef<unsigned> overloadedResults, ArrayRef<unsigned> overloadedOperands,
590 ArrayRef<unsigned> immArgPositions,
591 ArrayRef<StringLiteral> immArgAttrNames);
592
593} // namespace detail
594
595} // namespace LLVM
596} // namespace mlir
597
598#endif // MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
static LogicalResult convertOperationImpl(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:33
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.
Definition LLVMAttrs.h:29
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.
void mapOmpLoop(Value mlir, llvm::CanonicalLoopInfo *llvm)
Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR OpenMPIRBuilder CanonicalLoopInfo...
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.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
void invalidateOmpLoop(omp::NewCliOp mlir)
Mark an OpenMP loop as having been consumed.
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.
void invalidateOmpLoop(Value mlir)
Mark an OpenMP loop as having been consumed.
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::OpenMPIRBuilder * getOpenMPBuilder()
Returns the OpenMP IR builder associated with the LLVM IR module being constructed.
llvm::vfs::FileSystem & getFileSystem()
Returns the virtual filesystem to use for file operations.
void mapOmpLoop(omp::NewCliOp mlir, llvm::CanonicalLoopInfo *llvm)
Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR OpenMPIRBuilder CanonicalLoopInfo...
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.
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.
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)
llvm::CanonicalLoopInfo * lookupOMPLoop(Value mlir) const
Find the LLVM-IR loop that represents an MLIR loop.
void stackPop()
Pops the last element from the ModuleTranslation stack.
void forgetMapping(Region &region)
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::CanonicalLoopInfo * lookupOMPLoop(omp::NewCliOp mlir) const
Find the LLVM-IR loop that represents an MLIR loop.
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.
Definition TypeToLLVM.h:39
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...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:164
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class represents a collection of SymbolTables.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:228
void connectPHINodes(Region &region, 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.
AttrTypeReplacer.
Include the generated interface declarations.
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
Definition LLVM.h:120
RAII object calling stackPush/stackPop on construction/destruction.
Definition StateStack.h:106