clang 24.0.0git
CIRGenModule.cpp
Go to the documentation of this file.
1//===- CIRGenModule.cpp - Per-Module state for CIR generation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This is the internal per-translation-unit state used for CIR translation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CIRGenModule.h"
14#include "CIRGenCUDARuntime.h"
15#include "CIRGenCXXABI.h"
17#include "CIRGenFunction.h"
18
19#include "mlir/Dialect/LLVMIR/LLVMDialectDecl.h"
20#include "mlir/Dialect/OpenMP/Utils/Utils.h"
21#include "mlir/IR/SymbolTable.h"
23#include "clang/AST/ASTLambda.h"
24#include "clang/AST/Attrs.inc"
25#include "clang/AST/DeclBase.h"
28#include "clang/AST/Mangle.h"
32#include "clang/Basic/Module.h"
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"
47
48#include "CIRGenFunctionInfo.h"
49#include "TargetInfo.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"
57
58using namespace clang;
59using namespace clang::CIRGen;
60
62 switch (cgm.getASTContext().getCXXABIKind()) {
63 case TargetCXXABI::GenericItanium:
64 case TargetCXXABI::GenericAArch64:
65 case TargetCXXABI::AppleARM64:
66 case TargetCXXABI::GenericARM:
67 return CreateCIRGenItaniumCXXABI(cgm);
68 case TargetCXXABI::Microsoft:
70
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");
78 return nullptr;
79 }
80
81 llvm_unreachable("invalid C++ ABI kind");
82}
83
84CIRGenModule::CIRGenModule(mlir::MLIRContext &mlirContext,
85 clang::ASTContext &astContext,
86 const clang::CodeGenOptions &cgo,
87 DiagnosticsEngine &diags)
88 : builder(mlirContext, *this), astContext(astContext),
89 langOpts(astContext.getLangOpts()), atomicOpts(astContext.getLangOpts()),
90 codeGenOpts(cgo),
91 theModule{mlir::ModuleOp::create(mlir::UnknownLoc::get(&mlirContext))},
92 diags(diags), target(astContext.getTargetInfo()),
93 abi(createCXXABI(*this)), genTypes(*this), vtables(*this) {
94
95 // Classic CodeGen's CXX20ModuleInits: C++20 named modules get an
96 // initializer function of their own only under the Itanium mangler, since
97 // no Microsoft mangling for it has been settled on yet; otherwise they fall
98 // back to `_GLOBAL__sub_I_` as in classic CodeGen.
99 cxx20ModuleInits =
100 langOpts.CPlusPlusModules &&
102
103 // Initialize cached types
104 voidTy = cir::VoidType::get(&getMLIRContext());
105 voidPtrTy = cir::PointerType::get(voidTy);
106 sInt8Ty = cir::IntType::get(&getMLIRContext(), 8, /*isSigned=*/true);
107 sInt16Ty = cir::IntType::get(&getMLIRContext(), 16, /*isSigned=*/true);
108 sInt32Ty = cir::IntType::get(&getMLIRContext(), 32, /*isSigned=*/true);
109 sInt64Ty = cir::IntType::get(&getMLIRContext(), 64, /*isSigned=*/true);
110 sInt128Ty = cir::IntType::get(&getMLIRContext(), 128, /*isSigned=*/true);
111 uInt8Ty = cir::IntType::get(&getMLIRContext(), 8, /*isSigned=*/false);
112 uInt8PtrTy = cir::PointerType::get(uInt8Ty);
114 uInt16Ty = cir::IntType::get(&getMLIRContext(), 16, /*isSigned=*/false);
115 uInt32Ty = cir::IntType::get(&getMLIRContext(), 32, /*isSigned=*/false);
116 uInt64Ty = cir::IntType::get(&getMLIRContext(), 64, /*isSigned=*/false);
117 uInt128Ty = cir::IntType::get(&getMLIRContext(), 128, /*isSigned=*/false);
118 fP16Ty = cir::FP16Type::get(&getMLIRContext());
119 bFloat16Ty = cir::BF16Type::get(&getMLIRContext());
120 floatTy = cir::SingleType::get(&getMLIRContext());
121 doubleTy = cir::DoubleType::get(&getMLIRContext());
122 fP80Ty = cir::FP80Type::get(&getMLIRContext());
123 fP128Ty = cir::FP128Type::get(&getMLIRContext());
124 mFloat8Ty = cir::MFloat8Type::get(&getMLIRContext());
125
126 allocaInt8PtrTy = cir::PointerType::get(uInt8Ty, cirAllocaAddressSpace);
127
129 astContext
130 .toCharUnitsFromBits(
131 astContext.getTargetInfo().getPointerAlign(LangAS::Default))
132 .getQuantity();
133
134 const unsigned charSize = target.getCharWidth();
135 uCharTy = cir::IntType::get(&getMLIRContext(), charSize, /*isSigned=*/false);
136
137 const unsigned sizeTypeSize = target.getTypeWidth(target.getSizeType());
138 SizeSizeInBytes = sizeTypeSize / charSize;
139 // In CIRGenTypeCache, UIntPtrTy and SizeType are fields of the same union
140 uIntPtrTy =
141 cir::IntType::get(&getMLIRContext(), sizeTypeSize, /*isSigned=*/false);
142 ptrDiffTy =
143 cir::IntType::get(&getMLIRContext(), sizeTypeSize, /*isSigned=*/true);
144
145 std::optional<cir::SourceLanguage> sourceLanguage = getCIRSourceLanguage();
146 if (sourceLanguage)
147 getModule()->setAttr(
148 cir::CIRDialect::getSourceLanguageAttrName(),
149 cir::SourceLanguageAttr::get(&mlirContext, *sourceLanguage));
150 if (langOpts.OpenCL || (langOpts.CUDAIsDevice && getTriple().isSPIRV())) {
151 // CUDA and HIP use OpenCL 2.0 metadata when targeting SPIR-V.
152 unsigned version =
153 langOpts.OpenCL ? langOpts.getOpenCLCompatibleVersion() : 200;
154 setOpenCLVersionAttr(cir::CIRDialect::getOpenCLVersionAttrName(), version);
155 if (langOpts.OpenCLCPlusPlus)
156 setOpenCLVersionAttr(cir::CIRDialect::getOpenCLCXXVersionAttrName(),
157 langOpts.OpenCLCPlusPlusVersion);
158 // SPIR v2.0 s2.12 requires opencl.spir.version.
159 if (getTriple().isSPIR()) {
160 unsigned spirMajor = version / 100;
161 getModule()->setAttr(cir::CIRDialect::getOpenCLSPIRVersionAttrName(),
162 cir::OpenCLVersionAttr::get(&getMLIRContext(),
163 spirMajor,
164 spirMajor > 1 ? 0 : 2));
165 }
166 }
167 getModule()->setAttr(cir::CIRDialect::getTripleAttrName(),
168 builder.getStringAttr(getTriple().str()));
169 getModule()->setAttr(cir::CIRDialect::getTargetABIAttrName(),
170 builder.getStringAttr(getTarget().getABI()));
171
172 // Assign the target-cpu and target-features as attributes to the module. This
173 // will allow subsequent passes to use this to ensure that 'generated'
174 // functions get the correct behavior for the model.
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));
179
180 // If cxxabi was overridden via -fc++-abi, record it.
181 if (langOpts.CXXABI)
182 getModule()->setAttr(
183 cir::CIRDialect::getCXXABIAttrName(),
184 builder.getStringAttr(TargetCXXABI::getSpelling(*langOpts.CXXABI)));
185
186 if (llvm::VersionTuple sdkVersion = getTarget().getSDKVersion();
187 !sdkVersion.empty())
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()));
193 // TODO(CIR): These attributes should eventually be replaced by
194 // TypeSizeInfoAttr once it is upstreamed.
195 getModule()->setAttr(cir::CIRDialect::getSizeTypeWidthAttrName(),
196 builder.getI32IntegerAttr(sizeTypeSize));
197 getModule()->setAttr(cir::CIRDialect::getIntTypeWidthAttrName(),
198 builder.getI32IntegerAttr(target.getIntWidth()));
199
200 // Serialize the lowering-relevant LangOptions and CodeGenOptions onto the
201 // ModuleOp so a reloaded .cir is self-describing and lowers the same way it
202 // was compiled, without a live clang::LangOptions or clang::CodeGenOptions.
203 getModule()->setAttr(
204 cir::CIRDialect::getLoweringOptionsAttrName(),
205 cir::LoweringOptionsAttr::get(
206 &mlirContext,
207 /*exceptions=*/langOpts.Exceptions,
208 /*threadsafe_statics=*/langOpts.ThreadsafeStatics,
209 /*cuda=*/langOpts.CUDA,
210 /*cuda_is_device=*/langOpts.CUDAIsDevice,
211 /*hip=*/langOpts.HIP,
212 /*hlsl=*/langOpts.HLSL,
213 /*sycl_is_device=*/langOpts.SYCLIsDevice,
214 /*gpu_rdc=*/langOpts.GPURelocatableDeviceCode,
215 /*openmp=*/langOpts.OpenMP != 0,
216 /*openmp_is_target_device=*/langOpts.OpenMPIsTargetDevice,
217 /*clang_abi_compat=*/
218 static_cast<int32_t>(langOpts.getClangABICompat()),
219 static_cast<int32_t>(langOpts.LongDoubleSize),
220 /*enable_noundef_attrs=*/cgo.EnableNoundefAttrs,
221 /*no_trapping_math=*/langOpts.getDefaultExceptionMode() ==
223 /*ssp_buffer_size=*/cgo.SSPBufferSize,
224 /*relative_cxx_abi_vtables=*/langOpts.RelativeCXXABIVTables));
225
226 if (cgo.OptimizationLevel > 0 || cgo.OptimizeSize > 0)
227 getModule()->setAttr(cir::CIRDialect::getOptInfoAttrName(),
228 cir::OptInfoAttr::get(&mlirContext,
229 cgo.OptimizationLevel,
230 cgo.OptimizeSize));
231
232 getModule()->setAttr(
233 cir::CIRDialect::getDefaultTlsModelAttrName(),
234 cir::TLSModelAttr::get(&mlirContext, getDefaultCIRTLSModel()));
235
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);
245 }
246
247 if (langOpts.CUDA)
248 createCUDARuntime();
249 if (langOpts.OpenMP)
250 createOpenMPRuntime();
251
252 // Enable TBAA unless it's suppressed.
255 if (!codeGenOpts.RelaxedAliasing && codeGenOpts.OptimizationLevel > 0 &&
256 !codeGenOpts.NewStructPathTBAA)
257 tbaa = std::make_unique<CIRGenTBAA>(mlirContext, astContext, getCXXABI(),
258 codeGenOpts, langOpts);
259
260 // Set the module name to be the name of the main file. TranslationUnitDecl
261 // often contains invalid source locations and isn't a reliable source for the
262 // module location.
263 FileID mainFileId = astContext.getSourceManager().getMainFileID();
264 const FileEntry &mainFile =
265 *astContext.getSourceManager().getFileEntryForID(mainFileId);
266 StringRef path = mainFile.tryGetRealPathName();
267 if (!path.empty()) {
268 getModule().setSymName(path);
269 getModule()->setLoc(mlir::FileLineColLoc::get(&mlirContext, path,
270 /*line=*/0,
271 /*column=*/0));
272 }
273}
274
276
278 if (!tbaa)
279 return {};
280 return tbaa->getTypeInfo(qty);
281}
282
284 if (!tbaa)
285 return TBAAAccessInfo();
286 if (getLangOpts().CUDAIsDevice) {
287 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
288 // access info.
289 if (accessType->isCUDADeviceBuiltinSurfaceType() ||
290 accessType->isCUDADeviceBuiltinTextureType())
291 return TBAAAccessInfo();
292 }
293 return tbaa->getAccessInfo(accessType);
294}
295
297 if (!tbaa)
298 return {};
299 return tbaa->getBaseTypeInfo(qty);
300}
301
303 if (!tbaa)
304 return {};
305 return tbaa->getAccessTagInfo(tbaaInfo);
306}
307
309 TBAAAccessInfo targetInfo) {
310 if (!tbaa)
311 return TBAAAccessInfo();
312 return tbaa->mergeTBAAInfoForCast(sourceInfo, targetInfo);
313}
314
317 TBAAAccessInfo infoB) {
318 if (!tbaa)
319 return TBAAAccessInfo();
320 return tbaa->mergeTBAAInfoForConditionalOperator(infoA, infoB);
321}
322
323void CIRGenModule::setOpenCLVersionAttr(StringRef attrName, unsigned version) {
324 getModule()->setAttr(
325 attrName, cir::OpenCLVersionAttr::get(&getMLIRContext(), version / 100,
326 (version % 100) / 10));
327}
328
329void CIRGenModule::createCUDARuntime() {
330 cudaRuntime.reset(createNVCUDARuntime(*this));
331}
332
333void CIRGenModule::createOpenMPRuntime() {
334 openMPRuntime = std::make_unique<CIRGenOpenMPRuntime>(*this);
335}
336
337/// FIXME: this could likely be a common helper and not necessarily related
338/// with codegen.
339/// Return the best known alignment for an unknown pointer to a
340/// particular class.
342 if (!rd->hasDefinition())
343 return CharUnits::One(); // Hopefully won't be used anywhere.
344
345 auto &layout = astContext.getASTRecordLayout(rd);
346
347 // If the class is final, then we know that the pointer points to an
348 // object of that type and can use the full alignment.
349 if (rd->isEffectivelyFinal())
350 return layout.getAlignment();
351
352 // Otherwise, we have to assume it could be a subclass.
353 return layout.getNonVirtualAlignment();
354}
355
357 LValueBaseInfo *baseInfo,
358 TBAAAccessInfo *tbaaInfo,
359 bool forPointeeType) {
360 if (tbaaInfo)
361 *tbaaInfo = getTBAAAccessInfo(t);
362
363 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown, but
364 // that doesn't return the information we need to compute baseInfo.
365
366 // Honor alignment typedef attributes even on incomplete types.
367 // We also honor them straight for C++ class types, even as pointees;
368 // there's an expressivity gap here.
369 if (const auto *tt = t->getAs<TypedefType>()) {
370 if (unsigned align = tt->getDecl()->getMaxAlignment()) {
371 if (baseInfo)
373 return astContext.toCharUnitsFromBits(align);
374 }
375 }
376
377 bool alignForArray = t->isArrayType();
378
379 // Analyze the base element type, so we don't get confused by incomplete
380 // array types.
381 t = astContext.getBaseElementType(t);
382
383 if (t->isIncompleteType()) {
384 // We could try to replicate the logic from
385 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
386 // type is incomplete, so it's impossible to test. We could try to reuse
387 // getTypeAlignIfKnown, but that doesn't return the information we need
388 // to set baseInfo. So just ignore the possibility that the alignment is
389 // greater than one.
390 if (baseInfo)
392 return CharUnits::One();
393 }
394
395 if (baseInfo)
397
398 CharUnits alignment;
399 const CXXRecordDecl *rd = nullptr;
400 if (t.getQualifiers().hasUnaligned()) {
401 alignment = CharUnits::One();
402 } else if (forPointeeType && !alignForArray &&
403 (rd = t->getAsCXXRecordDecl())) {
404 alignment = getClassPointerAlignment(rd);
405 } else {
406 alignment = astContext.getTypeAlignInChars(t);
407 }
408
409 // Cap to the global maximum type alignment unless the alignment
410 // was somehow explicit on the type.
411 if (unsigned maxAlign = astContext.getLangOpts().MaxTypeAlign) {
412 if (alignment.getQuantity() > maxAlign &&
413 !astContext.isAlignmentRequired(t))
414 alignment = CharUnits::fromQuantity(maxAlign);
415 }
416 return alignment;
417}
418
420 QualType t, LValueBaseInfo *baseInfo, TBAAAccessInfo *tbaaInfo) {
421 return getNaturalTypeAlignment(t->getPointeeType(), baseInfo, tbaaInfo,
422 /*forPointeeType=*/true);
423}
424
426 if (theTargetCIRGenInfo)
427 return *theTargetCIRGenInfo;
428
429 const llvm::Triple &triple = getTarget().getTriple();
430 switch (triple.getArch()) {
431 default:
433
434 // Currently we just fall through to x86_64.
435 [[fallthrough]];
436
437 case llvm::Triple::x86_64: {
438 switch (triple.getOS()) {
439 default:
441
442 // Currently we just fall through to x86_64.
443 [[fallthrough]];
444
445 case llvm::Triple::Linux:
446 theTargetCIRGenInfo = createX8664TargetCIRGenInfo(genTypes);
447 return *theTargetCIRGenInfo;
448 }
449 }
450 case llvm::Triple::aarch64:
451 case llvm::Triple::aarch64_32:
452 case llvm::Triple::aarch64_be: {
453 theTargetCIRGenInfo = createAArch64TargetCIRGenInfo(genTypes);
454 return *theTargetCIRGenInfo;
455 }
456 case llvm::Triple::nvptx:
457 case llvm::Triple::nvptx64:
458 theTargetCIRGenInfo = createNVPTXTargetCIRGenInfo(genTypes);
459 return *theTargetCIRGenInfo;
460 case llvm::Triple::amdgpu: {
461 theTargetCIRGenInfo = createAMDGPUTargetCIRGenInfo(genTypes);
462 return *theTargetCIRGenInfo;
463 }
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:
469 theTargetCIRGenInfo = createCommonSPIRTargetCIRGenInfo(genTypes);
470 return *theTargetCIRGenInfo;
471 case llvm::Triple::systemz: {
472 // z/OS XPLINK target info is not implemented yet.
473 // We just default to SystemZ ELF Target for now.
474 if (triple.isOSzOS())
476 theTargetCIRGenInfo = createSystemZTargetCIRGenInfo(genTypes);
477 return *theTargetCIRGenInfo;
478 }
479 }
480}
481
483 assert(cLoc.isValid() && "expected valid source location");
484 const SourceManager &sm = astContext.getSourceManager();
485 PresumedLoc pLoc = sm.getPresumedLoc(cLoc);
486 StringRef filename = pLoc.getFilename();
487 return mlir::FileLineColLoc::get(builder.getStringAttr(filename),
488 pLoc.getLine(), pLoc.getColumn());
489}
490
491mlir::Location CIRGenModule::getLoc(SourceRange cRange) {
492 assert(cRange.isValid() && "expected a valid source range");
493 mlir::Location begin = getLoc(cRange.getBegin());
494 mlir::Location end = getLoc(cRange.getEnd());
495 mlir::Attribute metadata;
496 return mlir::FusedLoc::get({begin, end}, metadata, builder.getContext());
497}
498
499mlir::Operation *
501 const Decl *d = gd.getDecl();
502
504 return getAddrOfCXXStructor(gd, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
505 /*DontDefer=*/false, isForDefinition);
506
507 if (isa<CXXMethodDecl>(d)) {
508 const CIRGenFunctionInfo &fi =
510 cir::FuncType ty = getTypes().getFunctionType(fi);
511 return getAddrOfFunction(gd, ty, /*ForVTable=*/false, /*DontDefer=*/false,
512 isForDefinition);
513 }
514
515 if (isa<FunctionDecl>(d)) {
517 cir::FuncType ty = getTypes().getFunctionType(fi);
518 return getAddrOfFunction(gd, ty, /*ForVTable=*/false, /*DontDefer=*/false,
519 isForDefinition);
520 }
521
522 return getOrCreateCIRGlobal(cast<VarDecl>(d), /*ty=*/nullptr,
523 isForDefinition);
524}
525
527 // We call getAddrOfGlobal with isForDefinition set to ForDefinition in
528 // order to get a Value with exactly the type we need, not something that
529 // might have been created for another decl with the same mangled name but
530 // different type.
531 mlir::Operation *op = getAddrOfGlobal(d, ForDefinition);
532
533 // In case of different address spaces, we may still get a cast, even with
534 // IsForDefinition equal to ForDefinition. Query mangled names table to get
535 // GlobalValue.
536 if (!op)
538
539 assert(op && "expected a valid global op");
540
541 // Check to see if we've already emitted this. This is necessary for a
542 // couple of reasons: first, decls can end up in deferred-decls queue
543 // multiple times, and second, decls can end up with definitions in unusual
544 // ways (e.g. by an extern inline function acquiring a strong function
545 // redefinition). Just ignore those cases.
546 // TODO: Not sure what to map this to for MLIR
547 mlir::Operation *globalValueOp = op;
548 if (auto gv = dyn_cast<cir::GetGlobalOp>(op)) {
549 globalValueOp = getGlobalValue(gv.getName());
550 assert(globalValueOp && "expected a valid global op");
551 }
552
553 if (auto cirGlobalValue =
554 dyn_cast<cir::CIRGlobalValueInterface>(globalValueOp))
555 if (!cirGlobalValue.isDeclaration())
556 return;
557
558 // If this is OpenMP, check if it is legal to emit this global normally.
560
561 // Otherwise, emit the definition and move on to the next one.
563}
564
566 // Emit code for any potentially referenced deferred decls. Since a previously
567 // unused static decl may become used during the generation of code for a
568 // static function, iterate until no changes are made.
569
571
573 // Emitting a vtable doesn't directly cause more vtables to
574 // become deferred, although it can cause functions to be
575 // emitted that then need those vtables.
576 assert(deferredVTables.empty());
577
578 // Emit CUDA/HIP static device variables referenced by host code only.
579 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
580 // needed for further handling.
581 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
582 llvm::append_range(deferredDeclsToEmit,
583 getASTContext().CUDADeviceVarODRUsedByHost);
584
585 // Stop if we're out of both deferred vtables and deferred declarations.
586 if (deferredDeclsToEmit.empty())
587 return;
588
589 // Grab the list of decls to emit. If emitGlobalDefinition schedules more
590 // work, it will not interfere with this.
591 std::vector<GlobalDecl> curDeclsToEmit;
592 curDeclsToEmit.swap(deferredDeclsToEmit);
593
594 for (const GlobalDecl &d : curDeclsToEmit) {
595 // Functions declared with the sycl_kernel_entry_point attribute are
596 // emitted normally during host compilation. During device compilation, a
597 // SYCL kernel caller offload entry point function is generated and emitted
598 // in place of each of these functions.
599 if (const auto *fd = d.getDecl()->getAsFunction()) {
600 if (langOpts.SYCLIsDevice && fd->hasAttr<SYCLKernelEntryPointAttr>() &&
601 fd->isDefined()) {
602 // Functions with an invalid sycl_kernel_entry_point attribute are
603 // ignored during device compilation.
604 if (!fd->getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
605 // Generate and emit the SYCL kernel caller function.
607 // Recurse to emit any symbols directly or indirectly referenced
608 // by the SYCL kernel caller function.
609 emitDeferred();
610 }
611 // Do not emit the sycl_kernel_entry_point attributed function.
612 continue;
613 }
614 }
615
617
618 // If we found out that we need to emit more decls, do that recursively.
619 // This has the advantage that the decls are emitted in a DFS and related
620 // ones are close together, which is convenient for testing.
621 if (!deferredVTables.empty() || !deferredDeclsToEmit.empty()) {
622 emitDeferred();
623 assert(deferredVTables.empty() && deferredDeclsToEmit.empty());
624 }
625 }
626}
627
629 const Decl *d) {
630 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
631 // postfix beginning with '.' since the symbol name can be demangled.
632 if (langOpts.HIP)
633 os << (isa<VarDecl>(d) ? ".static." : ".intern.");
634 else
635 os << (isa<VarDecl>(d) ? "__static__" : "__intern__");
636
637 // If the CUID is not specified we try to generate a unique postfix.
638 if (getLangOpts().CUID.empty()) {
639 // TODO: Once we add 'PreprocessorOpts' into CIRGenModule this part can be
640 // brought in from OG.
642 "printPostfixForExternalizedDecl: CUID is not specified");
643 } else {
644 os << getASTContext().getCUIDHash();
645 }
646}
647
649 const ValueDecl *global) {
650 const LangOptions &langOpts = cgm.getLangOpts();
651 if (!langOpts.OpenMPIsTargetDevice && !langOpts.CUDA)
652 return false;
653
654 const auto *aa = global->getAttr<AliasAttr>();
655 GlobalDecl aliaseeGD;
656
657 // Check if the aliasee exists, if the aliasee is not found, skip the alias
658 // emission. This is executed for both the host and device.
659 if (!cgm.lookupRepresentativeDecl(aa->getAliasee(), aliaseeGD))
660 return true;
661
662 const auto *aliaseeDecl = dyn_cast<ValueDecl>(aliaseeGD.getDecl());
663 if (langOpts.OpenMPIsTargetDevice)
664 return !aliaseeDecl ||
665 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(aliaseeDecl);
666
667 // CUDA / HIP
668 const bool hasDeviceAttr = global->hasAttr<CUDADeviceAttr>();
669 const bool aliaseeHasDeviceAttr =
670 aliaseeDecl && aliaseeDecl->hasAttr<CUDADeviceAttr>();
671
672 if (langOpts.CUDAIsDevice)
673 return !hasDeviceAttr || !aliaseeHasDeviceAttr;
674
675 // CUDA / HIP Host
676 // we know that the aliasee exists from above, so we know to emit
677 return false;
678}
679
681 if (const auto *cd = dyn_cast<clang::OpenACCConstructDecl>(gd.getDecl())) {
683 return;
684 }
685
686 const auto *global = cast<ValueDecl>(gd.getDecl());
687
688 // Weak references don't produce any output by themselves.
689 if (global->hasAttr<WeakRefAttr>())
690 return;
691
692 // If this is an alias definition (which otherwise looks like a declaration)
693 // emit it now.
694 if (global->hasAttr<AliasAttr>()) {
695 if (shouldSkipAliasEmission(*this, global))
696 return;
698 return;
699 }
700
701 // If this is CUDA, be selective about which declarations we emit.
702 if (langOpts.CUDA && !getASTContext().shouldEmitCUDADecl(global))
703 return;
704
705 if (langOpts.OpenMP) {
706 // If this is OpenMP, check if it is legal to emit this global normally.
707 if (openMPRuntime && openMPRuntime->emitTargetGlobal(gd))
708 return;
709 if (auto *drd = dyn_cast<OMPDeclareReductionDecl>(global)) {
710 if (mustBeEmitted(global))
712 return;
713 }
714 if (auto *dmd = dyn_cast<OMPDeclareMapperDecl>(global)) {
715 if (mustBeEmitted(global))
717 return;
718 }
719 }
720
721 if (const auto *fd = dyn_cast<FunctionDecl>(global)) {
722 // Update deferred annotations with the latest declaration if the function
723 // was already used or defined.
724 if (fd->hasAttr<AnnotateAttr>()) {
725 StringRef mangledName = getMangledName(gd);
726 if (getGlobalValue(mangledName))
727 deferredAnnotations[mangledName] = fd;
728 }
729 if (!fd->doesThisDeclarationHaveABody()) {
730 if (!fd->doesDeclarationForceExternallyVisibleDefinition() &&
731 (!fd->isMultiVersion() || !getTarget().getTriple().isAArch64()))
732 return;
733
735 cir::FuncType ty = getTypes().getFunctionType(fi);
736 getAddrOfFunction(gd, ty, /*ForVTable=*/false, /*DontDefer=*/false);
737 return;
738 }
739 } else {
740 const auto *vd = cast<VarDecl>(global);
741 assert(vd->isFileVarDecl() && "Cannot emit local var decl as global.");
742 if (vd->isThisDeclarationADefinition() != VarDecl::Definition &&
743 !astContext.isMSStaticDataMemberInlineDefinition(vd)) {
745 // If this declaration may have caused an inline variable definition to
746 // change linkage, make sure that it's emitted.
747 if (astContext.getInlineVariableDefinitionKind(vd) ==
750 // Otherwise, we can ignore this declaration. The variable will be emitted
751 // on its first use.
752 return;
753 }
754 }
755
756 // Defer code generation to first use when possible, e.g. if this is an inline
757 // function. If the global must always be emitted, do it eagerly if possible
758 // to benefit from cache locality. Deferring code generation is necessary to
759 // avoid adding initializers to external declarations.
760 if (mustBeEmitted(global) && mayBeEmittedEagerly(global)) {
761 // Make sure we don't double-emit this declaration.
762 if (auto existing = dyn_cast_if_present<cir::CIRGlobalValueInterface>(
764 existing && !existing.isDeclaration())
765 return;
766
767 // Emit the definition if it can't be deferred.
769 return;
770 }
771
772 // If we're deferring emission of a C++ variable with an initializer, remember
773 // the order in which it appeared on the file.
775
776 llvm::StringRef mangledName = getMangledName(gd);
777 if (getGlobalValue(mangledName) != nullptr) {
778 // The value has already been used and should therefore be emitted.
780 } else if (mustBeEmitted(global)) {
781 // The value must be emitted, but cannot be emitted eagerly.
782 assert(!mayBeEmittedEagerly(global));
784 } else {
785 // Otherwise, remember that we saw a deferred decl with this name. The first
786 // use of the mangled name will cause it to move into deferredDeclsToEmit.
787 deferredDecls[mangledName] = gd;
788 }
789}
790
792 mlir::Operation *op) {
793 auto const *funcDecl = cast<FunctionDecl>(gd.getDecl());
795 cir::FuncType funcType = getTypes().getFunctionType(fi);
796 cir::FuncOp funcOp = dyn_cast_if_present<cir::FuncOp>(op);
797 if (!funcOp || funcOp.getFunctionType() != funcType) {
798 funcOp = getAddrOfFunction(gd, funcType, /*ForVTable=*/false,
799 /*DontDefer=*/true, ForDefinition);
800 }
801
802 // Already emitted.
803 if (!funcOp.isDeclaration())
804 return;
805
806 setFunctionLinkage(gd, funcOp);
807 setGVProperties(funcOp, funcDecl);
809 maybeSetTrivialComdat(*funcDecl, funcOp);
811
812 CIRGenFunction cgf(*this, builder);
813 curCGF = &cgf;
814 {
815 mlir::OpBuilder::InsertionGuard guard(builder);
816 cgf.generateCode(gd, funcOp, funcType);
817 }
818 curCGF = nullptr;
819
820 setNonAliasAttributes(gd, funcOp);
822
823 auto getPriority = [this](const auto *attr) -> int {
824 Expr *e = attr->getPriority();
825 if (e)
826 return e->EvaluateKnownConstInt(this->getASTContext()).getExtValue();
827 return attr->DefaultPriority;
828 };
829
830 if (const ConstructorAttr *ca = funcDecl->getAttr<ConstructorAttr>())
831 addGlobalCtor(funcOp, getPriority(ca));
832 if (const DestructorAttr *da = funcDecl->getAttr<DestructorAttr>())
833 addGlobalDtor(funcOp, getPriority(da));
834
835 if (funcDecl->getAttr<AnnotateAttr>())
836 deferredAnnotations[getMangledName(gd)] = funcDecl;
837
838 if (getLangOpts().OpenMP && funcDecl->hasAttr<OMPDeclareTargetDeclAttr>())
840}
841
842/// Track functions to be called before main() runs.
843void CIRGenModule::addGlobalCtor(cir::FuncOp ctor,
844 std::optional<int> priority) {
847
848 // Traditional LLVM codegen directly adds the function to the list of global
849 // ctors. In CIR we just add a global_ctor attribute to the function. The
850 // global list is created in LoweringPrepare.
851 //
852 // FIXME(from traditional LLVM): Type coercion of void()* types.
853 ctor.setGlobalCtorPriority(priority);
854}
855
856/// Add a function to the list that will be called when the module is unloaded.
857void CIRGenModule::addGlobalDtor(cir::FuncOp dtor,
858 std::optional<int> priority) {
859 if (codeGenOpts.RegisterGlobalDtorsWithAtExit &&
860 (!getASTContext().getTargetInfo().getTriple().isOSAIX()))
861 errorNYI(dtor.getLoc(), "registerGlobalDtorsWithAtExit");
862
863 // FIXME(from traditional LLVM): Type coercion of void()* types.
864 dtor.setGlobalDtorPriority(priority);
865}
866
869 if ((dk == VarDecl::Definition && vd->hasAttr<DLLImportAttr>()) ||
870 (langOpts.CUDA && !getASTContext().shouldEmitCUDADecl(vd)))
871 return;
872
874 // If we have a definition, this might be a deferred decl. If the
875 // instantiation is explicit, make sure we emit it at the end.
878
880}
881
882mlir::Operation *CIRGenModule::getGlobalValue(StringRef name) {
883 auto it = symbolLookupCache.find(name);
884 return it != symbolLookupCache.end() ? it->second : nullptr;
885}
886
887cir::GlobalOp
888CIRGenModule::createGlobalOp(mlir::Location loc, StringRef name, mlir::Type t,
889 bool isConstant,
890 mlir::ptr::MemorySpaceAttrInterface addrSpace,
891 mlir::Operation *insertPoint) {
892 cir::GlobalOp g;
893 CIRGenBuilderTy &builder = getBuilder();
894
895 {
896 mlir::OpBuilder::InsertionGuard guard(builder);
897
898 // If an insertion point is provided, we're replacing an existing global,
899 // otherwise, create the new global immediately after the last gloabl we
900 // emitted.
901 if (insertPoint) {
902 builder.setInsertionPoint(insertPoint);
903 } else {
904 // Group global operations together at the top of the module.
905 if (lastGlobalOp)
906 builder.setInsertionPointAfter(lastGlobalOp);
907 else
908 builder.setInsertionPointToStart(getModule().getBody());
909 }
910
911 g = cir::GlobalOp::create(builder, loc, name, t, isConstant, addrSpace);
912 if (!insertPoint)
913 lastGlobalOp = g;
914
915 // Default to private until we can judge based on the initializer,
916 // since MLIR doesn't allow public declarations.
917 mlir::SymbolTable::setSymbolVisibility(
918 g, mlir::SymbolTable::Visibility::Private);
919 }
920 symbolLookupCache[g.getSymNameAttr()] = g;
921 return g;
922}
923
924void CIRGenModule::setCommonAttributes(GlobalDecl gd, mlir::Operation *gv) {
925 const Decl *d = gd.getDecl();
926 if (isa_and_nonnull<NamedDecl>(d))
927 setGVProperties(gv, dyn_cast<NamedDecl>(d));
929
930 if (auto gvi = mlir::dyn_cast<cir::CIRGlobalValueInterface>(gv)) {
931 if (d && d->hasAttr<UsedAttr>())
933
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 &&
939 vd->getStorageDuration() == SD_Static &&
940 vd->getType().isConstQualified())))
942 }
943}
944
945/// Get the feature delta from the default feature map for the given target CPU.
946static std::vector<std::string>
947getFeatureDeltaFromDefault(const CIRGenModule &cgm, llvm::StringRef targetCPU,
948 llvm::StringMap<bool> &featureMap) {
949 llvm::StringMap<bool> defaultFeatureMap;
951 defaultFeatureMap, cgm.getASTContext().getDiagnostics(), targetCPU, {});
952
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());
958 }
959
960 return delta;
961}
962
963bool CIRGenModule::getCPUAndFeaturesAttributes(
964 GlobalDecl gd, llvm::StringMap<std::string> &attrs,
965 bool setTargetFeatures) {
966 // Add target-cpu and target-features attributes to functions. If
967 // we have a decl for the function and it has a target attribute then
968 // parse that and add it to the feature set.
969 llvm::StringRef targetCPU = getTarget().getTargetOpts().CPU;
970 llvm::StringRef tuneCPU = getTarget().getTargetOpts().TuneCPU;
971 std::vector<std::string> features;
972 // `fd` may be null when emitting attributes for globals that don't have a
973 // FunctionDecl. The AMDGPU branch below handles
974 // the null case via initFeatureMap.
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);
986
987 // Now add the target-cpu and target-features to the function.
988 // While we populated the feature map above, we still need to
989 // get and parse the target/target_clones attribute so we can
990 // get the cpu for the function.
991 llvm::StringRef featureStr = td ? td->getFeaturesStr() : llvm::StringRef();
992 if (tc && (getTriple().isOSAIX() || getTriple().isX86()))
993 featureStr = tc->getFeatureStr(gd.getMultiVersionIndex());
994 if (!featureStr.empty()) {
995 clang::ParsedTargetAttr parsedAttr =
996 getTarget().parseTargetAttr(featureStr);
997 if (!parsedAttr.CPU.empty() &&
998 getTarget().isValidCPUName(parsedAttr.CPU)) {
999 targetCPU = parsedAttr.CPU;
1000 tuneCPU = ""; // Clear the tune CPU.
1001 }
1002 if (!parsedAttr.Tune.empty() &&
1003 getTarget().isValidCPUName(parsedAttr.Tune))
1004 tuneCPU = parsedAttr.Tune;
1005 }
1006
1007 if (sd) {
1008 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
1009 // favor this processor.
1010 tuneCPU = sd->getCPUName(gd.getMultiVersionIndex())->getName();
1011 }
1012
1013 // For AMDGPU, only emit delta features (features that differ from the
1014 // target CPU's defaults). Other targets might want to follow a similar
1015 // pattern.
1016 if (getTarget().getTriple().isAMDGPU()) {
1017 features = getFeatureDeltaFromDefault(*this, targetCPU, featureMap);
1018 } else {
1019 // Produce the canonical string for this set of features.
1020 features.reserve(features.size() + featureMap.size());
1021 for (const auto &entry : featureMap)
1022 features.push_back((entry.getValue() ? "+" : "-") +
1023 entry.getKey().str());
1024 }
1025 } else {
1026 // Just add the existing target cpu and target features to the function.
1027 if (setTargetFeatures && getTarget().getTriple().isAMDGPU()) {
1028 llvm::StringMap<bool> featureMap;
1029 if (fd)
1030 astContext.getFunctionFeatureMap(featureMap, gd);
1031 else
1032 getTarget().initFeatureMap(featureMap, astContext.getDiagnostics(),
1033 targetCPU,
1034 getTarget().getTargetOpts().Features);
1035 features = getFeatureDeltaFromDefault(*this, targetCPU, featureMap);
1036 } else {
1037 features = getTarget().getTargetOpts().Features;
1038 }
1039 }
1040
1041 if (!targetCPU.empty()) {
1042 attrs[cir::CIRDialect::getTargetCPUAttrName()] = targetCPU.str();
1043 addedAttr = true;
1044 }
1045 if (!tuneCPU.empty()) {
1046 attrs[cir::CIRDialect::getTuneCPUAttrName()] = tuneCPU.str();
1047 addedAttr = true;
1048 }
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 '-'");
1053 return getTarget().isReadOnlyFeature(f.substr(1));
1054 });
1055 llvm::sort(features);
1056 attrs[cir::CIRDialect::getTargetFeaturesAttrName()] =
1057 llvm::join(features, ",");
1058 addedAttr = true;
1059 }
1060 // TODO(cir): add metadata for AArch64 Function Multi Versioning.
1062 return addedAttr;
1063}
1064
1065void CIRGenModule::setNonAliasAttributes(GlobalDecl gd, mlir::Operation *op) {
1066 setCommonAttributes(gd, op);
1067
1068 const Decl *d = gd.getDecl();
1069 if (d) {
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()));
1073 if (d->hasAttr<RetainAttr>())
1074 addUsedGlobal(gvi);
1075
1076 if (auto func = dyn_cast<cir::FuncOp>(op)) {
1077 llvm::StringMap<std::string> attrs;
1078 if (getCPUAndFeaturesAttributes(gd, attrs)) {
1079 // TODO(cir): Classic codegen also removes fmv-features here, which
1080 // CIR does not emit yet.
1081 //
1082 // getCPUAndFeaturesAttributes reads the most recent declaration, so
1083 // its result supersedes anything an earlier one wrote. Clear first:
1084 // setAttr alone would leave a name this call no longer produces.
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));
1092 }
1093 }
1094 }
1095 }
1096
1099}
1100
1101std::optional<cir::SourceLanguage> CIRGenModule::getCIRSourceLanguage() const {
1102 using ClangStd = clang::LangStandard;
1103 using CIRLang = cir::SourceLanguage;
1104 auto opts = getLangOpts();
1105
1106 if (opts.OpenCLCPlusPlus)
1107 return CIRLang::OpenCLCXX;
1108 if (opts.OpenCL)
1109 return CIRLang::OpenCLC;
1110 if (opts.CPlusPlus)
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)
1115 return CIRLang::C;
1116
1117 // TODO(cir): support remaining source languages.
1119 errorNYI("CIR does not yet support the given source language");
1120 return std::nullopt;
1121}
1122
1124 if (langOpts.OpenCL) {
1129 return as;
1130 }
1131
1132 if (langOpts.SYCLIsDevice &&
1133 (!d || d->getType().getAddressSpace() == LangAS::Default))
1134 return LangAS::sycl_global;
1135
1136 if (langOpts.CUDA && langOpts.CUDAIsDevice) {
1137 if (d) {
1138 if (d->hasAttr<CUDAConstantAttr>())
1139 return LangAS::cuda_constant;
1140 if (d->hasAttr<CUDASharedAttr>())
1141 return LangAS::cuda_shared;
1142 if (d->hasAttr<CUDADeviceAttr>())
1143 return LangAS::cuda_device;
1144 if (d->getType().isConstQualified())
1145 return LangAS::cuda_constant;
1146 }
1147 return LangAS::cuda_device;
1148 }
1149
1150 if (langOpts.OpenMP && d && d->hasAttr<OMPAllocateDeclAttr>())
1151 errorNYI(d->getSourceRange(), "OpenMP global address space");
1152
1154}
1155
1156static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd) {
1157 // Set linkage and visibility in case we never see a definition.
1159 // Don't set internal linkage on declarations.
1160 // "extern_weak" is overloaded in LLVM; we probably should have
1161 // separate linkage types for this.
1162 if (isExternallyVisible(lv.getLinkage()) &&
1163 (nd->hasAttr<WeakAttr>() || nd->isWeakImported()))
1164 gv.setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
1165}
1166
1167static void setLinkageForFunction(CIRGenModule &cgm, cir::FuncOp &func,
1168 const NamedDecl *nd) {
1169 // Mirrors CodeGenModule::setLinkageForGV for function declarations.
1171 if (isExternallyVisible(lv.getLinkage()) &&
1172 (nd->hasAttr<WeakAttr>() || nd->isWeakImported())) {
1173 auto linkage = cir::GlobalLinkageKind::ExternalWeakLinkage;
1174 func.setLinkage(linkage);
1175 func.setLinkageAttr(
1176 cir::GlobalLinkageKindAttr::get(&cgm.getMLIRContext(), linkage));
1177 // Declarations must keep 'private' MLIR visibility; only update for defs.
1178 if (!func.isDeclaration())
1179 mlir::SymbolTable::setSymbolVisibility(
1180 func, cgm.getMLIRVisibilityFromCIRLinkage(linkage));
1181 }
1182}
1183
1184static llvm::SmallVector<int64_t> indexesOfArrayAttr(mlir::ArrayAttr indexes) {
1186 for (mlir::Attribute i : indexes) {
1187 auto ind = mlir::cast<mlir::IntegerAttr>(i);
1188 inds.push_back(ind.getValue().getSExtValue());
1189 }
1190 return inds;
1191}
1192
1193static bool isViewOnGlobal(cir::GlobalOp glob, cir::GlobalViewAttr view) {
1194 return view.getSymbol().getValue() == glob.getSymName();
1195}
1196
1197static mlir::Attribute createNewGlobalView(CIRGenModule &cgm,
1198 cir::GlobalOp newGlob,
1199 cir::GlobalViewAttr attr,
1200 mlir::Type oldTy) {
1201 // If the attribute does not require indexes or it is not a global view on
1202 // the global we're replacing, keep the original attribute.
1203 if (!attr.getIndices() || !isViewOnGlobal(newGlob, attr))
1204 return attr;
1205
1206 llvm::SmallVector<int64_t> oldInds = indexesOfArrayAttr(attr.getIndices());
1208 CIRGenBuilderTy &bld = cgm.getBuilder();
1209 const cir::CIRDataLayout &layout = cgm.getDataLayout();
1210 mlir::Type newTy = newGlob.getSymType();
1211
1212 uint64_t offset =
1213 bld.computeOffsetFromGlobalViewIndices(layout, oldTy, oldInds);
1214 if (!bld.computeGlobalViewIndicesFromFlatOffset(offset, newTy, layout,
1215 newInds))
1216 return cir::GlobalOffsetAttr::get(attr.getType(), attr.getSymbol(),
1217 static_cast<int64_t>(offset));
1218
1219 cir::PointerType newPtrTy;
1220
1221 if (isa<cir::RecordType>(oldTy))
1222 newPtrTy = cir::PointerType::get(newTy);
1223 else if (isa<cir::ArrayType>(oldTy))
1224 newPtrTy = cast<cir::PointerType>(attr.getType());
1225
1226 if (newPtrTy)
1227 return bld.getGlobalViewAttr(newPtrTy, newGlob, newInds,
1228 attr.getAddressPoint());
1229
1230 // This may be unreachable in practice, but keep it as errorNYI while CIR
1231 // is still under development.
1232 cgm.errorNYI("Unhandled type in createNewGlobalView");
1233 return {};
1234}
1235
1236static mlir::Attribute getNewInitValue(CIRGenModule &cgm, cir::GlobalOp newGlob,
1237 mlir::Type oldTy,
1238 mlir::Attribute oldInit) {
1239 if (auto oldView = mlir::dyn_cast<cir::GlobalViewAttr>(oldInit))
1240 return createNewGlobalView(cgm, newGlob, oldView, oldTy);
1241
1242 // A byte offset from a symbol doesn't depend on the symbol's type, so it
1243 // remains valid when the global is replaced.
1244 if (mlir::isa<cir::GlobalOffsetAttr>(oldInit))
1245 return oldInit;
1246
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))
1252 newElements.push_back(createNewGlobalView(cgm, newGlob, view, oldTy));
1253 else if (mlir::isa<cir::ConstArrayAttr, cir::ConstRecordAttr>(elt))
1254 newElements.push_back(getNewInitValue(cgm, newGlob, oldTy, elt));
1255 else
1256 newElements.push_back(elt);
1257 }
1258 return mlir::ArrayAttr::get(cgm.getBuilder().getContext(), newElements);
1259 };
1260
1261 if (auto oldArray = mlir::dyn_cast<cir::ConstArrayAttr>(oldInit)) {
1262 // ConstArrayAttr::verify guarantees the elements are either an ArrayAttr or
1263 // a StringAttr. A StringAttr is a string-literal initializer: raw 8-bit
1264 // character bytes with no nested global references, so there is nothing to
1265 // rewrite and it is returned unchanged. The ArrayAttr case recurses to
1266 // rewrite any nested global views.
1267 mlir::Attribute oldElts = oldArray.getElts();
1268 if (mlir::isa<mlir::StringAttr>(oldElts))
1269 return oldInit;
1270 mlir::Attribute newElements =
1271 getNewInitElements(mlir::cast<mlir::ArrayAttr>(oldElts));
1272 return cgm.getBuilder().getConstArray(
1273 newElements, mlir::cast<cir::ArrayType>(oldArray.getType()));
1274 }
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());
1278 return cgm.getBuilder().getConstRecordOrZeroAttr(newMembers, recordTy);
1279 }
1280
1281 // This may be unreachable in practice, but keep it as errorNYI while CIR
1282 // is still under development.
1283 cgm.errorNYI("Unhandled type in getNewInitValue");
1284 return {};
1285}
1286
1287// We want to replace a global value, but because of CIR's typed pointers,
1288// we need to update the existing uses to reflect the new type, not just replace
1289// them directly.
1290void CIRGenModule::replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV) {
1291 assert(oldGV.getSymName() == newGV.getSymName() && "symbol names must match");
1292
1293 mlir::Type oldTy = oldGV.getSymType();
1294 mlir::Type newTy = newGV.getSymType();
1295
1297
1298 // If the type didn't change, why are we here?
1299 assert(oldTy != newTy && "expected type change in replaceGlobal");
1300
1301 // Visit all uses and add handling to fix up the types.
1302 std::optional<mlir::SymbolTable::UseRange> oldSymUses =
1303 oldGV.getSymbolUses(getModule());
1304 for (mlir::SymbolTable::SymbolUse use : *oldSymUses) {
1305 mlir::Operation *userOp = use.getUser();
1306 assert(
1307 (mlir::isa<cir::GetGlobalOp, cir::GlobalOp, cir::ConstantOp>(userOp)) &&
1308 "Unexpected user for global op");
1309
1310 if (auto getGlobalOp = dyn_cast<cir::GetGlobalOp>(use.getUser())) {
1311 mlir::Value useOpResultValue = getGlobalOp.getAddr();
1312 useOpResultValue.setType(cir::PointerType::get(newTy));
1313
1314 mlir::OpBuilder::InsertionGuard guard(builder);
1315 builder.setInsertionPointAfter(getGlobalOp);
1316 mlir::Type ptrTy = builder.getPointerTo(oldTy);
1317 mlir::Value cast =
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);
1324 }
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());
1332 c.erase();
1333 }
1334 }
1335
1336 // If the old global is being tracked as the most-recently-created global,
1337 // update it so that subsequent globals are not inserted after a (now
1338 // erased) operation, which would leave them detached from the module.
1339 if (lastGlobalOp == oldGV)
1340 lastGlobalOp = newGV;
1341 if (getLangOpts().CUDA)
1342 getCUDARuntime().handleGlobalReplace(oldGV, newGV);
1343 eraseGlobalSymbol(oldGV);
1344 oldGV.erase();
1345}
1346
1347/// If the specified mangled name is not in the module,
1348/// create and return an mlir GlobalOp with the specified type (TODO(cir):
1349/// address space).
1350///
1351/// TODO(cir):
1352/// 1. If there is something in the module with the specified name, return
1353/// it potentially bitcasted to the right type.
1354///
1355/// 2. If \p d is non-null, it specifies a decl that correspond to this. This
1356/// is used to set the attributes on the global when it is first created.
1357///
1358/// 3. If \p isForDefinition is true, it is guaranteed that an actual global
1359/// with type \p ty will be returned, not conversion of a variable with the same
1360/// mangled name but some other type.
1362 StringRef mangledName, mlir::Type ty, LangAS langAS, mlir::Location loc,
1363 const VarDecl *d, ForDefinition_t isForDefinition) {
1364
1365 // Lookup the entry, lazily creating it if necessary.
1366 cir::GlobalOp entry;
1367 if (mlir::Operation *v = getGlobalValue(mangledName)) {
1368 if (!isa<cir::GlobalOp>(v)) {
1369 errorNYI(loc, "getOrCreateCIRGlobal: global with non-GlobalOp type");
1370 return nullptr;
1371 }
1372 entry = cast<cir::GlobalOp>(v);
1373 }
1374
1375 if (entry) {
1376 mlir::ptr::MemorySpaceAttrInterface entryCIRAS = entry.getAddrSpaceAttr();
1377
1378 // A weakref's target is only weak until something else names it.
1379 if (weakRefReferences.erase(entry) && d && !d->hasAttr<WeakAttr>())
1380 entry.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
1381
1383
1384 if (langOpts.OpenMP && !langOpts.OpenMPSimd && d)
1386
1387 if (entry.getSymType() == ty &&
1390 return entry;
1391
1392 // If there are two attempts to define the same mangled name, issue an
1393 // error.
1394 //
1395 // TODO(cir): look at mlir::GlobalValue::isDeclaration for all aspects of
1396 // recognizing the global as a declaration, for now only check if
1397 // initializer is present.
1398 if (isForDefinition && !entry.isDeclaration()) {
1399 errorNYI(loc, "getOrCreateCIRGlobal: global with conflicting type");
1400 }
1401
1402 // Address space check removed because it is unnecessary because CIR records
1403 // address space info in types.
1404
1405 // (If global is requested for a definition, we always need to create a new
1406 // global, not just return a bitcast.)
1407 if (!isForDefinition)
1408 return entry;
1409 }
1410
1411 // Calculate constant storage flag before creating the global. This was moved
1412 // from after the global creation to ensure the constant flag is set correctly
1413 // at creation time, matching the logic used in emitCXXGlobalVarDeclInit.
1414 bool isConstant = false;
1415 if (d) {
1416 QualType declType = d->getType();
1417
1418 // Classic codegen doesn't try to exclude ctor or dtor here, but has a FIXME
1419 // to try to do a better job. So this bit of code does slightly more effort
1420 // to get a more accurate answer. We can try to exclude ctor, but only when
1421 // the type is complete, as otherwise we have to check for
1422 // fields(particularly whether they are mutable).
1423 bool excludeCtor = !declType->isIncompleteType();
1424 bool needsDtor =
1426
1427 isConstant = declType.isConstantStorage(astContext, excludeCtor,
1428 /*ExcludeDtor=*/!needsDtor);
1429 }
1430
1431 mlir::ptr::MemorySpaceAttrInterface declCIRAS =
1433
1434 // mlir::SymbolTable::Visibility::Public is the default, no need to explicitly
1435 // mark it as such.
1436 cir::GlobalOp gv = createGlobalOp(loc, mangledName, ty, isConstant, declCIRAS,
1437 /*insertPoint=*/entry.getOperation());
1438
1439 // If we already created a global with the same mangled name (but different
1440 // type) before, remove it from its parent.
1441 if (entry)
1442 replaceGlobal(entry, gv);
1443
1444 // This is the first use or definition of a mangled name. If there is a
1445 // deferred decl with this name, remember that we need to emit it at the end
1446 // of the file.
1447 auto ddi = deferredDecls.find(mangledName);
1448 if (ddi != deferredDecls.end()) {
1449 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1450 // list, and remove it from DeferredDecls (since we don't need it anymore).
1451 addDeferredDeclToEmit(ddi->second);
1452 deferredDecls.erase(ddi);
1453 }
1454
1455 // Handle things which are present even on external declarations.
1456 if (d) {
1457 if (langOpts.OpenMP && !langOpts.OpenMPSimd)
1459
1460 gv.setAlignmentAttr(getSize(astContext.getDeclAlign(d)));
1461
1462 setLinkageForGV(gv, d);
1463
1464 if (d->getTLSKind())
1465 setTLSMode(gv, *d);
1466
1467 setGVProperties(gv, d);
1468
1469 // If required by the ABI, treat declarations of static data members with
1470 // inline initializers as definitions.
1471 if (astContext.isMSStaticDataMemberInlineDefinition(d))
1473 "getOrCreateCIRGlobal: MS static data member inline definition");
1474
1475 // Emit section information for extern variables.
1476 if (d->hasExternalStorage()) {
1477 if (const SectionAttr *sa = d->getAttr<SectionAttr>())
1478 gv.setSectionAttr(builder.getStringAttr(sa->getName()));
1479 }
1480
1481 // Handle XCore specific ABI requirements.
1482 if (getTriple().getArch() == llvm::Triple::xcore)
1484 "getOrCreateCIRGlobal: XCore specific ABI requirements");
1485
1486 // Check if we a have a const declaration with an initializer, we may be
1487 // able to emit it as available_externally to expose it's value to the
1488 // optimizer.
1489 if (getLangOpts().CPlusPlus && gv.isPublic() &&
1490 d->getType().isConstQualified() && gv.isDeclaration() &&
1491 !d->hasDefinition() && d->hasInit() && !d->hasAttr<DLLImportAttr>())
1492 errorNYI(
1493 d->getSourceRange(),
1494 "getOrCreateCIRGlobal: external const declaration with initializer");
1495 }
1496
1497 if (d &&
1500 // TODO(cir): set target attributes
1501 // External HIP managed variables needed to be recorded for transformation
1502 // in both device and host compilations.
1503 if (getLangOpts().CUDA && d && d->hasAttr<HIPManagedAttr>() &&
1504 d->hasExternalStorage())
1506 }
1507
1509 return gv;
1510}
1511
1513 const auto *aa = vd->getAttr<AliasAttr>();
1514 assert(aa && "No alias?");
1515
1516 // See if there is already something with the target's name in the module.
1517 if (mlir::Operation *entry = getGlobalValue(aa->getAliasee())) {
1518 // Classic codegen is able to just treat whatever value it gets as the
1519 // 'right' type. This needs to introduce SOME sort of conversion it seems.
1520 // For now, reject any cases that don't match.
1521 if (const auto *fd = dyn_cast<FunctionDecl>(vd)) {
1522 auto fn = dyn_cast<cir::FuncOp>(entry);
1523
1524 if (fn && fn.getFunctionType() == convertType(fd->getType()))
1525 return fn;
1526 } else if (auto gv = dyn_cast<cir::GlobalOp>(entry)) {
1527 if (gv.getSymType() == getTypes().convertTypeForMem(vd->getType()))
1528 return gv;
1529 }
1530
1532 "weakref target already declared with a different type");
1533 return nullptr;
1534 }
1535
1536 mlir::Operation *aliasee;
1537 if (const auto *fd = dyn_cast<FunctionDecl>(vd)) {
1538 cir::FuncOp fn =
1539 getOrCreateCIRFunction(aa->getAliasee(), convertType(fd->getType()),
1540 GlobalDecl(fd), /*forVTable=*/false);
1541 fn.setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
1542 aliasee = fn;
1543 } else {
1544 cir::GlobalOp gv = getOrCreateCIRGlobal(
1545 aa->getAliasee(), getTypes().convertTypeForMem(vd->getType()),
1546 LangAS::Default, getLoc(vd->getSourceRange()), /*d=*/nullptr,
1548 gv.setLinkage(cir::GlobalLinkageKind::ExternalWeakLinkage);
1549 aliasee = gv;
1550 }
1551
1552 weakRefReferences.insert(aliasee);
1553 return aliasee;
1554}
1555
1556cir::GlobalOp
1558 ForDefinition_t isForDefinition) {
1559 assert(d->hasGlobalStorage() && "Not a global variable");
1560 QualType astTy = d->getType();
1561 if (!ty)
1562 ty = getTypes().convertTypeForMem(astTy);
1563
1564 StringRef mangledName = getMangledName(d);
1565 return getOrCreateCIRGlobal(mangledName, ty, getGlobalVarAddressSpace(d),
1566 getLoc(d->getSourceRange()), d, isForDefinition);
1567}
1568
1569/// Return the mlir::Value for the address of the given global variable. If
1570/// \p ty is non-null and if the global doesn't exist, then it will be created
1571/// with the specified type instead of whatever the normal requested type would
1572/// be. If \p isForDefinition is true, it is guaranteed that an actual global
1573/// with type \p ty will be returned, not conversion of a variable with the same
1574/// mangled name but some other type.
1575mlir::Value CIRGenModule::getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty,
1576 ForDefinition_t isForDefinition) {
1577 assert(d->hasGlobalStorage() && "Not a global variable");
1578 QualType astTy = d->getType();
1579 if (!ty)
1580 ty = getTypes().convertTypeForMem(astTy);
1581
1582 bool tlsAccess = d->getTLSKind() != VarDecl::TLS_None;
1583 cir::GlobalOp g = getOrCreateCIRGlobal(d, ty, isForDefinition);
1584 mlir::Type ptrTy = builder.getPointerTo(g.getSymType(), g.getAddrSpaceAttr());
1585 mlir::Value addr = cir::GetGlobalOp::create(
1586 builder, getLoc(d->getSourceRange()), ptrTy, g.getSymNameAttr(),
1587 tlsAccess,
1588 /*static_local=*/g.getDynamicInitGuard().has_value() &&
1589 d->isLocalVarDecl());
1590 return castGlobalToDeclAddrSpace(addr, *d);
1591}
1592
1593mlir::Value CIRGenModule::castGlobalToDeclAddrSpace(mlir::Value addr,
1594 const VarDecl &vd) {
1595 // A global may live in a different address space than its declared type,
1596 // e.g. a CUDA __shared__ variable. Like classic CodeGen, cast once where
1597 // the address is formed so every user sees the declared type.
1598 auto ptrTy = mlir::cast<cir::PointerType>(addr.getType());
1599 mlir::ptr::MemorySpaceAttrInterface declAS =
1601 if (ptrTy.getAddrSpace() == declAS)
1602 return addr;
1603 return builder.createAddrSpaceCast(
1604 addr, builder.getPointerTo(ptrTy.getPointee(), declAS));
1605}
1606
1607cir::GlobalViewAttr CIRGenModule::getAddrOfGlobalVarAttr(const VarDecl *d) {
1608 assert(d->hasGlobalStorage() && "Not a global variable");
1609 mlir::Type ty = getTypes().convertTypeForMem(d->getType());
1610
1611 cir::GlobalOp globalOp = getOrCreateCIRGlobal(d, ty, NotForDefinition);
1612 cir::PointerType ptrTy =
1613 builder.getPointerTo(globalOp.getSymType(), globalOp.getAddrSpaceAttr());
1614 return builder.getGlobalViewAttr(ptrTy, globalOp);
1615}
1616
1617void CIRGenModule::addUsedGlobal(cir::CIRGlobalValueInterface gv) {
1618 assert((mlir::isa<cir::FuncOp>(gv.getOperation()) ||
1619 !gv.isDeclarationForLinker()) &&
1620 "Only globals with definition can force usage.");
1621 llvmUsed.emplace_back(gv);
1622}
1623
1624void CIRGenModule::addCompilerUsedGlobal(cir::CIRGlobalValueInterface gv) {
1625 assert(!gv.isDeclarationForLinker() &&
1626 "Only globals with definition can force usage.");
1627 llvmCompilerUsed.emplace_back(gv);
1628}
1629
1631 cir::CIRGlobalValueInterface gv) {
1632 assert((mlir::isa<cir::FuncOp>(gv.getOperation()) ||
1633 !gv.isDeclarationForLinker()) &&
1634 "Only globals with definition can force usage.");
1635 if (getTriple().isOSBinFormatELF())
1636 llvmCompilerUsed.emplace_back(gv);
1637 else
1638 llvmUsed.emplace_back(gv);
1639}
1640
1641static void emitUsed(CIRGenModule &cgm, StringRef name,
1642 std::vector<cir::CIRGlobalValueInterface> &list) {
1643 if (list.empty())
1644 return;
1645
1646 CIRGenBuilderTy &builder = cgm.getBuilder();
1647 mlir::Location loc = builder.getUnknownLoc();
1648 cir::PointerType voidPtrTy = builder.getVoidPtrTy(
1650
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()));
1656 }
1657
1658 cir::ArrayType arrayTy = cir::ArrayType::get(voidPtrTy, usedArray.size());
1659
1660 cir::ConstArrayAttr initAttr = cir::ConstArrayAttr::get(
1661 arrayTy, mlir::ArrayAttr::get(&cgm.getMLIRContext(), usedArray));
1662
1663 cir::GlobalOp gv = cgm.createGlobalOp(
1664 loc, name, arrayTy, /*isConstant=*/false,
1666 gv.setLinkage(cir::GlobalLinkageKind::AppendingLinkage);
1667 gv.setInitialValueAttr(initAttr);
1668 gv.setSectionAttr(builder.getStringAttr("llvm.metadata"));
1669}
1670
1672 emitUsed(*this, "llvm.used", llvmUsed);
1673 emitUsed(*this, "llvm.compiler.used", llvmCompilerUsed);
1674}
1675
1677 bool isTentative) {
1678 // OpenCL global variables of sampler type are translated to function calls,
1679 // therefore no need to be translated.
1680 if (getLangOpts().OpenCL && vd->getType()->isSamplerT())
1681 return;
1682
1683 if (getLangOpts().OpenMPIsTargetDevice) {
1685 "emitGlobalVarDefinition: emit OpenMP global variable");
1686 return;
1687 }
1688
1689 // Whether the definition of the variable is available externally.
1690 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
1691 // since this is the job for its original source.
1692 bool isDefinitionAvailableExternally =
1693 astContext.GetGVALinkageForVariable(vd) == GVA_AvailableExternally;
1694
1695 // It is useless to emit the definition for an available_externally variable
1696 // which can't be marked as const.
1697 if (isDefinitionAvailableExternally &&
1698 (!vd->hasConstantInitialization() ||
1699 // TODO: Update this when we have interface to check constexpr
1700 // destructor.
1701 vd->needsDestruction(astContext) ||
1702 !vd->getType().isConstantStorage(astContext, true, true)))
1703 return;
1704
1705 mlir::Attribute init;
1706 bool needsGlobalCtor = false;
1707 bool needsGlobalDtor =
1708 !isDefinitionAvailableExternally &&
1710 const VarDecl *initDecl;
1711 const Expr *initExpr = vd->getAnyInitializer(initDecl);
1712
1713 std::optional<ConstantEmitter> emitter;
1714
1715 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
1716 // as part of their declaration." Sema has already checked for
1717 // error cases, so we just need to set Init to PoisonValue.
1718 bool isCUDASharedVar =
1719 getLangOpts().CUDAIsDevice && vd->hasAttr<CUDASharedAttr>();
1720 // Shadows of initialized device-side global variables are also left
1721 // undefined.
1722 // Managed Variables should be initialized on both host side and device side.
1723 bool isCUDAShadowVar =
1724 !getLangOpts().CUDAIsDevice && !vd->hasAttr<HIPManagedAttr>() &&
1725 (vd->hasAttr<CUDAConstantAttr>() || vd->hasAttr<CUDADeviceAttr>() ||
1726 vd->hasAttr<CUDASharedAttr>());
1727 bool isCUDADeviceShadowVar =
1728 getLangOpts().CUDAIsDevice && !vd->hasAttr<HIPManagedAttr>() &&
1731
1732 if (getLangOpts().CUDA &&
1733 (isCUDASharedVar || isCUDAShadowVar || isCUDADeviceShadowVar)) {
1734 init = cir::UndefAttr::get(convertType(vd->getType()));
1735 } else if (vd->hasAttr<LoaderUninitializedAttr>()) {
1737 "emitGlobalVarDefinition: loader uninitialized attribute");
1738 } else if (!initExpr) {
1739 // This is a tentative definition; tentative definitions are
1740 // implicitly initialized with { 0 }.
1741 //
1742 // Note that tentative definitions are only emitted at the end of
1743 // a translation unit, so they should never have incomplete
1744 // type. In addition, EmitTentativeDefinition makes sure that we
1745 // never attempt to emit a tentative definition if a real one
1746 // exists. A use may still exists, however, so we still may need
1747 // to do a RAUW.
1748 assert(!vd->getType()->isIncompleteType() && "Unexpected incomplete type");
1749 init = emitNullConstantAttr(vd->getType());
1750 } else {
1751 emitter.emplace(*this);
1752 mlir::Attribute initializer = emitter->tryEmitForInitializer(*initDecl);
1753 if (!initializer) {
1754 QualType qt = initExpr->getType();
1755 if (vd->getType()->isReferenceType())
1756 qt = vd->getType();
1757
1758 if (getLangOpts().CPlusPlus) {
1759 if (initDecl->hasFlexibleArrayInit(astContext))
1761 "emitGlobalVarDefinition: flexible array initializer");
1762 init = emitNullConstantAttr(qt);
1763 if (!isDefinitionAvailableExternally)
1764 needsGlobalCtor = true;
1765 } else {
1767 "emitGlobalVarDefinition: static initializer");
1768 }
1769 } else {
1770 init = initializer;
1771 // We don't need an initializer, so remove the entry for the delayed
1772 // initializer position (just in case this entry was delayed) if we
1773 // also don't need to register a destructor.
1775 }
1776 }
1777
1778 mlir::Type initType;
1779 if (mlir::isa<mlir::SymbolRefAttr>(init)) {
1780 errorNYI(
1781 vd->getSourceRange(),
1782 "emitGlobalVarDefinition: global initializer is a symbol reference");
1783 return;
1784 } else {
1785 assert(mlir::isa<mlir::TypedAttr>(init) && "This should have a type");
1786 auto typedInitAttr = mlir::cast<mlir::TypedAttr>(init);
1787 initType = typedInitAttr.getType();
1788 }
1789 assert(!mlir::isa<mlir::NoneType>(initType) && "Should have a type by now");
1790
1791 cir::GlobalOp gv =
1792 getOrCreateCIRGlobal(vd, initType, ForDefinition_t(!isTentative));
1793 // TODO(cir): Strip off pointer casts from Entry if we get them?
1794
1795 if (!gv || gv.getSymType() != initType) {
1797 "emitGlobalVarDefinition: global initializer with type mismatch");
1798 return;
1799 }
1800
1802
1803 if (vd->hasAttr<AnnotateAttr>())
1804 addGlobalAnnotations(vd, gv);
1805
1806 // Set CIR's linkage type as appropriate.
1807 cir::GlobalLinkageKind linkage = getCIRLinkageVarDefinition(vd);
1808
1809 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
1810 // the device. [...]"
1811 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
1812 // __device__, declares a variable that: [...]
1813 // Is accessible from all the threads within the grid and from the host
1814 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
1815 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
1816 if (langOpts.CUDA) {
1817 if (langOpts.CUDAIsDevice) {
1818 // __shared__ variables is not marked as externally initialized,
1819 // because they must not be initialized.
1820 if (linkage != cir::GlobalLinkageKind::InternalLinkage &&
1821 !vd->isConstexpr() && !vd->getType().isConstQualified() &&
1822 (vd->hasAttr<CUDADeviceAttr>() || vd->hasAttr<CUDAConstantAttr>() ||
1825 gv->setAttr(cir::CUDAExternallyInitializedAttr::getMnemonic(),
1826 cir::CUDAExternallyInitializedAttr::get(&getMLIRContext()));
1827 }
1828 } else {
1829 // Adjust linkage of shadow variables in host compilation
1831 }
1833 }
1834
1835 // Set initializer and finalize emission
1837 if (emitter)
1838 emitter->finalize(gv);
1839
1840 // If it is safe to mark the global 'constant', do so now.
1841 // Use the same logic as classic codegen EmitGlobalVarDefinition.
1842 gv.setConstant((vd->hasAttr<CUDAConstantAttr>() && langOpts.CUDAIsDevice) ||
1843 (!needsGlobalCtor && !needsGlobalDtor &&
1844 vd->getType().isConstantStorage(astContext,
1845 /*ExcludeCtor=*/true,
1846 /*ExcludeDtor=*/true)));
1847 // If it is in a read-only section, mark it 'constant'.
1848 if (const SectionAttr *sa = vd->getAttr<SectionAttr>()) {
1849 const ASTContext::SectionInfo &si = astContext.SectionInfos[sa->getName()];
1850 if ((si.SectionFlags & ASTContext::PSF_Write) == 0)
1851 gv.setConstant(true);
1852 }
1853
1854 // The global may have been created without a declaration, e.g. as the target
1855 // of a weakref, so make sure the alignment comes from the definition.
1856 gv.setAlignmentAttr(getSize(astContext.getDeclAlign(vd)));
1857
1858 // Set CIR linkage and DLL storage class.
1859 gv.setLinkage(linkage);
1860 // FIXME(cir): setLinkage should likely set MLIR's visibility automatically.
1861 gv.setVisibility(getMLIRVisibilityFromCIRLinkage(linkage));
1863 if (linkage == cir::GlobalLinkageKind::CommonLinkage) {
1864 // common vars aren't constant even if declared const.
1865 gv.setConstant(false);
1866 // Tentative definition of global variables may be initialized with
1867 // non-zero null pointers. In this case they should have weak linkage
1868 // since common linkage must have zero initializer and must not have
1869 // explicit section therefore cannot have non-zero initial value.
1870 std::optional<mlir::Attribute> initializer = gv.getInitialValue();
1871 if (initializer && !getBuilder().isNullValue(*initializer))
1872 gv.setLinkage(cir::GlobalLinkageKind::WeakAnyLinkage);
1873 }
1874
1875 setNonAliasAttributes(vd, gv);
1876
1877 if (vd->getTLSKind() && !vd->isStaticLocal())
1878 setTLSMode(gv, *vd);
1879
1880 maybeSetTrivialComdat(*vd, gv);
1881
1882 // Emit the initializer function if necessary.
1883 if (needsGlobalCtor || needsGlobalDtor) {
1884 // We need to make sure that these are emitted 'in order' of definition,
1885 // rather than reference, so make sure this is now 'last', if it needs a
1886 // global ctor/dtor, so that initialization happens in the correct order.
1887 // Other uses of 'lastGlobalOp' just make sure we emit all our globals
1888 // before functions/etc, so it might have ended up out of order/referenced
1889 // earlier, so this is a 'move to the end' once we see definition thing
1890 // happening here.
1891 if (lastGlobalOp != gv.getOperation()) {
1892 if (lastGlobalOp)
1893 gv->moveAfter(lastGlobalOp);
1894 else
1895 gv->moveBefore(getModule().getBody(), getModule().getBody()->begin());
1896
1897 lastGlobalOp = gv.getOperation();
1898 }
1899
1900 emitCXXGlobalVarDeclInitFunc(vd, gv, needsGlobalCtor);
1901 }
1902}
1903
1905 if (getFunctionLinkage(gd) !=
1906 cir::GlobalLinkageKind::AvailableExternallyLinkage)
1907 return true;
1908
1909 const auto *fd = cast<FunctionDecl>(gd.getDecl());
1910 // Inline builtins must be emitted; the body is redirected to a `.inline`
1911 // symbol in CIRGenFunction::generateCode.
1912 if (fd->isInlineBuiltinDeclaration())
1913 return true;
1914
1915 if (codeGenOpts.OptimizationLevel == 0 && !fd->hasAttr<AlwaysInlineAttr>())
1916 return false;
1917
1918 // We don't import function bodies from other named module units since that
1919 // behavior may break ABI compatibility of the current unit.
1920 if (const Module *m = fd->getOwningModule();
1921 m && m->getTopLevelModule()->isNamedModule() &&
1922 getASTContext().getCurrentNamedModule() != m->getTopLevelModule()) {
1923 // There are practices to mark template member function as always-inline
1924 // and mark the template as extern explicit instantiation but not give
1925 // the definition for member function. So we have to emit the function
1926 // from explicitly instantiation with always-inline.
1927 //
1928 // See https://github.com/llvm/llvm-project/issues/86893 for details.
1929 //
1930 // TODO: Maybe it is better to give it a warning if we call a non-inline
1931 // function from other module units which is marked as always-inline.
1932 if (!fd->isTemplateInstantiation() || !fd->hasAttr<AlwaysInlineAttr>()) {
1933 return false;
1934 }
1935 }
1936
1937 if (fd->hasAttr<NoInlineAttr>())
1938 return false;
1939
1940 // PR9614 / glibc btowc workaround: an available_externally function whose
1941 // body just calls itself (via asm label or __builtin_* lowering on the
1942 // same name) is not a valid stand-in for the real implementation. Drop
1943 // it from the IR so the optimizer doesn't reason about its body.
1945}
1946
1948 mlir::Operation *op) {
1949 const auto *decl = cast<ValueDecl>(gd.getDecl());
1950 if (const auto *fd = dyn_cast<FunctionDecl>(decl)) {
1951 if (!shouldEmitFunction(gd))
1952 return;
1953
1954 if (const auto *method = dyn_cast<CXXMethodDecl>(decl)) {
1955 // Make sure to emit the definition(s) before we emit the thunks. This is
1956 // necessary for the generation of certain thunks.
1957 if (isa<CXXConstructorDecl>(method) || isa<CXXDestructorDecl>(method))
1958 abi->emitCXXStructor(gd);
1959 else if (fd->isMultiVersion())
1960 errorNYI(method->getSourceRange(), "multiversion functions");
1961 else
1963
1964 if (method->isVirtual())
1965 getVTables().emitThunks(gd);
1966
1967 return;
1968 }
1969
1970 if (fd->isMultiVersion())
1971 errorNYI(fd->getSourceRange(), "multiversion functions");
1973 return;
1974 }
1975
1976 if (const auto *vd = dyn_cast<VarDecl>(decl))
1977 return emitGlobalVarDefinition(vd, !vd->hasDefinition());
1978
1979 llvm_unreachable("Invalid argument to CIRGenModule::emitGlobalDefinition");
1980}
1981
1982mlir::Attribute
1984 assert(!e->getType()->isPointerType() && "Strings are always arrays");
1985
1986 // Don't emit it as the address of the string, emit the string data itself
1987 // as an inline array.
1988 if (e->getCharByteWidth() == 1) {
1989 SmallString<64> str(e->getString());
1990
1991 // Resize the string to the right size, which is indicated by its type.
1992 const ConstantArrayType *cat =
1993 astContext.getAsConstantArrayType(e->getType());
1994 uint64_t finalSize = cat->getZExtSize();
1995 str.resize(finalSize);
1996
1997 mlir::Type eltTy = convertType(cat->getElementType());
1998 return builder.getString(str, eltTy, finalSize, /*ensureNullTerm=*/false);
1999 }
2000
2001 auto arrayTy = mlir::cast<cir::ArrayType>(convertType(e->getType()));
2002
2003 auto arrayEltTy = mlir::cast<cir::IntType>(arrayTy.getElementType());
2004
2005 uint64_t arraySize = arrayTy.getSize();
2006 unsigned literalSize = e->getLength();
2007 assert(arraySize > literalSize &&
2008 "wide string literal array size must have room for null terminator?");
2009
2010 // Check if the string is all null bytes before building the vector.
2011 // In most non-zero cases, this will break out on the first element.
2012 bool isAllZero = true;
2013 for (unsigned i = 0; i < literalSize; ++i) {
2014 if (e->getCodeUnit(i) != 0) {
2015 isAllZero = false;
2016 break;
2017 }
2018 }
2019
2020 if (isAllZero)
2021 return cir::ZeroAttr::get(arrayTy);
2022
2023 // Otherwise emit a constant array holding the characters.
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))));
2029
2030 auto elementsAttr = mlir::ArrayAttr::get(&getMLIRContext(), elements);
2031 return builder.getConstArray(elementsAttr, arrayTy);
2032}
2033
2035 return getTriple().supportsCOMDAT();
2036}
2037
2038void CIRGenModule::maybeSetTrivialComdat(const Decl &d, mlir::Operation *op) {
2040 return;
2041 if (auto globalOp = dyn_cast_or_null<cir::GlobalOp>(op)) {
2042 globalOp.setSelfComdat();
2043 } else {
2044 auto funcOp = cast<cir::FuncOp>(op);
2045 funcOp.setSelfComdat();
2046 }
2047}
2048
2050 // Make sure that this type is translated.
2051 genTypes.updateCompletedType(td);
2052}
2053
2054void CIRGenModule::addReplacement(StringRef name, mlir::Operation *op) {
2055 replacements[name] = op;
2056}
2057
2058#ifndef NDEBUG
2060 cir::FuncOp newF) {
2061 for (mlir::Operation *user : users) {
2062 auto call = mlir::dyn_cast<cir::CallOp>(user);
2063 if (!call)
2064 continue;
2065
2066 for (auto [argOp, fnArgType] :
2067 llvm::zip(call.getArgs(), newF.getFunctionType().getInputs())) {
2068 if (argOp.getType() != fnArgType)
2069 return false;
2070 }
2071 }
2072
2073 return true;
2074}
2075#endif // NDEBUG
2076
2077void CIRGenModule::applyReplacements() {
2078 if (replacements.empty())
2079 return;
2080
2081 // Collect the users of the functions being replaced in one walk. Skip CIR
2082 // types. None can hold a symbol reference (see CIRTypes.td), and walking
2083 // them descends into every nested struct of every signature.
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));
2087
2088 mlir::ModuleOp module = getModule();
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();
2097 },
2098 [&](mlir::Type type) {
2099 return mlir::isa<cir::CIRDialect>(type.getDialect())
2100 ? mlir::WalkResult::skip()
2101 : mlir::WalkResult::advance();
2102 });
2103 };
2104 collect(op->getRawDictionaryAttrs());
2105 op->getName().walkInherentAttrs(
2106 op, [&](llvm::StringRef, mlir::Attribute &attr) { collect(attr); });
2107 // Like mlir::SymbolUserMap, don't look into nested symbol tables.
2108 if (op != module.getOperation() &&
2109 op->hasTrait<mlir::OpTrait::SymbolTable>())
2110 return mlir::WalkResult::skip();
2111 return mlir::WalkResult::advance();
2112 });
2113
2114 for (auto &i : replacements) {
2115 StringRef mangledName = i.first;
2116 mlir::Operation *replacement = i.second;
2117 mlir::Operation *entry = getGlobalValue(mangledName);
2118 if (!entry)
2119 continue;
2120 assert(isa<cir::FuncOp>(entry) && "expected function");
2121 auto oldF = cast<cir::FuncOp>(entry);
2122 auto newF = dyn_cast<cir::FuncOp>(replacement);
2123 if (!newF) {
2124 // In classic codegen, this can be a global alias, a bitcast, or a GEP.
2125 errorNYI(replacement->getLoc(), "replacement is not a function");
2126 continue;
2127 }
2128
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();
2132 assert(verifyPointerTypeArgs(oldUsers, newF) &&
2133 "call argument types do not match replacement function");
2134
2135 // Replace old with new, but keep the old order.
2136 for (mlir::Operation *user : oldUsers)
2137 (void)mlir::SymbolTable::replaceAllSymbolUses(oldF, newF.getSymNameAttr(),
2138 user);
2139 // These users now name newF. Keep them in case newF is replaced later.
2140 auto newIt = users.find(newF.getSymNameAttr());
2141 if (newIt != users.end())
2142 newIt->second.set_union(oldIt->second);
2143
2144 newF->moveBefore(oldF);
2145 eraseGlobalSymbol(oldF);
2146 oldF->erase();
2147 }
2148}
2149
2151 mlir::Location loc, StringRef name, mlir::Type ty,
2152 cir::GlobalLinkageKind linkage, clang::CharUnits alignment) {
2153 auto gv = mlir::dyn_cast_or_null<cir::GlobalOp>(getGlobalValue(name));
2154
2155 if (gv) {
2156 // Check if the variable has the right type.
2157 if (gv.getSymType() == ty)
2158 return gv;
2159
2160 // Because of C++ name mangling, the only way we can end up with an already
2161 // existing global with the same name is if it has been declared extern
2162 // "C".
2163 assert(gv.isDeclaration() && "Declaration has wrong type!");
2164
2165 errorNYI(loc, "createOrReplaceCXXRuntimeVariable: declaration exists with "
2166 "wrong type");
2167 return gv;
2168 }
2169
2170 // Create a new variable.
2171 gv = createGlobalOp(loc, name, ty, /*isConstant=*/true);
2172
2173 // Set up extra information and add to the module
2174 gv.setLinkageAttr(
2175 cir::GlobalLinkageKindAttr::get(&getMLIRContext(), linkage));
2176 mlir::SymbolTable::setSymbolVisibility(gv,
2178
2179 if (supportsCOMDAT() && cir::isWeakForLinker(linkage) &&
2180 !gv.hasAvailableExternallyLinkage()) {
2181 gv.setSelfComdat();
2182 }
2183
2184 gv.setAlignmentAttr(getSize(alignment));
2185 setDSOLocal(static_cast<mlir::Operation *>(gv));
2186 return gv;
2187}
2188
2189cir::GlobalLinkageKind
2191 GVALinkage linkage) {
2192 if (linkage == GVA_Internal)
2193 return cir::GlobalLinkageKind::InternalLinkage;
2194
2195 if (dd->hasAttr<WeakAttr>())
2196 return cir::GlobalLinkageKind::WeakAnyLinkage;
2197
2198 if (const auto *fd = dd->getAsFunction())
2199 if (fd->isMultiVersion() && linkage == GVA_AvailableExternally)
2200 return cir::GlobalLinkageKind::LinkOnceAnyLinkage;
2201
2202 // We are guaranteed to have a strong definition somewhere else,
2203 // so we can use available_externally linkage.
2204 if (linkage == GVA_AvailableExternally)
2205 return cir::GlobalLinkageKind::AvailableExternallyLinkage;
2206
2207 // Note that Apple's kernel linker doesn't support symbol
2208 // coalescing, so we need to avoid linkonce and weak linkages there.
2209 // Normally, this means we just map to internal, but for explicit
2210 // instantiations we'll map to external.
2211
2212 // In C++, the compiler has to emit a definition in every translation unit
2213 // that references the function. We should use linkonce_odr because
2214 // a) if all references in this translation unit are optimized away, we
2215 // don't need to codegen it. b) if the function persists, it needs to be
2216 // merged with other definitions. c) C++ has the ODR, so we know the
2217 // definition is dependable.
2218 if (linkage == GVA_DiscardableODR)
2219 return !astContext.getLangOpts().AppleKext
2220 ? cir::GlobalLinkageKind::LinkOnceODRLinkage
2221 : cir::GlobalLinkageKind::InternalLinkage;
2222
2223 // An explicit instantiation of a template has weak linkage, since
2224 // explicit instantiations can occur in multiple translation units
2225 // and must all be equivalent. However, we are not allowed to
2226 // throw away these explicit instantiations.
2227 //
2228 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
2229 // so say that CUDA templates are either external (for kernels) or internal.
2230 // This lets llvm perform aggressive inter-procedural optimizations. For
2231 // -fgpu-rdc case, device function calls across multiple TU's are allowed,
2232 // therefore we need to follow the normal linkage paradigm.
2233 if (linkage == GVA_StrongODR) {
2234 if (getLangOpts().AppleKext)
2235 return cir::GlobalLinkageKind::ExternalLinkage;
2236 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2237 !getLangOpts().GPURelocatableDeviceCode)
2238 return dd->hasAttr<CUDAGlobalAttr>()
2239 ? cir::GlobalLinkageKind::ExternalLinkage
2240 : cir::GlobalLinkageKind::InternalLinkage;
2241 return cir::GlobalLinkageKind::WeakODRLinkage;
2242 }
2243
2244 // C++ doesn't have tentative definitions and thus cannot have common
2245 // linkage.
2246 if (!getLangOpts().CPlusPlus && isa<VarDecl>(dd) &&
2248 getCodeGenOpts().NoCommon))
2249 return cir::GlobalLinkageKind::CommonLinkage;
2250
2251 // selectany symbols are externally visible, so use weak instead of
2252 // linkonce. MSVC optimizes away references to const selectany globals, so
2253 // all definitions should be the same and ODR linkage should be used.
2254 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2255 if (dd->hasAttr<SelectAnyAttr>())
2256 return cir::GlobalLinkageKind::WeakODRLinkage;
2257
2258 // Otherwise, we have strong external linkage.
2259 assert(linkage == GVA_StrongExternal);
2260 return cir::GlobalLinkageKind::ExternalLinkage;
2261}
2262
2263/// This function is called when we implement a function with no prototype, e.g.
2264/// "int foo() {}". If there are existing call uses of the old function in the
2265/// module, this adjusts them to call the new function directly.
2266///
2267/// This is not just a cleanup: the always_inline pass requires direct calls to
2268/// functions to be able to inline them. If there is a bitcast in the way, it
2269/// won't inline them. Instcombine normally deletes these calls, but it isn't
2270/// run at -O0.
2272 mlir::Operation *old, cir::FuncOp newFn) {
2273 // If we're redefining a global as a function, don't transform it.
2274 auto oldFn = mlir::dyn_cast<cir::FuncOp>(old);
2275 if (!oldFn)
2276 return;
2277
2278 // TODO(cir): this RAUW ignores the features below.
2282 // The caller sets function attributes from the replacement's declaration.
2283 // Copying the old attributes could retain incompatible assumptions from a
2284 // different declaration that happens to share the same symbol name.
2285
2286 // Mark new function as originated from a no-proto declaration.
2287 newFn.setNoProto(oldFn.getNoProto());
2288
2289 // Iterate through all calls of the no-proto function.
2290 std::optional<mlir::SymbolTable::UseRange> symUses =
2291 oldFn.getSymbolUses(oldFn->getParentOp());
2292
2293 if (!symUses)
2294 return;
2295
2296 for (const mlir::SymbolTable::SymbolUse &use : symUses.value()) {
2297 mlir::OpBuilder::InsertionGuard guard(builder);
2298
2299 if (auto noProtoCallOp = mlir::dyn_cast<cir::CallOp>(use.getUser())) {
2300 builder.setInsertionPoint(noProtoCallOp);
2301
2302 // Patch call type with the real function type.
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;
2314 ++i) {
2315 if (callOperands[i].getType() != newFnType.getInput(i))
2316 typesMatch = false;
2317 }
2318
2319 cir::CallOp realCallOp;
2320 if (typesMatch) {
2321 // Patch call type with the real function type.
2322 realCallOp =
2323 builder.createCallOp(noProtoCallOp.getLoc(), newFn, callOperands);
2324 } else {
2325 // Build an indirect call whose function-pointer signature matches
2326 // the existing call site. A prototyped declaration keeps its own
2327 // type, ellipsis included, so arguments passed through the ellipsis
2328 // stay variadic. A direct call to an unprototyped declaration, such
2329 // as a library call CIRGen emitted by name, keeps its own operand
2330 // types and stays non-variadic.
2331 cir::FuncType origFnType = oldFn.getFunctionType();
2332 cir::FuncType callFnType =
2333 oldFn.getNoProto()
2334 ? cir::FuncType::get(llvm::to_vector(callOperands.getTypes()),
2335 origFnType.getReturnType(),
2336 /*isVarArg=*/false)
2337 : origFnType;
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);
2345 }
2346 // The argument and result types are unchanged, so preserve their
2347 // attributes and the call semantics. The new callee is already set.
2348 for (mlir::NamedAttribute attr : noProtoCallOp->getAttrs())
2349 if (attr.getName() != cir::CIRDialect::getCalleeAttrName())
2350 realCallOp->setAttr(attr.getName(), attr.getValue());
2351
2352 // Replace old no proto call with fixed call.
2353 noProtoCallOp.replaceAllUsesWith(realCallOp);
2354 noProtoCallOp.erase();
2355 } else if (auto getGlobalOp =
2356 mlir::dyn_cast<cir::GetGlobalOp>(use.getUser())) {
2357 // The GetGlobal was emitted with the no-proto FuncType. Uses of this
2358 // operation (cir.store, cir.cast) were built for that pointer type. When
2359 // we re-type the result to the real FuncType, we need to add a bit the
2360 // old pointer type so those uses are still valid. This can lead to
2361 // some redundant bitcast chains, but those will be cleaned up by the
2362 // canonicalizer.
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());
2375 }
2376 } else if (mlir::isa<cir::GlobalOp>(use.getUser())) {
2377 // Function addresses in global initializers use GlobalViewAttrs typed to
2378 // the initializer context (e.g. struct field type), not the FuncOp type,
2379 // so no update is required when the no-proto FuncOp is replaced.
2380 } else {
2381 llvm_unreachable(
2382 "replaceUsesOfNonProtoTypeWithRealFunction: unexpected use type");
2383 }
2384 }
2385}
2386
2387cir::GlobalLinkageKind
2389 GVALinkage linkage = astContext.GetGVALinkageForVariable(vd);
2390 return getCIRLinkageForDeclarator(vd, linkage);
2391}
2392
2394 const auto *d = cast<FunctionDecl>(gd.getDecl());
2395
2396 GVALinkage linkage = astContext.GetGVALinkageForFunction(d);
2397
2398 if (const auto *dtor = dyn_cast<CXXDestructorDecl>(d))
2399 return getCXXABI().getCXXDestructorLinkage(linkage, dtor, gd.getDtorType());
2400
2401 return getCIRLinkageForDeclarator(d, linkage);
2402}
2403
2404static cir::GlobalOp
2405generateStringLiteral(mlir::Location loc, mlir::TypedAttr c,
2406 cir::GlobalLinkageKind lt, CIRGenModule &cgm,
2407 StringRef globalName, CharUnits alignment) {
2409 cgm.getTarget());
2410 mlir::ptr::MemorySpaceAttrInterface addrSpace =
2412
2413 // Create a global variable for this string
2414 // FIXME(cir): check for insertion point in module level.
2415 cir::GlobalOp gv =
2416 cgm.createGlobalOp(loc, globalName, c.getType(),
2417 !cgm.getLangOpts().WritableStrings, addrSpace);
2418
2419 // Set up extra information and add to the module
2420 gv.setAlignmentAttr(cgm.getSize(alignment));
2421 gv.setLinkageAttr(
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");
2428 gv.setSelfComdat();
2429 }
2430 cgm.setDSOLocal(static_cast<mlir::Operation *>(gv));
2431 return gv;
2432}
2433
2434// LLVM IR automatically uniques names when new llvm::GlobalVariables are
2435// created. This is handy, for example, when creating globals for string
2436// literals. Since we don't do that when creating cir::GlobalOp's, we need
2437// a mechanism to generate a unique name in advance.
2438//
2439// For now, this mechanism is only used in cases where we know that the
2440// name is compiler-generated, so we don't use the MLIR symbol table for
2441// the lookup.
2442std::string CIRGenModule::getUniqueGlobalName(const std::string &baseName) {
2443 // If this is the first time we've generated a name for this basename, use
2444 // it as is and start a counter for this base name.
2445 auto it = cgGlobalNames.find(baseName);
2446 if (it == cgGlobalNames.end()) {
2447 cgGlobalNames[baseName] = 1;
2448 return baseName;
2449 }
2450
2451 std::string result =
2452 baseName + "." + std::to_string(cgGlobalNames[baseName]++);
2453 // There should not be any symbol with this name in the module.
2454 assert(!getGlobalValue(result));
2455 return result;
2456}
2457
2458/// Return a pointer to a constant array for the given string literal.
2460 StringRef name) {
2461 CharUnits alignment =
2462 astContext.getAlignOfGlobalVarInChars(s->getType(), /*VD=*/nullptr);
2463
2464 mlir::Attribute c = getConstantArrayFromStringLiteral(s);
2465
2466 cir::GlobalOp gv;
2467 if (!getLangOpts().WritableStrings && constantStringMap.count(c)) {
2468 gv = constantStringMap[c];
2469 // The bigger alignment always wins.
2470 if (!gv.getAlignment() ||
2471 uint64_t(alignment.getQuantity()) > *gv.getAlignment())
2472 gv.setAlignmentAttr(getSize(alignment));
2473 } else {
2474 // Mangle the string literal if that's how the ABI merges duplicate strings.
2475 // Don't do it if they are writable, since we don't want writes in one TU to
2476 // affect strings in another.
2477 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(s) &&
2478 !getLangOpts().WritableStrings) {
2480 "getGlobalForStringLiteral: mangle string literals");
2481 }
2482
2483 // Unlike LLVM IR, CIR doesn't automatically unique names for globals, so
2484 // we need to do that explicitly.
2485 std::string uniqueName = getUniqueGlobalName(name.str());
2486 // Synthetic string literals (e.g., from SourceLocExpr) may not have valid
2487 // source locations. Use unknown location in those cases.
2488 mlir::Location loc = s->getBeginLoc().isValid()
2489 ? getLoc(s->getSourceRange())
2490 : builder.getUnknownLoc();
2491 auto typedC = llvm::cast<mlir::TypedAttr>(c);
2492 gv = generateStringLiteral(loc, typedC,
2493 cir::GlobalLinkageKind::PrivateLinkage, *this,
2494 uniqueName, alignment);
2495 setDSOLocal(static_cast<mlir::Operation *>(gv));
2496 constantStringMap[c] = gv;
2497
2499 }
2500 return gv;
2501}
2502
2503/// Return a pointer to a constant array for the given string literal.
2504cir::GlobalViewAttr
2506 StringRef name) {
2507 cir::GlobalOp gv = getGlobalForStringLiteral(s, name);
2508 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(gv.getSymType());
2509 assert(arrayTy && "String literal must be array");
2510 cir::PointerType ptrTy = getBuilder().getPointerTo(
2511 arrayTy.getElementType(),
2512 getTypes().getPointerAddressSpace(s->getType()));
2513
2514 return builder.getGlobalViewAttr(ptrTy, gv);
2515}
2516
2517cir::GlobalOp CIRGenModule::createGlobalString(mlir::Location loc,
2518 StringRef str, StringRef name) {
2519 mlir::Attribute init = builder.getString(str, convertType(astContext.CharTy),
2520 /*size=*/std::nullopt);
2521
2522 // Unlike LLVM IR, CIR doesn't automatically unique names for globals, so
2523 // we need to do that explicitly.
2524 return generateStringLiteral(loc, mlir::cast<mlir::TypedAttr>(init),
2525 cir::GlobalLinkageKind::PrivateLinkage, *this,
2526 getUniqueGlobalName(name.str()),
2527 CharUnits::One());
2528}
2529
2530mlir::ptr::MemorySpaceAttrInterface
2534
2535// TODO(cir): this could be a common AST helper for both CIR and LLVM codegen.
2537 if (getLangOpts().OpenCL)
2539
2540 // For temporaries inside functions, CUDA treats them as normal variables.
2541 // LangAS::cuda_device, on the other hand, is reserved for those variables
2542 // explicitly marked with __device__.
2543 if (getLangOpts().CUDAIsDevice)
2544 return LangAS::Default;
2545
2546 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
2548
2549 if (getLangOpts().SYCLIsDevice)
2550 return LangAS::Default;
2551
2552 return LangAS::Default;
2553}
2554
2556 CIRGenFunction *cgf) {
2557 if (cgf && e->getType()->isVariablyModifiedType())
2559
2561 "emitExplicitCastExprType");
2562}
2563
2565 const MemberPointerType *mpt) {
2566 if (mpt->isMemberFunctionPointerType()) {
2567 auto ty = mlir::cast<cir::MethodType>(convertType(destTy));
2568 return builder.getNullMethodAttr(ty);
2569 }
2570
2571 auto ty = mlir::cast<cir::DataMemberType>(convertType(destTy));
2572 return builder.getNullDataMemberAttr(ty);
2573}
2574
2577
2578 mlir::Location loc = getLoc(e->getSourceRange());
2579
2580 const ValueDecl *decl = cast<DeclRefExpr>(e->getSubExpr())->getDecl();
2581
2582 // A member function pointer.
2583 if (const auto *methodDecl = dyn_cast<CXXMethodDecl>(decl)) {
2584 auto ty = mlir::cast<cir::MethodType>(convertType(e->getType()));
2585 if (methodDecl->isVirtual())
2586 return cir::ConstantOp::create(
2587 builder, loc, getCXXABI().buildVirtualMethodAttr(ty, methodDecl));
2588
2589 const CIRGenFunctionInfo &fi =
2591 cir::FuncType funcTy = getTypes().getFunctionType(fi);
2592 cir::FuncOp methodFuncOp = getAddrOfFunction(methodDecl, funcTy);
2593 return cir::ConstantOp::create(builder, loc,
2594 builder.getMethodAttr(ty, methodFuncOp));
2595 }
2596
2597 // Otherwise, a member data pointer.
2598 auto ty = mlir::cast<cir::DataMemberType>(convertType(e->getType()));
2599 const auto *mpt = e->getType()->castAs<MemberPointerType>();
2600 const auto *destClass = mpt->getMostRecentCXXRecordDecl();
2601
2602 // Empty [[no_unique_address]] fields have no CIR field index; represent the
2603 // pointer-to-data-member by its concrete byte offset within the class.
2604 if (const auto *fieldDecl = dyn_cast<FieldDecl>(decl);
2606 // This function should ONLY be accessed in reference to itself, I don't see
2607 // any cases/couldn't find any cases where anything else could get here, and
2608 // classic-codegen does the same.
2609 assert(fieldDecl->getParent() == destClass &&
2610 "scalar member pointer should be relative to the declaring class");
2611 uint64_t offset =
2612 astContext.toCharUnitsFromBits(astContext.getFieldOffset(fieldDecl))
2613 .getQuantity();
2614 return cir::ConstantOp::create(builder, loc,
2615 cir::DataMemberOffsetAttr::get(ty, offset));
2616 }
2617
2618 std::optional<llvm::SmallVector<int32_t>> path =
2619 buildMemberPath(destClass, decl);
2620 if (!path)
2621 return {};
2622 return cir::ConstantOp::create(builder, loc,
2623 builder.getDataMemberAttr(ty, *path));
2624}
2625
2626std::optional<llvm::SmallVector<int32_t>>
2628 const ValueDecl *decl) {
2630
2631 // Members of an anonymous struct/union have an IndirectFieldDecl, which
2632 // contains the whole chain of how to get to it, so to get the 'path', we dig
2633 // through those rather than searching.
2634 if (const auto *indirectField = dyn_cast<IndirectFieldDecl>(decl)) {
2635 const CXXRecordDecl *currentClass = destClass;
2636 for (const NamedDecl *nd : indirectField->chain()) {
2637 const auto *field = cast<FieldDecl>(nd);
2638 if (!findFieldMemberPath(currentClass, field, path))
2639 return std::nullopt;
2640 currentClass = field->getType()->getAsCXXRecordDecl();
2641 }
2642 return path;
2643 }
2644
2645 if (!findFieldMemberPath(destClass, cast<FieldDecl>(decl), path))
2646 return std::nullopt;
2647 return path;
2648}
2649
2650bool CIRGenModule::findFieldMemberPath(const CXXRecordDecl *currentClass,
2651 const FieldDecl *field,
2653 const CIRGenRecordLayout &layout =
2654 getTypes().getCIRGenRecordLayout(currentClass);
2655
2656 // The field is declared directly in this class.
2657 if (astContext.isSameEntity(field->getParent()->getMostRecentDecl(),
2658 currentClass->getMostRecentDecl())) {
2659 int32_t fieldIdx;
2660 if (currentClass->isUnion()) {
2661 // For unions, getCIRFieldNo always returns 0 for every union member (all
2662 // members share offset 0 in the CIR record). Use the declaration-order
2663 // index to distinguish members with the same type at the same offset.
2664 if (!layout.isZeroInitializable()) {
2665 errorNYI(field->getLocation(),
2666 "data member pointer for non-zero-initializable union");
2667 return false;
2668 }
2669 fieldIdx = static_cast<int32_t>(field->getFieldIndex());
2670 } else {
2671 fieldIdx = static_cast<int32_t>(layout.getCIRFieldNo(field));
2672 }
2673 path.push_back(fieldIdx);
2674 return true;
2675 }
2676
2677 // Otherwise search the base subobjects. A virtual base only blocks lowering
2678 // when the field actually lives within it; a virtual base elsewhere in the
2679 // hierarchy must not stop us from reaching a member through a non-virtual
2680 // path.
2681 for (const CXXBaseSpecifier &base : currentClass->bases()) {
2682 const auto *baseDecl =
2683 cast<CXXRecordDecl>(base.getType()->getAsRecordDecl());
2684
2685 if (base.isVirtual()) {
2686 // A pointer to a data member that traverses a virtual base is ill-formed,
2687 // so this guard only fires defensively if the member is reached through
2688 // the virtual base. An unrelated virtual base is skipped so it does not
2689 // block members reached through a non-virtual path.
2690 llvm::SmallVector<int32_t> discardedPath;
2691 if (findFieldMemberPath(baseDecl, field, discardedPath)) {
2692 errorNYI(field->getLocation(),
2693 "data member pointer through virtual base");
2694 return false;
2695 }
2696 continue;
2697 }
2698
2699 // If a base class doesn't participate in layout, the field cannot be in it,
2700 // skip it.
2701 if (!layout.hasNonVirtualBaseCIRField(baseDecl))
2702 continue;
2703
2704 auto baseFieldIdx =
2705 static_cast<int32_t>(layout.getNonVirtualBaseCIRFieldNo(baseDecl));
2706 path.push_back(baseFieldIdx);
2707 if (findFieldMemberPath(baseDecl, field, path))
2708 return true;
2709 path.pop_back();
2710 }
2711 return false;
2712}
2713
2715 if (!field->isPotentiallyOverlapping() ||
2716 !CodeGenUtils::isEmptyFieldForLayout(astContext, field))
2717 return false;
2718
2719 // Unions always have a field even if they are empty.
2720 const RecordDecl *rec = field->getParent();
2721 if (rec->isUnion())
2722 return true;
2723
2724 // Otherwise, count on whether accumulateFields gave this a member.
2725 return !getTypes().getCIRGenRecordLayout(rec).hasCIRField(field);
2726}
2727
2729 for (Decl *decl : dc->decls()) {
2730 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
2731 // are themselves considered "top-level", so EmitTopLevelDecl on an
2732 // ObjCImplDecl does not recursively visit them. We need to do that in
2733 // case they're nested inside another construct (LinkageSpecDecl /
2734 // ExportDecl) that does stop them from being considered "top-level".
2735 if (auto *oid = dyn_cast<ObjCImplDecl>(decl))
2736 errorNYI(oid->getSourceRange(), "emitDeclConext: ObjCImplDecl");
2737
2739 }
2740}
2741
2742// Emit code for a single top level declaration.
2744
2745 // Ignore dependent declarations.
2746 if (decl->isTemplated())
2747 return;
2748
2749 switch (decl->getKind()) {
2750 default:
2751 errorNYI(decl->getBeginLoc(), "declaration of kind",
2752 decl->getDeclKindName());
2753 break;
2754
2755 case Decl::CXXConversion:
2756 case Decl::CXXMethod:
2757 case Decl::Function: {
2758 auto *fd = cast<FunctionDecl>(decl);
2759 // Consteval functions shouldn't be emitted.
2760 if (!fd->isConsteval())
2761 emitGlobal(fd);
2762 break;
2763 }
2764
2765 case Decl::Import: {
2766 auto *importDecl = cast<ImportDecl>(decl);
2767 clang::Module *mod = importDecl->getImportedModule();
2768
2769 // Nothing to record or to emit without a module.
2770 if (!mod)
2771 break;
2772
2773 // If we've already imported this module, we're done.
2774 if (!importedModules.insert(mod))
2775 break;
2776 moduleImportLocs[mod] = importDecl->getLocation();
2777
2779
2780 // A C++20 named module has its own initializer function, so its
2781 // initializers are not emitted here. The global init function of this
2782 // translation unit calls that initializer, which in turn covers the
2783 // modules it imports itself; release() records the modules to call.
2784 if (cxx20ModuleInits && mod->isNamedModule())
2785 break;
2786
2787 // For clang C++ module map modules the initializers for sub-modules are
2788 // emitted here.
2789
2790 // Find all of the submodules and emit the module initializers.
2793 visited.insert(mod);
2794 stack.push_back(mod);
2795
2796 while (!stack.empty()) {
2797 clang::Module *cur = stack.pop_back_val();
2798 if (!emittedModuleInitializers.insert(cur).second)
2799 continue;
2800
2801 for (Decl *initializer : astContext.getModuleInitializers(cur))
2802 emitTopLevelDecl(initializer);
2803
2804 // Visit the submodules of this module.
2805 for (clang::Module *submodule : cur->submodules()) {
2806 // Skip explicit children; they need to be explicitly imported to emit
2807 // the initializers.
2808 if (submodule->IsExplicit)
2809 continue;
2810
2811 if (visited.insert(submodule).second)
2812 stack.push_back(submodule);
2813 }
2814 }
2815 break;
2816 }
2817
2818 case Decl::Export:
2820 break;
2821
2822 case Decl::Var:
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())
2829 emitGlobal(holdingVar);
2830 break;
2831 }
2832 case Decl::OpenACCRoutine:
2834 break;
2835 case Decl::OpenACCDeclare:
2837 break;
2838 case Decl::OMPThreadPrivate:
2840 break;
2841 case Decl::OMPGroupPrivate:
2843 break;
2844 case Decl::OMPAllocate:
2846 break;
2847 case Decl::OMPCapturedExpr:
2849 break;
2850 case Decl::OMPDeclareReduction:
2852 break;
2853 case Decl::OMPDeclareMapper:
2855 break;
2856 case Decl::OMPRequires:
2858 break;
2859 case Decl::Enum:
2860 case Decl::Using: // using X; [C++]
2861 case Decl::UsingDirective: // using namespace X; [C++]
2862 case Decl::UsingEnum: // using enum X; [C++]
2863 case Decl::NamespaceAlias:
2864 case Decl::Typedef:
2865 case Decl::TypeAlias: // using foo = bar; [C++11]
2866 case Decl::Record:
2868 break;
2869
2870 // Indirect fields from global anonymous structs and unions can be
2871 // ignored; only the actual variable requires IR gen support.
2872 case Decl::IndirectField:
2873 break;
2874
2875 // No code generation needed.
2876 case Decl::ClassTemplate:
2877 case Decl::Concept:
2878 case Decl::CXXDeductionGuide:
2879 case Decl::Empty:
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:
2887 break;
2888
2889 case Decl::CXXConstructor:
2891 break;
2892 case Decl::CXXDestructor:
2894 break;
2895
2896 // C++ Decls
2897 case Decl::LinkageSpec:
2898 case Decl::Namespace:
2900 break;
2901
2902 case Decl::ClassTemplateSpecialization:
2903 case Decl::CXXRecord: {
2906 for (auto *childDecl : crd->decls())
2908 emitTopLevelDecl(childDecl);
2909 break;
2910 }
2911
2912 case Decl::FileScopeAsm:
2913 // File-scope asm is ignored during device-side CUDA compilation.
2914 if (langOpts.CUDA && langOpts.CUDAIsDevice)
2915 break;
2916 // File-scope asm is ignored during device-side OpenMP compilation.
2917 if (langOpts.OpenMPIsTargetDevice)
2918 break;
2919 // File-scope asm is ignored during device-side SYCL compilation.
2920 if (langOpts.SYCLIsDevice)
2921 break;
2922 auto *file_asm = cast<FileScopeAsmDecl>(decl);
2923 std::string line = file_asm->getAsmString();
2924 globalScopeAsm.push_back(builder.getStringAttr(line));
2925 break;
2926 }
2927}
2928
2929void CIRGenModule::setInitializer(cir::GlobalOp &op, mlir::Attribute value) {
2930 // Recompute visibility when updating initializer.
2931 op.setInitialValueAttr(value);
2933}
2934
2935std::pair<cir::FuncType, cir::FuncOp> CIRGenModule::getAddrAndTypeOfCXXStructor(
2936 GlobalDecl gd, const CIRGenFunctionInfo *fnInfo, cir::FuncType fnType,
2937 bool dontDefer, ForDefinition_t isForDefinition) {
2938 auto *md = cast<CXXMethodDecl>(gd.getDecl());
2939
2940 if (isa<CXXDestructorDecl>(md)) {
2941 // Always alias equivalent complete destructors to base destructors in the
2942 // MS ABI.
2943 if (getTarget().getCXXABI().isMicrosoft() &&
2944 gd.getDtorType() == Dtor_Complete &&
2945 md->getParent()->getNumVBases() == 0)
2946 errorNYI(md->getSourceRange(),
2947 "getAddrAndTypeOfCXXStructor: MS ABI complete destructor");
2948 }
2949
2950 if (!fnType) {
2951 if (!fnInfo)
2953 fnType = getTypes().getFunctionType(*fnInfo);
2954 }
2955
2956 auto fn = getOrCreateCIRFunction(getMangledName(gd), fnType, gd,
2957 /*ForVtable=*/false, dontDefer,
2958 /*IsThunk=*/false, isForDefinition);
2959
2960 return {fnType, fn};
2961}
2962
2964 mlir::Type funcType, bool forVTable,
2965 bool dontDefer,
2966 ForDefinition_t isForDefinition) {
2967 assert(!cast<FunctionDecl>(gd.getDecl())->isConsteval() &&
2968 "consteval function should never be emitted");
2969
2970 if (!funcType) {
2971 const auto *fd = cast<FunctionDecl>(gd.getDecl());
2972 funcType = convertType(fd->getType());
2973 }
2974
2975 // Devirtualized destructor calls may come through here instead of via
2976 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2977 // of the complete destructor when necessary.
2978 if (const auto *dd = dyn_cast<CXXDestructorDecl>(gd.getDecl())) {
2979 if (getTarget().getCXXABI().isMicrosoft() &&
2980 gd.getDtorType() == Dtor_Complete &&
2981 dd->getParent()->getNumVBases() == 0)
2982 errorNYI(dd->getSourceRange(),
2983 "getAddrOfFunction: MS ABI complete destructor");
2984 }
2985
2986 StringRef mangledName = getMangledName(gd);
2987 cir::FuncOp func =
2988 getOrCreateCIRFunction(mangledName, funcType, gd, forVTable, dontDefer,
2989 /*isThunk=*/false, isForDefinition);
2990 // Returns kernel handle for HIP kernel stub function.
2991 if (langOpts.CUDA && !langOpts.CUDAIsDevice &&
2992 cast<FunctionDecl>(gd.getDecl())->hasAttr<CUDAGlobalAttr>()) {
2993 mlir::Operation *handle = getCUDARuntime().getKernelHandle(func, gd);
2994
2995 // For HIP the kernel handle is a GlobalOp, which cannot be cast to
2996 // FuncOp. Return the stub directly in that case.
2997 bool isHIPHandle = mlir::isa<cir::GlobalOp>(*handle);
2998 if (isForDefinition || isHIPHandle)
2999 return func;
3000 return mlir::dyn_cast<cir::FuncOp>(*handle);
3001 }
3002 return func;
3003}
3004
3005static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd,
3006 const NamedDecl *nd) {
3007 SmallString<256> buffer;
3008
3009 llvm::raw_svector_ostream out(buffer);
3011
3013
3014 if (mc.shouldMangleDeclName(nd)) {
3015 mc.mangleName(gd.getWithDecl(nd), out);
3016 } else {
3017 IdentifierInfo *ii = nd->getIdentifier();
3018 assert(ii && "Attempt to mangle unnamed decl.");
3019
3020 const auto *fd = dyn_cast<FunctionDecl>(nd);
3021 if (fd &&
3022 fd->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
3023 cgm.errorNYI(nd->getSourceRange(), "getMangledName: X86RegCall");
3024 } else if (fd && fd->hasAttr<CUDAGlobalAttr>() &&
3026 out << "__device_stub__" << ii->getName();
3027 } else if (fd &&
3028 DeviceKernelAttr::isOpenCLSpelling(
3029 fd->getAttr<DeviceKernelAttr>()) &&
3031 cgm.errorNYI(nd->getSourceRange(), "getMangledName: OpenCL Stub");
3032 } else {
3033 out << ii->getName();
3034 }
3035 }
3036
3037 // Check if the module name hash should be appended for internal linkage
3038 // symbols. This should come before multi-version target suffixes are
3039 // appendded. This is to keep the name and module hash suffix of the internal
3040 // linkage function together. The unique suffix should only be added when name
3041 // mangling is done to make sure that the final name can be properly
3042 // demangled. For example, for C functions without prototypes, name mangling
3043 // is not done and the unique suffix should not be appended then.
3045
3046 if (const auto *fd = dyn_cast<FunctionDecl>(nd)) {
3047 if (fd->isMultiVersion()) {
3048 cgm.errorNYI(nd->getSourceRange(),
3049 "getMangledName: multi-version functions");
3050 }
3051 }
3052 // Make unique name for device side static file-scope variable for HIP.
3053 if (cgm.getASTContext().shouldExternalize(nd) &&
3054 cgm.getLangOpts().GPURelocatableDeviceCode)
3055 if (cgm.getLangOpts().CUDA)
3056 cgm.errorNYI(nd->getSourceRange(),
3057 "getMangledName: GPU relocatable device code");
3058
3059 return std::string(out.str());
3060}
3061
3062static FunctionDecl *
3064 const FunctionDecl *protoFunc) {
3065 // If this is a C no-prototype function, we can take the 'easy' way out and
3066 // just create a function with no arguments/functions, etc.
3067 if (!protoFunc->hasPrototype())
3068 return FunctionDecl::Create(
3069 ctx, /*DC=*/ctx.getTranslationUnitDecl(),
3070 /*StartLoc=*/SourceLocation{}, /*NLoc=*/SourceLocation{}, bindName,
3071 protoFunc->getType(), /*TInfo=*/nullptr, StorageClass::SC_None);
3072
3073 QualType funcTy = protoFunc->getType();
3074 auto *fpt = cast<FunctionProtoType>(protoFunc->getType());
3075
3076 // If this is a member function, add an explicit 'this' to the function type.
3077 if (auto *methodDecl = dyn_cast<CXXMethodDecl>(protoFunc);
3078 methodDecl && methodDecl->isImplicitObjectMemberFunction()) {
3079 llvm::SmallVector<QualType> paramTypes{fpt->getParamTypes()};
3080 paramTypes.insert(paramTypes.begin(), methodDecl->getThisType());
3081
3082 funcTy = ctx.getFunctionType(fpt->getReturnType(), paramTypes,
3083 fpt->getExtProtoInfo());
3084 fpt = cast<FunctionProtoType>(funcTy);
3085 }
3086
3087 auto *tempFunc =
3089 /*StartLoc=*/SourceLocation{},
3090 /*NLoc=*/SourceLocation{}, bindName, funcTy,
3091 /*TInfo=*/nullptr, StorageClass::SC_None);
3092
3094 params.reserve(fpt->getNumParams());
3095
3096 // Add all of the parameters.
3097 for (unsigned i = 0, e = fpt->getNumParams(); i != e; ++i) {
3099 ctx, tempFunc, /*StartLoc=*/SourceLocation{},
3100 /*IdLoc=*/SourceLocation{},
3101 /*Id=*/nullptr, fpt->getParamType(i), /*TInfo=*/nullptr,
3102 StorageClass::SC_None, /*DefArg=*/nullptr);
3103 parm->setScopeInfo(0, i);
3104 params.push_back(parm);
3105 }
3106
3107 tempFunc->setParams(params);
3108
3109 return tempFunc;
3110}
3111
3112std::string
3114 const FunctionDecl *attachedFunction) {
3116 getASTContext(), bindName, attachedFunction);
3117
3118 std::string ret = getMangledNameImpl(*this, GlobalDecl(tempFunc), tempFunc);
3119
3120 // This does nothing (it is a do-nothing function), since this is a
3121 // slab-allocator, but leave a call in to immediately destroy this in case we
3122 // ever come up with a way of getting allocations back.
3123 getASTContext().Deallocate(tempFunc);
3124 return ret;
3125}
3126
3128 GlobalDecl canonicalGd = gd.getCanonicalDecl();
3129
3130 // Some ABIs don't have constructor variants. Make sure that base and complete
3131 // constructors get mangled the same.
3132 if (const auto *cd = dyn_cast<CXXConstructorDecl>(canonicalGd.getDecl())) {
3133 if (!getTarget().getCXXABI().hasConstructorVariants()) {
3134 errorNYI(cd->getSourceRange(),
3135 "getMangledName: C++ constructor without variants");
3136 return cast<NamedDecl>(gd.getDecl())->getIdentifier()->getName();
3137 }
3138 }
3139
3140 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
3141 // static device variable depends on whether the variable is referenced by
3142 // a host or device host function. Therefore the mangled name cannot be
3143 // cached.
3144 if (!langOpts.CUDAIsDevice || !astContext.mayExternalize(gd.getDecl())) {
3145 auto foundName = mangledDeclNames.find(canonicalGd);
3146 if (foundName != mangledDeclNames.end())
3147 return foundName->second;
3148 }
3149
3150 // Keep the first result in the case of a mangling collision.
3151 const auto *nd = cast<NamedDecl>(gd.getDecl());
3152 std::string mangledName = getMangledNameImpl(*this, gd, nd);
3153
3154 auto result = manglings.insert(std::make_pair(mangledName, gd));
3155 return mangledDeclNames[canonicalGd] = result.first->first();
3156}
3157
3159 assert(!d->getInit() && "Cannot emit definite definitions here!");
3160
3161 StringRef mangledName = getMangledName(d);
3162 mlir::Operation *gv = getGlobalValue(mangledName);
3163
3164 // If we already have a definition, not declaration, with the same mangled
3165 // name, emitting of declaration is not required (and would actually overwrite
3166 // the emitted definition).
3167 if (gv) {
3168 auto gvOp = dyn_cast<cir::GlobalOp>(gv);
3169 if (!gvOp) {
3171 "emitTentativeDefinition: name already used by a non-global");
3172 return;
3173 }
3174 if (!gvOp.isDeclaration())
3175 return;
3176 }
3177
3178 // If we have not seen a reference to this variable yet, place it into the
3179 // deferred declarations table to be emitted if needed later.
3180 if (!mustBeEmitted(d) && !gv) {
3181 deferredDecls[mangledName] = d;
3182 return;
3183 }
3184
3185 // The tentative definition is the only definition.
3187}
3188
3190 // Never defer when EmitAllDecls is specified.
3191 if (langOpts.EmitAllDecls)
3192 return true;
3193
3194 const auto *vd = dyn_cast<VarDecl>(global);
3195 if (vd &&
3196 ((codeGenOpts.KeepPersistentStorageVariables &&
3197 (vd->getStorageDuration() == SD_Static ||
3198 vd->getStorageDuration() == SD_Thread)) ||
3199 (codeGenOpts.KeepStaticConsts && vd->getStorageDuration() == SD_Static &&
3200 vd->getType().isConstQualified())))
3201 return true;
3202
3203 return getASTContext().DeclMustBeEmitted(global);
3204}
3205
3207 // In OpenMP 5.0 variables and function may be marked as
3208 // device_type(host/nohost) and we should not emit them eagerly unless we sure
3209 // that they must be emitted on the host/device. To be sure we need to have
3210 // seen a declare target with an explicit mentioning of the function, we know
3211 // we have if the level of the declare target attribute is -1. Note that we
3212 // check somewhere else if we should emit this at all.
3213 if (langOpts.OpenMP >= 50 && !langOpts.OpenMPSimd) {
3214 std::optional<OMPDeclareTargetDeclAttr *> activeAttr =
3215 OMPDeclareTargetDeclAttr::getActiveAttr(global);
3216 if (!activeAttr || (*activeAttr)->getLevel() != (unsigned)-1)
3217 return false;
3218 }
3219
3220 const auto *fd = dyn_cast<FunctionDecl>(global);
3221 if (fd) {
3222 // Implicit template instantiations may change linkage if they are later
3223 // explicitly instantiated, so they should not be emitted eagerly.
3224 if (fd->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3225 return false;
3226 // Defer until all versions have been semantically checked.
3227 if (fd->hasAttr<TargetVersionAttr>() && !fd->isMultiVersion())
3228 return false;
3229 // Defer emission of SYCL kernel entry point functions during device
3230 // compilation.
3231 if (langOpts.SYCLIsDevice && fd->hasAttr<SYCLKernelEntryPointAttr>())
3232 return false;
3233 }
3234 const auto *vd = dyn_cast<VarDecl>(global);
3235 if (vd)
3236 if (astContext.getInlineVariableDefinitionKind(vd) ==
3238 // A definition of an inline constexpr static data member may change
3239 // linkage later if it's redeclared outside the class.
3240 return false;
3241
3242 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3243 // codegen for global variables, because they may be marked as threadprivate.
3244 if (langOpts.OpenMP && langOpts.OpenMPUseTLS &&
3245 astContext.getTargetInfo().isTLSSupported() && isa<VarDecl>(global) &&
3246 !global->getType().isConstantStorage(astContext, false, false) &&
3247 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(global))
3248 return false;
3249
3250 assert((fd || vd) &&
3251 "Only FunctionDecl and VarDecl should hit this path so far.");
3252 return true;
3253}
3254
3255static bool shouldAssumeDSOLocal(const CIRGenModule &cgm,
3256 cir::CIRGlobalValueInterface gv) {
3257 if (gv.hasLocalLinkage())
3258 return true;
3259
3260 if (!gv.hasDefaultVisibility() && !gv.hasExternalWeakLinkage())
3261 return true;
3262
3263 // DLLImport explicitly marks the GV as external.
3264 // so it shouldn't be dso_local
3265 // But we don't have the info set now
3267
3268 const llvm::Triple &tt = cgm.getTriple();
3269 const CodeGenOptions &cgOpts = cgm.getCodeGenOpts();
3270 if (tt.isOSCygMing()) {
3271 // In MinGW and Cygwin, variables without DLLImport can still be
3272 // automatically imported from a DLL by the linker; don't mark variables
3273 // that potentially could come from another DLL as DSO local.
3274
3275 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
3276 // (and this actually happens in the public interface of libstdc++), so
3277 // such variables can't be marked as DSO local. (Native TLS variables
3278 // can't be dllimported at all, though.)
3279 cgm.errorNYI("shouldAssumeDSOLocal: MinGW");
3280 }
3281
3282 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
3283 // remain unresolved in the link, they can be resolved to zero, which is
3284 // outside the current DSO.
3285 if (tt.isOSBinFormatCOFF() && gv.hasExternalWeakLinkage())
3286 return false;
3287
3288 // Every other GV is local on COFF.
3289 // Make an exception for windows OS in the triple: Some firmware builds use
3290 // *-win32-macho triples. This (accidentally?) produced windows relocations
3291 // without GOT tables in older clang versions; Keep this behaviour.
3292 // FIXME: even thread local variables?
3293 if (tt.isOSBinFormatCOFF() || (tt.isOSWindows() && tt.isOSBinFormatMachO()))
3294 return true;
3295
3296 // Only handle COFF and ELF for now.
3297 if (!tt.isOSBinFormatELF())
3298 return false;
3299
3300 llvm::Reloc::Model rm = cgOpts.RelocationModel;
3301 const LangOptions &lOpts = cgm.getLangOpts();
3302 if (rm != llvm::Reloc::Static && !lOpts.PIE) {
3303 // On ELF, if -fno-semantic-interposition is specified and the target
3304 // supports local aliases, there will be neither CC1
3305 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
3306 // dso_local on the function if using a local alias is preferable (can avoid
3307 // PLT indirection).
3308 auto func = dyn_cast<cir::FuncOp>(gv.getOperation());
3309 if (!func || func.getAliasee() || !gv.canBenefitFromLocalAlias())
3310 return false;
3311 return !(lOpts.SemanticInterposition || lOpts.HalfNoSemanticInterposition);
3312 }
3313
3314 // A definition cannot be preempted from an executable.
3315 if (!gv.isDeclarationForLinker())
3316 return true;
3317
3318 // Most PIC code sequences that assume that a symbol is local cannot produce a
3319 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
3320 // depended, it seems worth it to handle it here.
3321 if (rm == llvm::Reloc::PIC_ && gv.hasExternalWeakLinkage())
3322 return false;
3323
3324 // PowerPC64 prefers TOC indirection to avoid copy relocations.
3325 if (tt.isPPC64())
3326 return false;
3327
3328 if (cgOpts.DirectAccessExternalData) {
3329 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
3330 // for non-thread-local variables. If the symbol is not defined in the
3331 // executable, a copy relocation will be needed at link time. dso_local is
3332 // excluded for thread-local variables because they generally don't support
3333 // copy relocations.
3334 if (auto globalOp = dyn_cast<cir::GlobalOp>(gv.getOperation())) {
3335 // Assume variables are not thread-local until that support is added.
3337 return true;
3338 }
3339
3340 // -fno-pic sets dso_local on a function declaration to allow direct
3341 // accesses when taking its address (similar to a data symbol). If the
3342 // function is not defined in the executable, a canonical PLT entry will be
3343 // needed at link time. -fno-direct-access-external-data can avoid the
3344 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
3345 // it could just cause trouble without providing perceptible benefits.
3346 if (isa<cir::FuncOp>(gv) && !cgOpts.NoPLT && rm == llvm::Reloc::Static)
3347 return true;
3348 }
3349
3350 // If we can use copy relocations we can assume it is local.
3351
3352 // Otherwise don't assume it is local.
3353
3354 return false;
3355}
3356
3357void CIRGenModule::setGlobalVisibility(cir::CIRGlobalValueInterface gv,
3358 const NamedDecl *d) const {
3359 // Internal definitions always have default visibility.
3360 if (gv.hasLocalLinkage()) {
3361 gv.setGlobalVisibility(cir::VisibilityKind::Default);
3362 return;
3363 }
3364 if (!d)
3365 return;
3366
3367 // Set visibility for definitions, and for declarations if requested globally
3368 // or set explicitly.
3370
3371 // OpenMP declare target variables must be visible to the host so they can
3372 // be registered. We require protected visibility unless the variable has
3373 // the DT_nohost modifier and does not need to be registered.
3374 if (getASTContext().getLangOpts().OpenMP &&
3375 getASTContext().getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(d) &&
3376 d->hasAttr<OMPDeclareTargetDeclAttr>() &&
3377 d->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
3378 OMPDeclareTargetDeclAttr::DT_NoHost &&
3380 llvm_unreachable("setGlobalVisibility: OpenMP is NYI");
3381 return;
3382 }
3383
3384 // CUDA/HIP device kernels and global variables must be visible to the host
3385 // so they can be registered / initialized. We require protected visibility
3386 // unless the user explicitly requested hidden via an attribute.
3387 if (getASTContext().getLangOpts().CUDAIsDevice &&
3389 !d->hasAttr<OMPDeclareTargetDeclAttr>()) {
3390 bool needsProtected = false;
3391 if (isa<FunctionDecl>(d)) {
3392 needsProtected =
3393 d->hasAttr<CUDAGlobalAttr>() || d->hasAttr<DeviceKernelAttr>();
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();
3399 }
3400 if (needsProtected) {
3401 gv.setGlobalVisibility(cir::VisibilityKind::Protected);
3402 return;
3403 }
3404 }
3405
3407 gv.setGlobalVisibility(cir::VisibilityKind::Hidden);
3408 return;
3409 }
3410
3412
3413 if (lv.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
3414 !gv.isDeclarationForLinker())
3415 gv.setGlobalVisibility(getCIRVisibilityKind(lv.getVisibility()));
3416}
3417
3418void CIRGenModule::setDSOLocal(cir::CIRGlobalValueInterface gv) const {
3419 gv.setDSOLocal(shouldAssumeDSOLocal(*this, gv));
3420}
3421
3422void CIRGenModule::setDSOLocal(mlir::Operation *op) const {
3423 if (auto globalValue = dyn_cast<cir::CIRGlobalValueInterface>(op))
3424 setDSOLocal(globalValue);
3425}
3426
3427void CIRGenModule::setGVProperties(mlir::Operation *op,
3428 const NamedDecl *d) const {
3430 setGVPropertiesAux(op, d);
3431}
3432
3433void CIRGenModule::setGVPropertiesAux(mlir::Operation *op,
3434 const NamedDecl *d) const {
3436 setDSOLocal(op);
3438}
3439
3441 GlobalDecl &result) const {
3442 auto res = manglings.find(mangledName);
3443 if (res == manglings.end())
3444 return false;
3445 result = res->getValue();
3446 return true;
3447}
3448
3449static cir::TLSModel getCIRTLSModel(StringRef S) {
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);
3455}
3456
3458 switch (getCodeGenOpts().getDefaultTLSModel()) {
3460 return cir::TLSModel::GeneralDynamic;
3462 return cir::TLSModel::LocalDynamic;
3464 return cir::TLSModel::InitialExec;
3466 return cir::TLSModel::LocalExec;
3467 }
3468 llvm_unreachable("Invalid TLS model!");
3469}
3470
3471void CIRGenModule::setTLSMode(mlir::Operation *op, const VarDecl &d,
3472 bool isExtendingDecl) {
3473 assert(d.getTLSKind() && "setting TLS mode on non-TLS var!");
3474
3475 cir::TLSModel tlm = getDefaultCIRTLSModel();
3476
3477 // Override the TLS model if it is explicitly specified.
3478 if (const auto *attr = d.getAttr<TLSModelAttr>())
3479 tlm = getCIRTLSModel(attr->getModel());
3480
3481 auto global = cast<cir::GlobalOp>(op);
3482 global.setTlsModel(tlm);
3483
3484 // For namespace-scope dyanmic TLS we need to set the wrapper, int, or guard
3485 // info.
3486 if (d.isStaticLocal())
3487 return;
3488
3489 // If this function was called to set the TLS mode for a temporary whose
3490 // lifetime is extended by the variable declared by `d`, don't emit the
3491 // wrapper, init, and guard info.
3492 if (isExtendingDecl)
3493 return;
3494
3495 setGlobalTlsReferences(d, global);
3496}
3497
3499 const CIRGenFunctionInfo &info,
3500 cir::FuncOp func, bool isThunk) {
3501 // TODO(cir): More logic of constructAttributeList is needed.
3502 cir::CallingConv callingConv;
3503
3504 // TODO(cir): The current list should be initialized with the extra function
3505 // attributes, but we don't have those yet. For now, the PAL is initialized
3506 // with nothing.
3508 // Initialize PAL with existing attributes to merge attributes.
3509 mlir::NamedAttrList pal{};
3510 std::vector<mlir::NamedAttrList> argAttrs(info.arguments().size());
3511 mlir::NamedAttrList retAttrs{};
3512 constructAttributeList(func.getName(), info, globalDecl, pal, argAttrs,
3513 retAttrs, callingConv,
3514 /*attrOnCallSite=*/false, isThunk);
3515
3516 for (mlir::NamedAttribute attr : pal)
3517 func->setAttr(attr.getName(), attr.getValue());
3518
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());
3522 });
3523 if (!retAttrs.empty())
3524 mlir::function_interface_impl::setResultAttrs(func, 0, retAttrs);
3525
3526 // TODO(cir): Check X86_VectorCall incompatibility wiht WinARM64EC
3527
3528 func.setCallingConv(callingConv);
3529}
3530
3532 cir::FuncOp func,
3533 bool isIncompleteFunction,
3534 bool isThunk) {
3535 // NOTE(cir): Original CodeGen checks if this is an intrinsic. In CIR we
3536 // represent them in dedicated ops. The correct attributes are ensured during
3537 // translation to LLVM. Thus, we don't need to check for them here.
3538
3539 const auto *funcDecl = cast<FunctionDecl>(globalDecl.getDecl());
3540
3541 if (!isIncompleteFunction)
3542 setCIRFunctionAttributes(globalDecl,
3543 getTypes().arrangeGlobalDeclaration(globalDecl),
3544 func, isThunk);
3545
3546 // Add the Returned attribute for "this", except for iOS 5 and earlier
3547 // where substantial code, including the libstdc++ dylib, was compiled with
3548 // GCC and does not actually return "this".
3549 if (!isThunk && getCXXABI().hasThisReturn(globalDecl) &&
3550 !(getTriple().isiOS() && getTriple().isOSVersionLT(6)))
3551 func.setArgAttr(0, mlir::LLVM::LLVMDialect::getReturnedAttrName(),
3552 mlir::UnitAttr::get(&getMLIRContext()));
3553
3554 if (!isIncompleteFunction && func.isDeclaration())
3555 getTargetCIRGenInfo().setTargetAttributes(funcDecl, func, *this);
3556
3557 // Diagnose calls to this function at the backend level, mirroring
3558 // CodeGenModule::SetFunctionAttributes's "dontcall-error"/"dontcall-warn".
3559 if (const auto *errorAttr = funcDecl->getAttr<ErrorAttr>()) {
3560 if (errorAttr->isError())
3561 func->setAttr(cir::CIRDialect::getDontCallErrorAttrName(),
3562 mlir::StringAttr::get(&getMLIRContext(),
3563 errorAttr->getUserDiagnostic()));
3564 else if (errorAttr->isWarning())
3565 func->setAttr(cir::CIRDialect::getDontCallWarnAttrName(),
3566 mlir::StringAttr::get(&getMLIRContext(),
3567 errorAttr->getUserDiagnostic()));
3568 }
3569
3570 // Mirrors setLinkageForGV in CodeGenModule::SetFunctionAttributes.
3571 setLinkageForFunction(*this, func, funcDecl);
3572
3573 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
3574 if (funcDecl->isInlineBuiltinDeclaration()) {
3575 const FunctionDecl *fdBody;
3576 bool hasBody = funcDecl->hasBody(fdBody);
3577 (void)hasBody;
3578 assert(hasBody && "Inline builtin declarations should always have an "
3579 "available body!");
3581 }
3582
3583 if (funcDecl->isReplaceableGlobalAllocationFunction()) {
3584 // A replaceable global allocation function does not act like a builtin by
3585 // default, only if it is invoked by a new-expression or delete-expression.
3586 func->setAttr(cir::CIRDialect::getNoBuiltinAttrName(),
3587 mlir::UnitAttr::get(&getMLIRContext()));
3588 }
3589
3590 if (isa<CXXConstructorDecl>(funcDecl) || isa<CXXDestructorDecl>(funcDecl))
3591 func.setUnnamedAddr(true);
3592 else if (const auto *md = dyn_cast<CXXMethodDecl>(funcDecl))
3593 if (md->isVirtual())
3594 func.setUnnamedAddr(true);
3595}
3596
3598 const clang::Decl *decl, cir::FuncOp f) {
3599
3600 if ((!decl || !decl->hasAttr<NoUwtableAttr>()) && codeGenOpts.UnwindTables)
3601 f.setUwtable(static_cast<cir::UnwindTableKind>(codeGenOpts.UnwindTables));
3602
3604
3605 if (!CodeGenUtils::hasUnwindExceptions(langOpts))
3606 f->setAttr(cir::CIRDialect::getNoThrowAttrName(),
3607 mlir::UnitAttr::get(&getMLIRContext()));
3608
3609 std::optional<cir::InlineKind> existingInlineKind = f.getInlineKind();
3610 bool isNoInline =
3611 existingInlineKind && *existingInlineKind == cir::InlineKind::NoInline;
3612 bool isAlwaysInline = existingInlineKind &&
3613 *existingInlineKind == cir::InlineKind::AlwaysInline;
3614 if (!decl) {
3615 assert(!cir::MissingFeatures::hlsl());
3616
3617 if (!isAlwaysInline &&
3618 codeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
3619 // If inlining is disabled and we don't have a declaration to control
3620 // inlining, mark the function as 'noinline' unless it is explicitly
3621 // marked as 'alwaysinline'.
3622 f.setInlineKind(cir::InlineKind::NoInline);
3623 }
3624
3625 return;
3626 }
3627
3630 assert(!cir::MissingFeatures::hlsl());
3631
3632 // Track whether we need to add the optnone attribute, starting with the
3633 // default for this optimization level.
3634 bool shouldAddOptNone =
3635 !codeGenOpts.DisableO0ImplyOptNone && codeGenOpts.OptimizationLevel == 0;
3636 // optnone is incompatible with minsize and alwaysinline.
3637 shouldAddOptNone &= !decl->hasAttr<MinSizeAttr>();
3638 shouldAddOptNone &= !decl->hasAttr<AlwaysInlineAttr>();
3639
3640 // Handle inline attributes
3641 if ((shouldAddOptNone || decl->hasAttr<OptimizeNoneAttr>()) &&
3642 !isAlwaysInline) {
3643 // Add optnone, but do so only if the function isn't always_inline.
3644 f->setAttr(cir::CIRDialect::getOptNoneAttrName(),
3645 mlir::UnitAttr::get(&getMLIRContext()));
3646
3647 // OptimizeNone implies noinline; we should not be inlining such functions.
3648 f.setInlineKind(cir::InlineKind::NoInline);
3649
3650 // We still need to handle naked functions even though optnone subsumes
3651 // much of their semantics.
3652 if (decl->hasAttr<NakedAttr>())
3653 f->setAttr(cir::CIRDialect::getNakedAttrName(),
3654 mlir::UnitAttr::get(&getMLIRContext()));
3655
3656 // OptimizeNone wins over OptimizeForSize and MinSize.
3657 f->removeAttr(cir::CIRDialect::getOptimizeForSizeAttrName());
3658 f->removeAttr(cir::CIRDialect::getMinSizeAttrName());
3659 } else if (decl->hasAttr<NakedAttr>()) {
3660 // Naked implies noinline: we should not be inlining such functions.
3661 f->setAttr(cir::CIRDialect::getNakedAttrName(),
3662 mlir::UnitAttr::get(&getMLIRContext()));
3663 f.setInlineKind(cir::InlineKind::NoInline);
3664 } else if (decl->hasAttr<NoDuplicateAttr>()) {
3665 f->setAttr(cir::CIRDialect::getNoDuplicatesAttrName(),
3666 mlir::UnitAttr::get(&getMLIRContext()));
3667 } else if (decl->hasAttr<NoInlineAttr>() && !isAlwaysInline) {
3668 // Add noinline if the function isn't always_inline.
3669 f.setInlineKind(cir::InlineKind::NoInline);
3670 } else if (decl->hasAttr<AlwaysInlineAttr>() && !isNoInline) {
3671 // Don't override AlwaysInline with NoInline, or vice versa, since we can't
3672 // specify both in IR.
3673 f.setInlineKind(cir::InlineKind::AlwaysInline);
3674 } else if (codeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
3675 // If inlining is disabled, force everything that isn't always_inline
3676 // to carry an explicit noinline attribute.
3677 if (!isAlwaysInline)
3678 f.setInlineKind(cir::InlineKind::NoInline);
3679 } else {
3680 // Otherwise, propagate the inline hint attribute and potentially use its
3681 // absence to mark things as noinline.
3682 // Search function and template pattern redeclarations for inline.
3683 if (auto *fd = dyn_cast<FunctionDecl>(decl)) {
3684 // TODO: Share this checkForInline implementation with classic codegen.
3685 // This logic is likely to change over time, so sharing would help ensure
3686 // consistency.
3687 auto checkForInline = [](const FunctionDecl *decl) {
3688 auto checkRedeclForInline = [](const FunctionDecl *redecl) {
3689 return redecl->isInlineSpecified();
3690 };
3691 if (any_of(decl->redecls(), checkRedeclForInline))
3692 return true;
3693 const FunctionDecl *pattern = decl->getTemplateInstantiationPattern();
3694 if (!pattern)
3695 return false;
3696 return any_of(pattern->redecls(), checkRedeclForInline);
3697 };
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);
3704 }
3705 }
3706 }
3707
3708 // Add other optimization related attributes if we are optimizing this
3709 // function.
3710 if (!decl->hasAttr<OptimizeNoneAttr>()) {
3711 if (decl->hasAttr<ColdAttr>()) {
3712 if (!shouldAddOptNone)
3713 f->setAttr(cir::CIRDialect::getOptimizeForSizeAttrName(),
3714 mlir::UnitAttr::get(&getMLIRContext()));
3715
3716 f->setAttr(cir::CIRDialect::getColdAttrName(),
3717 mlir::UnitAttr::get(&getMLIRContext()));
3718 }
3719
3720 if (decl->hasAttr<HotAttr>())
3721 f->setAttr(cir::CIRDialect::getHotAttrName(),
3722 mlir::UnitAttr::get(&getMLIRContext()));
3723
3724 if (decl->hasAttr<MinSizeAttr>())
3725 f->setAttr(cir::CIRDialect::getMinSizeAttrName(),
3726 mlir::UnitAttr::get(&getMLIRContext()));
3727 }
3728
3729 std::optional<uint64_t> explicitAlignment;
3730 if (unsigned alignment =
3731 decl->getMaxAlignment() / getASTContext().getCharWidth())
3732 explicitAlignment = alignment;
3733 else if (langOpts.FunctionAlignment)
3734 explicitAlignment = 1ull << langOpts.FunctionAlignment;
3735
3736 if (explicitAlignment) {
3737 f.setAlignment(*explicitAlignment);
3738 f.setPreferredAlignment(*explicitAlignment);
3739 } else if (langOpts.PreferredFunctionAlignment) {
3740 f.setPreferredAlignment(langOpts.PreferredFunctionAlignment);
3741 }
3742
3743 // Some C++ ABIs require 2-byte alignment for member functions, in order to
3744 // reserve a bit for differentiating between virtual and non-virtual member
3745 // functions. If the current target's C++ ABI requires this and this is a
3746 // member function, set its alignment accordingly.
3747 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
3748 if (isa<CXXMethodDecl>(decl) && f.getAlignment().value_or(1) < 2)
3749 f.setAlignment(2);
3750 }
3751
3752 // Attach "sycl-module-id" to sycl_external function definitions to mark
3753 // them as entry points for per-translation-unit device-code splitting.
3754 if (getLangOpts().SYCLIsDevice && decl->hasAttr<SYCLExternalAttr>())
3756}
3757
3758// Maps an AST address space to the OpenCL logical address space kind recorded
3759// in kernel argument metadata. This mapping is independent of the target
3760// address space map, allowing consumers to distinguish OpenCL logical address
3761// spaces even when the target maps them to the same address space.
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;
3777 default:
3778 // All other AST address spaces, including target-specific ones, use the
3779 // OpenCL metadata default, which lowers to SPIR address space ID 0.
3780 return cir::LangAddressSpace::Default;
3781 }
3782}
3783
3785 const clang::FunctionDecl *fd) {
3786 assert(fd && "expected a kernel function declaration");
3788
3789 // Create arrays that represent the kernel argument metadata. Each array has
3790 // one value per kernel argument, in source order.
3791 SmallVector<mlir::Attribute> addressQuals;
3792 SmallVector<mlir::Attribute> accessQuals;
3793 SmallVector<mlir::Attribute> argTypeNames;
3794 SmallVector<mlir::Attribute> argBaseTypeNames;
3795 SmallVector<mlir::Attribute> argTypeQuals;
3797
3798 for (const ParmVarDecl *param : fd->parameters()) {
3799 argNames.push_back(builder.getStringAttr(param->getName()));
3800
3801 QualType type = param->getType();
3802 std::string typeQuals;
3803
3804 if (type->isImageType() || type->isPipeType()) {
3805 errorNYI(param->getSourceRange(),
3806 "OpenCL kernel argument metadata for image and pipe types");
3807 return;
3808 }
3809
3810 accessQuals.push_back(builder.getStringAttr("none"));
3811
3812 auto getTypeSpelling = [&](QualType paramType) {
3813 std::string typeName = paramType.getUnqualifiedType().getAsString(policy);
3814
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();
3821 }
3822
3823 return typeName;
3824 };
3825
3826 // Type metadata preserves source spelling, while base type metadata uses
3827 // canonical spelling without typedefs.
3828 if (type->isPointerType()) {
3829 QualType pointeeType = type->getPointeeType();
3830 addressQuals.push_back(cir::LangAddressSpaceAttr::get(
3831 &getMLIRContext(),
3832 getOpenCLKernelArgAddressSpace(pointeeType.getAddressSpace())));
3833
3834 argTypeNames.push_back(
3835 builder.getStringAttr(getTypeSpelling(pointeeType) + "*"));
3836 argBaseTypeNames.push_back(builder.getStringAttr(
3837 getTypeSpelling(pointeeType.getCanonicalType()) + "*"));
3838
3839 if (type.isRestrictQualified())
3840 typeQuals = "restrict";
3841 if (pointeeType.isConstQualified() ||
3842 pointeeType.getAddressSpace() == LangAS::opencl_constant)
3843 typeQuals += typeQuals.empty() ? "const" : " const";
3844 if (pointeeType.isVolatileQualified())
3845 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
3846 } else {
3847 addressQuals.push_back(cir::LangAddressSpaceAttr::get(
3848 &getMLIRContext(), cir::LangAddressSpace::Default));
3849
3850 argTypeNames.push_back(builder.getStringAttr(getTypeSpelling(type)));
3851 argBaseTypeNames.push_back(
3852 builder.getStringAttr(getTypeSpelling(type.getCanonicalType())));
3853 }
3854
3855 argTypeQuals.push_back(builder.getStringAttr(typeQuals));
3856 }
3857
3858 mlir::ArrayAttr names;
3859 if (getCodeGenOpts().EmitOpenCLArgMetadata)
3860 names = builder.getArrayAttr(argNames);
3861
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(),
3868 metadata);
3869}
3870
3872 StringRef mangledName, mlir::Type funcType, GlobalDecl gd, bool forVTable,
3873 bool dontDefer, bool isThunk, ForDefinition_t isForDefinition,
3874 mlir::NamedAttrList extraAttrs) {
3875 const Decl *d = gd.getDecl();
3876
3877 if (const auto *fd = cast_or_null<FunctionDecl>(d)) {
3878 // For the device, mark the function as one that should be emitted.
3879 if (getLangOpts().OpenMPIsTargetDevice && openMPRuntime &&
3880 !getOpenMPRuntime().markAsGlobalTarget(gd) && fd->isDefined() &&
3881 !dontDefer && !isForDefinition) {
3882 if (const FunctionDecl *fdDef = fd->getDefinition()) {
3883 GlobalDecl gdDef;
3884 if (const auto *cd = dyn_cast<CXXConstructorDecl>(fdDef))
3885 gdDef = GlobalDecl(cd, gd.getCtorType());
3886 else if (const auto *dd = dyn_cast<CXXDestructorDecl>(fdDef))
3887 gdDef = GlobalDecl(dd, gd.getDtorType());
3888 else
3889 gdDef = GlobalDecl(fdDef);
3890 emitGlobal(gdDef);
3891 }
3892 }
3893
3894 // Any attempts to use a MultiVersion function should result in retrieving
3895 // the iFunc instead. Name mangling will handle the rest of the changes.
3896 if (fd->isMultiVersion())
3897 errorNYI(fd->getSourceRange(), "getOrCreateCIRFunction: multi-version");
3898 }
3899
3900 // Lookup the entry, lazily creating it if necessary.
3901 mlir::Operation *entry = getGlobalValue(mangledName);
3902 if (entry) {
3903 assert(mlir::isa<cir::FuncOp>(entry));
3904
3905 // A weakref's target is only weak until something else names it.
3906 if (weakRefReferences.erase(entry)) {
3907 const auto *fd = cast_or_null<FunctionDecl>(d);
3908 if (fd && !fd->hasAttr<WeakAttr>())
3909 cast<cir::FuncOp>(entry).setLinkage(
3910 cir::GlobalLinkageKind::ExternalLinkage);
3911 }
3912
3913 // Handle dropped DLL attributes.
3914 if (d && !d->hasAttr<DLLImportAttr>() && !d->hasAttr<DLLExportAttr>()) {
3916 setDSOLocal(entry);
3917 }
3918
3919 // If there are two attempts to define the same mangled name, issue an
3920 // error.
3921 auto fn = cast<cir::FuncOp>(entry);
3922 if (isForDefinition && fn && !fn.isDeclaration()) {
3923 GlobalDecl otherGd;
3924 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3925 // to make sure that we issue an error only once.
3926 if (lookupRepresentativeDecl(mangledName, otherGd) &&
3927 (gd.getCanonicalDecl().getDecl() !=
3928 otherGd.getCanonicalDecl().getDecl()) &&
3929 diagnosedConflictingDefinitions.insert(gd).second) {
3930 getDiags().Report(d->getLocation(), diag::err_duplicate_mangled_name)
3931 << mangledName;
3932 getDiags().Report(otherGd.getDecl()->getLocation(),
3933 diag::note_previous_definition);
3934 }
3935 }
3936
3937 if (fn && fn.getFunctionType() == funcType) {
3938 return fn;
3939 }
3940
3941 if (!isForDefinition) {
3942 return fn;
3943 }
3944
3945 // TODO(cir): classic codegen checks here if this is a llvm::GlobalAlias.
3946 // How will we support this?
3947 }
3948
3949 auto *funcDecl = llvm::cast_or_null<FunctionDecl>(gd.getDecl());
3950 bool invalidLoc = !funcDecl ||
3951 funcDecl->getSourceRange().getBegin().isInvalid() ||
3952 funcDecl->getSourceRange().getEnd().isInvalid();
3953 cir::FuncOp funcOp = createCIRFunction(
3954 invalidLoc ? theModule->getLoc() : getLoc(funcDecl->getSourceRange()),
3955 mangledName, mlir::cast<cir::FuncType>(funcType), funcDecl);
3956
3957 if (funcDecl && funcDecl->hasAttr<AnnotateAttr>())
3958 deferredAnnotations[mangledName] = funcDecl;
3959
3960 // If we already created a function with the same mangled name (but different
3961 // type) before, take its name and add it to the list of functions to be
3962 // replaced with F at the end of CodeGen.
3963 //
3964 // This happens if there is a prototype for a function (e.g. "int f()") and
3965 // then a definition of a different type (e.g. "int f(int x)").
3966 if (entry) {
3967
3968 // Fetch a generic symbol-defining operation and its uses.
3969 auto symbolOp = mlir::cast<mlir::SymbolOpInterface>(entry);
3970
3971 // This might be an implementation of a function without a prototype, in
3972 // which case, try to do special replacement of calls which match the new
3973 // prototype. The really key thing here is that we also potentially drop
3974 // arguments from the call site so as to make a direct call, which makes the
3975 // inliner happier and suppresses a number of optimizer warnings (!) about
3976 // dropping arguments.
3977 if (symbolOp.getSymbolUses(symbolOp->getParentOp()))
3979
3980 // Obliterate no-proto declaration.
3981 eraseGlobalSymbol(entry);
3982 entry->erase();
3983 }
3984
3985 if (d)
3986 setFunctionAttributes(gd, funcOp, /*isIncompleteFunction=*/false, isThunk);
3987 if (!extraAttrs.empty())
3988 for (mlir::NamedAttribute attr : extraAttrs)
3989 if (!funcOp->hasDiscardableAttr(attr.getName()))
3990 funcOp->setDiscardableAttr(attr.getName(), attr.getValue());
3991
3992 // 'dontDefer' actually means don't move this to the deferredDeclsToEmit list.
3993 if (dontDefer) {
3994 // TODO(cir): This assertion will need an additional condition when we
3995 // support incomplete functions.
3996 assert(funcOp.getFunctionType() == funcType);
3997 return funcOp;
3998 }
3999
4000 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
4001 // each other bottoming out wiht the base dtor. Therefore we emit non-base
4002 // dtors on usage, even if there is no dtor definition in the TU.
4003 if (isa_and_nonnull<CXXDestructorDecl>(d) &&
4004 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(d),
4005 gd.getDtorType()))
4006 errorNYI(d->getSourceRange(), "getOrCreateCIRFunction: dtor");
4007
4008 // This is the first use or definition of a mangled name. If there is a
4009 // deferred decl with this name, remember that we need to emit it at the end
4010 // of the file.
4011 auto ddi = deferredDecls.find(mangledName);
4012 if (ddi != deferredDecls.end()) {
4013 // Move the potentially referenced deferred decl to the
4014 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
4015 // don't need it anymore).
4016 addDeferredDeclToEmit(ddi->second);
4017 deferredDecls.erase(ddi);
4018
4019 // Otherwise, there are cases we have to worry about where we're using a
4020 // declaration for which we must emit a definition but where we might not
4021 // find a top-level definition.
4022 // - member functions defined inline in their classes
4023 // - friend functions defined inline in some class
4024 // - special member functions with implicit definitions
4025 // If we ever change our AST traversal to walk into class methods, this
4026 // will be unnecessary.
4027 //
4028 // We also don't emit a definition for a function if it's going to be an
4029 // entry in a vtable, unless it's already marked as used.
4030 } else if (getLangOpts().CPlusPlus && d) {
4031 // Look for a declaration that's lexically in a record.
4032 for (const auto *fd = cast<FunctionDecl>(d)->getMostRecentDecl(); fd;
4033 fd = fd->getPreviousDecl()) {
4034 if (isa<CXXRecordDecl>(fd->getLexicalDeclContext())) {
4035 if (fd->doesThisDeclarationHaveABody()) {
4037 break;
4038 }
4039 }
4040 }
4041 }
4042
4043 return funcOp;
4044}
4045
4046cir::FuncOp
4047CIRGenModule::createCIRFunction(mlir::Location loc, StringRef name,
4048 cir::FuncType funcType,
4049 const clang::FunctionDecl *funcDecl) {
4050 cir::FuncOp func;
4051 {
4052 mlir::OpBuilder::InsertionGuard guard(builder);
4053
4054 // Functions always belong at module scope, but the ambient insertion
4055 // point may be inside another op's region, e.g. a thunk body or a
4056 // global's ctor region, so it cannot be used here.
4057 builder.setInsertionPointToEnd(getModule().getBody());
4058
4059 func = cir::FuncOp::create(builder, loc, name, funcType);
4060
4061 symbolLookupCache[func.getSymNameAttr()] = func;
4062
4064
4065 if (funcDecl && !funcDecl->hasPrototype())
4066 func.setNoProto(true);
4067
4068 assert(func.isDeclaration() && "expected empty body");
4069
4070 // A declaration gets private visibility by default, but external linkage
4071 // as the default linkage.
4072 func.setLinkageAttr(cir::GlobalLinkageKindAttr::get(
4073 &getMLIRContext(), cir::GlobalLinkageKind::ExternalLinkage));
4074 mlir::SymbolTable::setSymbolVisibility(
4075 func, mlir::SymbolTable::Visibility::Private);
4076
4078
4079 // Record the func_info tag, a C++ special member form or a known standard
4080 // library entity.
4081 setFuncInfoAttr(func, funcDecl);
4082
4083 if (funcDecl && this->getLangOpts().OpenACC) {
4084 // We only have to handle this attribute, since OpenACCAnnotAttrs are
4085 // handled via the end-of-TU work.
4086 for (const auto *attr :
4087 funcDecl->specific_attrs<OpenACCRoutineDeclAttr>())
4088 emitOpenACCRoutineDecl(funcDecl, func, attr->getLocation(),
4089 attr->Clauses);
4090 }
4091 }
4092 return func;
4093}
4094
4095cir::FuncOp
4096CIRGenModule::createCIRBuiltinFunction(mlir::Location loc, StringRef name,
4097 cir::FuncType ty,
4098 const clang::FunctionDecl *fd) {
4099 cir::FuncOp fnOp = createCIRFunction(loc, name, ty, fd);
4100 fnOp.setBuiltin(true);
4101 return fnOp;
4102}
4103
4104static cir::CtorKind getCtorKindFromDecl(const CXXConstructorDecl *ctor) {
4105 if (ctor->isDefaultConstructor())
4106 return cir::CtorKind::Default;
4107 if (ctor->isCopyConstructor())
4108 return cir::CtorKind::Copy;
4109 if (ctor->isMoveConstructor())
4110 return cir::CtorKind::Move;
4111 return cir::CtorKind::Custom;
4112}
4113
4114static cir::AssignKind getAssignKindFromDecl(const CXXMethodDecl *method) {
4115 if (method->isCopyAssignmentOperator())
4116 return cir::AssignKind::Copy;
4117 if (method->isMoveAssignmentOperator())
4118 return cir::AssignKind::Move;
4119 llvm_unreachable("not a copy or move assignment operator");
4120}
4121
4122void CIRGenModule::setFuncInfoAttr(cir::FuncOp funcOp,
4123 const clang::FunctionDecl *funcDecl) {
4124 if (!funcDecl)
4125 return;
4126
4127 if (const auto *dtor = dyn_cast<CXXDestructorDecl>(funcDecl)) {
4128 auto cxxDtor = cir::CXXDtorAttr::get(
4129 convertType(getASTContext().getCanonicalTagType(dtor->getParent())),
4130 dtor->isTrivial());
4131 funcOp.setFuncInfoAttr(cxxDtor);
4132 return;
4133 }
4134
4135 if (const auto *ctor = dyn_cast<CXXConstructorDecl>(funcDecl)) {
4136 cir::CtorKind kind = getCtorKindFromDecl(ctor);
4137 auto cxxCtor = cir::CXXCtorAttr::get(
4138 convertType(getASTContext().getCanonicalTagType(ctor->getParent())),
4139 kind, ctor->isTrivial());
4140 funcOp.setFuncInfoAttr(cxxCtor);
4141 return;
4142 }
4143
4144 const auto *method = dyn_cast<CXXMethodDecl>(funcDecl);
4145 if (method && (method->isCopyAssignmentOperator() ||
4146 method->isMoveAssignmentOperator())) {
4147 cir::AssignKind assignKind = getAssignKindFromDecl(method);
4148 auto cxxAssign = cir::CXXAssignAttr::get(
4149 convertType(getASTContext().getCanonicalTagType(method->getParent())),
4150 assignKind, method->isTrivial());
4151 funcOp.setFuncInfoAttr(cxxAssign);
4152 return;
4153 }
4154
4155 // Otherwise tag a function that matches a known standard library entity. A
4156 // known entity is named by a plain identifier in std. For a member the
4157 // record decides std membership. Inline namespaces, like the versioning
4158 // namespace of libc++, count as part of std.
4159 if (!funcDecl->getIdentifier())
4160 return;
4161 bool inStdNamespace = method ? method->getParent()->isInStdNamespace()
4162 : funcDecl->isInStdNamespace();
4163 if (!inStdNamespace)
4164 return;
4165
4166 // The names and the tags come from CIRStdOps.td, and the recognizer checks
4167 // the shape of each call. Only free functions name a known entity today, so
4168 // a member like char_traits::find never shares the tag of the free std::find.
4169 std::optional<cir::KnownFuncKind> kind;
4170 if (!method) {
4171 kind = llvm::StringSwitch<std::optional<cir::KnownFuncKind>>(
4172 funcDecl->getName())
4173 .Case(cir::StdFindOp::getFunctionName(),
4174 cir::StdFindOp::getFuncKind())
4175 .Default(std::nullopt);
4176 }
4177 if (!kind)
4178 return;
4179
4180 funcOp.setFuncInfoAttr(cir::FuncIdentityAttr::get(&getMLIRContext(), *kind));
4181}
4182
4183static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal,
4184 cir::FuncOp funcOp, StringRef name) {
4185 // In Windows Itanium environments, try to mark runtime functions
4186 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4187 // will link their standard library statically or dynamically. Marking
4188 // functions imported when they are not imported can cause linker errors
4189 // and warnings.
4190 if (!isLocal && cgm.getTarget().getTriple().isWindowsItaniumEnvironment() &&
4191 !cgm.getCodeGenOpts().LTOVisibilityPublicStd) {
4195 }
4196}
4197
4198cir::FuncOp CIRGenModule::createRuntimeFunction(cir::FuncType ty,
4199 StringRef name,
4200 mlir::NamedAttrList extraAttrs,
4201 bool isLocal,
4202 bool assumeConvergent) {
4203 if (assumeConvergent)
4204 errorNYI("createRuntimeFunction: assumeConvergent");
4205
4206 extraAttrs.set(cir::CIRDialect::getRuntimeFuncAttrName(),
4207 mlir::UnitAttr::get(&getMLIRContext()));
4208 cir::FuncOp entry = getOrCreateCIRFunction(name, ty, GlobalDecl(),
4209 /*forVtable=*/false, extraAttrs);
4210
4211 if (entry) {
4212 // TODO(cir): set the attributes of the function.
4215 setWindowsItaniumDLLImport(*this, isLocal, entry, name);
4216 entry.setDSOLocal(true);
4217 }
4218
4219 return entry;
4220}
4221
4222mlir::SymbolTable::Visibility
4224 // MLIR doesn't accept public symbols declarations (only
4225 // definitions).
4226 if (op.isDeclaration())
4227 return mlir::SymbolTable::Visibility::Private;
4228 return getMLIRVisibilityFromCIRLinkage(op.getLinkage());
4229}
4230
4231mlir::SymbolTable::Visibility
4233 switch (glk) {
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;
4245 default: {
4246 llvm::errs() << "visibility not implemented for '"
4247 << stringifyGlobalLinkageKind(glk) << "'\n";
4248 assert(0 && "not implemented");
4249 }
4250 }
4251 llvm_unreachable("linkage should be handled above!");
4252}
4253
4254std::string CIRGenModule::getModuleInitializerName(clang::Module *mod) {
4255 std::string name;
4256 llvm::raw_string_ostream out(name);
4257 cast<clang::ItaniumMangleContext>(getCXXABI().getMangleContext())
4258 .mangleModuleInitializer(mod, out);
4259 return name;
4260}
4261
4263 emitDeferred();
4265 applyReplacements();
4266
4267 getModule()->setAttr(cir::CIRDialect::getModuleLevelAsmAttrName(),
4268 builder.getArrayAttr(globalScopeAsm));
4269
4270 emitGlobalAnnotations();
4271
4272 if (std::optional<cir::FramePointerKind> kind =
4273 getFramePointerKind(codeGenOpts.getFramePointer()))
4274 getModule()->setAttr(
4275 cir::CIRDialect::getModuleFramePointerAttrName(),
4276 cir::FramePointerKindAttr::get(&getMLIRContext(), *kind));
4277
4278 if (!recordLayoutEntries.empty())
4279 getModule()->setAttr(
4280 cir::CIRDialect::getRecordLayoutsAttrName(),
4281 mlir::DictionaryAttr::get(&getMLIRContext(), recordLayoutEntries));
4282
4283 if (getTriple().isAMDGPU() ||
4284 (getTriple().isSPIRV() && getTriple().getVendor() == llvm::Triple::AMD))
4286
4287 if (getLangOpts().HIP) {
4288 // Emit a unique ID so that host and device binaries from the same
4289 // compilation unit can be associated.
4290 std::string cuidName =
4291 ("__hip_cuid_" + getASTContext().getCUIDHash()).str();
4292 auto int8Ty = cir::IntType::get(&getMLIRContext(), 8, /*isSigned=*/false);
4293 auto loc = builder.getUnknownLoc();
4294 mlir::ptr::MemorySpaceAttrInterface addrSpace =
4296
4297 auto gv = createGlobalOp(loc, cuidName, int8Ty,
4298 /*isConstant=*/false, addrSpace);
4299 gv.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
4300 // Initialize with zero
4301 auto zeroAttr = cir::IntAttr::get(int8Ty, 0);
4302 gv.setInitialValueAttr(zeroAttr);
4303 // External linkage requires public visibility
4304 mlir::SymbolTable::setSymbolVisibility(
4305 gv, mlir::SymbolTable::Visibility::Public);
4306
4308 }
4309
4310 if (astContext.getLangOpts().CUDA && cudaRuntime)
4312
4313 emitLLVMUsed();
4314
4315 // Precompute the mangled C++20 named-module initializer function name and
4316 // stash it on the ModuleOp so LoweringPrepare (which runs without a live
4317 // ASTContext) can read it back as an attribute. This attribute is the only
4318 // channel through which the named-module initializer reaches lowering: its
4319 // presence tells LoweringPrepare both what to call the global-init function
4320 // and that the function needs external linkage, and its absence selects the
4321 // `_GLOBAL__sub_I_` form. Lowering therefore never has to rediscover the
4322 // module from the AST.
4323 if (cxx20ModuleInits) {
4324 clang::Module *primary = astContext.getCurrentNamedModule();
4325 bool isInterfaceUnit = primary && !primary->isModuleImplementation();
4326 if (isInterfaceUnit)
4327 getModule()->setAttr(
4328 cir::CIRDialect::getCXXModuleInitFnNameAttrName(),
4329 builder.getStringAttr(getModuleInitializerName(primary)));
4330
4331 // The imported modules whose initializers the global init function of
4332 // this translation unit calls first, selected as in classic CodeGen.
4335 primary, importedModules.getArrayRef())) {
4336 // A module that only the interface unit's export or import lists name
4337 // takes the location of the module declaration.
4338 auto importLoc = moduleImportLocs.find(mod);
4339 mlir::Location loc =
4340 getLoc(importLoc != moduleImportLocs.end() ? importLoc->second
4341 : primary->DefinitionLoc);
4342 importedInits.push_back(cir::CXXModuleInitAttr::get(
4343 &getMLIRContext(),
4344 builder.getStringAttr(getModuleInitializerName(mod)), loc));
4345 }
4346 if (!importedInits.empty())
4347 getModule()->setAttr(cir::CIRDialect::getCXXModuleImportedInitsAttrName(),
4348 builder.getArrayAttr(importedInits));
4349 }
4350
4351 // Autolink metadata for the imported modules is not emitted yet.
4353
4354 // Classic codegen calls `checkAliases` here to validate any alias
4355 // definitions emitted during codegen.
4357
4358 // There's a lot of code that is not implemented yet.
4360}
4361
4363 const auto *d = cast<ValueDecl>(gd.getDecl());
4364 const AliasAttr *aa = d->getAttr<AliasAttr>();
4365 assert(aa && "Not an alias?");
4366
4367 StringRef mangledName = getMangledName(gd);
4368
4369 if (aa->getAliasee() == mangledName) {
4370 diags.Report(aa->getLocation(), diag::err_cyclic_alias) << 0;
4371 return;
4372 }
4373
4374 // If there is a definition in the module, then it wins over the alias.
4375 // This is dubious, but allow it to be safe. Just ignore the alias.
4376 mlir::Operation *entry = getGlobalValue(mangledName);
4377 if (entry) {
4378 auto entryGV = mlir::dyn_cast<cir::CIRGlobalValueInterface>(entry);
4379 if (entryGV && entryGV.isDefinition())
4380 return;
4381 }
4382
4383 // Classic codegen pushes the alias onto an `Aliases` list at this point so
4384 // that `checkAliases` can later validate the alias and recover on error.
4386
4387 mlir::Location loc = getLoc(d->getSourceRange());
4388 bool isFunction = isa<FunctionDecl>(d);
4389
4390 // Get the linkage and the type of the alias.
4391 mlir::Type declTy;
4392 cir::GlobalLinkageKind linkage;
4393 if (isFunction) {
4394 declTy = getTypes().getFunctionType(gd);
4395 linkage = getFunctionLinkage(gd);
4396 } else {
4397 declTy = getTypes().convertTypeForMem(d->getType());
4398 const auto *vd = cast<VarDecl>(d);
4399 linkage = getCIRLinkageVarDefinition(vd);
4400 }
4401 //
4402 // Create the alias op.
4403 // TODO(cir): Make GlobalAlias a separate op.
4404 cir::CIRGlobalValueInterface alias =
4405 isFunction ? mlir::cast<cir::CIRGlobalValueInterface>(
4406 createCIRFunction(loc, mangledName,
4407 mlir::cast<cir::FuncType>(declTy),
4409 .getOperation())
4410 : mlir::cast<cir::CIRGlobalValueInterface>(
4411 createGlobalOp(loc, mangledName, declTy).getOperation());
4412
4413 // Create the alias op. If there is an existing declaration with the same
4414 // name, erase it: any references to it via flat symbol reference will
4415 // automatically resolve to the new alias.
4416 // However, function aliases actually change its type, so we have to replace
4417 // uses of it.
4418 if (entry) {
4419 if (isFunction)
4421 entry, mlir::cast<cir::FuncOp>(alias.getOperation()));
4422 eraseGlobalSymbol(entry);
4423 entry->erase();
4424 }
4425
4426 // Aliases that target weak symbols must themselves be marked weak.
4427 if (d->hasAttr<WeakAttr>() || d->hasAttr<WeakRefAttr>() ||
4428 d->isWeakImported())
4429 linkage = cir::GlobalLinkageKind::WeakAnyLinkage;
4430
4431 // Aliases are always definitions, so the MLIR visibility should match the
4432 // linkage rather than defaulting to private.
4433 mlir::SymbolTable::Visibility visibility =
4435
4436 alias.setAliasee(aa->getAliasee());
4437 alias.setLinkage(linkage);
4438 mlir::SymbolTable::setSymbolVisibility(alias, visibility);
4440 setCommonAttributes(gd, alias);
4442}
4443
4444cir::FuncOp CIRGenModule::emitAliasForGlobal(StringRef mangledName,
4445 mlir::Operation *op,
4446 GlobalDecl aliasGD,
4447 cir::FuncOp aliasee,
4448 cir::GlobalLinkageKind linkage) {
4449
4450 auto *aliasFD = dyn_cast<FunctionDecl>(aliasGD.getDecl());
4451 assert(aliasFD && "expected FunctionDecl");
4452
4453 // The aliasee function type is different from the alias one, this difference
4454 // is specific to CIR because in LLVM the ptr types are already erased at this
4455 // point.
4456 const CIRGenFunctionInfo &fnInfo =
4458 cir::FuncType fnType = getTypes().getFunctionType(fnInfo);
4459
4460 cir::FuncOp alias =
4462 mangledName, fnType, aliasFD);
4463 alias.setAliasee(aliasee.getName());
4464 alias.setLinkage(linkage);
4465 // Declarations cannot have public MLIR visibility, just mark them private
4466 // but this really should have no meaning since CIR should not be using
4467 // this information to derive linkage information.
4468 mlir::SymbolTable::setSymbolVisibility(
4469 alias, mlir::SymbolTable::Visibility::Private);
4470
4471 if (op) {
4472 // Any existing users of the existing function declaration will be
4473 // referencing the function by flat symbol reference (i.e. the name), so
4474 // those uses will automatically resolve to the alias now that we've
4475 // replaced the function declaration. We can safely erase the existing
4476 // function declaration.
4477 assert(cast<cir::FuncOp>(op).getFunctionType() == alias.getFunctionType() &&
4478 "declaration exists with different type");
4480 op->erase();
4481 } else {
4482 // Name already set by createCIRFunction
4483 }
4484
4485 // Finally, set up the alias with its proper name and attributes.
4486 setCommonAttributes(aliasGD, alias);
4487 return alias;
4488}
4489
4491 return genTypes.convertType(type);
4492}
4493
4495 // Verify the module after we have finished constructing it, this will
4496 // check the structural properties of the IR and invoke any specific
4497 // verifiers we have on the CIR operations.
4498 return mlir::verify(getModule()).succeeded();
4499}
4500
4501mlir::Attribute CIRGenModule::getAddrOfRTTIDescriptor(mlir::Location loc,
4502 QualType ty, bool forEh) {
4503 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4504 // FIXME: should we even be calling this method if RTTI is disabled
4505 // and it's not for EH?
4506 if (!shouldEmitRTTI(forEh))
4507 return builder.getConstNullPtrAttr(builder.getUInt8PtrTy());
4508
4509 if (forEh && ty->isObjCObjectPointerType() &&
4510 langOpts.ObjCRuntime.isGNUFamily()) {
4511 errorNYI(loc, "getAddrOfRTTIDescriptor: Objc PtrType & Objc RT GUN");
4512 return {};
4513 }
4514
4515 return getCXXABI().getAddrOfRTTIDescriptor(loc, ty);
4516}
4517
4518// TODO(cir): this can be shared with LLVM codegen.
4520 const CXXRecordDecl *derivedClass,
4521 llvm::iterator_range<CastExpr::path_const_iterator> path) {
4522 CharUnits offset = CharUnits::Zero();
4523
4524 const ASTContext &astContext = getASTContext();
4525 const CXXRecordDecl *rd = derivedClass;
4526
4527 for (const CXXBaseSpecifier *base : path) {
4528 assert(!base->isVirtual() && "Should not see virtual bases here!");
4529
4530 // Get the layout.
4531 const ASTRecordLayout &layout = astContext.getASTRecordLayout(rd);
4532
4533 const auto *baseDecl = base->getType()->castAsCXXRecordDecl();
4534
4535 // Add the offset.
4536 offset += layout.getBaseClassOffset(baseDecl);
4537
4538 rd = baseDecl;
4539 }
4540
4541 return offset;
4542}
4543
4545 llvm::StringRef feature) {
4546 unsigned diagID = diags.getCustomDiagID(
4547 DiagnosticsEngine::Error, "ClangIR code gen Not Yet Implemented: %0");
4548 return diags.Report(loc, diagID) << feature;
4549}
4550
4552 llvm::StringRef feature) {
4553 return errorNYI(loc.getBegin(), feature) << loc;
4554}
4555
4557 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
4558 getDiags().Report(astContext.getFullLoc(loc), diagID) << error;
4559}
4560
4561/// Print out an error that codegen doesn't support the specified stmt yet.
4562void CIRGenModule::errorUnsupported(const Stmt *s, llvm::StringRef type) {
4563 unsigned diagId = diags.getCustomDiagID(DiagnosticsEngine::Error,
4564 "cannot compile this %0 yet");
4565 diags.Report(astContext.getFullLoc(s->getBeginLoc()), diagId)
4566 << type << s->getSourceRange();
4567}
4568
4569/// Print out an error that codegen doesn't support the specified decl yet.
4570void CIRGenModule::errorUnsupported(const Decl *d, llvm::StringRef type) {
4571 unsigned diagId = diags.getCustomDiagID(DiagnosticsEngine::Error,
4572 "cannot compile this %0 yet");
4573 diags.Report(astContext.getFullLoc(d->getLocation()), diagId) << type;
4574}
4575
4576mlir::Operation *
4578 const Expr *init) {
4579 assert((mte->getStorageDuration() == SD_Static ||
4580 mte->getStorageDuration() == SD_Thread) &&
4581 "not a global temporary");
4582 const auto *varDecl = cast<VarDecl>(mte->getExtendingDecl());
4583
4584 // Use the MaterializeTemporaryExpr's type if it has the same unqualified
4585 // base type as Init. This preserves cv-qualifiers (e.g. const from a
4586 // constexpr or const-ref binding) that skipRValueSubobjectAdjustments may
4587 // have dropped via NoOp casts, while correctly falling back to Init's type
4588 // when a real subobject adjustment changed the type (e.g. member access or
4589 // base-class cast in C++98), where E->getType() reflects the reference type,
4590 // not the actual storage type.
4591 QualType materializedType = init->getType();
4592 if (getASTContext().hasSameUnqualifiedType(mte->getType(), materializedType))
4593 materializedType = mte->getType();
4594
4595 CharUnits align = getASTContext().getTypeAlignInChars(materializedType);
4596 mlir::Location loc = getLoc(mte->getSourceRange());
4597
4598 // FIXME: If an externally-visible declaration extends multiple temporaries,
4599 // we need to give each temporary the same name in every translation unit (and
4600 // we also need to make the temporaries externally-visible).
4602 llvm::raw_svector_ostream out(name);
4604 varDecl, mte->getManglingNumber(), out);
4605
4606 auto insertResult = materializedGlobalTemporaryMap.insert({mte, nullptr});
4607 if (!insertResult.second) {
4608 mlir::Type type = getTypes().convertTypeForMem(materializedType);
4609 // We've seen this before: either we already created it or we're in the
4610 // process of doing so.
4611 if (!insertResult.first->second) {
4612 // We recursively re-entered this function, probably during emission of
4613 // the initializer. Create a placeholder.
4614 insertResult.first->second =
4615 createGlobalOp(loc, name, type, /*isConstant=*/false);
4616 }
4617 return insertResult.first->second;
4618 }
4619
4620 APValue *value = nullptr;
4621 if (mte->getStorageDuration() == SD_Static && varDecl->evaluateValue()) {
4622 // If the initializer of the extending declaration is a constant
4623 // initializer, we should have a cached constant initializer for this
4624 // temporay. Note taht this m ight have a different value from the value
4625 // computed by evaluating the initializer if the surrounding constant
4626 // expression modifies the temporary.
4627 value = mte->getOrCreateValue(/*MayCreate=*/false);
4628 }
4629
4630 // Try evaluating it now, it might have a constant initializer
4631 Expr::EvalResult evalResult;
4632 if (!value && init->EvaluateAsRValue(evalResult, getASTContext()) &&
4633 !evalResult.hasSideEffects())
4634 value = &evalResult.Val;
4635
4637
4638 std::optional<ConstantEmitter> emitter;
4639 mlir::Attribute initialValue = nullptr;
4640 bool isConstant = false;
4641 mlir::Type type;
4642
4643 if (value) {
4644 emitter.emplace(*this);
4645 initialValue = emitter->emitForInitializer(*value, materializedType);
4646
4647 isConstant = materializedType.isConstantStorage(
4648 getASTContext(), /*ExcludeCtor=*/value, /*ExcludeDtor=*/false);
4649
4650 type = mlir::cast<mlir::TypedAttr>(initialValue).getType();
4651 } else {
4652 // No initializer, the initialization will be provided when we initialize
4653 // the declaration which performed lifetime extension.
4654 type = getTypes().convertTypeForMem(materializedType);
4655 }
4656
4657 // Create a global variable for this lifetime-extended temporary.
4658 cir::GlobalLinkageKind linkage = getCIRLinkageVarDefinition(varDecl);
4659 if (linkage == cir::GlobalLinkageKind::ExternalLinkage) {
4660 const VarDecl *initVD;
4661 if (varDecl->isStaticDataMember() && varDecl->getAnyInitializer(initVD) &&
4663 // Temporaries defined inside a class get linkonce_odr linkage because the
4664 // calss can be defined in multiple translation units.
4665 errorNYI(mte->getSourceRange(), "static data member initialization");
4666 } else {
4667 // There is no need for this temporary to have external linkage if the
4668 // VarDecl has external linkage.
4669 linkage = cir::GlobalLinkageKind::InternalLinkage;
4670 }
4671 }
4672 cir::GlobalOp gv = createGlobalOp(loc, name, type, isConstant);
4673 gv.setInitialValueAttr(initialValue);
4674 gv.setLinkage(linkage);
4675 gv.setVisibility(getMLIRVisibilityFromCIRLinkage(linkage));
4676
4677 if (emitter)
4678 emitter->finalize(gv);
4679 // Don't assign dllimport or dllexport to local linkage globals
4680 if (!gv.hasLocalLinkage()) {
4683 }
4684
4685 gv.setAlignment(align.getAsAlign().value());
4686 if (supportsCOMDAT() && gv.isWeakForLinker())
4687 gv.setSelfComdat();
4688 if (varDecl->getTLSKind())
4689 setTLSMode(gv, *varDecl, /*isExtendingDecl=*/true);
4690 mlir::Operation *cv = gv;
4691
4693
4694 // Update the map with the new temporary. If we created a placeholder above,
4695 // erase it as well, the name will have been the same, so our symbol
4696 // references would have been correct. We still do a 'replaceAllUsesWith' in
4697 // case some sort of expression formed a reference to the placeholder
4698 // temporary.
4699 mlir::Operation *&entry = materializedGlobalTemporaryMap[mte];
4700 if (entry) {
4701 entry->replaceAllUsesWith(cv);
4702 eraseGlobalSymbol(entry);
4703 entry->erase();
4704 }
4705 entry = cv;
4706
4707 return cv;
4708}
4709
4711 const UnnamedGlobalConstantDecl *gcd) {
4712 unsigned numEntries = unnamedGlobalConstantDeclMap.size();
4713 cir::GlobalOp *globalOpEntry = &unnamedGlobalConstantDeclMap[gcd];
4714
4715 if (*globalOpEntry)
4716 return *globalOpEntry;
4717
4718 ConstantEmitter emitter(*this);
4719
4720 const APValue &value = gcd->getValue();
4721 assert(!value.isAbsent());
4723 "emitForInitializer should take gcd->getType().getAddressSpace()");
4724 mlir::Attribute init = emitter.emitForInitializer(value, gcd->getType());
4725 auto typedInit = dyn_cast<mlir::TypedAttr>(init);
4726
4727 if (!typedInit)
4728 errorNYI(gcd->getSourceRange(),
4729 "getAddrOfUnnamedGlobalConstantDecl: non-typed initializer");
4730
4732
4733 // Classic codegen always creates these with .constant, then counts on the
4734 // auto-addition of '.#'. CIR global doesn't have this, so we'll just auto-add
4735 // one if this isn't the first. We could probably choose a better name than
4736 // .constant to be unique for this type of decl, but this is consistent with
4737 // classic codegen.
4738 std::string name = numEntries == 0
4739 ? ".constant"
4740 : (Twine(".constant.") + Twine(numEntries)).str();
4741 auto globalOp = createGlobalOp(builder.getUnknownLoc(), name,
4742 typedInit.getType(), /*is_constant=*/true);
4743 globalOp.setLinkage(cir::GlobalLinkageKind::PrivateLinkage);
4744
4745 CharUnits alignment = getASTContext().getTypeAlignInChars(gcd->getType());
4746 globalOp.setAlignment(alignment.getAsAlign().value());
4747 globalOp.setUnnamedAddr(true);
4748 CIRGenModule::setInitializer(globalOp, init);
4749
4750 emitter.finalize(globalOp);
4751 *globalOpEntry = globalOp;
4752 return globalOp;
4753}
4754
4755cir::GlobalOp
4757 StringRef name = getMangledName(tpo);
4758 CharUnits alignment = getNaturalTypeAlignment(tpo->getType());
4759
4760 if (auto globalOp =
4761 mlir::dyn_cast_or_null<cir::GlobalOp>(getGlobalValue(name)))
4762 return globalOp;
4763
4764 ConstantEmitter emitter(*this);
4766 "emitForInitializer should take tpo->getType().getAddressSpace()");
4767 mlir::Attribute init =
4768 emitter.emitForInitializer(tpo->getValue(), tpo->getType());
4769
4770 if (!init) {
4771 errorUnsupported(tpo, "template parameter object");
4772 return {};
4773 }
4774
4775 mlir::TypedAttr typedInit = cast<mlir::TypedAttr>(init);
4776
4777 cir::GlobalLinkageKind linkage =
4779 ? cir::GlobalLinkageKind::LinkOnceODRLinkage
4780 : cir::GlobalLinkageKind::InternalLinkage;
4781
4783 auto globalOp = createGlobalOp(builder.getUnknownLoc(), name,
4784 typedInit.getType(), /*is_constant=*/true);
4785 globalOp.setLinkage(linkage);
4786 globalOp.setAlignment(alignment.getAsAlign().value());
4787 if (supportsCOMDAT() && linkage == cir::GlobalLinkageKind::LinkOnceODRLinkage)
4788 globalOp.setSelfComdat();
4789
4790 CIRGenModule::setInitializer(globalOp, init);
4791 emitter.finalize(globalOp);
4792
4793 insertGlobalSymbol(globalOp);
4794
4795 return globalOp;
4796}
4797
4798//===----------------------------------------------------------------------===//
4799// Annotations
4800//===----------------------------------------------------------------------===//
4801
4802mlir::ArrayAttr
4804 ArrayRef<Expr *> exprs = {attr->args_begin(), attr->args_size()};
4805 // Return a null attr for no-args annotations so OptionalParameter omits
4806 // the args portion entirely from the printed IR.
4807 if (exprs.empty())
4808 return {};
4809
4810 llvm::FoldingSetNodeID id;
4811 for (Expr *e : exprs)
4812 id.Add(cast<clang::ConstantExpr>(e)->getAPValueResult());
4813
4814 mlir::ArrayAttr &lookup = annotationArgs[id.computeHash()];
4815 if (lookup)
4816 return lookup;
4817
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()));
4827 } else {
4828 errorNYI(e->getExprLoc(), "annotation argument expression");
4829 }
4830 }
4831
4832 return lookup = builder.getArrayAttr(args);
4833}
4834
4835cir::AnnotationAttr CIRGenModule::emitAnnotateAttr(const AnnotateAttr *aa) {
4836 mlir::StringAttr annoGV = builder.getStringAttr(aa->getAnnotation());
4837 mlir::ArrayAttr args = getOrCreateAnnotationArgs(aa);
4838 return cir::AnnotationAttr::get(&getMLIRContext(), annoGV, args);
4839}
4840
4842 mlir::Operation *gv) {
4843 assert(d->hasAttr<AnnotateAttr>() && "no annotate attribute");
4844 assert((isa<cir::GlobalOp>(gv) || isa<cir::FuncOp>(gv)) &&
4845 "annotation only on globals");
4847 for (const auto *i : d->specific_attrs<AnnotateAttr>())
4848 annotations.push_back(emitAnnotateAttr(i));
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));
4853}
4854
4855void CIRGenModule::emitGlobalAnnotations() {
4856 for (const auto &[mangledName, vd] : deferredAnnotations) {
4857 mlir::Operation *gv = getGlobalValue(mangledName);
4858 if (gv)
4859 addGlobalAnnotations(vd, gv);
4860 }
4861 deferredAnnotations.clear();
4862}
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()
TokenType getType() const
Returns the token's type, e.g.
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)
Definition Parsing.cpp:137
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.
Definition CIRAttrs.h:48
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
bool isAbsent() const
Definition APValue.h:545
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
TranslationUnitDecl * getTranslationUnitDecl() const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ 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
Definition ASTContext.h:942
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:915
CanQualType VoidTy
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.
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
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.
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.
Definition TargetInfo.h:76
virtual mlir::ptr::MemorySpaceAttrInterface getCIRAllocaAddressSpace() const
Get the address space for alloca.
Definition TargetInfo.h:68
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.
Definition TargetInfo.h:160
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition DeclCXX.cpp:3063
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3058
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3049
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isEffectivelyFinal() const
Determine whether it's impossible for a class to be derived from this class.
Definition DeclCXX.cpp:2341
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:540
base_class_range bases()
Definition DeclCXX.h:609
bool hasDefinition() const
Definition DeclCXX.h:562
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
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.
Definition TypeBase.h:3859
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2407
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
T * getAttr() const
Definition DeclBase.h:582
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition DeclBase.cpp:884
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.
Definition DeclBase.cpp:273
static DeclContext * castToDeclContext(const Decl *)
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:436
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
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.
Definition Diagnostic.h:956
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3997
This represents one expression.
Definition Expr.h:114
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...
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3341
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
Definition Decl.cpp:4909
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:273
StringRef tryGetRealPathName() const
Definition FileEntry.h:298
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition Decl.h:2082
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={})
Definition Decl.h:2345
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2612
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3207
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4846
CallingConv getCallConv() const
Definition TypeBase.h:5201
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
CXXCtorType getCtorType() const
Definition GlobalDecl.h:117
GlobalDecl getCanonicalDecl() const
Definition GlobalDecl.h:106
KernelReferenceKind getKernelReferenceKind() const
Definition GlobalDecl.h:142
GlobalDecl getWithDecl(const Decl *D)
Definition GlobalDecl.h:170
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:134
CXXDtorType getDtorType() const
Definition GlobalDecl.h:122
const Decl * getDecl() const
Definition GlobalDecl.h:115
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
Definition Visibility.h:89
void setLinkage(Linkage L)
Definition Visibility.h:92
Linkage getLinkage() const
Definition Visibility.h:88
bool isVisibilityExplicit() const
Definition Visibility.h:90
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:56
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 ...
Definition Mangle.cpp:202
bool shouldMangleDeclName(const NamedDecl *D)
Definition Mangle.cpp:129
void mangleName(GlobalDecl GD, raw_ostream &)
Definition Mangle.cpp:249
ManglerKind getKind() const
Definition Mangle.h:76
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.
Definition ExprCXX.h:4974
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4999
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:5007
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5024
unsigned getManglingNumber() const
Definition ExprCXX.h:5035
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5874
Describes a module or submodule.
Definition Module.h:340
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:1079
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:885
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:426
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition Decl.cpp:1229
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
Represents a parameter to a function.
Definition Decl.h:1832
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1865
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2965
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.
Definition TypeBase.h:938
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8806
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8720
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8753
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1037
bool hasUnaligned() const
Definition TypeBase.h:512
Represents a struct/union/class.
Definition Decl.h:4506
RecordDecl * getMostRecentDecl()
Definition Decl.h:4532
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.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2042
unsigned getLength() const
Definition Expr.h:1969
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1931
StringRef getString() const
Definition Expr.h:1912
unsigned getCharByteWidth() const
Definition Expr.h:1971
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
bool isUnion() const
Definition Decl.h:4109
static const auto & getSpelling(Kind ABIKind)
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:334
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...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:9016
bool isPointerType() const
Definition TypeBase.h:8917
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9604
bool isReferenceType() const
Definition TypeBase.h:8941
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5681
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2882
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5690
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2678
bool isObjCObjectPointerType() const
Definition TypeBase.h:9100
bool isMemberFunctionPointerType() const
Definition TypeBase.h:9002
bool isSamplerT() const
Definition TypeBase.h:9165
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Expr * getSubExpr() const
Definition Expr.h:2354
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4525
const APValue & getValue() const
Definition DeclCXX.h:4551
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
TLSKind getTLSKind() const
Definition Decl.cpp:2151
bool hasInit() const
Definition Decl.cpp:2402
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2258
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2173
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
Definition Decl.cpp:2856
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2663
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2370
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2845
const Expr * getInit() const
Definition Decl.h:1393
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1240
@ TLS_None
Not a TLS variable.
Definition Decl.h:954
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1320
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1326
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2379
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1276
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2773
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
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)
Definition NVPTX.cpp:153
CIRGenCXXABI * CreateCIRGenItaniumCXXABI(CIRGenModule &cgm)
Creates and Itanium-family ABI.
std::unique_ptr< TargetCIRGenInfo > createX8664TargetCIRGenInfo(CIRGenTypes &cgt)
std::unique_ptr< TargetCIRGenInfo > createCommonSPIRTargetCIRGenInfo(CIRGenTypes &cgt)
Definition SPIRV.cpp:129
std::unique_ptr< TargetCIRGenInfo > createSystemZTargetCIRGenInfo(CIRGenTypes &cgt)
Definition SystemZ.cpp:44
std::unique_ptr< TargetCIRGenInfo > createAArch64TargetCIRGenInfo(CIRGenTypes &cgt)
Definition AArch64.cpp:68
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)
Definition Address.h:330
@ CPlusPlus
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
QualType pointeeType(QualType T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_None
Definition Specifiers.h:254
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:344
@ SD_Static
Static storage duration.
Definition Specifiers.h:345
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
LangAS
Defines the address space values used by the address space qualifier of QualType.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ CC_X86RegCall
Definition Specifiers.h:291
U cast(CodeGen::Address addr)
Definition Address.h:327
bool isExternallyVisible(Linkage L)
Definition Linkage.h:90
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
__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.
cir::PointerType allocaInt8PtrTy
void* in alloca address space
mlir::ptr::MemorySpaceAttrInterface cirAllocaAddressSpace
cir::PointerType voidPtrTy
void* in address space 0
Describes a memory access in terms of TBAA.
Definition CIRGenTBAA.h:44
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool hasSideEffects() const
Return true if the evaluated expression has side effects.
Definition Expr.h:661
Describes how types, statements, expressions, and declarations should be printed.