1//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
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++ code generation targeting the Microsoft Visual C++ ABI.
10// The class in this file generates structures that follow the Microsoft
11// Visual C++ ABI, which is actually not very well documented at all outside
12// of Microsoft.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CGCXXABI.h"
17#include "CGCleanup.h"
18#include "CGVTables.h"
19#include "CodeGenModule.h"
20#include "CodeGenTypes.h"
21#include "TargetInfo.h"
22#include "clang/AST/Attr.h"
23#include "clang/AST/CXXInheritance.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/VTableBuilder.h"
28#include "clang/CodeGen/ConstantInitBuilder.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/StringSet.h"
31#include "llvm/IR/Intrinsics.h"
32
33using namespace clang;
34using namespace CodeGen;
35
36namespace {
37
38/// Holds all the vbtable globals for a given class.
39struct VBTableGlobals {
40 const VPtrInfoVector *VBTables;
41 SmallVector<llvm::GlobalVariable *, 2> Globals;
42};
43
44class MicrosoftCXXABI : public CGCXXABI {
45public:
46 MicrosoftCXXABI(CodeGenModule &CGM)
47 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
48 ClassHierarchyDescriptorType(nullptr),
49 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
50 ThrowInfoType(nullptr) {}
51
52 bool HasThisReturn(GlobalDecl GD) const override;
53 bool hasMostDerivedReturn(GlobalDecl GD) const override;
54
55 bool classifyReturnType(CGFunctionInfo &FI) const override;
56
57 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
58
59 bool isSRetParameterAfterThis() const override { return true; }
60
61 bool isThisCompleteObject(GlobalDecl GD) const override {
62 // The Microsoft ABI doesn't use separate complete-object vs.
63 // base-object variants of constructors, but it does of destructors.
64 if (isa<CXXDestructorDecl>(GD.getDecl())) {
65 switch (GD.getDtorType()) {
66 case Dtor_Complete:
67 case Dtor_Deleting:
68 return true;
69
70 case Dtor_Base:
71 return false;
72
73 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
74 }
75 llvm_unreachable("bad dtor kind");
76 }
77
78 // No other kinds.
79 return false;
80 }
81
82 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
83 FunctionArgList &Args) const override {
84 assert(Args.size() >= 2 &&
85 "expected the arglist to have at least two args!");
86 // The 'most_derived' parameter goes second if the ctor is variadic and
87 // has v-bases.
88 if (CD->getParent()->getNumVBases() > 0 &&
89 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
90 return 2;
91 return 1;
92 }
93
94 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
95 std::vector<CharUnits> VBPtrOffsets;
96 const ASTContext &Context = getContext();
97 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
98
99 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
100 for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
101 const ASTRecordLayout &SubobjectLayout =
102 Context.getASTRecordLayout(VBT->IntroducingObject);
103 CharUnits Offs = VBT->NonVirtualOffset;
104 Offs += SubobjectLayout.getVBPtrOffset();
105 if (VBT->getVBaseWithVPtr())
106 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
107 VBPtrOffsets.push_back(Offs);
108 }
109 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
110 return VBPtrOffsets;
111 }
112
113 StringRef GetPureVirtualCallName() override { return "_purecall"; }
114 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
115
116 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
117 Address Ptr, QualType ElementType,
118 const CXXDestructorDecl *Dtor) override;
119
120 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
121 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
122
123 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
124
125 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
126 const VPtrInfo &Info);
127
128 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
129 CatchTypeInfo
130 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
131
132 /// MSVC needs an extra flag to indicate a catchall.
133 CatchTypeInfo getCatchAllTypeInfo() override {
134 return CatchTypeInfo{nullptr, 0x40};
135 }
136
137 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
138 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
139 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
140 Address ThisPtr,
141 llvm::Type *StdTypeInfoPtrTy) override;
142
143 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
144 QualType SrcRecordTy) override;
145
146 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
147 QualType SrcRecordTy, QualType DestTy,
148 QualType DestRecordTy,
149 llvm::BasicBlock *CastEnd) override;
150
151 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
152 QualType SrcRecordTy,
153 QualType DestTy) override;
154
155 bool EmitBadCastCall(CodeGenFunction &CGF) override;
156 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
157 return false;
158 }
159
160 llvm::Value *
161 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
162 const CXXRecordDecl *ClassDecl,
163 const CXXRecordDecl *BaseClassDecl) override;
164
165 llvm::BasicBlock *
166 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
167 const CXXRecordDecl *RD) override;
168
169 llvm::BasicBlock *
170 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
171
172 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
173 const CXXRecordDecl *RD) override;
174
175 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
176
177 // Background on MSVC destructors
178 // ==============================
179 //
180 // Both Itanium and MSVC ABIs have destructor variants. The variant names
181 // roughly correspond in the following way:
182 // Itanium Microsoft
183 // Base -> no name, just ~Class
184 // Complete -> vbase destructor
185 // Deleting -> scalar deleting destructor
186 // vector deleting destructor
187 //
188 // The base and complete destructors are the same as in Itanium, although the
189 // complete destructor does not accept a VTT parameter when there are virtual
190 // bases. A separate mechanism involving vtordisps is used to ensure that
191 // virtual methods of destroyed subobjects are not called.
192 //
193 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
194 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
195 // pointer points to an array. The scalar deleting destructor assumes that
196 // bit 2 is zero, and therefore does not contain a loop.
197 //
198 // For virtual destructors, only one entry is reserved in the vftable, and it
199 // always points to the vector deleting destructor. The vector deleting
200 // destructor is the most general, so it can be used to destroy objects in
201 // place, delete single heap objects, or delete arrays.
202 //
203 // A TU defining a non-inline destructor is only guaranteed to emit a base
204 // destructor, and all of the other variants are emitted on an as-needed basis
205 // in COMDATs. Because a non-base destructor can be emitted in a TU that
206 // lacks a definition for the destructor, non-base destructors must always
207 // delegate to or alias the base destructor.
208
209 AddedStructorArgCounts
210 buildStructorSignature(GlobalDecl GD,
211 SmallVectorImpl<CanQualType> &ArgTys) override;
212
213 /// Non-base dtors should be emitted as delegating thunks in this ABI.
214 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
215 CXXDtorType DT) const override {
216 return DT != Dtor_Base;
217 }
218
219 void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
220 const CXXDestructorDecl *Dtor,
221 CXXDtorType DT) const override;
222
223 llvm::GlobalValue::LinkageTypes
224 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
225 CXXDtorType DT) const override;
226
227 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
228
229 const CXXRecordDecl *
230 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
231 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
232 MethodVFTableLocation ML =
233 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
234 // The vbases might be ordered differently in the final overrider object
235 // and the complete object, so the "this" argument may sometimes point to
236 // memory that has no particular type (e.g. past the complete object).
237 // In this case, we just use a generic pointer type.
238 // FIXME: might want to have a more precise type in the non-virtual
239 // multiple inheritance case.
240 if (ML.VBase || !ML.VFPtrOffset.isZero())
241 return nullptr;
242 }
243 return MD->getParent();
244 }
245
246 Address
247 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
248 Address This,
249 bool VirtualCall) override;
250
251 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
252 FunctionArgList &Params) override;
253
254 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
255
256 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
257 const CXXConstructorDecl *D,
258 CXXCtorType Type,
259 bool ForVirtualBase,
260 bool Delegating) override;
261
262 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
263 const CXXDestructorDecl *DD,
264 CXXDtorType Type,
265 bool ForVirtualBase,
266 bool Delegating) override;
267
268 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
269 CXXDtorType Type, bool ForVirtualBase,
270 bool Delegating, Address This,
271 QualType ThisTy) override;
272
273 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
274 llvm::GlobalVariable *VTable);
275
276 void emitVTableDefinitions(CodeGenVTables &CGVT,
277 const CXXRecordDecl *RD) override;
278
279 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
280 CodeGenFunction::VPtr Vptr) override;
281
282 /// Don't initialize vptrs if dynamic class
283 /// is marked with with the 'novtable' attribute.
284 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
285 return !VTableClass->hasAttr<MSNoVTableAttr>();
286 }
287
288 llvm::Constant *
289 getVTableAddressPoint(BaseSubobject Base,
290 const CXXRecordDecl *VTableClass) override;
291
292 llvm::Value *getVTableAddressPointInStructor(
293 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
294 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
295
296 llvm::Constant *
297 getVTableAddressPointForConstExpr(BaseSubobject Base,
298 const CXXRecordDecl *VTableClass) override;
299
300 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
301 CharUnits VPtrOffset) override;
302
303 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
304 Address This, llvm::Type *Ty,
305 SourceLocation Loc) override;
306
307 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
308 const CXXDestructorDecl *Dtor,
309 CXXDtorType DtorType, Address This,
310 DeleteOrMemberCallExpr E) override;
311
312 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
313 CallArgList &CallArgs) override {
314 assert(GD.getDtorType() == Dtor_Deleting &&
315 "Only deleting destructor thunks are available in this ABI");
316 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
317 getContext().IntTy);
318 }
319
320 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
321
322 llvm::GlobalVariable *
323 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
324 llvm::GlobalVariable::LinkageTypes Linkage);
325
326 llvm::GlobalVariable *
327 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
328 const CXXRecordDecl *DstRD) {
329 SmallString<256> OutName;
330 llvm::raw_svector_ostream Out(OutName);
331 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
332 StringRef MangledName = OutName.str();
333
334 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
335 return VDispMap;
336
337 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
338 unsigned NumEntries = 1 + SrcRD->getNumVBases();
339 SmallVector<llvm::Constant *, 4> Map(NumEntries,
340 llvm::UndefValue::get(CGM.IntTy));
341 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
342 bool AnyDifferent = false;
343 for (const auto &I : SrcRD->vbases()) {
344 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
345 if (!DstRD->isVirtuallyDerivedFrom(VBase))
346 continue;
347
348 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
349 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
350 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
351 AnyDifferent |= SrcVBIndex != DstVBIndex;
352 }
353 // This map would be useless, don't use it.
354 if (!AnyDifferent)
355 return nullptr;
356
357 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
358 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
359 llvm::GlobalValue::LinkageTypes Linkage =
360 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
361 ? llvm::GlobalValue::LinkOnceODRLinkage
362 : llvm::GlobalValue::InternalLinkage;
363 auto *VDispMap = new llvm::GlobalVariable(
364 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
365 /*Initializer=*/Init, MangledName);
366 return VDispMap;
367 }
368
369 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
370 llvm::GlobalVariable *GV) const;
371
372 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
373 GlobalDecl GD, bool ReturnAdjustment) override {
374 GVALinkage Linkage =
375 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
376
377 if (Linkage == GVA_Internal)
378 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
379 else if (ReturnAdjustment)
380 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
381 else
382 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
383 }
384
385 bool exportThunk() override { return false; }
386
387 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
388 const ThisAdjustment &TA) override;
389
390 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
391 const ReturnAdjustment &RA) override;
392
393 void EmitThreadLocalInitFuncs(
394 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
395 ArrayRef<llvm::Function *> CXXThreadLocalInits,
396 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
397
398 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
399 return false;
400 }
401 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
402 QualType LValType) override;
403
404 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
405 llvm::GlobalVariable *DeclPtr,
406 bool PerformInit) override;
407 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
408 llvm::FunctionCallee Dtor,
409 llvm::Constant *Addr) override;
410
411 // ==== Notes on array cookies =========
412 //
413 // MSVC seems to only use cookies when the class has a destructor; a
414 // two-argument usual array deallocation function isn't sufficient.
415 //
416 // For example, this code prints "100" and "1":
417 // struct A {
418 // char x;
419 // void *operator new[](size_t sz) {
420 // printf("%u\n", sz);
421 // return malloc(sz);
422 // }
423 // void operator delete[](void *p, size_t sz) {
424 // printf("%u\n", sz);
425 // free(p);
426 // }
427 // };
428 // int main() {
429 // A *p = new A[100];
430 // delete[] p;
431 // }
432 // Whereas it prints "104" and "104" if you give A a destructor.
433
434 bool requiresArrayCookie(const CXXDeleteExpr *expr,
435 QualType elementType) override;
436 bool requiresArrayCookie(const CXXNewExpr *expr) override;
437 CharUnits getArrayCookieSizeImpl(QualType type) override;
438 Address InitializeArrayCookie(CodeGenFunction &CGF,
439 Address NewPtr,
440 llvm::Value *NumElements,
441 const CXXNewExpr *expr,
442 QualType ElementType) override;
443 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
444 Address allocPtr,
445 CharUnits cookieSize) override;
446
447 friend struct MSRTTIBuilder;
448
449 bool isImageRelative() const {
450 return CGM.getTarget().getPointerWidth(/*AddrSpace=*/0) == 64;
451 }
452
453 // 5 routines for constructing the llvm types for MS RTTI structs.
454 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
455 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
456 TDTypeName += llvm::utostr(TypeInfoString.size());
457 llvm::StructType *&TypeDescriptorType =
458 TypeDescriptorTypeMap[TypeInfoString.size()];
459 if (TypeDescriptorType)
460 return TypeDescriptorType;
461 llvm::Type *FieldTypes[] = {
462 CGM.Int8PtrPtrTy,
463 CGM.Int8PtrTy,
464 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
465 TypeDescriptorType =
466 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
467 return TypeDescriptorType;
468 }
469
470 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
471 if (!isImageRelative())
472 return PtrType;
473 return CGM.IntTy;
474 }
475
476 llvm::StructType *getBaseClassDescriptorType() {
477 if (BaseClassDescriptorType)
478 return BaseClassDescriptorType;
479 llvm::Type *FieldTypes[] = {
480 getImageRelativeType(CGM.Int8PtrTy),
481 CGM.IntTy,
482 CGM.IntTy,
483 CGM.IntTy,
484 CGM.IntTy,
485 CGM.IntTy,
486 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
487 };
488 BaseClassDescriptorType = llvm::StructType::create(
489 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
490 return BaseClassDescriptorType;
491 }
492
493 llvm::StructType *getClassHierarchyDescriptorType() {
494 if (ClassHierarchyDescriptorType)
495 return ClassHierarchyDescriptorType;
496 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
497 ClassHierarchyDescriptorType = llvm::StructType::create(
498 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
499 llvm::Type *FieldTypes[] = {
500 CGM.IntTy,
501 CGM.IntTy,
502 CGM.IntTy,
503 getImageRelativeType(
504 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
505 };
506 ClassHierarchyDescriptorType->setBody(FieldTypes);
507 return ClassHierarchyDescriptorType;
508 }
509
510 llvm::StructType *getCompleteObjectLocatorType() {
511 if (CompleteObjectLocatorType)
512 return CompleteObjectLocatorType;
513 CompleteObjectLocatorType = llvm::StructType::create(
514 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
515 llvm::Type *FieldTypes[] = {
516 CGM.IntTy,
517 CGM.IntTy,
518 CGM.IntTy,
519 getImageRelativeType(CGM.Int8PtrTy),
520 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
521 getImageRelativeType(CompleteObjectLocatorType),
522 };
523 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
524 if (!isImageRelative())
525 FieldTypesRef = FieldTypesRef.drop_back();
526 CompleteObjectLocatorType->setBody(FieldTypesRef);
527 return CompleteObjectLocatorType;
528 }
529
530 llvm::GlobalVariable *getImageBase() {
531 StringRef Name = "__ImageBase";
532 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
533 return GV;
534
535 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
536 /*isConstant=*/true,
537 llvm::GlobalValue::ExternalLinkage,
538 /*Initializer=*/nullptr, Name);
539 CGM.setDSOLocal(GV);
540 return GV;
541 }
542
543 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
544 if (!isImageRelative())
545 return PtrVal;
546
547 if (PtrVal->isNullValue())
548 return llvm::Constant::getNullValue(CGM.IntTy);
549
550 llvm::Constant *ImageBaseAsInt =
551 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
552 llvm::Constant *PtrValAsInt =
553 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
554 llvm::Constant *Diff =
555 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
556 /*HasNUW=*/true, /*HasNSW=*/true);
557 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
558 }
559
560private:
561 MicrosoftMangleContext &getMangleContext() {
562 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
563 }
564
565 llvm::Constant *getZeroInt() {
566 return llvm::ConstantInt::get(CGM.IntTy, 0);
567 }
568
569 llvm::Constant *getAllOnesInt() {
570 return llvm::Constant::getAllOnesValue(CGM.IntTy);
571 }
572
573 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
574
575 void
576 GetNullMemberPointerFields(const MemberPointerType *MPT,
577 llvm::SmallVectorImpl<llvm::Constant *> &fields);
578
579 /// Shared code for virtual base adjustment. Returns the offset from
580 /// the vbptr to the virtual base. Optionally returns the address of the
581 /// vbptr itself.
582 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
583 Address Base,
584 llvm::Value *VBPtrOffset,
585 llvm::Value *VBTableOffset,
586 llvm::Value **VBPtr = nullptr);
587
588 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
589 Address Base,
590 int32_t VBPtrOffset,
591 int32_t VBTableOffset,
592 llvm::Value **VBPtr = nullptr) {
593 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
594 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
595 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
596 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
597 }
598
599 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
600 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
601 QualType SrcRecordTy);
602
603 /// Performs a full virtual base adjustment. Used to dereference
604 /// pointers to members of virtual bases.
605 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
606 const CXXRecordDecl *RD, Address Base,
607 llvm::Value *VirtualBaseAdjustmentOffset,
608 llvm::Value *VBPtrOffset /* optional */);
609
610 /// Emits a full member pointer with the fields common to data and
611 /// function member pointers.
612 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
613 bool IsMemberFunction,
614 const CXXRecordDecl *RD,
615 CharUnits NonVirtualBaseAdjustment,
616 unsigned VBTableIndex);
617
618 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
619 llvm::Constant *MP);
620
621 /// - Initialize all vbptrs of 'this' with RD as the complete type.
622 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
623
624 /// Caching wrapper around VBTableBuilder::enumerateVBTables().
625 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
626
627 /// Generate a thunk for calling a virtual member function MD.
628 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
629 const MethodVFTableLocation &ML);
630
631 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
632 CharUnits offset);
633
634public:
635 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
636
637 bool isZeroInitializable(const MemberPointerType *MPT) override;
638
639 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
640 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
641 return RD->hasAttr<MSInheritanceAttr>();
642 }
643
644 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
645
646 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
647 CharUnits offset) override;
648 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
649 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
650
651 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
652 llvm::Value *L,
653 llvm::Value *R,
654 const MemberPointerType *MPT,
655 bool Inequality) override;
656
657 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
658 llvm::Value *MemPtr,
659 const MemberPointerType *MPT) override;
660
661 llvm::Value *
662 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
663 Address Base, llvm::Value *MemPtr,
664 const MemberPointerType *MPT) override;
665
666 llvm::Value *EmitNonNullMemberPointerConversion(
667 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
668 CastKind CK, CastExpr::path_const_iterator PathBegin,
669 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
670 CGBuilderTy &Builder);
671
672 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
673 const CastExpr *E,
674 llvm::Value *Src) override;
675
676 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
677 llvm::Constant *Src) override;
678
679 llvm::Constant *EmitMemberPointerConversion(
680 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
681 CastKind CK, CastExpr::path_const_iterator PathBegin,
682 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
683
684 CGCallee
685 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
686 Address This, llvm::Value *&ThisPtrForCall,
687 llvm::Value *MemPtr,
688 const MemberPointerType *MPT) override;
689
690 void emitCXXStructor(GlobalDecl GD) override;
691
692 llvm::StructType *getCatchableTypeType() {
693 if (CatchableTypeType)
694 return CatchableTypeType;
695 llvm::Type *FieldTypes[] = {
696 CGM.IntTy, // Flags
697 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
698 CGM.IntTy, // NonVirtualAdjustment
699 CGM.IntTy, // OffsetToVBPtr
700 CGM.IntTy, // VBTableIndex
701 CGM.IntTy, // Size
702 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
703 };
704 CatchableTypeType = llvm::StructType::create(
705 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
706 return CatchableTypeType;
707 }
708
709 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
710 llvm::StructType *&CatchableTypeArrayType =
711 CatchableTypeArrayTypeMap[NumEntries];
712 if (CatchableTypeArrayType)
713 return CatchableTypeArrayType;
714
715 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
716 CTATypeName += llvm::utostr(NumEntries);
717 llvm::Type *CTType =
718 getImageRelativeType(getCatchableTypeType()->getPointerTo());
719 llvm::Type *FieldTypes[] = {
720 CGM.IntTy, // NumEntries
721 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
722 };
723 CatchableTypeArrayType =
724 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
725 return CatchableTypeArrayType;
726 }
727
728 llvm::StructType *getThrowInfoType() {
729 if (ThrowInfoType)
730 return ThrowInfoType;
731 llvm::Type *FieldTypes[] = {
732 CGM.IntTy, // Flags
733 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
734 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
735 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
736 };
737 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
738 "eh.ThrowInfo");
739 return ThrowInfoType;
740 }
741
742 llvm::FunctionCallee getThrowFn() {
743 // _CxxThrowException is passed an exception object and a ThrowInfo object
744 // which describes the exception.
745 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
746 llvm::FunctionType *FTy =
747 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
748 llvm::FunctionCallee Throw =
749 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
750 // _CxxThrowException is stdcall on 32-bit x86 platforms.
751 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
752 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
753 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
754 }
755 return Throw;
756 }
757
758 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
759 CXXCtorType CT);
760
761 llvm::Constant *getCatchableType(QualType T,
762 uint32_t NVOffset = 0,
763 int32_t VBPtrOffset = -1,
764 uint32_t VBIndex = 0);
765
766 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
767
768 llvm::GlobalVariable *getThrowInfo(QualType T) override;
769
770 std::pair<llvm::Value *, const CXXRecordDecl *>
771 LoadVTablePtr(CodeGenFunction &CGF, Address This,
772 const CXXRecordDecl *RD) override;
773
774 virtual bool
775 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
776
777private:
778 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
779 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
780 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
781 /// All the vftables that have been referenced.
782 VFTablesMapTy VFTablesMap;
783 VTablesMapTy VTablesMap;
784
785 /// This set holds the record decls we've deferred vtable emission for.
786 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
787
788
789 /// All the vbtables which have been referenced.
790 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
791
792 /// Info on the global variable used to guard initialization of static locals.
793 /// The BitIndex field is only used for externally invisible declarations.
794 struct GuardInfo {
795 GuardInfo() : Guard(nullptr), BitIndex(0) {}
796 llvm::GlobalVariable *Guard;
797 unsigned BitIndex;
798 };
799
800 /// Map from DeclContext to the current guard variable. We assume that the
801 /// AST is visited in source code order.
802 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
803 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
804 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
805
806 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
807 llvm::StructType *BaseClassDescriptorType;
808 llvm::StructType *ClassHierarchyDescriptorType;
809 llvm::StructType *CompleteObjectLocatorType;
810
811 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
812
813 llvm::StructType *CatchableTypeType;
814 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
815 llvm::StructType *ThrowInfoType;
816};
817
818}
819
820CGCXXABI::RecordArgABI
821MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
822 // Use the default C calling convention rules for things that can be passed in
823 // registers, i.e. non-trivially copyable records or records marked with
824 // [[trivial_abi]].
825 if (RD->canPassInRegisters())
826 return RAA_Default;
827
828 switch (CGM.getTarget().getTriple().getArch()) {
829 default:
830 // FIXME: Implement for other architectures.
831 return RAA_Indirect;
832
833 case llvm::Triple::thumb:
834 // Pass things indirectly for now because it is simple.
835 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
836 // copy ctor.
837 return RAA_Indirect;
838
839 case llvm::Triple::x86: {
840 // If the argument has *required* alignment greater than four bytes, pass
841 // it indirectly. Prior to MSVC version 19.14, passing overaligned
842 // arguments was not supported and resulted in a compiler error. In 19.14
843 // and later versions, such arguments are now passed indirectly.
844 TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
845 if (Info.AlignIsRequired && Info.Align > 4)
846 return RAA_Indirect;
847
848 // If C++ prohibits us from making a copy, construct the arguments directly
849 // into argument memory.
850 return RAA_DirectInMemory;
851 }
852
853 case llvm::Triple::x86_64:
854 case llvm::Triple::aarch64:
855 return RAA_Indirect;
856 }
857
858 llvm_unreachable("invalid enum");
859}
860
861void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
862 const CXXDeleteExpr *DE,
863 Address Ptr,
864 QualType ElementType,
865 const CXXDestructorDecl *Dtor) {
866 // FIXME: Provide a source location here even though there's no
867 // CXXMemberCallExpr for dtor call.
868 bool UseGlobalDelete = DE->isGlobalDelete();
869 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
870 llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
871 if (UseGlobalDelete)
872 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
873}
874
875void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
876 llvm::Value *Args[] = {
877 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
878 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
879 llvm::FunctionCallee Fn = getThrowFn();
880 if (isNoReturn)
881 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
882 else
883 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
884}
885
886void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
887 const CXXCatchStmt *S) {
888 // In the MS ABI, the runtime handles the copy, and the catch handler is
889 // responsible for destruction.
890 VarDecl *CatchParam = S->getExceptionDecl();
891 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
892 llvm::CatchPadInst *CPI =
893 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
894 CGF.CurrentFuncletPad = CPI;
895
896 // If this is a catch-all or the catch parameter is unnamed, we don't need to
897 // emit an alloca to the object.
898 if (!CatchParam || !CatchParam->getDeclName()) {
899 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
900 return;
901 }
902
903 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
904 CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
905 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
906 CGF.EmitAutoVarCleanups(var);
907}
908
909/// We need to perform a generic polymorphic operation (like a typeid
910/// or a cast), which requires an object with a vfptr. Adjust the
911/// address to point to an object with a vfptr.
912std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
913MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
914 QualType SrcRecordTy) {
915 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
916 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
917 const ASTContext &Context = getContext();
918
919 // If the class itself has a vfptr, great. This check implicitly
920 // covers non-virtual base subobjects: a class with its own virtual
921 // functions would be a candidate to be a primary base.
922 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
923 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
924 SrcDecl);
925
926 // Okay, one of the vbases must have a vfptr, or else this isn't
927 // actually a polymorphic class.
928 const CXXRecordDecl *PolymorphicBase = nullptr;
929 for (auto &Base : SrcDecl->vbases()) {
930 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
931 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
932 PolymorphicBase = BaseDecl;
933 break;
934 }
935 }
936 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
937
938 llvm::Value *Offset =
939 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
940 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
941 Value.getElementType(), Value.getPointer(), Offset);
942 CharUnits VBaseAlign =
943 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
944 return std::make_tuple(Address(Ptr, VBaseAlign), Offset, PolymorphicBase);
945}
946
947bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
948 QualType SrcRecordTy) {
949 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
950 return IsDeref &&
951 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
952}
953
954static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
955 llvm::Value *Argument) {
956 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
957 llvm::FunctionType *FTy =
958 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
959 llvm::Value *Args[] = {Argument};
960 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
961 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
962}
963
964void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
965 llvm::CallBase *Call =
966 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
967 Call->setDoesNotReturn();
968 CGF.Builder.CreateUnreachable();
969}
970
971llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
972 QualType SrcRecordTy,
973 Address ThisPtr,
974 llvm::Type *StdTypeInfoPtrTy) {
975 std::tie(ThisPtr, std::ignore, std::ignore) =
976 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
977 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
978 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
979}
980
981bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
982 QualType SrcRecordTy) {
983 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
984 return SrcIsPtr &&
985 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
986}
987
988llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
989 CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
990 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
991 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
992
993 llvm::Value *SrcRTTI =
994 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
995 llvm::Value *DestRTTI =
996 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
997
998 llvm::Value *Offset;
999 std::tie(This, Offset, std::ignore) =
1000 performBaseAdjustment(CGF, This, SrcRecordTy);
1001 llvm::Value *ThisPtr = This.getPointer();
1002 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1003
1004 // PVOID __RTDynamicCast(
1005 // PVOID inptr,
1006 // LONG VfDelta,
1007 // PVOID SrcType,
1008 // PVOID TargetType,
1009 // BOOL isReference)
1010 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1011 CGF.Int8PtrTy, CGF.Int32Ty};
1012 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1013 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1014 "__RTDynamicCast");
1015 llvm::Value *Args[] = {
1016 ThisPtr, Offset, SrcRTTI, DestRTTI,
1017 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1018 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
1019 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1020}
1021
1022llvm::Value *
1023MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1024 QualType SrcRecordTy,
1025 QualType DestTy) {
1026 std::tie(Value, std::ignore, std::ignore) =
1027 performBaseAdjustment(CGF, Value, SrcRecordTy);
1028
1029 // PVOID __RTCastToVoid(
1030 // PVOID inptr)
1031 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1032 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1033 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1034 "__RTCastToVoid");
1035 llvm::Value *Args[] = {Value.getPointer()};
1036 return CGF.EmitRuntimeCall(Function, Args);
1037}
1038
1039bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1040 return false;
1041}
1042
1043llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1044 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1045 const CXXRecordDecl *BaseClassDecl) {
1046 const ASTContext &Context = getContext();
1047 int64_t VBPtrChars =
1048 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1049 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1050 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1051 CharUnits VBTableChars =
1052 IntSize *
1053 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1054 llvm::Value *VBTableOffset =
1055 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1056
1057 llvm::Value *VBPtrToNewBase =
1058 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1059 VBPtrToNewBase =
1060 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1061 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1062}
1063
1064bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1065 return isa<CXXConstructorDecl>(GD.getDecl());
1066}
1067
1068static bool isDeletingDtor(GlobalDecl GD) {
1069 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1070 GD.getDtorType() == Dtor_Deleting;
1071}
1072
1073bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1074 return isDeletingDtor(GD);
1075}
1076
1077static bool isTrivialForAArch64MSVC(const CXXRecordDecl *RD) {
1078 // For AArch64, we use the C++14 definition of an aggregate, so we also
1079 // check for:
1080 // No private or protected non static data members.
1081 // No base classes
1082 // No virtual functions
1083 // Additionally, we need to ensure that there is a trivial copy assignment
1084 // operator, a trivial destructor and no user-provided constructors.
1085 if (RD->hasProtectedFields() || RD->hasPrivateFields())
1086 return false;
1087 if (RD->getNumBases() > 0)
1088 return false;
1089 if (RD->isPolymorphic())
1090 return false;
1091 if (RD->hasNonTrivialCopyAssignment())
1092 return false;
1093 for (const CXXConstructorDecl *Ctor : RD->ctors())
1094 if (Ctor->isUserProvided())
1095 return false;
1096 if (RD->hasNonTrivialDestructor())
1097 return false;
1098 return true;
1099}
1100
1101bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1102 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1103 if (!RD)
1104 return false;
1105
1106 // Normally, the C++ concept of "is trivially copyable" is used to determine
1107 // if a struct can be returned directly. However, as MSVC and the language
1108 // have evolved, the definition of "trivially copyable" has changed, while the
1109 // ABI must remain stable. AArch64 uses the C++14 concept of an "aggregate",
1110 // while other ISAs use the older concept of "plain old data".
1111 bool isTrivialForABI = RD->isPOD();
1112 bool isAArch64 = CGM.getTarget().getTriple().isAArch64();
1113 if (isAArch64)
1114 isTrivialForABI = RD->canPassInRegisters() && isTrivialForAArch64MSVC(RD);
1115
1116 // MSVC always returns structs indirectly from C++ instance methods.
1117 bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
1118
1119 if (isIndirectReturn) {
1120 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1121 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1122
1123 // MSVC always passes `this` before the `sret` parameter.
1124 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1125
1126 // On AArch64, use the `inreg` attribute if the object is considered to not
1127 // be trivially copyable, or if this is an instance method struct return.
1128 FI.getReturnInfo().setInReg(isAArch64);
1129
1130 return true;
1131 }
1132
1133 // Otherwise, use the C ABI rules.
1134 return false;
1135}
1136
1137llvm::BasicBlock *
1138MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1139 const CXXRecordDecl *RD) {
1140 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1141 assert(IsMostDerivedClass &&
1142 "ctor for a class with virtual bases must have an implicit parameter");
1143 llvm::Value *IsCompleteObject =
1144 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1145
1146 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1147 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1148 CGF.Builder.CreateCondBr(IsCompleteObject,
1149 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1150
1151 CGF.EmitBlock(CallVbaseCtorsBB);
1152
1153 // Fill in the vbtable pointers here.
1154 EmitVBPtrStores(CGF, RD);
1155
1156 // CGF will put the base ctor calls in this basic block for us later.
1157
1158 return SkipVbaseCtorsBB;
1159}
1160
1161llvm::BasicBlock *
1162MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1163 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1164 assert(IsMostDerivedClass &&
1165 "ctor for a class with virtual bases must have an implicit parameter");
1166 llvm::Value *IsCompleteObject =
1167 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1168
1169 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1170 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1171 CGF.Builder.CreateCondBr(IsCompleteObject,
1172 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1173
1174 CGF.EmitBlock(CallVbaseDtorsBB);
1175 // CGF will put the base dtor calls in this basic block for us later.
1176
1177 return SkipVbaseDtorsBB;
1178}
1179
1180void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1181 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1182 // In most cases, an override for a vbase virtual method can adjust
1183 // the "this" parameter by applying a constant offset.
1184 // However, this is not enough while a constructor or a destructor of some
1185 // class X is being executed if all the following conditions are met:
1186 // - X has virtual bases, (1)
1187 // - X overrides a virtual method M of a vbase Y, (2)
1188 // - X itself is a vbase of the most derived class.
1189 //
1190 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1191 // which holds the extra amount of "this" adjustment we must do when we use
1192 // the X vftables (i.e. during X ctor or dtor).
1193 // Outside the ctors and dtors, the values of vtorDisps are zero.
1194
1195 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1196 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1197 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1198 CGBuilderTy &Builder = CGF.Builder;
1199
1200 unsigned AS = getThisAddress(CGF).getAddressSpace();
1201 llvm::Value *Int8This = nullptr; // Initialize lazily.
1202
1203 for (const CXXBaseSpecifier &S : RD->vbases()) {
1204 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1205 auto I = VBaseMap.find(VBase);
1206 assert(I != VBaseMap.end());
1207 if (!I->second.hasVtorDisp())
1208 continue;
1209
1210 llvm::Value *VBaseOffset =
1211 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1212 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1213
1214 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1215 llvm::Value *VtorDispValue = Builder.CreateSub(
1216 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1217 "vtordisp.value");
1218 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1219
1220 if (!Int8This)
1221 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1222 CGF.Int8Ty->getPointerTo(AS));
1223 llvm::Value *VtorDispPtr =
1224 Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
1225 // vtorDisp is always the 32-bits before the vbase in the class layout.
1226 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1227 VtorDispPtr = Builder.CreateBitCast(
1228 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1229
1230 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1231 CharUnits::fromQuantity(4));
1232 }
1233}
1234
1235static bool hasDefaultCXXMethodCC(ASTContext &Context,
1236 const CXXMethodDecl *MD) {
1237 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1238 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1239 CallingConv ActualCallingConv =
1240 MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1241 return ExpectedCallingConv == ActualCallingConv;
1242}
1243
1244void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1245 // There's only one constructor type in this ABI.
1246 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1247
1248 // Exported default constructors either have a simple call-site where they use
1249 // the typical calling convention and have a single 'this' pointer for an
1250 // argument -or- they get a wrapper function which appropriately thunks to the
1251 // real default constructor. This thunk is the default constructor closure.
1252 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
1253 D->isDefined()) {
1254 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1255 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1256 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1257 CGM.setGVProperties(Fn, D);
1258 }
1259 }
1260}
1261
1262void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1263 const CXXRecordDecl *RD) {
1264 Address This = getThisAddress(CGF);
1265 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1266 const ASTContext &Context = getContext();
1267 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1268
1269 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1270 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1271 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1272 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1273 const ASTRecordLayout &SubobjectLayout =
1274 Context.getASTRecordLayout(VBT->IntroducingObject);
1275 CharUnits Offs = VBT->NonVirtualOffset;
1276 Offs += SubobjectLayout.getVBPtrOffset();
1277 if (VBT->getVBaseWithVPtr())
1278 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1279 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1280 llvm::Value *GVPtr =
1281 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1282 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1283 "vbptr." + VBT->ObjectWithVPtr->getName());
1284 CGF.Builder.CreateStore(GVPtr, VBPtr);
1285 }
1286}
1287
1288CGCXXABI::AddedStructorArgCounts
1289MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1290 SmallVectorImpl<CanQualType> &ArgTys) {
1291 AddedStructorArgCounts Added;
1292 // TODO: 'for base' flag
1293 if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1294 GD.getDtorType() == Dtor_Deleting) {
1295 // The scalar deleting destructor takes an implicit int parameter.
1296 ArgTys.push_back(getContext().IntTy);
1297 ++Added.Suffix;
1298 }
1299 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1300 if (!CD)
1301 return Added;
1302
1303 // All parameters are already in place except is_most_derived, which goes
1304 // after 'this' if it's variadic and last if it's not.
1305
1306 const CXXRecordDecl *Class = CD->getParent();
1307 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1308 if (Class->getNumVBases()) {
1309 if (FPT->isVariadic()) {
1310 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1311 ++Added.Prefix;
1312 } else {
1313 ArgTys.push_back(getContext().IntTy);
1314 ++Added.Suffix;
1315 }
1316 }
1317
1318 return Added;
1319}
1320
1321void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1322 const CXXDestructorDecl *Dtor,
1323 CXXDtorType DT) const {
1324 // Deleting destructor variants are never imported or exported. Give them the
1325 // default storage class.
1326 if (DT == Dtor_Deleting) {
1327 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1328 } else {
1329 const NamedDecl *ND = Dtor;
1330 CGM.setDLLImportDLLExport(GV, ND);
1331 }
1332}
1333
1334llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1335 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1336 // Internal things are always internal, regardless of attributes. After this,
1337 // we know the thunk is externally visible.
1338 if (Linkage == GVA_Internal)
1339 return llvm::GlobalValue::InternalLinkage;
1340
1341 switch (DT) {
1342 case Dtor_Base:
1343 // The base destructor most closely tracks the user-declared constructor, so
1344 // we delegate back to the normal declarator case.
1345 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
1346 /*IsConstantVariable=*/false);
1347 case Dtor_Complete:
1348 // The complete destructor is like an inline function, but it may be
1349 // imported and therefore must be exported as well. This requires changing
1350 // the linkage if a DLL attribute is present.
1351 if (Dtor->hasAttr<DLLExportAttr>())
1352 return llvm::GlobalValue::WeakODRLinkage;
1353 if (Dtor->hasAttr<DLLImportAttr>())
1354 return llvm::GlobalValue::AvailableExternallyLinkage;
1355 return llvm::GlobalValue::LinkOnceODRLinkage;
1356 case Dtor_Deleting:
1357 // Deleting destructors are like inline functions. They have vague linkage
1358 // and are emitted everywhere they are used. They are internal if the class
1359 // is internal.
1360 return llvm::GlobalValue::LinkOnceODRLinkage;
1361 case Dtor_Comdat:
1362 llvm_unreachable("MS C++ ABI does not support comdat dtors");
1363 }
1364 llvm_unreachable("invalid dtor type");
1365}
1366
1367void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1368 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1369 // other destructor variants are delegating thunks.
1370 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1371
1372 // If the class is dllexported, emit the complete (vbase) destructor wherever
1373 // the base dtor is emitted.
1374 // FIXME: To match MSVC, this should only be done when the class is exported
1375 // with -fdllexport-inlines enabled.
1376 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
1377 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1378}
1379
1380CharUnits
1381MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1382 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1383
1384 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1385 // Complete destructors take a pointer to the complete object as a
1386 // parameter, thus don't need this adjustment.
1387 if (GD.getDtorType() == Dtor_Complete)
1388 return CharUnits();
1389
1390 // There's no Dtor_Base in vftable but it shares the this adjustment with
1391 // the deleting one, so look it up instead.
1392 GD = GlobalDecl(DD, Dtor_Deleting);
1393 }
1394
1395 MethodVFTableLocation ML =
1396 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1397 CharUnits Adjustment = ML.VFPtrOffset;
1398
1399 // Normal virtual instance methods need to adjust from the vfptr that first
1400 // defined the virtual method to the virtual base subobject, but destructors
1401 // do not. The vector deleting destructor thunk applies this adjustment for
1402 // us if necessary.
1403 if (isa<CXXDestructorDecl>(MD))
1404 Adjustment = CharUnits::Zero();
1405
1406 if (ML.VBase) {
1407 const ASTRecordLayout &DerivedLayout =
1408 getContext().getASTRecordLayout(MD->getParent());
1409 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1410 }
1411
1412 return Adjustment;
1413}
1414
1415Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1416 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1417 bool VirtualCall) {
1418 if (!VirtualCall) {
1419 // If the call of a virtual function is not virtual, we just have to
1420 // compensate for the adjustment the virtual function does in its prologue.
1421 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1422 if (Adjustment.isZero())
1423 return This;
1424
1425 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1426 assert(Adjustment.isPositive());
1427 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1428 }
1429
1430 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1431
1432 GlobalDecl LookupGD = GD;
1433 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1434 // Complete dtors take a pointer to the complete object,
1435 // thus don't need adjustment.
1436 if (GD.getDtorType() == Dtor_Complete)
1437 return This;
1438
1439 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1440 // with the base one, so look up the deleting one instead.
1441 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1442 }
1443 MethodVFTableLocation ML =
1444 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1445
1446 CharUnits StaticOffset = ML.VFPtrOffset;
1447
1448 // Base destructors expect 'this' to point to the beginning of the base
1449 // subobject, not the first vfptr that happens to contain the virtual dtor.
1450 // However, we still need to apply the virtual base adjustment.
1451 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1452 StaticOffset = CharUnits::Zero();
1453
1454 Address Result = This;
1455 if (ML.VBase) {
1456 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1457
1458 const CXXRecordDecl *Derived = MD->getParent();
1459 const CXXRecordDecl *VBase = ML.VBase;
1460 llvm::Value *VBaseOffset =
1461 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1462 llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
1463 Result.getElementType(), Result.getPointer(), VBaseOffset);
1464 CharUnits VBaseAlign =
1465 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1466 Result = Address(VBasePtr, VBaseAlign);
1467 }
1468 if (!StaticOffset.isZero()) {
1469 assert(StaticOffset.isPositive());
1470 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1471 if (ML.VBase) {
1472 // Non-virtual adjustment might result in a pointer outside the allocated
1473 // object, e.g. if the final overrider class is laid out after the virtual
1474 // base that declares a method in the most derived class.
1475 // FIXME: Update the code that emits this adjustment in thunks prologues.
1476 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1477 } else {
1478 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1479 }
1480 }
1481 return Result;
1482}
1483
1484void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1485 QualType &ResTy,
1486 FunctionArgList &Params) {
1487 ASTContext &Context = getContext();
1488 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1489 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1490 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1491 auto *IsMostDerived = ImplicitParamDecl::Create(
1492 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1493 &Context.Idents.get("is_most_derived"), Context.IntTy,
1494 ImplicitParamDecl::Other);
1495 // The 'most_derived' parameter goes second if the ctor is variadic and last
1496 // if it's not. Dtors can't be variadic.
1497 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1498 if (FPT->isVariadic())
1499 Params.insert(Params.begin() + 1, IsMostDerived);
1500 else
1501 Params.push_back(IsMostDerived);
1502 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1503 } else if (isDeletingDtor(CGF.CurGD)) {
1504 auto *ShouldDelete = ImplicitParamDecl::Create(
1505 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1506 &Context.Idents.get("should_call_delete"), Context.IntTy,
1507 ImplicitParamDecl::Other);
1508 Params.push_back(ShouldDelete);
1509 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1510 }
1511}
1512
1513void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1514 // Naked functions have no prolog.
1515 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1516 return;
1517
1518 // Overridden virtual methods of non-primary bases need to adjust the incoming
1519 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1520 // sizeof(void*) to adjust from B* to C*:
1521 // struct A { virtual void a(); };
1522 // struct B { virtual void b(); };
1523 // struct C : A, B { virtual void b(); };
1524 //
1525 // Leave the value stored in the 'this' alloca unadjusted, so that the
1526 // debugger sees the unadjusted value. Microsoft debuggers require this, and
1527 // will apply the ThisAdjustment in the method type information.
1528 // FIXME: Do something better for DWARF debuggers, which won't expect this,
1529 // without making our codegen depend on debug info settings.
1530 llvm::Value *This = loadIncomingCXXThis(CGF);
1531 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1532 if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1533 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1534 if (!Adjustment.isZero()) {
1535 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1536 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1537 *thisTy = This->getType();
1538 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1539 assert(Adjustment.isPositive());
1540 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1541 -Adjustment.getQuantity());
1542 This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
1543 }
1544 }
1545 setCXXABIThisValue(CGF, This);
1546
1547 // If this is a function that the ABI specifies returns 'this', initialize
1548 // the return slot to 'this' at the start of the function.
1549 //
1550 // Unlike the setting of return types, this is done within the ABI
1551 // implementation instead of by clients of CGCXXABI because:
1552 // 1) getThisValue is currently protected
1553 // 2) in theory, an ABI could implement 'this' returns some other way;
1554 // HasThisReturn only specifies a contract, not the implementation
1555 if (HasThisReturn(CGF.CurGD))
1556 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1557 else if (hasMostDerivedReturn(CGF.CurGD))
1558 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1559 CGF.ReturnValue);
1560
1561 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1562 assert(getStructorImplicitParamDecl(CGF) &&
1563 "no implicit parameter for a constructor with virtual bases?");
1564 getStructorImplicitParamValue(CGF)
1565 = CGF.Builder.CreateLoad(
1566 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1567 "is_most_derived");
1568 }
1569
1570 if (isDeletingDtor(CGF.CurGD)) {
1571 assert(getStructorImplicitParamDecl(CGF) &&
1572 "no implicit parameter for a deleting destructor?");
1573 getStructorImplicitParamValue(CGF)
1574 = CGF.Builder.CreateLoad(
1575 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1576 "should_call_delete");
1577 }
1578}
1579
1580CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1581 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1582 bool ForVirtualBase, bool Delegating) {
1583 assert(Type == Ctor_Complete || Type == Ctor_Base);
1584
1585 // Check if we need a 'most_derived' parameter.
1586 if (!D->getParent()->getNumVBases())
1587 return AddedStructorArgs{};
1588
1589 // Add the 'most_derived' argument second if we are variadic or last if not.
1590 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1591 llvm::Value *MostDerivedArg;
1592 if (Delegating) {
1593 MostDerivedArg = getStructorImplicitParamValue(CGF);
1594 } else {
1595 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1596 }
1597 if (FPT->isVariadic()) {
1598 return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1599 }
1600 return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1601}
1602
1603llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1604 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
1605 bool ForVirtualBase, bool Delegating) {
1606 return nullptr;
1607}
1608
1609void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1610 const CXXDestructorDecl *DD,
1611 CXXDtorType Type, bool ForVirtualBase,
1612 bool Delegating, Address This,
1613 QualType ThisTy) {
1614 // Use the base destructor variant in place of the complete destructor variant
1615 // if the class has no virtual bases. This effectively implements some of the
1616 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1617 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
1618 Type = Dtor_Base;
1619
1620 GlobalDecl GD(DD, Type);
1621 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1622
1623 if (DD->isVirtual()) {
1624 assert(Type != CXXDtorType::Dtor_Deleting &&
1625 "The deleting destructor should only be called via a virtual call");
1626 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1627 This, false);
1628 }
1629
1630 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1631 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1632 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1633 }
1634
1635 llvm::Value *Implicit =
1636 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1637 Delegating); // = nullptr
1638 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1639 /*ImplicitParam=*/Implicit,
1640 /*ImplicitParamTy=*/QualType(), nullptr);
1641 if (BaseDtorEndBB) {
1642 // Complete object handler should continue to be the remaining
1643 CGF.Builder.CreateBr(BaseDtorEndBB);
1644 CGF.EmitBlock(BaseDtorEndBB);
1645 }
1646}
1647
1648void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1649 const CXXRecordDecl *RD,
1650 llvm::GlobalVariable *VTable) {
1651 if (!CGM.getCodeGenOpts().LTOUnit)
1652 return;
1653
1654 // TODO: Should VirtualFunctionElimination also be supported here?
1655 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1656 if (CGM.getCodeGenOpts().WholeProgramVTables) {
1657 llvm::DenseSet<const CXXRecordDecl *> Visited;
1658 llvm::GlobalObject::VCallVisibility TypeVis =
1659 CGM.GetVCallVisibilityLevel(RD, Visited);
1660 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1661 VTable->setVCallVisibilityMetadata(TypeVis);
1662 }
1663
1664 // The location of the first virtual function pointer in the virtual table,
1665 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1666 // disabled, or sizeof(void*) if RTTI is enabled.
1667 CharUnits AddressPoint =
1668 getContext().getLangOpts().RTTIData
1669 ? getContext().toCharUnitsFromBits(
1670 getContext().getTargetInfo().getPointerWidth(0))
1671 : CharUnits::Zero();
1672
1673 if (Info.PathToIntroducingObject.empty()) {
1674 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1675 return;
1676 }
1677
1678 // Add a bitset entry for the least derived base belonging to this vftable.
1679 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1680 Info.PathToIntroducingObject.back());
1681
1682 // Add a bitset entry for each derived class that is laid out at the same
1683 // offset as the least derived base.
1684 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1685 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1686 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1687
1688 const ASTRecordLayout &Layout =
1689 getContext().getASTRecordLayout(DerivedRD);
1690 CharUnits Offset;
1691 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1692 if (VBI == Layout.getVBaseOffsetsMap().end())
1693 Offset = Layout.getBaseClassOffset(BaseRD);
1694 else
1695 Offset = VBI->second.VBaseOffset;
1696 if (!Offset.isZero())
1697 return;
1698 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1699 }
1700
1701 // Finally do the same for the most derived class.
1702 if (Info.FullOffsetInMDC.isZero())
1703 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1704}
1705
1706void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1707 const CXXRecordDecl *RD) {
1708 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1709 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1710
1711 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1712 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1713 if (VTable->hasInitializer())
1714 continue;
1715
1716 const VTableLayout &VTLayout =
1717 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1718
1719 llvm::Constant *RTTI = nullptr;
1720 if (any_of(VTLayout.vtable_components(),
1721 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1722 RTTI = getMSCompleteObjectLocator(RD, *Info);
1723
1724 ConstantInitBuilder builder(CGM);
1725 auto components = builder.beginStruct();
1726 CGVT.createVTableInitializer(components, VTLayout, RTTI,
1727 VTable->hasLocalLinkage());
1728 components.finishAndSetAsInitializer(VTable);
1729
1730 emitVTableTypeMetadata(*Info, RD, VTable);
1731 }
1732}
1733
1734bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1735 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1736 return Vptr.NearestVBase != nullptr;
1737}
1738
1739llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1740 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1741 const CXXRecordDecl *NearestVBase) {
1742 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1743 if (!VTableAddressPoint) {
1744 assert(Base.getBase()->getNumVBases() &&
1745 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1746 }
1747 return VTableAddressPoint;
1748}
1749
1750static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1751 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1752 SmallString<256> &Name) {
1753 llvm::raw_svector_ostream Out(Name);
1754 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1755}
1756
1757llvm::Constant *
1758MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1759 const CXXRecordDecl *VTableClass) {
1760 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1761 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1762 return VFTablesMap[ID];
1763}
1764
1765llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1766 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1767 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1768 assert(VFTable && "Couldn't find a vftable for the given base?");
1769 return VFTable;
1770}
1771
1772llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1773 CharUnits VPtrOffset) {
1774 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1775 // shouldn't be used in the given record type. We want to cache this result in
1776 // VFTablesMap, thus a simple zero check is not sufficient.
1777
1778 VFTableIdTy ID(RD, VPtrOffset);
1779 VTablesMapTy::iterator I;
1780 bool Inserted;
1781 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1782 if (!Inserted)
1783 return I->second;
1784
1785 llvm::GlobalVariable *&VTable = I->second;
1786
1787 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1788 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1789
1790 if (DeferredVFTables.insert(RD).second) {
1791 // We haven't processed this record type before.
1792 // Queue up this vtable for possible deferred emission.
1793 CGM.addDeferredVTable(RD);
1794
1795#ifndef NDEBUG
1796 // Create all the vftables at once in order to make sure each vftable has
1797 // a unique mangled name.
1798 llvm::StringSet<> ObservedMangledNames;
1799 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1800 SmallString<256> Name;
1801 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1802 if (!ObservedMangledNames.insert(Name.str()).second)
1803 llvm_unreachable("Already saw this mangling before?");
1804 }
1805#endif
1806 }
1807
1808 const std::unique_ptr<VPtrInfo> *VFPtrI = std::find_if(
1809 VFPtrs.begin(), VFPtrs.end(), [&](const std::unique_ptr<VPtrInfo>& VPI) {
1810 return VPI->FullOffsetInMDC == VPtrOffset;
1811 });
1812 if (VFPtrI == VFPtrs.end()) {
1813 VFTablesMap[ID] = nullptr;
1814 return nullptr;
1815 }
1816 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1817
1818 SmallString<256> VFTableName;
1819 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1820
1821 // Classes marked __declspec(dllimport) need vftables generated on the
1822 // import-side in order to support features like constexpr. No other
1823 // translation unit relies on the emission of the local vftable, translation
1824 // units are expected to generate them as needed.
1825 //
1826 // Because of this unique behavior, we maintain this logic here instead of
1827 // getVTableLinkage.
1828 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1829 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1830 : CGM.getVTableLinkage(RD);
1831 bool VFTableComesFromAnotherTU =
1832 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1833 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1834 bool VTableAliasIsRequred =
1835 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1836
1837 if (llvm::GlobalValue *VFTable =
1838 CGM.getModule().getNamedGlobal(VFTableName)) {
1839 VFTablesMap[ID] = VFTable;
1840 VTable = VTableAliasIsRequred
1841 ? cast<llvm::GlobalVariable>(
1842 cast<llvm::GlobalAlias>(VFTable)->getBaseObject())
1843 : cast<llvm::GlobalVariable>(VFTable);
1844 return VTable;
1845 }
1846
1847 const VTableLayout &VTLayout =
1848 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1849 llvm::GlobalValue::LinkageTypes VTableLinkage =
1850 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1851
1852 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1853
1854 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1855
1856 // Create a backing variable for the contents of VTable. The VTable may
1857 // or may not include space for a pointer to RTTI data.
1858 llvm::GlobalValue *VFTable;
1859 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1860 /*isConstant=*/true, VTableLinkage,
1861 /*Initializer=*/nullptr, VTableName);
1862 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1863
1864 llvm::Comdat *C = nullptr;
1865 if (!VFTableComesFromAnotherTU &&
1866 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1867 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1868 VTableAliasIsRequred)))
1869 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1870
1871 // Only insert a pointer into the VFTable for RTTI data if we are not
1872 // importing it. We never reference the RTTI data directly so there is no
1873 // need to make room for it.
1874 if (VTableAliasIsRequred) {
1875 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1876 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1877 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1878 // Create a GEP which points just after the first entry in the VFTable,
1879 // this should be the location of the first virtual method.
1880 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1881 VTable->getValueType(), VTable, GEPIndices);
1882 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1883 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1884 if (C)
1885 C->setSelectionKind(llvm::Comdat::Largest);
1886 }
1887 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1888 /*AddressSpace=*/0, VFTableLinkage,
1889 VFTableName.str(), VTableGEP,
1890 &CGM.getModule());
1891 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1892 } else {
1893 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1894 // be referencing any RTTI data.
1895 // The GlobalVariable will end up being an appropriate definition of the
1896 // VFTable.
1897 VFTable = VTable;
1898 }
1899 if (C)
1900 VTable->setComdat(C);
1901
1902 if (RD->hasAttr<DLLExportAttr>())
1903 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1904
1905 VFTablesMap[ID] = VFTable;
1906 return VTable;
1907}
1908
1909CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1910 GlobalDecl GD,
1911 Address This,
1912 llvm::Type *Ty,
1913 SourceLocation Loc) {
1914 CGBuilderTy &Builder = CGF.Builder;
1915
1916 Ty = Ty->getPointerTo();
1917 Address VPtr =
1918 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1919
1920 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1921 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
1922 MethodDecl->getParent());
1923
1924 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1925 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
1926
1927 // Compute the identity of the most derived class whose virtual table is
1928 // located at the MethodVFTableLocation ML.
1929 auto getObjectWithVPtr = [&] {
1930 return llvm::find_if(VFTContext.getVFPtrOffsets(
1931 ML.VBase ? ML.VBase : MethodDecl->getParent()),
1932 [&](const std::unique_ptr<VPtrInfo> &Info) {
1933 return Info->FullOffsetInMDC == ML.VFPtrOffset;
1934 })
1935 ->get()
1936 ->ObjectWithVPtr;
1937 };