MLIR  20.0.0git
LLVMIRToLLVMTranslation.cpp
Go to the documentation of this file.
1 //===- LLVMIRToLLVMTranslation.cpp - Translate LLVM IR to LLVM dialect ----===//
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 a translation between LLVM IR and the MLIR LLVM dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
16 #include "mlir/Support/LLVM.h"
18 
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/ScopeExit.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/TypeSwitch.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/Support/ModRef.h"
28 
29 using namespace mlir;
30 using namespace mlir::LLVM;
31 using namespace mlir::LLVM::detail;
32 
33 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsFromLLVM.inc"
34 
35 static constexpr StringLiteral vecTypeHintMDName = "vec_type_hint";
36 static constexpr StringLiteral workGroupSizeHintMDName = "work_group_size_hint";
37 static constexpr StringLiteral reqdWorkGroupSizeMDName = "reqd_work_group_size";
38 static constexpr StringLiteral intelReqdSubGroupSizeMDName =
39  "intel_reqd_sub_group_size";
40 
41 /// Returns true if the LLVM IR intrinsic is convertible to an MLIR LLVM dialect
42 /// intrinsic. Returns false otherwise.
44  static const DenseSet<unsigned> convertibleIntrinsics = {
45 #include "mlir/Dialect/LLVMIR/LLVMConvertibleLLVMIRIntrinsics.inc"
46  };
47  return convertibleIntrinsics.contains(id);
48 }
49 
50 /// Returns the list of LLVM IR intrinsic identifiers that are convertible to
51 /// MLIR LLVM dialect intrinsics.
53  static const SmallVector<unsigned> convertibleIntrinsics = {
54 #include "mlir/Dialect/LLVMIR/LLVMConvertibleLLVMIRIntrinsics.inc"
55  };
56  return convertibleIntrinsics;
57 }
58 
59 /// Converts the LLVM intrinsic to an MLIR LLVM dialect operation if a
60 /// conversion exits. Returns failure otherwise.
61 static LogicalResult convertIntrinsicImpl(OpBuilder &odsBuilder,
62  llvm::CallInst *inst,
63  LLVM::ModuleImport &moduleImport) {
64  llvm::Intrinsic::ID intrinsicID = inst->getIntrinsicID();
65 
66  // Check if the intrinsic is convertible to an MLIR dialect counterpart and
67  // copy the arguments to an an LLVM operands array reference for conversion.
68  if (isConvertibleIntrinsic(intrinsicID)) {
69  SmallVector<llvm::Value *> args(inst->args());
70  ArrayRef<llvm::Value *> llvmOperands(args);
71 #include "mlir/Dialect/LLVMIR/LLVMIntrinsicFromLLVMIRConversions.inc"
72  }
73 
74  return failure();
75 }
76 
77 /// Returns the list of LLVM IR metadata kinds that are convertible to MLIR LLVM
78 /// dialect attributes.
79 static ArrayRef<unsigned> getSupportedMetadataImpl(llvm::LLVMContext &context) {
80  static const SmallVector<unsigned> convertibleMetadata = {
81  llvm::LLVMContext::MD_prof,
82  llvm::LLVMContext::MD_tbaa,
83  llvm::LLVMContext::MD_access_group,
84  llvm::LLVMContext::MD_loop,
85  llvm::LLVMContext::MD_noalias,
86  llvm::LLVMContext::MD_alias_scope,
87  context.getMDKindID(vecTypeHintMDName),
88  context.getMDKindID(workGroupSizeHintMDName),
89  context.getMDKindID(reqdWorkGroupSizeMDName),
90  context.getMDKindID(intelReqdSubGroupSizeMDName)};
91  return convertibleMetadata;
92 }
93 
94 /// Converts the given profiling metadata `node` to an MLIR profiling attribute
95 /// and attaches it to the imported operation if the translation succeeds.
96 /// Returns failure otherwise.
97 static LogicalResult setProfilingAttr(OpBuilder &builder, llvm::MDNode *node,
98  Operation *op,
99  LLVM::ModuleImport &moduleImport) {
100  // Return failure for empty metadata nodes since there is nothing to import.
101  if (!node->getNumOperands())
102  return failure();
103 
104  auto *name = dyn_cast<llvm::MDString>(node->getOperand(0));
105  if (!name)
106  return failure();
107 
108  // Handle function entry count metadata.
109  if (name->getString() == "function_entry_count") {
110 
111  // TODO support function entry count metadata with GUID fields.
112  if (node->getNumOperands() != 2)
113  return failure();
114 
115  llvm::ConstantInt *entryCount =
116  llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(1));
117  if (!entryCount)
118  return failure();
119  if (auto funcOp = dyn_cast<LLVMFuncOp>(op)) {
120  funcOp.setFunctionEntryCount(entryCount->getZExtValue());
121  return success();
122  }
123  return op->emitWarning()
124  << "expected function_entry_count to be attached to a function";
125  }
126 
127  if (name->getString() != "branch_weights")
128  return failure();
129 
130  // Handle branch weights metadata.
131  SmallVector<int32_t> branchWeights;
132  branchWeights.reserve(node->getNumOperands() - 1);
133  for (unsigned i = 1, e = node->getNumOperands(); i != e; ++i) {
134  llvm::ConstantInt *branchWeight =
135  llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(i));
136  if (!branchWeight)
137  return failure();
138  branchWeights.push_back(branchWeight->getZExtValue());
139  }
140 
141  if (auto iface = dyn_cast<BranchWeightOpInterface>(op)) {
142  iface.setBranchWeights(builder.getDenseI32ArrayAttr(branchWeights));
143  return success();
144  }
145  return failure();
146 }
147 
148 /// Searches for the attribute that maps to the given TBAA metadata `node` and
149 /// attaches it to the imported operation if the lookup succeeds. Returns
150 /// failure otherwise.
151 static LogicalResult setTBAAAttr(const llvm::MDNode *node, Operation *op,
152  LLVM::ModuleImport &moduleImport) {
153  Attribute tbaaTagSym = moduleImport.lookupTBAAAttr(node);
154  if (!tbaaTagSym)
155  return failure();
156 
157  auto iface = dyn_cast<AliasAnalysisOpInterface>(op);
158  if (!iface)
159  return failure();
160 
161  iface.setTBAATags(ArrayAttr::get(iface.getContext(), tbaaTagSym));
162  return success();
163 }
164 
165 /// Looks up all the access group attributes that map to the access group nodes
166 /// starting from the access group metadata `node`, and attaches all of them to
167 /// the imported operation if the lookups succeed. Returns failure otherwise.
168 static LogicalResult setAccessGroupsAttr(const llvm::MDNode *node,
169  Operation *op,
170  LLVM::ModuleImport &moduleImport) {
171  FailureOr<SmallVector<AccessGroupAttr>> accessGroups =
172  moduleImport.lookupAccessGroupAttrs(node);
173  if (failed(accessGroups))
174  return failure();
175 
176  auto iface = dyn_cast<AccessGroupOpInterface>(op);
177  if (!iface)
178  return failure();
179 
180  iface.setAccessGroups(ArrayAttr::get(
181  iface.getContext(), llvm::to_vector_of<Attribute>(*accessGroups)));
182  return success();
183 }
184 
185 /// Converts the given loop metadata node to an MLIR loop annotation attribute
186 /// and attaches it to the imported operation if the translation succeeds.
187 /// Returns failure otherwise.
188 static LogicalResult setLoopAttr(const llvm::MDNode *node, Operation *op,
189  LLVM::ModuleImport &moduleImport) {
190  LoopAnnotationAttr attr =
191  moduleImport.translateLoopAnnotationAttr(node, op->getLoc());
192  if (!attr)
193  return failure();
194 
196  .Case<LLVM::BrOp, LLVM::CondBrOp>([&](auto branchOp) {
197  branchOp.setLoopAnnotationAttr(attr);
198  return success();
199  })
200  .Default([](auto) { return failure(); });
201 }
202 
203 /// Looks up all the alias scope attributes that map to the alias scope nodes
204 /// starting from the alias scope metadata `node`, and attaches all of them to
205 /// the imported operation if the lookups succeed. Returns failure otherwise.
206 static LogicalResult setAliasScopesAttr(const llvm::MDNode *node, Operation *op,
207  LLVM::ModuleImport &moduleImport) {
208  FailureOr<SmallVector<AliasScopeAttr>> aliasScopes =
209  moduleImport.lookupAliasScopeAttrs(node);
210  if (failed(aliasScopes))
211  return failure();
212 
213  auto iface = dyn_cast<AliasAnalysisOpInterface>(op);
214  if (!iface)
215  return failure();
216 
217  iface.setAliasScopes(ArrayAttr::get(
218  iface.getContext(), llvm::to_vector_of<Attribute>(*aliasScopes)));
219  return success();
220 }
221 
222 /// Looks up all the alias scope attributes that map to the alias scope nodes
223 /// starting from the noalias metadata `node`, and attaches all of them to the
224 /// imported operation if the lookups succeed. Returns failure otherwise.
225 static LogicalResult setNoaliasScopesAttr(const llvm::MDNode *node,
226  Operation *op,
227  LLVM::ModuleImport &moduleImport) {
228  FailureOr<SmallVector<AliasScopeAttr>> noAliasScopes =
229  moduleImport.lookupAliasScopeAttrs(node);
230  if (failed(noAliasScopes))
231  return failure();
232 
233  auto iface = dyn_cast<AliasAnalysisOpInterface>(op);
234  if (!iface)
235  return failure();
236 
237  iface.setNoAliasScopes(ArrayAttr::get(
238  iface.getContext(), llvm::to_vector_of<Attribute>(*noAliasScopes)));
239  return success();
240 }
241 
242 /// Extracts an integer from the provided metadata `md` if possible. Returns
243 /// nullopt otherwise.
244 static std::optional<int32_t> parseIntegerMD(llvm::Metadata *md) {
245  auto *constant = dyn_cast_if_present<llvm::ConstantAsMetadata>(md);
246  if (!constant)
247  return {};
248 
249  auto *intConstant = dyn_cast<llvm::ConstantInt>(constant->getValue());
250  if (!intConstant)
251  return {};
252 
253  return intConstant->getValue().getSExtValue();
254 }
255 
256 /// Converts the provided metadata node `node` to an LLVM dialect
257 /// VecTypeHintAttr if possible.
258 static VecTypeHintAttr convertVecTypeHint(Builder builder, llvm::MDNode *node,
259  ModuleImport &moduleImport) {
260  if (!node || node->getNumOperands() != 2)
261  return {};
262 
263  auto *hintMD = dyn_cast<llvm::ValueAsMetadata>(node->getOperand(0).get());
264  if (!hintMD)
265  return {};
266  TypeAttr hint = TypeAttr::get(moduleImport.convertType(hintMD->getType()));
267 
268  std::optional<int32_t> optIsSigned =
269  parseIntegerMD(node->getOperand(1).get());
270  if (!optIsSigned)
271  return {};
272  bool isSigned = *optIsSigned != 0;
273 
274  return builder.getAttr<VecTypeHintAttr>(hint, isSigned);
275 }
276 
277 /// Converts the provided metadata node `node` to an MLIR DenseI32ArrayAttr if
278 /// possible.
280  llvm::MDNode *node) {
281  if (!node)
282  return {};
284  for (const llvm::MDOperand &op : node->operands()) {
285  std::optional<int32_t> mdValue = parseIntegerMD(op.get());
286  if (!mdValue)
287  return {};
288  vals.push_back(*mdValue);
289  }
290  return builder.getDenseI32ArrayAttr(vals);
291 }
292 
293 /// Convert an `MDNode` to an MLIR `IntegerAttr` if possible.
294 static IntegerAttr convertIntegerMD(Builder builder, llvm::MDNode *node) {
295  if (!node || node->getNumOperands() != 1)
296  return {};
297  std::optional<int32_t> val = parseIntegerMD(node->getOperand(0));
298  if (!val)
299  return {};
300  return builder.getI32IntegerAttr(*val);
301 }
302 
303 static LogicalResult setVecTypeHintAttr(Builder &builder, llvm::MDNode *node,
304  Operation *op,
305  LLVM::ModuleImport &moduleImport) {
306  auto funcOp = dyn_cast<LLVM::LLVMFuncOp>(op);
307  if (!funcOp)
308  return failure();
309 
310  VecTypeHintAttr attr = convertVecTypeHint(builder, node, moduleImport);
311  if (!attr)
312  return failure();
313 
314  funcOp.setVecTypeHintAttr(attr);
315  return success();
316 }
317 
318 static LogicalResult
319 setWorkGroupSizeHintAttr(Builder &builder, llvm::MDNode *node, Operation *op) {
320  auto funcOp = dyn_cast<LLVM::LLVMFuncOp>(op);
321  if (!funcOp)
322  return failure();
323 
324  DenseI32ArrayAttr attr = convertDenseI32Array(builder, node);
325  if (!attr)
326  return failure();
327 
328  funcOp.setWorkGroupSizeHintAttr(attr);
329  return success();
330 }
331 
332 static LogicalResult
333 setReqdWorkGroupSizeAttr(Builder &builder, llvm::MDNode *node, Operation *op) {
334  auto funcOp = dyn_cast<LLVM::LLVMFuncOp>(op);
335  if (!funcOp)
336  return failure();
337 
338  DenseI32ArrayAttr attr = convertDenseI32Array(builder, node);
339  if (!attr)
340  return failure();
341 
342  funcOp.setReqdWorkGroupSizeAttr(attr);
343  return success();
344 }
345 
346 /// Converts the given intel required subgroup size metadata node to an MLIR
347 /// attribute and attaches it to the imported operation if the translation
348 /// succeeds. Returns failure otherwise.
349 static LogicalResult setIntelReqdSubGroupSizeAttr(Builder &builder,
350  llvm::MDNode *node,
351  Operation *op) {
352  auto funcOp = dyn_cast<LLVM::LLVMFuncOp>(op);
353  if (!funcOp)
354  return failure();
355 
356  IntegerAttr attr = convertIntegerMD(builder, node);
357  if (!attr)
358  return failure();
359 
360  funcOp.setIntelReqdSubGroupSizeAttr(attr);
361  return success();
362 }
363 
364 namespace {
365 
366 /// Implementation of the dialect interface that converts operations belonging
367 /// to the LLVM dialect to LLVM IR.
368 class LLVMDialectLLVMIRImportInterface : public LLVMImportDialectInterface {
369 public:
371 
372  /// Converts the LLVM intrinsic to an MLIR LLVM dialect operation if a
373  /// conversion exits. Returns failure otherwise.
374  LogicalResult convertIntrinsic(OpBuilder &builder, llvm::CallInst *inst,
375  LLVM::ModuleImport &moduleImport) const final {
376  return convertIntrinsicImpl(builder, inst, moduleImport);
377  }
378 
379  /// Attaches the given LLVM metadata to the imported operation if a conversion
380  /// to an LLVM dialect attribute exists and succeeds. Returns failure
381  /// otherwise.
382  LogicalResult setMetadataAttrs(OpBuilder &builder, unsigned kind,
383  llvm::MDNode *node, Operation *op,
384  LLVM::ModuleImport &moduleImport) const final {
385  // Call metadata specific handlers.
386  if (kind == llvm::LLVMContext::MD_prof)
387  return setProfilingAttr(builder, node, op, moduleImport);
388  if (kind == llvm::LLVMContext::MD_tbaa)
389  return setTBAAAttr(node, op, moduleImport);
390  if (kind == llvm::LLVMContext::MD_access_group)
391  return setAccessGroupsAttr(node, op, moduleImport);
392  if (kind == llvm::LLVMContext::MD_loop)
393  return setLoopAttr(node, op, moduleImport);
394  if (kind == llvm::LLVMContext::MD_alias_scope)
395  return setAliasScopesAttr(node, op, moduleImport);
396  if (kind == llvm::LLVMContext::MD_noalias)
397  return setNoaliasScopesAttr(node, op, moduleImport);
398 
399  llvm::LLVMContext &context = node->getContext();
400  if (kind == context.getMDKindID(vecTypeHintMDName))
401  return setVecTypeHintAttr(builder, node, op, moduleImport);
402  if (kind == context.getMDKindID(workGroupSizeHintMDName))
403  return setWorkGroupSizeHintAttr(builder, node, op);
404  if (kind == context.getMDKindID(reqdWorkGroupSizeMDName))
405  return setReqdWorkGroupSizeAttr(builder, node, op);
406  if (kind == context.getMDKindID(intelReqdSubGroupSizeMDName))
407  return setIntelReqdSubGroupSizeAttr(builder, node, op);
408 
409  // A handler for a supported metadata kind is missing.
410  llvm_unreachable("unknown metadata type");
411  }
412 
413  /// Returns the list of LLVM IR intrinsic identifiers that are convertible to
414  /// MLIR LLVM dialect intrinsics.
415  ArrayRef<unsigned> getSupportedIntrinsics() const final {
417  }
418 
419  /// Returns the list of LLVM IR metadata kinds that are convertible to MLIR
420  /// LLVM dialect attributes.
422  getSupportedMetadata(llvm::LLVMContext &context) const final {
423  return getSupportedMetadataImpl(context);
424  }
425 };
426 } // namespace
427 
429  registry.insert<LLVM::LLVMDialect>();
430  registry.addExtension(+[](MLIRContext *ctx, LLVM::LLVMDialect *dialect) {
431  dialect->addInterfaces<LLVMDialectLLVMIRImportInterface>();
432  });
433 }
434 
436  DialectRegistry registry;
437  registerLLVMDialectImport(registry);
438  context.appendDialectRegistry(registry);
439 }
static VecTypeHintAttr convertVecTypeHint(Builder builder, llvm::MDNode *node, ModuleImport &moduleImport)
Converts the provided metadata node node to an LLVM dialect VecTypeHintAttr if possible.
static constexpr StringLiteral workGroupSizeHintMDName
static LogicalResult setReqdWorkGroupSizeAttr(Builder &builder, llvm::MDNode *node, Operation *op)
static DenseI32ArrayAttr convertDenseI32Array(Builder builder, llvm::MDNode *node)
Converts the provided metadata node node to an MLIR DenseI32ArrayAttr if possible.
static LogicalResult setWorkGroupSizeHintAttr(Builder &builder, llvm::MDNode *node, Operation *op)
static LogicalResult setVecTypeHintAttr(Builder &builder, llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport)
static LogicalResult setLoopAttr(const llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport)
Converts the given loop metadata node to an MLIR loop annotation attribute and attaches it to the imp...
static ArrayRef< unsigned > getSupportedIntrinsicsImpl()
Returns the list of LLVM IR intrinsic identifiers that are convertible to MLIR LLVM dialect intrinsic...
static LogicalResult setTBAAAttr(const llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport)
Searches for the attribute that maps to the given TBAA metadata node and attaches it to the imported ...
static constexpr StringLiteral intelReqdSubGroupSizeMDName
static ArrayRef< unsigned > getSupportedMetadataImpl(llvm::LLVMContext &context)
Returns the list of LLVM IR metadata kinds that are convertible to MLIR LLVM dialect attributes.
static LogicalResult setProfilingAttr(OpBuilder &builder, llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport)
Converts the given profiling metadata node to an MLIR profiling attribute and attaches it to the impo...
static LogicalResult setIntelReqdSubGroupSizeAttr(Builder &builder, llvm::MDNode *node, Operation *op)
Converts the given intel required subgroup size metadata node to an MLIR attribute and attaches it to...
static LogicalResult setAliasScopesAttr(const llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport)
Looks up all the alias scope attributes that map to the alias scope nodes starting from the alias sco...
static LogicalResult setNoaliasScopesAttr(const llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport)
Looks up all the alias scope attributes that map to the alias scope nodes starting from the noalias m...
static bool isConvertibleIntrinsic(llvm::Intrinsic::ID id)
Returns true if the LLVM IR intrinsic is convertible to an MLIR LLVM dialect intrinsic.
static constexpr StringLiteral reqdWorkGroupSizeMDName
static LogicalResult convertIntrinsicImpl(OpBuilder &odsBuilder, llvm::CallInst *inst, LLVM::ModuleImport &moduleImport)
Converts the LLVM intrinsic to an MLIR LLVM dialect operation if a conversion exits.
static constexpr StringLiteral vecTypeHintMDName
static LogicalResult setAccessGroupsAttr(const llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport)
Looks up all the access group attributes that map to the access group nodes starting from the access ...
static IntegerAttr convertIntegerMD(Builder builder, llvm::MDNode *node)
Convert an MDNode to an MLIR IntegerAttr if possible.
static std::optional< int32_t > parseIntegerMD(llvm::Metadata *md)
Extracts an integer from the provided metadata md if possible.
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class is a general helper class for creating context-global objects like types,...
Definition: Builders.h:50
IntegerAttr getI32IntegerAttr(int32_t value)
Definition: Builders.cpp:228
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:191
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition: Builders.h:103
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
Base class for dialect interfaces used to import LLVM IR.
LLVMImportDialectInterface(Dialect *dialect)
Module import implementation class that provides methods to import globals and functions from an LLVM...
Definition: ModuleImport.h:47
Attribute lookupTBAAAttr(const llvm::MDNode *node) const
Returns the MLIR attribute mapped to the given LLVM TBAA metadata node.
Definition: ModuleImport.h:210
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.
Type convertType(llvm::Type *type)
Converts the type from LLVM to MLIR LLVM dialect.
Definition: ModuleImport.h:174
LoopAnnotationAttr translateLoopAnnotationAttr(const llvm::MDNode *node, Location loc) const
Returns the loop annotation attribute that corresponds to the given LLVM loop metadata node.
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...
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
void appendDialectRegistry(const DialectRegistry &registry)
Append the contents of the given dialect registry to the registry associated with this context.
This class helps build Operations.
Definition: Builders.h:212
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
InFlightDiagnostic emitWarning(const Twine &message={})
Emit a warning about this operation, reporting up to any diagnostic handlers that may be listening.
Definition: Operation.cpp:280
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
Include the generated interface declarations.
void registerLLVMDialectImport(DialectRegistry &registry)
Registers the LLVM dialect and its import from LLVM IR in the given registry.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...