| 1 | //===--- CIRGenModule.h - Per-Module state for CIR gen ----------*- C++ -*-===// |
| 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 | #ifndef LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H |
| 14 | #define LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H |
| 15 | |
| 16 | #include "CIRGenBuilder.h" |
| 17 | #include "CIRGenCUDARuntime.h" |
| 18 | #include "CIRGenCall.h" |
| 19 | #include "CIRGenOpenMPRuntime.h" |
| 20 | #include "CIRGenTypeCache.h" |
| 21 | #include "CIRGenTypes.h" |
| 22 | #include "CIRGenVTables.h" |
| 23 | #include "CIRGenValue.h" |
| 24 | |
| 25 | #include "clang/AST/CharUnits.h" |
| 26 | #include "clang/CIR/Dialect/IR/CIRDataLayout.h" |
| 27 | #include "clang/CIR/Dialect/IR/CIRDialect.h" |
| 28 | |
| 29 | #include "TargetInfo.h" |
| 30 | #include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h" |
| 31 | #include "mlir/IR/Builders.h" |
| 32 | #include "mlir/IR/BuiltinOps.h" |
| 33 | #include "mlir/IR/MLIRContext.h" |
| 34 | #include "clang/AST/Decl.h" |
| 35 | #include "clang/Basic/OpenACCKinds.h" |
| 36 | #include "clang/Basic/SourceManager.h" |
| 37 | #include "clang/Basic/TargetInfo.h" |
| 38 | #include "clang/CIR/Dialect/IR/CIROpsEnums.h" |
| 39 | #include "llvm/ADT/SetVector.h" |
| 40 | #include "llvm/ADT/SmallPtrSet.h" |
| 41 | #include "llvm/ADT/StringMap.h" |
| 42 | #include "llvm/ADT/StringRef.h" |
| 43 | #include "llvm/TargetParser/Triple.h" |
| 44 | |
| 45 | namespace clang { |
| 46 | class ASTContext; |
| 47 | class CodeGenOptions; |
| 48 | class Decl; |
| 49 | class GlobalDecl; |
| 50 | class LangOptions; |
| 51 | class OpenACCConstructDecl; |
| 52 | class OpenACCDeclareDecl; |
| 53 | class OpenACCRoutineDecl; |
| 54 | class TargetInfo; |
| 55 | class VarDecl; |
| 56 | |
| 57 | namespace CIRGen { |
| 58 | |
| 59 | class CIRGenFunction; |
| 60 | class CIRGenCXXABI; |
| 61 | |
| 62 | enum ForDefinition_t : bool { NotForDefinition = false, ForDefinition = true }; |
| 63 | |
| 64 | /// This class organizes the cross-function state that is used while generating |
| 65 | /// CIR code. |
| 66 | class CIRGenModule : public CIRGenTypeCache { |
| 67 | CIRGenModule(CIRGenModule &) = delete; |
| 68 | CIRGenModule &operator=(CIRGenModule &) = delete; |
| 69 | |
| 70 | public: |
| 71 | CIRGenModule(mlir::MLIRContext &mlirContext, clang::ASTContext &astContext, |
| 72 | const clang::CodeGenOptions &cgo, |
| 73 | clang::DiagnosticsEngine &diags); |
| 74 | |
| 75 | ~CIRGenModule(); |
| 76 | |
| 77 | private: |
| 78 | mutable std::unique_ptr<TargetCIRGenInfo> theTargetCIRGenInfo; |
| 79 | |
| 80 | CIRGenBuilderTy builder; |
| 81 | |
| 82 | /// Hold Clang AST information. |
| 83 | clang::ASTContext &astContext; |
| 84 | |
| 85 | const clang::LangOptions &langOpts; |
| 86 | |
| 87 | /// Seeded from langOpts and then pushed and popped by clang::atomic. |
| 88 | clang::AtomicOptions atomicOpts; |
| 89 | |
| 90 | const clang::CodeGenOptions &codeGenOpts; |
| 91 | |
| 92 | /// A "module" matches a c/cpp source file: containing a list of functions. |
| 93 | mlir::OwningOpRef<mlir::ModuleOp> theModule; |
| 94 | |
| 95 | /// Cached data layout for the module. Built lazily: the layout spec is |
| 96 | /// attached after construction, in CIRGenerator::Initialize. |
| 97 | mutable std::optional<cir::CIRDataLayout> dataLayout; |
| 98 | |
| 99 | clang::DiagnosticsEngine &diags; |
| 100 | |
| 101 | const clang::TargetInfo ⌖ |
| 102 | |
| 103 | std::unique_ptr<CIRGenCXXABI> abi; |
| 104 | |
| 105 | CIRGenTypes genTypes; |
| 106 | |
| 107 | /// Holds information about C++ vtables. |
| 108 | CIRGenVTables vtables; |
| 109 | |
| 110 | /// Holds the CUDA runtime |
| 111 | std::unique_ptr<CIRGenCUDARuntime> cudaRuntime; |
| 112 | |
| 113 | /// Holds the OpenMP runtime |
| 114 | std::unique_ptr<CIRGenOpenMPRuntime> openMPRuntime; |
| 115 | |
| 116 | /// Per-function codegen information. Updated everytime emitCIR is called |
| 117 | /// for FunctionDecls's. |
| 118 | CIRGenFunction *curCGF = nullptr; |
| 119 | |
| 120 | llvm::SmallVector<mlir::Attribute> globalScopeAsm; |
| 121 | |
| 122 | /// Accumulated record layout entries, materialized in release(). |
| 123 | llvm::SmallVector<mlir::NamedAttribute> recordLayoutEntries; |
| 124 | |
| 125 | /// Whether C++20 named modules get their own module initializer function, |
| 126 | /// which requires the Itanium mangling of the initializer name. |
| 127 | bool cxx20ModuleInits = false; |
| 128 | |
| 129 | /// The complete set of modules that have been imported. |
| 130 | llvm::SetVector<clang::Module *> importedModules; |
| 131 | |
| 132 | /// The location of the first import declaration of each imported module. |
| 133 | llvm::DenseMap<clang::Module *, clang::SourceLocation> moduleImportLocs; |
| 134 | |
| 135 | /// The set of modules for which the module initializers have been emitted. |
| 136 | llvm::SmallPtrSet<clang::Module *, 16> emittedModuleInitializers; |
| 137 | |
| 138 | /// The Itanium-mangled name of the initializer function of a C++20 named |
| 139 | /// module. |
| 140 | std::string getModuleInitializerName(clang::Module *mod); |
| 141 | |
| 142 | llvm::DenseSet<clang::GlobalDecl> diagnosedConflictingDefinitions; |
| 143 | |
| 144 | /// Symbols created as the target of a weakref. They are extern_weak until |
| 145 | /// something names them in a way that is not itself weak, such as an |
| 146 | /// ordinary declaration or definition of the target. |
| 147 | llvm::SmallPtrSet<mlir::Operation *, 4> weakRefReferences; |
| 148 | |
| 149 | /// ------- |
| 150 | /// Annotations |
| 151 | /// ------- |
| 152 | |
| 153 | /// We store each annotation as an attribute of GlobalOp and FuncOp rather |
| 154 | /// than collecting them into a single module-level list. The deferred map |
| 155 | /// lets us attach annotations at the end of codegen so the most up-to-date |
| 156 | /// ValueDecl (which carries all inherited annotations) is used. |
| 157 | |
| 158 | /// Used for uniquing of annotation arguments. |
| 159 | llvm::DenseMap<unsigned, mlir::ArrayAttr> annotationArgs; |
| 160 | |
| 161 | /// Store deferred function annotations so they can be emitted at the end |
| 162 | /// with the most up to date ValueDecl that will have all the inherited |
| 163 | /// annotations. |
| 164 | llvm::DenseMap<llvm::StringRef, const clang::ValueDecl *> deferredAnnotations; |
| 165 | |
| 166 | /// A queue of (optional) vtables to consider emitting. |
| 167 | std::vector<const CXXRecordDecl *> deferredVTables; |
| 168 | |
| 169 | /// A queue of (optional) vtables that may be emitted opportunistically. |
| 170 | std::vector<const CXXRecordDecl *> opportunisticVTables; |
| 171 | |
| 172 | void createCUDARuntime(); |
| 173 | void createOpenMPRuntime(); |
| 174 | void setOpenCLVersionAttr(llvm::StringRef attrName, unsigned version); |
| 175 | |
| 176 | /// A helper for constructAttributeList that handles return attributes. |
| 177 | void constructFunctionReturnAttributes(const CIRGenFunctionInfo &info, |
| 178 | const Decl *targetDecl, bool isThunk, |
| 179 | mlir::NamedAttrList &retAttrs); |
| 180 | /// A helper for constructAttributeList that handles argument attributes. |
| 181 | void constructFunctionArgumentAttributes( |
| 182 | const CIRGenFunctionInfo &info, clang::GlobalDecl calleeDecl, |
| 183 | bool isThunk, bool attrOnCallSite, |
| 184 | llvm::MutableArrayRef<mlir::NamedAttrList> argAttrs); |
| 185 | /// A helper function for constructAttributeList that determines whether a |
| 186 | /// return value might have been discarded. |
| 187 | bool mayDropFunctionReturn(const ASTContext &context, QualType retTy); |
| 188 | /// A helper function for constructAttributeList that determines whether |
| 189 | /// `noundef` on a return is possible. |
| 190 | bool hasStrictReturn(QualType retTy, const Decl *targetDecl); |
| 191 | |
| 192 | llvm::DenseMap<const Expr *, mlir::Operation *> |
| 193 | materializedGlobalTemporaryMap; |
| 194 | |
| 195 | public: |
| 196 | mlir::ModuleOp getModule() const { return *theModule; } |
| 197 | CIRGenBuilderTy &getBuilder() { return builder; } |
| 198 | |
| 199 | /// Queue a record layout entry for materialization in release(). |
| 200 | void addRecordLayout(mlir::StringAttr name, cir::RecordLayoutAttr attr) { |
| 201 | recordLayoutEntries.push_back(Elt: mlir::NamedAttribute(name, attr)); |
| 202 | } |
| 203 | clang::ASTContext &getASTContext() const { return astContext; } |
| 204 | const clang::TargetInfo &getTarget() const { return target; } |
| 205 | const clang::CodeGenOptions &getCodeGenOpts() const { return codeGenOpts; } |
| 206 | clang::DiagnosticsEngine &getDiags() const { return diags; } |
| 207 | CIRGenTypes &getTypes() { return genTypes; } |
| 208 | const clang::LangOptions &getLangOpts() const { return langOpts; } |
| 209 | |
| 210 | /// The atomic options in effect at the point currently being emitted. |
| 211 | /// clang::atomic adjusts these for the extent of the statement it is attached |
| 212 | /// to, so they are module state rather than a fixed language option. |
| 213 | clang::AtomicOptions getAtomicOpts() const { return atomicOpts; } |
| 214 | void setAtomicOpts(clang::AtomicOptions opts) { atomicOpts = opts; } |
| 215 | |
| 216 | CIRGenCXXABI &getCXXABI() const { return *abi; } |
| 217 | mlir::MLIRContext &getMLIRContext() { return *builder.getContext(); } |
| 218 | |
| 219 | const cir::CIRDataLayout &getDataLayout() const { |
| 220 | if (!dataLayout) |
| 221 | dataLayout.emplace(args: getModule()); |
| 222 | return *dataLayout; |
| 223 | } |
| 224 | |
| 225 | /// ------- |
| 226 | /// Handling globals |
| 227 | /// ------- |
| 228 | |
| 229 | mlir::Operation *lastGlobalOp = nullptr; |
| 230 | |
| 231 | /// Keep a map between lambda fields and names, this needs to be per module |
| 232 | /// since lambdas might get generated later as part of defered work, and since |
| 233 | /// the pointers are supposed to be uniqued, should be fine. Revisit this if |
| 234 | /// it ends up taking too much memory. |
| 235 | llvm::DenseMap<const clang::FieldDecl *, llvm::StringRef> lambdaFieldToName; |
| 236 | |
| 237 | /// Add a global value to the llvmUsed list. |
| 238 | void addUsedGlobal(cir::CIRGlobalValueInterface gv); |
| 239 | |
| 240 | /// Add a global value to the llvmCompilerUsed list. |
| 241 | void addCompilerUsedGlobal(cir::CIRGlobalValueInterface gv); |
| 242 | |
| 243 | /// Add a global to a list to be added to the llvm.compiler.used metadata. |
| 244 | void addUsedOrCompilerUsedGlobal(cir::CIRGlobalValueInterface gv); |
| 245 | |
| 246 | /// Emit llvm.used and llvm.compiler.used globals. |
| 247 | void emitLLVMUsed(); |
| 248 | |
| 249 | /// Tell the consumer that this variable has been instantiated. |
| 250 | void handleCXXStaticMemberVarInstantiation(VarDecl *vd); |
| 251 | |
| 252 | llvm::DenseMap<const Decl *, cir::GlobalOp> staticLocalDeclMap; |
| 253 | llvm::DenseMap<const VarDecl *, cir::GlobalOp> initializerConstants; |
| 254 | |
| 255 | /// Cache for O(1) symbol lookups by name, replacing the O(N) linear scan |
| 256 | /// in SymbolTable::lookupSymbolIn that getGlobalValue used previously. |
| 257 | llvm::StringMap<mlir::Operation *> symbolLookupCache; |
| 258 | |
| 259 | mlir::Operation *getGlobalValue(llvm::StringRef ref); |
| 260 | |
| 261 | /// O(1) lookup of a FuncOp by name in the symbol cache. |
| 262 | /// Returns nullptr if the name is not found or is not a FuncOp. |
| 263 | cir::FuncOp lookupFuncOp(llvm::StringRef name) { |
| 264 | auto *op = getGlobalValue(ref: name); |
| 265 | return op ? mlir::dyn_cast<cir::FuncOp>(Val: op) : cir::FuncOp{}; |
| 266 | } |
| 267 | |
| 268 | void insertGlobalSymbol(mlir::Operation *op) { |
| 269 | if (auto sym = mlir::dyn_cast<mlir::SymbolOpInterface>(Val: op)) |
| 270 | symbolLookupCache[sym.getName()] = op; |
| 271 | } |
| 272 | void eraseGlobalSymbol(mlir::Operation *op) { |
| 273 | if (auto sym = mlir::dyn_cast<mlir::SymbolOpInterface>(Val: op)) { |
| 274 | auto it = symbolLookupCache.find(Key: sym.getName()); |
| 275 | if (it != symbolLookupCache.end() && it->second == op) |
| 276 | symbolLookupCache.erase(I: it); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | cir::GlobalOp getStaticLocalDeclAddress(const VarDecl *d) { |
| 281 | return staticLocalDeclMap[d]; |
| 282 | } |
| 283 | |
| 284 | void setStaticLocalDeclAddress(const VarDecl *d, cir::GlobalOp c) { |
| 285 | staticLocalDeclMap[d] = c; |
| 286 | } |
| 287 | |
| 288 | cir::GlobalOp getOrCreateStaticVarDecl(const VarDecl &d, |
| 289 | cir::GlobalLinkageKind linkage); |
| 290 | |
| 291 | Address createUnnamedGlobalFrom(const VarDecl &d, mlir::Attribute constAttr, |
| 292 | CharUnits align); |
| 293 | |
| 294 | /// If the specified mangled name is not in the module, create and return an |
| 295 | /// mlir::GlobalOp value |
| 296 | cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty, |
| 297 | LangAS langAS, mlir::Location loc, |
| 298 | const VarDecl *d, |
| 299 | ForDefinition_t isForDefinition); |
| 300 | |
| 301 | cir::GlobalOp getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty, |
| 302 | ForDefinition_t isForDefinition); |
| 303 | |
| 304 | /// Return the symbol that a weakref declaration refers to: the cir.func or |
| 305 | /// cir.global named by its alias target, declared extern_weak if it did not |
| 306 | /// already exist. |
| 307 | mlir::Operation *getWeakRefReference(const clang::ValueDecl *vd); |
| 308 | |
| 309 | cir::GlobalOp |
| 310 | createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t, |
| 311 | bool isConstant = false, |
| 312 | mlir::ptr::MemorySpaceAttrInterface addrSpace = {}, |
| 313 | mlir::Operation *insertPoint = nullptr); |
| 314 | |
| 315 | /// Add a global constructor or destructor to the module. |
| 316 | /// The priority is optional, if not specified, the default priority is used. |
| 317 | void addGlobalCtor(cir::FuncOp ctor, |
| 318 | std::optional<int> priority = std::nullopt); |
| 319 | void addGlobalDtor(cir::FuncOp dtor, |
| 320 | std::optional<int> priority = std::nullopt); |
| 321 | |
| 322 | bool shouldZeroInitPadding() const { |
| 323 | // In C23 (N3096) $6.7.10: |
| 324 | // """ |
| 325 | // If any object is initialized with an empty initializer, then it is |
| 326 | // subject to default initialization: |
| 327 | // - if it is an aggregate, every member is initialized (recursively) |
| 328 | // according to these rules, and any padding is initialized to zero bits; |
| 329 | // - if it is a union, the first named member is initialized (recursively) |
| 330 | // according to these rules, and any padding is initialized to zero bits. |
| 331 | // |
| 332 | // If the aggregate or union contains elements or members that are |
| 333 | // aggregates or unions, these rules apply recursively to the subaggregates |
| 334 | // or contained unions. |
| 335 | // |
| 336 | // If there are fewer initializers in a brace-enclosed list than there are |
| 337 | // elements or members of an aggregate, or fewer characters in a string |
| 338 | // literal used to initialize an array of known size than there are elements |
| 339 | // in the array, the remainder of the aggregate is subject to default |
| 340 | // initialization. |
| 341 | // """ |
| 342 | // |
| 343 | // The standard seems ambiguous in the following two areas: |
| 344 | // 1. For a union type with empty initializer, if the first named member is |
| 345 | // not the largest member, then the bytes comes after the first named member |
| 346 | // but before padding are left unspecified. An example is: |
| 347 | // union U { int a; long long b;}; |
| 348 | // union U u = {}; // The first 4 bytes are 0, but 4-8 bytes are left |
| 349 | // unspecified. |
| 350 | // |
| 351 | // 2. It only mentions padding for empty initializer, but doesn't mention |
| 352 | // padding for a non empty initialization list. And if the aggregation or |
| 353 | // union contains elements or members that are aggregates or unions, and |
| 354 | // some are non empty initializers, while others are empty initializers, |
| 355 | // the padding initialization is unclear. An example is: |
| 356 | // struct S1 { int a; long long b; }; |
| 357 | // struct S2 { char c; struct S1 s1; }; |
| 358 | // // The values for paddings between s2.c and s2.s1.a, between s2.s1.a |
| 359 | // and s2.s1.b are unclear. |
| 360 | // struct S2 s2 = { 'c' }; |
| 361 | // |
| 362 | // Here we choose to zero initiailize left bytes of a union type because |
| 363 | // projects like the Linux kernel are relying on this behavior. If we don't |
| 364 | // explicitly zero initialize them, the undef values can be optimized to |
| 365 | // return garbage data. We also choose to zero initialize paddings for |
| 366 | // aggregates and unions, no matter they are initialized by empty |
| 367 | // initializers or non empty initializers. This can provide a consistent |
| 368 | // behavior. So projects like the Linux kernel can rely on it. |
| 369 | return !getLangOpts().CPlusPlus; |
| 370 | } |
| 371 | |
| 372 | llvm::StringMap<unsigned> cgGlobalNames; |
| 373 | std::string getUniqueGlobalName(const std::string &baseName); |
| 374 | |
| 375 | /// Return the mlir::Value for the address of the given global variable. |
| 376 | /// If Ty is non-null and if the global doesn't exist, then it will be created |
| 377 | /// with the specified type instead of whatever the normal requested type |
| 378 | /// would be. If IsForDefinition is true, it is guaranteed that an actual |
| 379 | /// global with type Ty will be returned, not conversion of a variable with |
| 380 | /// the same mangled name but some other type. |
| 381 | mlir::Value |
| 382 | getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty = {}, |
| 383 | ForDefinition_t isForDefinition = NotForDefinition); |
| 384 | |
| 385 | /// Cast \p addr, the address of the global \p vd, to the address space of |
| 386 | /// the declared type of \p vd if they differ. |
| 387 | mlir::Value castGlobalToDeclAddrSpace(mlir::Value addr, const VarDecl &vd); |
| 388 | |
| 389 | /// Get or create a thunk function with the given name and type. |
| 390 | cir::FuncOp getAddrOfThunk(StringRef name, mlir::Type fnTy, GlobalDecl gd); |
| 391 | |
| 392 | /// Return the mlir::GlobalViewAttr for the address of the given global. |
| 393 | cir::GlobalViewAttr getAddrOfGlobalVarAttr(const VarDecl *d); |
| 394 | |
| 395 | /// Get the GlobalOp of a template parameter object. |
| 396 | cir::GlobalOp |
| 397 | getAddrOfTemplateParamObject(const TemplateParamObjectDecl *tpo); |
| 398 | // Get the GlobalOp of a source_location object. |
| 399 | cir::GlobalOp |
| 400 | getAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *gcd); |
| 401 | |
| 402 | CharUnits computeNonVirtualBaseClassOffset( |
| 403 | const CXXRecordDecl *derivedClass, |
| 404 | llvm::iterator_range<CastExpr::path_const_iterator> path); |
| 405 | |
| 406 | /// Get the CIR attributes and calling convention to use for a particular |
| 407 | /// function type. |
| 408 | /// |
| 409 | /// \param name - The function name. |
| 410 | /// \param info - The function type information. |
| 411 | /// \param calleeInfo - The callee information these attributes are being |
| 412 | /// constructed for. If valid, the attributes applied to this decl may |
| 413 | /// contribute to the function attributes and calling convention. |
| 414 | /// \param attrs [out] - On return, the attribute list to use. |
| 415 | /// \param callingConv [out] - On return, the calling convention to use. |
| 416 | /// \param attrOnCallSite - Whether or not the attributes are on a call site. |
| 417 | /// \param isThunk - Whether the function is a thunk. |
| 418 | void constructAttributeList( |
| 419 | llvm::StringRef name, const CIRGenFunctionInfo &info, |
| 420 | CIRGenCalleeInfo calleeInfo, mlir::NamedAttrList &attrs, |
| 421 | llvm::MutableArrayRef<mlir::NamedAttrList> argAttrs, |
| 422 | mlir::NamedAttrList &retAttrs, cir::CallingConv &callingConv, |
| 423 | bool attrOnCallSite, bool isThunk); |
| 424 | /// Helper function for constructAttributeList/others. Builds a set of |
| 425 | /// function attributes to add to a function based on language opts, codegen |
| 426 | /// opts, and some small properties. |
| 427 | void addDefaultFunctionAttributes(StringRef name, bool hasOptNoneAttr, |
| 428 | bool attrOnCallSite, |
| 429 | mlir::NamedAttrList &attrs); |
| 430 | |
| 431 | /// Returns the frame pointer kind to record on functions and on the module, |
| 432 | /// or std::nullopt when \p kind is CodeGenOptions::FramePointerKind::None, |
| 433 | /// the default, which is left implicit. |
| 434 | static std::optional<cir::FramePointerKind> |
| 435 | getFramePointerKind(CodeGenOptions::FramePointerKind kind); |
| 436 | |
| 437 | /// Will return a global variable of the given type. If a variable with a |
| 438 | /// different type already exists then a new variable with the right type |
| 439 | /// will be created and all uses of the old variable will be replaced with a |
| 440 | /// bitcast to the new variable. |
| 441 | cir::GlobalOp createOrReplaceCXXRuntimeVariable( |
| 442 | mlir::Location loc, llvm::StringRef name, mlir::Type ty, |
| 443 | cir::GlobalLinkageKind linkage, clang::CharUnits alignment); |
| 444 | |
| 445 | void emitVTable(const CXXRecordDecl *rd); |
| 446 | |
| 447 | /// Return the appropriate linkage for the vtable, VTT, and type information |
| 448 | /// of the given class. |
| 449 | cir::GlobalLinkageKind getVTableLinkage(const CXXRecordDecl *rd); |
| 450 | |
| 451 | /// Get the address of the RTTI descriptor for the given type. |
| 452 | mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty, |
| 453 | bool forEH = false); |
| 454 | |
| 455 | static cir::VisibilityKind getCIRVisibilityKind(Visibility v) { |
| 456 | switch (v) { |
| 457 | case DefaultVisibility: |
| 458 | return cir::VisibilityKind::Default; |
| 459 | case HiddenVisibility: |
| 460 | return cir::VisibilityKind::Hidden; |
| 461 | case ProtectedVisibility: |
| 462 | return cir::VisibilityKind::Protected; |
| 463 | } |
| 464 | |
| 465 | llvm_unreachable("unknown visibility!" ); |
| 466 | } |
| 467 | |
| 468 | llvm::DenseMap<mlir::Attribute, cir::GlobalOp> constantStringMap; |
| 469 | llvm::DenseMap<const UnnamedGlobalConstantDecl *, cir::GlobalOp> |
| 470 | unnamedGlobalConstantDeclMap; |
| 471 | llvm::DenseMap<const CompoundLiteralExpr *, cir::GlobalOp> |
| 472 | emittedCompoundLiterals; |
| 473 | |
| 474 | cir::GlobalOp |
| 475 | getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *e) { |
| 476 | return emittedCompoundLiterals.lookup(Val: e); |
| 477 | } |
| 478 | void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *e, |
| 479 | cir::GlobalOp gv) { |
| 480 | [[maybe_unused]] bool ok = emittedCompoundLiterals.insert(KV: {e, gv}).second; |
| 481 | assert(ok && "compound literal global already emitted" ); |
| 482 | } |
| 483 | |
| 484 | /// Return a constant array for the given string. |
| 485 | mlir::Attribute getConstantArrayFromStringLiteral(const StringLiteral *e); |
| 486 | |
| 487 | /// Return a global symbol reference to a constant array for the given string |
| 488 | /// literal. |
| 489 | cir::GlobalOp getGlobalForStringLiteral(const StringLiteral *s, |
| 490 | llvm::StringRef name = ".str" ); |
| 491 | |
| 492 | /// Return a global symbol reference to a constant array for the given string |
| 493 | /// literal. |
| 494 | cir::GlobalViewAttr |
| 495 | getAddrOfConstantStringFromLiteral(const StringLiteral *s, |
| 496 | llvm::StringRef name = ".str" ); |
| 497 | |
| 498 | /// Create a private constant global holding the null-terminated string |
| 499 | /// \p str, mirroring llvm::IRBuilder::CreateGlobalString. |
| 500 | cir::GlobalOp createGlobalString(mlir::Location loc, llvm::StringRef str, |
| 501 | llvm::StringRef name); |
| 502 | |
| 503 | /// Returns the address space for temporary allocations in the language. This |
| 504 | /// ensures that the allocated variable's address space matches the |
| 505 | /// expectations of the AST, rather than using the target's allocation address |
| 506 | /// space, which may lead to type mismatches in other parts of the IR. |
| 507 | LangAS getLangTempAllocaAddressSpace() const; |
| 508 | |
| 509 | /// Return the AST address space of the underlying global variable for D, as |
| 510 | /// determined by its declaration. Normally this is the same as the address |
| 511 | /// space of D's type, but in CUDA, address spaces are associated with |
| 512 | /// declarations, not types. If D is nullptr, return the default address |
| 513 | /// space for global variable. |
| 514 | /// |
| 515 | /// For languages without explicit address spaces, if D has default address |
| 516 | /// space, target-specific global or constant address space may be returned. |
| 517 | LangAS getGlobalVarAddressSpace(const VarDecl *decl); |
| 518 | |
| 519 | /// Return the CIR address space attribute for a global in \p as, honoring |
| 520 | /// the target address space map where the LangAS fold would lose it. |
| 521 | mlir::ptr::MemorySpaceAttrInterface getGlobalCIRAddressSpace(LangAS as); |
| 522 | |
| 523 | /// Set attributes which are common to any form of a global definition (alias, |
| 524 | /// Objective-C method, function, global variable). |
| 525 | /// |
| 526 | /// NOTE: This should only be called for definitions. |
| 527 | void setCommonAttributes(GlobalDecl gd, mlir::Operation *op); |
| 528 | |
| 529 | const TargetCIRGenInfo &getTargetCIRGenInfo(); |
| 530 | |
| 531 | /// Helpers to convert the presumed location of Clang's SourceLocation to an |
| 532 | /// MLIR Location. |
| 533 | mlir::Location getLoc(clang::SourceLocation cLoc); |
| 534 | mlir::Location getLoc(clang::SourceRange cRange); |
| 535 | |
| 536 | /// Return the best known alignment for an unknown pointer to a |
| 537 | /// particular class. |
| 538 | clang::CharUnits getClassPointerAlignment(const clang::CXXRecordDecl *rd); |
| 539 | |
| 540 | /// FIXME: this could likely be a common helper and not necessarily related |
| 541 | /// with codegen. |
| 542 | clang::CharUnits getNaturalTypeAlignment(clang::QualType t, |
| 543 | LValueBaseInfo *baseInfo = nullptr, |
| 544 | bool forPointeeType = false); |
| 545 | clang::CharUnits |
| 546 | getNaturalPointeeTypeAlignment(clang::QualType t, |
| 547 | LValueBaseInfo *baseInfo = nullptr); |
| 548 | |
| 549 | /// Returns the minimum object size for an object of the given class type |
| 550 | /// (or a class derived from it). |
| 551 | CharUnits getMinimumClassObjectSize(const CXXRecordDecl *cd); |
| 552 | |
| 553 | /// Returns the minimum object size for an object of the given type. |
| 554 | CharUnits getMinimumObjectSize(QualType ty) { |
| 555 | if (CXXRecordDecl *rd = ty->getAsCXXRecordDecl()) |
| 556 | return getMinimumClassObjectSize(cd: rd); |
| 557 | return getASTContext().getTypeSizeInChars(T: ty); |
| 558 | } |
| 559 | |
| 560 | /// TODO: Add TBAAAccessInfo |
| 561 | CharUnits getDynamicOffsetAlignment(CharUnits actualBaseAlign, |
| 562 | const CXXRecordDecl *baseDecl, |
| 563 | CharUnits expectedTargetAlign); |
| 564 | |
| 565 | /// Returns the assumed alignment of a virtual base of a class. |
| 566 | CharUnits getVBaseAlignment(CharUnits derivedAlign, |
| 567 | const CXXRecordDecl *derived, |
| 568 | const CXXRecordDecl *vbase); |
| 569 | |
| 570 | cir::FuncOp |
| 571 | getAddrOfCXXStructor(clang::GlobalDecl gd, |
| 572 | const CIRGenFunctionInfo *fnInfo = nullptr, |
| 573 | cir::FuncType fnType = nullptr, bool dontDefer = false, |
| 574 | ForDefinition_t isForDefinition = NotForDefinition) { |
| 575 | return getAddrAndTypeOfCXXStructor(gd, fnInfo, fnType, dontDefer, |
| 576 | isForDefinition) |
| 577 | .second; |
| 578 | } |
| 579 | |
| 580 | std::pair<cir::FuncType, cir::FuncOp> getAddrAndTypeOfCXXStructor( |
| 581 | clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo = nullptr, |
| 582 | cir::FuncType fnType = nullptr, bool dontDefer = false, |
| 583 | ForDefinition_t isForDefinition = NotForDefinition); |
| 584 | |
| 585 | /// List of global values which are required to be present in the object file; |
| 586 | /// This is used for forcing visibility of symbols which may otherwise be |
| 587 | /// optimized out. |
| 588 | std::vector<cir::CIRGlobalValueInterface> llvmUsed; |
| 589 | std::vector<cir::CIRGlobalValueInterface> llvmCompilerUsed; |
| 590 | |
| 591 | mlir::Type getVTableComponentType(); |
| 592 | CIRGenVTables &getVTables() { return vtables; } |
| 593 | |
| 594 | ItaniumVTableContext &getItaniumVTableContext() { |
| 595 | return vtables.getItaniumVTableContext(); |
| 596 | } |
| 597 | const ItaniumVTableContext &getItaniumVTableContext() const { |
| 598 | return vtables.getItaniumVTableContext(); |
| 599 | } |
| 600 | |
| 601 | /// This contains all the decls which have definitions but which are deferred |
| 602 | /// for emission and therefore should only be output if they are actually |
| 603 | /// used. If a decl is in this, then it is known to have not been referenced |
| 604 | /// yet. |
| 605 | std::map<llvm::StringRef, clang::GlobalDecl> deferredDecls; |
| 606 | |
| 607 | // This is a list of deferred decls which we have seen that *are* actually |
| 608 | // referenced. These get code generated when the module is done. |
| 609 | std::vector<clang::GlobalDecl> deferredDeclsToEmit; |
| 610 | void addDeferredDeclToEmit(clang::GlobalDecl GD) { |
| 611 | deferredDeclsToEmit.emplace_back(args&: GD); |
| 612 | } |
| 613 | |
| 614 | void emitTopLevelDecl(clang::Decl *decl); |
| 615 | |
| 616 | /// Determine whether the definition must be emitted; if this returns \c |
| 617 | /// false, the definition can be emitted lazily if it's used. |
| 618 | bool mustBeEmitted(const clang::ValueDecl *d); |
| 619 | |
| 620 | /// Check if `fd` ends up calling itself directly through asm label or |
| 621 | /// builtin-pointer-to-self trickery (e.g., glibc's `extern inline` libc |
| 622 | /// wrappers that call `__builtin_strrchr`, which the codegen lowers to a |
| 623 | /// call on the same asm-named symbol). Emitting an |
| 624 | /// `available_externally` body for such a function feeds the LLVM |
| 625 | /// Decide whether to emit the body of `gd` to CIR. Returns false for |
| 626 | /// available_externally functions that are trivially recursive (PR9614). |
| 627 | /// Mirrors classic CodeGen's `CodeGenModule::shouldEmitFunction`. |
| 628 | bool shouldEmitFunction(clang::GlobalDecl gd); |
| 629 | |
| 630 | /// Determine whether the definition can be emitted eagerly, or should be |
| 631 | /// delayed until the end of the translation unit. This is relevant for |
| 632 | /// definitions whose linkage can change, e.g. implicit function |
| 633 | /// instantiations which may later be explicitly instantiated. |
| 634 | bool mayBeEmittedEagerly(const clang::ValueDecl *d); |
| 635 | |
| 636 | bool verifyModule() const; |
| 637 | |
| 638 | /// Return the address of the given function. If funcType is non-null, then |
| 639 | /// this function will use the specified type if it has to create it. |
| 640 | // TODO: this is a bit weird as `GetAddr` given we give back a FuncOp? |
| 641 | cir::FuncOp |
| 642 | getAddrOfFunction(clang::GlobalDecl gd, mlir::Type funcType = nullptr, |
| 643 | bool forVTable = false, bool dontDefer = false, |
| 644 | ForDefinition_t isForDefinition = NotForDefinition); |
| 645 | |
| 646 | mlir::Operation * |
| 647 | getAddrOfGlobal(clang::GlobalDecl gd, |
| 648 | ForDefinition_t isForDefinition = NotForDefinition); |
| 649 | |
| 650 | /// Return a function pointer for a reference to the given function. |
| 651 | /// This correctly handles weak references, but does not apply a |
| 652 | /// pointer signature. |
| 653 | cir::FuncOp getRawFunctionPointer(GlobalDecl GD); |
| 654 | |
| 655 | /// Return the ABI-correct function pointer value for a reference |
| 656 | /// to the given function. This will apply a pointer signature if |
| 657 | /// necessary, caching the result for the given function. |
| 658 | cir::FuncOp getFunctionPointer(GlobalDecl GD); |
| 659 | |
| 660 | /// Return true if a vtable with the given linkage may have more than one |
| 661 | /// address in the program, in which case its address is insignificant and it |
| 662 | /// can be marked unnamed_addr. |
| 663 | bool mayVTableBeDuplicated(cir::GlobalLinkageKind linkage) const; |
| 664 | |
| 665 | // Return whether RTTI information should be emitted for this target. |
| 666 | bool shouldEmitRTTI(bool forEH = false) { |
| 667 | return (forEH || getLangOpts().RTTI) && |
| 668 | (!getLangOpts().isTargetDevice() || !getTriple().isGPU()); |
| 669 | } |
| 670 | |
| 671 | /// Emit type info if type of an expression is a variably modified |
| 672 | /// type. Also emit proper debug info for cast types. |
| 673 | void emitExplicitCastExprType(const ExplicitCastExpr *e, |
| 674 | CIRGenFunction *cgf = nullptr); |
| 675 | |
| 676 | void addDeferredVTable(const CXXRecordDecl *rd) { |
| 677 | deferredVTables.push_back(x: rd); |
| 678 | } |
| 679 | |
| 680 | /// Emit code for a single global function or variable declaration. Forward |
| 681 | /// declarations are emitted lazily. |
| 682 | void emitGlobal(clang::GlobalDecl gd); |
| 683 | |
| 684 | /// Emit `aliasGD` as an alias of `aliasee`, replacing any existing |
| 685 | /// declaration `op`, and return the alias. |
| 686 | cir::FuncOp emitAliasForGlobal(llvm::StringRef mangledName, |
| 687 | mlir::Operation *op, GlobalDecl aliasGD, |
| 688 | cir::FuncOp aliasee, |
| 689 | cir::GlobalLinkageKind linkage); |
| 690 | |
| 691 | /// Emit a definition for an `__attribute__((alias))` declaration. |
| 692 | void emitAliasDefinition(GlobalDecl gd); |
| 693 | |
| 694 | mlir::Type convertType(clang::QualType type); |
| 695 | |
| 696 | /// Set the visibility for the given global. |
| 697 | void setGlobalVisibility(cir::CIRGlobalValueInterface gv, |
| 698 | const NamedDecl *d) const; |
| 699 | void setDSOLocal(mlir::Operation *op) const; |
| 700 | void setDSOLocal(cir::CIRGlobalValueInterface gv) const; |
| 701 | |
| 702 | /// Set visibility, dllimport/dllexport and dso_local. |
| 703 | /// This must be called after dllimport/dllexport is set. |
| 704 | void setGVProperties(mlir::Operation *op, const NamedDecl *d) const; |
| 705 | void setGVPropertiesAux(mlir::Operation *op, const NamedDecl *d) const; |
| 706 | |
| 707 | /// Set TLS mode for the given operation based on the given variable |
| 708 | /// declaration. If `isExtendingDecl` is true, then the operation is a |
| 709 | /// temporary whose lifetime is extended by the variable declared by `d`. |
| 710 | void setTLSMode(mlir::Operation *op, const VarDecl &d, |
| 711 | bool isExtendingDecl = false); |
| 712 | |
| 713 | /// Get TLS mode from CodeGenOptions. |
| 714 | cir::TLSModel getDefaultCIRTLSModel() const; |
| 715 | |
| 716 | /// Set function attributes for a function declaration. |
| 717 | void setFunctionAttributes(GlobalDecl gd, cir::FuncOp f, |
| 718 | bool isIncompleteFunction, bool isThunk); |
| 719 | |
| 720 | /// Set the CIR function attributes (Sext, zext, etc). |
| 721 | void setCIRFunctionAttributes(GlobalDecl gd, const CIRGenFunctionInfo &info, |
| 722 | cir::FuncOp func, bool isThunk); |
| 723 | |
| 724 | /// Set extra attributes (inline, etc.) for a function. |
| 725 | void setCIRFunctionAttributesForDefinition(const clang::Decl *decl, |
| 726 | cir::FuncOp f); |
| 727 | |
| 728 | /// Generate OpenCL kernel argument metadata for a kernel function. |
| 729 | void emitOpenCLKernelArgMetadata(cir::FuncOp func, |
| 730 | const clang::FunctionDecl *fd); |
| 731 | |
| 732 | void emitGlobalDefinition(clang::GlobalDecl gd, |
| 733 | mlir::Operation *op = nullptr); |
| 734 | void emitGlobalFunctionDefinition(clang::GlobalDecl gd, mlir::Operation *op); |
| 735 | |
| 736 | /// Emit the SYCL kernel caller offload entry point function generated for a |
| 737 | /// function declared with the sycl_kernel_entry_point attribute. |
| 738 | void emitSYCLKernelCaller(const clang::FunctionDecl *kernelEntryPointFn, |
| 739 | clang::ASTContext &ctx); |
| 740 | |
| 741 | void addSYCLModuleIdAttr(cir::FuncOp fn); |
| 742 | void emitGlobalVarDefinition(const clang::VarDecl *vd, |
| 743 | bool isTentative = false); |
| 744 | |
| 745 | /// Helper function for the below two that will create the |
| 746 | /// constructor/destructor in specified regions, rather than in the GlobalOp. |
| 747 | void emitCXXSpecialVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr, |
| 748 | bool performInit, mlir::Region &ctorRegion, |
| 749 | mlir::Region &dtorRegion); |
| 750 | /// Emit the function that initializes the specified static-local variable. |
| 751 | void emitCXXStaticLocalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr, |
| 752 | bool performInit); |
| 753 | /// Emit the function that initializes the specified global |
| 754 | void emitCXXGlobalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr, |
| 755 | bool performInit); |
| 756 | |
| 757 | void setGlobalTlsReferences(const VarDecl &vd, cir::GlobalOp globalOp); |
| 758 | void emitCXXGlobalVarDeclInitFunc(const VarDecl *vd, cir::GlobalOp addr, |
| 759 | bool performInit); |
| 760 | |
| 761 | void emitGlobalOpenACCDecl(const clang::OpenACCConstructDecl *cd); |
| 762 | void emitGlobalOpenACCRoutineDecl(const clang::OpenACCRoutineDecl *cd); |
| 763 | void emitGlobalOpenACCDeclareDecl(const clang::OpenACCDeclareDecl *cd); |
| 764 | template <typename BeforeOpTy, typename DataClauseTy> |
| 765 | void emitGlobalOpenACCDeclareDataOperands(const Expr *varOperand, |
| 766 | DataClauseTy dataClause, |
| 767 | OpenACCModifierKind modifiers, |
| 768 | bool structured, bool implicit, |
| 769 | bool requiresDtor); |
| 770 | // Each of the acc.routine operations must have a unique name, so we just use |
| 771 | // an integer counter. This is how Flang does it, so it seems reasonable. |
| 772 | unsigned routineCounter = 0; |
| 773 | void emitOpenACCRoutineDecl(const clang::FunctionDecl *funcDecl, |
| 774 | cir::FuncOp func, SourceLocation pragmaLoc, |
| 775 | ArrayRef<const OpenACCClause *> clauses); |
| 776 | |
| 777 | void emitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *d); |
| 778 | void emitOMPGroupPrivateDecl(const OMPGroupPrivateDecl *d); |
| 779 | void emitOMPCapturedExpr(const OMPCapturedExprDecl *d); |
| 780 | void emitOMPAllocateDecl(const OMPAllocateDecl *d); |
| 781 | void emitOMPDeclareReduction(const OMPDeclareReductionDecl *d); |
| 782 | void emitOMPDeclareMapper(const OMPDeclareMapperDecl *d); |
| 783 | void emitOMPRequiresDecl(const OMPRequiresDecl *d); |
| 784 | |
| 785 | // C++ related functions. |
| 786 | void emitDeclContext(const DeclContext *dc); |
| 787 | |
| 788 | /// Return the result of value-initializing the given type, i.e. a null |
| 789 | /// expression of the given type. |
| 790 | mlir::Value emitNullConstant(QualType t, mlir::Location loc); |
| 791 | |
| 792 | mlir::TypedAttr emitNullConstantAttr(QualType t); |
| 793 | |
| 794 | /// Get target specific null pointer. |
| 795 | mlir::Value getNullPointer(cir::PointerType ptrTy, QualType qt, |
| 796 | mlir::Location loc); |
| 797 | |
| 798 | /// Return a null constant appropriate for zero-initializing a base class with |
| 799 | /// the given type. This is usually, but not always, an LLVM null constant. |
| 800 | mlir::TypedAttr emitNullConstantForBase(const CXXRecordDecl *record); |
| 801 | |
| 802 | mlir::Value emitMemberPointerConstant(const UnaryOperator *e); |
| 803 | /// Returns a null attribute to represent either a null method or null data |
| 804 | /// member, depending on the type of mpt. |
| 805 | mlir::TypedAttr emitNullMemberAttr(QualType t, const MemberPointerType *mpt); |
| 806 | |
| 807 | /// Build a GEP-style field-index path from \p destClass to \p decl. |
| 808 | /// \p decl may be a FieldDecl, or an IndirectFieldDecl(in the case of an |
| 809 | /// anonymous struct/union). |
| 810 | /// Returns std::nullopt and emits errorNYI for virtual-base paths. |
| 811 | std::optional<llvm::SmallVector<int32_t>> |
| 812 | buildMemberPath(const CXXRecordDecl *destClass, const ValueDecl *decl); |
| 813 | |
| 814 | /// Returns true if \p field is a potentially-overlapping field with no CIR |
| 815 | /// field index (e.g. a [[no_unique_address]] member that is empty for both |
| 816 | /// layout and the ABI). Such fields have no entry in the CIR record, so a |
| 817 | /// pointer-to-data-member to them is represented by an explicit byte offset |
| 818 | /// (#cir.data_member_offset) rather than a field-index path. |
| 819 | bool isEmptyFieldForMemberPointer(const FieldDecl *field); |
| 820 | |
| 821 | llvm::StringRef getMangledName(clang::GlobalDecl gd); |
| 822 | // This function is to support the OpenACC 'bind' clause, which names an |
| 823 | // alternate name for the function to be called by. This function mangles |
| 824 | // `attachedFunction` as-if its name was actually `bindName` (that is, with |
| 825 | // the same signature). It has some additional complications, as the 'bind' |
| 826 | // target is always going to be a global function, so member functions need an |
| 827 | // explicit instead of implicit 'this' parameter, and thus gets mangled |
| 828 | // differently. |
| 829 | std::string getOpenACCBindMangledName(const IdentifierInfo *bindName, |
| 830 | const FunctionDecl *attachedFunction); |
| 831 | |
| 832 | void emitTentativeDefinition(const VarDecl *d); |
| 833 | |
| 834 | // Make sure that this type is translated. |
| 835 | void updateCompletedType(const clang::TagDecl *td); |
| 836 | |
| 837 | // Produce code for this constructor/destructor. This method doesn't try to |
| 838 | // apply any ABI rules about which other constructors/destructors are needed |
| 839 | // or if they are alias to each other. |
| 840 | cir::FuncOp codegenCXXStructor(clang::GlobalDecl gd); |
| 841 | |
| 842 | bool lookupRepresentativeDecl(llvm::StringRef mangledName, |
| 843 | clang::GlobalDecl &gd) const; |
| 844 | |
| 845 | bool supportsCOMDAT() const; |
| 846 | void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op); |
| 847 | |
| 848 | static void setInitializer(cir::GlobalOp &op, mlir::Attribute value); |
| 849 | |
| 850 | /// Print the postfix for externalized static variable or kernels for single |
| 851 | /// source offloading languages CUDA and HIP. The unique postfix is created |
| 852 | /// using either the CUID argument, or the file's UniqueID and active macros. |
| 853 | /// The fallback method without a CUID requires that the offloading toolchain |
| 854 | /// does not define separate macros via the -cc1 options. |
| 855 | void printPostfixForExternalizedDecl(llvm::raw_ostream &os, const Decl *d); |
| 856 | |
| 857 | /// Replace all uses of the old global with the new global, updating types |
| 858 | /// and references as needed. Erases the old global when done. |
| 859 | void replaceGlobal(cir::GlobalOp oldGV, cir::GlobalOp newGV); |
| 860 | |
| 861 | void replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old, |
| 862 | cir::FuncOp newFn); |
| 863 | |
| 864 | cir::FuncOp |
| 865 | getOrCreateCIRFunction(llvm::StringRef mangledName, mlir::Type funcType, |
| 866 | clang::GlobalDecl gd, bool forVTable, |
| 867 | bool dontDefer = false, bool isThunk = false, |
| 868 | ForDefinition_t isForDefinition = NotForDefinition, |
| 869 | mlir::NamedAttrList = {}); |
| 870 | |
| 871 | cir::FuncOp getOrCreateCIRFunction(llvm::StringRef mangledName, |
| 872 | mlir::Type funcType, clang::GlobalDecl gd, |
| 873 | bool forVTable, |
| 874 | mlir::NamedAttrList ) { |
| 875 | return getOrCreateCIRFunction(mangledName, funcType, gd, forVTable, |
| 876 | /*dontDefer=*/dontDefer: false, /*isThunk=*/isThunk: false, |
| 877 | isForDefinition: NotForDefinition, extraAttrs); |
| 878 | } |
| 879 | |
| 880 | cir::FuncOp createCIRFunction(mlir::Location loc, llvm::StringRef name, |
| 881 | cir::FuncType funcType, |
| 882 | const clang::FunctionDecl *funcDecl); |
| 883 | |
| 884 | /// Create a CIR function with builtin attribute set. |
| 885 | cir::FuncOp createCIRBuiltinFunction(mlir::Location loc, llvm::StringRef name, |
| 886 | cir::FuncType ty, |
| 887 | const clang::FunctionDecl *fd); |
| 888 | |
| 889 | /// Record the func_info tag for a function, either a C++ special member |
| 890 | /// form (constructor, destructor, assignment) or a known standard library |
| 891 | /// entity that passes can recognize without the AST. |
| 892 | void setFuncInfoAttr(cir::FuncOp funcOp, const clang::FunctionDecl *funcDecl); |
| 893 | |
| 894 | cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, |
| 895 | mlir::NamedAttrList = {}, |
| 896 | bool isLocal = false, |
| 897 | bool assumeConvergent = false); |
| 898 | |
| 899 | /// Given a builtin id for a function like "__builtin_fabsf", return a |
| 900 | /// Function* for "fabsf". |
| 901 | cir::FuncOp getBuiltinLibFunction(const FunctionDecl *fd, unsigned builtinID); |
| 902 | |
| 903 | CIRGenCUDARuntime &getCUDARuntime() { |
| 904 | assert(cudaRuntime != nullptr); |
| 905 | return *cudaRuntime; |
| 906 | } |
| 907 | |
| 908 | CIRGenOpenMPRuntime &getOpenMPRuntime() { |
| 909 | assert(openMPRuntime != nullptr); |
| 910 | return *openMPRuntime; |
| 911 | } |
| 912 | |
| 913 | bool isPaddedAtomicType(QualType type); |
| 914 | bool isPaddedAtomicType(const AtomicType *type); |
| 915 | |
| 916 | mlir::IntegerAttr getSize(CharUnits size) { |
| 917 | return builder.getSizeFromCharUnits(size); |
| 918 | } |
| 919 | |
| 920 | /// Emit any needed decls for which code generation was deferred. |
| 921 | void emitDeferred(); |
| 922 | |
| 923 | bool shouldOpportunisticallyEmitVTables(); |
| 924 | /// Emit any vtables which we deferred and still have a use for. |
| 925 | void emitDeferredVTables(); |
| 926 | |
| 927 | /// Try to emit external vtables as available_externally if they have emitted |
| 928 | /// all inlined virtual functions. It runs after EmitDeferred() and therefore |
| 929 | /// is not allowed to create new references to things that need to be emitted |
| 930 | /// lazily. |
| 931 | void emitVTablesOpportunistically(); |
| 932 | |
| 933 | /// Helper for `emitDeferred` to apply actual codegen. |
| 934 | void emitGlobalDecl(const clang::GlobalDecl &d); |
| 935 | |
| 936 | const llvm::Triple &getTriple() const { return target.getTriple(); } |
| 937 | |
| 938 | // Finalize CIR code generation. |
| 939 | void release(); |
| 940 | |
| 941 | /// Returns a pointer to a global variable representing a temporary with |
| 942 | /// static or thread storage duration. |
| 943 | mlir::Operation *getAddrOfGlobalTemporary(const MaterializeTemporaryExpr *mte, |
| 944 | const Expr *init); |
| 945 | |
| 946 | /// ------- |
| 947 | /// Visibility and Linkage |
| 948 | /// ------- |
| 949 | |
| 950 | static mlir::SymbolTable::Visibility |
| 951 | getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK); |
| 952 | cir::GlobalLinkageKind getFunctionLinkage(GlobalDecl gd); |
| 953 | static mlir::SymbolTable::Visibility getMLIRVisibility(cir::GlobalOp op); |
| 954 | cir::GlobalLinkageKind getCIRLinkageForDeclarator(const DeclaratorDecl *dd, |
| 955 | GVALinkage linkage); |
| 956 | void setFunctionLinkage(GlobalDecl gd, cir::FuncOp f) { |
| 957 | cir::GlobalLinkageKind l = getFunctionLinkage(gd); |
| 958 | f.setLinkageAttr(cir::GlobalLinkageKindAttr::get(context: &getMLIRContext(), value: l)); |
| 959 | mlir::SymbolTable::setSymbolVisibility(symbol: f, |
| 960 | vis: getMLIRVisibilityFromCIRLinkage(GLK: l)); |
| 961 | } |
| 962 | |
| 963 | cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd); |
| 964 | |
| 965 | void addReplacement(llvm::StringRef name, mlir::Operation *op); |
| 966 | |
| 967 | /// Helpers to emit "not yet implemented" error diagnostics |
| 968 | DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef); |
| 969 | |
| 970 | template <typename T> |
| 971 | DiagnosticBuilder errorNYI(SourceLocation loc, llvm::StringRef feature, |
| 972 | const T &name) { |
| 973 | unsigned diagID = |
| 974 | diags.getCustomDiagID(L: DiagnosticsEngine::Error, |
| 975 | FormatString: "ClangIR code gen Not Yet Implemented: %0: %1" ); |
| 976 | return diags.Report(Loc: loc, DiagID: diagID) << feature << name; |
| 977 | } |
| 978 | |
| 979 | DiagnosticBuilder errorNYI(mlir::Location loc, llvm::StringRef feature) { |
| 980 | // TODO: Convert the location to a SourceLocation |
| 981 | unsigned diagID = diags.getCustomDiagID( |
| 982 | L: DiagnosticsEngine::Error, FormatString: "ClangIR code gen Not Yet Implemented: %0" ); |
| 983 | return diags.Report(DiagID: diagID) << feature; |
| 984 | } |
| 985 | |
| 986 | DiagnosticBuilder errorNYI(llvm::StringRef feature) const { |
| 987 | // TODO: Make a default location? currSrcLoc? |
| 988 | unsigned diagID = diags.getCustomDiagID( |
| 989 | L: DiagnosticsEngine::Error, FormatString: "ClangIR code gen Not Yet Implemented: %0" ); |
| 990 | return diags.Report(DiagID: diagID) << feature; |
| 991 | } |
| 992 | |
| 993 | DiagnosticBuilder errorNYI(SourceRange, llvm::StringRef); |
| 994 | |
| 995 | template <typename T> |
| 996 | DiagnosticBuilder errorNYI(SourceRange loc, llvm::StringRef feature, |
| 997 | const T &name) { |
| 998 | return errorNYI(loc.getBegin(), feature, name) << loc; |
| 999 | } |
| 1000 | |
| 1001 | /// Emit a general error that something can't be done. |
| 1002 | void error(SourceLocation loc, llvm::StringRef error); |
| 1003 | |
| 1004 | /// Print out an error that codegen doesn't support the specified stmt yet. |
| 1005 | void errorUnsupported(const Stmt *s, llvm::StringRef type); |
| 1006 | |
| 1007 | /// Print out an error that codegen doesn't support the specified decl yet. |
| 1008 | void errorUnsupported(const Decl *d, llvm::StringRef type); |
| 1009 | |
| 1010 | /// Emits AMDGPU specific Metadata. |
| 1011 | void emitAMDGPUMetadata(); |
| 1012 | |
| 1013 | /// Build (or fetch from the dedup cache) the args ArrayAttr for an |
| 1014 | /// annotation. Returns the empty ArrayAttr when the annotation has none. |
| 1015 | mlir::ArrayAttr getOrCreateAnnotationArgs(const clang::AnnotateAttr *attr); |
| 1016 | |
| 1017 | /// Create cir::AnnotationAttr for a single AnnotateAttr. |
| 1018 | cir::AnnotationAttr emitAnnotateAttr(const clang::AnnotateAttr *aa); |
| 1019 | |
| 1020 | /// Add global annotations for a global value (GlobalOp or FuncOp). |
| 1021 | void addGlobalAnnotations(const clang::ValueDecl *d, mlir::Operation *gv); |
| 1022 | |
| 1023 | private: |
| 1024 | /// Search \p currentClass and its non-virtual base subobjects for \p field, |
| 1025 | /// appending CIR field indices along the path from \p currentClass. |
| 1026 | bool findFieldMemberPath(const CXXRecordDecl *currentClass, |
| 1027 | const FieldDecl *field, |
| 1028 | llvm::SmallVectorImpl<int32_t> &path); |
| 1029 | |
| 1030 | // An ordered map of canonical GlobalDecls to their mangled names. |
| 1031 | llvm::MapVector<clang::GlobalDecl, llvm::StringRef> mangledDeclNames; |
| 1032 | llvm::StringMap<clang::GlobalDecl, llvm::BumpPtrAllocator> manglings; |
| 1033 | |
| 1034 | // FIXME: should we use llvm::TrackingVH<mlir::Operation> here? |
| 1035 | llvm::MapVector<StringRef, mlir::Operation *> replacements; |
| 1036 | /// Call replaceAllUsesWith on all pairs in replacements. |
| 1037 | void applyReplacements(); |
| 1038 | |
| 1039 | bool getCPUAndFeaturesAttributes(GlobalDecl gd, |
| 1040 | llvm::StringMap<std::string> &attrs, |
| 1041 | bool setTargetFeatures = true); |
| 1042 | void setNonAliasAttributes(GlobalDecl gd, mlir::Operation *op); |
| 1043 | |
| 1044 | /// Map source language used to a CIR attribute. |
| 1045 | std::optional<cir::SourceLanguage> getCIRSourceLanguage() const; |
| 1046 | |
| 1047 | /// Emit all the global annotations. |
| 1048 | void emitGlobalAnnotations(); |
| 1049 | }; |
| 1050 | } // namespace CIRGen |
| 1051 | |
| 1052 | } // namespace clang |
| 1053 | |
| 1054 | #endif // LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H |
| 1055 | |