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