MLIR 24.0.0git
ModuleImport.h
Go to the documentation of this file.
1//===- ModuleImport.h - LLVM to MLIR 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 import of an LLVM IR module into an LLVM dialect
10// module.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef MLIR_TARGET_LLVMIR_MODULEIMPORT_H
15#define MLIR_TARGET_LLVMIR_MODULEIMPORT_H
16
18#include "mlir/IR/BuiltinOps.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/IR/Module.h"
24
25namespace llvm {
26class BasicBlock;
27class ModuleSlotTracker;
28class CallBase;
29class DbgVariableIntrinsic;
30class Function;
31class Instruction;
32class Value;
33} // namespace llvm
34
35namespace mlir {
36namespace LLVM {
37
38namespace detail {
40class DebugImporter;
42} // namespace detail
43
44/// Module import implementation class that provides methods to import globals
45/// and functions from an LLVM module into an MLIR module. It holds mappings
46/// between the original and translated globals, basic blocks, and values used
47/// during the translation. Additionally, it keeps track of the current constant
48/// insertion point since LLVM immediate values translate to MLIR operations
49/// that are introduced at the beginning of the region.
51public:
52 ModuleImport(ModuleOp mlirModule, std::unique_ptr<llvm::Module> llvmModule,
53 bool emitExpensiveWarnings, bool importEmptyDICompositeTypes,
54 bool preferUnregisteredIntrinsics, bool importStructsAsLiterals);
56
57 /// Calls the LLVMImportInterface initialization that queries the registered
58 /// dialect interfaces for the supported LLVM IR intrinsics and metadata kinds
59 /// and builds the dispatch tables. Returns failure if multiple dialect
60 /// interfaces translate the same LLVM IR intrinsic.
61 LogicalResult initializeImportInterface() {
62 return iface.initializeImport(llvmModule->getContext());
63 }
64
65 /// Converts all functions of the LLVM module to MLIR functions.
66 LogicalResult convertFunctions();
67
68 /// Converts all comdat selectors of the LLVM module to MLIR comdat
69 /// operations.
70 LogicalResult convertComdats();
71
72 /// Converts all global variables of the LLVM module to MLIR global variables.
73 LogicalResult convertGlobals();
74
75 /// Converts all aliases of the LLVM module to MLIR variables.
76 LogicalResult convertAliases();
77
78 /// Converts all ifuncs of the LLVM module to MLIR variables.
79 LogicalResult convertIFuncs();
80
81 /// Converts the data layout of the LLVM module to an MLIR data layout
82 /// specification.
83 LogicalResult convertDataLayout();
84
85 /// Converts target triple of the LLVM module to an MLIR target triple
86 /// specification.
88
89 /// Converts the module level asm of the LLVM module to an MLIR module
90 /// level asm specification.
92
93 /// Stores the mapping between an LLVM value and its MLIR counterpart.
94 void mapValue(llvm::Value *llvm, Value mlir) { mapValue(llvm) = mlir; }
95
96 /// Provides write-once access to store the MLIR value corresponding to the
97 /// given LLVM value.
98 Value &mapValue(llvm::Value *value) {
99 Value &mlir = valueMapping[value];
100 assert(mlir == nullptr &&
101 "attempting to map a value that is already mapped");
102 return mlir;
103 }
104
105 /// Returns the MLIR value mapped to the given LLVM value.
106 Value lookupValue(llvm::Value *value) { return valueMapping.lookup(value); }
107
108 /// Stores a mapping between an LLVM instruction and the imported MLIR
109 /// operation if the operation returns no result. Asserts if the operation
110 /// returns a result and should be added to valueMapping instead.
111 void mapNoResultOp(llvm::Instruction *llvm, Operation *mlir) {
113 }
114
115 /// Provides write-once access to store the MLIR operation corresponding to
116 /// the given LLVM instruction if the operation returns no result. Asserts if
117 /// the operation returns a result and should be added to valueMapping
118 /// instead.
119 Operation *&mapNoResultOp(llvm::Instruction *inst) {
120 Operation *&mlir = noResultOpMapping[inst];
121 assert(inst->getType()->isVoidTy() &&
122 "attempting to map an operation that returns a result");
123 assert(mlir == nullptr &&
124 "attempting to map an operation that is already mapped");
125 return mlir;
126 }
127
128 /// Returns the MLIR operation mapped to the given LLVM instruction. Queries
129 /// valueMapping and noResultOpMapping to support operations with and without
130 /// result.
131 Operation *lookupOperation(llvm::Instruction *inst) {
132 if (Value value = lookupValue(inst))
133 return value.getDefiningOp();
134 return noResultOpMapping.lookup(inst);
135 }
136
137 /// Stores the mapping between an LLVM block and its MLIR counterpart.
138 void mapBlock(llvm::BasicBlock *llvm, Block *mlir) {
139 auto result = blockMapping.try_emplace(llvm, mlir);
140 (void)result;
141 assert(result.second && "attempting to map a block that is already mapped");
142 }
143
144 /// Returns the MLIR block mapped to the given LLVM block.
145 Block *lookupBlock(llvm::BasicBlock *block) const {
146 return blockMapping.lookup(block);
147 }
148
149 /// Converts an LLVM value to an MLIR value, or returns failure if the
150 /// conversion fails. Uses the `convertConstant` method to translate constant
151 /// LLVM values.
152 FailureOr<Value> convertValue(llvm::Value *value);
153
154 /// Converts an LLVM metadata value to an MLIR value, or returns failure if
155 /// the conversion fails. Uses the `convertConstant` method to translate
156 /// constant LLVM values.
157 FailureOr<Value> convertMetadataValue(llvm::Value *value);
158
159 /// Converts a range of LLVM values to a range of MLIR values using the
160 /// `convertValue` method, or returns failure if the conversion fails.
161 FailureOr<SmallVector<Value>> convertValues(ArrayRef<llvm::Value *> values);
162
163 /// Converts `value` to an integer attribute. Asserts if the matching fails.
164 IntegerAttr matchIntegerAttr(llvm::Value *value);
165
166 /// Converts `value` to a float attribute. Asserts if the matching fails.
167 FloatAttr matchFloatAttr(llvm::Value *value);
168
169 /// Converts `valOrVariable` to a local variable attribute. Asserts if the
170 /// matching fails.
171 DILocalVariableAttr matchLocalVariableAttr(
173
174 /// Converts `value` to a label attribute. Asserts if the matching fails.
175 DILabelAttr matchLabelAttr(llvm::Value *value);
176
177 /// Converts `value` to a FP exception behavior attribute. Asserts if the
178 /// matching fails.
179 FPExceptionBehaviorAttr matchFPExceptionBehaviorAttr(llvm::Value *value);
180
181 /// Converts `value` to a rounding mode attribute. Asserts if the matching
182 /// fails.
183 RoundingModeAttr matchRoundingModeAttr(llvm::Value *value);
184
185 /// Converts `value` to an array of alias scopes or returns failure if the
186 /// conversion fails.
187 FailureOr<SmallVector<AliasScopeAttr>>
188 matchAliasScopeAttrs(llvm::Value *value);
189
190 /// Translates the debug location.
191 Location translateLoc(llvm::DILocation *loc);
192
193 /// Converts the type from LLVM to MLIR LLVM dialect.
194 Type convertType(llvm::Type *type) {
195 return typeTranslator.translateType(type);
196 }
197
198 /// Imports `func` into the current module.
199 LogicalResult processFunction(llvm::Function *func);
200
201 /// Converts function attributes of LLVM Function `func` into LLVM dialect
202 /// attributes of LLVMFuncOp `funcOp`.
203 void processFunctionAttributes(llvm::Function *func, LLVMFuncOp funcOp);
204
205 /// Sets the integer overflow flags (nsw/nuw) attribute for the imported
206 /// operation `op` given the original instruction `inst`. Asserts if the
207 /// operation does not implement the integer overflow flag interface.
208 void setIntegerOverflowFlags(llvm::Instruction *inst, Operation *op) const;
209
210 /// Sets the exact flag attribute for the imported operation `op` given
211 /// the original instruction `inst`. Asserts if the operation does not
212 /// implement the exact flag interface.
213 void setExactFlag(llvm::Instruction *inst, Operation *op) const;
214
215 /// Sets the disjoint flag attribute for the imported operation `op`
216 /// given the original instruction `inst`. Asserts if the operation does
217 /// not implement the disjoint flag interface.
218 void setDisjointFlag(llvm::Instruction *inst, Operation *op) const;
219
220 /// Sets the nneg flag attribute for the imported operation `op` given
221 /// the original instruction `inst`. Asserts if the operation does not
222 /// implement the nneg flag interface.
223 void setNonNegFlag(llvm::Instruction *inst, Operation *op) const;
224
225 /// Sets the fastmath flags attribute for the imported operation `op` given
226 /// the original instruction `inst`. Asserts if the operation does not
227 /// implement the fastmath interface.
228 void setFastmathFlagsAttr(llvm::Instruction *inst, Operation *op) const;
229
230 /// Converts !llvm.linker.options metadata to the llvm.linker.options
231 /// LLVM dialect operation.
232 LogicalResult convertLinkerOptionsMetadata();
233
234 /// Converts !llvm.module.flags metadata.
235 LogicalResult convertModuleFlagsMetadata();
236
237 /// Converts !llvm.ident metadata to the llvm.ident LLVM ModuleOp attribute.
238 LogicalResult convertIdentMetadata();
239
240 /// Converts !llvm.commandline metadata to the llvm.commandline LLVM ModuleOp
241 /// attribute.
242 LogicalResult convertCommandlineMetadata();
243
244 /// Converts !llvm.dependent-libraries metadata to llvm.dependent_libraries
245 /// LLVM ModuleOp attribute.
246 LogicalResult convertDependentLibrariesMetadata();
247
248 /// Converts all LLVM metadata nodes that translate to attributes such as
249 /// alias analysis or access group metadata, and builds a map from the
250 /// metadata nodes to the converted attributes.
251 /// Returns success if all conversions succeed and failure otherwise.
252 LogicalResult convertMetadata();
253
254 /// Returns the MLIR attribute mapped to the given LLVM TBAA
255 /// metadata `node`.
256 Attribute lookupTBAAAttr(const llvm::MDNode *node) const {
257 return tbaaMapping.lookup(node);
258 }
259
260 /// Looks up a converted `!tbaa.struct` node. Returns null when the
261 /// node was never converted or could not be modeled.
262 Attribute lookupTBAAStructAttr(const llvm::MDNode *node) const {
263 return tbaaStructMapping.lookup(node);
264 }
265
266 /// Returns the access group attributes that map to the access group nodes
267 /// starting from the access group metadata `node`. Returns failure, if any of
268 /// the attributes cannot be found.
269 FailureOr<SmallVector<AccessGroupAttr>>
270 lookupAccessGroupAttrs(const llvm::MDNode *node) const;
271
272 /// Returns the loop annotation attribute that corresponds to the given LLVM
273 /// loop metadata `node`.
274 LoopAnnotationAttr translateLoopAnnotationAttr(const llvm::MDNode *node,
275 Location loc) const;
276
277 /// Returns the dereferenceable attribute that corresponds to the given LLVM
278 /// dereferenceable or dereferenceable_or_null metadata `node`. `kindID`
279 /// specifies the kind of the metadata node (dereferenceable or
280 /// dereferenceable_or_null).
281 FailureOr<DereferenceableAttr>
282 translateDereferenceableAttr(const llvm::MDNode *node, unsigned kindID);
283
284 /// Returns the alias scope attributes that map to the alias scope nodes
285 /// starting from the metadata `node`. Returns failure, if any of the
286 /// attributes cannot be found.
287 FailureOr<SmallVector<AliasScopeAttr>>
288 lookupAliasScopeAttrs(const llvm::MDNode *node) const;
289
290 /// Adds a debug intrinsics to the list of intrinsics that should be converted
291 /// after the function conversion has finished.
292 void addDebugIntrinsic(llvm::CallInst *intrinsic);
293
294 /// Adds a debug record to the list of debug records that need to be imported
295 /// after the function conversion has finished.
296 void addDebugRecord(llvm::DbgVariableRecord *dbgRecord);
297
298 /// Converts the LLVM values for an intrinsic to mixed MLIR values and
299 /// attributes for LLVM_IntrOpBase. Attributes correspond to LLVM immargs. The
300 /// list `immArgPositions` contains the positions of immargs on the LLVM
301 /// intrinsic, and `immArgAttrNames` list (of the same length) contains the
302 /// corresponding MLIR attribute names.
303 LogicalResult
306 bool requiresOpBundles,
307 ArrayRef<unsigned> immArgPositions,
308 ArrayRef<StringLiteral> immArgAttrNames,
309 SmallVectorImpl<Value> &valuesOut,
311
312 /// Converts the argument and result attributes attached to `call` and adds
313 /// them to `attrsOp`. For intrinsic calls, filters out attributes
314 /// corresponding to immediate arguments specified by `immArgPositions`.
315 void convertArgAndResultAttrs(llvm::CallBase *call,
316 ArgAndResultAttrsOpInterface attrsOp,
317 ArrayRef<unsigned> immArgPositions = {});
318
319 /// Whether the importer should try to convert all intrinsics to
320 /// llvm.call_intrinsic instead of dialect supported operations.
322 return preferUnregisteredIntrinsics;
323 }
324
325private:
326 /// Renders `value` into a bounded string for a diagnostic.
327 std::string renderValue(const llvm::Value &value);
328 /// Renders `node` into a bounded string for a diagnostic.
329 std::string renderMetadata(const llvm::Metadata *node);
330 /// Shared slot tracker for diagnostics, created on first use.
331 llvm::ModuleSlotTracker &getDiagSlotTracker();
332
333 /// Clears the accumulated state before processing a new region.
334 void clearRegionState() {
335 valueMapping.clear();
336 noResultOpMapping.clear();
337 blockMapping.clear();
338 debugIntrinsics.clear();
339 }
340 /// Sets the constant insertion point to the start of the given block.
341 void setConstantInsertionPointToStart(Block *block) {
342 constantInsertionBlock = block;
343 constantInsertionOp = nullptr;
344 }
345
346 /// Converts an LLVM global variable into an MLIR LLVM dialect global
347 /// operation if a conversion exists. Otherwise, returns failure.
348 LogicalResult convertGlobal(llvm::GlobalVariable *globalVar);
349 /// Imports the magic globals "global_ctors" and "global_dtors".
350 LogicalResult convertGlobalCtorsAndDtors(llvm::GlobalVariable *globalVar);
351 /// Converts an LLVM global alias variable into an MLIR LLVM dialect alias
352 /// operation if a conversion exists. Otherwise, returns failure.
353 LogicalResult convertAlias(llvm::GlobalAlias *alias);
354 // Converts an LLVM global ifunc into an MLIR LLVM dialect ifunc operation.
355 LogicalResult convertIFunc(llvm::GlobalIFunc *ifunc);
356 /// Returns personality of `func` as a FlatSymbolRefAttr.
357 FlatSymbolRefAttr getPersonalityAsAttr(llvm::Function *func);
358 /// Imports `bb` into `block`, which must be initially empty.
359 LogicalResult processBasicBlock(llvm::BasicBlock *bb, Block *block);
360 /// Converts all debug intrinsics in `debugIntrinsics`. Assumes that the
361 /// function containing the intrinsics has been fully converted to MLIR.
362 LogicalResult processDebugIntrinsics();
363 /// Converts all debug records in `dbgRecords`. Assumes that the
364 /// function containing the record has been fully converted to MLIR.
365 LogicalResult processDebugRecords();
366 /// Converts a single debug intrinsic.
367 LogicalResult processDebugIntrinsic(llvm::DbgVariableIntrinsic *dbgIntr,
368 DominanceInfo &domInfo);
369 /// Converts a single debug record.
370 LogicalResult processDebugRecord(llvm::DbgVariableRecord &dbgRecord,
371 DominanceInfo &domInfo);
372 /// Process arguments for declare/value operation insertion. `localVarAttr`
373 /// and `localExprAttr` are the attained attributes after importing the debug
374 /// variable and expressions. This also sets the builder insertion point to be
375 /// used by these operations.
376 std::tuple<DILocalVariableAttr, DIExpressionAttr, Value>
377 processDebugOpArgumentsAndInsertionPt(
378 Location loc,
379 llvm::function_ref<FailureOr<Value>()> convertArgOperandToValue,
380 llvm::Value *address,
382 llvm::DIExpression *expression, DominanceInfo &domInfo);
383 /// Converts LLMV IR asm inline call operand's attributes into an array of
384 /// MLIR attributes to be utilized in `llvm.inline_asm`.
385 ArrayAttr convertAsmInlineOperandAttrs(const llvm::CallBase &llvmCall);
386 /// Converts an LLVM intrinsic to an MLIR LLVM dialect operation if an MLIR
387 /// counterpart exists. Otherwise, returns failure.
388 LogicalResult convertIntrinsic(llvm::CallInst *inst);
389 /// Converts an LLVM instruction to an MLIR LLVM dialect operation if an MLIR
390 /// counterpart exists. Otherwise, returns failure.
391 LogicalResult convertInstruction(llvm::Instruction *inst);
392 /// Converts the metadata attached to the original instruction `inst` if
393 /// a dialect interfaces supports the specific kind of metadata and attaches
394 /// the resulting dialect attributes to the converted operation `op`. Emits a
395 /// warning if the conversion of a supported metadata kind fails.
396 void setNonDebugMetadataAttrs(llvm::Instruction *inst, Operation *op);
397 /// Returns the symbol reference for a global value that has a corresponding
398 /// imported MLIR symbol, or a null attribute otherwise.
399 FlatSymbolRefAttr getMetadataGlobalValueSymbolRef(llvm::GlobalValue *global);
400 /// Returns a symbol ref if `md` refers to an imported global value.
401 FlatSymbolRefAttr getMetadataOperandSymbolRef(const llvm::Metadata *md);
402 /// Converts `md` to the matching LLVM dialect metadata attribute, or returns
403 /// a null attribute if the metadata cannot be represented.
404 Attribute convertMetadataToAttr(const llvm::Metadata *md);
405 /// Recursively converts `md` and tracks the current path and previously
406 /// converted nodes to reject cycles and preserve shared subgraphs.
407 Attribute convertMetadataToAttrImpl(
408 const llvm::Metadata *md, SmallPtrSetImpl<const llvm::Metadata *> &path,
410 /// Imports `inst` and populates valueMapping[inst] with the result of the
411 /// imported operation or noResultOpMapping[inst] with the imported operation
412 /// if it has no result.
413 LogicalResult processInstruction(llvm::Instruction *inst);
414 /// Converts the `branch` arguments in the order of the phi's found in
415 /// `target` and appends them to the `blockArguments` to attach to the
416 /// generated branch operation. The `blockArguments` thus have the same order
417 /// as the phi's in `target`.
418 LogicalResult convertBranchArgs(llvm::Instruction *branch,
419 llvm::BasicBlock *target,
420 SmallVectorImpl<Value> &blockArguments);
421 /// Convert `callInst` operands. For indirect calls, the method additionally
422 /// inserts the called function at the beginning of the returned `operands`
423 /// array. If `allowInlineAsm` is set to false (the default), it will return
424 /// failure if the called operand is an inline asm which isn't convertible to
425 /// MLIR as a value.
426 FailureOr<SmallVector<Value>>
427 convertCallOperands(llvm::CallBase *callInst, bool allowInlineAsm = false);
428 /// Converts the callee's function type. For direct calls, it converts the
429 /// actual function type, which may differ from the called operand type in
430 /// variadic functions. For indirect calls, it converts the function type
431 /// associated with the call instruction. When the call and the callee are not
432 /// compatible (or when nested type conversions failed), emit a warning and
433 /// update `isIncompatibleCall` to indicate it.
434 FailureOr<LLVMFunctionType> convertFunctionType(llvm::CallBase *callInst,
435 bool &isIncompatibleCall);
436 /// Returns the callee name, or an empty symbol if the call is not direct.
437 FlatSymbolRefAttr convertCalleeName(llvm::CallBase *callInst);
438 /// Converts the argument and result attributes attached to `func` and adds
439 /// them to the `funcOp`.
440 void convertArgAndResultAttrs(llvm::Function *func, LLVMFuncOp funcOp);
441 /// Converts the argument or result attributes in `llvmAttrSet` to a
442 /// corresponding MLIR LLVM dialect attribute dictionary.
443 DictionaryAttr convertArgOrResultAttrSet(llvm::AttributeSet llvmAttrSet);
444 /// Converts the attributes attached to `inst` and adds them to the `op`.
445 LogicalResult convertCallAttributes(llvm::CallInst *inst, CallOp op);
446 /// Converts the attributes attached to `inst` and adds them to the `op`.
447 LogicalResult convertInvokeAttributes(llvm::InvokeInst *inst, InvokeOp op);
448 /// Returns the builtin type equivalent to the given LLVM dialect type or
449 /// nullptr if there is no equivalent. The returned type can be used to create
450 /// an attribute for a GlobalOp or a ConstantOp.
451 Type getBuiltinTypeForAttr(Type type);
452 /// Returns `constant` as an attribute to attach to a GlobalOp or ConstantOp
453 /// or nullptr if the constant is not convertible. It supports scalar integer
454 /// and float constants as well as shaped types thereof including strings.
455 Attribute getConstantAsAttr(llvm::Constant *constant);
456 /// Returns the topologically sorted set of transitive dependencies needed to
457 /// convert the given constant.
458 SetVector<llvm::Constant *> getConstantsToConvert(llvm::Constant *constant);
459 /// Converts an LLVM constant to an MLIR value, or returns failure if the
460 /// conversion fails. The MLIR value may be produced by a ConstantOp,
461 /// AddressOfOp, NullOp, or a side-effect free operation (for ConstantExprs or
462 /// ConstantGEPs).
463 FailureOr<Value> convertConstant(llvm::Constant *constant);
464 /// Converts an LLVM constant and its transitive constant dependencies to MLIR
465 /// operations by converting them in topological order using the
466 /// `convertConstant` method, or returns failure if the conversion of any of
467 /// them fails. All operations are inserted at the start of the current
468 /// function entry block.
469 FailureOr<Value> convertConstantExpr(llvm::Constant *constant);
470 /// Returns a global comdat operation that serves as a container for LLVM
471 /// comdat selectors. Creates the global comdat operation on the first
472 /// invocation.
473 ComdatOp getGlobalComdatOp();
474 /// Performs conversion of LLVM TBAA metadata starting from
475 /// `node`. On exit from this function all nodes reachable
476 /// from `node` are converted, and tbaaMapping map is updated
477 /// (unless all dependencies have been converted by a previous
478 /// invocation of this function).
479 LogicalResult processTBAAMetadata(const llvm::MDNode *node);
480 /// Converts a `!tbaa.struct` node to the `tbaa_struct` attribute. The
481 /// node's tags must already be converted (see the pre-walk in
482 /// convertMetadata). Returns null for nodes that cannot be modeled;
483 /// callers record the null in tbaaStructMapping so the node is
484 /// declined at attach time.
485 Attribute convertTBAAStructMetadata(const llvm::MDNode *node);
486 /// Converts all LLVM access groups starting from `node` to MLIR access group
487 /// operations and stores a mapping from every nested access group node to the
488 /// translated attribute. Returns success if all conversions succeed and
489 /// failure otherwise.
490 LogicalResult processAccessGroupMetadata(const llvm::MDNode *node);
491 /// Converts all LLVM alias scopes and domains starting from `node` to MLIR
492 /// alias scope and domain attributes and stores a mapping from every nested
493 /// alias scope or alias domain node to the translated attribute. Returns
494 /// success if all conversions succeed and failure otherwise.
495 LogicalResult processAliasScopeMetadata(const llvm::MDNode *node);
496 /// Converts the given LLVM comdat struct to an MLIR comdat selector operation
497 /// and stores a mapping from the struct to the symbol pointing to the
498 /// translated operation.
499 void processComdat(const llvm::Comdat *comdat);
500 /// Returns a symbol name for a nameless global. MLIR, in contrast to LLVM,
501 /// always requires a symbol name.
502 FlatSymbolRefAttr
503 getOrCreateNamelessSymbolName(llvm::GlobalVariable *globalVar);
504 /// Returns the global insertion point for the next global operation. If the
505 /// `globalInsertionOp` is set, the insertion point is placed after the
506 /// specified operation. Otherwise, it defaults to the start of the module.
507 OpBuilder::InsertionGuard setGlobalInsertionPoint();
508
509 /// Builder pointing at where the next instruction should be generated.
510 OpBuilder builder;
511 /// Block to insert the next constant into.
512 Block *constantInsertionBlock = nullptr;
513 /// Operation to insert the next constant after.
514 Operation *constantInsertionOp = nullptr;
515 /// Operation to insert the next global after.
516 Operation *globalInsertionOp = nullptr;
517 /// Operation to insert comdat selector operations into.
518 ComdatOp globalComdatOp = nullptr;
519 /// The current context.
520 MLIRContext *context;
521 /// The MLIR module being created.
522 ModuleOp mlirModule;
523 /// The LLVM module being imported.
524 std::unique_ptr<llvm::Module> llvmModule;
525 /// Nameless globals.
527 /// Counter used to assign a unique ID to each nameless global.
528 unsigned namelessGlobalId = 0;
529
530 /// A dialect interface collection used for dispatching the import to specific
531 /// dialects.
532 LLVMImportInterface iface;
533
534 /// Function-local mapping between original and imported block.
536 /// Function-local mapping between original and imported values.
538 /// Function-local mapping between original instructions and imported
539 /// operations for all operations that return no result. All operations that
540 /// return a result have a valueMapping entry instead.
542 /// Function-local list of debug intrinsics that need to be imported after the
543 /// function conversion has finished.
544 SetVector<llvm::Instruction *> debugIntrinsics;
545 /// Function-local list of debug records that need to be imported after the
546 /// function conversion has finished.
547 SetVector<llvm::DbgVariableRecord *> dbgRecords;
548 /// Mapping between LLVM alias scope and domain metadata nodes and
549 /// attributes in the LLVM dialect corresponding to these nodes.
551 /// Mapping between LLVM TBAA metadata nodes and LLVM dialect TBAA attributes
552 /// corresponding to these nodes.
554 /// Mapping between LLVM `!tbaa.struct` nodes and the converted
555 /// `tbaa_struct` attributes. Kept separate from tbaaMapping so a struct
556 /// node can never be mistaken for a TBAA tag or type descriptor node,
557 /// which processTBAAMetadata casts to those attribute kinds. A null
558 /// value records that the node was converted and could not be modeled.
560 /// Mapping between LLVM comdat structs and symbol references to LLVM dialect
561 /// comdat selector operations corresponding to these structs.
562 DenseMap<const llvm::Comdat *, SymbolRefAttr> comdatMapping;
563 /// The stateful type translator (contains named structs).
564 LLVM::TypeFromLLVMIRTranslator typeTranslator;
565 /// Stateful debug information importer.
566 std::unique_ptr<detail::DebugImporter> debugImporter;
567 /// Loop annotation importer.
568 std::unique_ptr<detail::LoopAnnotationImporter> loopAnnotationImporter;
569 /// Slot tracker shared by every diagnostic that renders an LLVM entity.
570 /// Metadata::print and Value::print each construct their own tracker when
571 /// not given one, and building one walks the module, so a per-call tracker
572 /// makes a per-instruction diagnostic quadratic in module size. Sharing one
573 /// makes that walk a per-import cost instead. Created lazily, so an import
574 /// that renders nothing never pays for it at all.
575 std::unique_ptr<llvm::ModuleSlotTracker> diagSlotTracker;
576
577 /// An option to control if expensive but uncritical diagnostics should be
578 /// emitted. Avoids generating warnings for unhandled debug intrinsics and
579 /// metadata that otherwise dominate the translation time for large inputs.
580 bool emitExpensiveWarnings;
581
582 /// An option to control whether the importer should try to convert all
583 /// intrinsics to llvm.call_intrinsic instead of dialect supported operations.
584 bool preferUnregisteredIntrinsics;
585};
586
587} // namespace LLVM
588} // namespace mlir
589
590#endif // MLIR_TARGET_LLVMIR_MODULEIMPORT_H
ArrayAttr()
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
LogicalResult convertIFuncs()
Converts all ifuncs of the LLVM module to MLIR variables.
LogicalResult convertIntrinsicArguments(ArrayRef< llvm::Value * > values, ArrayRef< llvm::OperandBundleUse > opBundles, bool requiresOpBundles, ArrayRef< unsigned > immArgPositions, ArrayRef< StringLiteral > immArgAttrNames, SmallVectorImpl< Value > &valuesOut, SmallVectorImpl< NamedAttribute > &attrsOut)
Converts the LLVM values for an intrinsic to mixed MLIR values and attributes for LLVM_IntrOpBase.
Location translateLoc(llvm::DILocation *loc)
Translates the debug location.
LogicalResult convertComdats()
Converts all comdat selectors of the LLVM module to MLIR comdat operations.
LogicalResult convertAliases()
Converts all aliases of the LLVM module to MLIR variables.
LogicalResult convertFunctions()
Converts all functions of the LLVM module to MLIR functions.
FailureOr< SmallVector< Value > > convertValues(ArrayRef< llvm::Value * > values)
Converts a range of LLVM values to a range of MLIR values using the convertValue method,...
Attribute lookupTBAAAttr(const llvm::MDNode *node) const
Returns the MLIR attribute mapped to the given LLVM TBAA metadata node.
bool useUnregisteredIntrinsicsOnly() const
Whether the importer should try to convert all intrinsics to llvm.call_intrinsic instead of dialect s...
LogicalResult convertLinkerOptionsMetadata()
Converts !llvm.linker.options metadata to the llvm.linker.options LLVM dialect operation.
Block * lookupBlock(llvm::BasicBlock *block) const
Returns the MLIR block mapped to the given LLVM block.
void mapBlock(llvm::BasicBlock *llvm, Block *mlir)
Stores the mapping between an LLVM block and its MLIR counterpart.
DILocalVariableAttr matchLocalVariableAttr(llvm::PointerUnion< llvm::Value *, llvm::DILocalVariable * > valOrVariable)
Converts valOrVariable to a local variable attribute.
void processFunctionAttributes(llvm::Function *func, LLVMFuncOp funcOp)
Converts function attributes of LLVM Function func into LLVM dialect attributes of LLVMFuncOp funcOp.
Attribute lookupTBAAStructAttr(const llvm::MDNode *node) const
Looks up a converted !tbaa.struct node.
LogicalResult convertMetadata()
Converts all LLVM metadata nodes that translate to attributes such as alias analysis or access group ...
FailureOr< Value > convertValue(llvm::Value *value)
Converts an LLVM value to an MLIR value, or returns failure if the conversion fails.
LogicalResult initializeImportInterface()
Calls the LLVMImportInterface initialization that queries the registered dialect interfaces for the s...
void addDebugIntrinsic(llvm::CallInst *intrinsic)
Adds a debug intrinsics to the list of intrinsics that should be converted after the function convers...
LogicalResult convertIdentMetadata()
Converts !llvm.ident metadata to the llvm.ident LLVM ModuleOp attribute.
FailureOr< Value > convertMetadataValue(llvm::Value *value)
Converts an LLVM metadata value to an MLIR value, or returns failure if the conversion fails.
FailureOr< SmallVector< AliasScopeAttr > > lookupAliasScopeAttrs(const llvm::MDNode *node) const
Returns the alias scope attributes that map to the alias scope nodes starting from the metadata node.
void setDisjointFlag(llvm::Instruction *inst, Operation *op) const
Sets the disjoint flag attribute for the imported operation op given the original instruction inst.
void mapNoResultOp(llvm::Instruction *llvm, Operation *mlir)
Stores a mapping between an LLVM instruction and the imported MLIR operation if the operation returns...
void convertModuleLevelAsm()
Converts the module level asm of the LLVM module to an MLIR module level asm specification.
Value & mapValue(llvm::Value *value)
Provides write-once access to store the MLIR value corresponding to the given LLVM value.
void setExactFlag(llvm::Instruction *inst, Operation *op) const
Sets the exact flag attribute for the imported operation op given the original instruction inst.
Type convertType(llvm::Type *type)
Converts the type from LLVM to MLIR LLVM dialect.
ModuleImport(ModuleOp mlirModule, std::unique_ptr< llvm::Module > llvmModule, bool emitExpensiveWarnings, bool importEmptyDICompositeTypes, bool preferUnregisteredIntrinsics, bool importStructsAsLiterals)
DILabelAttr matchLabelAttr(llvm::Value *value)
Converts value to a label attribute. Asserts if the matching fails.
FloatAttr matchFloatAttr(llvm::Value *value)
Converts value to a float attribute. Asserts if the matching fails.
LoopAnnotationAttr translateLoopAnnotationAttr(const llvm::MDNode *node, Location loc) const
Returns the loop annotation attribute that corresponds to the given LLVM loop metadata node.
void setFastmathFlagsAttr(llvm::Instruction *inst, Operation *op) const
Sets the fastmath flags attribute for the imported operation op given the original instruction inst.
FailureOr< SmallVector< AliasScopeAttr > > matchAliasScopeAttrs(llvm::Value *value)
Converts value to an array of alias scopes or returns failure if the conversion fails.
Value lookupValue(llvm::Value *value)
Returns the MLIR value mapped to the given LLVM value.
Operation * lookupOperation(llvm::Instruction *inst)
Returns the MLIR operation mapped to the given LLVM instruction.
LogicalResult processFunction(llvm::Function *func)
Imports func into the current module.
LogicalResult convertDependentLibrariesMetadata()
Converts !llvm.dependent-libraries metadata to llvm.dependent_libraries LLVM ModuleOp attribute.
Operation *& mapNoResultOp(llvm::Instruction *inst)
Provides write-once access to store the MLIR operation corresponding to the given LLVM instruction if...
RoundingModeAttr matchRoundingModeAttr(llvm::Value *value)
Converts value to a rounding mode attribute.
void convertTargetTriple()
Converts target triple of the LLVM module to an MLIR target triple specification.
void addDebugRecord(llvm::DbgVariableRecord *dbgRecord)
Adds a debug record to the list of debug records that need to be imported after the function conversi...
void convertArgAndResultAttrs(llvm::CallBase *call, ArgAndResultAttrsOpInterface attrsOp, ArrayRef< unsigned > immArgPositions={})
Converts the argument and result attributes attached to call and adds them to attrsOp.
LogicalResult convertModuleFlagsMetadata()
Converts !llvm.module.flags metadata.
void mapValue(llvm::Value *llvm, Value mlir)
Stores the mapping between an LLVM value and its MLIR counterpart.
FailureOr< SmallVector< AccessGroupAttr > > lookupAccessGroupAttrs(const llvm::MDNode *node) const
Returns the access group attributes that map to the access group nodes starting from the access group...
LogicalResult convertGlobals()
Converts all global variables of the LLVM module to MLIR global variables.
void setIntegerOverflowFlags(llvm::Instruction *inst, Operation *op) const
Sets the integer overflow flags (nsw/nuw) attribute for the imported operation op given the original ...
LogicalResult convertCommandlineMetadata()
Converts !llvm.commandline metadata to the llvm.commandline LLVM ModuleOp attribute.
FPExceptionBehaviorAttr matchFPExceptionBehaviorAttr(llvm::Value *value)
Converts value to a FP exception behavior attribute.
void setNonNegFlag(llvm::Instruction *inst, Operation *op) const
Sets the nneg flag attribute for the imported operation op given the original instruction inst.
FailureOr< DereferenceableAttr > translateDereferenceableAttr(const llvm::MDNode *node, unsigned kindID)
Returns the dereferenceable attribute that corresponds to the given LLVM dereferenceable or dereferen...
LogicalResult convertDataLayout()
Converts the data layout of the LLVM module to an MLIR data layout specification.
IntegerAttr matchIntegerAttr(llvm::Value *value)
Converts value to an integer attribute. Asserts if the matching fails.
Helper class that translates an LLVM data layout string to an MLIR data layout specification.
A helper class that converts llvm.loop metadata nodes into corresponding LoopAnnotationAttrs and llvm...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
Include the generated interface declarations.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123