clang 19.0.0git
MicrosoftCXXABI.cpp
Go to the documentation of this file.
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 "ABIInfo.h"
17#include "CGCXXABI.h"
18#include "CGCleanup.h"
19#include "CGVTables.h"
20#include "CodeGenModule.h"
21#include "CodeGenTypes.h"
22#include "TargetInfo.h"
23#include "clang/AST/Attr.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclCXX.h"
27#include "clang/AST/StmtCXX.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/StringSet.h"
32#include "llvm/IR/Intrinsics.h"
33
34using namespace clang;
35using namespace CodeGen;
36
37namespace {
38
39/// Holds all the vbtable globals for a given class.
40struct VBTableGlobals {
41 const VPtrInfoVector *VBTables;
43};
44
45class MicrosoftCXXABI : public CGCXXABI {
46public:
47 MicrosoftCXXABI(CodeGenModule &CGM)
48 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
49 ClassHierarchyDescriptorType(nullptr),
50 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
51 ThrowInfoType(nullptr) {
54 "visibility export mapping option unimplemented in this ABI");
55 }
56
57 bool HasThisReturn(GlobalDecl GD) const override;
58 bool hasMostDerivedReturn(GlobalDecl GD) const override;
59
60 bool classifyReturnType(CGFunctionInfo &FI) const override;
61
62 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
63
64 bool isSRetParameterAfterThis() const override { return true; }
65
66 bool isThisCompleteObject(GlobalDecl GD) const override {
67 // The Microsoft ABI doesn't use separate complete-object vs.
68 // base-object variants of constructors, but it does of destructors.
69 if (isa<CXXDestructorDecl>(GD.getDecl())) {
70 switch (GD.getDtorType()) {
71 case Dtor_Complete:
72 case Dtor_Deleting:
73 return true;
74
75 case Dtor_Base:
76 return false;
77
78 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
79 }
80 llvm_unreachable("bad dtor kind");
81 }
82
83 // No other kinds.
84 return false;
85 }
86
88 FunctionArgList &Args) const override {
89 assert(Args.size() >= 2 &&
90 "expected the arglist to have at least two args!");
91 // The 'most_derived' parameter goes second if the ctor is variadic and
92 // has v-bases.
93 if (CD->getParent()->getNumVBases() > 0 &&
95 return 2;
96 return 1;
97 }
98
99 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
100 std::vector<CharUnits> VBPtrOffsets;
101 const ASTContext &Context = getContext();
102 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
103
104 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
105 for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
106 const ASTRecordLayout &SubobjectLayout =
107 Context.getASTRecordLayout(VBT->IntroducingObject);
108 CharUnits Offs = VBT->NonVirtualOffset;
109 Offs += SubobjectLayout.getVBPtrOffset();
110 if (VBT->getVBaseWithVPtr())
111 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
112 VBPtrOffsets.push_back(Offs);
113 }
114 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
115 return VBPtrOffsets;
116 }
117
118 StringRef GetPureVirtualCallName() override { return "_purecall"; }
119 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
120
122 Address Ptr, QualType ElementType,
123 const CXXDestructorDecl *Dtor) override;
124
125 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
126 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
127
128 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
129
130 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
131 const VPtrInfo &Info);
132
133 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
135 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
136
137 /// MSVC needs an extra flag to indicate a catchall.
139 // For -EHa catch(...) must handle HW exception
140 // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
141 if (getContext().getLangOpts().EHAsynch)
142 return CatchTypeInfo{nullptr, 0};
143 else
144 return CatchTypeInfo{nullptr, 0x40};
145 }
146
147 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
148 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
149 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
150 Address ThisPtr,
151 llvm::Type *StdTypeInfoPtrTy) override;
152
153 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
154 QualType SrcRecordTy) override;
155
156 bool shouldEmitExactDynamicCast(QualType DestRecordTy) override {
157 // TODO: Add support for exact dynamic_casts.
158 return false;
159 }
161 QualType SrcRecordTy, QualType DestTy,
162 QualType DestRecordTy,
163 llvm::BasicBlock *CastSuccess,
164 llvm::BasicBlock *CastFail) override {
165 llvm_unreachable("unsupported");
166 }
167
169 QualType SrcRecordTy, QualType DestTy,
170 QualType DestRecordTy,
171 llvm::BasicBlock *CastEnd) override;
172
174 QualType SrcRecordTy) override;
175
176 bool EmitBadCastCall(CodeGenFunction &CGF) override;
177 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
178 return false;
179 }
180
181 llvm::Value *
183 const CXXRecordDecl *ClassDecl,
184 const CXXRecordDecl *BaseClassDecl) override;
185
186 llvm::BasicBlock *
188 const CXXRecordDecl *RD) override;
189
190 llvm::BasicBlock *
191 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
192
194 const CXXRecordDecl *RD) override;
195
196 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
197
198 // Background on MSVC destructors
199 // ==============================
200 //
201 // Both Itanium and MSVC ABIs have destructor variants. The variant names
202 // roughly correspond in the following way:
203 // Itanium Microsoft
204 // Base -> no name, just ~Class
205 // Complete -> vbase destructor
206 // Deleting -> scalar deleting destructor
207 // vector deleting destructor
208 //
209 // The base and complete destructors are the same as in Itanium, although the
210 // complete destructor does not accept a VTT parameter when there are virtual
211 // bases. A separate mechanism involving vtordisps is used to ensure that
212 // virtual methods of destroyed subobjects are not called.
213 //
214 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
215 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
216 // pointer points to an array. The scalar deleting destructor assumes that
217 // bit 2 is zero, and therefore does not contain a loop.
218 //
219 // For virtual destructors, only one entry is reserved in the vftable, and it
220 // always points to the vector deleting destructor. The vector deleting
221 // destructor is the most general, so it can be used to destroy objects in
222 // place, delete single heap objects, or delete arrays.
223 //
224 // A TU defining a non-inline destructor is only guaranteed to emit a base
225 // destructor, and all of the other variants are emitted on an as-needed basis
226 // in COMDATs. Because a non-base destructor can be emitted in a TU that
227 // lacks a definition for the destructor, non-base destructors must always
228 // delegate to or alias the base destructor.
229
230 AddedStructorArgCounts
232 SmallVectorImpl<CanQualType> &ArgTys) override;
233
234 /// Non-base dtors should be emitted as delegating thunks in this ABI.
236 CXXDtorType DT) const override {
237 return DT != Dtor_Base;
238 }
239
240 void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
241 const CXXDestructorDecl *Dtor,
242 CXXDtorType DT) const override;
243
244 llvm::GlobalValue::LinkageTypes
246 CXXDtorType DT) const override;
247
248 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
249
251 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
252
253 if (MD->isVirtual()) {
254 GlobalDecl LookupGD = GD;
255 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
256 // Complete dtors take a pointer to the complete object,
257 // thus don't need adjustment.
258 if (GD.getDtorType() == Dtor_Complete)
259 return MD->getParent();
260
261 // There's only Dtor_Deleting in vftable but it shares the this
262 // adjustment with the base one, so look up the deleting one instead.
263 LookupGD = GlobalDecl(DD, Dtor_Deleting);
264 }
267
268 // The vbases might be ordered differently in the final overrider object
269 // and the complete object, so the "this" argument may sometimes point to
270 // memory that has no particular type (e.g. past the complete object).
271 // In this case, we just use a generic pointer type.
272 // FIXME: might want to have a more precise type in the non-virtual
273 // multiple inheritance case.
274 if (ML.VBase || !ML.VFPtrOffset.isZero())
275 return nullptr;
276 }
277 return MD->getParent();
278 }
279
280 Address
282 Address This,
283 bool VirtualCall) override;
284
286 FunctionArgList &Params) override;
287
289
290 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
291 const CXXConstructorDecl *D,
293 bool ForVirtualBase,
294 bool Delegating) override;
295
297 const CXXDestructorDecl *DD,
299 bool ForVirtualBase,
300 bool Delegating) override;
301
303 CXXDtorType Type, bool ForVirtualBase,
304 bool Delegating, Address This,
305 QualType ThisTy) override;
306
307 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
308 llvm::GlobalVariable *VTable);
309
311 const CXXRecordDecl *RD) override;
312
314 CodeGenFunction::VPtr Vptr) override;
315
316 /// Don't initialize vptrs if dynamic class
317 /// is marked with the 'novtable' attribute.
318 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
319 return !VTableClass->hasAttr<MSNoVTableAttr>();
320 }
321
322 llvm::Constant *
324 const CXXRecordDecl *VTableClass) override;
325
327 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
328 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
329
330 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
331 CharUnits VPtrOffset) override;
332
334 Address This, llvm::Type *Ty,
335 SourceLocation Loc) override;
336
338 const CXXDestructorDecl *Dtor,
339 CXXDtorType DtorType, Address This,
340 DeleteOrMemberCallExpr E) override;
341
343 CallArgList &CallArgs) override {
344 assert(GD.getDtorType() == Dtor_Deleting &&
345 "Only deleting destructor thunks are available in this ABI");
347 getContext().IntTy);
348 }
349
350 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
351
352 llvm::GlobalVariable *
353 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
354 llvm::GlobalVariable::LinkageTypes Linkage);
355
356 llvm::GlobalVariable *
357 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
358 const CXXRecordDecl *DstRD) {
359 SmallString<256> OutName;
360 llvm::raw_svector_ostream Out(OutName);
361 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
362 StringRef MangledName = OutName.str();
363
364 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
365 return VDispMap;
366
368 unsigned NumEntries = 1 + SrcRD->getNumVBases();
370 llvm::UndefValue::get(CGM.IntTy));
371 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
372 bool AnyDifferent = false;
373 for (const auto &I : SrcRD->vbases()) {
374 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
375 if (!DstRD->isVirtuallyDerivedFrom(VBase))
376 continue;
377
378 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
379 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
380 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
381 AnyDifferent |= SrcVBIndex != DstVBIndex;
382 }
383 // This map would be useless, don't use it.
384 if (!AnyDifferent)
385 return nullptr;
386
387 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
388 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
389 llvm::GlobalValue::LinkageTypes Linkage =
390 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
391 ? llvm::GlobalValue::LinkOnceODRLinkage
392 : llvm::GlobalValue::InternalLinkage;
393 auto *VDispMap = new llvm::GlobalVariable(
394 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
395 /*Initializer=*/Init, MangledName);
396 return VDispMap;
397 }
398
399 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
400 llvm::GlobalVariable *GV) const;
401
402 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
403 GlobalDecl GD, bool ReturnAdjustment) override {
405 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
406
407 if (Linkage == GVA_Internal)
408 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
409 else if (ReturnAdjustment)
410 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
411 else
412 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
413 }
414
415 bool exportThunk() override { return false; }
416
417 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
418 const ThisAdjustment &TA) override;
419
420 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
421 const ReturnAdjustment &RA) override;
422
424 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
425 ArrayRef<llvm::Function *> CXXThreadLocalInits,
426 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
427
428 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
430 LangOptions::MSVC2019_5) &&
432 }
434 QualType LValType) override;
435
436 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
437 llvm::GlobalVariable *DeclPtr,
438 bool PerformInit) override;
439 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
440 llvm::FunctionCallee Dtor,
441 llvm::Constant *Addr) override;
442
443 // ==== Notes on array cookies =========
444 //
445 // MSVC seems to only use cookies when the class has a destructor; a
446 // two-argument usual array deallocation function isn't sufficient.
447 //
448 // For example, this code prints "100" and "1":
449 // struct A {
450 // char x;
451 // void *operator new[](size_t sz) {
452 // printf("%u\n", sz);
453 // return malloc(sz);
454 // }
455 // void operator delete[](void *p, size_t sz) {
456 // printf("%u\n", sz);
457 // free(p);
458 // }
459 // };
460 // int main() {
461 // A *p = new A[100];
462 // delete[] p;
463 // }
464 // Whereas it prints "104" and "104" if you give A a destructor.
465
467 QualType elementType) override;
468 bool requiresArrayCookie(const CXXNewExpr *expr) override;
471 Address NewPtr,
472 llvm::Value *NumElements,
473 const CXXNewExpr *expr,
474 QualType ElementType) override;
475 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
476 Address allocPtr,
477 CharUnits cookieSize) override;
478
479 friend struct MSRTTIBuilder;
480
481 bool isImageRelative() const {
482 return CGM.getTarget().getPointerWidth(LangAS::Default) == 64;
483 }
484
485 // 5 routines for constructing the llvm types for MS RTTI structs.
486 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
487 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
488 TDTypeName += llvm::utostr(TypeInfoString.size());
489 llvm::StructType *&TypeDescriptorType =
490 TypeDescriptorTypeMap[TypeInfoString.size()];
491 if (TypeDescriptorType)
492 return TypeDescriptorType;
493 llvm::Type *FieldTypes[] = {
494 CGM.Int8PtrPtrTy,
495 CGM.Int8PtrTy,
496 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
497 TypeDescriptorType =
498 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
499 return TypeDescriptorType;
500 }
501
502 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
503 if (!isImageRelative())
504 return PtrType;
505 return CGM.IntTy;
506 }
507
508 llvm::StructType *getBaseClassDescriptorType() {
509 if (BaseClassDescriptorType)
510 return BaseClassDescriptorType;
511 llvm::Type *FieldTypes[] = {
512 getImageRelativeType(CGM.Int8PtrTy),
513 CGM.IntTy,
514 CGM.IntTy,
515 CGM.IntTy,
516 CGM.IntTy,
517 CGM.IntTy,
518 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
519 };
520 BaseClassDescriptorType = llvm::StructType::create(
521 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
522 return BaseClassDescriptorType;
523 }
524
525 llvm::StructType *getClassHierarchyDescriptorType() {
526 if (ClassHierarchyDescriptorType)
527 return ClassHierarchyDescriptorType;
528 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
529 ClassHierarchyDescriptorType = llvm::StructType::create(
530 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
531 llvm::Type *FieldTypes[] = {
532 CGM.IntTy,
533 CGM.IntTy,
534 CGM.IntTy,
535 getImageRelativeType(
536 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
537 };
538 ClassHierarchyDescriptorType->setBody(FieldTypes);
539 return ClassHierarchyDescriptorType;
540 }
541
542 llvm::StructType *getCompleteObjectLocatorType() {
543 if (CompleteObjectLocatorType)
544 return CompleteObjectLocatorType;
545 CompleteObjectLocatorType = llvm::StructType::create(
546 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
547 llvm::Type *FieldTypes[] = {
548 CGM.IntTy,
549 CGM.IntTy,
550 CGM.IntTy,
551 getImageRelativeType(CGM.Int8PtrTy),
552 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
553 getImageRelativeType(CompleteObjectLocatorType),
554 };
555 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
556 if (!isImageRelative())
557 FieldTypesRef = FieldTypesRef.drop_back();
558 CompleteObjectLocatorType->setBody(FieldTypesRef);
559 return CompleteObjectLocatorType;
560 }
561
562 llvm::GlobalVariable *getImageBase() {
563 StringRef Name = "__ImageBase";
564 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
565 return GV;
566
567 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
568 /*isConstant=*/true,
569 llvm::GlobalValue::ExternalLinkage,
570 /*Initializer=*/nullptr, Name);
571 CGM.setDSOLocal(GV);
572 return GV;
573 }
574
575 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
576 if (!isImageRelative())
577 return PtrVal;
578
579 if (PtrVal->isNullValue())
580 return llvm::Constant::getNullValue(CGM.IntTy);
581
582 llvm::Constant *ImageBaseAsInt =
583 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
584 llvm::Constant *PtrValAsInt =
585 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
586 llvm::Constant *Diff =
587 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
588 /*HasNUW=*/true, /*HasNSW=*/true);
589 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
590 }
591
592private:
594 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
595 }
596
597 llvm::Constant *getZeroInt() {
598 return llvm::ConstantInt::get(CGM.IntTy, 0);
599 }
600
601 llvm::Constant *getAllOnesInt() {
602 return llvm::Constant::getAllOnesValue(CGM.IntTy);
603 }
604
606
607 void
608 GetNullMemberPointerFields(const MemberPointerType *MPT,
610
611 /// Shared code for virtual base adjustment. Returns the offset from
612 /// the vbptr to the virtual base. Optionally returns the address of the
613 /// vbptr itself.
614 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
616 llvm::Value *VBPtrOffset,
617 llvm::Value *VBTableOffset,
618 llvm::Value **VBPtr = nullptr);
619
620 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
622 int32_t VBPtrOffset,
623 int32_t VBTableOffset,
624 llvm::Value **VBPtr = nullptr) {
625 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
626 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
627 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
628 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
629 }
630
631 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
632 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
633 QualType SrcRecordTy);
634
635 /// Performs a full virtual base adjustment. Used to dereference
636 /// pointers to members of virtual bases.
637 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
638 const CXXRecordDecl *RD, Address Base,
639 llvm::Value *VirtualBaseAdjustmentOffset,
640 llvm::Value *VBPtrOffset /* optional */);
641
642 /// Emits a full member pointer with the fields common to data and
643 /// function member pointers.
644 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
645 bool IsMemberFunction,
646 const CXXRecordDecl *RD,
647 CharUnits NonVirtualBaseAdjustment,
648 unsigned VBTableIndex);
649
650 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
651 llvm::Constant *MP);
652
653 /// - Initialize all vbptrs of 'this' with RD as the complete type.
654 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
655
656 /// Caching wrapper around VBTableBuilder::enumerateVBTables().
657 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
658
659 /// Generate a thunk for calling a virtual member function MD.
660 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
661 const MethodVFTableLocation &ML);
662
663 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
664 CharUnits offset);
665
666public:
667 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
668
669 bool isZeroInitializable(const MemberPointerType *MPT) override;
670
671 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
672 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
673 return RD->hasAttr<MSInheritanceAttr>();
674 }
675
676 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
677
678 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
679 CharUnits offset) override;
680 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
681 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
682
684 llvm::Value *L,
685 llvm::Value *R,
686 const MemberPointerType *MPT,
687 bool Inequality) override;
688
690 llvm::Value *MemPtr,
691 const MemberPointerType *MPT) override;
692
693 llvm::Value *
695 Address Base, llvm::Value *MemPtr,
696 const MemberPointerType *MPT) override;
697
698 llvm::Value *EmitNonNullMemberPointerConversion(
699 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
701 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
702 CGBuilderTy &Builder);
703
705 const CastExpr *E,
706 llvm::Value *Src) override;
707
708 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
709 llvm::Constant *Src) override;
710
711 llvm::Constant *EmitMemberPointerConversion(
712 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
714 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
715
718 Address This, llvm::Value *&ThisPtrForCall,
719 llvm::Value *MemPtr,
720 const MemberPointerType *MPT) override;
721
722 void emitCXXStructor(GlobalDecl GD) override;
723
724 llvm::StructType *getCatchableTypeType() {
725 if (CatchableTypeType)
726 return CatchableTypeType;
727 llvm::Type *FieldTypes[] = {
728 CGM.IntTy, // Flags
729 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
730 CGM.IntTy, // NonVirtualAdjustment
731 CGM.IntTy, // OffsetToVBPtr
732 CGM.IntTy, // VBTableIndex
733 CGM.IntTy, // Size
734 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
735 };
736 CatchableTypeType = llvm::StructType::create(
737 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
738 return CatchableTypeType;
739 }
740
741 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
742 llvm::StructType *&CatchableTypeArrayType =
743 CatchableTypeArrayTypeMap[NumEntries];
744 if (CatchableTypeArrayType)
745 return CatchableTypeArrayType;
746
747 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
748 CTATypeName += llvm::utostr(NumEntries);
749 llvm::Type *CTType =
750 getImageRelativeType(getCatchableTypeType()->getPointerTo());
751 llvm::Type *FieldTypes[] = {
752 CGM.IntTy, // NumEntries
753 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
754 };
755 CatchableTypeArrayType =
756 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
757 return CatchableTypeArrayType;
758 }
759
760 llvm::StructType *getThrowInfoType() {
761 if (ThrowInfoType)
762 return ThrowInfoType;
763 llvm::Type *FieldTypes[] = {
764 CGM.IntTy, // Flags
765 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
766 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
767 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
768 };
769 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
770 "eh.ThrowInfo");
771 return ThrowInfoType;
772 }
773
774 llvm::FunctionCallee getThrowFn() {
775 // _CxxThrowException is passed an exception object and a ThrowInfo object
776 // which describes the exception.
777 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
778 llvm::FunctionType *FTy =
779 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
780 llvm::FunctionCallee Throw =
781 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
782 // _CxxThrowException is stdcall on 32-bit x86 platforms.
783 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
784 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
785 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
786 }
787 return Throw;
788 }
789
790 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
791 CXXCtorType CT);
792
793 llvm::Constant *getCatchableType(QualType T,
794 uint32_t NVOffset = 0,
795 int32_t VBPtrOffset = -1,
796 uint32_t VBIndex = 0);
797
798 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
799
800 llvm::GlobalVariable *getThrowInfo(QualType T) override;
801
802 std::pair<llvm::Value *, const CXXRecordDecl *>
804 const CXXRecordDecl *RD) override;
805
806 bool
807 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
808
809private:
810 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
811 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
812 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
813 /// All the vftables that have been referenced.
814 VFTablesMapTy VFTablesMap;
815 VTablesMapTy VTablesMap;
816
817 /// This set holds the record decls we've deferred vtable emission for.
819
820
821 /// All the vbtables which have been referenced.
822 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
823
824 /// Info on the global variable used to guard initialization of static locals.
825 /// The BitIndex field is only used for externally invisible declarations.
826 struct GuardInfo {
827 GuardInfo() = default;
828 llvm::GlobalVariable *Guard = nullptr;
829 unsigned BitIndex = 0;
830 };
831
832 /// Map from DeclContext to the current guard variable. We assume that the
833 /// AST is visited in source code order.
834 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
835 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
836 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
837
838 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
839 llvm::StructType *BaseClassDescriptorType;
840 llvm::StructType *ClassHierarchyDescriptorType;
841 llvm::StructType *CompleteObjectLocatorType;
842
843 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
844
845 llvm::StructType *CatchableTypeType;
846 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
847 llvm::StructType *ThrowInfoType;
848};
849
850}
851
853MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
854 // Use the default C calling convention rules for things that can be passed in
855 // registers, i.e. non-trivially copyable records or records marked with
856 // [[trivial_abi]].
857 if (RD->canPassInRegisters())
858 return RAA_Default;
859
860 switch (CGM.getTarget().getTriple().getArch()) {
861 default:
862 // FIXME: Implement for other architectures.
863 return RAA_Indirect;
864
865 case llvm::Triple::thumb:
866 // Pass things indirectly for now because it is simple.
867 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
868 // copy ctor.
869 return RAA_Indirect;
870
871 case llvm::Triple::x86: {
872 // If the argument has *required* alignment greater than four bytes, pass
873 // it indirectly. Prior to MSVC version 19.14, passing overaligned
874 // arguments was not supported and resulted in a compiler error. In 19.14
875 // and later versions, such arguments are now passed indirectly.
876 TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
877 if (Info.isAlignRequired() && Info.Align > 4)
878 return RAA_Indirect;
879
880 // If C++ prohibits us from making a copy, construct the arguments directly
881 // into argument memory.
882 return RAA_DirectInMemory;
883 }
884
885 case llvm::Triple::x86_64:
886 case llvm::Triple::aarch64:
887 return RAA_Indirect;
888 }
889
890 llvm_unreachable("invalid enum");
891}
892
893void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
894 const CXXDeleteExpr *DE,
895 Address Ptr,
896 QualType ElementType,
897 const CXXDestructorDecl *Dtor) {
898 // FIXME: Provide a source location here even though there's no
899 // CXXMemberCallExpr for dtor call.
900 bool UseGlobalDelete = DE->isGlobalDelete();
901 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
902 llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
903 if (UseGlobalDelete)
904 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
905}
906
907void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
908 llvm::Value *Args[] = {
909 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
910 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
911 llvm::FunctionCallee Fn = getThrowFn();
912 if (isNoReturn)
914 else
915 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
916}
917
918void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
919 const CXXCatchStmt *S) {
920 // In the MS ABI, the runtime handles the copy, and the catch handler is
921 // responsible for destruction.
922 VarDecl *CatchParam = S->getExceptionDecl();
923 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
924 llvm::CatchPadInst *CPI =
925 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
926 CGF.CurrentFuncletPad = CPI;
927
928 // If this is a catch-all or the catch parameter is unnamed, we don't need to
929 // emit an alloca to the object.
930 if (!CatchParam || !CatchParam->getDeclName()) {
931 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
932 return;
933 }
934
935 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
936 CPI->setArgOperand(2, var.getObjectAddress(CGF).emitRawPointer(CGF));
937 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
938 CGF.EmitAutoVarCleanups(var);
939}
940
941/// We need to perform a generic polymorphic operation (like a typeid
942/// or a cast), which requires an object with a vfptr. Adjust the
943/// address to point to an object with a vfptr.
944std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
945MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
946 QualType SrcRecordTy) {
947 Value = Value.withElementType(CGF.Int8Ty);
948 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
949 const ASTContext &Context = getContext();
950
951 // If the class itself has a vfptr, great. This check implicitly
952 // covers non-virtual base subobjects: a class with its own virtual
953 // functions would be a candidate to be a primary base.
954 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
955 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
956 SrcDecl);
957
958 // Okay, one of the vbases must have a vfptr, or else this isn't
959 // actually a polymorphic class.
960 const CXXRecordDecl *PolymorphicBase = nullptr;
961 for (auto &Base : SrcDecl->vbases()) {
962 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
963 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
964 PolymorphicBase = BaseDecl;
965 break;
966 }
967 }
968 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
969
970 llvm::Value *Offset =
971 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
972 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
973 Value.getElementType(), Value.emitRawPointer(CGF), Offset);
974 CharUnits VBaseAlign =
975 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
976 return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,
977 PolymorphicBase);
978}
979
980bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
981 QualType SrcRecordTy) {
982 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
983 return IsDeref &&
984 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
985}
986
987static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
988 llvm::Value *Argument) {
989 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
990 llvm::FunctionType *FTy =
991 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
992 llvm::Value *Args[] = {Argument};
993 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
994 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
995}
996
997void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
998 llvm::CallBase *Call =
999 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
1000 Call->setDoesNotReturn();
1001 CGF.Builder.CreateUnreachable();
1002}
1003
1004llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
1005 QualType SrcRecordTy,
1006 Address ThisPtr,
1007 llvm::Type *StdTypeInfoPtrTy) {
1008 std::tie(ThisPtr, std::ignore, std::ignore) =
1009 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
1010 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.emitRawPointer(CGF));
1011 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
1012}
1013
1014bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1015 QualType SrcRecordTy) {
1016 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1017 return SrcIsPtr &&
1018 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1019}
1020
1021llvm::Value *MicrosoftCXXABI::emitDynamicCastCall(
1022 CodeGenFunction &CGF, Address This, QualType SrcRecordTy, QualType DestTy,
1023 QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1024 llvm::Value *SrcRTTI =
1026 llvm::Value *DestRTTI =
1028
1029 llvm::Value *Offset;
1030 std::tie(This, Offset, std::ignore) =
1031 performBaseAdjustment(CGF, This, SrcRecordTy);
1032 llvm::Value *ThisPtr = This.emitRawPointer(CGF);
1033 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1034
1035 // PVOID __RTDynamicCast(
1036 // PVOID inptr,
1037 // LONG VfDelta,
1038 // PVOID SrcType,
1039 // PVOID TargetType,
1040 // BOOL isReference)
1041 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1042 CGF.Int8PtrTy, CGF.Int32Ty};
1043 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1044 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1045 "__RTDynamicCast");
1046 llvm::Value *Args[] = {
1047 ThisPtr, Offset, SrcRTTI, DestRTTI,
1048 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1049 return CGF.EmitRuntimeCallOrInvoke(Function, Args);
1050}
1051
1052llvm::Value *MicrosoftCXXABI::emitDynamicCastToVoid(CodeGenFunction &CGF,
1053 Address Value,
1054 QualType SrcRecordTy) {
1055 std::tie(Value, std::ignore, std::ignore) =
1056 performBaseAdjustment(CGF, Value, SrcRecordTy);
1057
1058 // PVOID __RTCastToVoid(
1059 // PVOID inptr)
1060 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1061 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1062 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1063 "__RTCastToVoid");
1064 llvm::Value *Args[] = {Value.emitRawPointer(CGF)};
1065 return CGF.EmitRuntimeCall(Function, Args);
1066}
1067
1068bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1069 return false;
1070}
1071
1072llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1073 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1074 const CXXRecordDecl *BaseClassDecl) {
1075 const ASTContext &Context = getContext();
1076 int64_t VBPtrChars =
1077 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1078 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1079 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1080 CharUnits VBTableChars =
1081 IntSize *
1082 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1083 llvm::Value *VBTableOffset =
1084 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1085
1086 llvm::Value *VBPtrToNewBase =
1087 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1088 VBPtrToNewBase =
1089 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1090 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1091}
1092
1093bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1094 return isa<CXXConstructorDecl>(GD.getDecl());
1095}
1096
1098 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1099 GD.getDtorType() == Dtor_Deleting;
1100}
1101
1102bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1103 return isDeletingDtor(GD);
1104}
1105
1106static bool isTrivialForMSVC(const CXXRecordDecl *RD, QualType Ty,
1107 CodeGenModule &CGM) {
1108 // On AArch64, HVAs that can be passed in registers can also be returned
1109 // in registers. (Note this is using the MSVC definition of an HVA; see
1110 // isPermittedToBeHomogeneousAggregate().)
1111 const Type *Base = nullptr;
1112 uint64_t NumElts = 0;
1113 if (CGM.getTarget().getTriple().isAArch64() &&
1114 CGM.getTypes().getABIInfo().isHomogeneousAggregate(Ty, Base, NumElts) &&
1115 isa<VectorType>(Base)) {
1116 return true;
1117 }
1118
1119 // We use the C++14 definition of an aggregate, so we also
1120 // check for:
1121 // No private or protected non static data members.
1122 // No base classes
1123 // No virtual functions
1124 // Additionally, we need to ensure that there is a trivial copy assignment
1125 // operator, a trivial destructor, no user-provided constructors and no
1126 // deleted copy assignment operator.
1127
1128 // We need to cover two cases when checking for a deleted copy assignment
1129 // operator.
1130 //
1131 // struct S { int& r; };
1132 // The above will have an implicit copy assignment operator that is deleted
1133 // and there will not be a `CXXMethodDecl` for the copy assignment operator.
1134 // This is handled by the `needsImplicitCopyAssignment()` check below.
1135 //
1136 // struct S { S& operator=(const S&) = delete; int i; };
1137 // The above will not have an implicit copy assignment operator that is
1138 // deleted but there is a deleted `CXXMethodDecl` for the declared copy
1139 // assignment operator. This is handled by the `isDeleted()` check below.
1140
1141 if (RD->hasProtectedFields() || RD->hasPrivateFields())
1142 return false;
1143 if (RD->getNumBases() > 0)
1144 return false;
1145 if (RD->isPolymorphic())
1146 return false;
1148 return false;
1150 return false;
1151 for (const Decl *D : RD->decls()) {
1152 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1153 if (Ctor->isUserProvided())
1154 return false;
1155 } else if (auto *Template = dyn_cast<FunctionTemplateDecl>(D)) {
1156 if (isa<CXXConstructorDecl>(Template->getTemplatedDecl()))
1157 return false;
1158 } else if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
1159 if (MethodDecl->isCopyAssignmentOperator() && MethodDecl->isDeleted())
1160 return false;
1161 }
1162 }
1163 if (RD->hasNonTrivialDestructor())
1164 return false;
1165 return true;
1166}
1167
1168bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1169 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1170 if (!RD)
1171 return false;
1172
1173 bool isTrivialForABI = RD->canPassInRegisters() &&
1174 isTrivialForMSVC(RD, FI.getReturnType(), CGM);
1175
1176 // MSVC always returns structs indirectly from C++ instance methods.
1177 bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
1178
1179 if (isIndirectReturn) {
1181 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1182
1183 // MSVC always passes `this` before the `sret` parameter.
1185
1186 // On AArch64, use the `inreg` attribute if the object is considered to not
1187 // be trivially copyable, or if this is an instance method struct return.
1188 FI.getReturnInfo().setInReg(CGM.getTarget().getTriple().isAArch64());
1189
1190 return true;
1191 }
1192
1193 // Otherwise, use the C ABI rules.
1194 return false;
1195}
1196
1197llvm::BasicBlock *
1198MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1199 const CXXRecordDecl *RD) {
1200 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1201 assert(IsMostDerivedClass &&
1202 "ctor for a class with virtual bases must have an implicit parameter");
1203 llvm::Value *IsCompleteObject =
1204 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1205
1206 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1207 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1208 CGF.Builder.CreateCondBr(IsCompleteObject,
1209 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1210
1211 CGF.EmitBlock(CallVbaseCtorsBB);
1212
1213 // Fill in the vbtable pointers here.
1214 EmitVBPtrStores(CGF, RD);
1215
1216 // CGF will put the base ctor calls in this basic block for us later.
1217
1218 return SkipVbaseCtorsBB;
1219}
1220
1221llvm::BasicBlock *
1222MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1223 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1224 assert(IsMostDerivedClass &&
1225 "ctor for a class with virtual bases must have an implicit parameter");
1226 llvm::Value *IsCompleteObject =
1227 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1228
1229 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1230 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1231 CGF.Builder.CreateCondBr(IsCompleteObject,
1232 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1233
1234 CGF.EmitBlock(CallVbaseDtorsBB);
1235 // CGF will put the base dtor calls in this basic block for us later.
1236
1237 return SkipVbaseDtorsBB;
1238}
1239
1240void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1241 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1242 // In most cases, an override for a vbase virtual method can adjust
1243 // the "this" parameter by applying a constant offset.
1244 // However, this is not enough while a constructor or a destructor of some
1245 // class X is being executed if all the following conditions are met:
1246 // - X has virtual bases, (1)
1247 // - X overrides a virtual method M of a vbase Y, (2)
1248 // - X itself is a vbase of the most derived class.
1249 //
1250 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1251 // which holds the extra amount of "this" adjustment we must do when we use
1252 // the X vftables (i.e. during X ctor or dtor).
1253 // Outside the ctors and dtors, the values of vtorDisps are zero.
1254
1255 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1256 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1257 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1258 CGBuilderTy &Builder = CGF.Builder;
1259
1260 llvm::Value *Int8This = nullptr; // Initialize lazily.
1261
1262 for (const CXXBaseSpecifier &S : RD->vbases()) {
1263 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1264 auto I = VBaseMap.find(VBase);
1265 assert(I != VBaseMap.end());
1266 if (!I->second.hasVtorDisp())
1267 continue;
1268
1269 llvm::Value *VBaseOffset =
1270 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1271 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1272
1273 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1274 llvm::Value *VtorDispValue = Builder.CreateSub(
1275 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1276 "vtordisp.value");
1277 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1278
1279 if (!Int8This)
1280 Int8This = getThisValue(CGF);
1281
1282 llvm::Value *VtorDispPtr =
1283 Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
1284 // vtorDisp is always the 32-bits before the vbase in the class layout.
1285 VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
1286
1287 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1289 }
1290}
1291
1293 const CXXMethodDecl *MD) {
1294 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1295 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1296 CallingConv ActualCallingConv =
1297 MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1298 return ExpectedCallingConv == ActualCallingConv;
1299}
1300
1301void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1302 // There's only one constructor type in this ABI.
1304
1305 // Exported default constructors either have a simple call-site where they use
1306 // the typical calling convention and have a single 'this' pointer for an
1307 // argument -or- they get a wrapper function which appropriately thunks to the
1308 // real default constructor. This thunk is the default constructor closure.
1309 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
1310 D->isDefined()) {
1311 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1312 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1313 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1314 CGM.setGVProperties(Fn, D);
1315 }
1316 }
1317}
1318
1319void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1320 const CXXRecordDecl *RD) {
1321 Address This = getThisAddress(CGF);
1322 This = This.withElementType(CGM.Int8Ty);
1323 const ASTContext &Context = getContext();
1324 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1325
1326 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1327 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1328 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1329 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1330 const ASTRecordLayout &SubobjectLayout =
1331 Context.getASTRecordLayout(VBT->IntroducingObject);
1332 CharUnits Offs = VBT->NonVirtualOffset;
1333 Offs += SubobjectLayout.getVBPtrOffset();
1334 if (VBT->getVBaseWithVPtr())
1335 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1336 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1337 llvm::Value *GVPtr =
1338 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1339 VBPtr = VBPtr.withElementType(GVPtr->getType());
1340 CGF.Builder.CreateStore(GVPtr, VBPtr);
1341 }
1342}
1343
1345MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1347 AddedStructorArgCounts Added;
1348 // TODO: 'for base' flag
1349 if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1350 GD.getDtorType() == Dtor_Deleting) {
1351 // The scalar deleting destructor takes an implicit int parameter.
1352 ArgTys.push_back(getContext().IntTy);
1353 ++Added.Suffix;
1354 }
1355 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1356 if (!CD)
1357 return Added;
1358
1359 // All parameters are already in place except is_most_derived, which goes
1360 // after 'this' if it's variadic and last if it's not.
1361
1362 const CXXRecordDecl *Class = CD->getParent();
1363 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1364 if (Class->getNumVBases()) {
1365 if (FPT->isVariadic()) {
1366 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1367 ++Added.Prefix;
1368 } else {
1369 ArgTys.push_back(getContext().IntTy);
1370 ++Added.Suffix;
1371 }
1372 }
1373
1374 return Added;
1375}
1376
1377void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1378 const CXXDestructorDecl *Dtor,
1379 CXXDtorType DT) const {
1380 // Deleting destructor variants are never imported or exported. Give them the
1381 // default storage class.
1382 if (DT == Dtor_Deleting) {
1383 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1384 } else {
1385 const NamedDecl *ND = Dtor;
1386 CGM.setDLLImportDLLExport(GV, ND);
1387 }
1388}
1389
1390llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1391 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1392 // Internal things are always internal, regardless of attributes. After this,
1393 // we know the thunk is externally visible.
1394 if (Linkage == GVA_Internal)
1395 return llvm::GlobalValue::InternalLinkage;
1396
1397 switch (DT) {
1398 case Dtor_Base:
1399 // The base destructor most closely tracks the user-declared constructor, so
1400 // we delegate back to the normal declarator case.
1401 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage);
1402 case Dtor_Complete:
1403 // The complete destructor is like an inline function, but it may be
1404 // imported and therefore must be exported as well. This requires changing
1405 // the linkage if a DLL attribute is present.
1406 if (Dtor->hasAttr<DLLExportAttr>())
1407 return llvm::GlobalValue::WeakODRLinkage;
1408 if (Dtor->hasAttr<DLLImportAttr>())
1409 return llvm::GlobalValue::AvailableExternallyLinkage;
1410 return llvm::GlobalValue::LinkOnceODRLinkage;
1411 case Dtor_Deleting:
1412 // Deleting destructors are like inline functions. They have vague linkage
1413 // and are emitted everywhere they are used. They are internal if the class
1414 // is internal.
1415 return llvm::GlobalValue::LinkOnceODRLinkage;
1416 case Dtor_Comdat:
1417 llvm_unreachable("MS C++ ABI does not support comdat dtors");
1418 }
1419 llvm_unreachable("invalid dtor type");
1420}
1421
1422void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1423 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1424 // other destructor variants are delegating thunks.
1426
1427 // If the class is dllexported, emit the complete (vbase) destructor wherever
1428 // the base dtor is emitted.
1429 // FIXME: To match MSVC, this should only be done when the class is exported
1430 // with -fdllexport-inlines enabled.
1431 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
1433}
1434
1436MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1437 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1438
1439 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1440 // Complete destructors take a pointer to the complete object as a
1441 // parameter, thus don't need this adjustment.
1442 if (GD.getDtorType() == Dtor_Complete)
1443 return CharUnits();
1444
1445 // There's no Dtor_Base in vftable but it shares the this adjustment with
1446 // the deleting one, so look it up instead.
1447 GD = GlobalDecl(DD, Dtor_Deleting);
1448 }
1449
1452 CharUnits Adjustment = ML.VFPtrOffset;
1453
1454 // Normal virtual instance methods need to adjust from the vfptr that first
1455 // defined the virtual method to the virtual base subobject, but destructors
1456 // do not. The vector deleting destructor thunk applies this adjustment for
1457 // us if necessary.
1458 if (isa<CXXDestructorDecl>(MD))
1459 Adjustment = CharUnits::Zero();
1460
1461 if (ML.VBase) {
1462 const ASTRecordLayout &DerivedLayout =
1463 getContext().getASTRecordLayout(MD->getParent());
1464 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1465 }
1466
1467 return Adjustment;
1468}
1469
1470Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1471 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1472 bool VirtualCall) {
1473 if (!VirtualCall) {
1474 // If the call of a virtual function is not virtual, we just have to
1475 // compensate for the adjustment the virtual function does in its prologue.
1476 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1477 if (Adjustment.isZero())
1478 return This;
1479
1480 This = This.withElementType(CGF.Int8Ty);
1481 assert(Adjustment.isPositive());
1482 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1483 }
1484
1485 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1486
1487 GlobalDecl LookupGD = GD;
1488 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1489 // Complete dtors take a pointer to the complete object,
1490 // thus don't need adjustment.
1491 if (GD.getDtorType() == Dtor_Complete)
1492 return This;
1493
1494 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1495 // with the base one, so look up the deleting one instead.
1496 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1497 }
1500
1501 CharUnits StaticOffset = ML.VFPtrOffset;
1502
1503 // Base destructors expect 'this' to point to the beginning of the base
1504 // subobject, not the first vfptr that happens to contain the virtual dtor.
1505 // However, we still need to apply the virtual base adjustment.
1506 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1507 StaticOffset = CharUnits::Zero();
1508
1509 Address Result = This;
1510 if (ML.VBase) {
1511 Result = Result.withElementType(CGF.Int8Ty);
1512
1513 const CXXRecordDecl *Derived = MD->getParent();
1514 const CXXRecordDecl *VBase = ML.VBase;
1515 llvm::Value *VBaseOffset =
1516 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1517 llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
1518 Result.getElementType(), Result.emitRawPointer(CGF), VBaseOffset);
1519 CharUnits VBaseAlign =
1520 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1521 Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);
1522 }
1523 if (!StaticOffset.isZero()) {
1524 assert(StaticOffset.isPositive());
1525 Result = Result.withElementType(CGF.Int8Ty);
1526 if (ML.VBase) {
1527 // Non-virtual adjustment might result in a pointer outside the allocated
1528 // object, e.g. if the final overrider class is laid out after the virtual
1529 // base that declares a method in the most derived class.
1530 // FIXME: Update the code that emits this adjustment in thunks prologues.
1531 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1532 } else {
1533 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1534 }
1535 }
1536 return Result;
1537}
1538
1539void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1540 QualType &ResTy,
1541 FunctionArgList &Params) {
1542 ASTContext &Context = getContext();
1543 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1544 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1545 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1546 auto *IsMostDerived = ImplicitParamDecl::Create(
1547 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1548 &Context.Idents.get("is_most_derived"), Context.IntTy,
1549 ImplicitParamKind::Other);
1550 // The 'most_derived' parameter goes second if the ctor is variadic and last
1551 // if it's not. Dtors can't be variadic.
1552 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1553 if (FPT->isVariadic())
1554 Params.insert(Params.begin() + 1, IsMostDerived);
1555 else
1556 Params.push_back(IsMostDerived);
1557 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1558 } else if (isDeletingDtor(CGF.CurGD)) {
1559 auto *ShouldDelete = ImplicitParamDecl::Create(
1560 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1561 &Context.Idents.get("should_call_delete"), Context.IntTy,
1562 ImplicitParamKind::Other);
1563 Params.push_back(ShouldDelete);
1564 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1565 }
1566}
1567
1568void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1569 // Naked functions have no prolog.
1570 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1571 return;
1572
1573 // Overridden virtual methods of non-primary bases need to adjust the incoming
1574 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1575 // sizeof(void*) to adjust from B* to C*:
1576 // struct A { virtual void a(); };
1577 // struct B { virtual void b(); };
1578 // struct C : A, B { virtual void b(); };
1579 //
1580 // Leave the value stored in the 'this' alloca unadjusted, so that the
1581 // debugger sees the unadjusted value. Microsoft debuggers require this, and
1582 // will apply the ThisAdjustment in the method type information.
1583 // FIXME: Do something better for DWARF debuggers, which won't expect this,
1584 // without making our codegen depend on debug info settings.
1585 llvm::Value *This = loadIncomingCXXThis(CGF);
1586 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1587 if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1588 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1589 if (!Adjustment.isZero()) {
1590 assert(Adjustment.isPositive());
1591 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1592 -Adjustment.getQuantity());
1593 }
1594 }
1595 setCXXABIThisValue(CGF, This);
1596
1597 // If this is a function that the ABI specifies returns 'this', initialize
1598 // the return slot to 'this' at the start of the function.
1599 //
1600 // Unlike the setting of return types, this is done within the ABI
1601 // implementation instead of by clients of CGCXXABI because:
1602 // 1) getThisValue is currently protected
1603 // 2) in theory, an ABI could implement 'this' returns some other way;
1604 // HasThisReturn only specifies a contract, not the implementation
1605 if (HasThisReturn(CGF.CurGD) || hasMostDerivedReturn(CGF.CurGD))
1606 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1607
1608 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1609 assert(getStructorImplicitParamDecl(CGF) &&
1610 "no implicit parameter for a constructor with virtual bases?");
1611 getStructorImplicitParamValue(CGF)
1612 = CGF.Builder.CreateLoad(
1613 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1614 "is_most_derived");
1615 }
1616
1617 if (isDeletingDtor(CGF.CurGD)) {
1618 assert(getStructorImplicitParamDecl(CGF) &&
1619 "no implicit parameter for a deleting destructor?");
1620 getStructorImplicitParamValue(CGF)
1621 = CGF.Builder.CreateLoad(
1622 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1623 "should_call_delete");
1624 }
1625}
1626
1627CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1629 bool ForVirtualBase, bool Delegating) {
1630 assert(Type == Ctor_Complete || Type == Ctor_Base);
1631
1632 // Check if we need a 'most_derived' parameter.
1633 if (!D->getParent()->getNumVBases())
1634 return AddedStructorArgs{};
1635
1636 // Add the 'most_derived' argument second if we are variadic or last if not.
1637 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1638 llvm::Value *MostDerivedArg;
1639 if (Delegating) {
1640 MostDerivedArg = getStructorImplicitParamValue(CGF);
1641 } else {
1642 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1643 }
1644 if (FPT->isVariadic()) {
1645 return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1646 }
1647 return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1648}
1649
1650llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1652 bool ForVirtualBase, bool Delegating) {
1653 return nullptr;
1654}
1655
1656void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1657 const CXXDestructorDecl *DD,
1658 CXXDtorType Type, bool ForVirtualBase,
1659 bool Delegating, Address This,
1660 QualType ThisTy) {
1661 // Use the base destructor variant in place of the complete destructor variant
1662 // if the class has no virtual bases. This effectively implements some of the
1663 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1664 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
1665 Type = Dtor_Base;
1666
1667 GlobalDecl GD(DD, Type);
1669
1670 if (DD->isVirtual()) {
1671 assert(Type != CXXDtorType::Dtor_Deleting &&
1672 "The deleting destructor should only be called via a virtual call");
1673 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1674 This, false);
1675 }
1676
1677 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1678 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1679 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1680 }
1681
1682 llvm::Value *Implicit =
1683 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1684 Delegating); // = nullptr
1685 CGF.EmitCXXDestructorCall(GD, Callee, CGF.getAsNaturalPointerTo(This, ThisTy),
1686 ThisTy,
1687 /*ImplicitParam=*/Implicit,
1688 /*ImplicitParamTy=*/QualType(), nullptr);
1689 if (BaseDtorEndBB) {
1690 // Complete object handler should continue to be the remaining
1691 CGF.Builder.CreateBr(BaseDtorEndBB);
1692 CGF.EmitBlock(BaseDtorEndBB);
1693 }
1694}
1695
1696void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1697 const CXXRecordDecl *RD,
1698 llvm::GlobalVariable *VTable) {
1699 // Emit type metadata on vtables with LTO or IR instrumentation.
1700 // In IR instrumentation, the type metadata could be used to find out vtable
1701 // definitions (for type profiling) among all global variables.
1702 if (!CGM.getCodeGenOpts().LTOUnit &&
1704 return;
1705
1706 // TODO: Should VirtualFunctionElimination also be supported here?
1707 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1708 if (CGM.getCodeGenOpts().WholeProgramVTables) {
1710 llvm::GlobalObject::VCallVisibility TypeVis =
1712 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1713 VTable->setVCallVisibilityMetadata(TypeVis);
1714 }
1715
1716 // The location of the first virtual function pointer in the virtual table,
1717 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1718 // disabled, or sizeof(void*) if RTTI is enabled.
1719 CharUnits AddressPoint =
1720 getContext().getLangOpts().RTTIData
1721 ? getContext().toCharUnitsFromBits(
1722 getContext().getTargetInfo().getPointerWidth(LangAS::Default))
1723 : CharUnits::Zero();
1724
1725 if (Info.PathToIntroducingObject.empty()) {
1726 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1727 return;
1728 }
1729
1730 // Add a bitset entry for the least derived base belonging to this vftable.
1731 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1732 Info.PathToIntroducingObject.back());
1733
1734 // Add a bitset entry for each derived class that is laid out at the same
1735 // offset as the least derived base.
1736 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1737 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1738 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1739
1740 const ASTRecordLayout &Layout =
1741 getContext().getASTRecordLayout(DerivedRD);
1742 CharUnits Offset;
1743 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1744 if (VBI == Layout.getVBaseOffsetsMap().end())
1745 Offset = Layout.getBaseClassOffset(BaseRD);
1746 else
1747 Offset = VBI->second.VBaseOffset;
1748 if (!Offset.isZero())
1749 return;
1750 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1751 }
1752
1753 // Finally do the same for the most derived class.
1754 if (Info.FullOffsetInMDC.isZero())
1755 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1756}
1757
1758void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1759 const CXXRecordDecl *RD) {
1761 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1762
1763 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1764 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1765 if (VTable->hasInitializer())
1766 continue;
1767
1768 const VTableLayout &VTLayout =
1769 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1770
1771 llvm::Constant *RTTI = nullptr;
1772 if (any_of(VTLayout.vtable_components(),
1773 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1774 RTTI = getMSCompleteObjectLocator(RD, *Info);
1775
1776 ConstantInitBuilder builder(CGM);
1777 auto components = builder.beginStruct();
1778 CGVT.createVTableInitializer(components, VTLayout, RTTI,
1779 VTable->hasLocalLinkage());
1780 components.finishAndSetAsInitializer(VTable);
1781
1782 emitVTableTypeMetadata(*Info, RD, VTable);
1783 }
1784}
1785
1786bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1787 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1788 return Vptr.NearestVBase != nullptr;
1789}
1790
1791llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1792 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1793 const CXXRecordDecl *NearestVBase) {
1794 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1795 if (!VTableAddressPoint) {
1796 assert(Base.getBase()->getNumVBases() &&
1797 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1798 }
1799 return VTableAddressPoint;
1800}
1801
1803 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1804 SmallString<256> &Name) {
1805 llvm::raw_svector_ostream Out(Name);
1806 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1807}
1808
1809llvm::Constant *
1810MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1811 const CXXRecordDecl *VTableClass) {
1812 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1813 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1814 return VFTablesMap[ID];
1815}
1816
1817llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1818 CharUnits VPtrOffset) {
1819 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1820 // shouldn't be used in the given record type. We want to cache this result in
1821 // VFTablesMap, thus a simple zero check is not sufficient.
1822
1823 VFTableIdTy ID(RD, VPtrOffset);
1824 VTablesMapTy::iterator I;
1825 bool Inserted;
1826 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1827 if (!Inserted)
1828 return I->second;
1829
1830 llvm::GlobalVariable *&VTable = I->second;
1831
1833 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1834
1835 if (DeferredVFTables.insert(RD).second) {
1836 // We haven't processed this record type before.
1837 // Queue up this vtable for possible deferred emission.
1838 CGM.addDeferredVTable(RD);
1839
1840#ifndef NDEBUG
1841 // Create all the vftables at once in order to make sure each vftable has
1842 // a unique mangled name.
1843 llvm::StringSet<> ObservedMangledNames;
1844 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1845 SmallString<256> Name;
1846 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1847 if (!ObservedMangledNames.insert(Name.str()).second)
1848 llvm_unreachable("Already saw this mangling before?");
1849 }
1850#endif
1851 }
1852
1853 const std::unique_ptr<VPtrInfo> *VFPtrI =
1854 llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
1855 return VPI->FullOffsetInMDC == VPtrOffset;
1856 });
1857 if (VFPtrI == VFPtrs.end()) {
1858 VFTablesMap[ID] = nullptr;
1859 return nullptr;
1860 }
1861 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1862
1863 SmallString<256> VFTableName;
1864 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1865
1866 // Classes marked __declspec(dllimport) need vftables generated on the
1867 // import-side in order to support features like constexpr. No other
1868 // translation unit relies on the emission of the local vftable, translation
1869 // units are expected to generate them as needed.
1870 //
1871 // Because of this unique behavior, we maintain this logic here instead of
1872 // getVTableLinkage.
1873 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1874 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1875 : CGM.getVTableLinkage(RD);
1876 bool VFTableComesFromAnotherTU =
1877 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1878 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1879 bool VTableAliasIsRequred =
1880 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1881
1882 if (llvm::GlobalValue *VFTable =
1883 CGM.getModule().getNamedGlobal(VFTableName)) {
1884 VFTablesMap[ID] = VFTable;
1885 VTable = VTableAliasIsRequred
1886 ? cast<llvm::GlobalVariable>(
1887 cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
1888 : cast<llvm::GlobalVariable>(VFTable);
1889 return VTable;
1890 }
1891
1892 const VTableLayout &VTLayout =
1893 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1894 llvm::GlobalValue::LinkageTypes VTableLinkage =
1895 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1896
1897 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1898
1899 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1900
1901 // Create a backing variable for the contents of VTable. The VTable may
1902 // or may not include space for a pointer to RTTI data.
1903 llvm::GlobalValue *VFTable;
1904 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1905 /*isConstant=*/true, VTableLinkage,
1906 /*Initializer=*/nullptr, VTableName);
1907 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1908
1909 llvm::Comdat *C = nullptr;
1910 if (!VFTableComesFromAnotherTU &&
1911 llvm::GlobalValue::isWeakForLinker(VFTableLinkage))
1912 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1913
1914 // Only insert a pointer into the VFTable for RTTI data if we are not
1915 // importing it. We never reference the RTTI data directly so there is no
1916 // need to make room for it.
1917 if (VTableAliasIsRequred) {
1918 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1919 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1920 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1921 // Create a GEP which points just after the first entry in the VFTable,
1922 // this should be the location of the first virtual method.
1923 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1924 VTable->getValueType(), VTable, GEPIndices);
1925 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1926 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1927 if (C)
1928 C->setSelectionKind(llvm::Comdat::Largest);
1929 }
1930 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1931 /*AddressSpace=*/0, VFTableLinkage,
1932 VFTableName.str(), VTableGEP,
1933 &CGM.getModule());
1934 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1935 } else {
1936 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1937 // be referencing any RTTI data.
1938 // The GlobalVariable will end up being an appropriate definition of the
1939 // VFTable.
1940 VFTable = VTable;
1941 }
1942 if (C)
1943 VTable->setComdat(C);
1944
1945 if (RD->hasAttr<DLLExportAttr>())
1946 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1947
1948 VFTablesMap[ID] = VFTable;
1949 return VTable;
1950}
1951
1952CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1953 GlobalDecl GD,
1954 Address This,
1955 llvm::Type *Ty,
1957 CGBuilderTy &Builder = CGF.Builder;
1958
1959 Ty = Ty->getPointerTo();
1960 Address VPtr =
1961 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1962
1963 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1964 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
1965 MethodDecl->getParent());
1966
1969
1970 // Compute the identity of the most derived class whose virtual table is
1971 // located at the MethodVFTableLocation ML.
1972 auto getObjectWithVPtr = [&] {
1973 return llvm::find_if(VFTContext.getVFPtrOffsets(
1974 ML.VBase ? ML.VBase : MethodDecl->getParent()),
1975 [&](const std::unique_ptr<VPtrInfo> &Info) {
1976 return Info->FullOffsetInMDC == ML.VFPtrOffset;
1977 })
1978 ->get()
1979 ->ObjectWithVPtr;
1980 };
1981
1982 llvm::Value *VFunc;
1983 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1984 VFunc = CGF.EmitVTableTypeCheckedLoad(
1985 getObjectWithVPtr(), VTable, Ty,
1986 ML.Index *
1987 CGM.getContext().getTargetInfo().getPointerWidth(LangAS::Default) /
1988 8);
1989 } else {
1990 if (CGM.getCodeGenOpts().PrepareForLTO)
1991 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1992
1993 llvm::Value *VFuncPtr =
1994 Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
1995 VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
1996 }
1997
1998 CGCallee Callee(GD, VFunc);
1999 return Callee;
2000}
2001
2002llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
2003 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
2004 Address This, DeleteOrMemberCallExpr E) {
2005 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
2006 auto *D = E.dyn_cast<const CXXDeleteExpr *>();
2007 assert((CE != nullptr) ^ (D != nullptr));
2008 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
2009 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
2010
2011 // We have only one destructor in the vftable but can get both behaviors
2012 // by passing an implicit int parameter.
2013 GlobalDecl GD(Dtor, Dtor_Deleting);
2014 const CGFunctionInfo *FInfo =
2016 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
2017 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
2018
2019 ASTContext &Context = getContext();
2020 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
2021 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
2022 DtorType == Dtor_Deleting);
2023
2024 QualType ThisTy;
2025 if (CE) {
2026 ThisTy = CE->getObjectType();
2027 } else {
2028 ThisTy = D->getDestroyedType();
2029 }
2030
2031 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
2032 RValue RV =
2033 CGF.EmitCXXDestructorCall(GD, Callee, This.emitRawPointer(CGF), ThisTy,
2034 ImplicitParam, Context.IntTy, CE);
2035 return RV.getScalarVal();
2036}
2037
2038const VBTableGlobals &
2039MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
2040 // At this layer, we can key the cache off of a single class, which is much
2041 // easier than caching each vbtable individually.
2042 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
2043 bool Added;
2044 std::tie(Entry, Added) =
2045 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
2046 VBTableGlobals &VBGlobals = Entry->second;
2047 if (!Added)
2048 return VBGlobals;
2049
2051 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
2052
2053 // Cache the globals for all vbtables so we don't have to recompute the
2054 // mangled names.
2055 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2056 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
2057 E = VBGlobals.VBTables->end();
2058 I != E; ++I) {
2059 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
2060 }
2061
2062 return VBGlobals;
2063}
2064
2065llvm::Function *
2066MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
2067 const MethodVFTableLocation &ML) {
2068 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
2069 "can't form pointers to ctors or virtual dtors");
2070
2071 // Calculate the mangled name.
2072 SmallString<256> ThunkName;
2073 llvm::raw_svector_ostream Out(ThunkName);
2074 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
2075
2076 // If the thunk has been generated previously, just return it.
2077 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
2078 return cast<llvm::Function>(GV);
2079
2080 // Create the llvm::Function.
2081 const CGFunctionInfo &FnInfo =
2083 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2084 llvm::Function *ThunkFn =
2085 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2086 ThunkName.str(), &CGM.getModule());
2087 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2088
2089 ThunkFn->setLinkage(MD->isExternallyVisible()
2090 ? llvm::GlobalValue::LinkOnceODRLinkage
2091 : llvm::GlobalValue::InternalLinkage);
2092 if (MD->isExternallyVisible())
2093 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2094
2095 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
2097
2098 // Add the "thunk" attribute so that LLVM knows that the return type is
2099 // meaningless. These thunks can be used to call functions with differing
2100 // return types, and the caller is required to cast the prototype
2101 // appropriately to extract the correct value.
2102 ThunkFn->addFnAttr("thunk");
2103
2104 // These thunks can be compared, so they are not unnamed.
2105 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2106
2107 // Start codegen.
2108 CodeGenFunction CGF(CGM);
2109 CGF.CurGD = GlobalDecl(MD);
2110 CGF.CurFuncIsThunk = true;
2111
2112 // Build FunctionArgs, but only include the implicit 'this' parameter
2113 // declaration.
2114 FunctionArgList FunctionArgs;
2115 buildThisParam(CGF, FunctionArgs);
2116
2117 // Start defining the function.
2118 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2119 FunctionArgs, MD->getLocation(), SourceLocation());
2120
2121 ApplyDebugLocation AL(CGF, MD->getLocation());
2122 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2123
2124 // Load the vfptr and then callee from the vftable. The callee should have
2125 // adjusted 'this' so that the vfptr is at offset zero.
2126 llvm::Type *ThunkPtrTy = ThunkTy->getPointerTo();
2127 llvm::Value *VTable = CGF.GetVTablePtr(
2128 getThisAddress(CGF), ThunkPtrTy->getPointerTo(), MD->getParent());
2129
2130 llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2131 ThunkPtrTy, VTable, ML.Index, "vfn");
2132 llvm::Value *Callee =
2133 CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
2134
2135 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2136
2137 return ThunkFn;
2138}
2139
2140void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2141 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2142 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2143 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2144 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2145 if (GV->isDeclaration())
2146 emitVBTableDefinition(*VBT, RD, GV);
2147 }
2148}
2149
2150llvm::GlobalVariable *
2151MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2152 llvm::GlobalVariable::LinkageTypes Linkage) {
2153 SmallString<256> OutName;
2154 llvm::raw_svector_ostream Out(OutName);
2155 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2156 StringRef Name = OutName.str();
2157
2158 llvm::ArrayType *VBTableType =
2159 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2160
2161 assert(!CGM.getModule().getNamedGlobal(Name) &&
2162 "vbtable with this name already exists: mangling bug?");
2163 CharUnits Alignment =
2165 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2166 Name, VBTableType, Linkage, Alignment.getAsAlign());
2167 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2168
2169 if (RD->hasAttr<DLLImportAttr>())
2170 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2171 else if (RD->hasAttr<DLLExportAttr>())
2172 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2173
2174 if (!GV->hasExternalLinkage())
2175 emitVBTableDefinition(VBT, RD, GV);
2176
2177 return GV;
2178}
2179
2180void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2181 const CXXRecordDecl *RD,
2182 llvm::GlobalVariable *GV) const {
2183 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2184
2185 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2186 "should only emit vbtables for classes with vbtables");
2187
2188 const ASTRecordLayout &BaseLayout =
2189 getContext().getASTRecordLayout(VBT.IntroducingObject);
2190 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2191
2192 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2193 nullptr);
2194
2195 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2196 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2197 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2198
2200 for (const auto &I : ObjectWithVPtr->vbases()) {
2201 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2202 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2203 assert(!Offset.isNegative());
2204
2205 // Make it relative to the subobject vbptr.
2206 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2207 if (VBT.getVBaseWithVPtr())
2208 CompleteVBPtrOffset +=
2209 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2210 Offset -= CompleteVBPtrOffset;
2211
2212 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2213 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2214 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2215 }
2216
2217 assert(Offsets.size() ==
2218 cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
2219 llvm::ArrayType *VBTableType =
2220 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2221 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2222 GV->setInitializer(Init);
2223
2224 if (RD->hasAttr<DLLImportAttr>())
2225 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2226}
2227
2228llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2229 Address This,
2230 const ThisAdjustment &TA) {
2231 if (TA.isEmpty())
2232 return This.emitRawPointer(CGF);
2233
2234 This = This.withElementType(CGF.Int8Ty);
2235
2236 llvm::Value *V;
2237 if (TA.Virtual.isEmpty()) {
2238 V = This.emitRawPointer(CGF);
2239 } else {
2240 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2241 // Adjust the this argument based on the vtordisp value.
2242 Address VtorDispPtr =
2245 VtorDispPtr = VtorDispPtr.withElementType(CGF.Int32Ty);
2246 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2247 V = CGF.Builder.CreateGEP(This.getElementType(), This.emitRawPointer(CGF),
2248 CGF.Builder.CreateNeg(VtorDisp));
2249
2250 // Unfortunately, having applied the vtordisp means that we no
2251 // longer really have a known alignment for the vbptr step.
2252 // We'll assume the vbptr is pointer-aligned.
2253
2254 if (TA.Virtual.Microsoft.VBPtrOffset) {
2255 // If the final overrider is defined in a virtual base other than the one
2256 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2257 // the vbtable of the derived class.
2258 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2259 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2260 llvm::Value *VBPtr;
2261 llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(
2262 CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),
2264 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2265 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2266 }
2267 }
2268
2269 if (TA.NonVirtual) {
2270 // Non-virtual adjustment might result in a pointer outside the allocated
2271 // object, e.g. if the final overrider class is laid out after the virtual
2272 // base that declares a method in the most derived class.
2273 V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
2274 }
2275
2276 // Don't need to bitcast back, the call CodeGen will handle this.
2277 return V;
2278}
2279
2280llvm::Value *
2281MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2282 const ReturnAdjustment &RA) {
2283 if (RA.isEmpty())
2284 return Ret.emitRawPointer(CGF);
2285
2286 Ret = Ret.withElementType(CGF.Int8Ty);
2287
2288 llvm::Value *V = Ret.emitRawPointer(CGF);
2289 if (RA.Virtual.Microsoft.VBIndex) {
2290 assert(RA.Virtual.Microsoft.VBIndex > 0);
2291 int32_t IntSize = CGF.getIntSize().getQuantity();
2292 llvm::Value *VBPtr;
2293 llvm::Value *VBaseOffset =
2294 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2295 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2296 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2297 }
2298
2299 if (RA.NonVirtual)
2300 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2301
2302 return V;
2303}
2304
2305bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2306 QualType elementType) {
2307 // Microsoft seems to completely ignore the possibility of a
2308 // two-argument usual deallocation function.
2309 return elementType.isDestructedType();
2310}
2311
2312bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2313 // Microsoft seems to completely ignore the possibility of a
2314 // two-argument usual deallocation function.
2315 return expr->getAllocatedType().isDestructedType();
2316}
2317
2318CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2319 // The array cookie is always a size_t; we then pad that out to the
2320 // alignment of the element type.
2321 ASTContext &Ctx = getContext();
2322 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2324}
2325
2326llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2327 Address allocPtr,
2328 CharUnits cookieSize) {
2329 Address numElementsPtr = allocPtr.withElementType(CGF.SizeTy);
2330 return CGF.Builder.CreateLoad(numElementsPtr);
2331}
2332
2333Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2334 Address newPtr,
2335 llvm::Value *numElements,
2336 const CXXNewExpr *expr,
2337 QualType elementType) {
2338 assert(requiresArrayCookie(expr));
2339
2340 // The size of the cookie.
2341 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2342
2343 // Compute an offset to the cookie.
2344 Address cookiePtr = newPtr;
2345
2346 // Write the number of elements into the appropriate slot.
2347 Address numElementsPtr = cookiePtr.withElementType(CGF.SizeTy);
2348 CGF.Builder.CreateStore(numElements, numElementsPtr);
2349
2350 // Finally, compute a pointer to the actual data buffer by skipping
2351 // over the cookie completely.
2352 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2353}
2354
2356 llvm::FunctionCallee Dtor,
2357 llvm::Constant *Addr) {
2358 // Create a function which calls the destructor.
2359 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2360
2361 // extern "C" int __tlregdtor(void (*f)(void));
2362 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2363 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2364
2365 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2366 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2367 if (llvm::Function *TLRegDtorFn =
2368 dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2369 TLRegDtorFn->setDoesNotThrow();
2370
2371 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2372}
2373
2374void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2375 llvm::FunctionCallee Dtor,
2376 llvm::Constant *Addr) {
2377 if (D.isNoDestroy(CGM.getContext()))
2378 return;
2379
2380 if (D.getTLSKind())
2381 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2382
2383 // HLSL doesn't support atexit.
2384 if (CGM.getLangOpts().HLSL)
2385 return CGM.AddCXXDtorEntry(Dtor, Addr);
2386
2387 // The default behavior is to use atexit.
2388 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2389}
2390
2391void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2392 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2393 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2394 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2395 if (CXXThreadLocalInits.empty())
2396 return;
2397
2398 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2399 llvm::Triple::x86
2400 ? "/include:___dyn_tls_init@12"
2401 : "/include:__dyn_tls_init");
2402
2403 // This will create a GV in the .CRT$XDU section. It will point to our
2404 // initialization function. The CRT will call all of these function
2405 // pointers at start-up time and, eventually, at thread-creation time.
2406 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2407 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2408 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2409 llvm::GlobalVariable::InternalLinkage, InitFunc,
2410 Twine(InitFunc->getName(), "$initializer$"));
2411 InitFuncPtr->setSection(".CRT$XDU");
2412 // This variable has discardable linkage, we have to add it to @llvm.used to
2413 // ensure it won't get discarded.
2414 CGM.addUsedGlobal(InitFuncPtr);
2415 return InitFuncPtr;
2416 };
2417
2418 std::vector<llvm::Function *> NonComdatInits;
2419 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2420 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2421 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2422 llvm::Function *F = CXXThreadLocalInits[I];
2423
2424 // If the GV is already in a comdat group, then we have to join it.
2425 if (llvm::Comdat *C = GV->getComdat())
2426 AddToXDU(F)->setComdat(C);
2427 else
2428 NonComdatInits.push_back(F);
2429 }
2430
2431 if (!NonComdatInits.empty()) {
2432 llvm::FunctionType *FTy =
2433 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2434 llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
2435 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2436 SourceLocation(), /*TLS=*/true);
2437 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2438
2439 AddToXDU(InitFunc);
2440 }
2441}
2442
2443static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
2444 // __tls_guard comes from the MSVC runtime and reflects
2445 // whether TLS has been initialized for a particular thread.
2446 // It is set from within __dyn_tls_init by the runtime.
2447 // Every library and executable has its own variable.
2448 llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
2449 llvm::Constant *TlsGuardConstant =
2450 CGM.CreateRuntimeVariable(VTy, "__tls_guard");
2451 llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
2452
2453 TlsGuard->setThreadLocal(true);
2454
2455 return TlsGuard;
2456}
2457
2458static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
2459 // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
2460 // dynamic TLS initialization by calling __dyn_tls_init internally.
2461 llvm::FunctionType *FTy =
2462 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
2463 /*isVarArg=*/false);
2464 return CGM.CreateRuntimeFunction(
2465 FTy, "__dyn_tls_on_demand_init",
2466 llvm::AttributeList::get(CGM.getLLVMContext(),
2467 llvm::AttributeList::FunctionIndex,
2468 llvm::Attribute::NoUnwind),
2469 /*Local=*/true);
2470}
2471
2472static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
2473 llvm::BasicBlock *DynInitBB,
2474 llvm::BasicBlock *ContinueBB) {
2475 llvm::LoadInst *TlsGuardValue =
2476 CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));
2477 llvm::Value *CmpResult =
2478 CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
2479 CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
2480}
2481
2483 llvm::GlobalValue *TlsGuard,
2484 llvm::BasicBlock *ContinueBB) {
2485 llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
2486 llvm::Function *InitializerFunction =
2487 cast<llvm::Function>(Initializer.getCallee());
2488 llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
2489 CallVal->setCallingConv(InitializerFunction->getCallingConv());
2490
2491 CGF.Builder.CreateBr(ContinueBB);
2492}
2493
2495 llvm::BasicBlock *DynInitBB =
2496 CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
2497 llvm::BasicBlock *ContinueBB =
2498 CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
2499
2500 llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
2501
2502 emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
2503 CGF.Builder.SetInsertPoint(DynInitBB);
2504 emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
2505 CGF.Builder.SetInsertPoint(ContinueBB);
2506}
2507
2508LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2509 const VarDecl *VD,
2510 QualType LValType) {
2511 // Dynamic TLS initialization works by checking the state of a
2512 // guard variable (__tls_guard) to see whether TLS initialization
2513 // for a thread has happend yet.
2514 // If not, the initialization is triggered on-demand
2515 // by calling __dyn_tls_on_demand_init.
2517
2518 // Emit the variable just like any regular global variable.
2519
2520 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2521 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2522
2523 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2524 Address Addr(V, RealVarTy, Alignment);
2525
2526 LValue LV = VD->getType()->isReferenceType()
2527 ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2528 AlignmentSource::Decl)
2529 : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
2530 return LV;
2531}
2532
2534 StringRef VarName("_Init_thread_epoch");
2535 CharUnits Align = CGM.getIntAlign();
2536 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2537 return ConstantAddress(GV, GV->getValueType(), Align);
2538 auto *GV = new llvm::GlobalVariable(
2539 CGM.getModule(), CGM.IntTy,
2540 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2541 /*Initializer=*/nullptr, VarName,
2542 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2543 GV->setAlignment(Align.getAsAlign());
2544 return ConstantAddress(GV, GV->getValueType(), Align);
2545}
2546
2547static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2548 llvm::FunctionType *FTy =
2549 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2550 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2551 return CGM.CreateRuntimeFunction(
2552 FTy, "_Init_thread_header",
2553 llvm::AttributeList::get(CGM.getLLVMContext(),
2554 llvm::AttributeList::FunctionIndex,
2555 llvm::Attribute::NoUnwind),
2556 /*Local=*/true);
2557}
2558
2559static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2560 llvm::FunctionType *FTy =
2561 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2562 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2563 return CGM.CreateRuntimeFunction(
2564 FTy, "_Init_thread_footer",
2565 llvm::AttributeList::get(CGM.getLLVMContext(),
2566 llvm::AttributeList::FunctionIndex,
2567 llvm::Attribute::NoUnwind),
2568 /*Local=*/true);
2569}
2570
2571static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2572 llvm::FunctionType *FTy =
2573 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2574 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2575 return CGM.CreateRuntimeFunction(
2576 FTy, "_Init_thread_abort",
2577 llvm::AttributeList::get(CGM.getLLVMContext(),
2578 llvm::AttributeList::FunctionIndex,
2579 llvm::Attribute::NoUnwind),
2580 /*Local=*/true);
2581}
2582
2583namespace {
2584struct ResetGuardBit final : EHScopeStack::Cleanup {
2585 Address Guard;
2586 unsigned GuardNum;
2587 ResetGuardBit(Address Guard, unsigned GuardNum)
2588 : Guard(Guard), GuardNum(GuardNum) {}
2589
2590 void Emit(CodeGenFunction &CGF, Flags flags) override {
2591 // Reset the bit in the mask so that the static variable may be
2592 // reinitialized.
2593 CGBuilderTy &Builder = CGF.Builder;
2594 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2595 llvm::ConstantInt *Mask =
2596 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2597 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2598 }
2599};
2600
2601struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2602 llvm::Value *Guard;
2603 CallInitThreadAbort(RawAddress Guard) : Guard(Guard.getPointer()) {}
2604
2605 void Emit(CodeGenFunction &CGF, Flags flags) override {
2606 // Calling _Init_thread_abort will reset the guard's state.
2608 }
2609};
2610}
2611
2612void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2613 llvm::GlobalVariable *GV,
2614 bool PerformInit) {
2615 // MSVC only uses guards for static locals.
2616 if (!D.isStaticLocal()) {
2617 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2618 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2619 llvm::Function *F = CGF.CurFn;
2620 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2621 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2622 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2623 return;
2624 }
2625
2626 bool ThreadlocalStatic = D.getTLSKind();
2627 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2628
2629 // Thread-safe static variables which aren't thread-specific have a
2630 // per-variable guard.
2631 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2632
2633 CGBuilderTy &Builder = CGF.Builder;
2634 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2635 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2636 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2637
2638 // Get the guard variable for this function if we have one already.
2639 GuardInfo *GI = nullptr;
2640 if (ThreadlocalStatic)
2641 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2642 else if (!ThreadsafeStatic)
2643 GI = &GuardVariableMap[D.getDeclContext()];
2644
2645 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2646 unsigned GuardNum;
2647 if (D.isExternallyVisible()) {
2648 // Externally visible variables have to be numbered in Sema to properly
2649 // handle unreachable VarDecls.
2650 GuardNum = getContext().getStaticLocalNumber(&D);
2651 assert(GuardNum > 0);
2652 GuardNum--;
2653 } else if (HasPerVariableGuard) {
2654 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2655 } else {
2656 // Non-externally visible variables are numbered here in CodeGen.
2657 GuardNum = GI->BitIndex++;
2658 }
2659
2660 if (!HasPerVariableGuard && GuardNum >= 32) {
2661 if (D.isExternallyVisible())
2662 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2663 GuardNum %= 32;
2664 GuardVar = nullptr;
2665 }
2666
2667 if (!GuardVar) {
2668 // Mangle the name for the guard.
2669 SmallString<256> GuardName;
2670 {
2671 llvm::raw_svector_ostream Out(GuardName);
2672 if (HasPerVariableGuard)
2673 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2674 Out);
2675 else
2676 getMangleContext().mangleStaticGuardVariable(&D, Out);
2677 }
2678
2679 // Create the guard variable with a zero-initializer. Just absorb linkage,
2680 // visibility and dll storage class from the guarded variable.
2681 GuardVar =
2682 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2683 GV->getLinkage(), Zero, GuardName.str());
2684 GuardVar->setVisibility(GV->getVisibility());
2685 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2686 GuardVar->setAlignment(GuardAlign.getAsAlign());
2687 if (GuardVar->isWeakForLinker())
2688 GuardVar->setComdat(
2689 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2690 if (D.getTLSKind())
2691 CGM.setTLSMode(GuardVar, D);
2692 if (GI && !HasPerVariableGuard)
2693 GI->Guard = GuardVar;
2694 }
2695
2696 ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
2697
2698 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2699 "static local from the same function had different linkage");
2700
2701 if (!HasPerVariableGuard) {
2702 // Pseudo code for the test:
2703 // if (!(GuardVar & MyGuardBit)) {
2704 // GuardVar |= MyGuardBit;
2705 // ... initialize the object ...;
2706 // }
2707
2708 // Test our bit from the guard variable.
2709 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2710 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2711 llvm::Value *NeedsInit =
2712 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2713 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2714 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2715 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2716 CodeGenFunction::GuardKind::VariableGuard, &D);
2717
2718 // Set our bit in the guard variable and emit the initializer and add a global
2719 // destructor if appropriate.
2720 CGF.EmitBlock(InitBlock);
2721 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2722 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2723 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2724 CGF.PopCleanupBlock();
2725 Builder.CreateBr(EndBlock);
2726
2727 // Continue.
2728 CGF.EmitBlock(EndBlock);
2729 } else {
2730 // Pseudo code for the test:
2731 // if (TSS > _Init_thread_epoch) {
2732 // _Init_thread_header(&TSS);
2733 // if (TSS == -1) {
2734 // ... initialize the object ...;
2735 // _Init_thread_footer(&TSS);
2736 // }
2737 // }
2738 //
2739 // The algorithm is almost identical to what can be found in the appendix
2740 // found in N2325.
2741
2742 // This BasicBLock determines whether or not we have any work to do.
2743 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2744 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2745 llvm::LoadInst *InitThreadEpoch =
2746 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2747 llvm::Value *IsUninitialized =
2748 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2749 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2750 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2751 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2752 CodeGenFunction::GuardKind::VariableGuard, &D);
2753
2754 // This BasicBlock attempts to determine whether or not this thread is
2755 // responsible for doing the initialization.
2756 CGF.EmitBlock(AttemptInitBlock);
2758 GuardAddr.getPointer());
2759 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2760 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2761 llvm::Value *ShouldDoInit =
2762 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2763 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2764 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2765
2766 // Ok, we ended up getting selected as the initializing thread.
2767 CGF.EmitBlock(InitBlock);
2768 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2769 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2770 CGF.PopCleanupBlock();
2772 GuardAddr.getPointer());
2773 Builder.CreateBr(EndBlock);
2774
2775 CGF.EmitBlock(EndBlock);
2776 }
2777}
2778
2779bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2780 // Null-ness for function memptrs only depends on the first field, which is
2781 // the function pointer. The rest don't matter, so we can zero initialize.
2782 if (MPT->isMemberFunctionPointer())
2783 return true;
2784
2785 // The virtual base adjustment field is always -1 for null, so if we have one
2786 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2787 // valid field offset.
2788 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2789 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2790 return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2791 RD->nullFieldOffsetIsZero());
2792}
2793
2794llvm::Type *
2795MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2796 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2797 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2799 if (MPT->isMemberFunctionPointer())
2800 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2801 else
2802 fields.push_back(CGM.IntTy); // FieldOffset
2803
2805 Inheritance))
2806 fields.push_back(CGM.IntTy);
2807 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2808 fields.push_back(CGM.IntTy);
2810 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2811
2812 if (fields.size() == 1)
2813 return fields[0];
2814 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2815}
2816
2817void MicrosoftCXXABI::
2818GetNullMemberPointerFields(const MemberPointerType *MPT,
2820 assert(fields.empty());
2821 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2822 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2823 if (MPT->isMemberFunctionPointer()) {
2824 // FunctionPointerOrVirtualThunk
2825 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2826 } else {
2827 if (RD->nullFieldOffsetIsZero())
2828 fields.push_back(getZeroInt()); // FieldOffset
2829 else
2830 fields.push_back(getAllOnesInt()); // FieldOffset
2831 }
2832
2834 Inheritance))
2835 fields.push_back(getZeroInt());
2836 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2837 fields.push_back(getZeroInt());
2839 fields.push_back(getAllOnesInt());
2840}
2841
2842llvm::Constant *
2843MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2845 GetNullMemberPointerFields(MPT, fields);
2846 if (fields.size() == 1)
2847 return fields[0];
2848 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2849 assert(Res->getType() == ConvertMemberPointerType(MPT));
2850 return Res;
2851}
2852
2853llvm::Constant *
2854MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2855 bool IsMemberFunction,
2856 const CXXRecordDecl *RD,
2857 CharUnits NonVirtualBaseAdjustment,
2858 unsigned VBTableIndex) {
2859 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2860
2861 // Single inheritance class member pointer are represented as scalars instead
2862 // of aggregates.
2863 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2864 return FirstField;
2865
2867 fields.push_back(FirstField);
2868
2869 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2870 fields.push_back(llvm::ConstantInt::get(
2871 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2872
2873 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2874 CharUnits Offs = CharUnits::Zero();
2875 if (VBTableIndex)
2876 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2877 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2878 }
2879
2880 // The rest of the fields are adjusted by conversions to a more derived class.
2882 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2883
2884 return llvm::ConstantStruct::getAnon(fields);
2885}
2886
2887llvm::Constant *
2888MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2889 CharUnits offset) {
2890 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2891}
2892
2893llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2894 CharUnits offset) {
2895 if (RD->getMSInheritanceModel() ==
2896 MSInheritanceModel::Virtual)
2897 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2898 llvm::Constant *FirstField =
2899 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2900 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2901 CharUnits::Zero(), /*VBTableIndex=*/0);
2902}
2903
2904llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2905 QualType MPType) {
2906 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2907 const ValueDecl *MPD = MP.getMemberPointerDecl();
2908 if (!MPD)
2909 return EmitNullMemberPointer(DstTy);
2910
2911 ASTContext &Ctx = getContext();
2913
2914 llvm::Constant *C;
2915 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2916 C = EmitMemberFunctionPointer(MD);
2917 } else {
2918 // For a pointer to data member, start off with the offset of the field in
2919 // the class in which it was declared, and convert from there if necessary.
2920 // For indirect field decls, get the outermost anonymous field and use the
2921 // parent class.
2922 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2923 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2924 if (!FD)
2925 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2926 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2928 C = EmitMemberDataPointer(RD, FieldOffset);
2929 }
2930
2931 if (!MemberPointerPath.empty()) {
2932 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2933 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2934 const MemberPointerType *SrcTy =
2935 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2937
2938 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2940 const CXXRecordDecl *PrevRD = SrcRD;
2941 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2942 const CXXRecordDecl *Base = nullptr;
2943 const CXXRecordDecl *Derived = nullptr;
2944 if (DerivedMember) {
2945 Base = PathElem;
2946 Derived = PrevRD;
2947 } else {
2948 Base = PrevRD;
2949 Derived = PathElem;
2950 }
2951 for (const CXXBaseSpecifier &BS : Derived->bases())
2952 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2953 Base->getCanonicalDecl())
2954 DerivedToBasePath.push_back(&BS);
2955 PrevRD = PathElem;
2956 }
2957 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2958
2959 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2960 : CK_BaseToDerivedMemberPointer;
2961 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2962 DerivedToBasePath.end(), C);
2963 }
2964 return C;
2965}
2966
2967llvm::Constant *
2968MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2969 assert(MD->isInstance() && "Member function must not be static!");
2970
2971 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2973 CodeGenTypes &Types = CGM.getTypes();
2974
2975 unsigned VBTableIndex = 0;
2976 llvm::Constant *FirstField;
2977 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2978 if (!MD->isVirtual()) {
2979 llvm::Type *Ty;
2980 // Check whether the function has a computable LLVM signature.
2981 if (Types.isFuncTypeConvertible(FPT)) {
2982 // The function has a computable LLVM signature; use the correct type.
2983 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2984 } else {
2985 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2986 // function type is incomplete.
2987 Ty = CGM.PtrDiffTy;
2988 }
2989 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2990 } else {
2991 auto &VTableContext = CGM.getMicrosoftVTableContext();
2992 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2993 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2994 // Include the vfptr adjustment if the method is in a non-primary vftable.
2995 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2996 if (ML.VBase)
2997 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2998 }
2999
3000 if (VBTableIndex == 0 &&
3001 RD->getMSInheritanceModel() ==
3002 MSInheritanceModel::Virtual)
3003 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
3004
3005 // The rest of the fields are common with data member pointers.
3006 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
3007 NonVirtualBaseAdjustment, VBTableIndex);
3008}
3009
3010/// Member pointers are the same if they're either bitwise identical *or* both
3011/// null. Null-ness for function members is determined by the first field,
3012/// while for data member pointers we must compare all fields.
3013llvm::Value *
3014MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
3015 llvm::Value *L,
3016 llvm::Value *R,
3017 const MemberPointerType *MPT,
3018 bool Inequality) {
3019 CGBuilderTy &Builder = CGF.Builder;
3020
3021 // Handle != comparisons by switching the sense of all boolean operations.
3022 llvm::ICmpInst::Predicate Eq;
3023 llvm::Instruction::BinaryOps And, Or;
3024 if (Inequality) {
3025 Eq = llvm::ICmpInst::ICMP_NE;
3026 And = llvm::Instruction::Or;
3027 Or = llvm::Instruction::And;
3028 } else {
3029 Eq = llvm::ICmpInst::ICMP_EQ;
3030 And = llvm::Instruction::And;
3031 Or = llvm::Instruction::Or;
3032 }
3033
3034 // If this is a single field member pointer (single inheritance), this is a
3035 // single icmp.
3036 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3037 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3039 Inheritance))
3040 return Builder.CreateICmp(Eq, L, R);
3041
3042 // Compare the first field.
3043 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
3044 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
3045 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
3046
3047 // Compare everything other than the first field.
3048 llvm::Value *Res = nullptr;
3049 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
3050 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
3051 llvm::Value *LF = Builder.CreateExtractValue(L, I);
3052 llvm::Value *RF = Builder.CreateExtractValue(R, I);
3053 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
3054 if (Res)
3055 Res = Builder.CreateBinOp(And, Res, Cmp);
3056 else
3057 Res = Cmp;
3058 }
3059
3060 // Check if the first field is 0 if this is a function pointer.
3061 if (MPT->isMemberFunctionPointer()) {
3062 // (l1 == r1 && ...) || l0 == 0
3063 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
3064 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
3065 Res = Builder.CreateBinOp(Or, Res, IsZero);
3066 }
3067
3068 // Combine the comparison of the first field, which must always be true for
3069 // this comparison to succeeed.
3070 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
3071}
3072
3073llvm::Value *
3074MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
3075 llvm::Value *MemPtr,
3076 const MemberPointerType *MPT) {
3077 CGBuilderTy &Builder = CGF.Builder;
3079 // We only need one field for member functions.
3080 if (MPT->isMemberFunctionPointer())
3081 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
3082 else
3083 GetNullMemberPointerFields(MPT, fields);
3084 assert(!fields.empty());
3085 llvm::Value *FirstField = MemPtr;
3086 if (MemPtr->getType()->isStructTy())
3087 FirstField = Builder.CreateExtractValue(MemPtr, 0);
3088 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
3089
3090 // For function member pointers, we only need to test the function pointer
3091 // field. The other fields if any can be garbage.
3092 if (MPT->isMemberFunctionPointer())
3093 return Res;
3094
3095 // Otherwise, emit a series of compares and combine the results.
3096 for (int I = 1, E = fields.size(); I < E; ++I) {
3097 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
3098 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
3099 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
3100 }
3101 return Res;
3102}
3103
3104bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
3105 llvm::Constant *Val) {
3106 // Function pointers are null if the pointer in the first field is null.
3107 if (MPT->isMemberFunctionPointer()) {
3108 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
3109 Val->getAggregateElement(0U) : Val;
3110 return FirstField->isNullValue();
3111 }
3112
3113 // If it's not a function pointer and it's zero initializable, we can easily
3114 // check zero.
3115 if (isZeroInitializable(MPT) && Val->isNullValue())
3116 return true;
3117
3118 // Otherwise, break down all the fields for comparison. Hopefully these
3119 // little Constants are reused, while a big null struct might not be.
3121 GetNullMemberPointerFields(MPT, Fields);
3122 if (Fields.size() == 1) {
3123 assert(Val->getType()->isIntegerTy());
3124 return Val == Fields[0];
3125 }
3126
3127 unsigned I, E;
3128 for (I = 0, E = Fields.size(); I != E; ++I) {
3129 if (Val->getAggregateElement(I) != Fields[I])
3130 break;
3131 }
3132 return I == E;
3133}
3134
3135llvm::Value *
3136MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
3137 Address This,
3138 llvm::Value *VBPtrOffset,
3139 llvm::Value *VBTableOffset,
3140 llvm::Value **VBPtrOut) {
3141 CGBuilderTy &Builder = CGF.Builder;
3142 // Load the vbtable pointer from the vbptr in the instance.
3143 llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
3144 CGM.Int8Ty, This.emitRawPointer(CGF), VBPtrOffset, "vbptr");
3145 if (VBPtrOut)
3146 *VBPtrOut = VBPtr;
3147
3148 CharUnits VBPtrAlign;
3149 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
3150 VBPtrAlign = This.getAlignment().alignmentAtOffset(
3151 CharUnits::fromQuantity(CI->getSExtValue()));
3152 } else {
3153 VBPtrAlign = CGF.getPointerAlign();
3154 }
3155
3156 llvm::Value *VBTable = Builder.CreateAlignedLoad(
3157 CGM.Int32Ty->getPointerTo(0), VBPtr, VBPtrAlign, "vbtable");
3158
3159 // Translate from byte offset to table index. It improves analyzability.
3160 llvm::Value *VBTableIndex = Builder.CreateAShr(
3161 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
3162 "vbtindex", /*isExact=*/true);
3163
3164 // Load an i32 offset from the vb-table.
3165 llvm::Value *VBaseOffs =
3166 Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
3167 return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
3168 CharUnits::fromQuantity(4), "vbase_offs");
3169}
3170
3171// Returns an adjusted base cast to i8*, since we do more address arithmetic on
3172// it.
3173llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3174 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3175 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3176 CGBuilderTy &Builder = CGF.Builder;
3177 Base = Base.withElementType(CGM.Int8Ty);
3178 llvm::BasicBlock *OriginalBB = nullptr;
3179 llvm::BasicBlock *SkipAdjustBB = nullptr;
3180 llvm::BasicBlock *VBaseAdjustBB = nullptr;
3181
3182 // In the unspecified inheritance model, there might not be a vbtable at all,
3183 // in which case we need to skip the virtual base lookup. If there is a
3184 // vbtable, the first entry is a no-op entry that gives back the original
3185 // base, so look for a virtual base adjustment offset of zero.
3186 if (VBPtrOffset) {
3187 OriginalBB = Builder.GetInsertBlock();
3188 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3189 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3190 llvm::Value *IsVirtual =
3191 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3192 "memptr.is_vbase");
3193 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3194 CGF.EmitBlock(VBaseAdjustBB);
3195 }
3196
3197 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3198 // know the vbptr offset.
3199 if (!VBPtrOffset) {
3200 CharUnits offs = CharUnits::Zero();
3201 if (!RD->hasDefinition()) {
3202 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3203 unsigned DiagID = Diags.getCustomDiagID(
3205 "member pointer representation requires a "
3206 "complete class type for %0 to perform this expression");
3207 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3208 } else if (RD->getNumVBases())
3209 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3210 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3211 }
3212 llvm::Value *VBPtr = nullptr;
3213 llvm::Value *VBaseOffs =
3214 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3215 llvm::Value *AdjustedBase =
3216 Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
3217
3218 // Merge control flow with the case where we didn't have to adjust.
3219 if (VBaseAdjustBB) {
3220 Builder.CreateBr(SkipAdjustBB);
3221 CGF.EmitBlock(SkipAdjustBB);
3222 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3223 Phi->addIncoming(Base.emitRawPointer(CGF), OriginalBB);
3224 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3225 return Phi;
3226 }
3227 return AdjustedBase;
3228}
3229
3230llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3231 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3232 const MemberPointerType *MPT) {
3233 assert(MPT->isMemberDataPointer());
3234 CGBuilderTy &Builder = CGF.Builder;
3235 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3236 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3237
3238 // Extract the fields we need, regardless of model. We'll apply them if we
3239 // have them.
3240 llvm::Value *FieldOffset = MemPtr;
3241 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3242 llvm::Value *VBPtrOffset = nullptr;
3243 if (MemPtr->getType()->isStructTy()) {
3244 // We need to extract values.
3245 unsigned I = 0;
3246 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3247 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3248 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3250 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3251 }
3252
3253 llvm::Value *Addr;
3254 if (VirtualBaseAdjustmentOffset) {
3255 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3256 VBPtrOffset);
3257 } else {
3258 Addr = Base.emitRawPointer(CGF);
3259 }
3260
3261 // Apply the offset, which we assume is non-null.
3262 return Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
3263 "memptr.offset");
3264}
3265
3266llvm::Value *
3267MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3268 const CastExpr *E,
3269 llvm::Value *Src) {
3270 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3271 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3272 E->getCastKind() == CK_ReinterpretMemberPointer);
3273
3274 // Use constant emission if we can.
3275 if (isa<llvm::Constant>(Src))
3276 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3277
3278 // We may be adding or dropping fields from the member pointer, so we need
3279 // both types and the inheritance models of both records.
3280 const MemberPointerType *SrcTy =
3282 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3283 bool IsFunc = SrcTy->isMemberFunctionPointer();
3284
3285 // If the classes use the same null representation, reinterpret_cast is a nop.
3286 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3287 if (IsReinterpret && IsFunc)
3288 return Src;
3289
3290 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3291 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3292 if (IsReinterpret &&
3293 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3294 return Src;
3295
3296 CGBuilderTy &Builder = CGF.Builder;
3297
3298 // Branch past the conversion if Src is null.
3299 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3300 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3301
3302 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3303 // pointer value of the destination type.
3304 if (IsReinterpret) {
3305 // For reinterpret casts, sema ensures that src and dst are both functions
3306 // or data and have the same size, which means the LLVM types should match.
3307 assert(Src->getType() == DstNull->getType());
3308 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3309 }
3310
3311 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3312 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3313 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3314 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3315 CGF.EmitBlock(ConvertBB);
3316
3317 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3318 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3319 Builder);
3320
3321 Builder.CreateBr(ContinueBB);
3322
3323 // In the continuation, choose between DstNull and Dst.
3324 CGF.EmitBlock(ContinueBB);
3325 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3326 Phi->addIncoming(DstNull, OriginalBB);
3327 Phi->addIncoming(Dst, ConvertBB);
3328 return Phi;
3329}
3330
3331llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3332 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3334 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3335 CGBuilderTy &Builder) {
3336 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3337 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3338 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3339 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3340 bool IsFunc = SrcTy->isMemberFunctionPointer();
3341 bool IsConstant = isa<llvm::Constant>(Src);
3342
3343 // Decompose src.
3344 llvm::Value *FirstField = Src;
3345 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3346 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3347 llvm::Value *VBPtrOffset = getZeroInt();
3348 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3349 // We need to extract values.
3350 unsigned I = 0;
3351 FirstField = Builder.CreateExtractValue(Src, I++);
3352 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3353 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3354 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3355 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3356 if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3357 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3358 }
3359
3360 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3361 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3362 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3363
3364 // For data pointers, we adjust the field offset directly. For functions, we
3365 // have a separate field.
3366 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3367
3368 // The virtual inheritance model has a quirk: the virtual base table is always
3369 // referenced when dereferencing a member pointer even if the member pointer
3370 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3371 // to point backwards to the top of the MDC from the first VBase. Undo this
3372 // adjustment to normalize the member pointer.
3373 llvm::Value *SrcVBIndexEqZero =
3374 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3375 if (SrcInheritance == MSInheritanceModel::Virtual) {
3376 if (int64_t SrcOffsetToFirstVBase =
3377 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3378 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3379 SrcVBIndexEqZero,
3380 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3381 getZeroInt());
3382 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3383 }
3384 }
3385
3386 // A non-zero vbindex implies that we are dealing with a source member in a
3387 // floating virtual base in addition to some non-virtual offset. If the
3388 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3389 // fixed, base. The difference between these two cases is that the vbindex +
3390 // nvoffset *always* point to the member regardless of what context they are
3391 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3392 // base requires explicit nv adjustment.
3393 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3394 CGM.IntTy,
3395 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3396 .getQuantity());
3397
3398 llvm::Value *NVDisp;
3399 if (IsDerivedToBase)
3400 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3401 else
3402 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3403
3404 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3405
3406 // Update the vbindex to an appropriate value in the destination because
3407 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3408 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3409 if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3410 inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3411 if (llvm::GlobalVariable *VDispMap =
3412 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3413 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3414 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3415 if (IsConstant) {
3416 llvm::Constant *Mapping = VDispMap->getInitializer();
3417 VirtualBaseAdjustmentOffset =
3418 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3419 } else {
3420 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3421 VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
3422 CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
3423 VDispMap, Idxs),
3425 }
3426
3427 DstVBIndexEqZero =
3428 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3429 }
3430 }
3431
3432 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3433 // it to the offset of the vbptr.
3434 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3435 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3436 CGM.IntTy,
3437 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3438 VBPtrOffset =
3439 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3440 }
3441
3442 // Likewise, apply a similar adjustment so that dereferencing the member
3443 // pointer correctly accounts for the distance between the start of the first
3444 // virtual base and the top of the MDC.
3445 if (DstInheritance == MSInheritanceModel::Virtual) {
3446 if (int64_t DstOffsetToFirstVBase =
3447 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3448 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3449 DstVBIndexEqZero,
3450 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3451 getZeroInt());
3452 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3453 }
3454 }
3455
3456 // Recompose dst from the null struct and the adjusted fields from src.
3457 llvm::Value *Dst;
3458 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3459 Dst = FirstField;
3460 } else {
3461 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3462 unsigned Idx = 0;
3463 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3464 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3465 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3466 if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3467 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3468 if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3469 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3470 }
3471 return Dst;
3472}
3473
3474llvm::Constant *
3475MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3476 llvm::Constant *Src) {
3477 const MemberPointerType *SrcTy =
3479 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3480
3481 CastKind CK = E->getCastKind();
3482
3483 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3484 E->path_end(), Src);
3485}
3486
3487llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3488 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3490 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3491 assert(CK == CK_DerivedToBaseMemberPointer ||
3492 CK == CK_BaseToDerivedMemberPointer ||
3493 CK == CK_ReinterpretMemberPointer);
3494 // If src is null, emit a new null for dst. We can't return src because dst
3495 // might have a new representation.
3496 if (MemberPointerConstantIsNull(SrcTy, Src))
3497 return EmitNullMemberPointer(DstTy);
3498
3499 // We don't need to do anything for reinterpret_casts of non-null member
3500 // pointers. We should only get here when the two type representations have
3501 // the same size.
3502 if (CK == CK_ReinterpretMemberPointer)
3503 return Src;
3504
3505 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3506 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3507 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3508
3509 return Dst;
3510}
3511
3512CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3513 CodeGenFunction &CGF, const Expr *E, Address This,
3514 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3515 const MemberPointerType *MPT) {
3516 assert(MPT->isMemberFunctionPointer());
3517 const FunctionProtoType *FPT =
3519 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3520 CGBuilderTy &Builder = CGF.Builder;
3521
3522 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3523
3524 // Extract the fields we need, regardless of model. We'll apply them if we
3525 // have them.
3526 llvm::Value *FunctionPointer = MemPtr;
3527 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3528 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3529 llvm::Value *VBPtrOffset = nullptr;
3530 if (MemPtr->getType()->isStructTy()) {
3531 // We need to extract values.
3532 unsigned I = 0;
3533 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3534 if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3535 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3536 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3537 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3539 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3540 }
3541
3542 if (VirtualBaseAdjustmentOffset) {
3543 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3544 VirtualBaseAdjustmentOffset, VBPtrOffset);
3545 } else {
3546 ThisPtrForCall = This.emitRawPointer(CGF);
3547 }
3548
3549 if (NonVirtualBaseAdjustment)
3550 ThisPtrForCall = Builder.CreateInBoundsGEP(CGF.Int8Ty, ThisPtrForCall,
3551 NonVirtualBaseAdjustment);
3552
3553 CGCallee Callee(FPT, FunctionPointer);
3554 return Callee;
3555}
3556
3558 return new MicrosoftCXXABI(CGM);
3559}
3560
3561// MS RTTI Overview:
3562// The run time type information emitted by cl.exe contains 5 distinct types of
3563// structures. Many of them reference each other.
3564//
3565// TypeInfo: Static classes that are returned by typeid.
3566//
3567// CompleteObjectLocator: Referenced by vftables. They contain information
3568// required for dynamic casting, including OffsetFromTop. They also contain
3569// a reference to the TypeInfo for the type and a reference to the
3570// CompleteHierarchyDescriptor for the type.
3571//
3572// ClassHierarchyDescriptor: Contains information about a class hierarchy.
3573// Used during dynamic_cast to walk a class hierarchy. References a base
3574// class array and the size of said array.
3575//
3576// BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3577// somewhat of a misnomer because the most derived class is also in the list
3578// as well as multiple copies of virtual bases (if they occur multiple times
3579// in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
3580// every path in the hierarchy, in pre-order depth first order. Note, we do
3581// not declare a specific llvm type for BaseClassArray, it's merely an array
3582// of BaseClassDescriptor pointers.
3583//
3584// BaseClassDescriptor: Contains information about a class in a class hierarchy.
3585// BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3586// BaseClassArray is. It contains information about a class within a
3587// hierarchy such as: is this base is ambiguous and what is its offset in the
3588// vbtable. The names of the BaseClassDescriptors have all of their fields
3589// mangled into them so they can be aggressively deduplicated by the linker.
3590
3591static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3592 StringRef MangledName("??_7type_info@@6B@");
3593 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3594 return VTable;
3595 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3596 /*isConstant=*/true,
3597 llvm::GlobalVariable::ExternalLinkage,
3598 /*Initializer=*/nullptr, MangledName);
3599}
3600
3601namespace {
3602
3603/// A Helper struct that stores information about a class in a class
3604/// hierarchy. The information stored in these structs struct is used during
3605/// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3606// During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3607// implicit depth first pre-order tree connectivity. getFirstChild and
3608// getNextSibling allow us to walk the tree efficiently.
3609struct MSRTTIClass {
3610 enum {
3611 IsPrivateOnPath = 1 | 8,
3612 IsAmbiguous = 2,
3613 IsPrivate = 4,
3614 IsVirtual = 16,
3615 HasHierarchyDescriptor = 64
3616 };
3617 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3618 uint32_t initialize(const MSRTTIClass *Parent,
3619 const CXXBaseSpecifier *Specifier);
3620
3621 MSRTTIClass *getFirstChild() { return this + 1; }
3622 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3623 return Child + 1 + Child->NumBases;
3624 }
3625
3626 const CXXRecordDecl *RD, *VirtualRoot;
3627 uint32_t Flags, NumBases, OffsetInVBase;
3628};
3629
3630/// Recursively initialize the base class array.
3631uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3632 const CXXBaseSpecifier *Specifier) {
3633 Flags = HasHierarchyDescriptor;
3634 if (!Parent) {
3635 VirtualRoot = nullptr;
3636 OffsetInVBase = 0;
3637 } else {
3638 if (Specifier->getAccessSpecifier() != AS_public)
3639 Flags |= IsPrivate | IsPrivateOnPath;
3640 if (Specifier->isVirtual()) {
3641 Flags |= IsVirtual;
3642 VirtualRoot = RD;
3643 OffsetInVBase = 0;
3644 } else {
3645 if (Parent->Flags & IsPrivateOnPath)
3646 Flags |= IsPrivateOnPath;
3647 VirtualRoot = Parent->VirtualRoot;
3648 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3649 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3650 }
3651 }
3652 NumBases = 0;
3653 MSRTTIClass *Child = getFirstChild();
3654 for (const CXXBaseSpecifier &Base : RD->bases()) {
3655 NumBases += Child->initialize(this, &Base) + 1;
3656 Child = getNextChild(Child);
3657 }
3658 return NumBases;
3659}
3660
3661static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3662 switch (Ty->getLinkage()) {
3663 case Linkage::Invalid:
3664 llvm_unreachable("Linkage hasn't been computed!");
3665
3666 case Linkage::None:
3667 case Linkage::Internal:
3668 case Linkage::UniqueExternal:
3669 return llvm::GlobalValue::InternalLinkage;
3670
3671 case Linkage::VisibleNone:
3672 case Linkage::Module:
3673 case Linkage::External:
3674 return llvm::GlobalValue::LinkOnceODRLinkage;
3675 }
3676 llvm_unreachable("Invalid linkage!");
3677}
3678
3679/// An ephemeral helper class for building MS RTTI types. It caches some
3680/// calls to the module and information about the most derived class in a
3681/// hierarchy.
3682struct MSRTTIBuilder {
3683 enum {
3684 HasBranchingHierarchy = 1,
3685 HasVirtualBranchingHierarchy = 2,
3686 HasAmbiguousBases = 4
3687 };
3688
3689 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3690 : CGM(ABI.CGM), Context(CGM.getContext()),
3691 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3692 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3693 ABI(ABI) {}
3694
3695 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3696 llvm::GlobalVariable *
3697 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3698 llvm::GlobalVariable *getClassHierarchyDescriptor();
3699 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3700
3701 CodeGenModule &CGM;
3702 ASTContext &Context;
3703 llvm::LLVMContext &VMContext;
3704 llvm::Module &Module;
3705 const CXXRecordDecl *RD;
3706 llvm::GlobalVariable::LinkageTypes Linkage;
3707 MicrosoftCXXABI &ABI;
3708};
3709
3710} // namespace
3711
3712/// Recursively serializes a class hierarchy in pre-order depth first
3713/// order.
3715 const CXXRecordDecl *RD) {
3716 Classes.push_back(MSRTTIClass(RD));
3717 for (const CXXBaseSpecifier &Base : RD->bases())
3718 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3719}
3720
3721/// Find ambiguity among base classes.
3722static void
3727 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3728 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3729 !VirtualBases.insert(Class->RD).second) {
3730 Class = MSRTTIClass::getNextChild(Class);
3731 continue;
3732 }
3733 if (!UniqueBases.insert(Class->RD).second)
3734 AmbiguousBases.insert(Class->RD);
3735 Class++;
3736 }
3737 if (AmbiguousBases.empty())
3738 return;
3739 for (MSRTTIClass &Class : Classes)
3740 if (AmbiguousBases.count(Class.RD))
3741 Class.Flags |= MSRTTIClass::IsAmbiguous;
3742}
3743
3744llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3745 SmallString<256> MangledName;
3746 {
3747 llvm::raw_svector_ostream Out(MangledName);
3748 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3749 }
3750
3751 // Check to see if we've already declared this ClassHierarchyDescriptor.
3752 if (auto CHD = Module.getNamedGlobal(MangledName))
3753 return CHD;
3754
3755 // Serialize the class hierarchy and initialize the CHD Fields.
3757 serializeClassHierarchy(Classes, RD);
3758 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3759 detectAmbiguousBases(Classes);
3760 int Flags = 0;
3761 for (const MSRTTIClass &Class : Classes) {
3762 if (Class.RD->getNumBases() > 1)
3763 Flags |= HasBranchingHierarchy;
3764 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3765 // believe the field isn't actually used.
3766 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3767 Flags |= HasAmbiguousBases;
3768 }
3769 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3770 Flags |= HasVirtualBranchingHierarchy;
3771 // These gep indices are used to get the address of the first element of the
3772 // base class array.
3773 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3774 llvm::ConstantInt::get(CGM.IntTy, 0)};
3775
3776 // Forward-declare the class hierarchy descriptor
3777 auto Type = ABI.getClassHierarchyDescriptorType();
3778 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3779 /*Initializer=*/nullptr,
3780 MangledName);
3781 if (CHD->isWeakForLinker())
3782 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3783
3784 auto *Bases = getBaseClassArray(Classes);
3785
3786 // Initialize the base class ClassHierarchyDescriptor.
3787 llvm::Constant *Fields[] = {
3788 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3789 llvm::ConstantInt::get(CGM.IntTy, Flags),
3790 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3791 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3792 Bases->getValueType(), Bases,
3793 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3794 };
3795 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3796 return CHD;
3797}
3798
3799llvm::GlobalVariable *
3800MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3801 SmallString<256> MangledName;
3802 {
3803 llvm::raw_svector_ostream Out(MangledName);
3804 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3805 }
3806
3807 // Forward-declare the base class array.
3808 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3809 // mode) bytes of padding. We provide a pointer sized amount of padding by
3810 // adding +1 to Classes.size(). The sections have pointer alignment and are
3811 // marked pick-any so it shouldn't matter.
3812 llvm::Type *PtrType = ABI.getImageRelativeType(
3813 ABI.getBaseClassDescriptorType()->getPointerTo());
3814 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3815 auto *BCA =
3816 new llvm::GlobalVariable(Module, ArrType,
3817 /*isConstant=*/true, Linkage,
3818 /*Initializer=*/nullptr, MangledName);
3819 if (BCA->isWeakForLinker())
3820 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3821
3822 // Initialize the BaseClassArray.
3823 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3824 for (MSRTTIClass &Class : Classes)
3825 BaseClassArrayData.push_back(
3826 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3827 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3828 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3829 return BCA;
3830}
3831
3832llvm::GlobalVariable *
3833MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3834 // Compute the fields for the BaseClassDescriptor. They are computed up front
3835 // because they are mangled into the name of the object.
3836 uint32_t OffsetInVBTable = 0;
3837 int32_t VBPtrOffset = -1;
3838 if (Class.VirtualRoot) {
3839 auto &VTableContext = CGM.getMicrosoftVTableContext();
3840 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3841 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3842 }
3843
3844 SmallString<256> MangledName;
3845 {
3846 llvm::raw_svector_ostream Out(MangledName);
3847 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3848 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3849 Class.Flags, Out);
3850 }
3851
3852 // Check to see if we've already declared this object.
3853 if (auto BCD = Module.getNamedGlobal(MangledName))
3854 return BCD;
3855
3856 // Forward-declare the base class descriptor.
3857 auto Type = ABI.getBaseClassDescriptorType();
3858 auto BCD =
3859 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3860 /*Initializer=*/nullptr, MangledName);
3861 if (BCD->isWeakForLinker())
3862 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3863
3864 // Initialize the BaseClassDescriptor.
3865 llvm::Constant *Fields[] = {
3866 ABI.getImageRelativeConstant(
3867 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3868 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3869 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3870 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3871 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3872 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3873 ABI.getImageRelativeConstant(
3874 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3875 };
3876 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3877 return BCD;
3878}
3879
3880llvm::GlobalVariable *
3881MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3882 SmallString<256> MangledName;
3883 {
3884 llvm::raw_svector_ostream Out(MangledName);
3885 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3886 }
3887
3888 // Check to see if we've already computed this complete object locator.
3889 if (auto COL = Module.getNamedGlobal(MangledName))
3890 return COL;
3891
3892 // Compute the fields of the complete object locator.
3893 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3894 int VFPtrOffset = 0;
3895 // The offset includes the vtordisp if one exists.
3896 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3897 if (Context.getASTRecordLayout(RD)
3899 .find(VBase)
3900 ->second.hasVtorDisp())
3901 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3902
3903 // Forward-declare the complete object locator.
3904 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3905 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3906 /*Initializer=*/nullptr, MangledName);
3907
3908 // Initialize the CompleteObjectLocator.
3909 llvm::Constant *Fields[] = {
3910 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3911 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3912 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3913 ABI.getImageRelativeConstant(
3914 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3915 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3916 ABI.getImageRelativeConstant(COL),
3917 };
3918 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3919 if (!ABI.isImageRelative())
3920 FieldsRef = FieldsRef.drop_back();
3921 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3922 if (COL->isWeakForLinker())
3923 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3924 return COL;
3925}
3926
3928 bool &IsConst, bool &IsVolatile,
3929 bool &IsUnaligned) {
3930 T = Context.getExceptionObjectType(T);
3931
3932 // C++14 [except.handle]p3:
3933 // A handler is a match for an exception object of type E if [...]
3934 // - the handler is of type cv T or const T& where T is a pointer type and
3935 // E is a pointer type that can be converted to T by [...]
3936 // - a qualification conversion
3937 IsConst = false;
3938 IsVolatile = false;
3939 IsUnaligned = false;
3940 QualType PointeeType = T->getPointeeType();
3941 if (!PointeeType.isNull()) {
3942 IsConst = PointeeType.isConstQualified();
3943 IsVolatile = PointeeType.isVolatileQualified();
3944 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3945 }
3946
3947 // Member pointer types like "const int A::*" are represented by having RTTI
3948 // for "int A::*" and separately storing the const qualifier.
3949 if (const auto *MPTy = T->getAs<MemberPointerType>())
3950 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3951 MPTy->getClass());
3952
3953 // Pointer types like "const int * const *" are represented by having RTTI
3954 // for "const int **" and separately storing the const qualifier.
3955 if (T->isPointerType())
3956 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3957
3958 return T;
3959}
3960
3962MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3963 QualType CatchHandlerType) {
3964 // TypeDescriptors for exceptions never have qualified pointer types,
3965 // qualifiers are stored separately in order to support qualification
3966 // conversions.
3967 bool IsConst, IsVolatile, IsUnaligned;
3968 Type =
3969 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3970
3971 bool IsReference = CatchHandlerType->isReferenceType();
3972
3973 uint32_t Flags = 0;
3974 if (IsConst)
3975 Flags |= 1;
3976 if (IsVolatile)
3977 Flags |= 2;
3978 if (IsUnaligned)
3979 Flags |= 4;
3980 if (IsReference)
3981 Flags |= 8;
3982
3983 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3984 Flags};
3985}
3986
3987/// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3988/// llvm::GlobalVariable * because different type descriptors have different
3989/// types, and need to be abstracted. They are abstracting by casting the
3990/// address to an Int8PtrTy.
3991llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3992 SmallString<256> MangledName;
3993 {
3994 llvm::raw_svector_ostream Out(MangledName);
3995 getMangleContext().mangleCXXRTTI(Type, Out);
3996 }
3997
3998 // Check to see if we've already declared this TypeDescriptor.
3999 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4000 return GV;
4001
4002 // Note for the future: If we would ever like to do deferred emission of
4003 // RTTI, check if emitting vtables opportunistically need any adjustment.
4004
4005 // Compute the fields for the TypeDescriptor.
4006 SmallString<256> TypeInfoString;
4007 {
4008 llvm::raw_svector_ostream Out(TypeInfoString);
4009 getMangleContext().mangleCXXRTTIName(Type, Out);
4010 }
4011
4012 // Declare and initialize the TypeDescriptor.
4013 llvm::Constant *Fields[] = {
4014 getTypeInfoVTable(CGM), // VFPtr
4015 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
4016 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
4017 llvm::StructType *TypeDescriptorType =
4018 getTypeDescriptorType(TypeInfoString);
4019 auto *Var = new llvm::GlobalVariable(
4020 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
4021 getLinkageForRTTI(Type),
4022 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
4023 MangledName);
4024 if (Var->isWeakForLinker())
4025 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
4026 return Var;
4027}
4028
4029/// Gets or a creates a Microsoft CompleteObjectLocator.
4030llvm::GlobalVariable *
4031MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
4032 const VPtrInfo &Info) {
4033 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
4034}
4035
4036void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
4037 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
4038 // There are no constructor variants, always emit the complete destructor.
4039 llvm::Function *Fn =
4041 CGM.maybeSetTrivialComdat(*ctor, *Fn);
4042 return;
4043 }
4044
4045 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
4046
4047 // Emit the base destructor if the base and complete (vbase) destructors are
4048 // equivalent. This effectively implements -mconstructor-aliases as part of
4049 // the ABI.
4050 if (GD.getDtorType() == Dtor_Complete &&
4051 dtor->getParent()->getNumVBases() == 0)
4052 GD = GD.getWithDtorType(Dtor_Base);
4053
4054 // The base destructor is equivalent to the base destructor of its
4055 // base class if there is exactly one non-virtual base class with a
4056 // non-trivial destructor, there are no fields with a non-trivial
4057 // destructor, and the body of the destructor is trivial.
4058 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
4059 return;
4060
4061 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4062 if (Fn->isWeakForLinker())
4063 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
4064}
4065
4066llvm::Function *
4067MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
4068 CXXCtorType CT) {
4069 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
4070
4071 // Calculate the mangled name.
4072 SmallString<256> ThunkName;
4073 llvm::raw_svector_ostream Out(ThunkName);
4074 getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
4075
4076 // If the thunk has been generated previously, just return it.
4077 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
4078 return cast<llvm::Function>(GV);
4079
4080 // Create the llvm::Function.
4081 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
4082 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
4083 const CXXRecordDecl *RD = CD->getParent();
4084 QualType RecordTy = getContext().getRecordType(RD);
4085 llvm::Function *ThunkFn = llvm::Function::Create(
4086 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
4087 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
4089 if (ThunkFn->isWeakForLinker())
4090 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
4091 bool IsCopy = CT == Ctor_CopyingClosure;
4092
4093 // Start codegen.
4094 CodeGenFunction CGF(CGM);
4095 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
4096
4097 // Build FunctionArgs.
4098 FunctionArgList FunctionArgs;
4099
4100 // A constructor always starts with a 'this' pointer as its first argument.
4101 buildThisParam(CGF, FunctionArgs);
4102
4103 // Following the 'this' pointer is a reference to the source object that we
4104 // are copying from.
4105 ImplicitParamDecl SrcParam(
4106 getContext(), /*DC=*/nullptr, SourceLocation(),
4107 &getContext().Idents.get("src"),
4108 getContext().getLValueReferenceType(RecordTy,
4109 /*SpelledAsLValue=*/true),
4110 ImplicitParamKind::Other);
4111 if (IsCopy)
4112 FunctionArgs.push_back(&SrcParam);
4113
4114 // Constructors for classes which utilize virtual bases have an additional
4115 // parameter which indicates whether or not it is being delegated to by a more
4116 // derived constructor.
4117 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
4119 &getContext().Idents.get("is_most_derived"),
4120 getContext().IntTy, ImplicitParamKind::Other);
4121 // Only add the parameter to the list if the class has virtual bases.
4122 if (RD->getNumVBases() > 0)
4123 FunctionArgs.push_back(&IsMostDerived);
4124
4125 // Start defining the function.
4126 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4127 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
4128 FunctionArgs, CD->getLocation(), SourceLocation());
4129 // Create a scope with an artificial location for the body of this function.
4131 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
4132 llvm::Value *This = getThisValue(CGF);
4133
4134 llvm::Value *SrcVal =
4135 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
4136 : nullptr;
4137
4138 CallArgList Args;
4139
4140 // Push the this ptr.
4141 Args.add(RValue::get(This), CD->getThisType());
4142
4143 // Push the src ptr.
4144 if (SrcVal)
4145 Args.add(RValue::get(SrcVal), SrcParam.getType());
4146
4147 // Add the rest of the default arguments.
4149 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
4150 for (const ParmVarDecl *PD : params) {
4151 assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4152 ArgVec.push_back(PD->getDefaultArg());
4153 }
4154
4155 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4156
4157 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4158 CGF.EmitCallArgs(Args, FPT, llvm::ArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
4159
4160 // Insert any ABI-specific implicit constructor arguments.
4161 AddedStructorArgCounts ExtraArgs =
4162 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4163 /*ForVirtualBase=*/false,
4164 /*Delegating=*/false, Args);
4165 // Call the destructor with our arguments.
4166 llvm::Constant *CalleePtr =
4170 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4171 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4172 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4173
4174 Cleanups.ForceCleanup();
4175
4176 // Emit the ret instruction, remove any temporary instructions created for the
4177 // aid of CodeGen.
4179
4180 return ThunkFn;
4181}
4182
4183llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4184 uint32_t NVOffset,
4185 int32_t VBPtrOffset,
4186 uint32_t VBIndex) {
4187 assert(!T->isReferenceType());
4188
4190 const CXXConstructorDecl *CD =
4191 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
4193 if (CD)
4194 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4196
4197 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4198 SmallString<256> MangledName;
4199 {
4200 llvm::raw_svector_ostream Out(MangledName);
4201 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4202 VBPtrOffset, VBIndex, Out);
4203 }
4204 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4205 return getImageRelativeConstant(GV);
4206
4207 // The TypeDescriptor is used by the runtime to determine if a catch handler
4208 // is appropriate for the exception object.
4209 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4210
4211 // The runtime is responsible for calling the copy constructor if the
4212 // exception is caught by value.
4213 llvm::Constant *CopyCtor;
4214 if (CD) {
4215 if (CT == Ctor_CopyingClosure)
4216 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4217 else
4218 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4219 } else {
4220 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4221 }
4222 CopyCtor = getImageRelativeConstant(CopyCtor);
4223
4224 bool IsScalar = !RD;
4225 bool HasVirtualBases = false;
4226 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4227 QualType PointeeType = T;
4228 if (T->isPointerType())
4229 PointeeType = T->getPointeeType();
4230 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4231 HasVirtualBases = RD->getNumVBases() > 0;
4232 if (IdentifierInfo *II = RD->getIdentifier())
4233 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4234 }
4235
4236 // Encode the relevant CatchableType properties into the Flags bitfield.
4237 // FIXME: Figure out how bits 2 or 8 can get set.
4238 uint32_t Flags = 0;
4239 if (IsScalar)
4240 Flags |= 1;
4241 if (HasVirtualBases)
4242 Flags |= 4;
4243 if (IsStdBadAlloc)
4244 Flags |= 16;
4245
4246 llvm::Constant *Fields[] = {
4247 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4248 TD, // TypeDescriptor
4249 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4250 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4251 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4252 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4253 CopyCtor // CopyCtor
4254 };
4255 llvm::StructType *CTType = getCatchableTypeType();
4256 auto *GV = new llvm::GlobalVariable(
4257 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4258 llvm::ConstantStruct::get(CTType, Fields), MangledName);
4259 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4260 GV->setSection(".xdata");
4261 if (GV->isWeakForLinker())
4262 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4263 return getImageRelativeConstant(GV);
4264}
4265
4266llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4267 assert(!T->isReferenceType());
4268
4269 // See if we've already generated a CatchableTypeArray for this type before.
4270 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4271 if (CTA)
4272 return CTA;
4273
4274 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4275 // using a SmallSetVector. Duplicates may arise due to virtual bases
4276 // occurring more than once in the hierarchy.
4278
4279 // C++14 [except.handle]p3:
4280 // A handler is a match for an exception object of type E if [...]
4281 // - the handler is of type cv T or cv T& and T is an unambiguous public
4282 // base class of E, or
4283 // - the handler is of type cv T or const T& where T is a pointer type and
4284 // E is a pointer type that can be converted to T by [...]
4285 // - a standard pointer conversion (4.10) not involving conversions to
4286 // pointers to private or protected or ambiguous classes
4287 const CXXRecordDecl *MostDerivedClass = nullptr;
4288 bool IsPointer = T->isPointerType();
4289 if (IsPointer)
4290 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4291 else
4292 MostDerivedClass = T->getAsCXXRecordDecl();
4293
4294 // Collect all the unambiguous public bases of the MostDerivedClass.
4295 if (MostDerivedClass) {
4296 const ASTContext &Context = getContext();
4297 const ASTRecordLayout &MostDerivedLayout =
4298 Context.getASTRecordLayout(MostDerivedClass);
4301 serializeClassHierarchy(Classes, MostDerivedClass);
4302 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4303 detectAmbiguousBases(Classes);
4304 for (const MSRTTIClass &Class : Classes) {
4305 // Skip any ambiguous or private bases.
4306 if (Class.Flags &
4307 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4308 continue;
4309 // Write down how to convert from a derived pointer to a base pointer.
4310 uint32_t OffsetInVBTable = 0;
4311 int32_t VBPtrOffset = -1;
4312 if (Class.VirtualRoot) {
4313 OffsetInVBTable =
4314 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4315 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4316 }
4317
4318 // Turn our record back into a pointer if the exception object is a
4319 // pointer.
4320 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4321 if (IsPointer)
4322 RTTITy = Context.getPointerType(RTTITy);
4323 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4324 VBPtrOffset, OffsetInVBTable));
4325 }
4326 }
4327
4328 // C++14 [except.handle]p3:
4329 // A handler is a match for an exception object of type E if
4330 // - The handler is of type cv T or cv T& and E and T are the same type
4331 // (ignoring the top-level cv-qualifiers)
4332 CatchableTypes.insert(getCatchableType(T));
4333
4334 // C++14 [except.handle]p3:
4335 // A handler is a match for an exception object of type E if
4336 // - the handler is of type cv T or const T& where T is a pointer type and
4337 // E is a pointer type that can be converted to T by [...]
4338 // - a standard pointer conversion (4.10) not involving conversions to
4339 // pointers to private or protected or ambiguous classes
4340 //
4341 // C++14 [conv.ptr]p2:
4342 // A prvalue of type "pointer to cv T," where T is an object type, can be
4343 // converted to a prvalue of type "pointer to cv void".
4344 if (IsPointer && T->getPointeeType()->isObjectType())
4345 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4346
4347 // C++14 [except.handle]p3:
4348 // A handler is a match for an exception object of type E if [...]
4349 // - the handler is of type cv T or const T& where T is a pointer or
4350 // pointer to member type and E is std::nullptr_t.
4351 //
4352 // We cannot possibly list all possible pointer types here, making this
4353 // implementation incompatible with the standard. However, MSVC includes an
4354 // entry for pointer-to-void in this case. Let's do the same.
4355 if (T->isNullPtrType())
4356 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4357
4358 uint32_t NumEntries = CatchableTypes.size();
4359 llvm::Type *CTType =
4360 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4361 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4362 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4363 llvm::Constant *Fields[] = {
4364 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4365 llvm::ConstantArray::get(
4366 AT, llvm::ArrayRef(CatchableTypes.begin(),
4367 CatchableTypes.end())) // CatchableTypes
4368 };
4369 SmallString<256> MangledName;
4370 {
4371 llvm::raw_svector_ostream Out(MangledName);
4372 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4373 }
4374 CTA = new llvm::GlobalVariable(
4375 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4376 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4377 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4378 CTA->setSection(".xdata");
4379 if (CTA->isWeakForLinker())
4380 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4381 return CTA;
4382}
4383
4384llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4385 bool IsConst, IsVolatile, IsUnaligned;
4386 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4387
4388 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4389 // the exception object may be caught as.
4390 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4391 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4392 // This is used as a component of the mangled name which means that we need to
4393 // know what it is in order to see if we have previously generated the
4394 // ThrowInfo.
4395 uint32_t NumEntries =
4396 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4397 ->getLimitedValue();
4398
4399 SmallString<256> MangledName;
4400 {
4401 llvm::raw_svector_ostream Out(MangledName);
4402 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4403 NumEntries, Out);
4404 }
4405
4406 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4407 // one before.
4408 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4409 return GV;
4410
4411 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4412 // be at least as CV qualified. Encode this requirement into the Flags
4413 // bitfield.
4414 uint32_t Flags = 0;
4415 if (IsConst)
4416 Flags |= 1;
4417 if (IsVolatile)
4418 Flags |= 2;
4419 if (IsUnaligned)
4420 Flags |= 4;
4421
4422 // The cleanup-function (a destructor) must be called when the exception
4423 // object's lifetime ends.
4424 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4425 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4426 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4427 if (!DtorD->isTrivial())
4428 CleanupFn = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
4429 // This is unused as far as we can tell, initialize it to null.
4430 llvm::Constant *ForwardCompat =
4431 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4432 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(CTA);
4433 llvm::StructType *TIType = getThrowInfoType();
4434 llvm::Constant *Fields[] = {
4435 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4436 getImageRelativeConstant(CleanupFn), // CleanupFn
4437 ForwardCompat, // ForwardCompat
4438 PointerToCatchableTypes // CatchableTypeArray
4439 };
4440 auto *GV = new llvm::GlobalVariable(
4441 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4442 llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
4443 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4444 GV->setSection(".xdata");
4445 if (GV->isWeakForLinker())
4446 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4447 return GV;
4448}
4449
4450void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4451 const Expr *SubExpr = E->getSubExpr();
4452 assert(SubExpr && "SubExpr cannot be null");
4453 QualType ThrowType = SubExpr->getType();
4454 // The exception object lives on the stack and it's address is passed to the
4455 // runtime function.
4456 Address AI = CGF.CreateMemTemp(ThrowType);
4457 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4458 /*IsInit=*/true);
4459
4460 // The so-called ThrowInfo is used to describe how the exception object may be
4461 // caught.
4462 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4463
4464 // Call into the runtime to throw the exception.
4465 llvm::Value *Args[] = {AI.emitRawPointer(CGF), TI};
4467}
4468
4469std::pair<llvm::Value *, const CXXRecordDecl *>
4470MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4471 const CXXRecordDecl *RD) {
4472 std::tie(This, std::ignore, RD) =
4473 performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4474 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4475}
4476
4477bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
4478 const CXXRecordDecl *RD) const {
4479 // All aggregates are permitted to be HFA on non-ARM platforms, which mostly
4480 // affects vectorcall on x64/x86.
4481 if (!CGM.getTarget().getTriple().isAArch64())
4482 return true;
4483 // MSVC Windows on Arm64 has its own rules for determining if a type is HFA
4484 // that are inconsistent with the AAPCS64 ABI. The following are our best
4485 // determination of those rules so far, based on observation of MSVC's
4486 // behavior.
4487 if (RD->isEmpty())
4488 return false;
4489 if (RD->isPolymorphic())
4490 return false;
4492 return false;
4493 if (RD->hasNonTrivialDestructor())
4494 return false;
4496 return false;
4497 // These two are somewhat redundant given the caller
4498 // (ABIInfo::isHomogeneousAggregate) checks the bases and fields, but that
4499 // caller doesn't consider empty bases/fields to be non-homogenous, but it
4500 // looks like Microsoft's AArch64 ABI does care about these empty types &
4501 // anything containing/derived from one is non-homogeneous.
4502 // Instead we could add another CXXABI entry point to query this property and
4503 // have ABIInfo::isHomogeneousAggregate use that property.
4504 // I don't think any other of the features listed above could be true of a
4505 // base/field while not true of the outer struct. For example, if you have a
4506 // base/field that has an non-trivial copy assignment/dtor/default ctor, then
4507 // the outer struct's corresponding operation must be non-trivial.
4508 for (const CXXBaseSpecifier &B : RD->bases()) {
4509 if (const CXXRecordDecl *FRD = B.getType()->getAsCXXRecordDecl()) {
4510 if (!isPermittedToBeHomogeneousAggregate(FRD))
4511 return false;
4512 }
4513 }
4514 // empty fields seem to be caught by the ABIInfo::isHomogeneousAggregate
4515 // checking for padding - but maybe there are ways to end up with an empty
4516 // field without padding? Not that I know of, so don't check fields here &
4517 // rely on the padding check.
4518 return true;
4519}
#define V(N, I)
Definition: ASTContext.h:3285
NodeId Parent
Definition: ASTDiff.cpp:191
static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM)
static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard, llvm::BasicBlock *DynInitBB, llvm::BasicBlock *ContinueBB)
static llvm::GlobalVariable * getTypeInfoVTable(CodeGenModule &CGM)
static bool hasDefaultCXXMethodCC(ASTContext &Context, const CXXMethodDecl *MD)
static bool isTrivialForMSVC(const CXXRecordDecl *RD, QualType Ty, CodeGenModule &CGM)
static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM)
static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM)
static llvm::GlobalValue * getTlsGuardVar(CodeGenModule &CGM)
static QualType decomposeTypeForEH(ASTContext &Context, QualType T, bool &IsConst, bool &IsVolatile, bool &IsUnaligned)
static llvm::CallBase * emitRTtypeidCall(CodeGenFunction &CGF, llvm::Value *Argument)
static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM)
static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard, llvm::BasicBlock *ContinueBB)
static void detectAmbiguousBases(SmallVectorImpl< MSRTTIClass > &Classes)
Find ambiguity among base classes.
static void emitDynamicTlsInitialization(CodeGenFunction &CGF)
static void serializeClassHierarchy(SmallVectorImpl< MSRTTIClass > &Classes, const CXXRecordDecl *RD)
Recursively serializes a class hierarchy in pre-order depth first order.
static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM)
static bool isDeletingDtor(GlobalDecl GD)
static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD, llvm::FunctionCallee Dtor, llvm::Constant *Addr)
static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM)
static void mangleVFTableName(MicrosoftMangleContext &MangleContext, const CXXRecordDecl *RD, const VPtrInfo &VFPtr, SmallString< 256 > &Name)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
SourceLocation Loc
Definition: SemaObjC.cpp:755
const NestedNameSpecifier * Specifier
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1064
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1071
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1591
IdentifierTable & Idents
Definition: ASTContext.h:644
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType IntTy
Definition: ASTContext.h:1100
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getExceptionObjectType(QualType T) const
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
llvm::DenseMap< const CXXRecordDecl *, VBaseInfo > VBaseOffsetsMapTy
Definition: RecordLayout.h:59
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
Definition: RecordLayout.h:324
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
const VBaseOffsetsMapTy & getVBaseOffsetsMap() const
Definition: RecordLayout.h:334
bool hasExtendableVFPtr() const
hasVFPtr - Does this class have a virtual function table pointer that can be extended by a derived cl...
Definition: RecordLayout.h:288
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2753
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2493
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2532
bool isGlobalDelete() const
Definition: ExprCXX.h:2518
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2565
bool isInstance() const
Definition: DeclCXX.h:2087
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2236
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1335
bool hasPrivateFields() const
Definition: DeclCXX.h:1199
base_class_range bases()
Definition: DeclCXX.h:619
bool hasProtectedFields() const
Definition: DeclCXX.h:1203
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1377
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
CXXRecordDecl * getMostRecentNonInjectedDecl()
Definition: DeclCXX.h:549
base_class_range vbases()
Definition: DeclCXX.h:636
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
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1190
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1975
bool hasNonTrivialDefaultConstructor() const
Determine whether this class has a non-trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1248
bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is virtually derived from the class Base.
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:929
bool hasSimpleCopyAssignment() const
true if we know for sure that this class has a single, accessible, unambiguous copy assignment operat...
Definition: DeclCXX.h:748
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:634
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1202
const Expr * getSubExpr() const
Definition: ExprCXX.h:1222
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3483
path_iterator path_begin()
Definition: Expr.h:3553
CastKind getCastKind() const
Definition: Expr.h:3527
path_iterator path_end()
Definition: Expr.h:3554
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3550
Expr * getSubExpr()
Definition: Expr.h:3533
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition: CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
static ABIArgInfo getIndirect(CharUnits Alignment, bool ByVal=true, bool Realign=false, llvm::Type *Padding=nullptr)
void setSRetAfterThis(bool AfterThis)
bool isHomogeneousAggregate(QualType Ty, const Type *&Base, uint64_t &Members) const
isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous aggregate.
Definition: ABIInfo.cpp:61
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:111
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:220
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:241
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:824
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:864
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
Definition: CGDebugInfo.h:881
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition: CGBuilder.h:305
Address CreateConstInBoundsGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition: CGBuilder.h:325
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:292
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
Address CreateConstByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Definition: CGBuilder.h:315
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:128
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition: CGBuilder.h:345
Implements C++ ABI-specific code generation functions.
Definition: CGCXXABI.h:43
virtual bool shouldEmitExactDynamicCast(QualType DestRecordTy)=0
llvm::Value *& getStructorImplicitParamValue(CodeGenFunction &CGF)
Definition: CGCXXABI.h:72
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:131
virtual llvm::Value * performReturnAdjustment(CodeGenFunction &CGF, Address Ret, const ReturnAdjustment &RA)=0
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
Definition: CGCXXABI.h:123
virtual llvm::Value * getVTableAddressPointInStructor(CodeGenFunction &CGF, const CXXRecordDecl *RD, BaseSubobject Base, const CXXRecordDecl *NearestVBase)=0
Get the address point of the vtable for the given base subobject while building a constructor or a de...
virtual void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C)=0
virtual std::vector< CharUnits > getVBPtrOffsets(const CXXRecordDecl *RD)
Gets the offsets of all the virtual base pointers in a given class.
Definition: CGCXXABI.cpp:342
virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn)=0
virtual void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF, const CXXRecordDecl *RD)
Emit the code to initialize hidden members required to handle virtual inheritance,...
Definition: CGCXXABI.h:320
virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const
Return whether or not a member pointers type is convertible to an IR type.
Definition: CGCXXABI.h:213
virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *, FunctionArgList &Args) const =0
virtual bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr)=0
Checks if ABI requires extra virtual offset for vtable field.
virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit)=0
Emits the guarded initializer and destructor setup for the given variable, given that it couldn't be ...
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, CXXDtorType DT) const =0
Returns true if the given destructor type should be emitted as a linkonce delegating thunk,...
virtual CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD)
Get the ABI-specific "this" parameter adjustment to apply in the prologue of a virtual function.
Definition: CGCXXABI.h:416
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
Definition: CGCXXABI.cpp:314
RecordArgABI
Specify how one should pass an argument of a record type.
Definition: CGCXXABI.h:150
virtual llvm::Type * ConvertMemberPointerType(const MemberPointerType *MPT)
Find the LLVM type used to represent the given member pointer type.
Definition: CGCXXABI.cpp:43
virtual llvm::Constant * EmitNullMemberPointer(const MemberPointerType *MPT)
Create a null member pointer of the given type.
Definition: CGCXXABI.cpp:105
virtual StringRef GetPureVirtualCallName()=0
Gets the pure virtual member call function.
virtual CharUnits getArrayCookieSizeImpl(QualType elementType)
Returns the extra size required in order to store the array cookie for the given type.
Definition: CGCXXABI.cpp:221
virtual bool isSRetParameterAfterThis() const
Returns true if the implicit 'sret' parameter comes after the implicit 'this' parameter of C++ instan...
Definition: CGCXXABI.h:169
virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const =0
Determine whether it's possible to emit a vtable for RD, even though we do not know that the vtable h...
virtual StringRef GetDeletedVirtualCallName()=0
Gets the deleted virtual member call name.
virtual llvm::Value * EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *MemPtr, const MemberPointerType *MPT)
Determine if a member pointer is non-null. Returns an i1.
Definition: CGCXXABI.cpp:97
virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType)=0
Emit a reference to a non-local thread_local variable (including triggering the initialization of all...
bool isEmittedWithConstantInitializer(const VarDecl *VD, bool InspectInitForWeakDef=false) const
Determine whether we will definitely emit this variable with a constant initializer,...
Definition: CGCXXABI.cpp:176
virtual llvm::Value * EmitMemberPointerComparison(CodeGenFunction &CGF, llvm::Value *L, llvm::Value *R, const MemberPointerType *MPT, bool Inequality)
Emit a comparison between two member pointers. Returns an i1.
Definition: CGCXXABI.cpp:87
virtual llvm::Constant * EmitMemberPointer(const APValue &MP, QualType MPT)
Create a member pointer for the given member pointer constant.
Definition: CGCXXABI.cpp:119
virtual llvm::Constant * getVTableAddressPoint(BaseSubobject Base, const CXXRecordDecl *VTableClass)=0
Get the address point of the vtable for the given base subobject.
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
Insert any ABI-specific implicit parameters into the parameter list for a function.
virtual llvm::Value * readArrayCookieImpl(CodeGenFunction &IGF, Address ptr, CharUnits cookieSize)
Reads the array cookie for an allocation which is known to have one.
Definition: CGCXXABI.cpp:276
virtual llvm::Value * EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr, const MemberPointerType *MPT)
Calculate an l-value from an object and a data member pointer.
Definition: CGCXXABI.cpp:65
virtual llvm::Value * getCXXDestructorImplicitParam(CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type, bool ForVirtualBase, bool Delegating)=0
Get the implicit (second) parameter that comes after the "this" pointer, or nullptr if there is isn't...
virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType)
Definition: CGCXXABI.cpp:236
virtual CatchTypeInfo getCatchAllTypeInfo()
Definition: CGCXXABI.cpp:338
virtual std::pair< llvm::Value *, const CXXRecordDecl * > LoadVTablePtr(CodeGenFunction &CGF, Address This, const CXXRecordDecl *RD)=0
Load a vtable from This, an object of polymorphic type RD, or from one of its virtual bases if it doe...
virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, bool ReturnAdjustment)=0
virtual Address adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD, Address This, bool VirtualCall)
Perform ABI-specific "this" argument adjustment required prior to a call of a virtual function.
Definition: CGCXXABI.h:396
virtual llvm::Value * EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, Address This, DeleteOrMemberCallExpr E)=0
Emit the ABI-specific virtual destructor call.
bool mayNeedDestruction(const VarDecl *VD) const
Definition: CGCXXABI.cpp:163
virtual llvm::BasicBlock * EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, const CXXRecordDecl *RD)
Definition: CGCXXABI.cpp:305
virtual bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass)=0
Checks if ABI requires to initialize vptrs for given dynamic class.
virtual void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E)=0
virtual llvm::Value * GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl)=0
virtual bool isThisCompleteObject(GlobalDecl GD) const =0
Determine whether there's something special about the rules of the ABI tell us that 'this' is a compl...
virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, Address This, llvm::Type *Ty, SourceLocation Loc)=0
Build a virtual function pointer in the ABI-specific way.
virtual bool classifyReturnType(CGFunctionInfo &FI) const =0
If the C++ ABI requires the given type be returned in a particular way, this method sets RetAI and re...
virtual void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, Address Ptr, QualType ElementType, const CXXDestructorDecl *Dtor)=0
virtual CatchTypeInfo getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType)=0
virtual void EmitThreadLocalInitFuncs(CodeGenModule &CGM, ArrayRef< const VarDecl * > CXXThreadLocals, ArrayRef< llvm::Function * > CXXThreadLocalInits, ArrayRef< const VarDecl * > CXXThreadLocalInitVars)=0
Emits ABI-required functions necessary to initialize thread_local variables in this translation unit.
virtual bool usesThreadWrapperFunction(const VarDecl *VD) const =0
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
virtual llvm::Value * emitExactDynamicCast(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy, QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastSuccess, llvm::BasicBlock *CastFail)=0
Emit a dynamic_cast from SrcRecordTy to DestRecordTy.
virtual const CXXRecordDecl * getThisArgumentTypeForMethod(GlobalDecl GD)
Get the type of the implicit "this" parameter used by a method.
Definition: CGCXXABI.h:388
virtual void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)=0
Emit the destructor call.
virtual llvm::GlobalVariable * getAddrOfVTable(const CXXRecordDecl *RD, CharUnits VPtrOffset)=0
Get the address of the vtable for the given record decl which should be used for the vptr at the give...
virtual bool EmitBadCastCall(CodeGenFunction &CGF)=0
virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, CallArgList &CallArgs)
Definition: CGCXXABI.h:495
virtual llvm::Constant * EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset)
Create a member pointer for the given field.
Definition: CGCXXABI.cpp:114
virtual llvm::Value * EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, Address ThisPtr, llvm::Type *StdTypeInfoPtrTy)=0
virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD)=0
Emit any tables needed to implement virtual inheritance.
virtual void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD)=0
Emits the VTable definitions required for the given record type.
virtual CGCallee EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, Address This, llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr, const MemberPointerType *MPT)
Load a member function from an object and a member function pointer.
Definition: CGCXXABI.cpp:47
virtual bool isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const
Returns true if the ABI permits the argument to be a homogeneous aggregate.
Definition: CGCXXABI.h:174
virtual void emitCXXStructor(GlobalDecl GD)=0
Emit a single constructor/destructor with the given type from a C++ constructor Decl.
virtual bool exportThunk()=0
virtual void EmitBadTypeidCall(CodeGenFunction &CGF)=0
virtual llvm::Value * emitDynamicCastToVoid(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy)=0
virtual bool isZeroInitializable(const MemberPointerType *MPT)
Return true if the given member pointer can be zero-initialized (in the C++ sense) with an LLVM zeroi...
Definition: CGCXXABI.cpp:123
virtual bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy)=0
virtual llvm::Value * EmitMemberPointerConversion(CodeGenFunction &CGF, const CastExpr *E, llvm::Value *Src)
Perform a derived-to-base, base-to-derived, or bitcast member pointer conversion.
Definition: CGCXXABI.cpp:74
virtual llvm::Constant * EmitMemberFunctionPointer(const CXXMethodDecl *MD)
Create a member pointer for the given method.
Definition: CGCXXABI.cpp:109
virtual llvm::Value * emitDynamicCastCall(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy, QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd)=0
virtual llvm::GlobalVariable * getThrowInfo(QualType T)
Definition: CGCXXABI.h:259
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
Definition: CGCXXABI.cpp:321
virtual Address InitializeArrayCookie(CodeGenFunction &CGF, Address NewPtr, llvm::Value *NumElements, const CXXNewExpr *expr, QualType ElementType)
Initialize the array cookie for the given allocation.
Definition: CGCXXABI.cpp:226
ASTContext & getContext() const
Definition: CGCXXABI.h:81
virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, QualType SrcRecordTy)=0
virtual AddedStructorArgCounts buildStructorSignature(GlobalDecl GD, SmallVectorImpl< CanQualType > &ArgTys)=0
Build the signature of the given constructor or destructor variant by adding any required parameters.
virtual llvm::Value * performThisAdjustment(CodeGenFunction &CGF, Address This, const ThisAdjustment &TA)=0
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:113
virtual AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating)=0
All available information about a concrete callee.
Definition: CGCall.h:62
static CGCallee forVirtual(const CallExpr *CE, GlobalDecl MD, Address Addr, llvm::FunctionType *FTy)
Definition: CGCall.h:139
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:129
CGFunctionInfo - Class to encapsulate the information about a function definition.
CanQualType getReturnType() const
unsigned getEffectiveCallingConvention() const
getEffectiveCallingConvention - Return the actual calling convention to use, which may depend on the ...
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:258
void add(RValue rvalue, QualType type)
Definition: CGCall.h:282
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCXXGlobalInitFunc(llvm::Function *Fn, ArrayRef< llvm::Function * > CXXThreadLocals, ConstantAddress Guard=ConstantAddress::invalid())
GenerateCXXGlobalInitFunc - Generates code for initializing global variables.
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, QualType DeleteTy, llvm::Value *NumElements=nullptr, CharUnits CookieSize=CharUnits())
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
llvm::Value * EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, llvm::Type *VTableTy, uint64_t VTableByteOffset)
Emit a type checked load from the given vtable.
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **callOrInvoke, bool IsMustTail, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type,...
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV, bool PerformInit)
EmitCXXGlobalVarDeclInit - Create the initializer for a C++ variable with global storage.
bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD)
Returns whether we should perform a type checked load when loading a virtual function for virtual cal...
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
llvm::Function * createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, llvm::Constant *Addr)
void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn, llvm::Constant *addr)
Call atexit() with a function that passes the given argument to the given function.
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
void EmitAutoVarCleanups(const AutoVarEmission &emission)
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, llvm::Value *VTable, SourceLocation Loc)
If whole-program virtual table optimization is enabled, emit an assumption that VTable is a member of...
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args)
CodeGenTypes & getTypes() const
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
llvm::Instruction * CurrentFuncletPad
llvm::LLVMContext & getLLVMContext()
void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, llvm::BasicBlock *InitBlock, llvm::BasicBlock *NoInitBlock, GuardKind Kind, const VarDecl *D)
Emit a branch to select whether or not to perform guarded initialization.
void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, llvm::FunctionCallee Callee)
Emit a musttail call for a thunk with a potentially adjusted this pointer.
This class organizes the cross-function state that is used while generating LLVM code.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object)
Add a destructor and object to add to the C++ global destructor function.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::GlobalObject::VCallVisibility GetVCallVisibilityLevel(const CXXRecordDecl *RD, llvm::DenseSet< const CXXRecordDecl * > &Visited)
Returns the vcall visibility of the given type.
Definition: CGVTables.cpp:1276
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
CodeGenVTables & getVTables()
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
DiagnosticsEngine & getDiags() const
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D)
Try to emit a base destructor as an alias to its primary base-class destructor.
Definition: CGCXX.cpp:34
CharUnits computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start, CastExpr::path_const_iterator End)
Definition: CGClass.cpp:172
CharUnits getVBaseAlignment(CharUnits DerivedAlign, const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the assumed alignment of a virtual base of a class.
Definition: CGClass.cpp:76
llvm::Function * codegenCXXStructor(GlobalDecl GD)
Definition: CGCXX.cpp:206
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ASTContext & getContext() const
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
MicrosoftVTableContext & getMicrosoftVTableContext()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
Definition: CGVTables.cpp:1050
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void addDeferredVTable(const CXXRecordDecl *RD)
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Function * CreateGlobalInitOrCleanUpFunction(llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI, SourceLocation Loc=SourceLocation(), bool TLS=false, llvm::GlobalVariable::LinkageTypes Linkage=llvm::GlobalVariable::InternalLinkage)
Definition: CGDeclCXX.cpp:436
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
const ABIInfo & getABIInfo() const
Definition: CodeGenTypes.h:109
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1632
const CGFunctionInfo & arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD)
Arrange a thunk that takes 'this' as the first parameter followed by varargs.
Definition: CGCall.cpp:560
llvm::Type * ConvertTypeForMem(QualType T, bool ForBitField=false)
ConvertTypeForMem - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXConstructorCall(const CallArgList &Args, const CXXConstructorDecl *D, CXXCtorType CtorKind, unsigned ExtraPrefixArgs, unsigned ExtraSuffixArgs, bool PassProtoArgs=true)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:419
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:334
const CGFunctionInfo & arrangeMSCtorClosure(const CXXConstructorDecl *CD, CXXCtorType CT)
Definition: CGCall.cpp:569
const CGFunctionInfo & arrangeNullaryFunction()
A nullary function is a freestanding function of type 'void ()'.
Definition: CGCall.cpp:722
void createVTableInitializer(ConstantStructBuilder &builder, const VTableLayout &layout, llvm::Constant *rtti, bool vtableHasLocalLinkage)
Add vtable components for the given vtable layout to the given global initializer.
Definition: CGVTables.cpp:867
llvm::Type * getVTableType(const VTableLayout &layout)
Returns the type of a vtable with the given layout.
Definition: CGVTables.cpp:858
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:260
The standard implementation of ConstantInitBuilder used in Clang.
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:352
LValue - This represents an lvalue references.
Definition: CGValue.h:181
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:41
static RValue get(llvm::Value *V)
Definition: CGValue.h:97
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:70
An abstract representation of an aligned address.
Definition: Address.h:41
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:356
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
bool hasAttr() const
Definition: DeclBase.h:583
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
This represents one expression.
Definition: Expr.h:110
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents a member of a struct/union/class.
Definition: Decl.h:3057
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3270
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3203
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5012
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
GlobalDecl getWithCtorType(CXXCtorType Type)
Definition: GlobalDecl.h:169
GlobalDecl getWithDtorType(CXXDtorType Type)
Definition: GlobalDecl.h:176
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:110
const Decl * getDecl() const
Definition: GlobalDecl.h:103
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:5379
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:625
bool isExplicitDefaultVisibilityExportMapping() const
Definition: LangOptions.h:715
bool isAllDefaultVisibilityExportMapping() const
Definition: LangOptions.h:720
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Definition: Type.cpp:4992
QualType getPointeeType() const
Definition: Type.h:3476
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition: Type.h:3480
bool isMemberDataPointer() const
Returns true if the member type (i.e.
Definition: Type.h:3486
unsigned getVBTableIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the index of VBase in the vbtable of Derived.
MethodVFTableLocation getMethodVFTableLocation(GlobalDecl GD)
const VPtrInfoVector & getVFPtrOffsets(const CXXRecordDecl *RD)
const VTableLayout & getVFTableLayout(const CXXRecordDecl *RD, CharUnits VFPtrOffset)
Describes a module or submodule.
Definition: Module.h:105
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
bool isExternallyVisible() const
Definition: Decl.h:408
Represents a parameter to a function.
Definition: Decl.h:1761
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
bool hasUnaligned() const
Definition: Type.h:497
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition: Decl.h:4297
Encodes a location in the source.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
const Type * getTypeForDecl() const
Definition: Decl.h:3414
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:1871
bool isPointerType() const
Definition: Type.h:7612
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2405
Linkage getLinkage() const
Determine the linkage of this type.
Definition: Type.cpp:4522
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isNullPtrType() const
Definition: Type.h:7938
Represents a single component in a vtable.
Definition: VTableBuilder.h:30
ArrayRef< VTableComponent > vtable_components() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
TLSKind getTLSKind() const
Definition: Decl.cpp:2165
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2813
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1195
llvm::Value * getCXXDestructorImplicitParam(CodeGenModule &CGM, llvm::BasicBlock *InsertBlock, llvm::BasicBlock::iterator InsertPoint, const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating)
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
CGCXXABI * CreateMicrosoftCXXABI(CodeGenModule &CGM)
Creates a Microsoft-family ABI.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:217
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1899
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1873
The JSON file list parser is used to communicate input to InstallAPI.
CXXCtorType
C++ constructor types.
Definition: ABI.h:24
@ Ctor_Base
Base object ctor.
Definition: ABI.h:26
@ Ctor_DefaultClosure
Default closure variant of a ctor.
Definition: ABI.h:29
@ Ctor_CopyingClosure
Copying closure variant of a ctor.
Definition: ABI.h:28
@ Ctor_Complete
Complete object ctor.
Definition: ABI.h:25
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:72
@ GVA_Internal
Definition: Linkage.h:73
void initialize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
bool inheritanceModelHasNVOffsetField(bool IsMemberFunction, MSInheritanceModel Inheritance)
bool inheritanceModelHasOnlyOneField(bool IsMemberFunction, MSInheritanceModel Inheritance)
bool inheritanceModelHasVBPtrOffsetField(MSInheritanceModel Inheritance)
bool inheritanceModelHasVBTableOffsetField(MSInheritanceModel Inheritance)
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
CXXDtorType
C++ destructor types.
Definition: ABI.h:33
@ Dtor_Comdat
The COMDAT used for dtors.
Definition: ABI.h:37
@ Dtor_Base
Base object dtor.
Definition: ABI.h:36
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
@ Dtor_Deleting
Deleting dtor.
Definition: ABI.h:34
CastKind
CastKind - The kind of operation required for a conversion.
const FunctionProtoType * T
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
U cast(CodeGen::Address addr)
Definition: Address.h:291
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Implicit
An implicit conversion.
@ AS_public
Definition: Specifiers.h:121
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
Similar to AddedStructorArgs, but only notes the number of additional arguments.
Definition: CGCXXABI.h:351
Additional implicit arguments to add to the beginning (Prefix) and end (Suffix) of a constructor / de...
Definition: CGCXXABI.h:331
The MS C++ ABI needs a pointer to RTTI data plus some flags to describe the type of a catch handler,...
Definition: CGCleanup.h:39
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * IntTy
int
const CXXRecordDecl * VBase
If nonnull, holds the last vbase which contains the vfptr that the method definition is adjusted to.
CharUnits VFPtrOffset
This is the offset of the vfptr from the start of the last vbase, or the complete type if there are n...
uint64_t Index
Method's index in the vftable.
A return adjustment.
Definition: Thunk.h:26
bool isEmpty() const
Definition: Thunk.h:69
union clang::ReturnAdjustment::VirtualAdjustment Virtual
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition: Thunk.h:29
A this pointer adjustment.
Definition: Thunk.h:91
union clang::ThisAdjustment::VirtualAdjustment Virtual
bool isEmpty() const
Definition: Thunk.h:136
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition: Thunk.h:94
bool isAlignRequired()
Definition: ASTContext.h:161
unsigned Align
Definition: ASTContext.h:154
Holds information about the inheritance path to a virtual base or function table pointer.
CharUnits NonVirtualOffset
IntroducingObject is at this offset from its containing complete object or virtual base.
CharUnits FullOffsetInMDC
Static offset from the top of the most derived class to this vfptr, including any virtual base offset...
const CXXRecordDecl * getVBaseWithVPtr() const
The vptr is stored inside the non-virtual component of this virtual base.
const CXXRecordDecl * IntroducingObject
This is the class that introduced the vptr by declaring new virtual methods or virtual bases.
BasePath MangledPath
The bases from the inheritance path that got used to mangle the vbtable name.
BasePath PathToIntroducingObject
This holds the base classes path from the complete type to the first base with the given vfptr offset...
const CXXRecordDecl * ObjectWithVPtr
This is the most derived class that has this vptr at offset zero.
struct clang::ReturnAdjustment::VirtualAdjustment::@189 Microsoft
uint32_t VBPtrOffset
The offset (in bytes) of the vbptr, relative to the beginning of the derived class.
Definition: Thunk.h:45
uint32_t VBIndex
Index of the virtual base in the vbtable.
Definition: Thunk.h:48
int32_t VtordispOffset
The offset of the vtordisp (in bytes), relative to the ECX.
Definition: Thunk.h:108
struct clang::ThisAdjustment::VirtualAdjustment::@191 Microsoft
int32_t VBOffsetOffset
The offset (in bytes) of the vbase offset in the vbtable.
Definition: Thunk.h:115
int32_t VBPtrOffset
The offset of the vbptr of the derived class (in bytes), relative to the ECX after vtordisp adjustmen...
Definition: Thunk.h:112