MLIR 24.0.0git
LLVMToLLVMIRTranslation.cpp
Go to the documentation of this file.
1//===- LLVMToLLVMIRTranslation.cpp - Translate LLVM dialect to LLVM IR ----===//
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 the MLIR LLVM dialect and LLVM IR.
10//
11//===----------------------------------------------------------------------===//
12
16#include "mlir/IR/Operation.h"
18#include "mlir/Support/LLVM.h"
20
21#include "llvm/ADT/TypeSwitch.h"
22#include "llvm/IR/DIBuilder.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/MDBuilder.h"
27#include "llvm/IR/MatrixBuilder.h"
28#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
29#include "llvm/Support/LogicalResult.h"
30
31using namespace mlir;
32using namespace mlir::LLVM;
34
35#include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
36
37static llvm::FastMathFlags getFastmathFlags(FastmathFlagsInterface &op) {
38 using llvmFMF = llvm::FastMathFlags;
39 using FuncT = void (llvmFMF::*)(bool);
40 const std::pair<FastmathFlags, FuncT> handlers[] = {
41 // clang-format off
42 {FastmathFlags::nnan, &llvmFMF::setNoNaNs},
43 {FastmathFlags::ninf, &llvmFMF::setNoInfs},
44 {FastmathFlags::nsz, &llvmFMF::setNoSignedZeros},
45 {FastmathFlags::arcp, &llvmFMF::setAllowReciprocal},
46 {FastmathFlags::contract, &llvmFMF::setAllowContract},
47 {FastmathFlags::afn, &llvmFMF::setApproxFunc},
48 {FastmathFlags::reassoc, &llvmFMF::setAllowReassoc},
49 // clang-format on
50 };
51 llvm::FastMathFlags ret;
52 ::mlir::LLVM::FastmathFlags fmfMlir = op.getFastmathAttr().getValue();
53 for (auto it : handlers)
54 if (bitEnumContainsAll(fmfMlir, it.first))
55 (ret.*(it.second))(true);
56 return ret;
57}
58
59/// Convert the value of a DenseI64ArrayAttr to a vector of unsigned indices.
61 SmallVector<unsigned> position;
62 llvm::append_range(position, indices);
63 return position;
64}
65
66/// Convert an LLVM type to a string for printing in diagnostics.
67static std::string diagStr(const llvm::Type *type) {
68 std::string str;
69 llvm::raw_string_ostream os(str);
70 type->print(os);
71 return str;
72}
73
74/// Get the declaration of an overloaded llvm intrinsic. First we get the
75/// overloaded argument types and/or result type from the CallIntrinsicOp, and
76/// then use those to get the correct declaration of the overloaded intrinsic.
77static FailureOr<llvm::Function *>
78getOverloadedDeclaration(CallIntrinsicOp op, llvm::Intrinsic::ID id,
79 llvm::Module *module,
80 LLVM::ModuleTranslation &moduleTranslation) {
82 for (Type type : op->getOperandTypes())
83 allArgTys.push_back(moduleTranslation.convertType(type));
84
85 llvm::Type *resTy;
86 if (op.getNumResults() == 0)
87 resTy = llvm::Type::getVoidTy(module->getContext());
88 else
89 resTy = moduleTranslation.convertType(op.getResult(0).getType());
90
91 // ATM we do not support variadic intrinsics.
92 llvm::FunctionType *ft = llvm::FunctionType::get(resTy, allArgTys, false);
93
94 std::string errorMsg;
95 llvm::raw_string_ostream errorOS(errorMsg);
96 SmallVector<llvm::Type *, 8> overloadedTys;
97 if (!llvm::Intrinsic::isSignatureValid(id, ft, overloadedTys, errorOS)) {
98 return mlir::emitError(op.getLoc(), "call intrinsic signature ")
99 << diagStr(ft) << " to overloaded intrinsic " << op.getIntrinAttr()
100 << " does not match any of the overloads: " << errorMsg;
101 }
102
103 return llvm::Intrinsic::getOrInsertDeclaration(module, id, overloadedTys);
104}
105
106static llvm::OperandBundleDef
107convertOperandBundle(OperandRange bundleOperands, StringRef bundleTag,
108 LLVM::ModuleTranslation &moduleTranslation) {
109 std::vector<llvm::Value *> operands;
110 operands.reserve(bundleOperands.size());
111 for (Value bundleArg : bundleOperands)
112 operands.push_back(moduleTranslation.lookupValue(bundleArg));
113 return llvm::OperandBundleDef(bundleTag.str(), std::move(operands));
114}
115
118 LLVM::ModuleTranslation &moduleTranslation) {
120 bundles.reserve(bundleOperands.size());
121
122 for (auto [operands, tagAttr] : llvm::zip_equal(bundleOperands, bundleTags)) {
123 StringRef tag = cast<StringAttr>(tagAttr).getValue();
124 bundles.push_back(convertOperandBundle(operands, tag, moduleTranslation));
125 }
126 return bundles;
127}
128
131 std::optional<ArrayAttr> bundleTags,
132 LLVM::ModuleTranslation &moduleTranslation) {
133 if (!bundleTags)
134 return {};
135 return convertOperandBundles(bundleOperands, *bundleTags, moduleTranslation);
136}
137
138/// Builder for LLVM_CallIntrinsicOp
139static LogicalResult
140convertCallLLVMIntrinsicOp(CallIntrinsicOp op, llvm::IRBuilderBase &builder,
141 LLVM::ModuleTranslation &moduleTranslation) {
142 llvm::Module *module = builder.GetInsertBlock()->getModule();
143 llvm::Intrinsic::ID id =
144 llvm::Intrinsic::lookupIntrinsicID(op.getIntrinAttr());
145 if (!id)
146 return mlir::emitError(op.getLoc(), "could not find LLVM intrinsic: ")
147 << op.getIntrinAttr();
148
149 llvm::Function *fn = nullptr;
150 if (llvm::Intrinsic::isOverloaded(id)) {
151 auto fnOrFailure =
152 getOverloadedDeclaration(op, id, module, moduleTranslation);
153 if (failed(fnOrFailure))
154 return failure();
155 fn = *fnOrFailure;
156 } else {
157 fn = llvm::Intrinsic::getOrInsertDeclaration(module, id, {});
158 }
159
160 // Check the result type of the call.
161 const llvm::Type *intrinType =
162 op.getNumResults() == 0
163 ? llvm::Type::getVoidTy(module->getContext())
164 : moduleTranslation.convertType(op.getResultTypes().front());
165 if (intrinType != fn->getReturnType()) {
166 return mlir::emitError(op.getLoc(), "intrinsic call returns ")
167 << diagStr(intrinType) << " but " << op.getIntrinAttr()
168 << " actually returns " << diagStr(fn->getReturnType());
169 }
170
171 // Check the argument types of the call. If the function is variadic, check
172 // the subrange of required arguments.
173 if (!fn->getFunctionType()->isVarArg() &&
174 op.getArgs().size() != fn->arg_size()) {
175 return mlir::emitError(op.getLoc(), "intrinsic call has ")
176 << op.getArgs().size() << " operands but " << op.getIntrinAttr()
177 << " expects " << fn->arg_size();
178 }
179 if (fn->getFunctionType()->isVarArg() &&
180 op.getArgs().size() < fn->arg_size()) {
181 return mlir::emitError(op.getLoc(), "intrinsic call has ")
182 << op.getArgs().size() << " operands but variadic "
183 << op.getIntrinAttr() << " expects at least " << fn->arg_size();
184 }
185 // Check the arguments up to the number the function requires.
186 for (unsigned i = 0, e = fn->arg_size(); i != e; ++i) {
187 const llvm::Type *expected = fn->getArg(i)->getType();
188 const llvm::Type *actual =
189 moduleTranslation.convertType(op.getOperandTypes()[i]);
190 if (actual != expected) {
191 return mlir::emitError(op.getLoc(), "intrinsic call operand #")
192 << i << " has type " << diagStr(actual) << " but "
193 << op.getIntrinAttr() << " expects " << diagStr(expected);
194 }
195 }
196
197 FastmathFlagsInterface itf = op;
198 builder.setFastMathFlags(getFastmathFlags(itf));
199
200 auto *inst = builder.CreateCall(
201 fn, moduleTranslation.lookupValues(op.getArgs()),
202 convertOperandBundles(op.getOpBundleOperands(), op.getOpBundleTags(),
203 moduleTranslation));
204
205 if (failed(moduleTranslation.convertArgAndResultAttrs(op, inst)))
206 return failure();
207
208 if (op.getNumResults() == 1)
209 moduleTranslation.mapValue(op->getResults().front()) = inst;
210 return success();
211}
212
213static LogicalResult
214convertNamedMetadataOp(NamedMetadataOp op,
215 LLVM::ModuleTranslation &moduleTranslation) {
216 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
217 llvm::NamedMDNode *namedMD =
218 llvmModule->getOrInsertNamedMetadata(op.getMetadataName());
219 for (Attribute nodeAttr : op.getNodes()) {
220 FailureOr<llvm::Metadata *> md =
221 moduleTranslation.convertMetadataAttr(nodeAttr, [&]() {
222 return op.emitError() << "failed to convert named metadata '"
223 << op.getMetadataName() << "': ";
224 });
225 if (failed(md))
226 return failure();
227 auto *mdNode = llvm::dyn_cast_if_present<llvm::MDNode>(*md);
228 if (!mdNode) {
229 return op.emitError() << "failed to convert named metadata '"
230 << op.getMetadataName() << "'";
231 }
232 namedMD->addOperand(mdNode);
233 }
234 return success();
235}
236
238 llvm::IRBuilderBase &builder,
239 LLVM::ModuleTranslation &moduleTranslation) {
240 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
241 llvm::LLVMContext &context = llvmModule->getContext();
242 llvm::NamedMDNode *linkerMDNode =
243 llvmModule->getOrInsertNamedMetadata("llvm.linker.options");
245 mdNodes.reserve(options.size());
246 for (auto s : options.getAsRange<StringAttr>()) {
247 auto *mdNode = llvm::MDString::get(context, s.getValue());
248 mdNodes.push_back(mdNode);
249 }
250
251 auto *listMDNode = llvm::MDTuple::get(context, mdNodes);
252 linkerMDNode->addOperand(listMDNode);
253}
254
255static llvm::Metadata *
256convertModuleFlagValue(StringRef key, ArrayAttr arrayAttr,
257 llvm::IRBuilderBase &builder,
258 LLVM::ModuleTranslation &moduleTranslation) {
259 llvm::LLVMContext &context = builder.getContext();
260 llvm::MDBuilder mdb(context);
262
263 if (key == LLVMDialect::getModuleFlagKeyCGProfileName()) {
264 for (auto entry : arrayAttr.getAsRange<ModuleFlagCGProfileEntryAttr>()) {
265 auto getFuncMetadata = [&](FlatSymbolRefAttr sym) -> llvm::Metadata * {
266 if (!sym)
267 return nullptr;
268 if (llvm::Function *fn =
269 moduleTranslation.lookupFunction(sym.getValue()))
270 return llvm::ValueAsMetadata::get(fn);
271 return nullptr;
272 };
273 llvm::Metadata *fromMetadata = getFuncMetadata(entry.getFrom());
274 llvm::Metadata *toMetadata = getFuncMetadata(entry.getTo());
275
276 llvm::Metadata *vals[] = {
277 fromMetadata, toMetadata,
278 mdb.createConstant(llvm::ConstantInt::get(
279 llvm::Type::getInt64Ty(context), entry.getCount()))};
280 nodes.push_back(llvm::MDNode::get(context, vals));
281 }
282 return llvm::MDTuple::getDistinct(context, nodes);
283 }
284 // Handle ArrayAttr of StringAttrs (e.g. "riscv-isa") by converting back to
285 // an MDTuple of MDStrings for a lossless round-trip.
286 if (llvm::all_of(arrayAttr, [](Attribute a) { return isa<StringAttr>(a); })) {
287 assert(!arrayAttr.empty() &&
288 "empty string-array is invalid per ModuleFlagAttr::verify");
289 for (StringAttr strAttr : arrayAttr.getAsRange<StringAttr>())
290 nodes.push_back(llvm::MDString::get(context, strAttr.getValue()));
291 return llvm::MDTuple::get(context, nodes);
292 }
293 return nullptr;
294}
295
297 StringRef key, ModuleFlagProfileSummaryAttr summaryAttr,
298 llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation) {
299 llvm::LLVMContext &context = builder.getContext();
300 llvm::MDBuilder mdb(context);
301
302 auto getIntTuple = [&](StringRef key, uint64_t val) -> llvm::MDTuple * {
304 mdb.createString(key), mdb.createConstant(llvm::ConstantInt::get(
305 llvm::Type::getInt64Ty(context), val))};
306 return llvm::MDTuple::get(context, tupleNodes);
307 };
308
310 mdb.createString("ProfileFormat"),
311 mdb.createString(
312 stringifyProfileSummaryFormatKind(summaryAttr.getFormat()))};
313
315 llvm::MDTuple::get(context, fmtNode),
316 getIntTuple("TotalCount", summaryAttr.getTotalCount()),
317 getIntTuple("MaxCount", summaryAttr.getMaxCount()),
318 getIntTuple("MaxInternalCount", summaryAttr.getMaxInternalCount()),
319 getIntTuple("MaxFunctionCount", summaryAttr.getMaxFunctionCount()),
320 getIntTuple("NumCounts", summaryAttr.getNumCounts()),
321 getIntTuple("NumFunctions", summaryAttr.getNumFunctions()),
322 };
323
324 if (summaryAttr.getIsPartialProfile())
325 vals.push_back(
326 getIntTuple("IsPartialProfile", *summaryAttr.getIsPartialProfile()));
327
328 if (summaryAttr.getPartialProfileRatio()) {
330 mdb.createString("PartialProfileRatio"),
331 mdb.createConstant(llvm::ConstantFP::get(
332 llvm::Type::getDoubleTy(context),
333 summaryAttr.getPartialProfileRatio().getValue()))};
334 vals.push_back(llvm::MDTuple::get(context, tupleNodes));
335 }
336
337 SmallVector<llvm::Metadata *> detailedEntries;
338 llvm::Type *llvmInt64Type = llvm::Type::getInt64Ty(context);
339 for (ModuleFlagProfileSummaryDetailedAttr detailedEntry :
340 summaryAttr.getDetailedSummary()) {
342 mdb.createConstant(
343 llvm::ConstantInt::get(llvmInt64Type, detailedEntry.getCutOff())),
344 mdb.createConstant(
345 llvm::ConstantInt::get(llvmInt64Type, detailedEntry.getMinCount())),
346 mdb.createConstant(llvm::ConstantInt::get(
347 llvmInt64Type, detailedEntry.getNumCounts()))};
348 detailedEntries.push_back(llvm::MDTuple::get(context, tupleNodes));
349 }
350 SmallVector<llvm::Metadata *> detailedSummary{
351 mdb.createString("DetailedSummary"),
352 llvm::MDTuple::get(context, detailedEntries)};
353 vals.push_back(llvm::MDTuple::get(context, detailedSummary));
354
355 return llvm::MDNode::get(context, vals);
356}
357
358static void convertModuleFlagsOp(ArrayAttr flags, llvm::IRBuilderBase &builder,
359 LLVM::ModuleTranslation &moduleTranslation) {
360 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
361 auto convertIntegerAttr = [&](IntegerAttr intAttr) -> llvm::Metadata * {
362 return llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
363 llvm::Type::getInt32Ty(builder.getContext()), intAttr.getInt()));
364 };
365 for (auto flagAttr : flags.getAsRange<ModuleFlagAttrInterface>()) {
366 llvm::Metadata *valueMetadata =
368 flagAttr.getModuleFlagValue())
369 .Case([&](StringAttr strAttr) {
370 return llvm::MDString::get(builder.getContext(),
371 strAttr.getValue());
372 })
373 .Case([&](IntegerAttr intAttr) {
374 return convertIntegerAttr(intAttr);
375 })
376 .Case([&](IntrinsicIntegerAttrInterface intAttr) {
377 return convertIntegerAttr(intAttr.getIntegerAttr());
378 })
379 .Case([&](ArrayAttr arrayAttr) {
381 flagAttr.getModuleFlagKey().getValue(), arrayAttr, builder,
382 moduleTranslation);
383 })
384 .Case([&](ModuleFlagProfileSummaryAttr summaryAttr) {
386 flagAttr.getModuleFlagKey().getValue(), summaryAttr, builder,
387 moduleTranslation);
388 })
389 .Default([](auto) { return nullptr; });
390
391 assert(valueMetadata && "expected valid metadata");
392 llvmModule->addModuleFlag(
393 convertModFlagBehaviorToLLVM(flagAttr.getModuleFlagBehavior()),
394 flagAttr.getModuleFlagKey().getValue(), valueMetadata);
395 }
396}
397
398/// Looks up the GlobalValue and FunctionType for a callee symbol that is not a
399/// regular LLVM function (i.e. an alias or ifunc). Returns the lowered
400/// GlobalValue and FunctionType derived from \p calleeFuncType.
401static std::pair<llvm::GlobalValue *, llvm::FunctionType *>
403 Operation &opInst,
404 LLVM::ModuleTranslation &moduleTranslation) {
405 Operation *moduleOp = parentLLVMModule(&opInst);
406 Operation *calleeOp =
407 moduleTranslation.symbolTable().lookupSymbolIn(moduleOp, attr);
408 llvm::FunctionType *calleeType = llvm::cast<llvm::FunctionType>(
409 moduleTranslation.convertType(calleeFuncType));
410 llvm::GlobalValue *calleeGV;
411 if (isa<LLVM::AliasOp>(calleeOp))
412 calleeGV = moduleTranslation.lookupAlias(calleeOp);
413 else
414 calleeGV = moduleTranslation.lookupIFunc(calleeOp);
415 return {calleeGV, calleeType};
416}
417
418static llvm::DILocalScope *
419getLocalScopeFromLoc(llvm::IRBuilderBase &builder, Location loc,
420 LLVM::ModuleTranslation &moduleTranslation) {
421 if (auto scopeLoc =
423 if (auto *localScope = llvm::dyn_cast<llvm::DILocalScope>(
424 moduleTranslation.translateDebugInfo(scopeLoc.getMetadata())))
425 return localScope;
426 return builder.GetInsertBlock()->getParent()->getSubprogram();
427}
428
429static LogicalResult
430convertOperationImpl(Operation &opInst, llvm::IRBuilderBase &builder,
431 LLVM::ModuleTranslation &moduleTranslation) {
432
433 llvm::IRBuilder<>::FastMathFlagGuard fmfGuard(builder);
434 if (auto fmf = dyn_cast<FastmathFlagsInterface>(opInst))
435 builder.setFastMathFlags(getFastmathFlags(fmf));
436
437#include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
438#include "mlir/Dialect/LLVMIR/LLVMIntrinsicConversions.inc"
439
440 // Emit function calls. If the "callee" attribute is present, this is a
441 // direct function call and we also need to look up the remapped function
442 // itself. Otherwise, this is an indirect call and the callee is the first
443 // operand, look it up as a normal value.
444 if (auto callOp = dyn_cast<LLVM::CallOp>(opInst)) {
445 auto operands = moduleTranslation.lookupValues(callOp.getCalleeOperands());
447 convertOperandBundles(callOp.getOpBundleOperands(),
448 callOp.getOpBundleTags(), moduleTranslation);
449 ArrayRef<llvm::Value *> operandsRef(operands);
450 llvm::CallInst *call;
451 if (auto attr = callOp.getCalleeAttr()) {
452 if (llvm::Function *function =
453 moduleTranslation.lookupFunction(attr.getValue())) {
454 call = builder.CreateCall(function, operandsRef, opBundles);
455 } else {
456 auto [calleeGV, calleeType] = lookupNonFunctionSymbolCallee(
457 attr, callOp.getCalleeFunctionType(), opInst, moduleTranslation);
458 call = builder.CreateCall(calleeType, calleeGV, operandsRef, opBundles);
459 }
460 } else {
461 llvm::FunctionType *calleeType = llvm::cast<llvm::FunctionType>(
462 moduleTranslation.convertType(callOp.getCalleeFunctionType()));
463 call = builder.CreateCall(calleeType, operandsRef.front(),
464 operandsRef.drop_front(), opBundles);
465 }
466 call->setCallingConv(convertCConvToLLVM(callOp.getCConv()));
467 call->setTailCallKind(convertTailCallKindToLLVM(callOp.getTailCallKind()));
468 if (callOp.getConvergentAttr())
469 call->addFnAttr(llvm::Attribute::Convergent);
470 if (callOp.getNoUnwindAttr())
471 call->addFnAttr(llvm::Attribute::NoUnwind);
472 if (callOp.getWillReturnAttr())
473 call->addFnAttr(llvm::Attribute::WillReturn);
474 if (callOp.getNoreturnAttr())
475 call->addFnAttr(llvm::Attribute::NoReturn);
476 if (callOp.getOptsizeAttr())
477 call->addFnAttr(llvm::Attribute::OptimizeForSize);
478 if (callOp.getMinsizeAttr())
479 call->addFnAttr(llvm::Attribute::MinSize);
480 if (callOp.getSaveRegParamsAttr())
481 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
482 "save-reg-params"));
483 if (callOp.getBuiltinAttr())
484 call->addFnAttr(llvm::Attribute::Builtin);
485 if (callOp.getNobuiltinAttr())
486 call->addFnAttr(llvm::Attribute::NoBuiltin);
487 if (callOp.getReturnsTwiceAttr())
488 call->addFnAttr(llvm::Attribute::ReturnsTwice);
489 if (callOp.getColdAttr())
490 call->addFnAttr(llvm::Attribute::Cold);
491 if (callOp.getHotAttr())
492 call->addFnAttr(llvm::Attribute::Hot);
493 if (callOp.getNoduplicateAttr())
494 call->addFnAttr(llvm::Attribute::NoDuplicate);
495 if (callOp.getNoInlineAttr())
496 call->addFnAttr(llvm::Attribute::NoInline);
497 if (callOp.getAlwaysInlineAttr())
498 call->addFnAttr(llvm::Attribute::AlwaysInline);
499 if (callOp.getInlineHintAttr())
500 call->addFnAttr(llvm::Attribute::InlineHint);
501 if (callOp.getNoCallerSavedRegistersAttr())
502 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
503 "no_caller_saved_registers"));
504 if (callOp.getNocallbackAttr())
505 call->addFnAttr(llvm::Attribute::NoCallback);
506 if (StringAttr modFormat = callOp.getModularFormatAttr())
507 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
508 "modular-format",
509 modFormat.getValue()));
510 if (StringAttr zcsr = callOp.getZeroCallUsedRegsAttr())
511 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
512 "zero-call-used-regs",
513 zcsr.getValue()));
514 if (StringAttr trapFunc = callOp.getTrapFuncNameAttr())
515 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
516 "trap-func-name",
517 trapFunc.getValue()));
518
519 if (ArrayAttr noBuiltins = callOp.getNobuiltinsAttr()) {
520 if (noBuiltins.empty())
521 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
522 "no-builtins"));
523
524 moduleTranslation.convertFunctionAttrCollection(
525 noBuiltins, call, ModuleTranslation::convertNoBuiltin);
526 }
527
528 moduleTranslation.convertFunctionAttrCollection(
529 callOp.getDefaultFuncAttrsAttr(), call,
531
532 if (llvm::Attribute attr =
533 moduleTranslation.convertAllocsizeAttr(callOp.getAllocsizeAttr());
534 attr.isValid())
535 call->addFnAttr(attr);
536
537 if (failed(moduleTranslation.convertArgAndResultAttrs(callOp, call)))
538 return failure();
539
540 if (MemoryEffectsAttr memAttr = callOp.getMemoryEffectsAttr()) {
541 llvm::MemoryEffects memEffects =
542 llvm::MemoryEffects(llvm::MemoryEffects::Location::ArgMem,
543 convertModRefInfoToLLVM(memAttr.getArgMem())) |
544 llvm::MemoryEffects(
545 llvm::MemoryEffects::Location::InaccessibleMem,
546 convertModRefInfoToLLVM(memAttr.getInaccessibleMem())) |
547 llvm::MemoryEffects(llvm::MemoryEffects::Location::Other,
548 convertModRefInfoToLLVM(memAttr.getOther())) |
549 llvm::MemoryEffects(llvm::MemoryEffects::Location::ErrnoMem,
550 convertModRefInfoToLLVM(memAttr.getErrnoMem())) |
551 llvm::MemoryEffects(
552 llvm::MemoryEffects::Location::TargetMem0,
553 convertModRefInfoToLLVM(memAttr.getTargetMem0())) |
554 llvm::MemoryEffects(llvm::MemoryEffects::Location::TargetMem1,
555 convertModRefInfoToLLVM(memAttr.getTargetMem1()));
556 call->setMemoryEffects(memEffects);
557 }
558
559 moduleTranslation.setAccessGroupsMetadata(callOp, call);
560 moduleTranslation.setAliasScopeMetadata(callOp, call);
561 moduleTranslation.setTBAAMetadata(callOp, call);
562 // If the called function has a result, remap the corresponding value. Note
563 // that LLVM IR dialect CallOp has either 0 or 1 result.
564 if (opInst.getNumResults() != 0)
565 moduleTranslation.mapValue(opInst.getResult(0), call);
566 // Check that LLVM call returns void for 0-result functions.
567 else if (!call->getType()->isVoidTy())
568 return failure();
569 moduleTranslation.mapCall(callOp, call);
570 return success();
571 }
572
573 if (auto inlineAsmOp = dyn_cast<LLVM::InlineAsmOp>(opInst)) {
574 // TODO: refactor function type creation which usually occurs in std-LLVM
575 // conversion.
576 SmallVector<Type, 8> operandTypes;
577 llvm::append_range(operandTypes, inlineAsmOp.getOperands().getTypes());
578
579 Type resultType;
580 if (inlineAsmOp.getNumResults() == 0) {
581 resultType = LLVM::LLVMVoidType::get(&moduleTranslation.getContext());
582 } else {
583 assert(inlineAsmOp.getNumResults() == 1);
584 resultType = inlineAsmOp.getResultTypes()[0];
585 }
586 auto ft = LLVM::LLVMFunctionType::get(resultType, operandTypes);
587 llvm::InlineAsm *inlineAsmInst =
588 inlineAsmOp.getAsmDialect()
589 ? llvm::InlineAsm::get(
590 static_cast<llvm::FunctionType *>(
591 moduleTranslation.convertType(ft)),
592 inlineAsmOp.getAsmString(), inlineAsmOp.getConstraints(),
593 inlineAsmOp.getHasSideEffects(),
594 inlineAsmOp.getIsAlignStack(),
595 convertAsmDialectToLLVM(*inlineAsmOp.getAsmDialect()))
596 : llvm::InlineAsm::get(static_cast<llvm::FunctionType *>(
597 moduleTranslation.convertType(ft)),
598 inlineAsmOp.getAsmString(),
599 inlineAsmOp.getConstraints(),
600 inlineAsmOp.getHasSideEffects(),
601 inlineAsmOp.getIsAlignStack());
602 llvm::CallInst *inst = builder.CreateCall(
603 inlineAsmInst,
604 moduleTranslation.lookupValues(inlineAsmOp.getOperands()));
605 inst->setTailCallKind(convertTailCallKindToLLVM(
606 inlineAsmOp.getTailCallKindAttr().getTailCallKind()));
607 if (auto maybeOperandAttrs = inlineAsmOp.getOperandAttrs()) {
608 llvm::AttributeList attrList;
609 for (const auto &it : llvm::enumerate(*maybeOperandAttrs)) {
610 Attribute attr = it.value();
611 if (!attr)
612 continue;
613 DictionaryAttr dAttr = cast<DictionaryAttr>(attr);
614 if (dAttr.empty())
615 continue;
616 TypeAttr tAttr =
617 cast<TypeAttr>(dAttr.get(InlineAsmOp::getElementTypeAttrName()));
618 llvm::AttrBuilder b(moduleTranslation.getLLVMContext());
619 llvm::Type *ty = moduleTranslation.convertType(tAttr.getValue());
620 b.addTypeAttr(llvm::Attribute::ElementType, ty);
621 // shift to account for the returned value (this is always 1 aggregate
622 // value in LLVM).
623 int shift = (opInst.getNumResults() > 0) ? 1 : 0;
624 attrList = attrList.addAttributesAtIndex(
625 moduleTranslation.getLLVMContext(), it.index() + shift, b);
626 }
627 inst->setAttributes(attrList);
628 }
629
630 if (opInst.getNumResults() != 0)
631 moduleTranslation.mapValue(opInst.getResult(0), inst);
632 return success();
633 }
634
635 if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
636 auto operands = moduleTranslation.lookupValues(invOp.getCalleeOperands());
638 convertOperandBundles(invOp.getOpBundleOperands(),
639 invOp.getOpBundleTags(), moduleTranslation);
640 ArrayRef<llvm::Value *> operandsRef(operands);
641 llvm::InvokeInst *result;
642 if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) {
643 if (llvm::Function *function =
644 moduleTranslation.lookupFunction(attr.getValue())) {
645 result = builder.CreateInvoke(
646 function, moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
647 moduleTranslation.lookupBlock(invOp.getSuccessor(1)), operandsRef,
648 opBundles);
649 } else {
650 auto [calleeGV, calleeType] = lookupNonFunctionSymbolCallee(
651 attr, invOp.getCalleeFunctionType(), opInst, moduleTranslation);
652 result = builder.CreateInvoke(
653 calleeType, calleeGV,
654 moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
655 moduleTranslation.lookupBlock(invOp.getSuccessor(1)), operandsRef,
656 opBundles);
657 }
658 } else {
659 llvm::FunctionType *calleeType = llvm::cast<llvm::FunctionType>(
660 moduleTranslation.convertType(invOp.getCalleeFunctionType()));
661 result = builder.CreateInvoke(
662 calleeType, operandsRef.front(),
663 moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
664 moduleTranslation.lookupBlock(invOp.getSuccessor(1)),
665 operandsRef.drop_front(), opBundles);
666 }
667 result->setCallingConv(convertCConvToLLVM(invOp.getCConv()));
668 moduleTranslation.convertFunctionAttrCollection(
669 invOp.getDefaultFuncAttrsAttr(), result,
671 if (failed(moduleTranslation.convertArgAndResultAttrs(invOp, result)))
672 return failure();
673 moduleTranslation.mapBranch(invOp, result);
674 // InvokeOp can only have 0 or 1 result
675 if (invOp->getNumResults() != 0) {
676 moduleTranslation.mapValue(opInst.getResult(0), result);
677 return success();
678 }
679 return success(result->getType()->isVoidTy());
680 }
681
682 if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
683 llvm::Type *ty = moduleTranslation.convertType(lpOp.getType());
684 llvm::LandingPadInst *lpi =
685 builder.CreateLandingPad(ty, lpOp.getNumOperands());
686 lpi->setCleanup(lpOp.getCleanup());
687
688 // Add clauses
689 for (llvm::Value *operand :
690 moduleTranslation.lookupValues(lpOp.getOperands())) {
691 // All operands should be constant - checked by verifier
692 if (auto *constOperand = dyn_cast<llvm::Constant>(operand))
693 lpi->addClause(constOperand);
694 }
695 moduleTranslation.mapValue(lpOp.getResult(), lpi);
696 return success();
697 }
698
699 // Emit branches. We need to look up the remapped blocks and ignore the
700 // block arguments that were transformed into PHI nodes.
701 if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
702 llvm::UncondBrInst *branch =
703 builder.CreateBr(moduleTranslation.lookupBlock(brOp.getSuccessor()));
704 moduleTranslation.mapBranch(&opInst, branch);
705 moduleTranslation.setLoopMetadata(&opInst, branch);
706 return success();
707 }
708 if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
709 llvm::CondBrInst *branch = builder.CreateCondBr(
710 moduleTranslation.lookupValue(condbrOp.getOperand(0)),
711 moduleTranslation.lookupBlock(condbrOp.getSuccessor(0)),
712 moduleTranslation.lookupBlock(condbrOp.getSuccessor(1)));
713 moduleTranslation.mapBranch(&opInst, branch);
714 moduleTranslation.setLoopMetadata(&opInst, branch);
715 return success();
716 }
717 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(opInst)) {
718 llvm::SwitchInst *switchInst = builder.CreateSwitch(
719 moduleTranslation.lookupValue(switchOp.getValue()),
720 moduleTranslation.lookupBlock(switchOp.getDefaultDestination()),
721 switchOp.getCaseDestinations().size());
722
723 // Handle switch with zero cases.
724 if (!switchOp.getCaseValues())
725 return success();
726
727 auto *ty = llvm::cast<llvm::IntegerType>(
728 moduleTranslation.convertType(switchOp.getValue().getType()));
729 for (auto i :
730 llvm::zip(llvm::cast<DenseIntElementsAttr>(*switchOp.getCaseValues()),
731 switchOp.getCaseDestinations()))
732 switchInst->addCase(
733 llvm::ConstantInt::get(ty, std::get<0>(i).getLimitedValue()),
734 moduleTranslation.lookupBlock(std::get<1>(i)));
735
736 moduleTranslation.mapBranch(&opInst, switchInst);
737 return success();
738 }
739 if (auto indBrOp = dyn_cast<LLVM::IndirectBrOp>(opInst)) {
740 llvm::IndirectBrInst *indBr = builder.CreateIndirectBr(
741 moduleTranslation.lookupValue(indBrOp.getAddr()),
742 indBrOp->getNumSuccessors());
743 for (auto *succ : indBrOp.getSuccessors())
744 indBr->addDestination(moduleTranslation.lookupBlock(succ));
745 moduleTranslation.mapBranch(&opInst, indBr);
746 return success();
747 }
748
749 // Emit addressof. We need to look up the global value referenced by the
750 // operation and store it in the MLIR-to-LLVM value mapping. This does not
751 // emit any LLVM instruction.
752 if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
753 LLVM::GlobalOp global =
754 addressOfOp.getGlobal(moduleTranslation.symbolTable());
755 LLVM::LLVMFuncOp function =
756 addressOfOp.getFunction(moduleTranslation.symbolTable());
757 LLVM::AliasOp alias = addressOfOp.getAlias(moduleTranslation.symbolTable());
758 LLVM::IFuncOp ifunc = addressOfOp.getIFunc(moduleTranslation.symbolTable());
759
760 // The verifier should not have allowed this.
761 assert((global || function || alias || ifunc) &&
762 "referencing an undefined global, function, alias, or ifunc");
763
764 llvm::Value *llvmValue = nullptr;
765 if (global)
766 llvmValue = moduleTranslation.lookupGlobal(global);
767 else if (alias)
768 llvmValue = moduleTranslation.lookupAlias(alias);
769 else if (function)
770 llvmValue = moduleTranslation.lookupFunction(function.getName());
771 else
772 llvmValue = moduleTranslation.lookupIFunc(ifunc);
773
774 moduleTranslation.mapValue(addressOfOp.getResult(), llvmValue);
775 return success();
776 }
777
778 // Emit dso_local_equivalent. We need to look up the global value referenced
779 // by the operation and store it in the MLIR-to-LLVM value mapping.
780 if (auto dsoLocalEquivalentOp =
781 dyn_cast<LLVM::DSOLocalEquivalentOp>(opInst)) {
782 LLVM::LLVMFuncOp function =
783 dsoLocalEquivalentOp.getFunction(moduleTranslation.symbolTable());
784 LLVM::AliasOp alias =
785 dsoLocalEquivalentOp.getAlias(moduleTranslation.symbolTable());
786
787 // The verifier should not have allowed this.
788 assert((function || alias) &&
789 "referencing an undefined function, or alias");
790
791 llvm::Value *llvmValue = nullptr;
792 if (alias)
793 llvmValue = moduleTranslation.lookupAlias(alias);
794 else
795 llvmValue = moduleTranslation.lookupFunction(function.getName());
796
797 moduleTranslation.mapValue(
798 dsoLocalEquivalentOp.getResult(),
799 llvm::DSOLocalEquivalent::get(cast<llvm::GlobalValue>(llvmValue)));
800 return success();
801 }
802
803 // Emit blockaddress. We first need to find the LLVM block referenced by this
804 // operation and then create a LLVM block address for it.
805 if (auto blockAddressOp = dyn_cast<LLVM::BlockAddressOp>(opInst)) {
806 BlockAddressAttr blockAddressAttr = blockAddressOp.getBlockAddr();
807 llvm::BasicBlock *llvmBlock =
808 moduleTranslation.lookupBlockAddress(blockAddressAttr);
809
810 llvm::Value *llvmValue = nullptr;
811 StringRef fnName = blockAddressAttr.getFunction().getValue();
812 if (llvmBlock) {
813 llvm::Function *llvmFn = moduleTranslation.lookupFunction(fnName);
814 llvmValue = llvm::BlockAddress::get(llvmFn, llvmBlock);
815 } else {
816 // The matching LLVM block is not yet emitted, a placeholder is created
817 // in its place. When the LLVM block is emitted later in translation,
818 // the llvmValue is replaced with the actual llvm::BlockAddress.
819 // A GlobalVariable is chosen as placeholder because in general LLVM
820 // constants are uniqued and are not proper for RAUW, since that could
821 // harm unrelated uses of the constant.
822 llvmValue = new llvm::GlobalVariable(
823 *moduleTranslation.getLLVMModule(),
824 llvm::PointerType::getUnqual(moduleTranslation.getLLVMContext()),
825 /*isConstant=*/true, llvm::GlobalValue::LinkageTypes::ExternalLinkage,
826 /*Initializer=*/nullptr,
827 Twine("__mlir_block_address_")
828 .concat(Twine(fnName))
829 .concat(Twine((uint64_t)blockAddressOp.getOperation())));
830 moduleTranslation.mapUnresolvedBlockAddress(blockAddressOp, llvmValue);
831 }
832
833 moduleTranslation.mapValue(blockAddressOp.getResult(), llvmValue);
834 return success();
835 }
836
837 // Emit block label. If this label is seen before BlockAddressOp is
838 // translated, go ahead and already map it.
839 if (auto blockTagOp = dyn_cast<LLVM::BlockTagOp>(opInst)) {
840 auto funcOp = blockTagOp->getParentOfType<LLVMFuncOp>();
841 BlockAddressAttr blockAddressAttr = BlockAddressAttr::get(
842 &moduleTranslation.getContext(),
843 FlatSymbolRefAttr::get(&moduleTranslation.getContext(),
844 funcOp.getName()),
845 blockTagOp.getTag());
846 moduleTranslation.mapBlockAddress(blockAddressAttr,
847 builder.GetInsertBlock());
848 return success();
849 }
850
851 return failure();
852}
853
854static LogicalResult
856 NamedAttribute attribute,
857 LLVM::ModuleTranslation &moduleTranslation) {
858 StringRef name = attribute.getName();
859 if (name == LLVMDialect::getMmraAttrName()) {
861 if (auto oneTag = dyn_cast<LLVM::MMRATagAttr>(attribute.getValue())) {
862 tags.emplace_back(oneTag.getPrefix(), oneTag.getSuffix());
863 } else if (auto manyTags = dyn_cast<ArrayAttr>(attribute.getValue())) {
864 for (Attribute attr : manyTags) {
865 auto tag = dyn_cast<MMRATagAttr>(attr);
866 if (!tag)
867 return op.emitOpError(
868 "MMRA annotations array contains value that isn't an MMRA tag");
869 tags.emplace_back(tag.getPrefix(), tag.getSuffix());
870 }
871 } else {
872 return op.emitOpError(
873 "llvm.mmra is something other than an MMRA tag or an array of them");
874 }
875 llvm::MDTuple *mmraMd =
876 llvm::MMRAMetadata::getMD(moduleTranslation.getLLVMContext(), tags);
877 if (!mmraMd) {
878 // Empty list, canonicalizes to nothing
879 return success();
880 }
881 for (llvm::Instruction *inst : instructions)
882 inst->setMetadata(llvm::LLVMContext::MD_mmra, mmraMd);
883 return success();
884 }
885 return success();
886}
887
888namespace {
889/// Implementation of the dialect interface that converts operations belonging
890/// to the LLVM dialect to LLVM IR.
891class LLVMDialectLLVMIRTranslationInterface
892 : public LLVMTranslationDialectInterface {
893public:
894 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
895
896 /// Translates the given operation to LLVM IR using the provided IR builder
897 /// and saving the state in `moduleTranslation`.
898 LogicalResult
899 convertOperation(Operation *op, llvm::IRBuilderBase &builder,
900 LLVM::ModuleTranslation &moduleTranslation) const final {
901 return convertOperationImpl(*op, builder, moduleTranslation);
902 }
903
904 /// Handle some metadata that is represented as a discardable attribute.
905 LogicalResult
906 amendOperation(Operation *op, ArrayRef<llvm::Instruction *> instructions,
907 NamedAttribute attribute,
908 LLVM::ModuleTranslation &moduleTranslation) const final {
909 return amendOperationImpl(*op, instructions, attribute, moduleTranslation);
910 }
911};
912} // namespace
913
915 registry.insert<LLVM::LLVMDialect>();
916 registry.addExtension(+[](MLIRContext *ctx, LLVM::LLVMDialect *dialect) {
917 dialect->addInterfaces<LLVMDialectLLVMIRTranslationInterface>();
918 });
919}
920
922 DialectRegistry registry;
924 context.appendDialectRegistry(registry);
925}
return success()
static IntegerAttr convertIntegerAttr(IntegerAttr srcAttr, IntegerType dstType, Builder builder)
Converts the given srcAttr to a new attribute of the given dstType.
static std::string diagStr(const llvm::Type *type)
Convert an LLVM type to a string for printing in diagnostics.
static llvm::Metadata * convertModuleFlagValue(StringRef key, ArrayAttr arrayAttr, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static SmallVector< llvm::OperandBundleDef > convertOperandBundles(OperandRangeRange bundleOperands, ArrayAttr bundleTags, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertNamedMetadataOp(NamedMetadataOp op, LLVM::ModuleTranslation &moduleTranslation)
static std::pair< llvm::GlobalValue *, llvm::FunctionType * > lookupNonFunctionSymbolCallee(FlatSymbolRefAttr attr, mlir::Type calleeFuncType, Operation &opInst, LLVM::ModuleTranslation &moduleTranslation)
Looks up the GlobalValue and FunctionType for a callee symbol that is not a regular LLVM function (i....
static FailureOr< llvm::Function * > getOverloadedDeclaration(CallIntrinsicOp op, llvm::Intrinsic::ID id, llvm::Module *module, LLVM::ModuleTranslation &moduleTranslation)
Get the declaration of an overloaded llvm intrinsic.
static void convertModuleFlagsOp(ArrayAttr flags, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertOperationImpl(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertCallLLVMIntrinsicOp(CallIntrinsicOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Builder for LLVM_CallIntrinsicOp.
static LogicalResult amendOperationImpl(Operation &op, ArrayRef< llvm::Instruction * > instructions, NamedAttribute attribute, LLVM::ModuleTranslation &moduleTranslation)
static llvm::FastMathFlags getFastmathFlags(FastmathFlagsInterface &op)
static llvm::OperandBundleDef convertOperandBundle(OperandRange bundleOperands, StringRef bundleTag, LLVM::ModuleTranslation &moduleTranslation)
static SmallVector< unsigned > extractPosition(ArrayRef< int64_t > indices)
Convert the value of a DenseI64ArrayAttr to a vector of unsigned indices.
static llvm::DILocalScope * getLocalScopeFromLoc(llvm::IRBuilderBase &builder, Location loc, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Metadata * convertModuleFlagProfileSummaryAttr(StringRef key, ModuleFlagProfileSummaryAttr summaryAttr, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static void convertLinkerOptionsOp(ArrayAttr options, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition Attributes.h:25
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.
A symbol reference with a reference path containing a single element.
static FlatSymbolRefAttr get(StringAttr value)
Construct a symbol reference for the given value name.
This class represents a fused location whose metadata is known to be an instance of the given type.
Definition Location.h:149
Implementation class for module translation.
void mapUnresolvedBlockAddress(BlockAddressOp op, llvm::Value *cst)
Maps a blockaddress operation to its corresponding placeholder LLVM value.
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::Attribute convertAllocsizeAttr(DenseI32ArrayAttr allocsizeAttr)
MLIRContext & getContext()
Returns the MLIR context of the module being translated.
void mapBranch(Operation *mlir, llvm::Instruction *llvm)
Stores the mapping between an MLIR operation with successors and a corresponding LLVM IR instruction.
SmallVector< llvm::Value * > lookupValues(ValueRange values)
Looks up remapped a list of remapped values.
void 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::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
LogicalResult convertArgAndResultAttrs(ArgAndResultAttrsOpInterface attrsOp, llvm::CallBase *call, ArrayRef< unsigned > immArgPositions={})
Converts argument and result attributes from attrsOp to LLVM IR attributes on the call instruction.
static std::optional< llvm::Attribute > convertNoBuiltin(llvm::LLVMContext &ctx, mlir::Attribute a)
SymbolTableCollection & symbolTable()
llvm::Type * convertType(Type type)
Converts the type from MLIR LLVM dialect to LLVM.
void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
FailureOr< llvm::Metadata * > convertMetadataAttr(Attribute attr, function_ref< InFlightDiagnostic()> emitError)
Converts an LLVM dialect metadata attribute to LLVM IR metadata.
llvm::BasicBlock * lookupBlockAddress(BlockAddressAttr attr) const
Finds the LLVM basic block that corresponds to the given BlockAddressAttr.
llvm::GlobalValue * lookupIFunc(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining an IFunc.
llvm::Metadata * translateDebugInfo(LLVM::DINodeAttr attr)
Translates the given LLVM debug info metadata.
llvm::GlobalValue * lookupAlias(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global alias va...
llvm::Function * lookupFunction(StringRef name) const
Finds an LLVM IR function by its name.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
static std::optional< llvm::Attribute > convertDefaultFuncAttr(llvm::LLVMContext &ctx, mlir::NamedAttribute namedAttr)
void setAliasScopeMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
void setAccessGroupsMetadata(AccessGroupOpInterface op, llvm::Instruction *inst)
void mapValue(Value mlir, llvm::Value *llvm)
Stores the mapping between an MLIR value and its LLVM IR counterpart.
llvm::LLVMContext & getLLVMContext() const
Returns the LLVM context in which the IR is being constructed.
void mapBlockAddress(BlockAddressAttr attr, llvm::BasicBlock *block)
Maps a BlockAddressAttr to its corresponding LLVM basic block.
void setLoopMetadata(Operation *op, llvm::Instruction *inst)
Sets LLVM loop metadata for branch operations that have a loop annotation attribute.
T findInstanceOf()
Return an instance of the given location type if one is nested under the current location.
Definition Location.h:45
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
void appendDialectRegistry(const DialectRegistry &registry)
Append the contents of the given dialect registry to the registry associated with this context.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:164
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:179
This class represents a contiguous range of operand ranges, e.g.
Definition ValueRange.h:85
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
AttrClass getAttrOfType(StringAttr name)
Definition Operation.h:575
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:432
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:429
virtual Operation * lookupSymbolIn(Operation *symbolTableOp, StringAttr symbol)
Look up a symbol with the specified name within the specified symbol table operation,...
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
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.
Operation * parentLLVMModule(Operation *op)
Lookup parent Module satisfying LLVM conditions on the Module Operation.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
void registerLLVMDialectTranslation(DialectRegistry &registry)
Register the LLVM dialect and the translation from it to the LLVM IR in the given registry;.