19#include "mlir/Dialect/LLVMIR/LLVMDialectDecl.h"
20#include "mlir/Dialect/OpenMP/Utils/Utils.h"
21#include "mlir/IR/SymbolTable.h"
24#include "clang/AST/Attrs.inc"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/ADT/StringRef.h"
45#include "llvm/ADT/StringSwitch.h"
46#include "llvm/Support/raw_ostream.h"
50#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
51#include "mlir/IR/Attributes.h"
52#include "mlir/IR/BuiltinOps.h"
53#include "mlir/IR/Location.h"
54#include "mlir/IR/MLIRContext.h"
55#include "mlir/IR/Operation.h"
56#include "mlir/IR/Verifier.h"
63 case TargetCXXABI::GenericItanium:
64 case TargetCXXABI::GenericAArch64:
65 case TargetCXXABI::AppleARM64:
66 case TargetCXXABI::GenericARM:
68 case TargetCXXABI::Microsoft:
71 case TargetCXXABI::Fuchsia:
72 case TargetCXXABI::iOS:
73 case TargetCXXABI::WatchOS:
74 case TargetCXXABI::GenericMIPS:
75 case TargetCXXABI::WebAssembly:
76 case TargetCXXABI::XL:
77 cgm.
errorNYI(
"createCXXABI: C++ ABI kind");
81 llvm_unreachable(
"invalid C++ ABI kind");
84CIRGenModule::CIRGenModule(mlir::MLIRContext &mlirContext,
88 : builder(mlirContext, *this), astContext(astContext),
91 theModule{
mlir::ModuleOp::create(
mlir::UnknownLoc::get(&mlirContext))},
92 diags(diags), target(astContext.getTargetInfo()),
93 abi(
createCXXABI(*this)), genTypes(*this), vtables(*this) {
100 langOpts.CPlusPlusModules &&
130 .toCharUnitsFromBits(
134 const unsigned charSize = target.getCharWidth();
137 const unsigned sizeTypeSize = target.getTypeWidth(target.getSizeType());
145 std::optional<cir::SourceLanguage> sourceLanguage = getCIRSourceLanguage();
148 cir::CIRDialect::getSourceLanguageAttrName(),
149 cir::SourceLanguageAttr::get(&mlirContext, *sourceLanguage));
150 if (langOpts.OpenCL || (langOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
153 langOpts.OpenCL ? langOpts.getOpenCLCompatibleVersion() : 200;
154 setOpenCLVersionAttr(cir::CIRDialect::getOpenCLVersionAttrName(), version);
155 if (langOpts.OpenCLCPlusPlus)
156 setOpenCLVersionAttr(cir::CIRDialect::getOpenCLCXXVersionAttrName(),
157 langOpts.OpenCLCPlusPlusVersion);
160 unsigned spirMajor = version / 100;
161 getModule()->setAttr(cir::CIRDialect::getOpenCLSPIRVersionAttrName(),
164 spirMajor > 1 ? 0 : 2));
167 getModule()->setAttr(cir::CIRDialect::getTripleAttrName(),
168 builder.getStringAttr(
getTriple().str()));
169 getModule()->setAttr(cir::CIRDialect::getTargetABIAttrName(),
170 builder.getStringAttr(
getTarget().getABI()));
175 llvm::StringMap<std::string> defaultCPUAndFeatures;
176 if (getCPUAndFeaturesAttributes(
GlobalDecl(), defaultCPUAndFeatures))
177 for (
const auto &[key, val] : defaultCPUAndFeatures)
178 getModule()->setAttr(key, builder.getStringAttr(val));
183 cir::CIRDialect::getCXXABIAttrName(),
186 if (llvm::VersionTuple sdkVersion =
getTarget().getSDKVersion();
188 getModule()->setAttr(cir::CIRDialect::getSDKVersionAttrName(),
189 builder.getStringAttr(sdkVersion.getAsString()));
190 if (langOpts.CUDA && !langOpts.CUID.empty())
191 getModule()->setAttr(cir::CIRDialect::getCUIDHashAttrName(),
192 builder.getStringAttr(astContext.getCUIDHash()));
195 getModule()->setAttr(cir::CIRDialect::getSizeTypeWidthAttrName(),
196 builder.getI32IntegerAttr(sizeTypeSize));
197 getModule()->setAttr(cir::CIRDialect::getIntTypeWidthAttrName(),
198 builder.getI32IntegerAttr(target.getIntWidth()));
204 cir::CIRDialect::getLoweringOptionsAttrName(),
205 cir::LoweringOptionsAttr::get(
208 langOpts.ThreadsafeStatics,
210 langOpts.CUDAIsDevice,
213 langOpts.SYCLIsDevice,
214 langOpts.GPURelocatableDeviceCode,
215 langOpts.OpenMP != 0,
216 langOpts.OpenMPIsTargetDevice,
218 static_cast<int32_t
>(langOpts.getClangABICompat()),
219 static_cast<int32_t
>(langOpts.LongDoubleSize),
220 cgo.EnableNoundefAttrs,
221 langOpts.getDefaultExceptionMode() ==
224 langOpts.RelativeCXXABIVTables));
226 if (cgo.OptimizationLevel > 0 || cgo.OptimizeSize > 0)
227 getModule()->setAttr(cir::CIRDialect::getOptInfoAttrName(),
228 cir::OptInfoAttr::get(&mlirContext,
229 cgo.OptimizationLevel,
233 cir::CIRDialect::getDefaultTlsModelAttrName(),
236 if (langOpts.OpenMP) {
237 mlir::omp::OffloadModuleOpts ompOpts(
238 langOpts.OpenMPTargetDebug, langOpts.OpenMPTeamSubscription,
239 langOpts.OpenMPThreadSubscription, langOpts.OpenMPNoThreadState,
240 langOpts.OpenMPNoNestedParallelism, langOpts.OpenMPIsTargetDevice,
241 getTriple().isGPU(), langOpts.OpenMPForceUSM, langOpts.OpenMP,
242 langOpts.OMPHostIRFile, langOpts.OMPTargetTriples, langOpts.NoGPULib);
243 mlir::omp::setOffloadModuleInterfaceAttributes(
getModule(), ompOpts);
244 mlir::omp::setOpenMPVersionAttribute(
getModule(), langOpts.OpenMP);
250 createOpenMPRuntime();
255 if (!codeGenOpts.RelaxedAliasing && codeGenOpts.OptimizationLevel > 0 &&
256 !codeGenOpts.NewStructPathTBAA)
257 tbaa = std::make_unique<CIRGenTBAA>(mlirContext, astContext,
getCXXABI(),
258 codeGenOpts, langOpts);
263 FileID mainFileId = astContext.getSourceManager().getMainFileID();
265 *astContext.getSourceManager().getFileEntryForID(mainFileId);
269 getModule()->setLoc(mlir::FileLineColLoc::get(&mlirContext, path,
280 return tbaa->getTypeInfo(qty);
293 return tbaa->getAccessInfo(accessType);
299 return tbaa->getBaseTypeInfo(qty);
305 return tbaa->getAccessTagInfo(tbaaInfo);
312 return tbaa->mergeTBAAInfoForCast(sourceInfo, targetInfo);
320 return tbaa->mergeTBAAInfoForConditionalOperator(infoA, infoB);
323void CIRGenModule::setOpenCLVersionAttr(StringRef attrName,
unsigned version) {
325 attrName, cir::OpenCLVersionAttr::get(&
getMLIRContext(), version / 100,
326 (version % 100) / 10));
329void CIRGenModule::createCUDARuntime() {
333void CIRGenModule::createOpenMPRuntime() {
334 openMPRuntime = std::make_unique<CIRGenOpenMPRuntime>(*
this);
345 auto &layout = astContext.getASTRecordLayout(rd);
350 return layout.getAlignment();
353 return layout.getNonVirtualAlignment();
359 bool forPointeeType) {
370 if (
unsigned align = tt->getDecl()->getMaxAlignment()) {
373 return astContext.toCharUnitsFromBits(align);
381 t = astContext.getBaseElementType(t);
402 }
else if (forPointeeType && !alignForArray &&
406 alignment = astContext.getTypeAlignInChars(t);
411 if (
unsigned maxAlign = astContext.getLangOpts().MaxTypeAlign) {
413 !astContext.isAlignmentRequired(t))
426 if (theTargetCIRGenInfo)
427 return *theTargetCIRGenInfo;
430 switch (triple.getArch()) {
437 case llvm::Triple::x86_64: {
438 switch (triple.getOS()) {
445 case llvm::Triple::Linux:
447 return *theTargetCIRGenInfo;
450 case llvm::Triple::aarch64:
451 case llvm::Triple::aarch64_32:
452 case llvm::Triple::aarch64_be: {
454 return *theTargetCIRGenInfo;
456 case llvm::Triple::nvptx:
457 case llvm::Triple::nvptx64:
459 return *theTargetCIRGenInfo;
460 case llvm::Triple::amdgpu: {
462 return *theTargetCIRGenInfo;
464 case llvm::Triple::spir:
465 case llvm::Triple::spir64:
466 case llvm::Triple::spirv:
467 case llvm::Triple::spirv32:
468 case llvm::Triple::spirv64:
470 return *theTargetCIRGenInfo;
471 case llvm::Triple::systemz: {
474 if (triple.isOSzOS())
477 return *theTargetCIRGenInfo;
483 assert(cLoc.
isValid() &&
"expected valid source location");
487 return mlir::FileLineColLoc::get(builder.getStringAttr(filename),
492 assert(cRange.
isValid() &&
"expected a valid source range");
495 mlir::Attribute metadata;
496 return mlir::FusedLoc::get({begin, end}, metadata, builder.getContext());
505 false, isForDefinition);
539 assert(op &&
"expected a valid global op");
547 mlir::Operation *globalValueOp = op;
548 if (
auto gv = dyn_cast<cir::GetGlobalOp>(op)) {
550 assert(globalValueOp &&
"expected a valid global op");
553 if (
auto cirGlobalValue =
554 dyn_cast<cir::CIRGlobalValueInterface>(globalValueOp))
555 if (!cirGlobalValue.isDeclaration())
576 assert(deferredVTables.empty());
591 std::vector<GlobalDecl> curDeclsToEmit;
599 if (
const auto *fd = d.getDecl()->getAsFunction()) {
600 if (langOpts.SYCLIsDevice && fd->hasAttr<SYCLKernelEntryPointAttr>() &&
604 if (!fd->getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
633 os << (isa<VarDecl>(d) ?
".static." :
".intern.");
635 os << (isa<VarDecl>(d) ?
"__static__" :
"__intern__");
642 "printPostfixForExternalizedDecl: CUID is not specified");
651 if (!langOpts.OpenMPIsTargetDevice && !langOpts.CUDA)
654 const auto *aa = global->
getAttr<AliasAttr>();
662 const auto *aliaseeDecl = dyn_cast<ValueDecl>(aliaseeGD.getDecl());
663 if (langOpts.OpenMPIsTargetDevice)
664 return !aliaseeDecl ||
665 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(aliaseeDecl);
668 const bool hasDeviceAttr = global->
hasAttr<CUDADeviceAttr>();
669 const bool aliaseeHasDeviceAttr =
670 aliaseeDecl && aliaseeDecl->hasAttr<CUDADeviceAttr>();
672 if (langOpts.CUDAIsDevice)
673 return !hasDeviceAttr || !aliaseeHasDeviceAttr;
681 if (
const auto *cd = dyn_cast<clang::OpenACCConstructDecl>(gd.
getDecl())) {
689 if (global->hasAttr<WeakRefAttr>())
694 if (global->hasAttr<AliasAttr>()) {
702 if (langOpts.CUDA && !
getASTContext().shouldEmitCUDADecl(global))
705 if (langOpts.OpenMP) {
707 if (openMPRuntime && openMPRuntime->emitTargetGlobal(gd))
709 if (
auto *drd = dyn_cast<OMPDeclareReductionDecl>(global)) {
714 if (
auto *dmd = dyn_cast<OMPDeclareMapperDecl>(global)) {
721 if (
const auto *fd = dyn_cast<FunctionDecl>(global)) {
724 if (fd->hasAttr<AnnotateAttr>()) {
727 deferredAnnotations[mangledName] = fd;
729 if (!fd->doesThisDeclarationHaveABody()) {
730 if (!fd->doesDeclarationForceExternallyVisibleDefinition() &&
741 assert(vd->isFileVarDecl() &&
"Cannot emit local var decl as global.");
743 !astContext.isMSStaticDataMemberInlineDefinition(vd)) {
747 if (astContext.getInlineVariableDefinitionKind(vd) ==
762 if (
auto existing = dyn_cast_if_present<cir::CIRGlobalValueInterface>(
764 existing && !existing.isDeclaration())
792 mlir::Operation *op) {
796 cir::FuncOp funcOp = dyn_cast_if_present<cir::FuncOp>(op);
797 if (!funcOp || funcOp.getFunctionType() != funcType) {
803 if (!funcOp.isDeclaration())
815 mlir::OpBuilder::InsertionGuard guard(builder);
820 setNonAliasAttributes(gd, funcOp);
823 auto getPriority = [
this](
const auto *
attr) ->
int {
827 return attr->DefaultPriority;
830 if (
const ConstructorAttr *ca = funcDecl->getAttr<ConstructorAttr>())
832 if (
const DestructorAttr *da = funcDecl->getAttr<DestructorAttr>())
835 if (funcDecl->getAttr<AnnotateAttr>())
838 if (
getLangOpts().OpenMP && funcDecl->hasAttr<OMPDeclareTargetDeclAttr>())
844 std::optional<int> priority) {
853 ctor.setGlobalCtorPriority(priority);
858 std::optional<int> priority) {
859 if (codeGenOpts.RegisterGlobalDtorsWithAtExit &&
861 errorNYI(dtor.getLoc(),
"registerGlobalDtorsWithAtExit");
864 dtor.setGlobalDtorPriority(priority);
890 mlir::ptr::MemorySpaceAttrInterface addrSpace,
891 mlir::Operation *insertPoint) {
896 mlir::OpBuilder::InsertionGuard guard(builder);
902 builder.setInsertionPoint(insertPoint);
908 builder.setInsertionPointToStart(
getModule().getBody());
911 g = cir::GlobalOp::create(builder, loc, name, t, isConstant, addrSpace);
917 mlir::SymbolTable::setSymbolVisibility(
918 g, mlir::SymbolTable::Visibility::Private);
926 if (isa_and_nonnull<NamedDecl>(d))
930 if (
auto gvi = mlir::dyn_cast<cir::CIRGlobalValueInterface>(gv)) {
931 if (d && d->
hasAttr<UsedAttr>())
934 if (
const auto *vd = dyn_cast_if_present<VarDecl>(d);
935 vd && ((codeGenOpts.KeepPersistentStorageVariables &&
936 (vd->getStorageDuration() ==
SD_Static ||
937 vd->getStorageDuration() ==
SD_Thread)) ||
938 (codeGenOpts.KeepStaticConsts &&
940 vd->getType().isConstQualified())))
946static std::vector<std::string>
948 llvm::StringMap<bool> &featureMap) {
949 llvm::StringMap<bool> defaultFeatureMap;
953 std::vector<std::string> delta;
954 for (
const auto &[k, v] : featureMap) {
955 auto defaultIt = defaultFeatureMap.find(k);
956 if (defaultIt == defaultFeatureMap.end() || defaultIt->getValue() != v)
957 delta.push_back((v ?
"+" :
"-") + k.str());
963bool CIRGenModule::getCPUAndFeaturesAttributes(
964 GlobalDecl gd, llvm::StringMap<std::string> &attrs,
965 bool setTargetFeatures) {
971 std::vector<std::string> features;
975 const auto *fd = dyn_cast_or_null<FunctionDecl>(gd.
getDecl());
976 fd = fd ? fd->getMostRecentDecl() : fd;
977 const auto *td = fd ? fd->getAttr<TargetAttr>() :
nullptr;
978 const auto *tv = fd ? fd->getAttr<TargetVersionAttr>() :
nullptr;
979 assert((!td || !tv) &&
"both target_version and target specified");
980 const auto *sd = fd ? fd->getAttr<CPUSpecificAttr>() :
nullptr;
981 const auto *tc = fd ? fd->getAttr<TargetClonesAttr>() :
nullptr;
982 bool addedAttr =
false;
983 if (td || tv || sd || tc) {
984 llvm::StringMap<bool> featureMap;
985 astContext.getFunctionFeatureMap(featureMap, gd);
991 llvm::StringRef featureStr = td ? td->getFeaturesStr() : llvm::StringRef();
994 if (!featureStr.empty()) {
995 clang::ParsedTargetAttr parsedAttr =
997 if (!parsedAttr.
CPU.empty() &&
999 targetCPU = parsedAttr.
CPU;
1002 if (!parsedAttr.
Tune.empty() &&
1004 tuneCPU = parsedAttr.
Tune;
1020 features.reserve(features.size() + featureMap.size());
1021 for (
const auto &entry : featureMap)
1022 features.push_back((entry.getValue() ?
"+" :
"-") +
1023 entry.getKey().str());
1028 llvm::StringMap<bool> featureMap;
1030 astContext.getFunctionFeatureMap(featureMap, gd);
1041 if (!targetCPU.empty()) {
1042 attrs[cir::CIRDialect::getTargetCPUAttrName()] = targetCPU.str();
1045 if (!tuneCPU.empty()) {
1046 attrs[cir::CIRDialect::getTuneCPUAttrName()] = tuneCPU.str();
1049 if (!features.empty() && setTargetFeatures) {
1050 llvm::erase_if(features, [&](
const std::string &f) {
1051 assert(!f.empty() && (f[0] ==
'+' || f[0] ==
'-') &&
1052 "feature string must start with '+' or '-'");
1055 llvm::sort(features);
1056 attrs[cir::CIRDialect::getTargetFeaturesAttrName()] =
1057 llvm::join(features,
",");
1065void CIRGenModule::setNonAliasAttributes(GlobalDecl gd, mlir::Operation *op) {
1070 if (
auto gvi = mlir::dyn_cast<cir::CIRGlobalValueInterface>(op)) {
1071 if (
const auto *sa = d->
getAttr<SectionAttr>())
1072 gvi.setSection(builder.getStringAttr(sa->getName()));
1076 if (
auto func = dyn_cast<cir::FuncOp>(op)) {
1077 llvm::StringMap<std::string> attrs;
1078 if (getCPUAndFeaturesAttributes(gd, attrs)) {
1085 for (llvm::StringRef name :
1086 {cir::CIRDialect::getTargetCPUAttrName(),
1087 cir::CIRDialect::getTuneCPUAttrName(),
1088 cir::CIRDialect::getTargetFeaturesAttrName()})
1089 func->removeAttr(name);
1090 for (
const auto &[key, val] : attrs)
1091 func->setAttr(key, builder.getStringAttr(val));
1101std::optional<cir::SourceLanguage> CIRGenModule::getCIRSourceLanguage()
const {
1102 using ClangStd = clang::LangStandard;
1103 using CIRLang = cir::SourceLanguage;
1106 if (opts.OpenCLCPlusPlus)
1107 return CIRLang::OpenCLCXX;
1109 return CIRLang::OpenCLC;
1111 return CIRLang::CXX;
1112 if (opts.C99 || opts.C11 || opts.C17 || opts.C23 || opts.C2y ||
1113 opts.LangStd == ClangStd::lang_c89 ||
1114 opts.LangStd == ClangStd::lang_gnu89)
1119 errorNYI(
"CIR does not yet support the given source language");
1120 return std::nullopt;
1124 if (langOpts.OpenCL) {
1132 if (langOpts.SYCLIsDevice &&
1136 if (langOpts.CUDA && langOpts.CUDAIsDevice) {
1138 if (d->
hasAttr<CUDAConstantAttr>())
1140 if (d->
hasAttr<CUDASharedAttr>())
1142 if (d->
hasAttr<CUDADeviceAttr>())
1150 if (langOpts.OpenMP && d && d->
hasAttr<OMPAllocateDeclAttr>())
1164 gv.
setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
1173 auto linkage = cir::GlobalLinkageKind::ExternalWeakLinkage;
1174 func.setLinkage(linkage);
1175 func.setLinkageAttr(
1176 cir::GlobalLinkageKindAttr::get(&cgm.
getMLIRContext(), linkage));
1178 if (!func.isDeclaration())
1179 mlir::SymbolTable::setSymbolVisibility(
1186 for (mlir::Attribute i : indexes) {
1187 auto ind = mlir::cast<mlir::IntegerAttr>(i);
1188 inds.push_back(ind.getValue().getSExtValue());
1194 return view.getSymbol().getValue() == glob.getSymName();
1198 cir::GlobalOp newGlob,
1199 cir::GlobalViewAttr
attr,
1210 mlir::Type newTy = newGlob.getSymType();
1216 return cir::GlobalOffsetAttr::get(
attr.getType(),
attr.getSymbol(),
1217 static_cast<int64_t>(offset));
1219 cir::PointerType newPtrTy;
1222 newPtrTy = cir::PointerType::get(newTy);
1228 attr.getAddressPoint());
1232 cgm.
errorNYI(
"Unhandled type in createNewGlobalView");
1238 mlir::Attribute oldInit) {
1239 if (
auto oldView = mlir::dyn_cast<cir::GlobalViewAttr>(oldInit))
1244 if (mlir::isa<cir::GlobalOffsetAttr>(oldInit))
1247 auto getNewInitElements =
1248 [&](mlir::ArrayAttr oldElements) -> mlir::ArrayAttr {
1250 for (mlir::Attribute elt : oldElements) {
1251 if (
auto view = mlir::dyn_cast<cir::GlobalViewAttr>(elt))
1253 else if (mlir::isa<cir::ConstArrayAttr, cir::ConstRecordAttr>(elt))
1256 newElements.push_back(elt);
1258 return mlir::ArrayAttr::get(cgm.
getBuilder().getContext(), newElements);
1261 if (
auto oldArray = mlir::dyn_cast<cir::ConstArrayAttr>(oldInit)) {
1267 mlir::Attribute oldElts = oldArray.getElts();
1268 if (mlir::isa<mlir::StringAttr>(oldElts))
1270 mlir::Attribute newElements =
1271 getNewInitElements(mlir::cast<mlir::ArrayAttr>(oldElts));
1273 newElements, mlir::cast<cir::ArrayType>(oldArray.getType()));
1275 if (
auto oldRecord = mlir::dyn_cast<cir::ConstRecordAttr>(oldInit)) {
1276 mlir::ArrayAttr newMembers = getNewInitElements(oldRecord.getMembers());
1277 auto recordTy = mlir::cast<cir::RecordType>(oldRecord.getType());
1283 cgm.
errorNYI(
"Unhandled type in getNewInitValue");
1291 assert(oldGV.getSymName() == newGV.getSymName() &&
"symbol names must match");
1293 mlir::Type oldTy = oldGV.getSymType();
1294 mlir::Type newTy = newGV.getSymType();
1299 assert(oldTy != newTy &&
"expected type change in replaceGlobal");
1302 std::optional<mlir::SymbolTable::UseRange> oldSymUses =
1304 for (mlir::SymbolTable::SymbolUse use : *oldSymUses) {
1305 mlir::Operation *userOp = use.getUser();
1307 (mlir::isa<cir::GetGlobalOp, cir::GlobalOp, cir::ConstantOp>(userOp)) &&
1308 "Unexpected user for global op");
1310 if (
auto getGlobalOp = dyn_cast<cir::GetGlobalOp>(use.getUser())) {
1311 mlir::Value useOpResultValue = getGlobalOp.getAddr();
1312 useOpResultValue.setType(cir::PointerType::get(newTy));
1314 mlir::OpBuilder::InsertionGuard guard(builder);
1315 builder.setInsertionPointAfter(getGlobalOp);
1316 mlir::Type ptrTy = builder.getPointerTo(oldTy);
1318 builder.createBitcast(getGlobalOp->getLoc(), useOpResultValue, ptrTy);
1319 useOpResultValue.replaceAllUsesExcept(
cast,
cast.getDefiningOp());
1320 }
else if (
auto glob = dyn_cast<cir::GlobalOp>(userOp)) {
1321 if (
auto init = glob.getInitialValue()) {
1322 mlir::Attribute nw =
getNewInitValue(*
this, newGV, oldTy, init.value());
1323 glob.setInitialValueAttr(nw);
1325 }
else if (
auto c = dyn_cast<cir::ConstantOp>(userOp)) {
1326 mlir::Attribute init =
getNewInitValue(*
this, newGV, oldTy, c.getValue());
1327 auto typedAttr = mlir::cast<mlir::TypedAttr>(init);
1328 mlir::OpBuilder::InsertionGuard guard(builder);
1329 builder.setInsertionPointAfter(c);
1330 auto newUser = cir::ConstantOp::create(builder, c.getLoc(), typedAttr);
1331 c.replaceAllUsesWith(newUser.getOperation());
1362 StringRef mangledName, mlir::Type ty,
LangAS langAS, mlir::Location loc,
1366 cir::GlobalOp entry;
1369 errorNYI(loc,
"getOrCreateCIRGlobal: global with non-GlobalOp type");
1376 mlir::ptr::MemorySpaceAttrInterface entryCIRAS = entry.getAddrSpaceAttr();
1379 if (weakRefReferences.erase(entry) && d && !d->
hasAttr<WeakAttr>())
1380 entry.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
1384 if (langOpts.OpenMP && !langOpts.OpenMPSimd && d)
1387 if (entry.getSymType() == ty &&
1398 if (isForDefinition && !entry.isDeclaration()) {
1399 errorNYI(loc,
"getOrCreateCIRGlobal: global with conflicting type");
1407 if (!isForDefinition)
1414 bool isConstant =
false;
1416 QualType declType = d->
getType();
1431 mlir::ptr::MemorySpaceAttrInterface declCIRAS =
1436 cir::GlobalOp gv =
createGlobalOp(loc, mangledName, ty, isConstant, declCIRAS,
1437 entry.getOperation());
1457 if (langOpts.OpenMP && !langOpts.OpenMPSimd)
1460 gv.setAlignmentAttr(
getSize(astContext.getDeclAlign(d)));
1471 if (astContext.isMSStaticDataMemberInlineDefinition(d))
1473 "getOrCreateCIRGlobal: MS static data member inline definition");
1477 if (
const SectionAttr *sa = d->
getAttr<SectionAttr>())
1478 gv.setSectionAttr(builder.getStringAttr(sa->getName()));
1482 if (
getTriple().getArch() == llvm::Triple::xcore)
1484 "getOrCreateCIRGlobal: XCore specific ABI requirements");
1494 "getOrCreateCIRGlobal: external const declaration with initializer");
1513 const auto *aa = vd->
getAttr<AliasAttr>();
1514 assert(aa &&
"No alias?");
1521 if (
const auto *fd = dyn_cast<FunctionDecl>(vd)) {
1522 auto fn = dyn_cast<cir::FuncOp>(entry);
1524 if (fn && fn.getFunctionType() ==
convertType(fd->getType()))
1526 }
else if (
auto gv = dyn_cast<cir::GlobalOp>(entry)) {
1532 "weakref target already declared with a different type");
1536 mlir::Operation *aliasee;
1537 if (
const auto *fd = dyn_cast<FunctionDecl>(vd)) {
1541 fn.setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
1548 gv.setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
1552 weakRefReferences.insert(aliasee);
1584 mlir::Type ptrTy = builder.getPointerTo(g.getSymType(), g.getAddrSpaceAttr());
1585 mlir::Value addr = cir::GetGlobalOp::create(
1588 g.getDynamicInitGuard().has_value() &&
1598 auto ptrTy = mlir::cast<cir::PointerType>(addr.getType());
1599 mlir::ptr::MemorySpaceAttrInterface declAS =
1601 if (ptrTy.getAddrSpace() == declAS)
1603 return builder.createAddrSpaceCast(
1604 addr, builder.getPointerTo(ptrTy.getPointee(), declAS));
1612 cir::PointerType ptrTy =
1613 builder.getPointerTo(globalOp.getSymType(), globalOp.getAddrSpaceAttr());
1614 return builder.getGlobalViewAttr(ptrTy, globalOp);
1618 assert((mlir::isa<cir::FuncOp>(gv.getOperation()) ||
1619 !gv.isDeclarationForLinker()) &&
1620 "Only globals with definition can force usage.");
1625 assert(!gv.isDeclarationForLinker() &&
1626 "Only globals with definition can force usage.");
1631 cir::CIRGlobalValueInterface gv) {
1632 assert((mlir::isa<cir::FuncOp>(gv.getOperation()) ||
1633 !gv.isDeclarationForLinker()) &&
1634 "Only globals with definition can force usage.");
1642 std::vector<cir::CIRGlobalValueInterface> &list) {
1647 mlir::Location loc = builder.getUnknownLoc();
1652 usedArray.resize(list.size());
1653 for (
auto [i, op] : llvm::enumerate(list)) {
1654 usedArray[i] = cir::GlobalViewAttr::get(
1655 voidPtrTy, mlir::FlatSymbolRefAttr::get(op.getNameAttr()));
1658 cir::ArrayType arrayTy = cir::ArrayType::get(voidPtrTy, usedArray.size());
1660 cir::ConstArrayAttr initAttr = cir::ConstArrayAttr::get(
1661 arrayTy, mlir::ArrayAttr::get(&cgm.
getMLIRContext(), usedArray));
1664 loc, name, arrayTy,
false,
1666 gv.setLinkage(cir::GlobalLinkageKind::AppendingLinkage);
1667 gv.setInitialValueAttr(initAttr);
1668 gv.setSectionAttr(builder.getStringAttr(
"llvm.metadata"));
1685 "emitGlobalVarDefinition: emit OpenMP global variable");
1692 bool isDefinitionAvailableExternally =
1697 if (isDefinitionAvailableExternally &&
1705 mlir::Attribute init;
1706 bool needsGlobalCtor =
false;
1707 bool needsGlobalDtor =
1708 !isDefinitionAvailableExternally &&
1713 std::optional<ConstantEmitter> emitter;
1718 bool isCUDASharedVar =
1723 bool isCUDAShadowVar =
1725 (vd->
hasAttr<CUDAConstantAttr>() || vd->
hasAttr<CUDADeviceAttr>() ||
1726 vd->
hasAttr<CUDASharedAttr>());
1727 bool isCUDADeviceShadowVar =
1733 (isCUDASharedVar || isCUDAShadowVar || isCUDADeviceShadowVar)) {
1735 }
else if (vd->
hasAttr<LoaderUninitializedAttr>()) {
1737 "emitGlobalVarDefinition: loader uninitialized attribute");
1738 }
else if (!initExpr) {
1751 emitter.emplace(*
this);
1752 mlir::Attribute initializer = emitter->tryEmitForInitializer(*initDecl);
1761 "emitGlobalVarDefinition: flexible array initializer");
1763 if (!isDefinitionAvailableExternally)
1764 needsGlobalCtor =
true;
1767 "emitGlobalVarDefinition: static initializer");
1778 mlir::Type initType;
1779 if (mlir::isa<mlir::SymbolRefAttr>(init)) {
1782 "emitGlobalVarDefinition: global initializer is a symbol reference");
1785 assert(mlir::isa<mlir::TypedAttr>(init) &&
"This should have a type");
1786 auto typedInitAttr = mlir::cast<mlir::TypedAttr>(init);
1787 initType = typedInitAttr.getType();
1789 assert(!mlir::isa<mlir::NoneType>(initType) &&
"Should have a type by now");
1795 if (!gv || gv.getSymType() != initType) {
1797 "emitGlobalVarDefinition: global initializer with type mismatch");
1803 if (vd->
hasAttr<AnnotateAttr>())
1816 if (langOpts.CUDA) {
1817 if (langOpts.CUDAIsDevice) {
1820 if (linkage != cir::GlobalLinkageKind::InternalLinkage &&
1822 (vd->
hasAttr<CUDADeviceAttr>() || vd->
hasAttr<CUDAConstantAttr>() ||
1825 gv->setAttr(cir::CUDAExternallyInitializedAttr::getMnemonic(),
1838 emitter->finalize(gv);
1842 gv.setConstant((vd->
hasAttr<CUDAConstantAttr>() && langOpts.CUDAIsDevice) ||
1843 (!needsGlobalCtor && !needsGlobalDtor &&
1848 if (
const SectionAttr *sa = vd->
getAttr<SectionAttr>()) {
1851 gv.setConstant(
true);
1856 gv.setAlignmentAttr(
getSize(astContext.getDeclAlign(vd)));
1859 gv.setLinkage(linkage);
1863 if (linkage == cir::GlobalLinkageKind::CommonLinkage) {
1865 gv.setConstant(
false);
1870 std::optional<mlir::Attribute> initializer = gv.getInitialValue();
1871 if (initializer && !
getBuilder().isNullValue(*initializer))
1872 gv.setLinkage(cir::GlobalLinkageKind::WeakAnyLinkage);
1875 setNonAliasAttributes(vd, gv);
1883 if (needsGlobalCtor || needsGlobalDtor) {
1906 cir::GlobalLinkageKind::AvailableExternallyLinkage)
1912 if (fd->isInlineBuiltinDeclaration())
1915 if (codeGenOpts.OptimizationLevel == 0 && !fd->hasAttr<AlwaysInlineAttr>())
1920 if (
const Module *m = fd->getOwningModule();
1922 getASTContext().getCurrentNamedModule() != m->getTopLevelModule()) {
1932 if (!fd->isTemplateInstantiation() || !fd->hasAttr<AlwaysInlineAttr>()) {
1937 if (fd->hasAttr<NoInlineAttr>())
1948 mlir::Operation *op) {
1950 if (
const auto *fd = dyn_cast<FunctionDecl>(
decl)) {
1954 if (
const auto *method = dyn_cast<CXXMethodDecl>(
decl)) {
1958 abi->emitCXXStructor(gd);
1959 else if (fd->isMultiVersion())
1960 errorNYI(method->getSourceRange(),
"multiversion functions");
1964 if (method->isVirtual())
1970 if (fd->isMultiVersion())
1971 errorNYI(fd->getSourceRange(),
"multiversion functions");
1976 if (
const auto *vd = dyn_cast<VarDecl>(
decl))
1979 llvm_unreachable(
"Invalid argument to CIRGenModule::emitGlobalDefinition");
1993 astContext.getAsConstantArrayType(e->
getType());
1994 uint64_t finalSize = cat->getZExtSize();
1995 str.resize(finalSize);
1997 mlir::Type eltTy =
convertType(cat->getElementType());
1998 return builder.getString(str, eltTy, finalSize,
false);
2003 auto arrayEltTy = mlir::cast<cir::IntType>(arrayTy.getElementType());
2005 uint64_t arraySize = arrayTy.getSize();
2007 assert(arraySize > literalSize &&
2008 "wide string literal array size must have room for null terminator?");
2012 bool isAllZero =
true;
2013 for (
unsigned i = 0; i < literalSize; ++i) {
2021 return cir::ZeroAttr::get(arrayTy);
2025 elements.reserve(arraySize);
2026 for (
unsigned i = 0; i < literalSize; ++i)
2027 elements.push_back(cir::IntAttr::get(
2028 arrayEltTy, llvm::APInt(arrayEltTy.getWidth(), e->
getCodeUnit(i))));
2030 auto elementsAttr = mlir::ArrayAttr::get(&
getMLIRContext(), elements);
2031 return builder.getConstArray(elementsAttr, arrayTy);
2041 if (
auto globalOp = dyn_cast_or_null<cir::GlobalOp>(op)) {
2042 globalOp.setSelfComdat();
2045 funcOp.setSelfComdat();
2051 genTypes.updateCompletedType(td);
2055 replacements[name] = op;
2061 for (mlir::Operation *user : users) {
2062 auto call = mlir::dyn_cast<cir::CallOp>(user);
2066 for (
auto [argOp, fnArgType] :
2067 llvm::zip(call.getArgs(), newF.getFunctionType().getInputs())) {
2068 if (argOp.getType() != fnArgType)
2077void CIRGenModule::applyReplacements() {
2078 if (replacements.empty())
2084 llvm::DenseMap<mlir::StringAttr, llvm::SetVector<mlir::Operation *>> users;
2085 for (
auto &i : replacements)
2086 users.try_emplace(mlir::StringAttr::get(&
getMLIRContext(), i.first));
2089 module->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
2090 auto collect = [&](mlir::Attribute attr) {
2091 attr.walk<mlir::WalkOrder::PreOrder>(
2092 [&](mlir::SymbolRefAttr ref) {
2093 auto it = users.find(ref.getRootReference());
2094 if (it != users.end())
2095 it->second.insert(op);
2096 return mlir::WalkResult::skip();
2098 [&](mlir::Type
type) {
2099 return mlir::isa<cir::CIRDialect>(
type.getDialect())
2100 ? mlir::WalkResult::skip()
2101 : mlir::WalkResult::
advance();
2104 collect(op->getRawDictionaryAttrs());
2105 op->getName().walkInherentAttrs(
2106 op, [&](llvm::StringRef, mlir::Attribute &attr) { collect(attr); });
2108 if (op != module.getOperation() &&
2109 op->hasTrait<mlir::OpTrait::SymbolTable>())
2110 return mlir::WalkResult::skip();
2111 return mlir::WalkResult::advance();
2114 for (
auto &i : replacements) {
2115 StringRef mangledName = i.first;
2116 mlir::Operation *replacement = i.second;
2117 mlir::Operation *entry = getGlobalValue(mangledName);
2122 auto newF = dyn_cast<cir::FuncOp>(replacement);
2125 errorNYI(replacement->getLoc(),
"replacement is not a function");
2129 auto oldIt = users.find(oldF.getSymNameAttr());
2130 assert(oldIt != users.end() &&
"replaced function was not collected");
2131 llvm::ArrayRef<mlir::Operation *> oldUsers = oldIt->second.getArrayRef();
2133 "call argument types do not match replacement function");
2136 for (mlir::Operation *user : oldUsers)
2137 (void)mlir::SymbolTable::replaceAllSymbolUses(oldF, newF.getSymNameAttr(),
2140 auto newIt = users.find(newF.getSymNameAttr());
2141 if (newIt != users.end())
2142 newIt->second.set_union(oldIt->second);
2144 newF->moveBefore(oldF);
2145 eraseGlobalSymbol(oldF);
2151 mlir::Location loc, StringRef name, mlir::Type ty,
2153 auto gv = mlir::dyn_cast_or_null<cir::GlobalOp>(
getGlobalValue(name));
2157 if (gv.getSymType() == ty)
2163 assert(gv.isDeclaration() &&
"Declaration has wrong type!");
2165 errorNYI(loc,
"createOrReplaceCXXRuntimeVariable: declaration exists with "
2176 mlir::SymbolTable::setSymbolVisibility(gv,
2180 !gv.hasAvailableExternallyLinkage()) {
2184 gv.setAlignmentAttr(
getSize(alignment));
2189cir::GlobalLinkageKind
2193 return cir::GlobalLinkageKind::InternalLinkage;
2196 return cir::GlobalLinkageKind::WeakAnyLinkage;
2200 return cir::GlobalLinkageKind::LinkOnceAnyLinkage;
2205 return cir::GlobalLinkageKind::AvailableExternallyLinkage;
2219 return !astContext.getLangOpts().AppleKext
2220 ? cir::GlobalLinkageKind::LinkOnceODRLinkage
2221 : cir::GlobalLinkageKind::InternalLinkage;
2235 return cir::GlobalLinkageKind::ExternalLinkage;
2238 return dd->
hasAttr<CUDAGlobalAttr>()
2239 ? cir::GlobalLinkageKind::ExternalLinkage
2240 : cir::GlobalLinkageKind::InternalLinkage;
2241 return cir::GlobalLinkageKind::WeakODRLinkage;
2249 return cir::GlobalLinkageKind::CommonLinkage;
2255 if (dd->
hasAttr<SelectAnyAttr>())
2256 return cir::GlobalLinkageKind::WeakODRLinkage;
2260 return cir::GlobalLinkageKind::ExternalLinkage;
2272 mlir::Operation *old, cir::FuncOp newFn) {
2274 auto oldFn = mlir::dyn_cast<cir::FuncOp>(old);
2287 newFn.setNoProto(oldFn.getNoProto());
2290 std::optional<mlir::SymbolTable::UseRange> symUses =
2291 oldFn.getSymbolUses(oldFn->getParentOp());
2296 for (
const mlir::SymbolTable::SymbolUse &use : symUses.value()) {
2297 mlir::OpBuilder::InsertionGuard guard(builder);
2299 if (
auto noProtoCallOp = mlir::dyn_cast<cir::CallOp>(use.getUser())) {
2300 builder.setInsertionPoint(noProtoCallOp);
2303 cir::FuncType newFnType = newFn.getFunctionType();
2304 mlir::OperandRange callOperands = noProtoCallOp.getOperands();
2305 bool returnTypeMatches =
2306 newFnType.hasVoidReturn()
2307 ? noProtoCallOp.getNumResults() == 0
2308 : noProtoCallOp.getNumResults() == 1 &&
2309 noProtoCallOp.getResultTypes().front() ==
2310 newFnType.getReturnType();
2311 bool typesMatch = !newFn.getNoProto() && returnTypeMatches &&
2312 callOperands.size() == newFnType.getNumInputs();
2313 for (
unsigned i = 0, e = newFnType.getNumInputs(); typesMatch && i != e;
2315 if (callOperands[i].
getType() != newFnType.getInput(i))
2319 cir::CallOp realCallOp;
2323 builder.createCallOp(noProtoCallOp.getLoc(), newFn, callOperands);
2331 cir::FuncType origFnType = oldFn.getFunctionType();
2332 cir::FuncType callFnType =
2334 ? cir::FuncType::get(llvm::to_vector(callOperands.getTypes()),
2335 origFnType.getReturnType(),
2338 mlir::Value addr = cir::GetGlobalOp::create(
2339 builder, noProtoCallOp.getLoc(), cir::PointerType::get(newFnType),
2340 newFn.getSymName());
2341 mlir::Value casted =
2342 builder.createBitcast(addr, cir::PointerType::get(callFnType));
2343 realCallOp = builder.createIndirectCallOp(
2344 noProtoCallOp.getLoc(), casted, callFnType, callOperands);
2348 for (mlir::NamedAttribute
attr : noProtoCallOp->getAttrs())
2349 if (
attr.getName() != cir::CIRDialect::getCalleeAttrName())
2350 realCallOp->setAttr(
attr.getName(),
attr.getValue());
2353 noProtoCallOp.replaceAllUsesWith(realCallOp);
2354 noProtoCallOp.erase();
2355 }
else if (
auto getGlobalOp =
2356 mlir::dyn_cast<cir::GetGlobalOp>(use.getUser())) {
2363 mlir::Value res = getGlobalOp.getAddr();
2364 const mlir::Type oldResTy = res.getType();
2365 const auto newPtrTy = cir::PointerType::get(
2366 newFn.getFunctionType(),
2367 mlir::cast<cir::PointerType>(oldResTy).getAddrSpace());
2368 if (oldResTy != newPtrTy) {
2369 res.setType(newPtrTy);
2370 builder.setInsertionPointAfter(getGlobalOp.getOperation());
2371 mlir::Value castRes =
2372 cir::CastOp::create(builder, getGlobalOp.getLoc(), oldResTy,
2373 cir::CastKind::bitcast, res);
2374 res.replaceAllUsesExcept(castRes, castRes.getDefiningOp());
2376 }
else if (mlir::isa<cir::GlobalOp>(use.getUser())) {
2382 "replaceUsesOfNonProtoTypeWithRealFunction: unexpected use type");
2387cir::GlobalLinkageKind
2389 GVALinkage linkage = astContext.GetGVALinkageForVariable(vd);
2396 GVALinkage linkage = astContext.GetGVALinkageForFunction(d);
2398 if (
const auto *dtor = dyn_cast<CXXDestructorDecl>(d))
2407 StringRef globalName,
CharUnits alignment) {
2410 mlir::ptr::MemorySpaceAttrInterface addrSpace =
2420 gv.setAlignmentAttr(cgm.
getSize(alignment));
2422 cir::GlobalLinkageKindAttr::get(cgm.
getBuilder().getContext(), lt));
2424 gv.setUnnamedAddr(
true);
2426 if (gv.isWeakForLinker()) {
2427 assert(cgm.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
2430 cgm.
setDSOLocal(
static_cast<mlir::Operation *
>(gv));
2451 std::string result =
2462 astContext.getAlignOfGlobalVarInChars(s->
getType(),
nullptr);
2470 if (!gv.getAlignment() ||
2471 uint64_t(alignment.
getQuantity()) > *gv.getAlignment())
2472 gv.setAlignmentAttr(
getSize(alignment));
2477 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(s) &&
2480 "getGlobalForStringLiteral: mangle string literals");
2490 : builder.getUnknownLoc();
2491 auto typedC = llvm::cast<mlir::TypedAttr>(c);
2493 cir::GlobalLinkageKind::PrivateLinkage, *
this,
2494 uniqueName, alignment);
2508 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(gv.getSymType());
2509 assert(arrayTy &&
"String literal must be array");
2511 arrayTy.getElementType(),
2514 return builder.getGlobalViewAttr(ptrTy, gv);
2518 StringRef str, StringRef name) {
2519 mlir::Attribute init = builder.getString(str,
convertType(astContext.CharTy),
2525 cir::GlobalLinkageKind::PrivateLinkage, *
this,
2530mlir::ptr::MemorySpaceAttrInterface
2561 "emitExplicitCastExprType");
2567 auto ty = mlir::cast<cir::MethodType>(
convertType(destTy));
2568 return builder.getNullMethodAttr(ty);
2571 auto ty = mlir::cast<cir::DataMemberType>(
convertType(destTy));
2572 return builder.getNullDataMemberAttr(ty);
2583 if (
const auto *methodDecl = dyn_cast<CXXMethodDecl>(
decl)) {
2585 if (methodDecl->isVirtual())
2586 return cir::ConstantOp::create(
2587 builder, loc,
getCXXABI().buildVirtualMethodAttr(ty, methodDecl));
2593 return cir::ConstantOp::create(builder, loc,
2594 builder.getMethodAttr(ty, methodFuncOp));
2609 assert(
fieldDecl->getParent() == destClass &&
2610 "scalar member pointer should be relative to the declaring class");
2612 astContext.toCharUnitsFromBits(astContext.getFieldOffset(
fieldDecl))
2614 return cir::ConstantOp::create(builder, loc,
2615 cir::DataMemberOffsetAttr::get(ty, offset));
2618 std::optional<llvm::SmallVector<int32_t>> path =
2622 return cir::ConstantOp::create(builder, loc,
2623 builder.getDataMemberAttr(ty, *path));
2626std::optional<llvm::SmallVector<int32_t>>
2634 if (
const auto *indirectField = dyn_cast<IndirectFieldDecl>(
decl)) {
2636 for (
const NamedDecl *nd : indirectField->chain()) {
2638 if (!findFieldMemberPath(currentClass, field, path))
2639 return std::nullopt;
2640 currentClass = field->getType()->getAsCXXRecordDecl();
2646 return std::nullopt;
2650bool CIRGenModule::findFieldMemberPath(
const CXXRecordDecl *currentClass,
2660 if (currentClass->
isUnion()) {
2666 "data member pointer for non-zero-initializable union");
2673 path.push_back(fieldIdx);
2681 for (
const CXXBaseSpecifier &base : currentClass->
bases()) {
2682 const auto *baseDecl =
2685 if (base.isVirtual()) {
2690 llvm::SmallVector<int32_t> discardedPath;
2691 if (findFieldMemberPath(baseDecl, field, discardedPath)) {
2693 "data member pointer through virtual base");
2706 path.push_back(baseFieldIdx);
2707 if (findFieldMemberPath(baseDecl, field, path))
2735 if (
auto *oid = dyn_cast<ObjCImplDecl>(
decl))
2736 errorNYI(oid->getSourceRange(),
"emitDeclConext: ObjCImplDecl");
2746 if (
decl->isTemplated())
2749 switch (
decl->getKind()) {
2752 decl->getDeclKindName());
2755 case Decl::CXXConversion:
2756 case Decl::CXXMethod:
2757 case Decl::Function: {
2760 if (!fd->isConsteval())
2765 case Decl::Import: {
2774 if (!importedModules.insert(mod))
2776 moduleImportLocs[mod] = importDecl->getLocation();
2793 visited.insert(mod);
2794 stack.push_back(mod);
2796 while (!stack.empty()) {
2798 if (!emittedModuleInitializers.insert(cur).second)
2801 for (
Decl *initializer : astContext.getModuleInitializers(cur))
2808 if (submodule->IsExplicit)
2811 if (visited.insert(submodule).second)
2812 stack.push_back(submodule);
2823 case Decl::Decomposition:
2824 case Decl::VarTemplateSpecialization: {
2826 if (
auto *decomp = dyn_cast<DecompositionDecl>(
decl))
2827 for (
auto *binding : decomp->flat_bindings())
2828 if (
auto *holdingVar = binding->getHoldingVar())
2832 case Decl::OpenACCRoutine:
2835 case Decl::OpenACCDeclare:
2838 case Decl::OMPThreadPrivate:
2841 case Decl::OMPGroupPrivate:
2844 case Decl::OMPAllocate:
2847 case Decl::OMPCapturedExpr:
2850 case Decl::OMPDeclareReduction:
2853 case Decl::OMPDeclareMapper:
2856 case Decl::OMPRequires:
2861 case Decl::UsingDirective:
2862 case Decl::UsingEnum:
2863 case Decl::NamespaceAlias:
2865 case Decl::TypeAlias:
2872 case Decl::IndirectField:
2876 case Decl::ClassTemplate:
2878 case Decl::CXXDeductionGuide:
2880 case Decl::ExplicitInstantiation:
2881 case Decl::FunctionTemplate:
2882 case Decl::StaticAssert:
2883 case Decl::TypeAliasTemplate:
2884 case Decl::UsingShadow:
2885 case Decl::VarTemplate:
2886 case Decl::VarTemplatePartialSpecialization:
2889 case Decl::CXXConstructor:
2892 case Decl::CXXDestructor:
2897 case Decl::LinkageSpec:
2898 case Decl::Namespace:
2902 case Decl::ClassTemplateSpecialization:
2903 case Decl::CXXRecord: {
2906 for (
auto *childDecl : crd->
decls())
2912 case Decl::FileScopeAsm:
2914 if (langOpts.CUDA && langOpts.CUDAIsDevice)
2917 if (langOpts.OpenMPIsTargetDevice)
2920 if (langOpts.SYCLIsDevice)
2923 std::string line = file_asm->getAsmString();
2924 globalScopeAsm.push_back(builder.getStringAttr(line));
2931 op.setInitialValueAttr(value);
2945 md->getParent()->getNumVBases() == 0)
2947 "getAddrAndTypeOfCXXStructor: MS ABI complete destructor");
2958 false, isForDefinition);
2960 return {fnType, fn};
2964 mlir::Type funcType,
bool forVTable,
2968 "consteval function should never be emitted");
2978 if (
const auto *dd = dyn_cast<CXXDestructorDecl>(gd.
getDecl())) {
2981 dd->getParent()->getNumVBases() == 0)
2983 "getAddrOfFunction: MS ABI complete destructor");
2989 false, isForDefinition);
2991 if (langOpts.CUDA && !langOpts.CUDAIsDevice &&
2997 bool isHIPHandle = mlir::isa<cir::GlobalOp>(*handle);
2998 if (isForDefinition || isHIPHandle)
3000 return mlir::dyn_cast<cir::FuncOp>(*handle);
3009 llvm::raw_svector_ostream
out(buffer);
3018 assert(ii &&
"Attempt to mangle unnamed decl.");
3020 const auto *fd = dyn_cast<FunctionDecl>(nd);
3024 }
else if (fd && fd->hasAttr<CUDAGlobalAttr>() &&
3028 DeviceKernelAttr::isOpenCLSpelling(
3029 fd->getAttr<DeviceKernelAttr>()) &&
3046 if (
const auto *fd = dyn_cast<FunctionDecl>(nd)) {
3047 if (fd->isMultiVersion()) {
3049 "getMangledName: multi-version functions");
3057 "getMangledName: GPU relocatable device code");
3059 return std::string(
out.str());
3062static FunctionDecl *
3077 if (
auto *methodDecl = dyn_cast<CXXMethodDecl>(protoFunc);
3078 methodDecl && methodDecl->isImplicitObjectMemberFunction()) {
3080 paramTypes.insert(paramTypes.begin(), methodDecl->getThisType());
3083 fpt->getExtProtoInfo());
3094 params.reserve(fpt->getNumParams());
3097 for (
unsigned i = 0, e = fpt->getNumParams(); i != e; ++i) {
3101 nullptr, fpt->getParamType(i),
nullptr,
3104 params.push_back(parm);
3107 tempFunc->setParams(params);
3132 if (
const auto *cd = dyn_cast<CXXConstructorDecl>(canonicalGd.
getDecl())) {
3135 "getMangledName: C++ constructor without variants");
3144 if (!langOpts.CUDAIsDevice || !astContext.mayExternalize(gd.
getDecl())) {
3145 auto foundName = mangledDeclNames.find(canonicalGd);
3146 if (foundName != mangledDeclNames.end())
3147 return foundName->second;
3154 auto result = manglings.insert(std::make_pair(mangledName, gd));
3155 return mangledDeclNames[canonicalGd] = result.first->first();
3159 assert(!d->
getInit() &&
"Cannot emit definite definitions here!");
3168 auto gvOp = dyn_cast<cir::GlobalOp>(gv);
3171 "emitTentativeDefinition: name already used by a non-global");
3174 if (!gvOp.isDeclaration())
3191 if (langOpts.EmitAllDecls)
3194 const auto *vd = dyn_cast<VarDecl>(global);
3196 ((codeGenOpts.KeepPersistentStorageVariables &&
3197 (vd->getStorageDuration() ==
SD_Static ||
3198 vd->getStorageDuration() ==
SD_Thread)) ||
3199 (codeGenOpts.KeepStaticConsts && vd->getStorageDuration() ==
SD_Static &&
3200 vd->getType().isConstQualified())))
3213 if (langOpts.OpenMP >= 50 && !langOpts.OpenMPSimd) {
3214 std::optional<OMPDeclareTargetDeclAttr *> activeAttr =
3215 OMPDeclareTargetDeclAttr::getActiveAttr(global);
3216 if (!activeAttr || (*activeAttr)->getLevel() != (
unsigned)-1)
3220 const auto *fd = dyn_cast<FunctionDecl>(global);
3227 if (fd->hasAttr<TargetVersionAttr>() && !fd->isMultiVersion())
3231 if (langOpts.SYCLIsDevice && fd->hasAttr<SYCLKernelEntryPointAttr>())
3234 const auto *vd = dyn_cast<VarDecl>(global);
3236 if (astContext.getInlineVariableDefinitionKind(vd) ==
3244 if (langOpts.OpenMP && langOpts.OpenMPUseTLS &&
3245 astContext.getTargetInfo().isTLSSupported() &&
isa<VarDecl>(global) &&
3247 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(global))
3250 assert((fd || vd) &&
3251 "Only FunctionDecl and VarDecl should hit this path so far.");
3256 cir::CIRGlobalValueInterface gv) {
3257 if (gv.hasLocalLinkage())
3260 if (!gv.hasDefaultVisibility() && !gv.hasExternalWeakLinkage())
3268 const llvm::Triple &tt = cgm.
getTriple();
3270 if (tt.isOSCygMing()) {
3279 cgm.
errorNYI(
"shouldAssumeDSOLocal: MinGW");
3285 if (tt.isOSBinFormatCOFF() && gv.hasExternalWeakLinkage())
3293 if (tt.isOSBinFormatCOFF() || (tt.isOSWindows() && tt.isOSBinFormatMachO()))
3297 if (!tt.isOSBinFormatELF())
3302 if (rm != llvm::Reloc::Static && !lOpts.PIE) {
3308 auto func = dyn_cast<cir::FuncOp>(gv.getOperation());
3309 if (!func || func.getAliasee() || !gv.canBenefitFromLocalAlias())
3311 return !(lOpts.SemanticInterposition || lOpts.HalfNoSemanticInterposition);
3315 if (!gv.isDeclarationForLinker())
3321 if (rm == llvm::Reloc::PIC_ && gv.hasExternalWeakLinkage())
3328 if (cgOpts.DirectAccessExternalData) {
3334 if (
auto globalOp = dyn_cast<cir::GlobalOp>(gv.getOperation())) {
3360 if (gv.hasLocalLinkage()) {
3361 gv.setGlobalVisibility(cir::VisibilityKind::Default);
3376 d->
hasAttr<OMPDeclareTargetDeclAttr>() &&
3377 d->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
3378 OMPDeclareTargetDeclAttr::DT_NoHost &&
3380 llvm_unreachable(
"setGlobalVisibility: OpenMP is NYI");
3389 !d->
hasAttr<OMPDeclareTargetDeclAttr>()) {
3390 bool needsProtected =
false;
3394 }
else if (
const auto *vd = dyn_cast<VarDecl>(d)) {
3395 needsProtected = vd->hasAttr<CUDADeviceAttr>() ||
3396 vd->hasAttr<CUDAConstantAttr>() ||
3397 vd->getType()->isCUDADeviceBuiltinSurfaceType() ||
3398 vd->getType()->isCUDADeviceBuiltinTextureType();
3400 if (needsProtected) {
3401 gv.setGlobalVisibility(cir::VisibilityKind::Protected);
3407 gv.setGlobalVisibility(cir::VisibilityKind::Hidden);
3414 !gv.isDeclarationForLinker())
3423 if (
auto globalValue = dyn_cast<cir::CIRGlobalValueInterface>(op))
3442 auto res = manglings.find(mangledName);
3443 if (res == manglings.end())
3445 result = res->getValue();
3450 return llvm::StringSwitch<cir::TLSModel>(S)
3451 .Case(
"global-dynamic", cir::TLSModel::GeneralDynamic)
3452 .Case(
"local-dynamic", cir::TLSModel::LocalDynamic)
3453 .Case(
"initial-exec", cir::TLSModel::InitialExec)
3454 .Case(
"local-exec", cir::TLSModel::LocalExec);
3460 return cir::TLSModel::GeneralDynamic;
3462 return cir::TLSModel::LocalDynamic;
3464 return cir::TLSModel::InitialExec;
3466 return cir::TLSModel::LocalExec;
3468 llvm_unreachable(
"Invalid TLS model!");
3472 bool isExtendingDecl) {
3473 assert(d.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
3482 global.setTlsModel(tlm);
3492 if (isExtendingDecl)
3500 cir::FuncOp func,
bool isThunk) {
3502 cir::CallingConv callingConv;
3509 mlir::NamedAttrList pal{};
3510 std::vector<mlir::NamedAttrList> argAttrs(info.arguments().size());
3511 mlir::NamedAttrList retAttrs{};
3513 retAttrs, callingConv,
3516 for (mlir::NamedAttribute
attr : pal)
3517 func->setAttr(
attr.getName(),
attr.getValue());
3519 llvm::for_each(llvm::enumerate(argAttrs), [func](
auto idx_arg_pair) {
3520 mlir::function_interface_impl::setArgAttrs(func, idx_arg_pair.index(),
3521 idx_arg_pair.value());
3523 if (!retAttrs.empty())
3524 mlir::function_interface_impl::setResultAttrs(func, 0, retAttrs);
3528 func.setCallingConv(callingConv);
3533 bool isIncompleteFunction,
3541 if (!isIncompleteFunction)
3543 getTypes().arrangeGlobalDeclaration(globalDecl),
3549 if (!isThunk &&
getCXXABI().hasThisReturn(globalDecl) &&
3551 func.setArgAttr(0, mlir::LLVM::LLVMDialect::getReturnedAttrName(),
3554 if (!isIncompleteFunction && func.isDeclaration())
3559 if (
const auto *errorAttr = funcDecl->getAttr<ErrorAttr>()) {
3560 if (errorAttr->isError())
3561 func->setAttr(cir::CIRDialect::getDontCallErrorAttrName(),
3563 errorAttr->getUserDiagnostic()));
3564 else if (errorAttr->isWarning())
3565 func->setAttr(cir::CIRDialect::getDontCallWarnAttrName(),
3567 errorAttr->getUserDiagnostic()));
3574 if (funcDecl->isInlineBuiltinDeclaration()) {
3576 bool hasBody = funcDecl->
hasBody(fdBody);
3578 assert(hasBody &&
"Inline builtin declarations should always have an "
3583 if (funcDecl->isReplaceableGlobalAllocationFunction()) {
3586 func->setAttr(cir::CIRDialect::getNoBuiltinAttrName(),
3591 func.setUnnamedAddr(
true);
3592 else if (
const auto *md = dyn_cast<CXXMethodDecl>(funcDecl))
3593 if (md->isVirtual())
3594 func.setUnnamedAddr(
true);
3600 if ((!
decl || !
decl->hasAttr<NoUwtableAttr>()) && codeGenOpts.UnwindTables)
3601 f.setUwtable(
static_cast<cir::UnwindTableKind
>(codeGenOpts.UnwindTables));
3606 f->setAttr(cir::CIRDialect::getNoThrowAttrName(),
3609 std::optional<cir::InlineKind> existingInlineKind = f.getInlineKind();
3611 existingInlineKind && *existingInlineKind == cir::InlineKind::NoInline;
3612 bool isAlwaysInline = existingInlineKind &&
3613 *existingInlineKind == cir::InlineKind::AlwaysInline;
3617 if (!isAlwaysInline &&
3622 f.setInlineKind(cir::InlineKind::NoInline);
3634 bool shouldAddOptNone =
3635 !codeGenOpts.DisableO0ImplyOptNone && codeGenOpts.OptimizationLevel == 0;
3637 shouldAddOptNone &= !
decl->hasAttr<MinSizeAttr>();
3638 shouldAddOptNone &= !
decl->hasAttr<AlwaysInlineAttr>();
3641 if ((shouldAddOptNone ||
decl->hasAttr<OptimizeNoneAttr>()) &&
3644 f->setAttr(cir::CIRDialect::getOptNoneAttrName(),
3648 f.setInlineKind(cir::InlineKind::NoInline);
3652 if (
decl->hasAttr<NakedAttr>())
3653 f->setAttr(cir::CIRDialect::getNakedAttrName(),
3657 f->removeAttr(cir::CIRDialect::getOptimizeForSizeAttrName());
3658 f->removeAttr(cir::CIRDialect::getMinSizeAttrName());
3659 }
else if (
decl->hasAttr<NakedAttr>()) {
3661 f->setAttr(cir::CIRDialect::getNakedAttrName(),
3663 f.setInlineKind(cir::InlineKind::NoInline);
3664 }
else if (
decl->hasAttr<NoDuplicateAttr>()) {
3665 f->setAttr(cir::CIRDialect::getNoDuplicatesAttrName(),
3667 }
else if (
decl->hasAttr<NoInlineAttr>() && !isAlwaysInline) {
3669 f.setInlineKind(cir::InlineKind::NoInline);
3670 }
else if (
decl->hasAttr<AlwaysInlineAttr>() && !isNoInline) {
3673 f.setInlineKind(cir::InlineKind::AlwaysInline);
3677 if (!isAlwaysInline)
3678 f.setInlineKind(cir::InlineKind::NoInline);
3683 if (
auto *fd = dyn_cast<FunctionDecl>(
decl)) {
3688 auto checkRedeclForInline = [](
const FunctionDecl *redecl) {
3689 return redecl->isInlineSpecified();
3691 if (any_of(
decl->redecls(), checkRedeclForInline))
3696 return any_of(pattern->
redecls(), checkRedeclForInline);
3698 if (checkForInline(fd)) {
3699 f.setInlineKind(cir::InlineKind::InlineHint);
3700 }
else if (codeGenOpts.getInlining() ==
3702 !fd->isInlined() && !isAlwaysInline) {
3703 f.setInlineKind(cir::InlineKind::NoInline);
3710 if (!
decl->hasAttr<OptimizeNoneAttr>()) {
3711 if (
decl->hasAttr<ColdAttr>()) {
3712 if (!shouldAddOptNone)
3713 f->setAttr(cir::CIRDialect::getOptimizeForSizeAttrName(),
3716 f->setAttr(cir::CIRDialect::getColdAttrName(),
3720 if (
decl->hasAttr<HotAttr>())
3721 f->setAttr(cir::CIRDialect::getHotAttrName(),
3724 if (
decl->hasAttr<MinSizeAttr>())
3725 f->setAttr(cir::CIRDialect::getMinSizeAttrName(),
3729 std::optional<uint64_t> explicitAlignment;
3730 if (
unsigned alignment =
3732 explicitAlignment = alignment;
3733 else if (langOpts.FunctionAlignment)
3734 explicitAlignment = 1ull << langOpts.FunctionAlignment;
3736 if (explicitAlignment) {
3737 f.setAlignment(*explicitAlignment);
3738 f.setPreferredAlignment(*explicitAlignment);
3739 }
else if (langOpts.PreferredFunctionAlignment) {
3740 f.setPreferredAlignment(langOpts.PreferredFunctionAlignment);
3762static cir::LangAddressSpace
3764 switch (addressSpace) {
3766 return cir::LangAddressSpace::OffloadGlobal;
3768 return cir::LangAddressSpace::OffloadConstant;
3770 return cir::LangAddressSpace::OffloadLocal;
3772 return cir::LangAddressSpace::OffloadGeneric;
3774 return cir::LangAddressSpace::OffloadGlobalDevice;
3776 return cir::LangAddressSpace::OffloadGlobalHost;
3780 return cir::LangAddressSpace::Default;
3786 assert(fd &&
"expected a kernel function declaration");
3799 argNames.push_back(builder.getStringAttr(param->getName()));
3802 std::string typeQuals;
3804 if (
type->isImageType() ||
type->isPipeType()) {
3806 "OpenCL kernel argument metadata for image and pipe types");
3810 accessQuals.push_back(builder.getStringAttr(
"none"));
3812 auto getTypeSpelling = [&](
QualType paramType) {
3813 std::string typeName = paramType.getUnqualifiedType().getAsString(policy);
3815 if (paramType.isCanonical()) {
3816 StringRef typeNameRef = typeName;
3817 if (typeNameRef.consume_front(
"unsigned "))
3818 return std::string(
"u") + typeNameRef.str();
3819 if (typeNameRef.consume_front(
"signed "))
3820 return typeNameRef.str();
3828 if (
type->isPointerType()) {
3830 addressQuals.push_back(cir::LangAddressSpaceAttr::get(
3834 argTypeNames.push_back(
3835 builder.getStringAttr(getTypeSpelling(
pointeeType) +
"*"));
3836 argBaseTypeNames.push_back(builder.getStringAttr(
3837 getTypeSpelling(
pointeeType.getCanonicalType()) +
"*"));
3839 if (
type.isRestrictQualified())
3840 typeQuals =
"restrict";
3843 typeQuals += typeQuals.empty() ?
"const" :
" const";
3845 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
3847 addressQuals.push_back(cir::LangAddressSpaceAttr::get(
3850 argTypeNames.push_back(builder.getStringAttr(getTypeSpelling(
type)));
3851 argBaseTypeNames.push_back(
3852 builder.getStringAttr(getTypeSpelling(
type.getCanonicalType())));
3855 argTypeQuals.push_back(builder.getStringAttr(typeQuals));
3858 mlir::ArrayAttr names;
3860 names = builder.getArrayAttr(argNames);
3862 mlir::Attribute metadata = cir::OpenCLKernelArgMetadataAttr::get(
3863 func.getContext(), builder.getArrayAttr(addressQuals),
3864 builder.getArrayAttr(accessQuals), builder.getArrayAttr(argTypeNames),
3865 builder.getArrayAttr(argBaseTypeNames),
3866 builder.getArrayAttr(argTypeQuals), names);
3867 func->setAttr(cir::CIRDialect::getOpenCLKernelArgMetadataAttrName(),
3872 StringRef mangledName, mlir::Type funcType,
GlobalDecl gd,
bool forVTable,
3874 mlir::NamedAttrList extraAttrs) {
3877 if (
const auto *fd = cast_or_null<FunctionDecl>(d)) {
3879 if (
getLangOpts().OpenMPIsTargetDevice && openMPRuntime &&
3881 !dontDefer && !isForDefinition) {
3884 if (
const auto *cd = dyn_cast<CXXConstructorDecl>(fdDef))
3886 else if (
const auto *dd = dyn_cast<CXXDestructorDecl>(fdDef))
3896 if (fd->isMultiVersion())
3897 errorNYI(fd->getSourceRange(),
"getOrCreateCIRFunction: multi-version");
3903 assert(mlir::isa<cir::FuncOp>(entry));
3906 if (weakRefReferences.erase(entry)) {
3907 const auto *fd = cast_or_null<FunctionDecl>(d);
3908 if (fd && !fd->hasAttr<WeakAttr>())
3910 cir::GlobalLinkageKind::ExternalLinkage);
3914 if (d && !d->
hasAttr<DLLImportAttr>() && !d->
hasAttr<DLLExportAttr>()) {
3922 if (isForDefinition && fn && !fn.isDeclaration()) {
3929 diagnosedConflictingDefinitions.insert(gd).second) {
3933 diag::note_previous_definition);
3937 if (fn && fn.getFunctionType() == funcType) {
3941 if (!isForDefinition) {
3949 auto *funcDecl = llvm::cast_or_null<FunctionDecl>(gd.
getDecl());
3950 bool invalidLoc = !funcDecl ||
3951 funcDecl->getSourceRange().getBegin().isInvalid() ||
3952 funcDecl->getSourceRange().getEnd().isInvalid();
3954 invalidLoc ? theModule->getLoc() :
getLoc(funcDecl->getSourceRange()),
3955 mangledName, mlir::cast<cir::FuncType>(funcType), funcDecl);
3957 if (funcDecl && funcDecl->hasAttr<AnnotateAttr>())
3958 deferredAnnotations[mangledName] = funcDecl;
3969 auto symbolOp = mlir::cast<mlir::SymbolOpInterface>(entry);
3977 if (symbolOp.getSymbolUses(symbolOp->getParentOp()))
3987 if (!extraAttrs.empty())
3988 for (mlir::NamedAttribute attr : extraAttrs)
3989 if (!funcOp->hasDiscardableAttr(
attr.getName()))
3990 funcOp->setDiscardableAttr(
attr.getName(),
attr.getValue());
3996 assert(funcOp.getFunctionType() == funcType);
4003 if (isa_and_nonnull<CXXDestructorDecl>(d) &&
4033 fd = fd->getPreviousDecl()) {
4035 if (fd->doesThisDeclarationHaveABody()) {
4048 cir::FuncType funcType,
4052 mlir::OpBuilder::InsertionGuard guard(builder);
4057 builder.setInsertionPointToEnd(
getModule().getBody());
4059 func = cir::FuncOp::create(builder, loc, name, funcType);
4066 func.setNoProto(
true);
4068 assert(func.isDeclaration() &&
"expected empty body");
4072 func.setLinkageAttr(cir::GlobalLinkageKindAttr::get(
4074 mlir::SymbolTable::setSymbolVisibility(
4075 func, mlir::SymbolTable::Visibility::Private);
4086 for (
const auto *
attr :
4100 fnOp.setBuiltin(
true);
4106 return cir::CtorKind::Default;
4108 return cir::CtorKind::Copy;
4110 return cir::CtorKind::Move;
4111 return cir::CtorKind::Custom;
4116 return cir::AssignKind::Copy;
4118 return cir::AssignKind::Move;
4119 llvm_unreachable(
"not a copy or move assignment operator");
4127 if (
const auto *dtor = dyn_cast<CXXDestructorDecl>(funcDecl)) {
4128 auto cxxDtor = cir::CXXDtorAttr::get(
4131 funcOp.setFuncInfoAttr(cxxDtor);
4135 if (
const auto *ctor = dyn_cast<CXXConstructorDecl>(funcDecl)) {
4137 auto cxxCtor = cir::CXXCtorAttr::get(
4139 kind, ctor->isTrivial());
4140 funcOp.setFuncInfoAttr(cxxCtor);
4144 const auto *method = dyn_cast<CXXMethodDecl>(funcDecl);
4145 if (method && (method->isCopyAssignmentOperator() ||
4146 method->isMoveAssignmentOperator())) {
4148 auto cxxAssign = cir::CXXAssignAttr::get(
4150 assignKind, method->isTrivial());
4151 funcOp.setFuncInfoAttr(cxxAssign);
4161 bool inStdNamespace = method ? method->getParent()->isInStdNamespace()
4163 if (!inStdNamespace)
4169 std::optional<cir::KnownFuncKind>
kind;
4171 kind = llvm::StringSwitch<std::optional<cir::KnownFuncKind>>(
4173 .Case(cir::StdFindOp::getFunctionName(),
4174 cir::StdFindOp::getFuncKind())
4175 .Default(std::nullopt);
4184 cir::FuncOp funcOp, StringRef name) {
4200 mlir::NamedAttrList extraAttrs,
4202 bool assumeConvergent) {
4203 if (assumeConvergent)
4204 errorNYI(
"createRuntimeFunction: assumeConvergent");
4206 extraAttrs.set(cir::CIRDialect::getRuntimeFuncAttrName(),
4216 entry.setDSOLocal(
true);
4222mlir::SymbolTable::Visibility
4226 if (op.isDeclaration())
4227 return mlir::SymbolTable::Visibility::Private;
4231mlir::SymbolTable::Visibility
4234 case cir::GlobalLinkageKind::InternalLinkage:
4235 case cir::GlobalLinkageKind::PrivateLinkage:
4236 return mlir::SymbolTable::Visibility::Private;
4237 case cir::GlobalLinkageKind::ExternalLinkage:
4238 case cir::GlobalLinkageKind::ExternalWeakLinkage:
4239 case cir::GlobalLinkageKind::LinkOnceODRLinkage:
4240 case cir::GlobalLinkageKind::AvailableExternallyLinkage:
4241 case cir::GlobalLinkageKind::CommonLinkage:
4242 case cir::GlobalLinkageKind::WeakAnyLinkage:
4243 case cir::GlobalLinkageKind::WeakODRLinkage:
4244 return mlir::SymbolTable::Visibility::Public;
4246 llvm::errs() <<
"visibility not implemented for '"
4247 << stringifyGlobalLinkageKind(glk) <<
"'\n";
4248 assert(0 &&
"not implemented");
4251 llvm_unreachable(
"linkage should be handled above!");
4254std::string CIRGenModule::getModuleInitializerName(
clang::Module *mod) {
4256 llvm::raw_string_ostream
out(name);
4258 .mangleModuleInitializer(mod,
out);
4265 applyReplacements();
4267 getModule()->setAttr(cir::CIRDialect::getModuleLevelAsmAttrName(),
4268 builder.getArrayAttr(globalScopeAsm));
4270 emitGlobalAnnotations();
4272 if (std::optional<cir::FramePointerKind>
kind =
4275 cir::CIRDialect::getModuleFramePointerAttrName(),
4278 if (!recordLayoutEntries.empty())
4280 cir::CIRDialect::getRecordLayoutsAttrName(),
4281 mlir::DictionaryAttr::get(&
getMLIRContext(), recordLayoutEntries));
4290 std::string cuidName =
4293 auto loc = builder.getUnknownLoc();
4294 mlir::ptr::MemorySpaceAttrInterface addrSpace =
4299 gv.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
4301 auto zeroAttr = cir::IntAttr::get(int8Ty, 0);
4302 gv.setInitialValueAttr(zeroAttr);
4304 mlir::SymbolTable::setSymbolVisibility(
4305 gv, mlir::SymbolTable::Visibility::Public);
4310 if (astContext.getLangOpts().CUDA && cudaRuntime)
4323 if (cxx20ModuleInits) {
4324 clang::Module *primary = astContext.getCurrentNamedModule();
4326 if (isInterfaceUnit)
4328 cir::CIRDialect::getCXXModuleInitFnNameAttrName(),
4329 builder.getStringAttr(getModuleInitializerName(primary)));
4335 primary, importedModules.getArrayRef())) {
4338 auto importLoc = moduleImportLocs.find(mod);
4339 mlir::Location loc =
4340 getLoc(importLoc != moduleImportLocs.end() ? importLoc->second
4342 importedInits.push_back(cir::CXXModuleInitAttr::get(
4344 builder.getStringAttr(getModuleInitializerName(mod)), loc));
4346 if (!importedInits.empty())
4347 getModule()->setAttr(cir::CIRDialect::getCXXModuleImportedInitsAttrName(),
4348 builder.getArrayAttr(importedInits));
4364 const AliasAttr *aa = d->
getAttr<AliasAttr>();
4365 assert(aa &&
"Not an alias?");
4369 if (aa->getAliasee() == mangledName) {
4370 diags.Report(aa->getLocation(), diag::err_cyclic_alias) << 0;
4378 auto entryGV = mlir::dyn_cast<cir::CIRGlobalValueInterface>(entry);
4379 if (entryGV && entryGV.isDefinition())
4392 cir::GlobalLinkageKind linkage;
4404 cir::CIRGlobalValueInterface alias =
4405 isFunction ? mlir::cast<cir::CIRGlobalValueInterface>(
4407 mlir::cast<cir::FuncType>(declTy),
4410 : mlir::cast<cir::CIRGlobalValueInterface>(
4421 entry, mlir::cast<cir::FuncOp>(alias.getOperation()));
4429 linkage = cir::GlobalLinkageKind::WeakAnyLinkage;
4433 mlir::SymbolTable::Visibility visibility =
4436 alias.setAliasee(aa->getAliasee());
4437 alias.setLinkage(linkage);
4438 mlir::SymbolTable::setSymbolVisibility(alias, visibility);
4445 mlir::Operation *op,
4447 cir::FuncOp aliasee,
4448 cir::GlobalLinkageKind linkage) {
4450 auto *aliasFD = dyn_cast<FunctionDecl>(aliasGD.
getDecl());
4451 assert(aliasFD &&
"expected FunctionDecl");
4462 mangledName, fnType, aliasFD);
4463 alias.setAliasee(aliasee.getName());
4464 alias.setLinkage(linkage);
4468 mlir::SymbolTable::setSymbolVisibility(
4469 alias, mlir::SymbolTable::Visibility::Private);
4478 "declaration exists with different type");
4491 return genTypes.convertType(
type);
4498 return mlir::verify(
getModule()).succeeded();
4507 return builder.getConstNullPtrAttr(builder.getUInt8PtrTy());
4510 langOpts.ObjCRuntime.isGNUFamily()) {
4511 errorNYI(loc,
"getAddrOfRTTIDescriptor: Objc PtrType & Objc RT GUN");
4521 llvm::iterator_range<CastExpr::path_const_iterator> path) {
4528 assert(!base->isVirtual() &&
"Should not see virtual bases here!");
4533 const auto *baseDecl = base->getType()->castAsCXXRecordDecl();
4545 llvm::StringRef feature) {
4546 unsigned diagID = diags.getCustomDiagID(
4548 return diags.Report(loc, diagID) << feature;
4552 llvm::StringRef feature) {
4564 "cannot compile this %0 yet");
4565 diags.Report(astContext.getFullLoc(s->
getBeginLoc()), diagId)
4572 "cannot compile this %0 yet");
4573 diags.Report(astContext.getFullLoc(d->
getLocation()), diagId) <<
type;
4581 "not a global temporary");
4593 materializedType = mte->
getType();
4602 llvm::raw_svector_ostream
out(name);
4606 auto insertResult = materializedGlobalTemporaryMap.insert({mte,
nullptr});
4607 if (!insertResult.second) {
4611 if (!insertResult.first->second) {
4614 insertResult.first->second =
4617 return insertResult.first->second;
4634 value = &evalResult.
Val;
4638 std::optional<ConstantEmitter> emitter;
4639 mlir::Attribute initialValue =
nullptr;
4640 bool isConstant =
false;
4644 emitter.emplace(*
this);
4645 initialValue = emitter->emitForInitializer(*value, materializedType);
4650 type = mlir::cast<mlir::TypedAttr>(initialValue).getType();
4659 if (linkage == cir::GlobalLinkageKind::ExternalLinkage) {
4661 if (
varDecl->isStaticDataMember() &&
varDecl->getAnyInitializer(initVD) &&
4669 linkage = cir::GlobalLinkageKind::InternalLinkage;
4673 gv.setInitialValueAttr(initialValue);
4674 gv.setLinkage(linkage);
4678 emitter->finalize(gv);
4680 if (!gv.hasLocalLinkage()) {
4685 gv.setAlignment(align.getAsAlign().value());
4690 mlir::Operation *cv = gv;
4699 mlir::Operation *&entry = materializedGlobalTemporaryMap[mte];
4701 entry->replaceAllUsesWith(cv);
4716 return *globalOpEntry;
4723 "emitForInitializer should take gcd->getType().getAddressSpace()");
4725 auto typedInit = dyn_cast<mlir::TypedAttr>(init);
4729 "getAddrOfUnnamedGlobalConstantDecl: non-typed initializer");
4738 std::string name = numEntries == 0
4740 : (Twine(
".constant.") + Twine(numEntries)).str();
4742 typedInit.getType(),
true);
4743 globalOp.setLinkage(cir::GlobalLinkageKind::PrivateLinkage);
4746 globalOp.setAlignment(alignment.
getAsAlign().value());
4747 globalOp.setUnnamedAddr(
true);
4751 *globalOpEntry = globalOp;
4766 "emitForInitializer should take tpo->getType().getAddressSpace()");
4767 mlir::Attribute init =
4777 cir::GlobalLinkageKind linkage =
4779 ? cir::GlobalLinkageKind::LinkOnceODRLinkage
4780 : cir::GlobalLinkageKind::InternalLinkage;
4784 typedInit.getType(),
true);
4785 globalOp.setLinkage(linkage);
4786 globalOp.setAlignment(alignment.
getAsAlign().value());
4787 if (
supportsCOMDAT() && linkage == cir::GlobalLinkageKind::LinkOnceODRLinkage)
4788 globalOp.setSelfComdat();
4810 llvm::FoldingSetNodeID id;
4811 for (
Expr *e : exprs)
4814 mlir::ArrayAttr &lookup = annotationArgs[
id.computeHash()];
4819 args.reserve(exprs.size());
4820 for (
Expr *e : exprs) {
4821 if (
auto *strE = dyn_cast<clang::StringLiteral>(e->IgnoreParenCasts())) {
4822 args.push_back(builder.getStringAttr(strE->getString()));
4823 }
else if (
auto *intE =
4824 dyn_cast<clang::IntegerLiteral>(e->IgnoreParenCasts())) {
4825 auto intTy = builder.getIntegerType(intE->getValue().getBitWidth());
4826 args.push_back(builder.getIntegerAttr(intTy, intE->getValue()));
4828 errorNYI(e->getExprLoc(),
"annotation argument expression");
4832 return lookup = builder.getArrayAttr(args);
4836 mlir::StringAttr annoGV = builder.getStringAttr(aa->getAnnotation());
4838 return cir::AnnotationAttr::get(&
getMLIRContext(), annoGV, args);
4842 mlir::Operation *gv) {
4843 assert(d->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
4845 "annotation only on globals");
4849 if (
auto global = dyn_cast<cir::GlobalOp>(gv))
4850 global.setAnnotationsAttr(builder.getArrayAttr(annotations));
4851 else if (
auto func = dyn_cast<cir::FuncOp>(gv))
4852 func.setAnnotationsAttr(builder.getArrayAttr(annotations));
4855void CIRGenModule::emitGlobalAnnotations() {
4856 for (
const auto &[mangledName, vd] : deferredAnnotations) {
4861 deferredAnnotations.clear();
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 shouldSkipAliasEmission(const CIRGenModule &cgm, const ValueDecl *global)
static cir::LangAddressSpace getOpenCLKernelArgAddressSpace(LangAS addressSpace)
static mlir::Attribute getNewInitValue(CIRGenModule &cgm, cir::GlobalOp newGlob, mlir::Type oldTy, mlir::Attribute oldInit)
static bool verifyPointerTypeArgs(llvm::ArrayRef< mlir::Operation * > users, cir::FuncOp newF)
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 void setLinkageForFunction(CIRGenModule &cgm, cir::FuncOp &func, const NamedDecl *nd)
static cir::GlobalOp generateStringLiteral(mlir::Location loc, mlir::TypedAttr c, cir::GlobalLinkageKind lt, CIRGenModule &cgm, StringRef globalName, CharUnits alignment)
static std::vector< std::string > getFeatureDeltaFromDefault(const CIRGenModule &cgm, llvm::StringRef targetCPU, llvm::StringMap< bool > &featureMap)
Get the feature delta from the default feature map for the given target CPU.
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static mlir::Attribute createNewGlobalView(CIRGenModule &cgm, cir::GlobalOp newGlob, cir::GlobalViewAttr attr, mlir::Type oldTy)
static cir::CtorKind getCtorKindFromDecl(const CXXConstructorDecl *ctor)
static void emitUsed(CIRGenModule &cgm, StringRef name, std::vector< cir::CIRGlobalValueInterface > &list)
static cir::TLSModel getCIRTLSModel(StringRef S)
This file defines OpenACC nodes for declarative directives.
static constexpr bool needsDtor()
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
Defines the clang::Module class, which describes a module in the source code.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static ParseState advance(ParseState S, size_t N)
Defines the SourceManager interface.
This file defines OpenMP AST classes for executable directives and clauses.
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)
cir::PointerType getVoidPtrTy(clang::LangAS langAS=clang::LangAS::Default)
mlir::ptr::MemorySpaceAttrInterface getDefaultGlobalsAddrSpace(mlir::MLIRContext *ctx) const
Base class of the TBAA type descriptor attributes.
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 shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
StringRef getCUIDHash() const
void Deallocate(void *Ptr) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
const clang::PrintingPolicy & getPrintingPolicy() const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
DiagnosticsEngine & getDiagnostics() 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.
bool computeGlobalViewIndicesFromFlatOffset(int64_t offset, mlir::Type ty, const cir::CIRDataLayout &layout, llvm::SmallVectorImpl< int64_t > &indices)
mlir::Attribute getConstRecordOrZeroAttr(mlir::ArrayAttr arrayAttr, cir::RecordType recordTy)
uint64_t computeOffsetFromGlobalViewIndices(const cir::CIRDataLayout &layout, mlir::Type ty, llvm::ArrayRef< int64_t > indices)
cir::ConstArrayAttr getConstArray(mlir::Attribute attrs, cir::ArrayType arrayTy) const
virtual void handleGlobalReplace(cir::GlobalOp oldGV, cir::GlobalOp newGV)
virtual mlir::Operation * getKernelHandle(cir::FuncOp fn, GlobalDecl gd)=0
virtual void finalizeModule()
Perform module finalization: on device side, mark ODR-used device variables as compiler-used.
virtual void internalizeDeviceSideVar(const VarDecl *d, cir::GlobalLinkageKind &linkage)=0
Adjust linkage of shadow variables in host compilation.
virtual void handleVarRegistration(const VarDecl *vd, cir::GlobalOp var)=0
Check whether a variable is a device variable and register it if true.
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
cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn, cir::FuncType funcType)
void emitVariablyModifiedType(QualType ty)
This class organizes the cross-function state that is used while generating CIR code.
cir::GlobalOp getAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *gcd)
void setGlobalVisibility(cir::CIRGlobalValueInterface gv, const NamedDecl *d) const
Set the visibility for the given global.
void addUsedOrCompilerUsedGlobal(cir::CIRGlobalValueInterface gv)
Add a global to a list to be added to the llvm.compiler.used metadata.
void setFuncInfoAttr(cir::FuncOp funcOp, const clang::FunctionDecl *funcDecl)
Record the func_info tag for a function, either a C++ special member form (constructor,...
void replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old, cir::FuncOp newFn)
This function is called when we implement a function with no prototype, e.g.
bool shouldEmitFunction(clang::GlobalDecl gd)
Check if fd ends up calling itself directly through asm label or builtin-pointer-to-self trickery (e....
llvm::StringRef getMangledName(clang::GlobalDecl gd)
CharUnits computeNonVirtualBaseClassOffset(const CXXRecordDecl *derivedClass, llvm::iterator_range< CastExpr::path_const_iterator > path)
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.
cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd)
clang::ASTContext & getASTContext() const
mlir::Operation * getWeakRefReference(const clang::ValueDecl *vd)
Return the symbol that a weakref declaration refers to: the cir.func or cir.global named by its alias...
void insertGlobalSymbol(mlir::Operation *op)
cir::FuncOp getAddrOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
CIRGenCUDARuntime & getCUDARuntime()
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 addSYCLModuleIdAttr(cir::FuncOp fn)
std::vector< cir::CIRGlobalValueInterface > llvmUsed
List of global values which are required to be present in the object file; This is used for forcing v...
cir::TBAATagAttr getTBAAAccessTagInfo(TBAAAccessInfo tbaaInfo)
Returns the TBAA access tag for the given memory access.
void emitOMPCapturedExpr(const OMPCapturedExprDecl *d)
std::optional< llvm::SmallVector< int32_t > > buildMemberPath(const CXXRecordDecl *destClass, const ValueDecl *decl)
Build a GEP-style field-index path from destClass to decl.
bool mustBeEmitted(const clang::ValueDecl *d)
Determine whether the definition must be emitted; if this returns false, the definition can be emitte...
clang::CharUnits getNaturalTypeAlignment(clang::QualType t, LValueBaseInfo *baseInfo=nullptr, TBAAAccessInfo *tbaaInfo=nullptr, bool forPointeeType=false)
FIXME: this could likely be a common helper and not necessarily related with codegen.
void emitGlobalOpenACCDeclareDecl(const clang::OpenACCDeclareDecl *cd)
mlir::IntegerAttr getSize(CharUnits size)
cir::TLSModel getDefaultCIRTLSModel() const
Get TLS mode from CodeGenOptions.
void setGlobalTlsReferences(const VarDecl &vd, cir::GlobalOp globalOp)
void emitOpenCLKernelArgMetadata(cir::FuncOp func, const clang::FunctionDecl *fd)
Generate OpenCL kernel argument metadata for a kernel function.
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::FuncOp createCIRBuiltinFunction(mlir::Location loc, llvm::StringRef name, cir::FuncType ty, const clang::FunctionDecl *fd)
Create a CIR function with builtin attribute set.
cir::GlobalOp getAddrOfTemplateParamObject(const TemplateParamObjectDecl *tpo)
Get the GlobalOp of a template parameter object.
TBAAAccessInfo getTBAAAccessInfo(QualType accessType)
Returns the TBAA information that describes an access to an object of the given type.
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.
llvm::DenseMap< const UnnamedGlobalConstantDecl *, cir::GlobalOp > unnamedGlobalConstantDeclMap
std::vector< cir::CIRGlobalValueInterface > llvmCompilerUsed
cir::FuncOp emitAliasForGlobal(llvm::StringRef mangledName, mlir::Operation *op, GlobalDecl aliasGD, cir::FuncOp aliasee, cir::GlobalLinkageKind linkage)
Emit aliasGD as an alias of aliasee, replacing any existing declaration op, and return the alias.
void emitOMPRequiresDecl(const OMPRequiresDecl *d)
void emitGlobalDefinition(clang::GlobalDecl gd, mlir::Operation *op=nullptr)
clang::DiagnosticsEngine & getDiags() const
cir::GlobalLinkageKind getCIRLinkageForDeclarator(const DeclaratorDecl *dd, GVALinkage linkage)
mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty, bool forEH=false)
Get the address of the RTTI descriptor for the given type.
cir::GlobalOp createGlobalString(mlir::Location loc, llvm::StringRef str, llvm::StringRef name)
Create a private constant global holding the null-terminated string str, mirroring llvm::IRBuilder::C...
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
static mlir::SymbolTable::Visibility getMLIRVisibility(cir::GlobalOp op)
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
void emitTentativeDefinition(const VarDecl *d)
const cir::CIRDataLayout & getDataLayout() const
void emitAliasDefinition(GlobalDecl gd)
Emit a definition for an __attribute__((alias)) declaration.
void addUsedGlobal(cir::CIRGlobalValueInterface gv)
Add a global value to the llvmUsed list.
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)
static std::optional< cir::FramePointerKind > getFramePointerKind(CodeGenOptions::FramePointerKind kind)
Returns the frame pointer kind to record on functions and on the module, or std::nullopt when kind is...
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::NamedAttrList extraAttrs={}, bool isLocal=false, bool assumeConvergent=false)
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.
mlir::TypedAttr emitNullConstantAttr(QualType t)
cir::TBAATypeDescriptorAttr getTBAATypeInfo(QualType qty)
Returns the type descriptor used to describe accesses to objects of the given type,...
void emitLLVMUsed()
Emit llvm.used and llvm.compiler.used globals.
mlir::Value emitMemberPointerConstant(const UnaryOperator *e)
void emitGlobalOpenACCDecl(const clang::OpenACCConstructDecl *cd)
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo sourceInfo, TBAAAccessInfo targetInfo)
Returns the merged TBAA information for the purpose of type casts.
bool verifyModule() const
LangAS getGlobalVarAddressSpace(const VarDecl *decl)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void setTLSMode(mlir::Operation *op, const VarDecl &d, bool isExtendingDecl=false)
Set TLS mode for the given operation based on the given variable declaration.
void emitExplicitCastExprType(const ExplicitCastExpr *e, CIRGenFunction *cgf=nullptr)
Emit type info if type of an expression is a variably modified type.
void eraseGlobalSymbol(mlir::Operation *op)
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.
llvm::StringMap< mlir::Operation * > symbolLookupCache
Cache for O(1) symbol lookups by name, replacing the O(N) linear scan in SymbolTable::lookupSymbolIn ...
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.
mlir::ArrayAttr getOrCreateAnnotationArgs(const clang::AnnotateAttr *attr)
Build (or fetch from the dedup cache) the args ArrayAttr for an annotation.
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 printPostfixForExternalizedDecl(llvm::raw_ostream &os, const Decl *d)
Print the postfix for externalized static variable or kernels for single source offloading languages ...
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::GlobalOp createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::ptr::MemorySpaceAttrInterface addrSpace={}, mlir::Operation *insertPoint=nullptr)
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.
clang::CharUnits getNaturalPointeeTypeAlignment(clang::QualType t, LValueBaseInfo *baseInfo=nullptr, TBAAAccessInfo *tbaaInfo=nullptr)
mlir::Value castGlobalToDeclAddrSpace(mlir::Value addr, const VarDecl &vd)
Cast addr, the address of the global vd, to the address space of the declared type of vd if they diff...
void addDeferredDeclToEmit(clang::GlobalDecl GD)
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)
static cir::VisibilityKind getCIRVisibilityKind(Visibility v)
void setGVPropertiesAux(mlir::Operation *op, const NamedDecl *d) const
LangAS getLangTempAllocaAddressSpace() const
Returns the address space for temporary allocations in the language.
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 setCIRFunctionAttributesForDefinition(const clang::Decl *decl, cir::FuncOp f)
Set extra attributes (inline, etc.) for a function.
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.
llvm::StringMap< unsigned > cgGlobalNames
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
void addCompilerUsedGlobal(cir::CIRGlobalValueInterface gv)
Add a global value to the llvmCompilerUsed list.
mlir::MLIRContext & getMLIRContext()
void emitSYCLKernelCaller(const clang::FunctionDecl *kernelEntryPointFn, clang::ASTContext &ctx)
Emit the SYCL kernel caller offload entry point function generated for a function declared with the s...
mlir::Operation * getAddrOfGlobal(clang::GlobalDecl gd, ForDefinition_t isForDefinition=NotForDefinition)
void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op)
bool isEmptyFieldForMemberPointer(const FieldDecl *field)
Returns true if field is a potentially-overlapping field with no CIR field index (e....
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.
bool lookupRepresentativeDecl(llvm::StringRef mangledName, clang::GlobalDecl &gd) const
void emitDeclContext(const DeclContext *dc)
mlir::ptr::MemorySpaceAttrInterface getGlobalCIRAddressSpace(LangAS as)
Return the CIR address space attribute for a global in as, honoring the target address space map wher...
void emitGlobal(clang::GlobalDecl gd)
Emit code for a single global function or variable declaration.
cir::TBAATypeDescriptorAttr getTBAABaseTypeInfo(QualType qty)
Returns the type descriptor that describes the given base access type, or null if the type is not sui...
bool mayBeEmittedEagerly(const clang::ValueDecl *d)
Determine whether the definition can be emitted eagerly, or should be delayed until the end of the tr...
void constructAttributeList(llvm::StringRef name, const CIRGenFunctionInfo &info, CIRGenCalleeInfo calleeInfo, mlir::NamedAttrList &attrs, llvm::MutableArrayRef< mlir::NamedAttrList > argAttrs, mlir::NamedAttrList &retAttrs, cir::CallingConv &callingConv, bool attrOnCallSite, bool isThunk)
Get the CIR attributes and calling convention to use for a particular function type.
void addGlobalAnnotations(const clang::ValueDecl *d, mlir::Operation *gv)
Add global annotations for a global value (GlobalOp or FuncOp).
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)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo infoA, TBAAAccessInfo infoB)
Returns the merged TBAA information for the purpose of conditional operator.
cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty, LangAS langAS, mlir::Location loc, const VarDecl *d, ForDefinition_t isForDefinition)
If the specified mangled name is not in the module, create and return an mlir::GlobalOp value.
std::vector< clang::GlobalDecl > deferredDeclsToEmit
cir::AnnotationAttr emitAnnotateAttr(const clang::AnnotateAttr *aa)
Create cir::AnnotationAttr for a single AnnotateAttr.
void emitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *d)
CIRGenOpenMPRuntime & getOpenMPRuntime()
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.
void setCommonAttributes(GlobalDecl gd, mlir::Operation *op)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
void emitDeclareTargetFunction(const FunctionDecl *fd, cir::FuncOp funcOp)
If the function has an OMPDeclareTargetDeclAttr, set the corresponding omp.declare_target attribute o...
void registerTargetGlobalVariable(const VarDecl *vd)
Register a global variable that may need an offload entry.
This class handles record and union layout info while lowering AST types to CIR types.
bool hasNonVirtualBaseCIRField(const CXXRecordDecl *rd) const
unsigned getCIRFieldNo(const clang::FieldDecl *fd) const
Return cir::RecordType element number that corresponds to the field FD.
bool hasCIRField(const clang::FieldDecl *fd) const
bool isZeroInitializable() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer.
unsigned getNonVirtualBaseCIRFieldNo(const CXXRecordDecl *rd) const
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)
mlir::ptr::MemorySpaceAttrInterface getPointerAddressSpace(clang::QualType pointeeTy) const
Returns the CIR address space for a pointer/reference to pointeeTy, or a null attribute for the defau...
cir::FuncType getFunctionType(const CIRGenFunctionInfo &info)
Get the CIR function type for.
const CIRGenRecordLayout & getCIRGenRecordLayout(const clang::RecordDecl *rd)
Return record layout info for the given record decl.
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.
void finalize(cir::GlobalOp gv)
mlir::Attribute emitForInitializer(const APValue &value, QualType destType)
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 getGlobalCIRAddressSpace(clang::LangAS as) const
Get the CIR address space attribute for a global in AST address space as.
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.
CXXRecordDecl * getMostRecentDecl()
bool hasDefinition() const
This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static CharUnits One()
Construct a CharUnits quantity of one.
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
static CharUnits 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 isInStdNamespace() const
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
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.
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
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={})
ArrayRef< ParmVarDecl * > parameters() const
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.
FunctionDecl * getDefinition()
Get the definition for this declaration.
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.
CXXCtorType getCtorType() const
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
unsigned getMultiVersionIndex() const
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.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::string CUID
The user provided compilation unit ID, if non-empty.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
bool isTriviallyRecursive(const FunctionDecl *FD)
Return true if FD's body contains a direct call back to the symbol it links as, through an asm label ...
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
ManglerKind getKind() const
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.
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.
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Describes a module or submodule.
SourceLocation DefinitionLoc
The location of the module definition.
llvm::iterator_range< submodule_iterator > submodules()
bool isModuleImplementation() const
Is this a module implementation.
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
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.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
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
Represents a struct/union/class.
RecordDecl * getMostRecentDecl()
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...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getBeginLoc() const LLVM_READONLY
unsigned getLength() const
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
static const auto & getSpelling(Kind ABIKind)
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
virtual bool initFeatureMap(llvm::StringMap< bool > &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector< std::string > &FeatureVec) const
Initialize the map with the default set of target features for the CPU this should include all legal ...
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
A template parameter object.
const APValue & getValue() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
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
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() 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.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
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_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.
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
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.
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
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)
std::unique_ptr< TargetCIRGenInfo > createCommonSPIRTargetCIRGenInfo(CIRGenTypes &cgt)
std::unique_ptr< TargetCIRGenInfo > createSystemZTargetCIRGenInfo(CIRGenTypes &cgt)
std::unique_ptr< TargetCIRGenInfo > createAArch64TargetCIRGenInfo(CIRGenTypes &cgt)
CIRGenCXXABI * CreateCIRGenMicrosoftCXXABI(CIRGenModule &cgm)
Creates Microsoft ABI.
CIRGenCUDARuntime * createNVCUDARuntime(CIRGenModule &cgm)
LangAS getGlobalConstantAddressSpace(const LangOptions &LangOpts, const TargetInfo &Target)
Determines whether the language options require us to model unwind exceptions.
bool isVarDeclStrongDefinition(const ASTContext &Ctx, const VarDecl *D, bool NoCommon)
Check whether D is a strong definition, and thus must not be given common linkage.
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
llvm::SmallVector< Module *, 8 > importedModulesToInitialize(Module *Primary, llvm::ArrayRef< Module * > Imported)
The C++20 named modules whose Itanium initializer function the global init function of a translation ...
bool hasUnwindExceptions(const LangOptions &LangOpts)
bool shouldBeInCOMDAT(const ASTContext &Ctx, const Decl &D)
Check whether D should be emitted into a COMDAT group.
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, FieldDecl > fieldDecl
Matches field declarations.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
QualType pointeeType(QualType T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
@ 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)
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t
static bool globalCtorLexOrder()
static bool opFuncArmNewAttr()
static bool getRuntimeFunctionDecl()
static bool addressSpace()
static bool opGlobalThreadLocal()
static bool opFuncMultiVersioning()
static bool sourceLanguageCases()
static bool opFuncAstDeclAttr()
static bool stackProtector()
static bool moduleNameHash()
static bool opGlobalVisibility()
static bool setDLLStorageClass()
static bool opFuncParameterAttributes()
static bool targetCIRGenInfoArch()
static bool opFuncExtraAttrs()
static bool tbaaNewStructPath()
static bool attributeNoBuiltin()
static bool opGlobalDLLImportExport()
static bool opGlobalPartition()
static bool opGlobalPragmaClangSection()
static bool deferredCXXGlobalInit()
static bool opFuncOperandBundles()
static bool opFuncCallingConv()
static bool globalCtorAssociatedData()
static bool defaultVisibility()
static bool opFuncExceptions()
static bool opFuncArmStreamingAttr()
static bool opFuncMaybeHandleStaticInExternC()
static bool checkAliases()
static bool generateDebugInfo()
static bool emitModuleLinkOptions()
static bool targetCIRGenInfoOS()
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::MFloat8Type mFloat8Ty
cir::PointerType voidPtrTy
void* in address space 0
Describes a memory access in terms of TBAA.
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.
Describes how types, statements, expressions, and declarations should be printed.