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