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 (callOp.getUniformWorkGroupSizeAttr())
515 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
516 "uniform-work-group-size"));
517 if (StringAttr trapFunc = callOp.getTrapFuncNameAttr())
518 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
519 "trap-func-name",
520 trapFunc.getValue()));
521
522 if (ArrayAttr noBuiltins = callOp.getNobuiltinsAttr()) {
523 if (noBuiltins.empty())
524 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
525 "no-builtins"));
526
527 moduleTranslation.convertFunctionAttrCollection(
528 noBuiltins, call, ModuleTranslation::convertNoBuiltin);
529 }
530
531 moduleTranslation.convertFunctionAttrCollection(
532 callOp.getDefaultFuncAttrsAttr(), call,
534
535 if (llvm::Attribute attr =
536 moduleTranslation.convertAllocsizeAttr(callOp.getAllocsizeAttr());
537 attr.isValid())
538 call->addFnAttr(attr);
539
540 if (failed(moduleTranslation.convertArgAndResultAttrs(callOp, call)))
541 return failure();
542
543 if (MemoryEffectsAttr memAttr = callOp.getMemoryEffectsAttr()) {
544 llvm::MemoryEffects memEffects =
545 llvm::MemoryEffects(llvm::MemoryEffects::Location::ArgMem,
546 convertModRefInfoToLLVM(memAttr.getArgMem())) |
547 llvm::MemoryEffects(
548 llvm::MemoryEffects::Location::InaccessibleMem,
549 convertModRefInfoToLLVM(memAttr.getInaccessibleMem())) |
550 llvm::MemoryEffects(llvm::MemoryEffects::Location::Other,
551 convertModRefInfoToLLVM(memAttr.getOther())) |
552 llvm::MemoryEffects(llvm::MemoryEffects::Location::ErrnoMem,
553 convertModRefInfoToLLVM(memAttr.getErrnoMem())) |
554 llvm::MemoryEffects(
555 llvm::MemoryEffects::Location::TargetMem0,
556 convertModRefInfoToLLVM(memAttr.getTargetMem0())) |
557 llvm::MemoryEffects(llvm::MemoryEffects::Location::TargetMem1,
558 convertModRefInfoToLLVM(memAttr.getTargetMem1()));
559 call->setMemoryEffects(memEffects);
560 }
561
562 moduleTranslation.setAccessGroupsMetadata(callOp, call);
563 moduleTranslation.setAliasScopeMetadata(callOp, call);
564 moduleTranslation.setTBAAMetadata(callOp, call);
565 // If the called function has a result, remap the corresponding value. Note
566 // that LLVM IR dialect CallOp has either 0 or 1 result.
567 if (opInst.getNumResults() != 0)
568 moduleTranslation.mapValue(opInst.getResult(0), call);
569 // Check that LLVM call returns void for 0-result functions.
570 else if (!call->getType()->isVoidTy())
571 return failure();
572 moduleTranslation.mapCall(callOp, call);
573 return success();
574 }
575
576 if (auto inlineAsmOp = dyn_cast<LLVM::InlineAsmOp>(opInst)) {
577 // TODO: refactor function type creation which usually occurs in std-LLVM
578 // conversion.
579 SmallVector<Type, 8> operandTypes;
580 llvm::append_range(operandTypes, inlineAsmOp.getOperands().getTypes());
581
582 Type resultType;
583 if (inlineAsmOp.getNumResults() == 0) {
584 resultType = LLVM::LLVMVoidType::get(&moduleTranslation.getContext());
585 } else {
586 assert(inlineAsmOp.getNumResults() == 1);
587 resultType = inlineAsmOp.getResultTypes()[0];
588 }
589 auto ft = LLVM::LLVMFunctionType::get(resultType, operandTypes);
590 llvm::InlineAsm *inlineAsmInst =
591 inlineAsmOp.getAsmDialect()
592 ? llvm::InlineAsm::get(
593 static_cast<llvm::FunctionType *>(
594 moduleTranslation.convertType(ft)),
595 inlineAsmOp.getAsmString(), inlineAsmOp.getConstraints(),
596 inlineAsmOp.getHasSideEffects(),
597 inlineAsmOp.getIsAlignStack(),
598 convertAsmDialectToLLVM(*inlineAsmOp.getAsmDialect()))
599 : llvm::InlineAsm::get(static_cast<llvm::FunctionType *>(
600 moduleTranslation.convertType(ft)),
601 inlineAsmOp.getAsmString(),
602 inlineAsmOp.getConstraints(),
603 inlineAsmOp.getHasSideEffects(),
604 inlineAsmOp.getIsAlignStack());
605 llvm::CallInst *inst = builder.CreateCall(
606 inlineAsmInst,
607 moduleTranslation.lookupValues(inlineAsmOp.getOperands()));
608 inst->setTailCallKind(convertTailCallKindToLLVM(
609 inlineAsmOp.getTailCallKindAttr().getTailCallKind()));
610 if (inlineAsmOp.getConvergent())
611 inst->addFnAttr(llvm::Attribute::Convergent);
612 if (auto maybeOperandAttrs = inlineAsmOp.getOperandAttrs()) {
613 llvm::AttributeList attrList;
614 for (const auto &it : llvm::enumerate(*maybeOperandAttrs)) {
615 Attribute attr = it.value();
616 if (!attr)
617 continue;
618 DictionaryAttr dAttr = cast<DictionaryAttr>(attr);
619 if (dAttr.empty())
620 continue;
621 TypeAttr tAttr =
622 cast<TypeAttr>(dAttr.get(InlineAsmOp::getElementTypeAttrName()));
623 llvm::AttrBuilder b(moduleTranslation.getLLVMContext());
624 llvm::Type *ty = moduleTranslation.convertType(tAttr.getValue());
625 b.addTypeAttr(llvm::Attribute::ElementType, ty);
626 // shift to account for the returned value (this is always 1 aggregate
627 // value in LLVM).
628 int shift = (opInst.getNumResults() > 0) ? 1 : 0;
629 attrList = attrList.addAttributesAtIndex(
630 moduleTranslation.getLLVMContext(), it.index() + shift, b);
631 }
632 inst->setAttributes(attrList);
633 }
634
635 if (opInst.getNumResults() != 0)
636 moduleTranslation.mapValue(opInst.getResult(0), inst);
637 return success();
638 }
639
640 if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
641 auto operands = moduleTranslation.lookupValues(invOp.getCalleeOperands());
643 convertOperandBundles(invOp.getOpBundleOperands(),
644 invOp.getOpBundleTags(), moduleTranslation);
645 ArrayRef<llvm::Value *> operandsRef(operands);
646 llvm::InvokeInst *result;
647 if (auto attr = invOp.getCalleeAttr()) {
648 if (llvm::Function *function =
649 moduleTranslation.lookupFunction(attr.getValue())) {
650 result = builder.CreateInvoke(
651 function, moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
652 moduleTranslation.lookupBlock(invOp.getSuccessor(1)), operandsRef,
653 opBundles);
654 } else {
655 auto [calleeGV, calleeType] = lookupNonFunctionSymbolCallee(
656 attr, invOp.getCalleeFunctionType(), opInst, moduleTranslation);
657 result = builder.CreateInvoke(
658 calleeType, calleeGV,
659 moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
660 moduleTranslation.lookupBlock(invOp.getSuccessor(1)), operandsRef,
661 opBundles);
662 }
663 } else {
664 llvm::FunctionType *calleeType = llvm::cast<llvm::FunctionType>(
665 moduleTranslation.convertType(invOp.getCalleeFunctionType()));
666 result = builder.CreateInvoke(
667 calleeType, operandsRef.front(),
668 moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
669 moduleTranslation.lookupBlock(invOp.getSuccessor(1)),
670 operandsRef.drop_front(), opBundles);
671 }
672 result->setCallingConv(convertCConvToLLVM(invOp.getCConv()));
673 if (invOp.getUniformWorkGroupSizeAttr())
674 result->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
675 "uniform-work-group-size"));
676 moduleTranslation.convertFunctionAttrCollection(
677 invOp.getDefaultFuncAttrsAttr(), result,
679 if (failed(moduleTranslation.convertArgAndResultAttrs(invOp, result)))
680 return failure();
681 moduleTranslation.mapBranch(invOp, result);
682 // InvokeOp can only have 0 or 1 result
683 if (invOp->getNumResults() != 0) {
684 moduleTranslation.mapValue(opInst.getResult(0), result);
685 return success();
686 }
687 return success(result->getType()->isVoidTy());
688 }
689
690 if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
691 llvm::Type *ty = moduleTranslation.convertType(lpOp.getType());
692 llvm::LandingPadInst *lpi =
693 builder.CreateLandingPad(ty, lpOp.getNumOperands());
694 lpi->setCleanup(lpOp.getCleanup());
695
696 // Add clauses
697 for (llvm::Value *operand :
698 moduleTranslation.lookupValues(lpOp.getOperands())) {
699 // All operands should be constant - checked by verifier
700 if (auto *constOperand = dyn_cast<llvm::Constant>(operand))
701 lpi->addClause(constOperand);
702 }
703 moduleTranslation.mapValue(lpOp.getResult(), lpi);
704 return success();
705 }
706
707 // Emit branches. We need to look up the remapped blocks and ignore the
708 // block arguments that were transformed into PHI nodes.
709 if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
710 llvm::UncondBrInst *branch =
711 builder.CreateBr(moduleTranslation.lookupBlock(brOp.getSuccessor()));
712 moduleTranslation.mapBranch(&opInst, branch);
713 moduleTranslation.setLoopMetadata(&opInst, branch);
714 return success();
715 }
716 if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
717 llvm::CondBrInst *branch = builder.CreateCondBr(
718 moduleTranslation.lookupValue(condbrOp.getOperand(0)),
719 moduleTranslation.lookupBlock(condbrOp.getSuccessor(0)),
720 moduleTranslation.lookupBlock(condbrOp.getSuccessor(1)));
721 moduleTranslation.mapBranch(&opInst, branch);
722 moduleTranslation.setLoopMetadata(&opInst, branch);
723 return success();
724 }
725 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(opInst)) {
726 llvm::SwitchInst *switchInst = builder.CreateSwitch(
727 moduleTranslation.lookupValue(switchOp.getValue()),
728 moduleTranslation.lookupBlock(switchOp.getDefaultDestination()),
729 switchOp.getCaseDestinations().size());
730
731 // Handle switch with zero cases.
732 if (!switchOp.getCaseValues())
733 return success();
734
735 auto *ty = llvm::cast<llvm::IntegerType>(
736 moduleTranslation.convertType(switchOp.getValue().getType()));
737 for (auto i :
738 llvm::zip(llvm::cast<DenseIntElementsAttr>(*switchOp.getCaseValues()),
739 switchOp.getCaseDestinations()))
740 switchInst->addCase(
741 llvm::ConstantInt::get(ty, std::get<0>(i).getLimitedValue()),
742 moduleTranslation.lookupBlock(std::get<1>(i)));
743
744 moduleTranslation.mapBranch(&opInst, switchInst);
745 return success();
746 }
747 if (auto indBrOp = dyn_cast<LLVM::IndirectBrOp>(opInst)) {
748 llvm::IndirectBrInst *indBr = builder.CreateIndirectBr(
749 moduleTranslation.lookupValue(indBrOp.getAddr()),
750 indBrOp->getNumSuccessors());
751 for (auto *succ : indBrOp.getSuccessors())
752 indBr->addDestination(moduleTranslation.lookupBlock(succ));
753 moduleTranslation.mapBranch(&opInst, indBr);
754 return success();
755 }
756
757 // Emit addressof. We need to look up the global value referenced by the
758 // operation and store it in the MLIR-to-LLVM value mapping. This does not
759 // emit any LLVM instruction.
760 if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
761 LLVM::GlobalOp global =
762 addressOfOp.getGlobal(moduleTranslation.symbolTable());
763 LLVM::LLVMFuncOp function =
764 addressOfOp.getFunction(moduleTranslation.symbolTable());
765 LLVM::AliasOp alias = addressOfOp.getAlias(moduleTranslation.symbolTable());
766 LLVM::IFuncOp ifunc = addressOfOp.getIFunc(moduleTranslation.symbolTable());
767
768 // The verifier should not have allowed this.
769 assert((global || function || alias || ifunc) &&
770 "referencing an undefined global, function, alias, or ifunc");
771
772 llvm::Value *llvmValue = nullptr;
773 if (global)
774 llvmValue = moduleTranslation.lookupGlobal(global);
775 else if (alias)
776 llvmValue = moduleTranslation.lookupAlias(alias);
777 else if (function)
778 llvmValue = moduleTranslation.lookupFunction(function.getName());
779 else
780 llvmValue = moduleTranslation.lookupIFunc(ifunc);
781
782 moduleTranslation.mapValue(addressOfOp.getResult(), llvmValue);
783 return success();
784 }
785
786 // Emit dso_local_equivalent. We need to look up the global value referenced
787 // by the operation and store it in the MLIR-to-LLVM value mapping.
788 if (auto dsoLocalEquivalentOp =
789 dyn_cast<LLVM::DSOLocalEquivalentOp>(opInst)) {
790 LLVM::LLVMFuncOp function =
791 dsoLocalEquivalentOp.getFunction(moduleTranslation.symbolTable());
792 LLVM::AliasOp alias =
793 dsoLocalEquivalentOp.getAlias(moduleTranslation.symbolTable());
794
795 // The verifier should not have allowed this.
796 assert((function || alias) &&
797 "referencing an undefined function, or alias");
798
799 llvm::Value *llvmValue = nullptr;
800 if (alias)
801 llvmValue = moduleTranslation.lookupAlias(alias);
802 else
803 llvmValue = moduleTranslation.lookupFunction(function.getName());
804
805 moduleTranslation.mapValue(
806 dsoLocalEquivalentOp.getResult(),
807 llvm::DSOLocalEquivalent::get(cast<llvm::GlobalValue>(llvmValue)));
808 return success();
809 }
810
811 // Emit blockaddress. We first need to find the LLVM block referenced by this
812 // operation and then create a LLVM block address for it.
813 if (auto blockAddressOp = dyn_cast<LLVM::BlockAddressOp>(opInst)) {
814 BlockAddressAttr blockAddressAttr = blockAddressOp.getBlockAddr();
815 llvm::BasicBlock *llvmBlock =
816 moduleTranslation.lookupBlockAddress(blockAddressAttr);
817
818 llvm::Value *llvmValue = nullptr;
819 StringRef fnName = blockAddressAttr.getFunction().getValue();
820 if (llvmBlock) {
821 llvm::Function *llvmFn = moduleTranslation.lookupFunction(fnName);
822 llvmValue = llvm::BlockAddress::get(llvmFn, llvmBlock);
823 } else {
824 // The matching LLVM block is not yet emitted, a placeholder is created
825 // in its place. When the LLVM block is emitted later in translation,
826 // the llvmValue is replaced with the actual llvm::BlockAddress.
827 // A GlobalVariable is chosen as placeholder because in general LLVM
828 // constants are uniqued and are not proper for RAUW, since that could
829 // harm unrelated uses of the constant.
830 llvmValue = new llvm::GlobalVariable(
831 *moduleTranslation.getLLVMModule(),
832 llvm::PointerType::getUnqual(moduleTranslation.getLLVMContext()),
833 /*isConstant=*/true, llvm::GlobalValue::LinkageTypes::ExternalLinkage,
834 /*Initializer=*/nullptr,
835 Twine("__mlir_block_address_")
836 .concat(Twine(fnName))
837 .concat(Twine((uint64_t)blockAddressOp.getOperation())));
838 moduleTranslation.mapUnresolvedBlockAddress(blockAddressOp, llvmValue);
839 }
840
841 moduleTranslation.mapValue(blockAddressOp.getResult(), llvmValue);
842 return success();
843 }
844
845 // Emit block label. If this label is seen before BlockAddressOp is
846 // translated, go ahead and already map it.
847 if (auto blockTagOp = dyn_cast<LLVM::BlockTagOp>(opInst)) {
848 auto funcOp = blockTagOp->getParentOfType<LLVMFuncOp>();
849 BlockAddressAttr blockAddressAttr = BlockAddressAttr::get(
850 &moduleTranslation.getContext(),
851 FlatSymbolRefAttr::get(&moduleTranslation.getContext(),
852 funcOp.getName()),
853 blockTagOp.getTag());
854 moduleTranslation.mapBlockAddress(blockAddressAttr,
855 builder.GetInsertBlock());
856 return success();
857 }
858
859 return failure();
860}
861
862static LogicalResult
864 NamedAttribute attribute,
865 LLVM::ModuleTranslation &moduleTranslation) {
866 StringRef name = attribute.getName();
867 if (name == LLVMDialect::getMmraAttrName()) {
869 if (auto oneTag = dyn_cast<LLVM::MMRATagAttr>(attribute.getValue())) {
870 tags.emplace_back(oneTag.getPrefix(), oneTag.getSuffix());
871 } else if (auto manyTags = dyn_cast<ArrayAttr>(attribute.getValue())) {
872 for (Attribute attr : manyTags) {
873 auto tag = dyn_cast<MMRATagAttr>(attr);
874 if (!tag)
875 return op.emitOpError(
876 "MMRA annotations array contains value that isn't an MMRA tag");
877 tags.emplace_back(tag.getPrefix(), tag.getSuffix());
878 }
879 } else {
880 return op.emitOpError(
881 "llvm.mmra is something other than an MMRA tag or an array of them");
882 }
883 llvm::MDTuple *mmraMd =
884 llvm::MMRAMetadata::getMD(moduleTranslation.getLLVMContext(), tags);
885 if (!mmraMd) {
886 // Empty list, canonicalizes to nothing
887 return success();
888 }
889 for (llvm::Instruction *inst : instructions)
890 inst->setMetadata(llvm::LLVMContext::MD_mmra, mmraMd);
891 return success();
892 }
893 return success();
894}
895
896namespace {
897/// Implementation of the dialect interface that converts operations belonging
898/// to the LLVM dialect to LLVM IR.
899class LLVMDialectLLVMIRTranslationInterface
900 : public LLVMTranslationDialectInterface {
901public:
902 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
903
904 /// Translates the given operation to LLVM IR using the provided IR builder
905 /// and saving the state in `moduleTranslation`.
906 LogicalResult
907 convertOperation(Operation *op, llvm::IRBuilderBase &builder,
908 LLVM::ModuleTranslation &moduleTranslation) const final {
909 return convertOperationImpl(*op, builder, moduleTranslation);
910 }
911
912 /// Handle some metadata that is represented as a discardable attribute.
913 LogicalResult
914 amendOperation(Operation *op, ArrayRef<llvm::Instruction *> instructions,
915 NamedAttribute attribute,
916 LLVM::ModuleTranslation &moduleTranslation) const final {
917 return amendOperationImpl(*op, instructions, attribute, moduleTranslation);
918 }
919};
920} // namespace
921
923 registry.insert<LLVM::LLVMDialect>();
924 registry.addExtension(+[](MLIRContext *ctx, LLVM::LLVMDialect *dialect) {
925 dialect->addInterfaces<LLVMDialectLLVMIRTranslationInterface>();
926 });
927}
928
930 DialectRegistry registry;
932 context.appendDialectRegistry(registry);
933}
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
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;.