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