clang 22.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 "CIRGenCall.h"
18#include "CIRGenTypeCache.h"
19#include "CIRGenTypes.h"
20#include "CIRGenVTables.h"
21#include "CIRGenValue.h"
22
23#include "clang/AST/CharUnits.h"
26
27#include "TargetInfo.h"
28#include "mlir/IR/Builders.h"
29#include "mlir/IR/BuiltinOps.h"
30#include "mlir/IR/MLIRContext.h"
31#include "clang/AST/Decl.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/TargetParser/Triple.h"
37
38namespace clang {
39class ASTContext;
40class CodeGenOptions;
41class Decl;
42class GlobalDecl;
43class LangOptions;
44class TargetInfo;
45class VarDecl;
46
47namespace CIRGen {
48
49class CIRGenFunction;
50class CIRGenCXXABI;
51
52enum ForDefinition_t : bool { NotForDefinition = false, ForDefinition = true };
53
54/// This class organizes the cross-function state that is used while generating
55/// CIR code.
56class CIRGenModule : public CIRGenTypeCache {
57 CIRGenModule(CIRGenModule &) = delete;
58 CIRGenModule &operator=(CIRGenModule &) = delete;
59
60public:
61 CIRGenModule(mlir::MLIRContext &mlirContext, clang::ASTContext &astContext,
62 const clang::CodeGenOptions &cgo,
64
66
67private:
68 mutable std::unique_ptr<TargetCIRGenInfo> theTargetCIRGenInfo;
69
70 CIRGenBuilderTy builder;
71
72 /// Hold Clang AST information.
73 clang::ASTContext &astContext;
74
75 const clang::LangOptions &langOpts;
76
77 const clang::CodeGenOptions &codeGenOpts;
78
79 /// A "module" matches a c/cpp source file: containing a list of functions.
80 mlir::ModuleOp theModule;
81
83
84 const clang::TargetInfo &target;
85
86 std::unique_ptr<CIRGenCXXABI> abi;
87
88 CIRGenTypes genTypes;
89
90 /// Holds information about C++ vtables.
91 CIRGenVTables vtables;
92
93 /// Per-function codegen information. Updated everytime emitCIR is called
94 /// for FunctionDecls's.
95 CIRGenFunction *curCGF = nullptr;
96
98
99public:
100 mlir::ModuleOp getModule() const { return theModule; }
101 CIRGenBuilderTy &getBuilder() { return builder; }
102 clang::ASTContext &getASTContext() const { return astContext; }
103 const clang::TargetInfo &getTarget() const { return target; }
104 const clang::CodeGenOptions &getCodeGenOpts() const { return codeGenOpts; }
105 clang::DiagnosticsEngine &getDiags() const { return diags; }
106 CIRGenTypes &getTypes() { return genTypes; }
107 const clang::LangOptions &getLangOpts() const { return langOpts; }
108
109 CIRGenCXXABI &getCXXABI() const { return *abi; }
110 mlir::MLIRContext &getMLIRContext() { return *builder.getContext(); }
111
113 // FIXME(cir): instead of creating a CIRDataLayout every time, set it as an
114 // attribute for the CIRModule class.
115 return cir::CIRDataLayout(theModule);
116 }
117
118 /// -------
119 /// Handling globals
120 /// -------
121
122 mlir::Operation *lastGlobalOp = nullptr;
123
124 /// Keep a map between lambda fields and names, this needs to be per module
125 /// since lambdas might get generated later as part of defered work, and since
126 /// the pointers are supposed to be uniqued, should be fine. Revisit this if
127 /// it ends up taking too much memory.
128 llvm::DenseMap<const clang::FieldDecl *, llvm::StringRef> lambdaFieldToName;
129 /// Map BlockAddrInfoAttr (function name, label name) to the corresponding CIR
130 /// LabelOp. This provides the main lookup table used to resolve block
131 /// addresses into their label operations.
132 llvm::DenseMap<cir::BlockAddrInfoAttr, cir::LabelOp> blockAddressInfoToLabel;
133 /// Map CIR BlockAddressOps directly to their resolved LabelOps.
134 /// Used once a block address has been successfully lowered to a label.
135 llvm::MapVector<cir::BlockAddressOp, cir::LabelOp> blockAddressToLabel;
136 /// Track CIR BlockAddressOps that cannot be resolved immediately
137 /// because their LabelOp has not yet been emitted. These entries
138 /// are solved later once the corresponding label is available.
139 llvm::DenseSet<cir::BlockAddressOp> unresolvedBlockAddressToLabel;
140 cir::LabelOp lookupBlockAddressInfo(cir::BlockAddrInfoAttr blockInfo);
141 void mapBlockAddress(cir::BlockAddrInfoAttr blockInfo, cir::LabelOp label);
142 void mapUnresolvedBlockAddress(cir::BlockAddressOp op);
143 void mapResolvedBlockAddress(cir::BlockAddressOp op, cir::LabelOp);
144 void updateResolvedBlockAddress(cir::BlockAddressOp op,
145 cir::LabelOp newLabel);
146 /// Tell the consumer that this variable has been instantiated.
148
149 llvm::DenseMap<const Decl *, cir::GlobalOp> staticLocalDeclMap;
150
151 mlir::Operation *getGlobalValue(llvm::StringRef ref);
152
153 cir::GlobalOp getStaticLocalDeclAddress(const VarDecl *d) {
154 return staticLocalDeclMap[d];
155 }
156
157 void setStaticLocalDeclAddress(const VarDecl *d, cir::GlobalOp c) {
159 }
160
161 cir::GlobalOp getOrCreateStaticVarDecl(const VarDecl &d,
162 cir::GlobalLinkageKind linkage);
163
164 /// If the specified mangled name is not in the module, create and return an
165 /// mlir::GlobalOp value
166 cir::GlobalOp getOrCreateCIRGlobal(llvm::StringRef mangledName, mlir::Type ty,
167 LangAS langAS, const VarDecl *d,
168 ForDefinition_t isForDefinition);
169
170 cir::GlobalOp getOrCreateCIRGlobal(const VarDecl *d, mlir::Type ty,
171 ForDefinition_t isForDefinition);
172
173 static cir::GlobalOp createGlobalOp(CIRGenModule &cgm, mlir::Location loc,
174 llvm::StringRef name, mlir::Type t,
175 bool isConstant = false,
176 mlir::Operation *insertPoint = nullptr);
177
178 /// Add a global constructor or destructor to the module.
179 /// The priority is optional, if not specified, the default priority is used.
180 void addGlobalCtor(cir::FuncOp ctor,
181 std::optional<int> priority = std::nullopt);
182 void addGlobalDtor(cir::FuncOp dtor,
183 std::optional<int> priority = std::nullopt);
184
186 // In C23 (N3096) $6.7.10:
187 // """
188 // If any object is initialized with an empty initializer, then it is
189 // subject to default initialization:
190 // - if it is an aggregate, every member is initialized (recursively)
191 // according to these rules, and any padding is initialized to zero bits;
192 // - if it is a union, the first named member is initialized (recursively)
193 // according to these rules, and any padding is initialized to zero bits.
194 //
195 // If the aggregate or union contains elements or members that are
196 // aggregates or unions, these rules apply recursively to the subaggregates
197 // or contained unions.
198 //
199 // If there are fewer initializers in a brace-enclosed list than there are
200 // elements or members of an aggregate, or fewer characters in a string
201 // literal used to initialize an array of known size than there are elements
202 // in the array, the remainder of the aggregate is subject to default
203 // initialization.
204 // """
205 //
206 // The standard seems ambiguous in the following two areas:
207 // 1. For a union type with empty initializer, if the first named member is
208 // not the largest member, then the bytes comes after the first named member
209 // but before padding are left unspecified. An example is:
210 // union U { int a; long long b;};
211 // union U u = {}; // The first 4 bytes are 0, but 4-8 bytes are left
212 // unspecified.
213 //
214 // 2. It only mentions padding for empty initializer, but doesn't mention
215 // padding for a non empty initialization list. And if the aggregation or
216 // union contains elements or members that are aggregates or unions, and
217 // some are non empty initializers, while others are empty initializers,
218 // the padding initialization is unclear. An example is:
219 // struct S1 { int a; long long b; };
220 // struct S2 { char c; struct S1 s1; };
221 // // The values for paddings between s2.c and s2.s1.a, between s2.s1.a
222 // and s2.s1.b are unclear.
223 // struct S2 s2 = { 'c' };
224 //
225 // Here we choose to zero initiailize left bytes of a union type because
226 // projects like the Linux kernel are relying on this behavior. If we don't
227 // explicitly zero initialize them, the undef values can be optimized to
228 // return garbage data. We also choose to zero initialize paddings for
229 // aggregates and unions, no matter they are initialized by empty
230 // initializers or non empty initializers. This can provide a consistent
231 // behavior. So projects like the Linux kernel can rely on it.
232 return !getLangOpts().CPlusPlus;
233 }
234
235 llvm::StringMap<unsigned> cgGlobalNames;
236 std::string getUniqueGlobalName(const std::string &baseName);
237
238 /// Return the mlir::Value for the address of the given global variable.
239 /// If Ty is non-null and if the global doesn't exist, then it will be created
240 /// with the specified type instead of whatever the normal requested type
241 /// would be. If IsForDefinition is true, it is guaranteed that an actual
242 /// global with type Ty will be returned, not conversion of a variable with
243 /// the same mangled name but some other type.
244 mlir::Value
245 getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty = {},
246 ForDefinition_t isForDefinition = NotForDefinition);
247
248 /// Return the mlir::GlobalViewAttr for the address of the given global.
249 cir::GlobalViewAttr getAddrOfGlobalVarAttr(const VarDecl *d);
250
252 const CXXRecordDecl *derivedClass,
253 llvm::iterator_range<CastExpr::path_const_iterator> path);
254
255 /// Get the CIR attributes and calling convention to use for a particular
256 /// function type.
257 ///
258 /// \param calleeInfo - The callee information these attributes are being
259 /// constructed for. If valid, the attributes applied to this decl may
260 /// contribute to the function attributes and calling convention.
262 mlir::NamedAttrList &attrs);
263
264 /// Will return a global variable of the given type. If a variable with a
265 /// different type already exists then a new variable with the right type
266 /// will be created and all uses of the old variable will be replaced with a
267 /// bitcast to the new variable.
269 mlir::Location loc, llvm::StringRef name, mlir::Type ty,
270 cir::GlobalLinkageKind linkage, clang::CharUnits alignment);
271
272 void emitVTable(const CXXRecordDecl *rd);
273
274 /// Return the appropriate linkage for the vtable, VTT, and type information
275 /// of the given class.
276 cir::GlobalLinkageKind getVTableLinkage(const CXXRecordDecl *rd);
277
278 /// Get the address of the RTTI descriptor for the given type.
279 mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty,
280 bool forEH = false);
281
282 static mlir::SymbolTable::Visibility getMLIRVisibility(Visibility v) {
283 switch (v) {
285 return mlir::SymbolTable::Visibility::Public;
286 case HiddenVisibility:
287 return mlir::SymbolTable::Visibility::Private;
289 // The distinction between ProtectedVisibility and DefaultVisibility is
290 // that symbols with ProtectedVisibility, while visible to the dynamic
291 // linker like DefaultVisibility, are guaranteed to always dynamically
292 // resolve to a symbol in the current shared object. There is currently no
293 // equivalent MLIR visibility, so we fall back on the fact that the symbol
294 // is visible.
295 return mlir::SymbolTable::Visibility::Public;
296 }
297 llvm_unreachable("unknown visibility!");
298 }
299
300 llvm::DenseMap<mlir::Attribute, cir::GlobalOp> constantStringMap;
301
302 /// Return a constant array for the given string.
303 mlir::Attribute getConstantArrayFromStringLiteral(const StringLiteral *e);
304
305 /// Return a global symbol reference to a constant array for the given string
306 /// literal.
307 cir::GlobalOp getGlobalForStringLiteral(const StringLiteral *s,
308 llvm::StringRef name = ".str");
309
310 /// Return a global symbol reference to a constant array for the given string
311 /// literal.
312 cir::GlobalViewAttr
314 llvm::StringRef name = ".str");
315
316 /// Returns the address space for temporary allocations in the language. This
317 /// ensures that the allocated variable's address space matches the
318 /// expectations of the AST, rather than using the target's allocation address
319 /// space, which may lead to type mismatches in other parts of the IR.
321
322 /// Set attributes which are common to any form of a global definition (alias,
323 /// Objective-C method, function, global variable).
324 ///
325 /// NOTE: This should only be called for definitions.
326 void setCommonAttributes(GlobalDecl gd, mlir::Operation *op);
327
329
330 /// Helpers to convert the presumed location of Clang's SourceLocation to an
331 /// MLIR Location.
332 mlir::Location getLoc(clang::SourceLocation cLoc);
333 mlir::Location getLoc(clang::SourceRange cRange);
334
335 /// Return the best known alignment for an unknown pointer to a
336 /// particular class.
338
339 /// FIXME: this could likely be a common helper and not necessarily related
340 /// with codegen.
342 LValueBaseInfo *baseInfo);
343
344 /// TODO: Add TBAAAccessInfo
346 const CXXRecordDecl *baseDecl,
347 CharUnits expectedTargetAlign);
348
349 /// Returns the assumed alignment of a virtual base of a class.
351 const CXXRecordDecl *derived,
352 const CXXRecordDecl *vbase);
353
354 cir::FuncOp
356 const CIRGenFunctionInfo *fnInfo = nullptr,
357 cir::FuncType fnType = nullptr, bool dontDefer = false,
358 ForDefinition_t isForDefinition = NotForDefinition) {
359 return getAddrAndTypeOfCXXStructor(gd, fnInfo, fnType, dontDefer,
360 isForDefinition)
361 .second;
362 }
363
364 std::pair<cir::FuncType, cir::FuncOp> getAddrAndTypeOfCXXStructor(
365 clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo = nullptr,
366 cir::FuncType fnType = nullptr, bool dontDefer = false,
367 ForDefinition_t isForDefinition = NotForDefinition);
368
369 mlir::Type getVTableComponentType();
370 CIRGenVTables &getVTables() { return vtables; }
371
373 return vtables.getItaniumVTableContext();
374 }
376 return vtables.getItaniumVTableContext();
377 }
378
379 /// This contains all the decls which have definitions but which are deferred
380 /// for emission and therefore should only be output if they are actually
381 /// used. If a decl is in this, then it is known to have not been referenced
382 /// yet.
383 std::map<llvm::StringRef, clang::GlobalDecl> deferredDecls;
384
385 // This is a list of deferred decls which we have seen that *are* actually
386 // referenced. These get code generated when the module is done.
387 std::vector<clang::GlobalDecl> deferredDeclsToEmit;
389 deferredDeclsToEmit.emplace_back(GD);
390 }
391
393
394 /// Determine whether the definition must be emitted; if this returns \c
395 /// false, the definition can be emitted lazily if it's used.
396 bool mustBeEmitted(const clang::ValueDecl *d);
397
398 /// Determine whether the definition can be emitted eagerly, or should be
399 /// delayed until the end of the translation unit. This is relevant for
400 /// definitions whose linkage can change, e.g. implicit function
401 /// instantiations which may later be explicitly instantiated.
403
404 bool verifyModule() const;
405
406 /// Return the address of the given function. If funcType is non-null, then
407 /// this function will use the specified type if it has to create it.
408 // TODO: this is a bit weird as `GetAddr` given we give back a FuncOp?
409 cir::FuncOp
410 getAddrOfFunction(clang::GlobalDecl gd, mlir::Type funcType = nullptr,
411 bool forVTable = false, bool dontDefer = false,
412 ForDefinition_t isForDefinition = NotForDefinition);
413
414 mlir::Operation *
416 ForDefinition_t isForDefinition = NotForDefinition);
417
418 // Return whether RTTI information should be emitted for this target.
419 bool shouldEmitRTTI(bool forEH = false) {
420 return (forEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice &&
421 !(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
422 getTriple().isNVPTX());
423 }
424
425 /// Emit type info if type of an expression is a variably modified
426 /// type. Also emit proper debug info for cast types.
428 CIRGenFunction *cgf = nullptr);
429
430 /// Emit code for a single global function or variable declaration. Forward
431 /// declarations are emitted lazily.
433
434 void emitAliasForGlobal(llvm::StringRef mangledName, mlir::Operation *op,
435 GlobalDecl aliasGD, cir::FuncOp aliasee,
436 cir::GlobalLinkageKind linkage);
437
438 mlir::Type convertType(clang::QualType type);
439
440 /// Set the visibility for the given global.
441 void setGlobalVisibility(mlir::Operation *op, const NamedDecl *d) const;
442 void setDSOLocal(mlir::Operation *op) const;
443 void setDSOLocal(cir::CIRGlobalValueInterface gv) const;
444
445 /// Set visibility, dllimport/dllexport and dso_local.
446 /// This must be called after dllimport/dllexport is set.
447 void setGVProperties(mlir::Operation *op, const NamedDecl *d) const;
448 void setGVPropertiesAux(mlir::Operation *op, const NamedDecl *d) const;
449
450 /// Set TLS mode for the given operation based on the given variable
451 /// declaration.
452 void setTLSMode(mlir::Operation *op, const VarDecl &d);
453
454 /// Get TLS mode from CodeGenOptions.
455 cir::TLS_Model getDefaultCIRTLSModel() const;
456
457 /// Set function attributes for a function declaration.
458 void setFunctionAttributes(GlobalDecl gd, cir::FuncOp f,
459 bool isIncompleteFunction, bool isThunk);
460
461 /// Set extra attributes (inline, etc.) for a function.
463 cir::FuncOp f);
464
466 mlir::Operation *op = nullptr);
467 void emitGlobalFunctionDefinition(clang::GlobalDecl gd, mlir::Operation *op);
469 bool isTentative = false);
470
471 /// Emit the function that initializes the specified global
472 void emitCXXGlobalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr,
473 bool performInit);
474
475 void emitCXXGlobalVarDeclInitFunc(const VarDecl *vd, cir::GlobalOp addr,
476 bool performInit);
477
481 template <typename BeforeOpTy, typename DataClauseTy>
482 void emitGlobalOpenACCDeclareDataOperands(const Expr *varOperand,
483 DataClauseTy dataClause,
484 OpenACCModifierKind modifiers,
485 bool structured, bool implicit,
486 bool requiresDtor);
487 // Each of the acc.routine operations must have a unique name, so we just use
488 // an integer counter. This is how Flang does it, so it seems reasonable.
489 unsigned routineCounter = 0;
490 void emitOpenACCRoutineDecl(const clang::FunctionDecl *funcDecl,
491 cir::FuncOp func, SourceLocation pragmaLoc,
493
501
502 // C++ related functions.
503 void emitDeclContext(const DeclContext *dc);
504
505 /// Return the result of value-initializing the given type, i.e. a null
506 /// expression of the given type.
507 mlir::Value emitNullConstant(QualType t, mlir::Location loc);
508
509 mlir::TypedAttr emitNullConstantAttr(QualType t);
510
511 /// Return a null constant appropriate for zero-initializing a base class with
512 /// the given type. This is usually, but not always, an LLVM null constant.
513 mlir::TypedAttr emitNullConstantForBase(const CXXRecordDecl *record);
514
515 mlir::Value emitMemberPointerConstant(const UnaryOperator *e);
516
517 llvm::StringRef getMangledName(clang::GlobalDecl gd);
518 // This function is to support the OpenACC 'bind' clause, which names an
519 // alternate name for the function to be called by. This function mangles
520 // `attachedFunction` as-if its name was actually `bindName` (that is, with
521 // the same signature). It has some additional complications, as the 'bind'
522 // target is always going to be a global function, so member functions need an
523 // explicit instead of implicit 'this' parameter, and thus gets mangled
524 // differently.
525 std::string getOpenACCBindMangledName(const IdentifierInfo *bindName,
526 const FunctionDecl *attachedFunction);
527
528 void emitTentativeDefinition(const VarDecl *d);
529
530 // Make sure that this type is translated.
531 void updateCompletedType(const clang::TagDecl *td);
532
533 // Produce code for this constructor/destructor. This method doesn't try to
534 // apply any ABI rules about which other constructors/destructors are needed
535 // or if they are alias to each other.
537
538 bool supportsCOMDAT() const;
539 void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op);
540
541 static void setInitializer(cir::GlobalOp &op, mlir::Attribute value);
542
543 void replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old,
544 cir::FuncOp newFn);
545
546 cir::FuncOp
547 getOrCreateCIRFunction(llvm::StringRef mangledName, mlir::Type funcType,
548 clang::GlobalDecl gd, bool forVTable,
549 bool dontDefer = false, bool isThunk = false,
550 ForDefinition_t isForDefinition = NotForDefinition,
551 mlir::ArrayAttr extraAttrs = {});
552
553 cir::FuncOp createCIRFunction(mlir::Location loc, llvm::StringRef name,
554 cir::FuncType funcType,
555 const clang::FunctionDecl *funcDecl);
556
557 /// Create a CIR function with builtin attribute set.
558 cir::FuncOp createCIRBuiltinFunction(mlir::Location loc, llvm::StringRef name,
559 cir::FuncType ty,
560 const clang::FunctionDecl *fd);
561
562 /// Mark the function as a special member (e.g. constructor, destructor)
563 void setCXXSpecialMemberAttr(cir::FuncOp funcOp,
564 const clang::FunctionDecl *funcDecl);
565
566 cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name,
567 mlir::ArrayAttr = {}, bool isLocal = false,
568 bool assumeConvergent = false);
569
570 static constexpr const char *builtinCoroId = "__builtin_coro_id";
571 static constexpr const char *builtinCoroAlloc = "__builtin_coro_alloc";
572 static constexpr const char *builtinCoroBegin = "__builtin_coro_begin";
573
574 /// Given a builtin id for a function like "__builtin_fabsf", return a
575 /// Function* for "fabsf".
576 cir::FuncOp getBuiltinLibFunction(const FunctionDecl *fd, unsigned builtinID);
577
578 mlir::IntegerAttr getSize(CharUnits size) {
579 return builder.getSizeFromCharUnits(size);
580 }
581
582 /// Emit any needed decls for which code generation was deferred.
583 void emitDeferred();
584
585 /// Helper for `emitDeferred` to apply actual codegen.
586 void emitGlobalDecl(const clang::GlobalDecl &d);
587
588 const llvm::Triple &getTriple() const { return target.getTriple(); }
589
590 // Finalize CIR code generation.
591 void release();
592
593 /// -------
594 /// Visibility and Linkage
595 /// -------
596
597 static mlir::SymbolTable::Visibility
598 getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK);
599 static cir::VisibilityKind getGlobalVisibilityKindFromClangVisibility(
600 clang::VisibilityAttr::VisibilityType visibility);
601 cir::VisibilityAttr getGlobalVisibilityAttrFromDecl(const Decl *decl);
602 cir::GlobalLinkageKind getFunctionLinkage(GlobalDecl gd);
603 static mlir::SymbolTable::Visibility getMLIRVisibility(cir::GlobalOp op);
604 cir::GlobalLinkageKind getCIRLinkageForDeclarator(const DeclaratorDecl *dd,
605 GVALinkage linkage,
606 bool isConstantVariable);
607 void setFunctionLinkage(GlobalDecl gd, cir::FuncOp f) {
608 cir::GlobalLinkageKind l = getFunctionLinkage(gd);
609 f.setLinkageAttr(cir::GlobalLinkageKindAttr::get(&getMLIRContext(), l));
610 mlir::SymbolTable::setSymbolVisibility(f,
612 }
613
614 cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd,
615 bool isConstant);
616
617 void addReplacement(llvm::StringRef name, mlir::Operation *op);
618
619 /// Helpers to emit "not yet implemented" error diagnostics
620 DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef);
621
622 template <typename T>
623 DiagnosticBuilder errorNYI(SourceLocation loc, llvm::StringRef feature,
624 const T &name) {
625 unsigned diagID =
626 diags.getCustomDiagID(DiagnosticsEngine::Error,
627 "ClangIR code gen Not Yet Implemented: %0: %1");
628 return diags.Report(loc, diagID) << feature << name;
629 }
630
631 DiagnosticBuilder errorNYI(mlir::Location loc, llvm::StringRef feature) {
632 // TODO: Convert the location to a SourceLocation
633 unsigned diagID = diags.getCustomDiagID(
634 DiagnosticsEngine::Error, "ClangIR code gen Not Yet Implemented: %0");
635 return diags.Report(diagID) << feature;
636 }
637
638 DiagnosticBuilder errorNYI(llvm::StringRef feature) const {
639 // TODO: Make a default location? currSrcLoc?
640 unsigned diagID = diags.getCustomDiagID(
641 DiagnosticsEngine::Error, "ClangIR code gen Not Yet Implemented: %0");
642 return diags.Report(diagID) << feature;
643 }
644
645 DiagnosticBuilder errorNYI(SourceRange, llvm::StringRef);
646
647 template <typename T>
648 DiagnosticBuilder errorNYI(SourceRange loc, llvm::StringRef feature,
649 const T &name) {
650 return errorNYI(loc.getBegin(), feature, name) << loc;
651 }
652
653private:
654 // An ordered map of canonical GlobalDecls to their mangled names.
655 llvm::MapVector<clang::GlobalDecl, llvm::StringRef> mangledDeclNames;
656 llvm::StringMap<clang::GlobalDecl, llvm::BumpPtrAllocator> manglings;
657
658 // FIXME: should we use llvm::TrackingVH<mlir::Operation> here?
659 typedef llvm::StringMap<mlir::Operation *> ReplacementsTy;
660 ReplacementsTy replacements;
661 /// Call replaceAllUsesWith on all pairs in replacements.
662 void applyReplacements();
663
664 /// A helper function to replace all uses of OldF to NewF that replace
665 /// the type of pointer arguments. This is not needed to tradtional
666 /// pipeline since LLVM has opaque pointers but CIR not.
667 void replacePointerTypeArgs(cir::FuncOp oldF, cir::FuncOp newF);
668
669 void setNonAliasAttributes(GlobalDecl gd, mlir::Operation *op);
670
671 /// Map source language used to a CIR attribute.
672 std::optional<cir::SourceLanguage> getCIRSourceLanguage() const;
673};
674} // namespace CIRGen
675
676} // namespace clang
677
678#endif // LLVM_CLANG_LIB_CIR_CODEGEN_CIRGENMODULE_H
Defines the SourceManager interface.
__device__ __2f16 float __ockl_bool s
__device__ __2f16 float c
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
Implements C++ ABI-specific code generation functions.
Abstract information about a function or function prototype.
Definition CIRGenCall.h:27
void updateResolvedBlockAddress(cir::BlockAddressOp op, cir::LabelOp newLabel)
void emitCXXGlobalVarDeclInit(const VarDecl *varDecl, cir::GlobalOp addr, bool performInit)
Emit the function that initializes the specified global.
void replaceUsesOfNonProtoTypeWithRealFunction(mlir::Operation *old, cir::FuncOp newFn)
This function is called when we implement a function with no prototype, e.g.
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)
void setGlobalVisibility(mlir::Operation *op, const NamedDecl *d) const
Set the visibility for the given global.
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.
clang::ASTContext & getASTContext() const
cir::FuncOp getAddrOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::ArrayAttr={}, bool isLocal=false, bool assumeConvergent=false)
llvm::DenseMap< cir::BlockAddrInfoAttr, cir::LabelOp > blockAddressInfoToLabel
Map BlockAddrInfoAttr (function name, label name) to the corresponding CIR LabelOp.
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 emitOMPCapturedExpr(const OMPCapturedExprDecl *d)
void mapUnresolvedBlockAddress(cir::BlockAddressOp op)
bool mustBeEmitted(const clang::ValueDecl *d)
Determine whether the definition must be emitted; if this returns false, the definition can be emitte...
void constructAttributeList(CIRGenCalleeInfo calleeInfo, mlir::NamedAttrList &attrs)
Get the CIR attributes and calling convention to use for a particular function type.
void emitGlobalOpenACCDeclareDecl(const clang::OpenACCDeclareDecl *cd)
mlir::IntegerAttr getSize(CharUnits size)
DiagnosticBuilder errorNYI(SourceRange loc, llvm::StringRef feature, const T &name)
CIRGenBuilderTy & getBuilder()
void setDSOLocal(mlir::Operation *op) const
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.
llvm::DenseMap< const Decl *, cir::GlobalOp > staticLocalDeclMap
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.
void emitOMPRequiresDecl(const OMPRequiresDecl *d)
void emitGlobalDefinition(clang::GlobalDecl gd, mlir::Operation *op=nullptr)
void mapResolvedBlockAddress(cir::BlockAddressOp op, cir::LabelOp)
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.
mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty, bool forEH=false)
Get the address of the RTTI descriptor for the given type.
clang::CharUnits getNaturalTypeAlignment(clang::QualType t, LValueBaseInfo *baseInfo)
FIXME: this could likely be a common helper and not necessarily related with codegen.
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.
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)
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 emitGlobalDecl(const clang::GlobalDecl &d)
Helper for emitDeferred to apply actual codegen.
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::ArrayAttr extraAttrs={})
void emitGlobalVarDefinition(const clang::VarDecl *vd, bool isTentative=false)
void setTLSMode(mlir::Operation *op, const VarDecl &d)
Set TLS mode for the given operation based on the given variable declaration.
DiagnosticBuilder errorNYI(mlir::Location loc, llvm::StringRef feature)
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)
mlir::Value emitMemberPointerConstant(const UnaryOperator *e)
void emitGlobalOpenACCDecl(const clang::OpenACCConstructDecl *cd)
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
std::map< llvm::StringRef, clang::GlobalDecl > deferredDecls
This contains all the decls which have definitions but which are deferred for emission and therefore ...
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.
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
const clang::LangOptions & getLangOpts() const
void emitOpenACCRoutineDecl(const clang::FunctionDecl *funcDecl, cir::FuncOp func, SourceLocation pragmaLoc, ArrayRef< const OpenACCClause * > clauses)
static constexpr const char * builtinCoroAlloc
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)
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)
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.
llvm::DenseSet< cir::BlockAddressOp > unresolvedBlockAddressToLabel
Track CIR BlockAddressOps that cannot be resolved immediately because their LabelOp has not yet been ...
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
static cir::VisibilityKind getGlobalVisibilityKindFromClangVisibility(clang::VisibilityAttr::VisibilityType visibility)
llvm::StringMap< unsigned > cgGlobalNames
void setCXXSpecialMemberAttr(cir::FuncOp funcOp, const clang::FunctionDecl *funcDecl)
Mark the function as a special member (e.g. constructor, destructor)
mlir::Operation * getGlobalValue(llvm::StringRef ref)
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
cir::GlobalLinkageKind getCIRLinkageForDeclarator(const DeclaratorDecl *dd, GVALinkage linkage, bool isConstantVariable)
mlir::MLIRContext & getMLIRContext()
mlir::Operation * getAddrOfGlobal(clang::GlobalDecl gd, ForDefinition_t isForDefinition=NotForDefinition)
DiagnosticBuilder errorNYI(llvm::StringRef feature) const
static cir::GlobalOp createGlobalOp(CIRGenModule &cgm, mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::Operation *insertPoint=nullptr)
void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op)
cir::GlobalOp getStaticLocalDeclAddress(const VarDecl *d)
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.
llvm::MapVector< cir::BlockAddressOp, cir::LabelOp > blockAddressToLabel
Map CIR BlockAddressOps directly to their resolved LabelOps.
void emitDeclContext(const DeclContext *dc)
static constexpr const char * builtinCoroBegin
static constexpr const char * builtinCoroId
void emitGlobal(clang::GlobalDecl gd)
Emit code for a single global function or variable declaration.
cir::LabelOp lookupBlockAddressInfo(cir::BlockAddrInfoAttr blockInfo)
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)
cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd, bool isConstant)
void mapBlockAddress(cir::BlockAddrInfoAttr blockInfo, cir::LabelOp label)
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)
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.
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:48
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...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
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:232
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3862
This represents one expression.
Definition Expr.h:112
Represents a function declaration or definition.
Definition Decl.h:2000
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...
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:937
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
Exposes information about the current target.
Definition TargetInfo.h:226
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
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:926
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