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/Analysis/ConstantFolding.h"
23#include "llvm/IR/ConstantRange.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DIBuilder.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/InlineAsm.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/MDBuilder.h"
30#include "llvm/IR/MatrixBuilder.h"
31#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
32#include "llvm/Support/LogicalResult.h"
33
34using namespace mlir;
35using namespace mlir::LLVM;
37
38#include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
39
40static llvm::FastMathFlags getFastmathFlags(FastmathFlagsInterface &op) {
41 using llvmFMF = llvm::FastMathFlags;
42 using FuncT = void (llvmFMF::*)(bool);
43 const std::pair<FastmathFlags, FuncT> handlers[] = {
44 // clang-format off
45 {FastmathFlags::nnan, &llvmFMF::setNoNaNs},
46 {FastmathFlags::ninf, &llvmFMF::setNoInfs},
47 {FastmathFlags::nsz, &llvmFMF::setNoSignedZeros},
48 {FastmathFlags::arcp, &llvmFMF::setAllowReciprocal},
49 {FastmathFlags::contract, &llvmFMF::setAllowContract},
50 {FastmathFlags::afn, &llvmFMF::setApproxFunc},
51 {FastmathFlags::reassoc, &llvmFMF::setAllowReassoc},
52 // clang-format on
53 };
54 llvm::FastMathFlags ret;
55 ::mlir::LLVM::FastmathFlags fmfMlir = op.getFastmathAttr().getValue();
56 for (auto it : handlers)
57 if (bitEnumContainsAll(fmfMlir, it.first))
58 (ret.*(it.second))(true);
59 return ret;
60}
61
62/// Convert the value of a DenseI64ArrayAttr to a vector of unsigned indices.
64 SmallVector<unsigned> position;
65 llvm::append_range(position, indices);
66 return position;
67}
68
69/// Convert an LLVM type to a string for printing in diagnostics.
70static std::string diagStr(const llvm::Type *type) {
71 std::string str;
72 llvm::raw_string_ostream os(str);
73 type->print(os);
74 return str;
75}
76
77/// Get the declaration of an overloaded llvm intrinsic. First we get the
78/// overloaded argument types and/or result type from the CallIntrinsicOp, and
79/// then use those to get the correct declaration of the overloaded intrinsic.
80static FailureOr<llvm::Function *>
81getOverloadedDeclaration(CallIntrinsicOp op, llvm::Intrinsic::ID id,
82 llvm::Module *module,
83 LLVM::ModuleTranslation &moduleTranslation) {
85 for (Type type : op.getArgs().getTypes())
86 allArgTys.push_back(moduleTranslation.convertType(type));
87
88 llvm::Type *resTy;
89 if (op.getNumResults() == 0)
90 resTy = llvm::Type::getVoidTy(module->getContext());
91 else
92 resTy = moduleTranslation.convertType(op.getResult(0).getType());
93
94 // ATM we do not support variadic intrinsics.
95 llvm::FunctionType *ft = llvm::FunctionType::get(resTy, allArgTys, false);
96
97 std::string errorMsg;
98 llvm::raw_string_ostream errorOS(errorMsg);
99 SmallVector<llvm::Type *, 8> overloadedTys;
100 if (!llvm::Intrinsic::isSignatureValid(id, ft, overloadedTys, errorOS)) {
101 return mlir::emitError(op.getLoc(), "call intrinsic signature ")
102 << diagStr(ft) << " to overloaded intrinsic " << op.getIntrinAttr()
103 << " does not match any of the overloads: " << errorMsg;
104 }
105
106 return llvm::Intrinsic::getOrInsertDeclaration(module, id, overloadedTys);
107}
108
109static llvm::OperandBundleDef
110convertOperandBundle(OperandRange bundleOperands, StringRef bundleTag,
111 LLVM::ModuleTranslation &moduleTranslation) {
112 std::vector<llvm::Value *> operands;
113 operands.reserve(bundleOperands.size());
114 for (Value bundleArg : bundleOperands)
115 operands.push_back(moduleTranslation.lookupValue(bundleArg));
116 return llvm::OperandBundleDef(bundleTag.str(), std::move(operands));
117}
118
121 LLVM::ModuleTranslation &moduleTranslation) {
123 bundles.reserve(bundleOperands.size());
124
125 for (auto [operands, tagAttr] : llvm::zip_equal(bundleOperands, bundleTags)) {
126 StringRef tag = cast<StringAttr>(tagAttr).getValue();
127 bundles.push_back(convertOperandBundle(operands, tag, moduleTranslation));
128 }
129 return bundles;
130}
131
134 std::optional<ArrayAttr> bundleTags,
135 LLVM::ModuleTranslation &moduleTranslation) {
136 if (!bundleTags)
137 return {};
138 return convertOperandBundles(bundleOperands, *bundleTags, moduleTranslation);
139}
140
141/// Builder for LLVM_CallIntrinsicOp
142static LogicalResult
143convertCallLLVMIntrinsicOp(CallIntrinsicOp op, llvm::IRBuilderBase &builder,
144 LLVM::ModuleTranslation &moduleTranslation) {
145 llvm::Module *module = builder.getModule();
146 llvm::Intrinsic::ID id =
147 llvm::Intrinsic::lookupIntrinsicID(op.getIntrinAttr());
148 if (!id)
149 return mlir::emitError(op.getLoc(), "could not find LLVM intrinsic: ")
150 << op.getIntrinAttr();
151
152 llvm::Function *fn = nullptr;
153 if (llvm::Intrinsic::isOverloaded(id)) {
154 auto fnOrFailure =
155 getOverloadedDeclaration(op, id, module, moduleTranslation);
156 if (failed(fnOrFailure))
157 return failure();
158 fn = *fnOrFailure;
159 } else {
160 fn = llvm::Intrinsic::getOrInsertDeclaration(module, id, {});
161 }
162
163 // Check the result type of the call.
164 const llvm::Type *intrinType =
165 op.getNumResults() == 0
166 ? llvm::Type::getVoidTy(module->getContext())
167 : moduleTranslation.convertType(op.getResultTypes().front());
168 if (intrinType != fn->getReturnType()) {
169 return mlir::emitError(op.getLoc(), "intrinsic call returns ")
170 << diagStr(intrinType) << " but " << op.getIntrinAttr()
171 << " actually returns " << diagStr(fn->getReturnType());
172 }
173
174 // Check the argument types of the call. If the function is variadic, check
175 // the subrange of required arguments.
176 if (!fn->getFunctionType()->isVarArg() &&
177 op.getArgs().size() != fn->arg_size()) {
178 return mlir::emitError(op.getLoc(), "intrinsic call has ")
179 << op.getArgs().size() << " operands but " << op.getIntrinAttr()
180 << " expects " << fn->arg_size();
181 }
182 if (fn->getFunctionType()->isVarArg() &&
183 op.getArgs().size() < fn->arg_size()) {
184 return mlir::emitError(op.getLoc(), "intrinsic call has ")
185 << op.getArgs().size() << " operands but variadic "
186 << op.getIntrinAttr() << " expects at least " << fn->arg_size();
187 }
188 // Check the arguments up to the number the function requires.
189 for (unsigned i = 0, e = fn->arg_size(); i != e; ++i) {
190 const llvm::Type *expected = fn->getArg(i)->getType();
191 const llvm::Type *actual =
192 moduleTranslation.convertType(op.getOperandTypes()[i]);
193 if (actual != expected) {
194 return mlir::emitError(op.getLoc(), "intrinsic call operand #")
195 << i << " has type " << diagStr(actual) << " but "
196 << op.getIntrinAttr() << " expects " << diagStr(expected);
197 }
198 }
199
200 FastmathFlagsInterface itf = op;
201 builder.setFastMathFlags(getFastmathFlags(itf));
202
203 auto *inst = builder.CreateCall(
204 fn, moduleTranslation.lookupValues(op.getArgs()),
205 convertOperandBundles(op.getOpBundleOperands(), op.getOpBundleTags(),
206 moduleTranslation));
207 if (op.getStrictfp())
208 inst->addFnAttr(llvm::Attribute::StrictFP);
209
210 if (failed(moduleTranslation.convertArgAndResultAttrs(op, inst)))
211 return failure();
212
213 if (op.getNumResults() == 1)
214 moduleTranslation.mapValue(op->getResults().front()) = inst;
215 return success();
216}
217
218static LogicalResult
219convertNamedMetadataOp(NamedMetadataOp op,
220 LLVM::ModuleTranslation &moduleTranslation) {
221 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
222 llvm::NamedMDNode *namedMD =
223 llvmModule->getOrInsertNamedMetadata(op.getMetadataName());
224 for (Attribute nodeAttr : op.getNodes()) {
225 FailureOr<llvm::Metadata *> md =
226 moduleTranslation.convertMetadataAttr(nodeAttr, [&]() {
227 return op.emitError() << "failed to convert named metadata '"
228 << op.getMetadataName() << "': ";
229 });
230 if (failed(md))
231 return failure();
232 auto *mdNode = llvm::dyn_cast_if_present<llvm::MDNode>(*md);
233 if (!mdNode) {
234 return op.emitError() << "failed to convert named metadata '"
235 << op.getMetadataName() << "'";
236 }
237 namedMD->addOperand(mdNode);
238 }
239 return success();
240}
241
242/// Translate `llvm.getelementptr`. `inrange` is only representable on LLVM
243/// constant GEP expressions.
244static LogicalResult convertGEPOp(GEPOp op, llvm::IRBuilderBase &builder,
245 LLVM::ModuleTranslation &moduleTranslation) {
247 indices.reserve(op.getRawConstantIndices().size());
248 for (PointerUnion<IntegerAttr, Value> valueOrAttr : op.getIndices()) {
249 if (Value value = dyn_cast_if_present<Value>(valueOrAttr))
250 indices.push_back(moduleTranslation.lookupValue(value));
251 else
252 indices.push_back(
253 builder.getInt32(cast<IntegerAttr>(valueOrAttr).getInt()));
254 }
255
256 llvm::Type *elementType = moduleTranslation.convertType(op.getElemType());
257 llvm::GEPNoWrapFlags nwFlags =
258 llvm::GEPNoWrapFlags::fromRaw(static_cast<unsigned>(op.getNoWrapFlags()));
259 ConstantRangeAttr inrangeAttr = op.getInrangeAttr();
260 llvm::Value *base = moduleTranslation.lookupValue(op.getBase());
261 llvm::Value *res;
262 if (inrangeAttr || !builder.GetInsertPoint().isValid()) {
263 StringRef WhyConstExpr =
264 inrangeAttr ? "'inrange' GEP" : "global initializer GEP";
265 auto *baseConst = dyn_cast<llvm::Constant>(base);
266 if (!baseConst || !llvm::all_of(indices, [](llvm::Value *value) {
267 return isa<llvm::Constant>(value);
268 }))
269 return op.emitError(WhyConstExpr + " requires the base and indices to "
270 "translate to LLVM constants");
271
272 std::optional<llvm::ConstantRange> inrangeCR;
273 if (inrangeAttr)
274 inrangeCR = llvm::ConstantRange::getNonEmpty(inrangeAttr.getLower(),
275 inrangeAttr.getUpper());
276
278 constIndices.reserve(indices.size());
279 for (llvm::Value *value : indices)
280 constIndices.push_back(cast<llvm::Constant>(value));
281 const llvm::DataLayout &dataLayout =
282 moduleTranslation.getLLVMModule()->getDataLayout();
283 res = llvm::ConstantExpr::getGetElementPtr(
284 dataLayout, elementType, baseConst, constIndices, nwFlags, inrangeCR);
285 if (!res)
286 return op.emitError("failed to lower " + WhyConstExpr +
287 " to a constant byte offset");
288 // Fold the constant as CreateGEP did through the TargetFolder. This also
289 // infers inbounds and nuw when the offset stays within the global.
290 res = llvm::ConstantFoldConstant(cast<llvm::Constant>(res), dataLayout);
291 } else {
292 res = builder.CreateGEP(elementType, base, indices, "", nwFlags);
293 }
294 moduleTranslation.mapValue(op.getRes()) = res;
295 return success();
296}
297
299 llvm::IRBuilderBase &builder,
300 LLVM::ModuleTranslation &moduleTranslation) {
301 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
302 llvm::LLVMContext &context = llvmModule->getContext();
303 llvm::NamedMDNode *linkerMDNode =
304 llvmModule->getOrInsertNamedMetadata("llvm.linker.options");
306 mdNodes.reserve(options.size());
307 for (auto s : options.getAsRange<StringAttr>()) {
308 auto *mdNode = llvm::MDString::get(context, s.getValue());
309 mdNodes.push_back(mdNode);
310 }
311
312 auto *listMDNode = llvm::MDTuple::get(context, mdNodes);
313 linkerMDNode->addOperand(listMDNode);
314}
315
316static llvm::Metadata *
317convertModuleFlagValue(StringRef key, ArrayAttr arrayAttr,
318 llvm::IRBuilderBase &builder,
319 LLVM::ModuleTranslation &moduleTranslation) {
320 llvm::LLVMContext &context = builder.getContext();
321 llvm::MDBuilder mdb(context);
323
324 if (key == LLVMDialect::getModuleFlagKeyCGProfileName()) {
325 for (auto entry : arrayAttr.getAsRange<ModuleFlagCGProfileEntryAttr>()) {
326 auto getFuncMetadata = [&](FlatSymbolRefAttr sym) -> llvm::Metadata * {
327 if (!sym)
328 return nullptr;
329 if (llvm::Function *fn =
330 moduleTranslation.lookupFunction(sym.getValue()))
331 return llvm::ValueAsMetadata::get(fn);
332 return nullptr;
333 };
334 llvm::Metadata *fromMetadata = getFuncMetadata(entry.getFrom());
335 llvm::Metadata *toMetadata = getFuncMetadata(entry.getTo());
336
337 llvm::Metadata *vals[] = {
338 fromMetadata, toMetadata,
339 mdb.createConstant(llvm::ConstantInt::get(
340 llvm::Type::getInt64Ty(context), entry.getCount()))};
341 nodes.push_back(llvm::MDNode::get(context, vals));
342 }
343 return llvm::MDTuple::getDistinct(context, nodes);
344 }
345 // Handle ArrayAttr of StringAttrs (e.g. "riscv-isa") by converting back to
346 // an MDTuple of MDStrings for a lossless round-trip.
347 if (llvm::all_of(arrayAttr, [](Attribute a) { return isa<StringAttr>(a); })) {
348 assert(!arrayAttr.empty() &&
349 "empty string-array is invalid per ModuleFlagAttr::verify");
350 for (StringAttr strAttr : arrayAttr.getAsRange<StringAttr>())
351 nodes.push_back(llvm::MDString::get(context, strAttr.getValue()));
352 return llvm::MDTuple::get(context, nodes);
353 }
354 return nullptr;
355}
356
358 StringRef key, ModuleFlagProfileSummaryAttr summaryAttr,
359 llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation) {
360 llvm::LLVMContext &context = builder.getContext();
361 llvm::MDBuilder mdb(context);
362
363 auto getIntTuple = [&](StringRef key, uint64_t val) -> llvm::MDTuple * {
365 mdb.createString(key), mdb.createConstant(llvm::ConstantInt::get(
366 llvm::Type::getInt64Ty(context), val))};
367 return llvm::MDTuple::get(context, tupleNodes);
368 };
369
371 mdb.createString("ProfileFormat"),
372 mdb.createString(
373 stringifyProfileSummaryFormatKind(summaryAttr.getFormat()))};
374
376 llvm::MDTuple::get(context, fmtNode),
377 getIntTuple("TotalCount", summaryAttr.getTotalCount()),
378 getIntTuple("MaxCount", summaryAttr.getMaxCount()),
379 getIntTuple("MaxInternalCount", summaryAttr.getMaxInternalCount()),
380 getIntTuple("MaxFunctionCount", summaryAttr.getMaxFunctionCount()),
381 getIntTuple("NumCounts", summaryAttr.getNumCounts()),
382 getIntTuple("NumFunctions", summaryAttr.getNumFunctions()),
383 };
384
385 if (summaryAttr.getIsPartialProfile())
386 vals.push_back(
387 getIntTuple("IsPartialProfile", *summaryAttr.getIsPartialProfile()));
388
389 if (summaryAttr.getPartialProfileRatio()) {
391 mdb.createString("PartialProfileRatio"),
392 mdb.createConstant(llvm::ConstantFP::get(
393 llvm::Type::getDoubleTy(context),
394 summaryAttr.getPartialProfileRatio().getValue()))};
395 vals.push_back(llvm::MDTuple::get(context, tupleNodes));
396 }
397
398 SmallVector<llvm::Metadata *> detailedEntries;
399 llvm::Type *llvmInt64Type = llvm::Type::getInt64Ty(context);
400 for (ModuleFlagProfileSummaryDetailedAttr detailedEntry :
401 summaryAttr.getDetailedSummary()) {
403 mdb.createConstant(
404 llvm::ConstantInt::get(llvmInt64Type, detailedEntry.getCutOff())),
405 mdb.createConstant(
406 llvm::ConstantInt::get(llvmInt64Type, detailedEntry.getMinCount())),
407 mdb.createConstant(llvm::ConstantInt::get(
408 llvmInt64Type, detailedEntry.getNumCounts()))};
409 detailedEntries.push_back(llvm::MDTuple::get(context, tupleNodes));
410 }
411 SmallVector<llvm::Metadata *> detailedSummary{
412 mdb.createString("DetailedSummary"),
413 llvm::MDTuple::get(context, detailedEntries)};
414 vals.push_back(llvm::MDTuple::get(context, detailedSummary));
415
416 return llvm::MDNode::get(context, vals);
417}
418
419static void convertModuleFlagsOp(ArrayAttr flags, llvm::IRBuilderBase &builder,
420 LLVM::ModuleTranslation &moduleTranslation) {
421 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
422 auto convertIntegerAttr = [&](IntegerAttr intAttr) -> llvm::Metadata * {
423 return llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
424 llvm::Type::getInt32Ty(builder.getContext()), intAttr.getInt()));
425 };
426 for (auto flagAttr : flags.getAsRange<ModuleFlagAttrInterface>()) {
427 llvm::Metadata *valueMetadata =
429 flagAttr.getModuleFlagValue())
430 .Case([&](StringAttr strAttr) {
431 return llvm::MDString::get(builder.getContext(),
432 strAttr.getValue());
433 })
434 .Case([&](IntegerAttr intAttr) {
435 return convertIntegerAttr(intAttr);
436 })
437 .Case([&](IntrinsicIntegerAttrInterface intAttr) {
438 return convertIntegerAttr(intAttr.getIntegerAttr());
439 })
440 .Case([&](ArrayAttr arrayAttr) {
442 flagAttr.getModuleFlagKey().getValue(), arrayAttr, builder,
443 moduleTranslation);
444 })
445 .Case([&](ModuleFlagProfileSummaryAttr summaryAttr) {
447 flagAttr.getModuleFlagKey().getValue(), summaryAttr, builder,
448 moduleTranslation);
449 })
450 .Default([](auto) { return nullptr; });
451
452 assert(valueMetadata && "expected valid metadata");
453 llvmModule->addModuleFlag(
454 convertModFlagBehaviorToLLVM(flagAttr.getModuleFlagBehavior()),
455 flagAttr.getModuleFlagKey().getValue(), valueMetadata);
456 }
457}
458
459/// Looks up the GlobalValue and FunctionType for a callee symbol that is not a
460/// regular LLVM function (i.e. an alias or ifunc). Returns the lowered
461/// GlobalValue and FunctionType derived from \p calleeFuncType.
462static std::pair<llvm::GlobalValue *, llvm::FunctionType *>
464 Operation &opInst,
465 LLVM::ModuleTranslation &moduleTranslation) {
466 Operation *moduleOp = parentLLVMModule(&opInst);
467 Operation *calleeOp =
468 moduleTranslation.symbolTable().lookupSymbolIn(moduleOp, attr);
469 llvm::FunctionType *calleeType = llvm::cast<llvm::FunctionType>(
470 moduleTranslation.convertType(calleeFuncType));
471 llvm::GlobalValue *calleeGV;
472 if (isa<LLVM::AliasOp>(calleeOp))
473 calleeGV = moduleTranslation.lookupAlias(calleeOp);
474 else
475 calleeGV = moduleTranslation.lookupIFunc(calleeOp);
476 return {calleeGV, calleeType};
477}
478
479static llvm::DILocalScope *
480getLocalScopeFromLoc(llvm::IRBuilderBase &builder, Location loc,
481 LLVM::ModuleTranslation &moduleTranslation) {
482 if (auto scopeLoc =
484 if (auto *localScope = llvm::dyn_cast<llvm::DILocalScope>(
485 moduleTranslation.translateDebugInfo(scopeLoc.getMetadata())))
486 return localScope;
487 return builder.GetInsertBlock()->getParent()->getSubprogram();
488}
489
490static LogicalResult
491convertOperationImpl(Operation &opInst, llvm::IRBuilderBase &builder,
492 LLVM::ModuleTranslation &moduleTranslation) {
493
494 llvm::IRBuilder<>::FastMathFlagGuard fmfGuard(builder);
495 if (auto fmf = dyn_cast<FastmathFlagsInterface>(opInst))
496 builder.setFastMathFlags(getFastmathFlags(fmf));
497
498#include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
499#include "mlir/Dialect/LLVMIR/LLVMIntrinsicConversions.inc"
500
501 // Emit function calls. If the "callee" attribute is present, this is a
502 // direct function call and we also need to look up the remapped function
503 // itself. Otherwise, this is an indirect call and the callee is the first
504 // operand, look it up as a normal value.
505 if (auto callOp = dyn_cast<LLVM::CallOp>(opInst)) {
506 auto operands = moduleTranslation.lookupValues(callOp.getCalleeOperands());
508 convertOperandBundles(callOp.getOpBundleOperands(),
509 callOp.getOpBundleTags(), moduleTranslation);
510 ArrayRef<llvm::Value *> operandsRef(operands);
511 llvm::CallInst *call;
512 if (auto attr = callOp.getCalleeAttr()) {
513 if (llvm::Function *function =
514 moduleTranslation.lookupFunction(attr.getValue())) {
515 call = builder.CreateCall(function, operandsRef, opBundles);
516 } else {
517 auto [calleeGV, calleeType] = lookupNonFunctionSymbolCallee(
518 attr, callOp.getCalleeFunctionType(), opInst, moduleTranslation);
519 call = builder.CreateCall(calleeType, calleeGV, operandsRef, opBundles);
520 }
521 } else {
522 llvm::FunctionType *calleeType = llvm::cast<llvm::FunctionType>(
523 moduleTranslation.convertType(callOp.getCalleeFunctionType()));
524 call = builder.CreateCall(calleeType, operandsRef.front(),
525 operandsRef.drop_front(), opBundles);
526 }
527 call->setCallingConv(convertCConvToLLVM(callOp.getCConv()));
528 call->setTailCallKind(convertTailCallKindToLLVM(callOp.getTailCallKind()));
529 if (callOp.getConvergentAttr())
530 call->addFnAttr(llvm::Attribute::Convergent);
531 if (callOp.getNoUnwindAttr())
532 call->addFnAttr(llvm::Attribute::NoUnwind);
533 if (callOp.getWillReturnAttr())
534 call->addFnAttr(llvm::Attribute::WillReturn);
535 if (callOp.getNoreturnAttr())
536 call->addFnAttr(llvm::Attribute::NoReturn);
537 if (callOp.getOptsizeAttr())
538 call->addFnAttr(llvm::Attribute::OptimizeForSize);
539 if (callOp.getMinsizeAttr())
540 call->addFnAttr(llvm::Attribute::MinSize);
541 if (callOp.getSaveRegParamsAttr())
542 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
543 "save-reg-params"));
544 if (callOp.getBuiltinAttr())
545 call->addFnAttr(llvm::Attribute::Builtin);
546 if (callOp.getNobuiltinAttr())
547 call->addFnAttr(llvm::Attribute::NoBuiltin);
548 if (callOp.getStrictfp())
549 call->addFnAttr(llvm::Attribute::StrictFP);
550 if (callOp.getReturnsTwiceAttr())
551 call->addFnAttr(llvm::Attribute::ReturnsTwice);
552 if (callOp.getColdAttr())
553 call->addFnAttr(llvm::Attribute::Cold);
554 if (callOp.getHotAttr())
555 call->addFnAttr(llvm::Attribute::Hot);
556 if (callOp.getNoduplicateAttr())
557 call->addFnAttr(llvm::Attribute::NoDuplicate);
558 if (callOp.getNoInlineAttr())
559 call->addFnAttr(llvm::Attribute::NoInline);
560 if (callOp.getAlwaysInlineAttr())
561 call->addFnAttr(llvm::Attribute::AlwaysInline);
562 if (callOp.getInlineHintAttr())
563 call->addFnAttr(llvm::Attribute::InlineHint);
564 if (callOp.getNoCallerSavedRegistersAttr())
565 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
566 "no_caller_saved_registers"));
567 if (callOp.getNocallbackAttr())
568 call->addFnAttr(llvm::Attribute::NoCallback);
569 if (StringAttr modFormat = callOp.getModularFormatAttr())
570 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
571 "modular-format",
572 modFormat.getValue()));
573 if (StringAttr zcsr = callOp.getZeroCallUsedRegsAttr())
574 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
575 "zero-call-used-regs",
576 zcsr.getValue()));
577 if (callOp.getUniformWorkGroupSizeAttr())
578 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
579 "uniform-work-group-size"));
580 if (StringAttr trapFunc = callOp.getTrapFuncNameAttr())
581 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
582 "trap-func-name",
583 trapFunc.getValue()));
584
585 if (ArrayAttr noBuiltins = callOp.getNobuiltinsAttr()) {
586 if (noBuiltins.empty())
587 call->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
588 "no-builtins"));
589
590 moduleTranslation.convertFunctionAttrCollection(
591 noBuiltins, call, ModuleTranslation::convertNoBuiltin);
592 }
593
594 moduleTranslation.convertFunctionAttrCollection(
595 callOp.getDefaultFuncAttrsAttr(), call,
597
598 if (llvm::Attribute attr =
599 moduleTranslation.convertAllocsizeAttr(callOp.getAllocsizeAttr());
600 attr.isValid())
601 call->addFnAttr(attr);
602
603 if (failed(moduleTranslation.convertArgAndResultAttrs(callOp, call)))
604 return failure();
605
606 if (MemoryEffectsAttr memAttr = callOp.getMemoryEffectsAttr()) {
607 llvm::MemoryEffects memEffects =
608 llvm::MemoryEffects(llvm::MemoryEffects::Location::ArgMem,
609 convertModRefInfoToLLVM(memAttr.getArgMem())) |
610 llvm::MemoryEffects(
611 llvm::MemoryEffects::Location::InaccessibleMem,
612 convertModRefInfoToLLVM(memAttr.getInaccessibleMem())) |
613 llvm::MemoryEffects(llvm::MemoryEffects::Location::Other,
614 convertModRefInfoToLLVM(memAttr.getOther())) |
615 llvm::MemoryEffects(llvm::MemoryEffects::Location::ErrnoMem,
616 convertModRefInfoToLLVM(memAttr.getErrnoMem())) |
617 llvm::MemoryEffects(
618 llvm::MemoryEffects::Location::TargetMem0,
619 convertModRefInfoToLLVM(memAttr.getTargetMem0())) |
620 llvm::MemoryEffects(llvm::MemoryEffects::Location::TargetMem1,
621 convertModRefInfoToLLVM(memAttr.getTargetMem1()));
622 call->setMemoryEffects(memEffects);
623 }
624
625 moduleTranslation.setAccessGroupsMetadata(callOp, call);
626 moduleTranslation.setAliasScopeMetadata(callOp, call);
627 moduleTranslation.setTBAAMetadata(callOp, call);
628 // If the called function has a result, remap the corresponding value. Note
629 // that LLVM IR dialect CallOp has either 0 or 1 result.
630 if (opInst.getNumResults() != 0)
631 moduleTranslation.mapValue(opInst.getResult(0), call);
632 // Check that LLVM call returns void for 0-result functions.
633 else if (!call->getType()->isVoidTy())
634 return failure();
635 moduleTranslation.mapCall(callOp, call);
636 return success();
637 }
638
639 if (auto inlineAsmOp = dyn_cast<LLVM::InlineAsmOp>(opInst)) {
640 // TODO: refactor function type creation which usually occurs in std-LLVM
641 // conversion.
642 SmallVector<Type, 8> operandTypes;
643 llvm::append_range(operandTypes, inlineAsmOp.getOperands().getTypes());
644
645 Type resultType;
646 if (inlineAsmOp.getNumResults() == 0) {
647 resultType = LLVM::LLVMVoidType::get(&moduleTranslation.getContext());
648 } else {
649 assert(inlineAsmOp.getNumResults() == 1);
650 resultType = inlineAsmOp.getResultTypes()[0];
651 }
652 auto ft = LLVM::LLVMFunctionType::get(resultType, operandTypes);
653 llvm::InlineAsm *inlineAsmInst =
654 inlineAsmOp.getAsmDialect()
655 ? llvm::InlineAsm::get(
656 static_cast<llvm::FunctionType *>(
657 moduleTranslation.convertType(ft)),
658 inlineAsmOp.getAsmString(), inlineAsmOp.getConstraints(),
659 inlineAsmOp.getHasSideEffects(),
660 inlineAsmOp.getIsAlignStack(),
661 convertAsmDialectToLLVM(*inlineAsmOp.getAsmDialect()))
662 : llvm::InlineAsm::get(static_cast<llvm::FunctionType *>(
663 moduleTranslation.convertType(ft)),
664 inlineAsmOp.getAsmString(),
665 inlineAsmOp.getConstraints(),
666 inlineAsmOp.getHasSideEffects(),
667 inlineAsmOp.getIsAlignStack());
668 llvm::CallInst *inst = builder.CreateCall(
669 inlineAsmInst,
670 moduleTranslation.lookupValues(inlineAsmOp.getOperands()));
671 inst->setTailCallKind(convertTailCallKindToLLVM(
672 inlineAsmOp.getTailCallKindAttr().getTailCallKind()));
673 if (inlineAsmOp.getConvergent())
674 inst->addFnAttr(llvm::Attribute::Convergent);
675 if (inlineAsmOp.getStrictfp())
676 inst->addFnAttr(llvm::Attribute::StrictFP);
677 if (auto maybeOperandAttrs = inlineAsmOp.getOperandAttrs()) {
678 llvm::AttributeList attrList = inst->getAttributes();
679 for (const auto &it : llvm::enumerate(*maybeOperandAttrs)) {
680 Attribute attr = it.value();
681 if (!attr)
682 continue;
683 DictionaryAttr dAttr = cast<DictionaryAttr>(attr);
684 if (dAttr.empty())
685 continue;
686 TypeAttr tAttr =
687 cast<TypeAttr>(dAttr.get(InlineAsmOp::getElementTypeAttrName()));
688 llvm::AttrBuilder b(moduleTranslation.getLLVMContext());
689 llvm::Type *ty = moduleTranslation.convertType(tAttr.getValue());
690 b.addTypeAttr(llvm::Attribute::ElementType, ty);
691 // shift to account for the returned value (this is always 1 aggregate
692 // value in LLVM).
693 int shift = (opInst.getNumResults() > 0) ? 1 : 0;
694 attrList = attrList.addAttributesAtIndex(
695 moduleTranslation.getLLVMContext(), it.index() + shift, b);
696 }
697 inst->setAttributes(attrList);
698 }
699
700 if (opInst.getNumResults() != 0)
701 moduleTranslation.mapValue(opInst.getResult(0), inst);
702 return success();
703 }
704
705 if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
706 auto operands = moduleTranslation.lookupValues(invOp.getCalleeOperands());
708 convertOperandBundles(invOp.getOpBundleOperands(),
709 invOp.getOpBundleTags(), moduleTranslation);
710 ArrayRef<llvm::Value *> operandsRef(operands);
711 llvm::InvokeInst *result;
712 if (auto attr = invOp.getCalleeAttr()) {
713 if (llvm::Function *function =
714 moduleTranslation.lookupFunction(attr.getValue())) {
715 result = builder.CreateInvoke(
716 function, moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
717 moduleTranslation.lookupBlock(invOp.getSuccessor(1)), operandsRef,
718 opBundles);
719 } else {
720 auto [calleeGV, calleeType] = lookupNonFunctionSymbolCallee(
721 attr, invOp.getCalleeFunctionType(), opInst, moduleTranslation);
722 result = builder.CreateInvoke(
723 calleeType, calleeGV,
724 moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
725 moduleTranslation.lookupBlock(invOp.getSuccessor(1)), operandsRef,
726 opBundles);
727 }
728 } else {
729 llvm::FunctionType *calleeType = llvm::cast<llvm::FunctionType>(
730 moduleTranslation.convertType(invOp.getCalleeFunctionType()));
731 result = builder.CreateInvoke(
732 calleeType, operandsRef.front(),
733 moduleTranslation.lookupBlock(invOp.getSuccessor(0)),
734 moduleTranslation.lookupBlock(invOp.getSuccessor(1)),
735 operandsRef.drop_front(), opBundles);
736 }
737 result->setCallingConv(convertCConvToLLVM(invOp.getCConv()));
738 if (invOp.getUniformWorkGroupSizeAttr())
739 result->addFnAttr(llvm::Attribute::get(moduleTranslation.getLLVMContext(),
740 "uniform-work-group-size"));
741 if (invOp.getStrictfp())
742 result->addFnAttr(llvm::Attribute::StrictFP);
743 moduleTranslation.convertFunctionAttrCollection(
744 invOp.getDefaultFuncAttrsAttr(), result,
746 if (failed(moduleTranslation.convertArgAndResultAttrs(invOp, result)))
747 return failure();
748 moduleTranslation.mapBranch(invOp, result);
749 // InvokeOp can only have 0 or 1 result
750 if (invOp->getNumResults() != 0) {
751 moduleTranslation.mapValue(opInst.getResult(0), result);
752 return success();
753 }
754 return success(result->getType()->isVoidTy());
755 }
756
757 if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
758 llvm::Type *ty = moduleTranslation.convertType(lpOp.getType());
759 llvm::LandingPadInst *lpi =
760 builder.CreateLandingPad(ty, lpOp.getNumOperands());
761 lpi->setCleanup(lpOp.getCleanup());
762
763 // Add clauses
764 for (llvm::Value *operand :
765 moduleTranslation.lookupValues(lpOp.getOperands())) {
766 // All operands should be constant - checked by verifier
767 if (auto *constOperand = dyn_cast<llvm::Constant>(operand))
768 lpi->addClause(constOperand);
769 }
770 moduleTranslation.mapValue(lpOp.getResult(), lpi);
771 return success();
772 }
773
774 // Emit branches. We need to look up the remapped blocks and ignore the
775 // block arguments that were transformed into PHI nodes.
776 if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
777 llvm::UncondBrInst *branch =
778 builder.CreateBr(moduleTranslation.lookupBlock(brOp.getSuccessor()));
779 moduleTranslation.mapBranch(&opInst, branch);
780 moduleTranslation.setLoopMetadata(&opInst, branch);
781 return success();
782 }
783 if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
784 llvm::CondBrInst *branch = builder.CreateCondBr(
785 moduleTranslation.lookupValue(condbrOp.getOperand(0)),
786 moduleTranslation.lookupBlock(condbrOp.getSuccessor(0)),
787 moduleTranslation.lookupBlock(condbrOp.getSuccessor(1)));
788 moduleTranslation.mapBranch(&opInst, branch);
789 moduleTranslation.setLoopMetadata(&opInst, branch);
790 return success();
791 }
792 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(opInst)) {
793 llvm::SwitchInst *switchInst = builder.CreateSwitch(
794 moduleTranslation.lookupValue(switchOp.getValue()),
795 moduleTranslation.lookupBlock(switchOp.getDefaultDestination()),
796 switchOp.getCaseDestinations().size());
797
798 // Handle switch with zero cases.
799 if (!switchOp.getCaseValues())
800 return success();
801
802 auto *ty = llvm::cast<llvm::IntegerType>(
803 moduleTranslation.convertType(switchOp.getValue().getType()));
804 for (auto i :
805 llvm::zip(llvm::cast<DenseIntElementsAttr>(*switchOp.getCaseValues()),
806 switchOp.getCaseDestinations()))
807 switchInst->addCase(
808 llvm::ConstantInt::get(ty, std::get<0>(i).getLimitedValue()),
809 moduleTranslation.lookupBlock(std::get<1>(i)));
810
811 moduleTranslation.mapBranch(&opInst, switchInst);
812 return success();
813 }
814 if (auto indBrOp = dyn_cast<LLVM::IndirectBrOp>(opInst)) {
815 llvm::IndirectBrInst *indBr = builder.CreateIndirectBr(
816 moduleTranslation.lookupValue(indBrOp.getAddr()),
817 indBrOp->getNumSuccessors());
818 for (auto *succ : indBrOp.getSuccessors())
819 indBr->addDestination(moduleTranslation.lookupBlock(succ));
820 moduleTranslation.mapBranch(&opInst, indBr);
821 return success();
822 }
823
824 // Emit addressof. We need to look up the global value referenced by the
825 // operation and store it in the MLIR-to-LLVM value mapping. This does not
826 // emit any LLVM instruction.
827 if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
828 LLVM::GlobalOp global =
829 addressOfOp.getGlobal(moduleTranslation.symbolTable());
830 LLVM::LLVMFuncOp function =
831 addressOfOp.getFunction(moduleTranslation.symbolTable());
832 LLVM::AliasOp alias = addressOfOp.getAlias(moduleTranslation.symbolTable());
833 LLVM::IFuncOp ifunc = addressOfOp.getIFunc(moduleTranslation.symbolTable());
834
835 // The verifier should not have allowed this.
836 assert((global || function || alias || ifunc) &&
837 "referencing an undefined global, function, alias, or ifunc");
838
839 llvm::Value *llvmValue = nullptr;
840 if (global)
841 llvmValue = moduleTranslation.lookupGlobal(global);
842 else if (alias)
843 llvmValue = moduleTranslation.lookupAlias(alias);
844 else if (function)
845 llvmValue = moduleTranslation.lookupFunction(function.getName());
846 else
847 llvmValue = moduleTranslation.lookupIFunc(ifunc);
848
849 moduleTranslation.mapValue(addressOfOp.getResult(), llvmValue);
850 return success();
851 }
852
853 // Emit dso_local_equivalent. We need to look up the global value referenced
854 // by the operation and store it in the MLIR-to-LLVM value mapping.
855 if (auto dsoLocalEquivalentOp =
856 dyn_cast<LLVM::DSOLocalEquivalentOp>(opInst)) {
857 LLVM::LLVMFuncOp function =
858 dsoLocalEquivalentOp.getFunction(moduleTranslation.symbolTable());
859 LLVM::AliasOp alias =
860 dsoLocalEquivalentOp.getAlias(moduleTranslation.symbolTable());
861
862 // The verifier should not have allowed this.
863 assert((function || alias) &&
864 "referencing an undefined function, or alias");
865
866 llvm::Value *llvmValue = nullptr;
867 if (alias)
868 llvmValue = moduleTranslation.lookupAlias(alias);
869 else
870 llvmValue = moduleTranslation.lookupFunction(function.getName());
871
872 moduleTranslation.mapValue(
873 dsoLocalEquivalentOp.getResult(),
874 llvm::DSOLocalEquivalent::get(cast<llvm::GlobalValue>(llvmValue)));
875 return success();
876 }
877
878 // Emit blockaddress. We first need to find the LLVM block referenced by this
879 // operation and then create a LLVM block address for it.
880 if (auto blockAddressOp = dyn_cast<LLVM::BlockAddressOp>(opInst)) {
881 BlockAddressAttr blockAddressAttr = blockAddressOp.getBlockAddr();
882 llvm::BasicBlock *llvmBlock =
883 moduleTranslation.lookupBlockAddress(blockAddressAttr);
884
885 llvm::Value *llvmValue = nullptr;
886 StringRef fnName = blockAddressAttr.getFunction().getValue();
887 if (llvmBlock) {
888 llvm::Function *llvmFn = moduleTranslation.lookupFunction(fnName);
889 llvmValue = llvm::BlockAddress::get(llvmFn, llvmBlock);
890 } else {
891 // The matching LLVM block is not yet emitted, a placeholder is created
892 // in its place. When the LLVM block is emitted later in translation,
893 // the llvmValue is replaced with the actual llvm::BlockAddress.
894 // A GlobalVariable is chosen as placeholder because in general LLVM
895 // constants are uniqued and are not proper for RAUW, since that could
896 // harm unrelated uses of the constant.
897 llvmValue = new llvm::GlobalVariable(
898 *moduleTranslation.getLLVMModule(),
899 llvm::PointerType::getUnqual(moduleTranslation.getLLVMContext()),
900 /*isConstant=*/true, llvm::GlobalValue::LinkageTypes::ExternalLinkage,
901 /*Initializer=*/nullptr,
902 Twine("__mlir_block_address_")
903 .concat(Twine(fnName))
904 .concat(Twine((uint64_t)blockAddressOp.getOperation())));
905 moduleTranslation.mapUnresolvedBlockAddress(blockAddressOp, llvmValue);
906 }
907
908 moduleTranslation.mapValue(blockAddressOp.getResult(), llvmValue);
909 return success();
910 }
911
912 // Emit block label. If this label is seen before BlockAddressOp is
913 // translated, go ahead and already map it.
914 if (auto blockTagOp = dyn_cast<LLVM::BlockTagOp>(opInst)) {
915 auto funcOp = blockTagOp->getParentOfType<LLVMFuncOp>();
916 BlockAddressAttr blockAddressAttr = BlockAddressAttr::get(
917 &moduleTranslation.getContext(),
918 FlatSymbolRefAttr::get(&moduleTranslation.getContext(),
919 funcOp.getName()),
920 blockTagOp.getTag());
921 moduleTranslation.mapBlockAddress(blockAddressAttr,
922 builder.GetInsertBlock());
923 return success();
924 }
925
926 return failure();
927}
928
929/// Builds a call stack node: one constant integer per source-location hash.
930/// Shared by `!callsite` and by the first operand of every `!memprof` MIB.
931static llvm::MDNode *convertCallStack(llvm::LLVMContext &ctx,
932 ArrayRef<int64_t> ids) {
933 llvm::Type *i64 = llvm::Type::getInt64Ty(ctx);
935 operands.reserve(ids.size());
936 for (int64_t id : ids)
937 operands.push_back(llvm::ConstantAsMetadata::get(
938 llvm::ConstantInt::get(i64, static_cast<uint64_t>(id))));
939 return llvm::MDNode::get(ctx, operands);
940}
941
942/// Builds one `!memprof` MemInfoBlock: the allocation call stack, the one
943/// allocation-type tag, then the `(context id, total size)` pairs. Both the
944/// single tag and the order are what the verifier requires, not a free choice.
945static llvm::MDNode *convertMemProfMIB(llvm::LLVMContext &ctx,
946 MemProfMIBAttr mib) {
947 llvm::Type *i64 = llvm::Type::getInt64Ty(ctx);
949 operands.push_back(convertCallStack(ctx, mib.getCallStack().asArrayRef()));
950 operands.push_back(llvm::MDString::get(ctx, mib.getAllocType().getValue()));
951 for (MemProfContextSizeAttr entry : mib.getContextSizes()) {
952 llvm::Metadata *pair[] = {
953 llvm::ConstantAsMetadata::get(
954 llvm::ConstantInt::get(i64, entry.getId())),
955 llvm::ConstantAsMetadata::get(
956 llvm::ConstantInt::get(i64, entry.getSize()))};
957 operands.push_back(llvm::MDNode::get(ctx, pair));
958 }
959 return llvm::MDNode::get(ctx, operands);
960}
961
962static LogicalResult
964 NamedAttribute attribute,
965 LLVM::ModuleTranslation &moduleTranslation) {
966 StringRef name = attribute.getName();
967 if (name == LLVMDialect::getMmraAttrName()) {
969 if (auto oneTag = dyn_cast<LLVM::MMRATagAttr>(attribute.getValue())) {
970 tags.emplace_back(oneTag.getPrefix(), oneTag.getSuffix());
971 } else if (auto manyTags = dyn_cast<ArrayAttr>(attribute.getValue())) {
972 for (Attribute attr : manyTags) {
973 auto tag = dyn_cast<MMRATagAttr>(attr);
974 if (!tag)
975 return op.emitOpError(
976 "MMRA annotations array contains value that isn't an MMRA tag");
977 tags.emplace_back(tag.getPrefix(), tag.getSuffix());
978 }
979 } else {
980 return op.emitOpError(
981 "llvm.mmra is something other than an MMRA tag or an array of them");
982 }
983 llvm::MDTuple *mmraMd =
984 llvm::MMRAMetadata::getMD(moduleTranslation.getLLVMContext(), tags);
985 if (!mmraMd) {
986 // Empty list, canonicalizes to nothing
987 return success();
988 }
989 for (llvm::Instruction *inst : instructions)
990 inst->setMetadata(llvm::LLVMContext::MD_mmra, mmraMd);
991 return success();
992 }
993 // `!memprof` is call-only (the verifier rejects it anywhere else), so it
994 // goes on the calls the op produced rather than on every instruction.
995 if (name == LLVMDialect::getMemProfAttrName()) {
996 auto mibs = dyn_cast<ArrayAttr>(attribute.getValue());
997 if (!mibs)
998 return op.emitOpError("expected an array for ")
999 << LLVMDialect::getMemProfAttrName();
1000 if (mibs.empty())
1001 return op.emitOpError("expected at least one memprof_mib for ")
1002 << LLVMDialect::getMemProfAttrName();
1003 for (Attribute mibAttr : mibs)
1004 if (!isa<MemProfMIBAttr>(mibAttr))
1005 return op.emitOpError("expected a memprof_mib for ")
1006 << LLVMDialect::getMemProfAttrName();
1007 // The verifier rejects `!memprof` without `!callsite`, so diagnose the
1008 // missing partner here rather than emitting IR that fails verification.
1009 if (!op.hasAttr(LLVMDialect::getCallsiteAttrName()))
1010 return op.emitOpError("expected an llvm.callsite attribute alongside ")
1011 << LLVMDialect::getMemProfAttrName();
1013 for (Attribute mibAttr : mibs)
1014 nodes.push_back(convertMemProfMIB(moduleTranslation.getLLVMContext(),
1015 cast<MemProfMIBAttr>(mibAttr)));
1016 llvm::MDNode *memprof =
1017 llvm::MDNode::get(moduleTranslation.getLLVMContext(), nodes);
1018 for (llvm::Instruction *inst : instructions) {
1019 if (!isa<llvm::CallBase>(inst))
1020 continue;
1021 inst->setMetadata(llvm::LLVMContext::MD_memprof, memprof);
1022 }
1023 return success();
1024 }
1025 if (name == LLVMDialect::getCallsiteAttrName()) {
1026 auto callStack = dyn_cast<DenseI64ArrayAttr>(attribute.getValue());
1027 if (!callStack)
1028 return op.emitOpError("expected a dense i64 array for ")
1029 << LLVMDialect::getCallsiteAttrName();
1030 if (callStack.empty())
1031 return op.emitOpError("expected a non-empty call stack for ")
1032 << LLVMDialect::getCallsiteAttrName();
1033 llvm::MDNode *callsite = convertCallStack(
1034 moduleTranslation.getLLVMContext(), callStack.asArrayRef());
1035 for (llvm::Instruction *inst : instructions) {
1036 if (!isa<llvm::CallBase>(inst))
1037 continue;
1038 inst->setMetadata(llvm::LLVMContext::MD_callsite, callsite);
1039 }
1040 return success();
1041 }
1042 return success();
1043}
1044
1045namespace {
1046/// Implementation of the dialect interface that converts operations belonging
1047/// to the LLVM dialect to LLVM IR.
1048class LLVMDialectLLVMIRTranslationInterface
1049 : public LLVMTranslationDialectInterface {
1050public:
1051 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
1052
1053 /// Translates the given operation to LLVM IR using the provided IR builder
1054 /// and saving the state in `moduleTranslation`.
1055 LogicalResult
1056 convertOperation(Operation *op, llvm::IRBuilderBase &builder,
1057 LLVM::ModuleTranslation &moduleTranslation) const final {
1058 return convertOperationImpl(*op, builder, moduleTranslation);
1059 }
1060
1061 /// Handle some metadata that is represented as a discardable attribute.
1062 LogicalResult
1063 amendOperation(Operation *op, ArrayRef<llvm::Instruction *> instructions,
1064 NamedAttribute attribute,
1065 LLVM::ModuleTranslation &moduleTranslation) const final {
1066 return amendOperationImpl(*op, instructions, attribute, moduleTranslation);
1067 }
1068};
1069} // namespace
1070
1072 registry.insert<LLVM::LLVMDialect>();
1073 registry.addExtension(+[](MLIRContext *ctx, LLVM::LLVMDialect *dialect) {
1074 dialect->addInterfaces<LLVMDialectLLVMIRTranslationInterface>();
1075 });
1076}
1077
1079 DialectRegistry registry;
1081 context.appendDialectRegistry(registry);
1082}
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 llvm::MDNode * convertMemProfMIB(llvm::LLVMContext &ctx, MemProfMIBAttr mib)
Builds one !memprof MemInfoBlock: the allocation call stack, the one allocation-type tag,...
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 LogicalResult convertGEPOp(GEPOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Translate llvm.getelementptr.
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::MDNode * convertCallStack(llvm::LLVMContext &ctx, ArrayRef< int64_t > ids)
Builds a call stack node: one constant integer per source-location hash.
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:151
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:71
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:166
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
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
bool hasAttr(StringAttr name)
Return true if the operation has an attribute with the provided name, false otherwise.
Definition Operation.h:614
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
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:431
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;.