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