21#include "clang/AST/Attrs.inc"
37#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
38#include "mlir/IR/BuiltinOps.h"
39#include "mlir/IR/Location.h"
40#include "mlir/IR/MLIRContext.h"
41#include "mlir/IR/Operation.h"
42#include "mlir/IR/Verifier.h"
51 case TargetCXXABI::GenericItanium:
52 case TargetCXXABI::GenericAArch64:
53 case TargetCXXABI::AppleARM64:
56 case TargetCXXABI::Fuchsia:
57 case TargetCXXABI::GenericARM:
58 case TargetCXXABI::iOS:
59 case TargetCXXABI::WatchOS:
60 case TargetCXXABI::GenericMIPS:
61 case TargetCXXABI::WebAssembly:
62 case TargetCXXABI::XL:
63 case TargetCXXABI::Microsoft:
64 cgm.
errorNYI(
"createCXXABI: C++ ABI kind");
68 llvm_unreachable(
"invalid C++ ABI kind");
71CIRGenModule::CIRGenModule(mlir::MLIRContext &mlirContext,
75 : builder(mlirContext, *this), astContext(astContext),
76 langOpts(astContext.
getLangOpts()), codeGenOpts(cgo),
77 theModule{
mlir::ModuleOp::create(
mlir::UnknownLoc::get(&mlirContext))},
78 diags(diags), target(astContext.getTargetInfo()),
79 abi(
createCXXABI(*this)), genTypes(*this), vtables(*this) {
107 .toCharUnitsFromBits(
111 const unsigned charSize = astContext.getTargetInfo().getCharWidth();
115 const unsigned sizeTypeSize =
116 astContext.getTypeSize(astContext.getSignedSizeType());
117 SizeSizeInBytes = astContext.toCharUnitsFromBits(sizeTypeSize).getQuantity();
124 std::optional<cir::SourceLanguage> sourceLanguage = getCIRSourceLanguage();
127 cir::CIRDialect::getSourceLanguageAttrName(),
128 cir::SourceLanguageAttr::get(&mlirContext, *sourceLanguage));
129 theModule->setAttr(cir::CIRDialect::getTripleAttrName(),
130 builder.getStringAttr(
getTriple().str()));
132 if (cgo.OptimizationLevel > 0 || cgo.OptimizeSize > 0)
133 theModule->setAttr(cir::CIRDialect::getOptInfoAttrName(),
134 cir::OptInfoAttr::get(&mlirContext,
135 cgo.OptimizationLevel,
144 FileID mainFileId = astContext.getSourceManager().getMainFileID();
146 *astContext.getSourceManager().getFileEntryForID(mainFileId);
149 theModule.setSymName(path);
150 theModule->setLoc(mlir::FileLineColLoc::get(&mlirContext, path,
158void CIRGenModule::createCUDARuntime() {
170 auto &layout = astContext.getASTRecordLayout(rd);
175 return layout.getAlignment();
178 return layout.getNonVirtualAlignment();
183 bool forPointeeType) {
193 if (
unsigned align = tt->getDecl()->getMaxAlignment()) {
196 return astContext.toCharUnitsFromBits(align);
204 t = astContext.getBaseElementType(t);
225 }
else if (forPointeeType && !alignForArray &&
229 alignment = astContext.getTypeAlignInChars(t);
234 if (
unsigned maxAlign = astContext.getLangOpts().MaxTypeAlign) {
236 !astContext.isAlignmentRequired(t))
243 if (theTargetCIRGenInfo)
244 return *theTargetCIRGenInfo;
247 switch (triple.getArch()) {
254 case llvm::Triple::x86_64: {
255 switch (triple.getOS()) {
262 case llvm::Triple::Linux:
264 return *theTargetCIRGenInfo;
267 case llvm::Triple::nvptx:
268 case llvm::Triple::nvptx64:
270 return *theTargetCIRGenInfo;
271 case llvm::Triple::amdgcn: {
273 return *theTargetCIRGenInfo;
279 assert(cLoc.
isValid() &&
"expected valid source location");
283 return mlir::FileLineColLoc::get(builder.getStringAttr(filename),
288 assert(cRange.
isValid() &&
"expected a valid source range");
291 mlir::Attribute metadata;
292 return mlir::FusedLoc::get({begin, end}, metadata, builder.getContext());
301 false, isForDefinition);
335 assert(op &&
"expected a valid global op");
343 mlir::Operation *globalValueOp = op;
344 if (
auto gv = dyn_cast<cir::GetGlobalOp>(op))
346 mlir::SymbolTable::lookupSymbolIn(
getModule(), gv.getNameAttr());
348 if (
auto cirGlobalValue =
349 dyn_cast<cir::CIRGlobalValueInterface>(globalValueOp))
350 if (!cirGlobalValue.isDeclaration())
371 assert(deferredVTables.empty());
381 std::vector<GlobalDecl> curDeclsToEmit;
400 if (
auto *
attr =
decl->getAttr<AttrT>())
401 return attr->isImplicit();
402 return decl->isImplicit();
407 assert(langOpts.CUDA &&
"Should not be called by non-CUDA languages");
412 return !langOpts.CUDAIsDevice || global->
hasAttr<CUDADeviceAttr>() ||
413 global->
hasAttr<CUDAConstantAttr>() ||
414 global->
hasAttr<CUDASharedAttr>() ||
420 if (
const auto *cd = dyn_cast<clang::OpenACCConstructDecl>(gd.
getDecl())) {
438 "Expected Variable or Function");
439 if (
const auto *
varDecl = dyn_cast<VarDecl>(global)) {
443 }
else if (langOpts.CUDAIsDevice) {
444 const auto *
functionDecl = dyn_cast<FunctionDecl>(global);
445 if ((!global->hasAttr<CUDADeviceAttr>() ||
446 (langOpts.OffloadImplicitHostDeviceTemplates &&
451 !
getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(
453 !global->hasAttr<CUDAGlobalAttr>() &&
455 !global->hasAttr<CUDAHostAttr>()))
458 }
else if (!global->hasAttr<CUDAHostAttr>() &&
459 global->hasAttr<CUDADeviceAttr>())
463 if (
const auto *fd = dyn_cast<FunctionDecl>(global)) {
466 if (fd->hasAttr<AnnotateAttr>())
467 errorNYI(fd->getSourceRange(),
"deferredAnnotations");
468 if (!fd->doesThisDeclarationHaveABody()) {
469 if (!fd->doesDeclarationForceExternallyVisibleDefinition())
473 "function declaration that forces code gen");
478 assert(vd->isFileVarDecl() &&
"Cannot emit local var decl as global.");
480 !astContext.isMSStaticDataMemberInlineDefinition(vd)) {
484 if (astContext.getInlineVariableDefinitionKind(vd) ==
523 mlir::Operation *op) {
527 cir::FuncOp funcOp = dyn_cast_if_present<cir::FuncOp>(op);
528 if (!funcOp || funcOp.getFunctionType() != funcType) {
534 if (!funcOp.isDeclaration())
546 mlir::OpBuilder::InsertionGuard guard(builder);
551 setNonAliasAttributes(gd, funcOp);
554 auto getPriority = [
this](
const auto *
attr) ->
int {
558 return attr->DefaultPriority;
561 if (
const ConstructorAttr *ca = funcDecl->getAttr<ConstructorAttr>())
563 if (
const DestructorAttr *da = funcDecl->getAttr<DestructorAttr>())
566 if (funcDecl->getAttr<AnnotateAttr>())
567 errorNYI(funcDecl->getSourceRange(),
"deferredAnnotations");
572 std::optional<int> priority) {
581 ctor.setGlobalCtorPriority(priority);
586 std::optional<int> priority) {
587 if (codeGenOpts.RegisterGlobalDtorsWithAtExit &&
589 errorNYI(dtor.getLoc(),
"registerGlobalDtorsWithAtExit");
592 dtor.setGlobalDtorPriority(priority);
610 return mlir::SymbolTable::lookupSymbolIn(theModule, name);
615 StringRef name, mlir::Type t,
bool isConstant,
616 mlir::ptr::MemorySpaceAttrInterface addrSpace,
617 mlir::Operation *insertPoint) {
622 mlir::OpBuilder::InsertionGuard guard(builder);
628 builder.setInsertionPoint(insertPoint);
634 builder.setInsertionPointToStart(cgm.
getModule().getBody());
637 g = cir::GlobalOp::create(builder, loc, name, t, isConstant, addrSpace);
643 mlir::SymbolTable::setSymbolVisibility(
644 g, mlir::SymbolTable::Visibility::Private);
651 if (isa_and_nonnull<NamedDecl>(d))
657void CIRGenModule::setNonAliasAttributes(
GlobalDecl gd, mlir::Operation *op) {
668std::optional<cir::SourceLanguage> CIRGenModule::getCIRSourceLanguage()
const {
670 using CIRLang = cir::SourceLanguage;
675 if (opts.C99 || opts.C11 || opts.C17 || opts.C23 || opts.C2y ||
676 opts.LangStd == ClangStd::lang_c89 ||
677 opts.LangStd == ClangStd::lang_gnu89)
682 errorNYI(
"CIR does not yet support the given source language");
686LangAS CIRGenModule::getGlobalVarAddressSpace(
const VarDecl *d) {
687 if (langOpts.OpenCL) {
695 if (langOpts.SYCLIsDevice &&
697 errorNYI(
"SYCL global address space");
699 if (langOpts.CUDA && langOpts.CUDAIsDevice) {
701 if (d->
hasAttr<CUDAConstantAttr>())
703 if (d->
hasAttr<CUDASharedAttr>())
705 if (d->
hasAttr<CUDADeviceAttr>())
714 errorNYI(
"OpenMP global address space");
727 gv.
setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
732 for (mlir::Attribute i : indexes) {
733 auto ind = mlir::cast<mlir::IntegerAttr>(i);
734 inds.push_back(ind.getValue().getSExtValue());
740 return view.getSymbol().getValue() == glob.getSymName();
744 cir::GlobalOp newGlob,
745 cir::GlobalViewAttr
attr,
756 mlir::Type newTy = newGlob.getSymType();
761 cir::PointerType newPtrTy;
764 newPtrTy = cir::PointerType::get(newTy);
773 cgm.
errorNYI(
"Unhandled type in createNewGlobalView");
779 mlir::Attribute oldInit) {
780 if (
auto oldView = mlir::dyn_cast<cir::GlobalViewAttr>(oldInit))
783 auto getNewInitElements =
784 [&](mlir::ArrayAttr oldElements) -> mlir::ArrayAttr {
786 for (mlir::Attribute elt : oldElements) {
787 if (
auto view = mlir::dyn_cast<cir::GlobalViewAttr>(elt))
789 else if (mlir::isa<cir::ConstArrayAttr, cir::ConstRecordAttr>(elt))
792 newElements.push_back(elt);
794 return mlir::ArrayAttr::get(cgm.
getBuilder().getContext(), newElements);
797 if (
auto oldArray = mlir::dyn_cast<cir::ConstArrayAttr>(oldInit)) {
798 mlir::Attribute newElements =
799 getNewInitElements(mlir::cast<mlir::ArrayAttr>(oldArray.getElts()));
801 newElements, mlir::cast<cir::ArrayType>(oldArray.getType()));
803 if (
auto oldRecord = mlir::dyn_cast<cir::ConstRecordAttr>(oldInit)) {
804 mlir::ArrayAttr newMembers = getNewInitElements(oldRecord.getMembers());
805 auto recordTy = mlir::cast<cir::RecordType>(oldRecord.getType());
807 newMembers, recordTy.getPacked(), recordTy.getPadded(), recordTy);
812 cgm.
errorNYI(
"Unhandled type in getNewInitValue");
820 assert(oldGV.getSymName() == newGV.getSymName() &&
"symbol names must match");
822 mlir::Type oldTy = oldGV.getSymType();
823 mlir::Type newTy = newGV.getSymType();
828 assert(oldTy != newTy &&
"expected type change in replaceGlobal");
831 std::optional<mlir::SymbolTable::UseRange> oldSymUses =
832 oldGV.getSymbolUses(theModule);
833 for (mlir::SymbolTable::SymbolUse use : *oldSymUses) {
834 mlir::Operation *userOp = use.getUser();
836 (mlir::isa<cir::GetGlobalOp, cir::GlobalOp, cir::ConstantOp>(userOp)) &&
837 "Unexpected user for global op");
839 if (
auto getGlobalOp = dyn_cast<cir::GetGlobalOp>(use.getUser())) {
840 mlir::Value useOpResultValue = getGlobalOp.getAddr();
841 useOpResultValue.setType(cir::PointerType::get(newTy));
843 mlir::OpBuilder::InsertionGuard guard(builder);
844 builder.setInsertionPointAfter(getGlobalOp);
845 mlir::Type ptrTy = builder.getPointerTo(oldTy);
847 builder.createBitcast(getGlobalOp->getLoc(), useOpResultValue, ptrTy);
848 useOpResultValue.replaceAllUsesExcept(
cast,
cast.getDefiningOp());
849 }
else if (
auto glob = dyn_cast<cir::GlobalOp>(userOp)) {
850 if (
auto init = glob.getInitialValue()) {
851 mlir::Attribute nw =
getNewInitValue(*
this, newGV, oldTy, init.value());
852 glob.setInitialValueAttr(nw);
854 }
else if (
auto c = dyn_cast<cir::ConstantOp>(userOp)) {
856 auto typedAttr = mlir::cast<mlir::TypedAttr>(init);
857 mlir::OpBuilder::InsertionGuard guard(builder);
858 builder.setInsertionPointAfter(
c);
859 auto newUser = cir::ConstantOp::create(builder,
c.getLoc(), typedAttr);
860 c.replaceAllUsesWith(newUser.getOperation());
891 "getOrCreateCIRGlobal: global with non-GlobalOp type");
901 if (entry.getSymType() == ty &&
911 if (isForDefinition && !entry.isDeclaration()) {
913 "getOrCreateCIRGlobal: global with conflicting type");
921 if (!isForDefinition)
930 bool isConstant =
false;
935 astContext,
true, !needsDtor);
938 mlir::ptr::MemorySpaceAttrInterface declCIRAS =
944 *
this, loc, mangledName, ty, isConstant, declCIRAS,
945 entry.getOperation());
965 if (langOpts.OpenMP && !langOpts.OpenMPSimd)
967 "getOrCreateCIRGlobal: OpenMP target global variable");
969 gv.setAlignmentAttr(
getSize(astContext.getDeclAlign(d)));
983 if (astContext.isMSStaticDataMemberInlineDefinition(d))
985 "getOrCreateCIRGlobal: MS static data member inline definition");
991 if (
getTriple().getArch() == llvm::Triple::xcore)
993 "getOrCreateCIRGlobal: XCore specific ABI requirements");
1003 "getOrCreateCIRGlobal: external const declaration with initializer");
1015 "getOrCreateCIRGlobal: HIP managed attribute");
1050 mlir::Type ptrTy = builder.getPointerTo(g.getSymType(), g.getAddrSpaceAttr());
1051 return cir::GetGlobalOp::create(
1054 g.getStaticLocalGuard().has_value());
1062 cir::PointerType ptrTy =
1063 builder.getPointerTo(globalOp.getSymType(), globalOp.getAddrSpaceAttr());
1064 return builder.getGlobalViewAttr(ptrTy, globalOp);
1071 "emitGlobalVarDefinition: emit OpenCL/OpenMP global variable");
1078 bool isDefinitionAvailableExternally =
1083 if (isDefinitionAvailableExternally &&
1091 mlir::Attribute init;
1092 bool needsGlobalCtor =
false;
1093 bool needsGlobalDtor =
1094 !isDefinitionAvailableExternally &&
1099 std::optional<ConstantEmitter> emitter;
1104 bool isCUDASharedVar =
1109 bool isCUDAShadowVar =
1111 (vd->
hasAttr<CUDAConstantAttr>() || vd->
hasAttr<CUDADeviceAttr>() ||
1112 vd->
hasAttr<CUDASharedAttr>());
1113 bool isCUDADeviceShadowVar =
1119 (isCUDASharedVar || isCUDAShadowVar || isCUDADeviceShadowVar)) {
1121 }
else if (vd->
hasAttr<LoaderUninitializedAttr>()) {
1123 "emitGlobalVarDefinition: loader uninitialized attribute");
1124 }
else if (!initExpr) {
1137 emitter.emplace(*
this);
1138 mlir::Attribute initializer = emitter->tryEmitForInitializer(*initDecl);
1147 "emitGlobalVarDefinition: flexible array initializer");
1149 if (!isDefinitionAvailableExternally)
1150 needsGlobalCtor =
true;
1153 "emitGlobalVarDefinition: static initializer");
1164 mlir::Type initType;
1165 if (mlir::isa<mlir::SymbolRefAttr>(init)) {
1168 "emitGlobalVarDefinition: global initializer is a symbol reference");
1171 assert(mlir::isa<mlir::TypedAttr>(init) &&
"This should have a type");
1172 auto typedInitAttr = mlir::cast<mlir::TypedAttr>(init);
1173 initType = typedInitAttr.getType();
1175 assert(!mlir::isa<mlir::NoneType>(initType) &&
"Should have a type by now");
1181 if (!gv || gv.getSymType() != initType) {
1183 "emitGlobalVarDefinition: global initializer with type mismatch");
1189 if (vd->
hasAttr<AnnotateAttr>()) {
1191 "emitGlobalVarDefinition: annotate global variable");
1195 cir::GlobalLinkageKind linkage =
1205 if (langOpts.CUDA) {
1206 if (langOpts.CUDAIsDevice) {
1209 if (linkage != cir::GlobalLinkageKind::InternalLinkage &&
1211 (vd->
hasAttr<CUDADeviceAttr>() || vd->
hasAttr<CUDAConstantAttr>() ||
1214 gv->setAttr(cir::CUDAExternallyInitializedAttr::getMnemonic(),
1230 emitter->finalize(gv);
1234 gv.setConstant((vd->
hasAttr<CUDAConstantAttr>() && langOpts.CUDAIsDevice) ||
1235 (!needsGlobalCtor && !needsGlobalDtor &&
1242 gv.setLinkage(linkage);
1246 if (linkage == cir::GlobalLinkageKind::CommonLinkage) {
1248 gv.setConstant(
false);
1253 std::optional<mlir::Attribute> initializer = gv.getInitialValue();
1254 if (initializer && !
getBuilder().isNullValue(*initializer))
1255 gv.setLinkage(cir::GlobalLinkageKind::WeakAnyLinkage);
1258 setNonAliasAttributes(vd, gv);
1265 if (needsGlobalCtor || needsGlobalDtor)
1270 mlir::Operation *op) {
1272 if (
const auto *fd = dyn_cast<FunctionDecl>(
decl)) {
1276 if (
const auto *method = dyn_cast<CXXMethodDecl>(
decl)) {
1280 abi->emitCXXStructor(gd);
1281 else if (fd->isMultiVersion())
1282 errorNYI(method->getSourceRange(),
"multiversion functions");
1286 if (method->isVirtual())
1292 if (fd->isMultiVersion())
1293 errorNYI(fd->getSourceRange(),
"multiversion functions");
1298 if (
const auto *vd = dyn_cast<VarDecl>(
decl))
1301 llvm_unreachable(
"Invalid argument to CIRGenModule::emitGlobalDefinition");
1315 astContext.getAsConstantArrayType(e->
getType());
1316 uint64_t finalSize = cat->getZExtSize();
1317 str.resize(finalSize);
1319 mlir::Type eltTy =
convertType(cat->getElementType());
1320 return builder.getString(str, eltTy, finalSize,
false);
1325 auto arrayEltTy = mlir::cast<cir::IntType>(arrayTy.getElementType());
1327 uint64_t arraySize = arrayTy.getSize();
1329 assert(arraySize == literalSize + 1 &&
1330 "wide string literal array size must be literal length plus null "
1335 bool isAllZero =
true;
1336 for (
unsigned i = 0; i < literalSize; ++i) {
1344 return cir::ZeroAttr::get(arrayTy);
1348 elements.reserve(arraySize);
1349 for (
unsigned i = 0; i < literalSize; ++i)
1350 elements.push_back(cir::IntAttr::get(arrayEltTy, e->
getCodeUnit(i)));
1352 elements.push_back(cir::IntAttr::get(arrayEltTy, 0));
1354 auto elementsAttr = mlir::ArrayAttr::get(&
getMLIRContext(), elements);
1355 return builder.getConstArray(elementsAttr, arrayTy);
1366 if (d.
hasAttr<SelectAnyAttr>())
1370 if (
auto *vd = dyn_cast<VarDecl>(&d))
1385 llvm_unreachable(
"No such linkage");
1391 if (
auto globalOp = dyn_cast_or_null<cir::GlobalOp>(op)) {
1392 globalOp.setComdat(
true);
1395 funcOp.setComdat(
true);
1401 genTypes.updateCompletedType(td);
1405 replacements[name] = op;
1408void CIRGenModule::replacePointerTypeArgs(cir::FuncOp oldF, cir::FuncOp newF) {
1409 std::optional<mlir::SymbolTable::UseRange> optionalUseRange =
1410 oldF.getSymbolUses(theModule);
1411 if (!optionalUseRange)
1414 for (
const mlir::SymbolTable::SymbolUse &u : *optionalUseRange) {
1416 auto call = mlir::dyn_cast<cir::CallOp>(u.getUser());
1420 for (
const auto [argOp, fnArgType] :
1421 llvm::zip(call.getArgs(), newF.getFunctionType().getInputs())) {
1422 if (argOp.getType() == fnArgType)
1428 errorNYI(call.getLoc(),
"replace call with mismatched types");
1433void CIRGenModule::applyReplacements() {
1434 for (
auto &i : replacements) {
1435 StringRef mangledName = i.first;
1436 mlir::Operation *replacement = i.second;
1442 auto newF = dyn_cast<cir::FuncOp>(replacement);
1445 errorNYI(replacement->getLoc(),
"replacement is not a function");
1451 replacePointerTypeArgs(oldF, newF);
1454 if (oldF.replaceAllSymbolUses(newF.getSymNameAttr(), theModule).failed())
1455 llvm_unreachable(
"internal error, cannot RAUW symbol");
1457 newF->moveBefore(oldF);
1464 mlir::Location loc, StringRef name, mlir::Type ty,
1466 auto gv = mlir::dyn_cast_or_null<cir::GlobalOp>(
1467 mlir::SymbolTable::lookupSymbolIn(theModule, name));
1471 if (gv.getSymType() == ty)
1477 assert(gv.isDeclaration() &&
"Declaration has wrong type!");
1479 errorNYI(loc,
"createOrReplaceCXXRuntimeVariable: declaration exists with "
1490 mlir::SymbolTable::setSymbolVisibility(gv,
1494 !gv.hasAvailableExternallyLinkage()) {
1498 gv.setAlignmentAttr(
getSize(alignment));
1509 if ((noCommon || vd->
hasAttr<NoCommonAttr>()) && !vd->
hasAttr<CommonAttr>())
1520 if (vd->
hasAttr<SectionAttr>())
1526 if (vd->
hasAttr<PragmaClangBSSSectionAttr>() ||
1527 vd->
hasAttr<PragmaClangDataSectionAttr>() ||
1528 vd->
hasAttr<PragmaClangRelroSectionAttr>() ||
1529 vd->
hasAttr<PragmaClangRodataSectionAttr>())
1537 if (vd->
hasAttr<WeakImportAttr>())
1547 if (vd->
hasAttr<AlignedAttr>())
1554 for (
const FieldDecl *fd : rd->fields()) {
1555 if (fd->isBitField())
1557 if (fd->hasAttr<AlignedAttr>())
1582 return cir::GlobalLinkageKind::InternalLinkage;
1584 if (dd->
hasAttr<WeakAttr>()) {
1585 if (isConstantVariable)
1586 return cir::GlobalLinkageKind::WeakODRLinkage;
1587 return cir::GlobalLinkageKind::WeakAnyLinkage;
1592 return cir::GlobalLinkageKind::LinkOnceAnyLinkage;
1597 return cir::GlobalLinkageKind::AvailableExternallyLinkage;
1611 return !astContext.getLangOpts().AppleKext
1612 ? cir::GlobalLinkageKind::LinkOnceODRLinkage
1613 : cir::GlobalLinkageKind::InternalLinkage;
1627 return cir::GlobalLinkageKind::ExternalLinkage;
1630 return dd->
hasAttr<CUDAGlobalAttr>()
1631 ? cir::GlobalLinkageKind::ExternalLinkage
1632 : cir::GlobalLinkageKind::InternalLinkage;
1633 return cir::GlobalLinkageKind::WeakODRLinkage;
1641 return cir::GlobalLinkageKind::CommonLinkage;
1647 if (dd->
hasAttr<SelectAnyAttr>())
1648 return cir::GlobalLinkageKind::WeakODRLinkage;
1652 return cir::GlobalLinkageKind::ExternalLinkage;
1664 mlir::Operation *old, cir::FuncOp newFn) {
1666 auto oldFn = mlir::dyn_cast<cir::FuncOp>(old);
1674 if (oldFn->getAttrs().size() <= 1)
1676 "replaceUsesOfNonProtoTypeWithRealFunction: Attribute forwarding");
1679 newFn.setNoProto(oldFn.getNoProto());
1682 std::optional<mlir::SymbolTable::UseRange> symUses =
1683 oldFn.getSymbolUses(oldFn->getParentOp());
1684 for (
const mlir::SymbolTable::SymbolUse &use : symUses.value()) {
1685 mlir::OpBuilder::InsertionGuard guard(builder);
1687 if (
auto noProtoCallOp = mlir::dyn_cast<cir::CallOp>(use.getUser())) {
1688 builder.setInsertionPoint(noProtoCallOp);
1691 cir::CallOp realCallOp = builder.createCallOp(
1692 noProtoCallOp.getLoc(), newFn, noProtoCallOp.getOperands());
1695 noProtoCallOp.replaceAllUsesWith(realCallOp);
1696 noProtoCallOp.erase();
1697 }
else if (
auto getGlobalOp =
1698 mlir::dyn_cast<cir::GetGlobalOp>(use.getUser())) {
1700 getGlobalOp.getAddr().setType(
1701 cir::PointerType::get(newFn.getFunctionType()));
1704 "replaceUsesOfNonProtoTypeWithRealFunction: unexpected use");
1709cir::GlobalLinkageKind
1711 assert(!isConstant &&
"constant variables NYI");
1712 GVALinkage linkage = astContext.GetGVALinkageForVariable(vd);
1719 GVALinkage linkage = astContext.GetGVALinkageForFunction(d);
1721 if (
const auto *dtor = dyn_cast<CXXDestructorDecl>(d))
1730 StringRef globalName,
CharUnits alignment) {
1736 cgm, loc, globalName,
c.getType(), !cgm.
getLangOpts().WritableStrings);
1739 gv.setAlignmentAttr(cgm.
getSize(alignment));
1741 cir::GlobalLinkageKindAttr::get(cgm.
getBuilder().getContext(), lt));
1745 if (gv.isWeakForLinker()) {
1746 assert(cgm.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
1749 cgm.
setDSOLocal(
static_cast<mlir::Operation *
>(gv));
1770 std::string result =
1773 assert(!mlir::SymbolTable::lookupSymbolIn(theModule, result));
1781 astContext.getAlignOfGlobalVarInChars(
s->getType(),
nullptr);
1789 if (!gv.getAlignment() ||
1790 uint64_t(alignment.
getQuantity()) > *gv.getAlignment())
1791 gv.setAlignmentAttr(
getSize(alignment));
1796 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(
s) &&
1799 "getGlobalForStringLiteral: mangle string literals");
1807 mlir::Location loc =
s->getBeginLoc().isValid()
1809 : builder.getUnknownLoc();
1810 auto typedC = llvm::cast<mlir::TypedAttr>(
c);
1812 cir::GlobalLinkageKind::PrivateLinkage, *
this,
1813 uniqueName, alignment);
1827 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(gv.getSymType());
1828 assert(arrayTy &&
"String literal must be array");
1832 return builder.getGlobalViewAttr(ptrTy, gv);
1848 errorNYI(
"SYCL or OpenMP temp address space");
1858 "emitExplicitCastExprType");
1864 auto ty = mlir::cast<cir::MethodType>(
convertType(destTy));
1865 return builder.getNullMethodAttr(ty);
1868 auto ty = mlir::cast<cir::DataMemberType>(
convertType(destTy));
1869 return builder.getNullDataMemberAttr(ty);
1880 if (
const auto *methodDecl = dyn_cast<CXXMethodDecl>(
decl)) {
1882 if (methodDecl->isVirtual())
1883 return cir::ConstantOp::create(
1884 builder, loc,
getCXXABI().buildVirtualMethodAttr(ty, methodDecl));
1887 return cir::ConstantOp::create(builder, loc,
1888 builder.getMethodAttr(ty, methodFuncOp));
1894 return cir::ConstantOp::create(
1895 builder, loc, builder.getDataMemberAttr(ty,
fieldDecl->getFieldIndex()));
1905 if (
auto *oid = dyn_cast<ObjCImplDecl>(
decl))
1906 errorNYI(oid->getSourceRange(),
"emitDeclConext: ObjCImplDecl");
1916 if (
decl->isTemplated())
1919 switch (
decl->getKind()) {
1922 decl->getDeclKindName());
1925 case Decl::CXXConversion:
1926 case Decl::CXXMethod:
1927 case Decl::Function: {
1930 if (!fd->isConsteval())
1936 case Decl::Decomposition:
1937 case Decl::VarTemplateSpecialization: {
1940 errorNYI(
decl->getSourceRange(),
"global variable decompositions");
1946 case Decl::OpenACCRoutine:
1949 case Decl::OpenACCDeclare:
1952 case Decl::OMPThreadPrivate:
1955 case Decl::OMPGroupPrivate:
1958 case Decl::OMPAllocate:
1961 case Decl::OMPCapturedExpr:
1964 case Decl::OMPDeclareReduction:
1967 case Decl::OMPDeclareMapper:
1970 case Decl::OMPRequires:
1975 case Decl::UsingDirective:
1976 case Decl::UsingEnum:
1977 case Decl::NamespaceAlias:
1979 case Decl::TypeAlias:
1985 case Decl::ClassTemplate:
1987 case Decl::CXXDeductionGuide:
1989 case Decl::FunctionTemplate:
1990 case Decl::StaticAssert:
1991 case Decl::TypeAliasTemplate:
1992 case Decl::UsingShadow:
1993 case Decl::VarTemplate:
1994 case Decl::VarTemplatePartialSpecialization:
1997 case Decl::CXXConstructor:
2000 case Decl::CXXDestructor:
2005 case Decl::LinkageSpec:
2006 case Decl::Namespace:
2010 case Decl::ClassTemplateSpecialization:
2011 case Decl::CXXRecord: {
2014 for (
auto *childDecl : crd->
decls())
2020 case Decl::FileScopeAsm:
2022 if (langOpts.CUDA && langOpts.CUDAIsDevice)
2025 if (langOpts.OpenMPIsTargetDevice)
2028 if (langOpts.SYCLIsDevice)
2031 std::string line = file_asm->getAsmString();
2032 globalScopeAsm.push_back(builder.getStringAttr(line));
2039 op.setInitialValueAttr(value);
2053 md->getParent()->getNumVBases() == 0)
2055 "getAddrAndTypeOfCXXStructor: MS ABI complete destructor");
2066 false, isForDefinition);
2068 return {fnType, fn};
2072 mlir::Type funcType,
bool forVTable,
2076 "consteval function should never be emitted");
2086 if (
const auto *dd = dyn_cast<CXXDestructorDecl>(gd.
getDecl())) {
2089 dd->getParent()->getNumVBases() == 0)
2091 "getAddrOfFunction: MS ABI complete destructor");
2097 false, isForDefinition);
2099 if (langOpts.CUDA && !langOpts.CUDAIsDevice &&
2105 bool isHIPHandle = mlir::isa<cir::GlobalOp>(*handle);
2106 if (isForDefinition || isHIPHandle)
2108 return mlir::dyn_cast<cir::FuncOp>(*handle);
2117 llvm::raw_svector_ostream
out(buffer);
2126 assert(ii &&
"Attempt to mangle unnamed decl.");
2128 const auto *fd = dyn_cast<FunctionDecl>(nd);
2132 }
else if (fd && fd->hasAttr<CUDAGlobalAttr>() &&
2136 DeviceKernelAttr::isOpenCLSpelling(
2137 fd->getAttr<DeviceKernelAttr>()) &&
2154 if (
const auto *fd = dyn_cast<FunctionDecl>(nd)) {
2155 if (fd->isMultiVersion()) {
2157 "getMangledName: multi-version functions");
2162 "getMangledName: GPU relocatable device code");
2165 return std::string(
out.str());
2168static FunctionDecl *
2183 if (
auto *methodDecl = dyn_cast<CXXMethodDecl>(protoFunc);
2184 methodDecl && methodDecl->isImplicitObjectMemberFunction()) {
2186 paramTypes.insert(paramTypes.begin(), methodDecl->getThisType());
2189 fpt->getExtProtoInfo());
2200 params.reserve(fpt->getNumParams());
2203 for (
unsigned i = 0, e = fpt->getNumParams(); i != e; ++i) {
2207 nullptr, fpt->getParamType(i),
nullptr,
2210 params.push_back(parm);
2213 tempFunc->setParams(params);
2238 if (
const auto *cd = dyn_cast<CXXConstructorDecl>(canonicalGd.
getDecl())) {
2241 "getMangledName: C++ constructor without variants");
2250 auto result = manglings.insert(std::make_pair(mangledName, gd));
2251 return mangledDeclNames[canonicalGd] = result.first->first();
2255 assert(!d->
getInit() &&
"Cannot emit definite definitions here!");
2263 if (gv && !mlir::cast<cir::GlobalOp>(gv).isDeclaration())
2279 if (langOpts.EmitAllDecls)
2282 const auto *vd = dyn_cast<VarDecl>(global);
2284 ((codeGenOpts.KeepPersistentStorageVariables &&
2285 (vd->getStorageDuration() ==
SD_Static ||
2286 vd->getStorageDuration() ==
SD_Thread)) ||
2287 (codeGenOpts.KeepStaticConsts && vd->getStorageDuration() ==
SD_Static &&
2288 vd->getType().isConstQualified())))
2301 if (langOpts.OpenMP >= 50 && !langOpts.OpenMPSimd) {
2302 std::optional<OMPDeclareTargetDeclAttr *> activeAttr =
2303 OMPDeclareTargetDeclAttr::getActiveAttr(global);
2304 if (!activeAttr || (*activeAttr)->getLevel() != (
unsigned)-1)
2308 const auto *fd = dyn_cast<FunctionDecl>(global);
2315 if (fd->hasAttr<TargetVersionAttr>() && !fd->isMultiVersion())
2317 if (langOpts.SYCLIsDevice) {
2318 errorNYI(fd->getSourceRange(),
"mayBeEmittedEagerly: SYCL");
2322 const auto *vd = dyn_cast<VarDecl>(global);
2324 if (astContext.getInlineVariableDefinitionKind(vd) ==
2332 if (langOpts.OpenMP && langOpts.OpenMPUseTLS &&
2333 astContext.getTargetInfo().isTLSSupported() &&
isa<VarDecl>(global) &&
2335 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(global))
2338 assert((fd || vd) &&
2339 "Only FunctionDecl and VarDecl should hit this path so far.");
2344 cir::CIRGlobalValueInterface gv) {
2345 if (gv.hasLocalLinkage())
2348 if (!gv.hasDefaultVisibility() && !gv.hasExternalWeakLinkage())
2356 const llvm::Triple &tt = cgm.
getTriple();
2358 if (tt.isOSCygMing()) {
2367 cgm.
errorNYI(
"shouldAssumeDSOLocal: MinGW");
2373 if (tt.isOSBinFormatCOFF() && gv.hasExternalWeakLinkage())
2381 if (tt.isOSBinFormatCOFF() || (tt.isOSWindows() && tt.isOSBinFormatMachO()))
2385 if (!tt.isOSBinFormatELF())
2390 if (rm != llvm::Reloc::Static && !lOpts.PIE) {
2398 return !(lOpts.SemanticInterposition || lOpts.HalfNoSemanticInterposition);
2402 if (!gv.isDeclarationForLinker())
2408 if (rm == llvm::Reloc::PIC_ && gv.hasExternalWeakLinkage())
2415 if (cgOpts.DirectAccessExternalData) {
2421 if (
auto globalOp = dyn_cast<cir::GlobalOp>(gv.getOperation())) {
2454 if (
auto globalValue = dyn_cast<cir::CIRGlobalValueInterface>(op))
2473 auto res = manglings.find(mangledName);
2474 if (res == manglings.end())
2476 result = res->getValue();
2483 return cir::TLS_Model::GeneralDynamic;
2485 return cir::TLS_Model::LocalDynamic;
2487 return cir::TLS_Model::InitialExec;
2489 return cir::TLS_Model::LocalExec;
2491 llvm_unreachable(
"Invalid TLS model!");
2495 assert(d.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2500 if (d.
getAttr<TLSModelAttr>())
2504 global.setTlsModel(tlm);
2509 cir::FuncOp func,
bool isThunk) {
2511 cir::CallingConv callingConv;
2512 cir::SideEffect sideEffect;
2519 mlir::NamedAttrList pal{};
2520 std::vector<mlir::NamedAttrList> argAttrs(info.
arguments().size());
2521 mlir::NamedAttrList retAttrs{};
2523 retAttrs, callingConv, sideEffect,
2526 for (mlir::NamedAttribute
attr : pal)
2527 func->setAttr(
attr.getName(),
attr.getValue());
2529 llvm::for_each(llvm::enumerate(argAttrs), [func](
auto idx_arg_pair) {
2530 mlir::function_interface_impl::setArgAttrs(func, idx_arg_pair.index(),
2531 idx_arg_pair.value());
2533 if (!retAttrs.empty())
2534 mlir::function_interface_impl::setResultAttrs(func, 0, retAttrs);
2547 bool isIncompleteFunction,
2553 if (!isIncompleteFunction)
2555 getTypes().arrangeGlobalDeclaration(globalDecl),
2571 if (fd->isInlineBuiltinDeclaration()) {
2573 bool hasBody = fd->
hasBody(fdBody);
2575 assert(hasBody &&
"Inline builtin declarations should always have an "
2580 if (fd->isReplaceableGlobalAllocationFunction()) {
2583 func->setAttr(cir::CIRDialect::getNoBuiltinAttrName(),
2595 if (!langOpts.Exceptions)
2598 if (langOpts.CXXExceptions)
2601 if (langOpts.ObjCExceptions)
2612 f->setAttr(cir::CIRDialect::getNoThrowAttrName(),
2615 std::optional<cir::InlineKind> existingInlineKind = f.getInlineKind();
2617 existingInlineKind && *existingInlineKind == cir::InlineKind::NoInline;
2618 bool isAlwaysInline = existingInlineKind &&
2619 *existingInlineKind == cir::InlineKind::AlwaysInline;
2623 if (!isAlwaysInline &&
2628 f.setInlineKind(cir::InlineKind::NoInline);
2643 if (
decl->hasAttr<NoInlineAttr>() && !isAlwaysInline) {
2645 f.setInlineKind(cir::InlineKind::NoInline);
2646 }
else if (
decl->hasAttr<AlwaysInlineAttr>() && !isNoInline) {
2649 f.setInlineKind(cir::InlineKind::AlwaysInline);
2653 if (!isAlwaysInline)
2654 f.setInlineKind(cir::InlineKind::NoInline);
2659 if (
auto *fd = dyn_cast<FunctionDecl>(
decl)) {
2664 auto checkRedeclForInline = [](
const FunctionDecl *redecl) {
2665 return redecl->isInlineSpecified();
2667 if (any_of(
decl->redecls(), checkRedeclForInline))
2672 return any_of(pattern->
redecls(), checkRedeclForInline);
2674 if (checkForInline(fd)) {
2675 f.setInlineKind(cir::InlineKind::InlineHint);
2676 }
else if (codeGenOpts.getInlining() ==
2678 !fd->isInlined() && !isAlwaysInline) {
2679 f.setInlineKind(cir::InlineKind::NoInline);
2688 StringRef mangledName, mlir::Type funcType,
GlobalDecl gd,
bool forVTable,
2690 mlir::NamedAttrList extraAttrs) {
2693 if (
const auto *fd = cast_or_null<FunctionDecl>(d)) {
2695 if (
getLangOpts().OpenMPIsTargetDevice && fd->isDefined() && !dontDefer &&
2698 "getOrCreateCIRFunction: OpenMP target function");
2702 if (fd->isMultiVersion())
2703 errorNYI(fd->getSourceRange(),
"getOrCreateCIRFunction: multi-version");
2709 assert(mlir::isa<cir::FuncOp>(entry));
2714 if (d && !d->
hasAttr<DLLImportAttr>() && !d->
hasAttr<DLLExportAttr>()) {
2722 if (isForDefinition && fn && !fn.isDeclaration()) {
2729 diagnosedConflictingDefinitions.insert(gd).second) {
2733 diag::note_previous_definition);
2737 if (fn && fn.getFunctionType() == funcType) {
2741 if (!isForDefinition) {
2749 auto *funcDecl = llvm::cast_or_null<FunctionDecl>(gd.
getDecl());
2750 bool invalidLoc = !funcDecl ||
2751 funcDecl->getSourceRange().getBegin().isInvalid() ||
2752 funcDecl->getSourceRange().getEnd().isInvalid();
2754 invalidLoc ? theModule->getLoc() :
getLoc(funcDecl->getSourceRange()),
2755 mangledName, mlir::cast<cir::FuncType>(funcType), funcDecl);
2766 auto symbolOp = mlir::cast<mlir::SymbolOpInterface>(entry);
2774 if (symbolOp.getSymbolUses(symbolOp->getParentOp()))
2783 if (!extraAttrs.empty()) {
2784 extraAttrs.append(funcOp->getAttrs());
2785 funcOp->setAttrs(extraAttrs);
2792 assert(funcOp.getFunctionType() == funcType);
2799 if (isa_and_nonnull<CXXDestructorDecl>(d) &&
2829 fd = fd->getPreviousDecl()) {
2831 if (fd->doesThisDeclarationHaveABody()) {
2844 cir::FuncType funcType,
2848 mlir::OpBuilder::InsertionGuard guard(builder);
2856 builder.setInsertionPoint(cgf->
curFn);
2858 func = cir::FuncOp::create(builder, loc, name, funcType);
2863 func.setNoProto(
true);
2865 assert(func.isDeclaration() &&
"expected empty body");
2869 func.setLinkageAttr(cir::GlobalLinkageKindAttr::get(
2871 mlir::SymbolTable::setSymbolVisibility(
2872 func, mlir::SymbolTable::Visibility::Private);
2880 theModule.push_back(func);
2885 for (
const auto *
attr :
2899 fnOp.setBuiltin(
true);
2905 return cir::CtorKind::Default;
2907 return cir::CtorKind::Copy;
2909 return cir::CtorKind::Move;
2910 return cir::CtorKind::Custom;
2915 return cir::AssignKind::Copy;
2917 return cir::AssignKind::Move;
2918 llvm_unreachable(
"not a copy or move assignment operator");
2926 if (
const auto *dtor = dyn_cast<CXXDestructorDecl>(funcDecl)) {
2927 auto cxxDtor = cir::CXXDtorAttr::get(
2930 funcOp.setCxxSpecialMemberAttr(cxxDtor);
2934 if (
const auto *ctor = dyn_cast<CXXConstructorDecl>(funcDecl)) {
2936 auto cxxCtor = cir::CXXCtorAttr::get(
2938 kind, ctor->isTrivial());
2939 funcOp.setCxxSpecialMemberAttr(cxxCtor);
2943 const auto *method = dyn_cast<CXXMethodDecl>(funcDecl);
2944 if (method && (method->isCopyAssignmentOperator() ||
2945 method->isMoveAssignmentOperator())) {
2947 auto cxxAssign = cir::CXXAssignAttr::get(
2949 assignKind, method->isTrivial());
2950 funcOp.setCxxSpecialMemberAttr(cxxAssign);
2956 cir::FuncOp funcOp, StringRef name) {
2972 mlir::NamedAttrList extraAttrs,
2974 bool assumeConvergent) {
2975 if (assumeConvergent)
2976 errorNYI(
"createRuntimeFunction: assumeConvergent");
2986 entry.setDSOLocal(
true);
2992mlir::SymbolTable::Visibility
2996 if (op.isDeclaration())
2997 return mlir::SymbolTable::Visibility::Private;
3001mlir::SymbolTable::Visibility
3004 case cir::GlobalLinkageKind::InternalLinkage:
3005 case cir::GlobalLinkageKind::PrivateLinkage:
3006 return mlir::SymbolTable::Visibility::Private;
3007 case cir::GlobalLinkageKind::ExternalLinkage:
3008 case cir::GlobalLinkageKind::ExternalWeakLinkage:
3009 case cir::GlobalLinkageKind::LinkOnceODRLinkage:
3010 case cir::GlobalLinkageKind::AvailableExternallyLinkage:
3011 case cir::GlobalLinkageKind::CommonLinkage:
3012 case cir::GlobalLinkageKind::WeakAnyLinkage:
3013 case cir::GlobalLinkageKind::WeakODRLinkage:
3014 return mlir::SymbolTable::Visibility::Public;
3016 llvm::errs() <<
"visibility not implemented for '"
3017 << stringifyGlobalLinkageKind(glk) <<
"'\n";
3018 assert(0 &&
"not implemented");
3021 llvm_unreachable(
"linkage should be handled above!");
3025 clang::VisibilityAttr::VisibilityType visibility) {
3026 switch (visibility) {
3027 case clang::VisibilityAttr::VisibilityType::Default:
3028 return cir::VisibilityKind::Default;
3029 case clang::VisibilityAttr::VisibilityType::Hidden:
3030 return cir::VisibilityKind::Hidden;
3031 case clang::VisibilityAttr::VisibilityType::Protected:
3032 return cir::VisibilityKind::Protected;
3034 llvm_unreachable(
"unexpected visibility value");
3039 const clang::VisibilityAttr *va =
decl->getAttr<clang::VisibilityAttr>();
3040 cir::VisibilityAttr cirVisibility =
3043 cirVisibility = cir::VisibilityAttr::get(
3047 return cirVisibility;
3053 applyReplacements();
3055 theModule->setAttr(cir::CIRDialect::getModuleLevelAsmAttrName(),
3056 builder.getArrayAttr(globalScopeAsm));
3068 cir::FuncOp aliasee,
3069 cir::GlobalLinkageKind linkage) {
3071 auto *aliasFD = dyn_cast<FunctionDecl>(aliasGD.
getDecl());
3072 assert(aliasFD &&
"expected FunctionDecl");
3083 mangledName, fnType, aliasFD);
3084 alias.setAliasee(aliasee.getName());
3085 alias.setLinkage(linkage);
3089 mlir::SymbolTable::setSymbolVisibility(
3090 alias, mlir::SymbolTable::Visibility::Private);
3097 errorNYI(aliasFD->getSourceRange(),
"emitAliasForGlobal: previous uses");
3107 return genTypes.convertType(
type);
3114 return mlir::verify(theModule).succeeded();
3123 return builder.getConstNullPtrAttr(builder.getUInt8PtrTy());
3126 langOpts.ObjCRuntime.isGNUFamily()) {
3127 errorNYI(loc,
"getAddrOfRTTIDescriptor: Objc PtrType & Objc RT GUN");
3137 llvm::iterator_range<CastExpr::path_const_iterator> path) {
3144 assert(!base->isVirtual() &&
"Should not see virtual bases here!");
3149 const auto *baseDecl = base->getType()->castAsCXXRecordDecl();
3161 llvm::StringRef feature) {
3162 unsigned diagID = diags.getCustomDiagID(
3164 return diags.Report(loc, diagID) << feature;
3168 llvm::StringRef feature) {
3180 "cannot compile this %0 yet");
3181 diags.Report(astContext.getFullLoc(
s->getBeginLoc()), diagId)
3182 <<
type <<
s->getSourceRange();
3188 "cannot compile this %0 yet");
3189 diags.Report(astContext.getFullLoc(d->
getLocation()), diagId) <<
type;
3193 cir::LabelOp label) {
3194 [[maybe_unused]]
auto result =
3196 assert(result.second &&
3197 "attempting to map a blockaddress info that is already mapped");
3202 assert(result.second &&
3203 "attempting to map a blockaddress operation that is already mapped");
3207 cir::LabelOp label) {
3209 assert(result.second &&
3210 "attempting to map a blockaddress operation that is already mapped");
3214 cir::LabelOp newLabel) {
3217 "trying to update a blockaddress not previously mapped");
3218 assert(!it->second &&
"blockaddress already has a resolved label");
3220 it->second = newLabel;
3233 "not a global temporary");
3240 materializedType = mte->
getType();
3244 auto insertResult = materializedGlobalTemporaryMap.insert({mte,
nullptr});
3245 if (!insertResult.second)
3252 llvm::raw_svector_ostream
out(name);
3270 value = &evalResult.
Val;
3274 std::optional<ConstantEmitter> emitter;
3275 mlir::Attribute initialValue =
nullptr;
3276 bool isConstant =
false;
3280 emitter.emplace(*
this);
3281 initialValue = emitter->emitForInitializer(*value, materializedType);
3286 type = mlir::cast<mlir::TypedAttr>(initialValue).getType();
3294 cir::GlobalLinkageKind linkage =
3296 if (linkage == cir::GlobalLinkageKind::ExternalLinkage) {
3298 if (
varDecl->isStaticDataMember() &&
varDecl->getAnyInitializer(initVD) &&
3306 linkage = cir::GlobalLinkageKind::InternalLinkage;
3311 gv.setInitialValueAttr(initialValue);
3314 emitter->finalize(gv);
3316 if (!gv.hasLocalLinkage()) {
3321 gv.setAlignment(align.getAsAlign().value());
3324 "Global temporary with comdat/weak linkage");
3327 "Global temporary with thread local storage");
3328 mlir::Operation *cv = gv;
3334 mlir::Operation *&entry = materializedGlobalTemporaryMap[mte];
3336 entry->replaceAllUsesWith(cv);
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool shouldAssumeDSOLocal(const CIRGenModule &cgm, cir::CIRGlobalValueInterface gv)
static cir::AssignKind getAssignKindFromDecl(const CXXMethodDecl *method)
static FunctionDecl * createOpenACCBindTempFunction(ASTContext &ctx, const IdentifierInfo *bindName, const FunctionDecl *protoFunc)
static bool shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static mlir::Attribute getNewInitValue(CIRGenModule &cgm, cir::GlobalOp newGlob, mlir::Type oldTy, mlir::Attribute oldInit)
static bool hasUnwindExceptions(const LangOptions &langOpts)
Determines whether the language options require us to model unwind exceptions.
static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal, cir::FuncOp funcOp, StringRef name)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static llvm::SmallVector< int64_t > indexesOfArrayAttr(mlir::ArrayAttr indexes)
static bool isViewOnGlobal(cir::GlobalOp glob, cir::GlobalViewAttr view)
static cir::GlobalOp generateStringLiteral(mlir::Location loc, mlir::TypedAttr c, cir::GlobalLinkageKind lt, CIRGenModule &cgm, StringRef globalName, CharUnits alignment)
static bool hasImplicitAttr(const ValueDecl *decl)
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static bool isVarDeclStrongDefinition(const ASTContext &astContext, CIRGenModule &cgm, const VarDecl *vd, bool noCommon)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static cir::CtorKind getCtorKindFromDecl(const CXXConstructorDecl *ctor)
static cir::GlobalViewAttr createNewGlobalView(CIRGenModule &cgm, cir::GlobalOp newGlob, cir::GlobalViewAttr attr, mlir::Type oldTy)
This file defines OpenACC nodes for declarative directives.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines the SourceManager interface.
__device__ __2f16 float __ockl_bool s
__device__ __2f16 float c
cir::GlobalViewAttr getGlobalViewAttr(cir::GlobalOp globalOp, mlir::ArrayAttr indices={})
Get constant address of a global variable as an MLIR attribute.
cir::PointerType getPointerTo(mlir::Type ty)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
TranslationUnitDecl * getTranslationUnitDecl() const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
void Deallocate(void *Ptr) const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const TargetInfo & getTargetInfo() const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
mlir::Attribute getConstRecordOrZeroAttr(mlir::ArrayAttr arrayAttr, bool packed=false, bool padded=false, mlir::Type type={})
uint64_t computeOffsetFromGlobalViewIndices(const cir::CIRDataLayout &layout, mlir::Type ty, llvm::ArrayRef< int64_t > indices)
void computeGlobalViewIndicesFromFlatOffset(int64_t offset, mlir::Type ty, cir::CIRDataLayout layout, llvm::SmallVectorImpl< int64_t > &indices)
cir::ConstArrayAttr getConstArray(mlir::Attribute attrs, cir::ArrayType arrayTy) const
virtual mlir::Operation * getKernelHandle(cir::FuncOp fn, GlobalDecl gd)=0
Implements C++ ABI-specific code generation functions.
virtual mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty)=0
virtual void emitCXXConstructors(const clang::CXXConstructorDecl *d)=0
Emit constructor variants required by this ABI.
virtual void emitCXXDestructors(const clang::CXXDestructorDecl *d)=0
Emit dtor variants required by this ABI.
clang::MangleContext & getMangleContext()
Gets the mangle context.
virtual cir::GlobalLinkageKind getCXXDestructorLinkage(GVALinkage linkage, const CXXDestructorDecl *dtor, CXXDtorType dt) const
llvm::ArrayRef< CanQualType > arguments() const
cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn, cir::FuncType funcType)
void emitVariablyModifiedType(QualType ty)
mlir::Operation * curFn
The current function or global initializer that is generated code for.
This class organizes the cross-function state that is used while generating CIR code.
void updateResolvedBlockAddress(cir::BlockAddressOp op, cir::LabelOp newLabel)
void replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old, cir::FuncOp newFn)
This function is called when we implement a function with no prototype, e.g.
static cir::GlobalOp createGlobalOp(CIRGenModule &cgm, mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::ptr::MemorySpaceAttrInterface addrSpace={}, mlir::Operation *insertPoint=nullptr)
llvm::StringRef getMangledName(clang::GlobalDecl gd)
CharUnits computeNonVirtualBaseClassOffset(const CXXRecordDecl *derivedClass, llvm::iterator_range< CastExpr::path_const_iterator > path)
void setGlobalVisibility(mlir::Operation *op, const NamedDecl *d) const
Set the visibility for the given global.
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
void emitDeferred()
Emit any needed decls for which code generation was deferred.
clang::ASTContext & getASTContext() const
cir::FuncOp getAddrOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
CIRGenCUDARuntime & getCUDARuntime()
llvm::DenseMap< cir::BlockAddrInfoAttr, cir::LabelOp > blockAddressInfoToLabel
Map BlockAddrInfoAttr (function name, label name) to the corresponding CIR LabelOp.
void emitTopLevelDecl(clang::Decl *decl)
void emitOMPDeclareMapper(const OMPDeclareMapperDecl *d)
void addReplacement(llvm::StringRef name, mlir::Operation *op)
mlir::Type convertType(clang::QualType type)
bool shouldEmitRTTI(bool forEH=false)
cir::GlobalOp getGlobalForStringLiteral(const StringLiteral *s, llvm::StringRef name=".str")
Return a global symbol reference to a constant array for the given string literal.
void emitOMPCapturedExpr(const OMPCapturedExprDecl *d)
void mapUnresolvedBlockAddress(cir::BlockAddressOp op)
bool mustBeEmitted(const clang::ValueDecl *d)
Determine whether the definition must be emitted; if this returns false, the definition can be emitte...
void emitGlobalOpenACCDeclareDecl(const clang::OpenACCDeclareDecl *cd)
mlir::IntegerAttr getSize(CharUnits size)
CIRGenBuilderTy & getBuilder()
void setDSOLocal(mlir::Operation *op) const
std::string getUniqueGlobalName(const std::string &baseName)
std::pair< cir::FuncType, cir::FuncOp > getAddrAndTypeOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
void setGVProperties(mlir::Operation *op, const NamedDecl *d) const
Set visibility, dllimport/dllexport and dso_local.
cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty, LangAS langAS, const VarDecl *d, ForDefinition_t isForDefinition)
If the specified mangled name is not in the module, create and return an mlir::GlobalOp value.
cir::FuncOp createCIRBuiltinFunction(mlir::Location loc, llvm::StringRef name, cir::FuncType ty, const clang::FunctionDecl *fd)
Create a CIR function with builtin attribute set.
void emitGlobalOpenACCRoutineDecl(const clang::OpenACCRoutineDecl *cd)
clang::CharUnits getClassPointerAlignment(const clang::CXXRecordDecl *rd)
Return the best known alignment for an unknown pointer to a particular class.
void handleCXXStaticMemberVarInstantiation(VarDecl *vd)
Tell the consumer that this variable has been instantiated.
void emitOMPRequiresDecl(const OMPRequiresDecl *d)
void emitGlobalDefinition(clang::GlobalDecl gd, mlir::Operation *op=nullptr)
void mapResolvedBlockAddress(cir::BlockAddressOp op, cir::LabelOp)
clang::DiagnosticsEngine & getDiags() const
mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty, bool forEH=false)
Get the address of the RTTI descriptor for the given type.
void setFunctionAttributes(GlobalDecl gd, cir::FuncOp f, bool isIncompleteFunction, bool isThunk)
Set function attributes for a function declaration.
static mlir::SymbolTable::Visibility getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK)
const clang::TargetInfo & getTarget() const
void setCIRFunctionAttributes(GlobalDecl gd, const CIRGenFunctionInfo &info, cir::FuncOp func, bool isThunk)
Set the CIR function attributes (Sext, zext, etc).
const llvm::Triple & getTriple() const
static mlir::SymbolTable::Visibility getMLIRVisibility(Visibility v)
void emitTentativeDefinition(const VarDecl *d)
cir::GlobalOp createOrReplaceCXXRuntimeVariable(mlir::Location loc, llvm::StringRef name, mlir::Type ty, cir::GlobalLinkageKind linkage, clang::CharUnits alignment)
Will return a global variable of the given type.
void emitOMPAllocateDecl(const OMPAllocateDecl *d)
void error(SourceLocation loc, llvm::StringRef error)
Emit a general error that something can't be done.
void emitGlobalDecl(const clang::GlobalDecl &d)
Helper for emitDeferred to apply actual codegen.
void emitGlobalVarDefinition(const clang::VarDecl *vd, bool isTentative=false)
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::NamedAttrList extraAttrs={}, bool isLocal=false, bool assumeConvergent=false)
void setTLSMode(mlir::Operation *op, const VarDecl &d)
Set TLS mode for the given operation based on the given variable declaration.
cir::FuncOp getAddrOfFunction(clang::GlobalDecl gd, mlir::Type funcType=nullptr, bool forVTable=false, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
Return the address of the given function.
void emitAliasForGlobal(llvm::StringRef mangledName, mlir::Operation *op, GlobalDecl aliasGD, cir::FuncOp aliasee, cir::GlobalLinkageKind linkage)
mlir::Value emitMemberPointerConstant(const UnaryOperator *e)
void emitGlobalOpenACCDecl(const clang::OpenACCConstructDecl *cd)
bool verifyModule() const
void emitExplicitCastExprType(const ExplicitCastExpr *e, CIRGenFunction *cgf=nullptr)
Emit type info if type of an expression is a variably modified type.
const cir::CIRDataLayout getDataLayout() const
mlir::Operation * getAddrOfGlobalTemporary(const MaterializeTemporaryExpr *mte, const Expr *init)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
std::map< llvm::StringRef, clang::GlobalDecl > deferredDecls
This contains all the decls which have definitions but which are deferred for emission and therefore ...
void errorUnsupported(const Stmt *s, llvm::StringRef type)
Print out an error that codegen doesn't support the specified stmt yet.
mlir::Value getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty={}, ForDefinition_t isForDefinition=NotForDefinition)
Return the mlir::Value for the address of the given global variable.
static void setInitializer(cir::GlobalOp &op, mlir::Attribute value)
cir::GlobalViewAttr getAddrOfGlobalVarAttr(const VarDecl *d)
Return the mlir::GlobalViewAttr for the address of the given global.
void addGlobalCtor(cir::FuncOp ctor, std::optional< int > priority=std::nullopt)
Add a global constructor or destructor to the module.
cir::GlobalLinkageKind getFunctionLinkage(GlobalDecl gd)
void updateCompletedType(const clang::TagDecl *td)
const clang::CodeGenOptions & getCodeGenOpts() const
void emitDeferredVTables()
Emit any vtables which we deferred and still have a use for.
const clang::LangOptions & getLangOpts() const
void constructAttributeList(llvm::StringRef name, const CIRGenFunctionInfo &info, CIRGenCalleeInfo calleeInfo, mlir::NamedAttrList &attrs, llvm::MutableArrayRef< mlir::NamedAttrList > argAttrs, mlir::NamedAttrList &retAttrs, cir::CallingConv &callingConv, cir::SideEffect &sideEffect, bool attrOnCallSite, bool isThunk)
Get the CIR attributes and calling convention to use for a particular function type.
cir::FuncOp getOrCreateCIRFunction(llvm::StringRef mangledName, mlir::Type funcType, clang::GlobalDecl gd, bool forVTable, bool dontDefer=false, bool isThunk=false, ForDefinition_t isForDefinition=NotForDefinition, mlir::NamedAttrList extraAttrs={})
void emitOpenACCRoutineDecl(const clang::FunctionDecl *funcDecl, cir::FuncOp func, SourceLocation pragmaLoc, ArrayRef< const OpenACCClause * > clauses)
void emitVTablesOpportunistically()
Try to emit external vtables as available_externally if they have emitted all inlined virtual functio...
cir::TLS_Model getDefaultCIRTLSModel() const
Get TLS mode from CodeGenOptions.
void addGlobalDtor(cir::FuncOp dtor, std::optional< int > priority=std::nullopt)
Add a function to the list that will be called when the module is unloaded.
void addDeferredDeclToEmit(clang::GlobalDecl GD)
bool shouldEmitCUDAGlobalVar(const VarDecl *global) const
cir::FuncOp createCIRFunction(mlir::Location loc, llvm::StringRef name, cir::FuncType funcType, const clang::FunctionDecl *funcDecl)
const TargetCIRGenInfo & getTargetCIRGenInfo()
void emitCXXGlobalVarDeclInitFunc(const VarDecl *vd, cir::GlobalOp addr, bool performInit)
void setGVPropertiesAux(mlir::Operation *op, const NamedDecl *d) const
LangAS getLangTempAllocaAddressSpace() const
Returns the address space for temporary allocations in the language.
llvm::DenseSet< cir::BlockAddressOp > unresolvedBlockAddressToLabel
Track CIR BlockAddressOps that cannot be resolved immediately because their LabelOp has not yet been ...
mlir::Location getLoc(clang::SourceLocation cLoc)
Helpers to convert the presumed location of Clang's SourceLocation to an MLIR Location.
llvm::DenseMap< mlir::Attribute, cir::GlobalOp > constantStringMap
mlir::Operation * lastGlobalOp
void replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV)
Replace all uses of the old global with the new global, updating types and references as needed.
static cir::VisibilityKind getGlobalVisibilityKindFromClangVisibility(clang::VisibilityAttr::VisibilityType visibility)
llvm::StringMap< unsigned > cgGlobalNames
void setCXXSpecialMemberAttr(cir::FuncOp funcOp, const clang::FunctionDecl *funcDecl)
Mark the function as a special member (e.g. constructor, destructor)
mlir::TypedAttr emitNullMemberAttr(QualType t, const MemberPointerType *mpt)
Returns a null attribute to represent either a null method or null data member, depending on the type...
mlir::Operation * getGlobalValue(llvm::StringRef ref)
void emitOMPDeclareReduction(const OMPDeclareReductionDecl *d)
mlir::ModuleOp getModule() const
bool supportsCOMDAT() const
clang::CharUnits getNaturalTypeAlignment(clang::QualType t, LValueBaseInfo *baseInfo=nullptr, bool forPointeeType=false)
FIXME: this could likely be a common helper and not necessarily related with codegen.
cir::GlobalLinkageKind getCIRLinkageForDeclarator(const DeclaratorDecl *dd, GVALinkage linkage, bool isConstantVariable)
mlir::MLIRContext & getMLIRContext()
mlir::Operation * getAddrOfGlobal(clang::GlobalDecl gd, ForDefinition_t isForDefinition=NotForDefinition)
void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op)
CIRGenCXXABI & getCXXABI() const
cir::GlobalViewAttr getAddrOfConstantStringFromLiteral(const StringLiteral *s, llvm::StringRef name=".str")
Return a global symbol reference to a constant array for the given string literal.
llvm::MapVector< cir::BlockAddressOp, cir::LabelOp > blockAddressToLabel
Map CIR BlockAddressOps directly to their resolved LabelOps.
bool lookupRepresentativeDecl(llvm::StringRef mangledName, clang::GlobalDecl &gd) const
void emitDeclContext(const DeclContext *dc)
void emitGlobal(clang::GlobalDecl gd)
Emit code for a single global function or variable declaration.
cir::LabelOp lookupBlockAddressInfo(cir::BlockAddrInfoAttr blockInfo)
bool mayBeEmittedEagerly(const clang::ValueDecl *d)
Determine whether the definition can be emitted eagerly, or should be delayed until the end of the tr...
cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd, bool isConstant)
void mapBlockAddress(cir::BlockAddrInfoAttr blockInfo, cir::LabelOp label)
void setCIRFunctionAttributesForDefinition(const clang::FunctionDecl *fd, cir::FuncOp f)
Set extra attributes (inline, etc.) for a function.
std::string getOpenACCBindMangledName(const IdentifierInfo *bindName, const FunctionDecl *attachedFunction)
void emitGlobalFunctionDefinition(clang::GlobalDecl gd, mlir::Operation *op)
CIRGenVTables & getVTables()
void setFunctionLinkage(GlobalDecl gd, cir::FuncOp f)
std::vector< clang::GlobalDecl > deferredDeclsToEmit
void emitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *d)
void emitAMDGPUMetadata()
Emits AMDGPU specific Metadata.
void emitOMPGroupPrivateDecl(const OMPGroupPrivateDecl *d)
mlir::Attribute getConstantArrayFromStringLiteral(const StringLiteral *e)
Return a constant array for the given string.
cir::VisibilityAttr getGlobalVisibilityAttrFromDecl(const Decl *decl)
void setCommonAttributes(GlobalDecl gd, mlir::Operation *op)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
const CIRGenFunctionInfo & arrangeGlobalDeclaration(GlobalDecl gd)
const CIRGenFunctionInfo & arrangeCXXMethodDeclaration(const clang::CXXMethodDecl *md)
C++ methods have some special rules and also have implicit parameters.
const CIRGenFunctionInfo & arrangeCXXStructorDeclaration(clang::GlobalDecl gd)
cir::FuncType getFunctionType(const CIRGenFunctionInfo &info)
Get the CIR function type for.
mlir::Type convertTypeForMem(clang::QualType, bool forBitField=false)
Convert type T into an mlir::Type.
void emitThunks(GlobalDecl gd)
Emit the associated thunks for the given global decl.
virtual clang::LangAS getGlobalVarAddressSpace(CIRGenModule &cgm, const clang::VarDecl *d) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual mlir::ptr::MemorySpaceAttrInterface getCIRAllocaAddressSpace() const
Get the address space for alloca.
virtual void setTargetAttributes(const clang::Decl *decl, mlir::Operation *global, CIRGenModule &module) const
Provides a convenient hook to handle extra target-specific attributes for the given global.
Represents a base class of a C++ class.
Represents a C++ constructor within a class.
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Represents a static or instance method of a struct/union/class.
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Represents a C++ struct/union/class.
bool isEffectivelyFinal() const
Determine whether it's impossible for a class to be derived from this class.
bool hasDefinition() const
CharUnits - This is an opaque type for sizes expressed in character units.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
Represents the canonical version of C arrays with a specified constant size.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Decl - This represents one declaration (or definition), e.g.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
static DeclContext * castToDeclContext(const Decl *)
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Represents a ValueDecl that came out of a declarator.
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
ExplicitCastExpr - An explicit cast written in the source code.
This represents one expression.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Represents a member of a struct/union/class.
Cached information about one file (either on disk or in the virtual file system).
StringRef tryGetRealPathName() const
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
FunctionType - C99 6.7.5.3 - Function Declarators.
CallingConv getCallConv() const
GlobalDecl - represents a global declaration.
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
void setLinkage(Linkage L)
Linkage getLinkage() const
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
unsigned getManglingNumber() const
A pointer to member type per C++ 8.3.3 - Pointers to members.
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
Represents a parameter to a function.
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
A (possibly-)qualified type.
LangAS getAddressSpace() const
Return the address space of this type.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
bool hasUnaligned() const
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
StringLiteral - This represents a string literal expression, e.g.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
bool isReferenceType() const
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
bool isMemberFunctionPointerType() const
const T * getAs() const
Member-template getAs<specific type>'.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Expr * getSubExpr() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ TLS_None
Not a TLS variable.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
bool isMatchingAddressSpace(mlir::ptr::MemorySpaceAttrInterface cirAS, clang::LangAS as)
mlir::ptr::MemorySpaceAttrInterface toCIRAddressSpaceAttr(mlir::MLIRContext &ctx, clang::LangAS langAS)
Convert an AST LangAS to the appropriate CIR address space attribute interface.
static bool isWeakForLinker(GlobalLinkageKind linkage)
Whether the definition of this global may be replaced at link time.
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCIRGenInfo > createAMDGPUTargetCIRGenInfo(CIRGenTypes &cgt)
std::unique_ptr< TargetCIRGenInfo > createNVPTXTargetCIRGenInfo(CIRGenTypes &cgt)
CIRGenCXXABI * CreateCIRGenItaniumCXXABI(CIRGenModule &cgm)
Creates and Itanium-family ABI.
std::unique_ptr< TargetCIRGenInfo > createX8664TargetCIRGenInfo(CIRGenTypes &cgt)
CIRGenCUDARuntime * createNVCUDARuntime(CIRGenModule &cgm)
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, FieldDecl > fieldDecl
Matches field declarations.
const internal::VariadicDynCastAllOfMatcher< Decl, FunctionDecl > functionDecl
Matches function declarations.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
U cast(CodeGen::Address addr)
bool isExternallyVisible(Linkage L)
static bool globalCtorLexOrder()
static bool opFuncArmNewAttr()
static bool getRuntimeFunctionDecl()
static bool weakRefReference()
static bool opFuncOptNoneAttr()
static bool opGlobalSection()
static bool addressSpace()
static bool opFuncMinSizeAttr()
static bool opGlobalUnnamedAddr()
static bool opGlobalThreadLocal()
static bool sourceLanguageCases()
static bool opFuncAstDeclAttr()
static bool opFuncNoDuplicateAttr()
static bool opGlobalUsedOrCompilerUsed()
static bool stackProtector()
static bool moduleNameHash()
static bool opGlobalVisibility()
static bool setDLLStorageClass()
static bool opFuncUnwindTablesAttr()
static bool opFuncParameterAttributes()
static bool targetCIRGenInfoArch()
static bool opFuncExtraAttrs()
static bool opFuncNakedAttr()
static bool opFuncSection()
static bool attributeNoBuiltin()
static bool opGlobalDLLImportExport()
static bool opGlobalPartition()
static bool opGlobalWeakRef()
static bool setTargetAttributes()
static bool deferredCXXGlobalInit()
static bool opFuncOperandBundles()
static bool opFuncCallingConv()
static bool globalCtorAssociatedData()
static bool defaultVisibility()
static bool opFuncColdHotAttr()
static bool opFuncExceptions()
static bool opFuncArmStreamingAttr()
static bool cudaSupport()
static bool opFuncMaybeHandleStaticInExternC()
static bool generateDebugInfo()
static bool targetCIRGenInfoOS()
static bool opFuncCPUAndFeaturesAttributes()
static bool maybeHandleStaticInExternC()
static bool setLLVMFunctionFEnvAttributes()
mlir::Type uCharTy
ClangIR char.
unsigned char SizeSizeInBytes
unsigned char PointerAlignInBytes
cir::PointerType allocaInt8PtrTy
void* in alloca address space
cir::PointerType uInt8PtrTy
mlir::ptr::MemorySpaceAttrInterface cirAllocaAddressSpace
cir::PointerType voidPtrTy
void* in address space 0
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool hasSideEffects() const
Return true if the evaluated expression has side effects.
LangStandard - Information about the properties of a particular language standard.