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