clang  19.0.0git
MicrosoftCXXABI.cpp
Go to the documentation of this file.
1 //===------- MicrosoftCXXABI.cpp - AST support for the Microsoft C++ ABI --===//
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 provides C++ AST support targeting the Microsoft Visual C++
10 // ABI.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CXXABI.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/Mangle.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/TargetInfo.h"
24 
25 using namespace clang;
26 
27 namespace {
28 
29 /// Numbers things which need to correspond across multiple TUs.
30 /// Typically these are things like static locals, lambdas, or blocks.
31 class MicrosoftNumberingContext : public MangleNumberingContext {
32  llvm::DenseMap<const Type *, unsigned> ManglingNumbers;
33  unsigned LambdaManglingNumber = 0;
34  unsigned StaticLocalNumber = 0;
35  unsigned StaticThreadlocalNumber = 0;
36 
37 public:
38  MicrosoftNumberingContext() = default;
39 
40  unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
41  return ++LambdaManglingNumber;
42  }
43 
44  unsigned getManglingNumber(const BlockDecl *BD) override {
45  const Type *Ty = nullptr;
46  return ++ManglingNumbers[Ty];
47  }
48 
49  unsigned getStaticLocalNumber(const VarDecl *VD) override {
50  if (VD->getTLSKind())
51  return ++StaticThreadlocalNumber;
52  return ++StaticLocalNumber;
53  }
54 
55  unsigned getManglingNumber(const VarDecl *VD,
56  unsigned MSLocalManglingNumber) override {
57  return MSLocalManglingNumber;
58  }
59 
60  unsigned getManglingNumber(const TagDecl *TD,
61  unsigned MSLocalManglingNumber) override {
62  return MSLocalManglingNumber;
63  }
64 };
65 
66 class MSHIPNumberingContext : public MicrosoftNumberingContext {
67  std::unique_ptr<MangleNumberingContext> DeviceCtx;
68 
69 public:
70  using MicrosoftNumberingContext::getManglingNumber;
71  MSHIPNumberingContext(MangleContext *DeviceMangler) {
72  DeviceCtx = createItaniumNumberingContext(DeviceMangler);
73  }
74 
75  unsigned getDeviceManglingNumber(const CXXMethodDecl *CallOperator) override {
76  return DeviceCtx->getManglingNumber(CallOperator);
77  }
78 
79  unsigned getManglingNumber(const TagDecl *TD,
80  unsigned MSLocalManglingNumber) override {
81  unsigned DeviceN = DeviceCtx->getManglingNumber(TD, MSLocalManglingNumber);
82  unsigned HostN =
83  MicrosoftNumberingContext::getManglingNumber(TD, MSLocalManglingNumber);
84  if (DeviceN > 0xFFFF || HostN > 0xFFFF) {
86  unsigned DiagID = Diags.getCustomDiagID(
87  DiagnosticsEngine::Error, "Mangling number exceeds limit (65535)");
88  Diags.Report(TD->getLocation(), DiagID);
89  }
90  return (DeviceN << 16) | HostN;
91  }
92 };
93 
94 class MSSYCLNumberingContext : public MicrosoftNumberingContext {
95  std::unique_ptr<MangleNumberingContext> DeviceCtx;
96 
97 public:
98  MSSYCLNumberingContext(MangleContext *DeviceMangler) {
99  DeviceCtx = createItaniumNumberingContext(DeviceMangler);
100  }
101 
102  unsigned getDeviceManglingNumber(const CXXMethodDecl *CallOperator) override {
103  return DeviceCtx->getManglingNumber(CallOperator);
104  }
105 };
106 
107 class MicrosoftCXXABI : public CXXABI {
108  ASTContext &Context;
109  llvm::SmallDenseMap<CXXRecordDecl *, CXXConstructorDecl *> RecordToCopyCtor;
110 
111  llvm::SmallDenseMap<TagDecl *, DeclaratorDecl *>
112  UnnamedTagDeclToDeclaratorDecl;
113  llvm::SmallDenseMap<TagDecl *, TypedefNameDecl *>
114  UnnamedTagDeclToTypedefNameDecl;
115 
116  // MangleContext for device numbering context, which is based on Itanium C++
117  // ABI.
118  std::unique_ptr<MangleContext> DeviceMangler;
119 
120 public:
121  MicrosoftCXXABI(ASTContext &Ctx) : Context(Ctx) {
122  if (Context.getLangOpts().CUDA && Context.getAuxTargetInfo()) {
123  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
124  Context.getAuxTargetInfo()->getCXXABI().isItaniumFamily() &&
125  "Unexpected combination of C++ ABIs.");
126  DeviceMangler.reset(
127  Context.createMangleContext(Context.getAuxTargetInfo()));
128  } else if (Context.getLangOpts().isSYCL()) {
129  DeviceMangler.reset(
130  ItaniumMangleContext::create(Context, Context.getDiagnostics()));
131  }
132  else if (Context.getLangOpts().isSYCL()) {
133  DeviceMangler.reset(
134  ItaniumMangleContext::create(Context, Context.getDiagnostics()));
135  }
136  }
137 
138  MemberPointerInfo
139  getMemberPointerInfo(const MemberPointerType *MPT) const override;
140 
141  CallingConv getDefaultMethodCallConv(bool isVariadic) const override {
142  if (!isVariadic &&
143  Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
144  return CC_X86ThisCall;
145  return Context.getTargetInfo().getDefaultCallingConv();
146  }
147 
148  bool isNearlyEmpty(const CXXRecordDecl *RD) const override {
149  llvm_unreachable("unapplicable to the MS ABI");
150  }
151 
152  const CXXConstructorDecl *
153  getCopyConstructorForExceptionObject(CXXRecordDecl *RD) override {
154  return RecordToCopyCtor[RD];
155  }
156 
157  void
158  addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
159  CXXConstructorDecl *CD) override {
160  assert(CD != nullptr);
161  assert(RecordToCopyCtor[RD] == nullptr || RecordToCopyCtor[RD] == CD);
162  RecordToCopyCtor[RD] = CD;
163  }
164 
165  void addTypedefNameForUnnamedTagDecl(TagDecl *TD,
166  TypedefNameDecl *DD) override {
167  TD = TD->getCanonicalDecl();
168  DD = DD->getCanonicalDecl();
169  TypedefNameDecl *&I = UnnamedTagDeclToTypedefNameDecl[TD];
170  if (!I)
171  I = DD;
172  }
173 
174  TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD) override {
175  return UnnamedTagDeclToTypedefNameDecl.lookup(
176  const_cast<TagDecl *>(TD->getCanonicalDecl()));
177  }
178 
179  void addDeclaratorForUnnamedTagDecl(TagDecl *TD,
180  DeclaratorDecl *DD) override {
181  TD = TD->getCanonicalDecl();
182  DD = cast<DeclaratorDecl>(DD->getCanonicalDecl());
183  DeclaratorDecl *&I = UnnamedTagDeclToDeclaratorDecl[TD];
184  if (!I)
185  I = DD;
186  }
187 
188  DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD) override {
189  return UnnamedTagDeclToDeclaratorDecl.lookup(
190  const_cast<TagDecl *>(TD->getCanonicalDecl()));
191  }
192 
193  std::unique_ptr<MangleNumberingContext>
194  createMangleNumberingContext() const override {
195  if (Context.getLangOpts().CUDA && Context.getAuxTargetInfo()) {
196  assert(DeviceMangler && "Missing device mangler");
197  return std::make_unique<MSHIPNumberingContext>(DeviceMangler.get());
198  } else if (Context.getLangOpts().isSYCL()) {
199  assert(DeviceMangler && "Missing device mangler");
200  return std::make_unique<MSSYCLNumberingContext>(DeviceMangler.get());
201  }
202 
203  return std::make_unique<MicrosoftNumberingContext>();
204  }
205 };
206 }
207 
208 // getNumBases() seems to only give us the number of direct bases, and not the
209 // total. This function tells us if we inherit from anybody that uses MI, or if
210 // we have a non-primary base class, which uses the multiple inheritance model.
212  while (RD->getNumBases() > 0) {
213  if (RD->getNumBases() > 1)
214  return true;
215  assert(RD->getNumBases() == 1);
216  const CXXRecordDecl *Base =
218  if (RD->isPolymorphic() && !Base->isPolymorphic())
219  return true;
220  RD = Base;
221  }
222  return false;
223 }
224 
228  if (getNumVBases() > 0)
233 }
234 
236  MSInheritanceAttr *IA = getAttr<MSInheritanceAttr>();
237  assert(IA && "Expected MSInheritanceAttr on the CXXRecordDecl!");
238  return IA->getInheritanceModel();
239 }
240 
242  return !inheritanceModelHasOnlyOneField(/*IsMemberFunction=*/false,
244  (hasDefinition() && isPolymorphic());
245 }
246 
248  if (MSVtorDispAttr *VDA = getAttr<MSVtorDispAttr>())
249  return VDA->getVtorDispMode();
250  return getASTContext().getLangOpts().getVtorDispMode();
251 }
252 
253 // Returns the number of pointer and integer slots used to represent a member
254 // pointer in the MS C++ ABI.
255 //
256 // Member function pointers have the following general form; however, fields
257 // are dropped as permitted (under the MSVC interpretation) by the inheritance
258 // model of the actual class.
259 //
260 // struct {
261 // // A pointer to the member function to call. If the member function is
262 // // virtual, this will be a thunk that forwards to the appropriate vftable
263 // // slot.
264 // void *FunctionPointerOrVirtualThunk;
265 //
266 // // An offset to add to the address of the vbtable pointer after
267 // // (possibly) selecting the virtual base but before resolving and calling
268 // // the function.
269 // // Only needed if the class has any virtual bases or bases at a non-zero
270 // // offset.
271 // int NonVirtualBaseAdjustment;
272 //
273 // // The offset of the vb-table pointer within the object. Only needed for
274 // // incomplete types.
275 // int VBPtrOffset;
276 //
277 // // An offset within the vb-table that selects the virtual base containing
278 // // the member. Loading from this offset produces a new offset that is
279 // // added to the address of the vb-table pointer to produce the base.
280 // int VirtualBaseAdjustmentOffset;
281 // };
282 static std::pair<unsigned, unsigned>
284  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
285  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
286  unsigned Ptrs = 0;
287  unsigned Ints = 0;
288  if (MPT->isMemberFunctionPointer())
289  Ptrs = 1;
290  else
291  Ints = 1;
293  Inheritance))
294  Ints++;
295  if (inheritanceModelHasVBPtrOffsetField(Inheritance))
296  Ints++;
297  if (inheritanceModelHasVBTableOffsetField(Inheritance))
298  Ints++;
299  return std::make_pair(Ptrs, Ints);
300 }
301 
302 CXXABI::MemberPointerInfo MicrosoftCXXABI::getMemberPointerInfo(
303  const MemberPointerType *MPT) const {
304  // The nominal struct is laid out with pointers followed by ints and aligned
305  // to a pointer width if any are present and an int width otherwise.
306  const TargetInfo &Target = Context.getTargetInfo();
307  unsigned PtrSize = Target.getPointerWidth(LangAS::Default);
308  unsigned IntSize = Target.getIntWidth();
309 
310  unsigned Ptrs, Ints;
311  std::tie(Ptrs, Ints) = getMSMemberPointerSlots(MPT);
312  MemberPointerInfo MPI;
313  MPI.HasPadding = false;
314  MPI.Width = Ptrs * PtrSize + Ints * IntSize;
315 
316  // When MSVC does x86_32 record layout, it aligns aggregate member pointers to
317  // 8 bytes. However, __alignof usually returns 4 for data memptrs and 8 for
318  // function memptrs.
319  if (Ptrs + Ints > 1 && Target.getTriple().isArch32Bit())
320  MPI.Align = 64;
321  else if (Ptrs)
322  MPI.Align = Target.getPointerAlign(LangAS::Default);
323  else
324  MPI.Align = Target.getIntAlign();
325 
326  if (Target.getTriple().isArch64Bit()) {
327  MPI.Width = llvm::alignTo(MPI.Width, MPI.Align);
328  MPI.HasPadding = MPI.Width != (Ptrs * PtrSize + Ints * IntSize);
329  }
330  return MPI;
331 }
332 
334  return new MicrosoftCXXABI(Ctx);
335 }
Defines the clang::ASTContext interface.
static bool usesMultipleInheritanceModel(const CXXRecordDecl *RD)
static std::pair< unsigned, unsigned > getMSMemberPointerSlots(const MemberPointerType *MPT)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
llvm::MachO::Target Target
Definition: MachO.h:50
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:778
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
DiagnosticsEngine & getDiagnostics() const
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:761
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4497
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isParsingBaseSpecifiers() const
Definition: DeclCXX.h:603
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1215
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
base_class_iterator bases_begin()
Definition: DeclCXX.h:626
MSInheritanceModel getMSInheritanceModel() const
Returns the inheritance model used for this record.
bool nullFieldOffsetIsZero() const
In the Microsoft C++ ABI, use zero for the field offset of a null data member pointer if we can guara...
bool hasDefinition() const
Definition: DeclCXX.h:571
MSInheritanceModel calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
MSVtorDispMode getMSVtorDispMode() const
Controls when vtordisps will be emitted if this record is used as a virtual base.
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:634
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
SourceLocation getLocation() const
Definition: DeclBase.h:445
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:771
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1553
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:879
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
bool isSYCL() const
Definition: LangOptions.h:749
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3472
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Definition: Type.cpp:5013
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition: Type.h:3492
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3587
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4730
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:122
Exposes information about the current target.
Definition: TargetInfo.h:218
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
virtual CallingConv getDefaultCallingConv() const
Gets the default calling convention for the given target and declaration context.
Definition: TargetInfo.h:1661
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1881
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3435
TypedefNameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this typedef-name.
Definition: Decl.h:3507
Represents a variable declaration or definition.
Definition: Decl.h:919
TLSKind getTLSKind() const
Definition: Decl.cpp:2169
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
std::unique_ptr< MangleNumberingContext > createItaniumNumberingContext(MangleContext *)
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
bool inheritanceModelHasNVOffsetField(bool IsMemberFunction, MSInheritanceModel Inheritance)
bool inheritanceModelHasOnlyOneField(bool IsMemberFunction, MSInheritanceModel Inheritance)
bool inheritanceModelHasVBPtrOffsetField(MSInheritanceModel Inheritance)
bool inheritanceModelHasVBTableOffsetField(MSInheritanceModel Inheritance)
MSVtorDispMode
In the Microsoft ABI, this controls the placement of virtual displacement members used to implement v...
Definition: LangOptions.h:35
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition: Specifiers.h:389
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86ThisCall
Definition: Specifiers.h:279