Debian Codegraph @

clang/lib/CodeGen/ItaniumCXXABI.cpp

raw
1 //===------- ItaniumCXXABI.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 Itanium C++ ABI. The class
10 // in this file generates structures that follow the Itanium C++ ABI, which is
11 // documented at:
12 // https://itanium-cxx-abi.github.io/cxx-abi/abi.html
13 // https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html
14 //
15 // It also supports the closely-related ARM ABI, documented at:
16 // https://developer.arm.com/documentation/ihi0041/g/
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "CGCXXABI.h"
21 #include "CGCleanup.h"
22 #include "CGDebugInfo.h"
23 #include "CGRecordLayout.h"
24 #include "CGVTables.h"
25 #include "CodeGenFunction.h"
26 #include "CodeGenModule.h"
27 #include "TargetInfo.h"
28 #include "clang/AST/Attr.h"
29 #include "clang/AST/Mangle.h"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/Type.h"
32 #include "clang/CodeGen/ConstantInitBuilder.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/ScopedPrinter.h"
39
40 #include <optional>
41
42 using namespace clang;
43 using namespace CodeGen;
44
45 namespace {
46 class ItaniumCXXABI : public CodeGen::CGCXXABI {
47 /// VTables - All the vtables which have been defined.
48 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
49
50 /// All the thread wrapper functions that have been used.
51 llvm::SmallVector<std::pair<const VarDecl *, llvm::Function *>, 8>
52 ThreadWrappers;
53
54 protected:
55 bool UseARMMethodPtrABI;
56 bool UseARMGuardVarABI;
57 bool Use32BitVTableOffsetABI;
58
59 ItaniumMangleContext &getMangleContext() {
60 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
61 }
62
63 public:
64 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
65 bool UseARMMethodPtrABI = false,
66 bool UseARMGuardVarABI = false) :
67 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
68 UseARMGuardVarABI(UseARMGuardVarABI),
69 Use32BitVTableOffsetABI(false) { }
70
71 bool classifyReturnType(CGFunctionInfo &FI) const override;
72
73 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
74 // If C++ prohibits us from making a copy, pass by address.
75 if (!RD->canPassInRegisters())
76 return RAA_Indirect;
77 return RAA_Default;
78 }
79
80 bool isThisCompleteObject(GlobalDecl GD) const override {
81 // The Itanium ABI has separate complete-object vs. base-object
82 // variants of both constructors and destructors.
83 if (isa<CXXDestructorDecl>(GD.getDecl())) {
84 switch (GD.getDtorType()) {
85 case Dtor_Complete:
86 case Dtor_Deleting:
87 return true;
88
89 case Dtor_Base:
90 return false;
91
92 case Dtor_Comdat:
93 llvm_unreachable("emitting dtor comdat as function?");
94 case Dtor_Unified:
95 llvm_unreachable("emitting unified dtor as function?");
96 case Dtor_VectorDeleting:
97 llvm_unreachable("unexpected dtor kind for this ABI");
98 }
99 llvm_unreachable("bad dtor kind");
100 }
101 if (isa<CXXConstructorDecl>(GD.getDecl())) {
102 switch (GD.getCtorType()) {
103 case Ctor_Complete:
104 return true;
105
106 case Ctor_Base:
107 return false;
108
109 case Ctor_CopyingClosure:
110 case Ctor_DefaultClosure:
111 llvm_unreachable("closure ctors in Itanium ABI?");
112
113 case Ctor_Comdat:
114 llvm_unreachable("emitting ctor comdat as function?");
115
116 case Ctor_Unified:
117 llvm_unreachable("emitting unified ctor as function?");
118 }
119 llvm_unreachable("bad dtor kind");
120 }
121
122 // No other kinds.
123 return false;
124 }
125
126 bool isZeroInitializable(const MemberPointerType *MPT) override;
127
128 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
129
130 CGCallee
131 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
132 const Expr *E,
133 Address This,
134 llvm::Value *&ThisPtrForCall,
135 llvm::Value *MemFnPtr,
136 const MemberPointerType *MPT) override;
137
138 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
139 Address Base, llvm::Value *MemPtr,
140 const MemberPointerType *MPT,
141 bool IsInBounds) override;
142
143 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
144 const CastExpr *E,
145 llvm::Value *Src) override;
146 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
147 llvm::Constant *Src) override;
148
149 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
150
151 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
152 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
153 CharUnits offset) override;
154 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
155 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
156 CharUnits ThisAdjustment);
157
158 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
159 llvm::Value *L, llvm::Value *R,
160 const MemberPointerType *MPT,
161 bool Inequality) override;
162
163 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
164 llvm::Value *Addr,
165 const MemberPointerType *MPT) override;
166
167 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
168 Address Ptr, QualType ElementType,
169 const CXXDestructorDecl *Dtor) override;
170
171 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
172 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
173
174 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
175
176 llvm::CallInst *
177 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
178 llvm::Value *Exn) override;
179
180 void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
181 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
182 CatchTypeInfo
183 getAddrOfCXXCatchHandlerType(QualType Ty,
184 QualType CatchHandlerType) override {
185 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
186 }
187
188 bool shouldTypeidBeNullChecked(QualType SrcRecordTy) override;
189 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
190 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
191 Address ThisPtr,
192 llvm::Type *StdTypeInfoPtrTy) override;
193
194 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
195 QualType SrcRecordTy) override;
196
197 /// Determine whether we know that all instances of type RecordTy will have
198 /// the same vtable pointer values, that is distinct from all other vtable
199 /// pointers. While this is required by the Itanium ABI, it doesn't happen in
200 /// practice in some cases due to language extensions.
201 bool hasUniqueVTablePointer(QualType RecordTy) {
202 const CXXRecordDecl *RD = RecordTy->getAsCXXRecordDecl();
203
204 // Under -fapple-kext, multiple definitions of the same vtable may be
205 // emitted.
206 if (!CGM.getCodeGenOpts().AssumeUniqueVTables ||
207 getContext().getLangOpts().AppleKext)
208 return false;
209
210 // If the type_info* would be null, the vtable might be merged with that of
211 // another type.
212 if (!CGM.shouldEmitRTTI())
213 return false;
214
215 // If there's only one definition of the vtable in the program, it has a
216 // unique address.
217 if (!llvm::GlobalValue::isWeakForLinker(CGM.getVTableLinkage(RD)))
218 return true;
219
220 // Even if there are multiple definitions of the vtable, they are required
221 // by the ABI to use the same symbol name, so should be merged at load
222 // time. However, if the class has hidden visibility, there can be
223 // different versions of the class in different modules, and the ABI
224 // library might treat them as being the same.
225 if (CGM.GetLLVMVisibility(RD->getVisibility()) !=
226 llvm::GlobalValue::DefaultVisibility)
227 return false;
228
229 return true;
230 }
231
232 bool shouldEmitExactDynamicCast(QualType DestRecordTy) override {
233 return hasUniqueVTablePointer(DestRecordTy);
234 }
235
236 std::optional<ExactDynamicCastInfo>
237 getExactDynamicCastInfo(QualType SrcRecordTy, QualType DestTy,
238 QualType DestRecordTy) override;
239
240 llvm::Value *emitDynamicCastCall(CodeGenFunction &CGF, Address Value,
241 QualType SrcRecordTy, QualType DestTy,
242 QualType DestRecordTy,
243 llvm::BasicBlock *CastEnd) override;
244
245 llvm::Value *emitExactDynamicCast(CodeGenFunction &CGF, Address ThisAddr,
246 QualType SrcRecordTy, QualType DestTy,
247 QualType DestRecordTy,
248 const ExactDynamicCastInfo &CastInfo,
249 llvm::BasicBlock *CastSuccess,
250 llvm::BasicBlock *CastFail) override;
251
252 llvm::Value *emitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
253 QualType SrcRecordTy) override;
254
255 bool EmitBadCastCall(CodeGenFunction &CGF) override;
256
257 llvm::Value *
258 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
259 const CXXRecordDecl *ClassDecl,
260 const CXXRecordDecl *BaseClassDecl) override;
261
262 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
263
264 AddedStructorArgCounts
265 buildStructorSignature(GlobalDecl GD,
266 SmallVectorImpl<CanQualType> &ArgTys) override;
267
268 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
269 CXXDtorType DT) const override {
270 // Itanium does not emit any destructor variant as an inline thunk.
271 // Delegating may occur as an optimization, but all variants are either
272 // emitted with external linkage or as linkonce if they are inline and used.
273 return false;
274 }
275
276 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
277
278 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
279 FunctionArgList &Params) override;
280
281 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
282
283 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
284 const CXXConstructorDecl *D,
285 CXXCtorType Type,
286 bool ForVirtualBase,
287 bool Delegating) override;
288
289 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
290 const CXXDestructorDecl *DD,
291 CXXDtorType Type,
292 bool ForVirtualBase,
293 bool Delegating) override;
294
295 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
296 CXXDtorType Type, bool ForVirtualBase,
297 bool Delegating, Address This,
298 QualType ThisTy) override;
299
300 void emitVTableDefinitions(CodeGenVTables &CGVT,
301 const CXXRecordDecl *RD) override;
302
303 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
304 CodeGenFunction::VPtr Vptr) override;
305
306 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
307 return true;
308 }
309
310 llvm::Constant *
311 getVTableAddressPoint(BaseSubobject Base,
312 const CXXRecordDecl *VTableClass) override;
313
314 llvm::Value *getVTableAddressPointInStructor(
315 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
316 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
317
318 llvm::Value *getVTableAddressPointInStructorWithVTT(
319 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
320 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
321
322 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
323 CharUnits VPtrOffset) override;
324
325 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
326 Address This, llvm::Type *Ty,
327 SourceLocation Loc) override;
328
329 llvm::Value *
330 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,
331 CXXDtorType DtorType, Address This,
332 DeleteOrMemberCallExpr E,
333 llvm::CallBase **CallOrInvoke) override;
334
335 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
336
337 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
338 bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
339
340 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
341 bool ReturnAdjustment) override {
342 // Allow inlining of thunks by emitting them with available_externally
343 // linkage together with vtables when needed.
344 if (ForVTable && !Thunk->hasLocalLinkage())
345 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
346 CGM.setGVProperties(Thunk, GD);
347 }
348
349 bool exportThunk() override { return true; }
350
351 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
352 const CXXRecordDecl *UnadjustedThisClass,
353 const ThunkInfo &TI) override;
354
355 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
356 const CXXRecordDecl *UnadjustedRetClass,
357 const ReturnAdjustment &RA) override;
358
359 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
360 FunctionArgList &Args) const override {
361 assert(!Args.empty() && "expected the arglist to not be empty!");
362 return Args.size() - 1;
363 }
364
365 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
366 StringRef GetDeletedVirtualCallName() override
367 { return "__cxa_deleted_virtual"; }
368
369 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
370 Address InitializeArrayCookie(CodeGenFunction &CGF,
371 Address NewPtr,
372 llvm::Value *NumElements,
373 const CXXNewExpr *expr,
374 QualType ElementType) override;
375 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
376 Address allocPtr,
377 CharUnits cookieSize) override;
378
379 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
380 llvm::GlobalVariable *DeclPtr,
381 bool PerformInit) override;
382 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
383 llvm::FunctionCallee dtor,
384 llvm::Constant *addr) override;
385
386 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
387 llvm::Value *Val);
388 void EmitThreadLocalInitFuncs(
389 CodeGenModule &CGM,
390 ArrayRef<const VarDecl *> CXXThreadLocals,
391 ArrayRef<llvm::Function *> CXXThreadLocalInits,
392 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
393
394 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
395 return !isEmittedWithConstantInitializer(VD) ||
396 mayNeedDestruction(VD);
397 }
398 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
399 QualType LValType) override;
400
401 bool NeedsVTTParameter(GlobalDecl GD) override;
402
403 llvm::Constant *
404 getOrCreateVirtualFunctionPointerThunk(const CXXMethodDecl *MD);
405
406 /**************************** RTTI Uniqueness ******************************/
407
408 protected:
409 /// Returns true if the ABI requires RTTI type_info objects to be unique
410 /// across a program.
411 virtual bool shouldRTTIBeUnique() const { return true; }
412
413 public:
414 /// What sort of unique-RTTI behavior should we use?
415 enum RTTIUniquenessKind {
416 /// We are guaranteeing, or need to guarantee, that the RTTI string
417 /// is unique.
418 RUK_Unique,
419
420 /// We are not guaranteeing uniqueness for the RTTI string, so we
421 /// can demote to hidden visibility but must use string comparisons.
422 RUK_NonUniqueHidden,
423
424 /// We are not guaranteeing uniqueness for the RTTI string, so we
425 /// have to use string comparisons, but we also have to emit it with
426 /// non-hidden visibility.
427 RUK_NonUniqueVisible
428 };
429
430 /// Return the required visibility status for the given type and linkage in
431 /// the current ABI.
432 RTTIUniquenessKind
433 classifyRTTIUniqueness(QualType CanTy,
434 llvm::GlobalValue::LinkageTypes Linkage) const;
435 friend class ItaniumRTTIBuilder;
436
437 void emitCXXStructor(GlobalDecl GD) override;
438
439 std::pair<llvm::Value *, const CXXRecordDecl *>
440 LoadVTablePtr(CodeGenFunction &CGF, Address This,
441 const CXXRecordDecl *RD) override;
442
443 private:
444 llvm::Constant *
445 getSignedVirtualMemberFunctionPointer(const CXXMethodDecl *MD);
446
447 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
448 const auto &VtableLayout =
449 CGM.getItaniumVTableContext().getVTableLayout(RD);
450
451 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
452 // Skip empty slot.
453 if (!VtableComponent.isUsedFunctionPointerKind())
454 continue;
455
456 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
457 const FunctionDecl *FD = Method->getDefinition();
458 const bool IsInlined =
459 Method->getCanonicalDecl()->isInlined() || (FD && FD->isInlined());
460 if (!IsInlined)
461 continue;
462
463 StringRef Name = CGM.getMangledName(
464 VtableComponent.getGlobalDecl(/*HasVectorDeletingDtors=*/false));
465 auto *Entry = CGM.GetGlobalValue(Name);
466 // This checks if virtual inline function has already been emitted.
467 // Note that it is possible that this inline function would be emitted
468 // after trying to emit vtable speculatively. Because of this we do
469 // an extra pass after emitting all deferred vtables to find and emit
470 // these vtables opportunistically.
471 if (!Entry || Entry->isDeclaration())
472 return true;
473 }
474 return false;
475 }
476
477 bool isVTableHidden(const CXXRecordDecl *RD) const {
478 const auto &VtableLayout =
479 CGM.getItaniumVTableContext().getVTableLayout(RD);
480
481 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
482 if (VtableComponent.isRTTIKind()) {
483 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
484 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
485 return true;
486 } else if (VtableComponent.isUsedFunctionPointerKind()) {
487 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
488 if (Method->getVisibility() == Visibility::HiddenVisibility &&
489 !Method->isDefined())
490 return true;
491 }
492 }
493 return false;
494 }
495 };
496
497 class ARMCXXABI : public ItaniumCXXABI {
498 public:
499 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
500 ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
501 /*UseARMGuardVarABI=*/true) {}
502
503 bool constructorsAndDestructorsReturnThis() const override { return true; }
504
505 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
506 QualType ResTy) override;
507
508 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
509 Address InitializeArrayCookie(CodeGenFunction &CGF,
510 Address NewPtr,
511 llvm::Value *NumElements,
512 const CXXNewExpr *expr,
513 QualType ElementType) override;
514 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
515 CharUnits cookieSize) override;
516 };
517
518 class AppleARM64CXXABI : public ARMCXXABI {
519 public:
520 AppleARM64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
521 Use32BitVTableOffsetABI = true;
522 }
523
524 // ARM64 libraries are prepared for non-unique RTTI.
525 bool shouldRTTIBeUnique() const override { return false; }
526 };
527
528 class FuchsiaCXXABI final : public ItaniumCXXABI {
529 public:
530 explicit FuchsiaCXXABI(CodeGen::CodeGenModule &CGM)
531 : ItaniumCXXABI(CGM) {}
532
533 private:
534 bool constructorsAndDestructorsReturnThis() const override { return true; }
535 };
536
537 class WebAssemblyCXXABI final : public ItaniumCXXABI {
538 public:
539 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
540 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
541 /*UseARMGuardVarABI=*/true) {}
542 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
543 llvm::CallInst *
544 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
545 llvm::Value *Exn) override;
546
547 private:
548 bool constructorsAndDestructorsReturnThis() const override { return true; }
549 bool canCallMismatchedFunctionType() const override { return false; }
550 };
551
552 class XLCXXABI final : public ItaniumCXXABI {
553 public:
554 explicit XLCXXABI(CodeGen::CodeGenModule &CGM)
555 : ItaniumCXXABI(CGM) {}
556
557 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
558 llvm::FunctionCallee dtor,
559 llvm::Constant *addr) override;
560
561 bool useSinitAndSterm() const override { return true; }
562
563 private:
564 void emitCXXStermFinalizer(const VarDecl &D, llvm::Function *dtorStub,
565 llvm::Constant *addr);
566 };
567 }
568
569 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
570 switch (CGM.getContext().getCXXABIKind()) {
571 // For IR-generation purposes, there's no significant difference
572 // between the ARM and iOS ABIs.
573 case TargetCXXABI::GenericARM:
574 case TargetCXXABI::iOS:
575 case TargetCXXABI::WatchOS:
576 return new ARMCXXABI(CGM);
577
578 case TargetCXXABI::AppleARM64:
579 return new AppleARM64CXXABI(CGM);
580
581 case TargetCXXABI::Fuchsia:
582 return new FuchsiaCXXABI(CGM);
583
584 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
585 // include the other 32-bit ARM oddities: constructor/destructor return values
586 // and array cookies.
587 case TargetCXXABI::GenericAArch64:
588 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
589 /*UseARMGuardVarABI=*/true);
590
591 case TargetCXXABI::GenericMIPS:
592 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
593
594 case TargetCXXABI::WebAssembly:
595 return new WebAssemblyCXXABI(CGM);
596
597 case TargetCXXABI::XL:
598 return new XLCXXABI(CGM);
599
600 case TargetCXXABI::GenericItanium:
601 return new ItaniumCXXABI(CGM);
602
603 case TargetCXXABI::Microsoft:
604 llvm_unreachable("Microsoft ABI is not Itanium-based");
605 }
606 llvm_unreachable("bad ABI kind");
607 }
608
609 llvm::Type *
610 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
611 if (MPT->isMemberDataPointer())
612 return CGM.PtrDiffTy;
613 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
614 }
615
616 /// In the Itanium and ARM ABIs, method pointers have the form:
617 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
618 ///
619 /// In the Itanium ABI:
620 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero
621 /// - the this-adjustment is (memptr.adj)
622 /// - the virtual offset is (memptr.ptr - 1)
623 ///
624 /// In the ARM ABI:
625 /// - method pointers are virtual if (memptr.adj & 1) is nonzero
626 /// - the this-adjustment is (memptr.adj >> 1)
627 /// - the virtual offset is (memptr.ptr)
628 /// ARM uses 'adj' for the virtual flag because Thumb functions
629 /// may be only single-byte aligned.
630 ///
631 /// If the member is virtual, the adjusted 'this' pointer points
632 /// to a vtable pointer from which the virtual offset is applied.
633 ///
634 /// If the member is non-virtual, memptr.ptr is the address of
635 /// the function to call.
636 CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
637 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
638 llvm::Value *&ThisPtrForCall,
639 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
640 CGBuilderTy &Builder = CGF.Builder;
641
642 const FunctionProtoType *FPT =
643 MPT->getPointeeType()->castAs<FunctionProtoType>();
644 auto *RD = MPT->getMostRecentCXXRecordDecl();
645
646 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
647
648 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
649 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
650 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
651
652 // Extract memptr.adj, which is in the second field.
653 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
654
655 // Compute the true adjustment.
656 llvm::Value *Adj = RawAdj;
657 if (UseARMMethodPtrABI)
658 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
659
660 // Apply the adjustment and cast back to the original struct type
661 // for consistency.
662 llvm::Value *This = ThisAddr.emitRawPointer(CGF);
663 This = Builder.CreateInBoundsGEP(Builder.getInt8Ty(), This, Adj);
664 ThisPtrForCall = This;
665
666 // Load the function pointer.
667 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
668
669 // If the LSB in the function pointer is 1, the function pointer points to
670 // a virtual function.
671 llvm::Value *IsVirtual;
672 if (UseARMMethodPtrABI)
673 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
674 else
675 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
676 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
677 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
678
679 // In the virtual path, the adjustment left 'This' pointing to the
680 // vtable of the correct base subobject. The "function pointer" is an
681 // offset within the vtable (+1 for the virtual flag on non-ARM).
682 CGF.EmitBlock(FnVirtual);
683
684 // Cast the adjusted this to a pointer to vtable pointer and load.
685 llvm::Type *VTableTy = CGF.CGM.GlobalsInt8PtrTy;
686 CharUnits VTablePtrAlign =
687 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
688 CGF.getPointerAlign());
689 llvm::Value *VTable = CGF.GetVTablePtr(
690 Address(This, ThisAddr.getElementType(), VTablePtrAlign), VTableTy, RD);
691
692 // Apply the offset.
693 // On ARM64, to reserve extra space in virtual member function pointers,
694 // we only pay attention to the low 32 bits of the offset.
695 llvm::Value *VTableOffset = FnAsInt;
696 if (!UseARMMethodPtrABI)
697 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
698 if (Use32BitVTableOffsetABI) {
699 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
700 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
701 }
702
703 // Check the address of the function pointer if CFI on member function
704 // pointers is enabled.
705 llvm::Constant *CheckSourceLocation;
706 llvm::Constant *CheckTypeDesc;
707 bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
708 CGM.HasHiddenLTOVisibility(RD);
709
710 if (ShouldEmitCFICheck) {
711 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
712 if (BinOp->isPtrMemOp() &&
713 BinOp->getRHS()
714 ->getType()
715 ->hasPointeeToCFIUncheckedCalleeFunctionType())
716 ShouldEmitCFICheck = false;
717 }
718 }
719
720 bool ShouldEmitVFEInfo = CGM.getCodeGenOpts().VirtualFunctionElimination &&
721 CGM.HasHiddenLTOVisibility(RD);
722 // TODO: Update this name not to be restricted to WPD only
723 // as we now emit the vtable info info for speculative devirtualization as
724 // well.
725 bool ShouldEmitWPDInfo =
726 (CGM.getCodeGenOpts().WholeProgramVTables &&
727 // Don't insert type tests if we are forcing public visibility.
728 !CGM.AlwaysHasLTOVisibilityPublic(RD)) ||
729 CGM.getCodeGenOpts().DevirtualizeSpeculatively;
730 llvm::Value *VirtualFn = nullptr;
731
732 {
733 auto CheckOrdinal = SanitizerKind::SO_CFIMFCall;
734 auto CheckHandler = SanitizerHandler::CFICheckFail;
735 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
736
737 llvm::Value *TypeId = nullptr;
738 llvm::Value *CheckResult = nullptr;
739
740 if (ShouldEmitCFICheck || ShouldEmitVFEInfo || ShouldEmitWPDInfo) {
741 // If doing CFI, VFE or WPD, we will need the metadata node to check
742 // against.
743 llvm::Metadata *MD =
744 CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
745 TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
746 }
747
748 if (ShouldEmitVFEInfo) {
749 llvm::Value *VFPAddr =
750 Builder.CreateGEP(CGF.Int8Ty, VTable, VTableOffset);
751
752 // If doing VFE, load from the vtable with a type.checked.load intrinsic
753 // call. Note that we use the GEP to calculate the address to load from
754 // and pass 0 as the offset to the intrinsic. This is because every
755 // vtable slot of the correct type is marked with matching metadata, and
756 // we know that the load must be from one of these slots.
757 llvm::Value *CheckedLoad = Builder.CreateCall(
758 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
759 {VFPAddr, llvm::ConstantInt::get(CGM.Int32Ty, 0), TypeId});
760 CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
761 VirtualFn = Builder.CreateExtractValue(CheckedLoad, 0);
762 } else {
763 // When not doing VFE, emit a normal load, as it allows more
764 // optimisations than type.checked.load.
765 if (ShouldEmitCFICheck || ShouldEmitWPDInfo) {
766 llvm::Value *VFPAddr =
767 Builder.CreateGEP(CGF.Int8Ty, VTable, VTableOffset);
768 llvm::Intrinsic::ID IID = CGM.HasHiddenLTOVisibility(RD)
769 ? llvm::Intrinsic::type_test
770 : llvm::Intrinsic::public_type_test;
771
772 CheckResult =
773 Builder.CreateCall(CGM.getIntrinsic(IID), {VFPAddr, TypeId});
774 }
775
776 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
777 VirtualFn = CGF.Builder.CreateCall(
778 CGM.getIntrinsic(llvm::Intrinsic::load_relative,
779 {VTableOffset->getType()}),
780 {VTable, VTableOffset});
781 } else {
782 llvm::Value *VFPAddr =
783 CGF.Builder.CreateGEP(CGF.Int8Ty, VTable, VTableOffset);
784 VirtualFn = CGF.Builder.CreateAlignedLoad(CGF.DefaultPtrTy, VFPAddr,
785 CGF.getPointerAlign(),
786 "memptr.virtualfn");
787 }
788 }
789 assert(VirtualFn && "Virtual fuction pointer not created!");
790 assert((!ShouldEmitCFICheck || !ShouldEmitVFEInfo || !ShouldEmitWPDInfo ||
791 CheckResult) &&
792 "Check result required but not created!");
793
794 if (ShouldEmitCFICheck) {
795 // If doing CFI, emit the check.
796 CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
797 CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
798 llvm::Constant *StaticData[] = {
799 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
800 CheckSourceLocation,
801 CheckTypeDesc,
802 };
803
804 if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
805 CGF.EmitTrapCheck(CheckResult, CheckHandler);
806 } else {
807 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
808 CGM.getLLVMContext(),
809 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
810 llvm::Value *ValidVtable = Builder.CreateCall(
811 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
812 CGF.EmitCheck(std::make_pair(CheckResult, CheckOrdinal), CheckHandler,
813 StaticData, {VTable, ValidVtable});
814 }
815
816 FnVirtual = Builder.GetInsertBlock();
817 }
818 } // End of sanitizer scope
819
820 CGF.EmitBranch(FnEnd);
821
822 // In the non-virtual path, the function pointer is actually a
823 // function pointer.
824 CGF.EmitBlock(FnNonVirtual);
825 llvm::Value *NonVirtualFn =
826 Builder.CreateIntToPtr(FnAsInt, CGF.DefaultPtrTy, "memptr.nonvirtualfn");
827
828 // Check the function pointer if CFI on member function pointers is enabled.
829 if (ShouldEmitCFICheck) {
830 CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
831 if (RD->hasDefinition()) {
832 auto CheckOrdinal = SanitizerKind::SO_CFIMFCall;
833 auto CheckHandler = SanitizerHandler::CFICheckFail;
834 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
835
836 llvm::Constant *StaticData[] = {
837 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
838 CheckSourceLocation,
839 CheckTypeDesc,
840 };
841
842 llvm::Value *Bit = Builder.getFalse();
843 for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
844 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
845 getContext().getMemberPointerType(MPT->getPointeeType(),
846 /*Qualifier=*/std::nullopt,
847 Base->getCanonicalDecl()));
848 llvm::Value *TypeId =
849 llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
850
851 llvm::Value *TypeTest =
852 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
853 {NonVirtualFn, TypeId});
854 Bit = Builder.CreateOr(Bit, TypeTest);
855 }
856
857 CGF.EmitCheck(std::make_pair(Bit, CheckOrdinal), CheckHandler, StaticData,
858 {NonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
859
860 FnNonVirtual = Builder.GetInsertBlock();
861 }
862 }
863
864 // We're done.
865 CGF.EmitBlock(FnEnd);
866 llvm::PHINode *CalleePtr = Builder.CreatePHI(CGF.DefaultPtrTy, 2);
867 CalleePtr->addIncoming(VirtualFn, FnVirtual);
868 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
869
870 CGPointerAuthInfo PointerAuth;
871
872 if (const auto &Schema =
873 CGM.getCodeGenOpts().PointerAuth.CXXMemberFunctionPointers) {
874 llvm::PHINode *DiscriminatorPHI = Builder.CreatePHI(CGF.IntPtrTy, 2);
875 DiscriminatorPHI->addIncoming(llvm::ConstantInt::get(CGF.IntPtrTy, 0),
876 FnVirtual);
877 const auto &AuthInfo =
878 CGM.getMemberFunctionPointerAuthInfo(QualType(MPT, 0));
879 assert(Schema.getKey() == AuthInfo.getKey() &&
880 "Keys for virtual and non-virtual member functions must match");
881 auto *NonVirtualDiscriminator = AuthInfo.getDiscriminator();
882 DiscriminatorPHI->addIncoming(NonVirtualDiscriminator, FnNonVirtual);
883 PointerAuth = CGPointerAuthInfo(
884 Schema.getKey(), Schema.getAuthenticationMode(), Schema.isIsaPointer(),
885 Schema.authenticatesNullValues(), DiscriminatorPHI);
886 }
887
888 CGCallee Callee(FPT, CalleePtr, PointerAuth);
889 return Callee;
890 }
891
892 /// Compute an l-value by applying the given pointer-to-member to a
893 /// base object.
894 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
895 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
896 const MemberPointerType *MPT, bool IsInBounds) {
897 assert(MemPtr->getType() == CGM.PtrDiffTy);
898
899 CGBuilderTy &Builder = CGF.Builder;
900
901 // Apply the offset.
902 llvm::Value *BaseAddr = Base.emitRawPointer(CGF);
903 return Builder.CreateGEP(CGF.Int8Ty, BaseAddr, MemPtr, "memptr.offset",
904 IsInBounds ? llvm::GEPNoWrapFlags::inBounds()
905 : llvm::GEPNoWrapFlags::none());
906 }
907
908 // See if it's possible to return a constant signed pointer.
909 static llvm::Constant *pointerAuthResignConstant(
910 llvm::Value *Ptr, const CGPointerAuthInfo &CurAuthInfo,
911 const CGPointerAuthInfo &NewAuthInfo, CodeGenModule &CGM) {
912 const auto *CPA = dyn_cast<llvm::ConstantPtrAuth>(Ptr);
913
914 if (!CPA)
915 return nullptr;
916
917 assert(CPA->getKey()->getZExtValue() == CurAuthInfo.getKey() &&
918 CPA->getAddrDiscriminator()->isZeroValue() &&
919 CPA->getDiscriminator() == CurAuthInfo.getDiscriminator() &&
920 "unexpected key or discriminators");
921
922 return CGM.getConstantSignedPointer(
923 CPA->getPointer(), NewAuthInfo.getKey(), nullptr,
924 cast<llvm::ConstantInt>(NewAuthInfo.getDiscriminator()));
925 }
926
927 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
928 /// conversion.
929 ///
930 /// Bitcast conversions are always a no-op under Itanium.
931 ///
932 /// Obligatory offset/adjustment diagram:
933 /// <-- offset --> <-- adjustment -->
934 /// |--------------------------|----------------------|--------------------|
935 /// ^Derived address point ^Base address point ^Member address point
936 ///
937 /// So when converting a base member pointer to a derived member pointer,
938 /// we add the offset to the adjustment because the address point has
939 /// decreased; and conversely, when converting a derived MP to a base MP
940 /// we subtract the offset from the adjustment because the address point
941 /// has increased.
942 ///
943 /// The standard forbids (at compile time) conversion to and from
944 /// virtual bases, which is why we don't have to consider them here.
945 ///
946 /// The standard forbids (at run time) casting a derived MP to a base
947 /// MP when the derived MP does not point to a member of the base.
948 /// This is why -1 is a reasonable choice for null data member
949 /// pointers.
950 llvm::Value *
951 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
952 const CastExpr *E,
953 llvm::Value *src) {
954 // Use constant emission if we can.
955 if (isa<llvm::Constant>(src))
956 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
957
958 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
959 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
960 E->getCastKind() == CK_ReinterpretMemberPointer);
961
962 CGBuilderTy &Builder = CGF.Builder;
963 QualType DstType = E->getType();
964
965 if (DstType->isMemberFunctionPointerType()) {
966 if (const auto &NewAuthInfo =
967 CGM.getMemberFunctionPointerAuthInfo(DstType)) {
968 QualType SrcType = E->getSubExpr()->getType();
969 assert(SrcType->isMemberFunctionPointerType());
970 const auto &CurAuthInfo = CGM.getMemberFunctionPointerAuthInfo(SrcType);
971 llvm::Value *MemFnPtr = Builder.CreateExtractValue(src, 0, "memptr.ptr");
972 llvm::Type *OrigTy = MemFnPtr->getType();
973
974 llvm::BasicBlock *StartBB = Builder.GetInsertBlock();
975 llvm::BasicBlock *ResignBB = CGF.createBasicBlock("resign");
976 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("merge");
977
978 // Check whether we have a virtual offset or a pointer to a function.
979 assert(UseARMMethodPtrABI && "ARM ABI expected");
980 llvm::Value *Adj = Builder.CreateExtractValue(src, 1, "memptr.adj");
981 llvm::Constant *Ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
982 llvm::Value *AndVal = Builder.CreateAnd(Adj, Ptrdiff_1);
983 llvm::Value *IsVirtualOffset =
984 Builder.CreateIsNotNull(AndVal, "is.virtual.offset");
985 Builder.CreateCondBr(IsVirtualOffset, MergeBB, ResignBB);
986
987 CGF.EmitBlock(ResignBB);
988 llvm::Type *PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
989 MemFnPtr = Builder.CreateIntToPtr(MemFnPtr, PtrTy);
990 MemFnPtr =
991 CGF.emitPointerAuthResign(MemFnPtr, SrcType, CurAuthInfo, NewAuthInfo,
992 isa<llvm::Constant>(src));
993 MemFnPtr = Builder.CreatePtrToInt(MemFnPtr, OrigTy);
994 llvm::Value *ResignedVal = Builder.CreateInsertValue(src, MemFnPtr, 0);
995 ResignBB = Builder.GetInsertBlock();
996
997 CGF.EmitBlock(MergeBB);
998 llvm::PHINode *NewSrc = Builder.CreatePHI(src->getType(), 2);
999 NewSrc->addIncoming(src, StartBB);
1000 NewSrc->addIncoming(ResignedVal, ResignBB);
1001 src = NewSrc;
1002 }
1003 }
1004
1005 // Under Itanium, reinterprets don't require any additional processing.
1006 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
1007
1008 llvm::Constant *adj = getMemberPointerAdjustment(E);
1009 if (!adj) return src;
1010
1011 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1012
1013 const MemberPointerType *destTy =
1014 E->getType()->castAs<MemberPointerType>();
1015
1016 // For member data pointers, this is just a matter of adding the
1017 // offset if the source is non-null.
1018 if (destTy->isMemberDataPointer()) {
1019 llvm::Value *dst;
1020 if (isDerivedToBase)
1021 dst = Builder.CreateNSWSub(src, adj, "adj");
1022 else
1023 dst = Builder.CreateNSWAdd(src, adj, "adj");
1024
1025 // Null check.
1026 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
1027 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
1028 return Builder.CreateSelect(isNull, src, dst);
1029 }
1030
1031 // The this-adjustment is left-shifted by 1 on ARM.
1032 if (UseARMMethodPtrABI) {
1033 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
1034 offset <<= 1;
1035 adj = llvm::ConstantInt::get(adj->getType(), offset);
1036 }
1037
1038 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
1039 llvm::Value *dstAdj;
1040 if (isDerivedToBase)
1041 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
1042 else
1043 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
1044
1045 return Builder.CreateInsertValue(src, dstAdj, 1);
1046 }
1047
1048 static llvm::Constant *
1049 pointerAuthResignMemberFunctionPointer(llvm::Constant *Src, QualType DestType,
1050 QualType SrcType, CodeGenModule &CGM) {
1051 assert(DestType->isMemberFunctionPointerType() &&
1052 SrcType->isMemberFunctionPointerType() &&
1053 "member function pointers expected");
1054 if (DestType == SrcType)
1055 return Src;
1056
1057 const auto &NewAuthInfo = CGM.getMemberFunctionPointerAuthInfo(DestType);
1058 const auto &CurAuthInfo = CGM.getMemberFunctionPointerAuthInfo(SrcType);
1059
1060 if (!NewAuthInfo && !CurAuthInfo)
1061 return Src;
1062
1063 llvm::Constant *MemFnPtr = Src->getAggregateElement(0u);
1064 if (MemFnPtr->getNumOperands() == 0) {
1065 // src must be a pair of null pointers.
1066 assert(isa<llvm::ConstantInt>(MemFnPtr) && "constant int expected");
1067 return Src;
1068 }
1069
1070 llvm::Constant *ConstPtr = pointerAuthResignConstant(
1071 cast<llvm::User>(MemFnPtr)->getOperand(0), CurAuthInfo, NewAuthInfo, CGM);
1072 ConstPtr = llvm::ConstantExpr::getPtrToInt(ConstPtr, MemFnPtr->getType());
1073 return ConstantFoldInsertValueInstruction(Src, ConstPtr, 0);
1074 }
1075
1076 llvm::Constant *
1077 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1078 llvm::Constant *src) {
1079 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1080 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1081 E->getCastKind() == CK_ReinterpretMemberPointer);
1082
1083 QualType DstType = E->getType();
1084
1085 if (DstType->isMemberFunctionPointerType())
1086 src = pointerAuthResignMemberFunctionPointer(
1087 src, DstType, E->getSubExpr()->getType(), CGM);
1088
1089 // Under Itanium, reinterprets don't require any additional processing.
1090 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
1091
1092 // If the adjustment is trivial, we don't need to do anything.
1093 llvm::Constant *adj = getMemberPointerAdjustment(E);
1094 if (!adj) return src;
1095
1096 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1097
1098 const MemberPointerType *destTy =
1099 E->getType()->castAs<MemberPointerType>();
1100
1101 // For member data pointers, this is just a matter of adding the
1102 // offset if the source is non-null.
1103 if (destTy->isMemberDataPointer()) {
1104 // null maps to null.
1105 if (src->isAllOnesValue()) return src;
1106
1107 if (isDerivedToBase)
1108 return llvm::ConstantExpr::getNSWSub(src, adj);
1109 else
1110 return llvm::ConstantExpr::getNSWAdd(src, adj);
1111 }
1112
1113 // The this-adjustment is left-shifted by 1 on ARM.
1114 if (UseARMMethodPtrABI) {
1115 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
1116 offset <<= 1;
1117 adj = llvm::ConstantInt::get(adj->getType(), offset);
1118 }
1119
1120 llvm::Constant *srcAdj = src->getAggregateElement(1);
1121 llvm::Constant *dstAdj;
1122 if (isDerivedToBase)
1123 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
1124 else
1125 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
1126
1127 llvm::Constant *res = ConstantFoldInsertValueInstruction(src, dstAdj, 1);
1128 assert(res != nullptr && "Folding must succeed");
1129 return res;
1130 }
1131
1132 llvm::Constant *
1133 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
1134 // Itanium C++ ABI 2.3:
1135 // A NULL pointer is represented as -1.
1136 if (MPT->isMemberDataPointer())
1137 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
1138
1139 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
1140 llvm::Constant *Values[2] = { Zero, Zero };
1141 return llvm::ConstantStruct::getAnon(Values);
1142 }
1143
1144 llvm::Constant *
1145 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1146 CharUnits offset) {
1147 // Itanium C++ ABI 2.3:
1148 // A pointer to data member is an offset from the base address of
1149 // the class object containing it, represented as a ptrdiff_t
1150 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
1151 }
1152
1153 llvm::Constant *
1154 ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
1155 return BuildMemberPointer(MD, CharUnits::Zero());
1156 }
1157
1158 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
1159 CharUnits ThisAdjustment) {
1160 assert(MD->isInstance() && "Member function must not be static!");
1161
1162 CodeGenTypes &Types = CGM.getTypes();
1163
1164 // Get the function pointer (or index if this is a virtual function).
1165 llvm::Constant *MemPtr[2];
1166 if (MD->isVirtual()) {
1167 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
1168 uint64_t VTableOffset;
1169 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
1170 // Multiply by 4-byte relative offsets.
1171 VTableOffset = Index * 4;
1172 } else {
1173 const ASTContext &Context = getContext();
1174 CharUnits PointerWidth = Context.toCharUnitsFromBits(
1175 Context.getTargetInfo().getPointerWidth(LangAS::Default));
1176 VTableOffset = Index * PointerWidth.getQuantity();
1177 }
1178
1179 if (UseARMMethodPtrABI) {
1180 // ARM C++ ABI 3.2.1:
1181 // This ABI specifies that adj contains twice the this
1182 // adjustment, plus 1 if the member function is virtual. The
1183 // least significant bit of adj then makes exactly the same
1184 // discrimination as the least significant bit of ptr does for
1185 // Itanium.
1186
1187 // We cannot use the Itanium ABI's representation for virtual member
1188 // function pointers under pointer authentication because it would
1189 // require us to store both the virtual offset and the constant
1190 // discriminator in the pointer, which would be immediately vulnerable
1191 // to attack. Instead we introduce a thunk that does the virtual dispatch
1192 // and store it as if it were a non-virtual member function. This means
1193 // that virtual function pointers may not compare equal anymore, but
1194 // fortunately they aren't required to by the standard, and we do make
1195 // a best-effort attempt to re-use the thunk.
1196 //
1197 // To support interoperation with code in which pointer authentication
1198 // is disabled, derefencing a member function pointer must still handle
1199 // the virtual case, but it can use a discriminator which should never
1200 // be valid.
1201 const auto &Schema =
1202 CGM.getCodeGenOpts().PointerAuth.CXXMemberFunctionPointers;
1203 if (Schema)
1204 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(
1205 getSignedVirtualMemberFunctionPointer(MD), CGM.PtrDiffTy);
1206 else
1207 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
1208 // Don't set the LSB of adj to 1 if pointer authentication for member
1209 // function pointers is enabled.
1210 MemPtr[1] = llvm::ConstantInt::get(
1211 CGM.PtrDiffTy, 2 * ThisAdjustment.getQuantity() + !Schema);
1212 } else {
1213 // Itanium C++ ABI 2.3:
1214 // For a virtual function, [the pointer field] is 1 plus the
1215 // virtual table offset (in bytes) of the function,
1216 // represented as a ptrdiff_t.
1217 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
1218 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
1219 ThisAdjustment.getQuantity());
1220 }
1221 } else {
1222 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1223 llvm::Type *Ty;
1224 // Check whether the function has a computable LLVM signature.
1225 if (Types.isFuncTypeConvertible(FPT)) {
1226 // The function has a computable LLVM signature; use the correct type.
1227 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1228 } else {
1229 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1230 // function type is incomplete.
1231 Ty = CGM.PtrDiffTy;
1232 }
1233 llvm::Constant *addr = CGM.getMemberFunctionPointer(MD, Ty);
1234
1235 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
1236 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
1237 (UseARMMethodPtrABI ? 2 : 1) *
1238 ThisAdjustment.getQuantity());
1239 }
1240
1241 return llvm::ConstantStruct::getAnon(MemPtr);
1242 }
1243
1244 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
1245 QualType MPType) {
1246 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1247 const ValueDecl *MPD = MP.getMemberPointerDecl();
1248 if (!MPD)
1249 return EmitNullMemberPointer(MPT);
1250
1251 CharUnits ThisAdjustment = getContext().getMemberPointerPathAdjustment(MP);
1252
1253 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
1254 llvm::Constant *Src = BuildMemberPointer(MD, ThisAdjustment);
1255 QualType SrcType = getContext().getMemberPointerType(
1256 MD->getType(), /*Qualifier=*/std::nullopt, MD->getParent());
1257 return pointerAuthResignMemberFunctionPointer(Src, MPType, SrcType, CGM);
1258 }
1259
1260 CharUnits FieldOffset =
1261 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1262 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
1263 }
1264
1265 /// The comparison algorithm is pretty easy: the member pointers are
1266 /// the same if they're either bitwise identical *or* both null.
1267 ///
1268 /// ARM is different here only because null-ness is more complicated.
1269 llvm::Value *
1270 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1271 llvm::Value *L,
1272 llvm::Value *R,
1273 const MemberPointerType *MPT,
1274 bool Inequality) {
1275 CGBuilderTy &Builder = CGF.Builder;
1276
1277 llvm::ICmpInst::Predicate Eq;
1278 llvm::Instruction::BinaryOps And, Or;
1279 if (Inequality) {
1280 Eq = llvm::ICmpInst::ICMP_NE;
1281 And = llvm::Instruction::Or;
1282 Or = llvm::Instruction::And;
1283 } else {
1284 Eq = llvm::ICmpInst::ICMP_EQ;
1285 And = llvm::Instruction::And;
1286 Or = llvm::Instruction::Or;
1287 }
1288
1289 // Member data pointers are easy because there's a unique null
1290 // value, so it just comes down to bitwise equality.
1291 if (MPT->isMemberDataPointer())
1292 return Builder.CreateICmp(Eq, L, R);
1293
1294 // For member function pointers, the tautologies are more complex.
1295 // The Itanium tautology is:
1296 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
1297 // The ARM tautology is:
1298 // (L == R) <==> (L.ptr == R.ptr &&
1299 // (L.adj == R.adj ||
1300 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
1301 // The inequality tautologies have exactly the same structure, except
1302 // applying De Morgan's laws.
1303
1304 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
1305 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
1306
1307 // This condition tests whether L.ptr == R.ptr. This must always be
1308 // true for equality to hold.
1309 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
1310
1311 // This condition, together with the assumption that L.ptr == R.ptr,
1312 // tests whether the pointers are both null. ARM imposes an extra
1313 // condition.
1314 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
1315 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
1316
1317 // This condition tests whether L.adj == R.adj. If this isn't
1318 // true, the pointers are unequal unless they're both null.
1319 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
1320 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
1321 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
1322
1323 // Null member function pointers on ARM clear the low bit of Adj,
1324 // so the zero condition has to check that neither low bit is set.
1325 if (UseARMMethodPtrABI) {
1326 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
1327
1328 // Compute (l.adj | r.adj) & 1 and test it against zero.
1329 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
1330 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
1331 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
1332 "cmp.or.adj");
1333 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
1334 }
1335
1336 // Tie together all our conditions.
1337 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
1338 Result = Builder.CreateBinOp(And, PtrEq, Result,
1339 Inequality ? "memptr.ne" : "memptr.eq");
1340 return Result;
1341 }
1342
1343 llvm::Value *
1344 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1345 llvm::Value *MemPtr,
1346 const MemberPointerType *MPT) {
1347 CGBuilderTy &Builder = CGF.Builder;
1348
1349 /// For member data pointers, this is just a check against -1.
1350 if (MPT->isMemberDataPointer()) {
1351 assert(MemPtr->getType() == CGM.PtrDiffTy);
1352 llvm::Value *NegativeOne =
1353 llvm::Constant::getAllOnesValue(MemPtr->getType());
1354 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1355 }
1356
1357 // In Itanium, a member function pointer is not null if 'ptr' is not null.
1358 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
1359
1360 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1361 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1362
1363 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1364 // (the virtual bit) is set.
1365 if (UseARMMethodPtrABI) {
1366 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
1367 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
1368 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
1369 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1370 "memptr.isvirtual");
1371 Result = Builder.CreateOr(Result, IsVirtual);
1372 }
1373
1374 return Result;
1375 }
1376
1377 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1378 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1379 if (!RD)
1380 return false;
1381
1382 // If C++ prohibits us from making a copy, return by address.
1383 if (!RD->canPassInRegisters()) {
1384 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1385 FI.getReturnInfo() = ABIArgInfo::getIndirect(
1386 Align, /*AddrSpace=*/CGM.getDataLayout().getAllocaAddrSpace(),
1387 /*ByVal=*/false);
1388 return true;
1389 }
1390 return false;
1391 }
1392
1393 /// The Itanium ABI requires non-zero initialization only for data
1394 /// member pointers, for which '0' is a valid offset.
1395 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1396 return MPT->isMemberFunctionPointer();
1397 }
1398
1399 /// The Itanium ABI always places an offset to the complete object
1400 /// at entry -2 in the vtable.
1401 void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1402 const CXXDeleteExpr *DE,
1403 Address Ptr,
1404 QualType ElementType,
1405 const CXXDestructorDecl *Dtor) {
1406 bool UseGlobalDelete = DE->isGlobalDelete();
1407 if (UseGlobalDelete) {
1408 // Derive the complete-object pointer, which is what we need
1409 // to pass to the deallocation function.
1410
1411 // Grab the vtable pointer as an intptr_t*.
1412 auto *ClassDecl = ElementType->castAsCXXRecordDecl();
1413 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.DefaultPtrTy, ClassDecl);
1414
1415 // Track back to entry -2 and pull out the offset there.
1416 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1417 CGF.IntPtrTy, VTable, -2, "complete-offset.ptr");
1418 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(CGF.IntPtrTy, OffsetPtr,
1419 CGF.getPointerAlign());
1420
1421 // Apply the offset.
1422 llvm::Value *CompletePtr = Ptr.emitRawPointer(CGF);
1423 CompletePtr =
1424 CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, CompletePtr, Offset);
1425
1426 // If we're supposed to call the global delete, make sure we do so
1427 // even if the destructor throws.
1428 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1429 ElementType);
1430 }
1431
1432 // FIXME: Provide a source location here even though there's no
1433 // CXXMemberCallExpr for dtor call.
1434 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1435 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE,
1436 /*CallOrInvoke=*/nullptr);
1437
1438 if (UseGlobalDelete)
1439 CGF.PopCleanupBlock();
1440 }
1441
1442 void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1443 // void __cxa_rethrow();
1444
1445 llvm::FunctionType *FTy =
1446 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1447
1448 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1449
1450 if (isNoReturn)
1451 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, {});
1452 else
1453 CGF.EmitRuntimeCallOrInvoke(Fn);
1454 }
1455
1456 static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
1457 // void *__cxa_allocate_exception(size_t thrown_size);
1458
1459 llvm::FunctionType *FTy =
1460 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
1461
1462 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1463 }
1464
1465 static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
1466 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1467 // void (*dest) (void *));
1468
1469 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.GlobalsInt8PtrTy, CGM.Int8PtrTy };
1470 llvm::FunctionType *FTy =
1471 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
1472
1473 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1474 }
1475
1476 void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1477 QualType ThrowType = E->getSubExpr()->getType();
1478 // Now allocate the exception object.
1479 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1480 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1481
1482 llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
1483 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1484 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1485
1486 CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
1487 CGF.EmitAnyExprToExn(
1488 E->getSubExpr(), Address(ExceptionPtr, CGM.Int8Ty, ExnAlign));
1489
1490 // Now throw the exception.
1491 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1492 /*ForEH=*/true);
1493
1494 // The address of the destructor. If the exception type has a
1495 // trivial destructor (or isn't a record), we just pass null.
1496 llvm::Constant *Dtor = nullptr;
1497 if (const auto *Record = ThrowType->getAsCXXRecordDecl();
1498 Record && !Record->hasTrivialDestructor()) {
1499 // __cxa_throw is declared to take its destructor as void (*)(void *). We
1500 // must match that if function pointers can be authenticated with a
1501 // discriminator based on their type.
1502 const ASTContext &Ctx = getContext();
1503 QualType DtorTy = Ctx.getFunctionType(Ctx.VoidTy, {Ctx.VoidPtrTy},
1504 FunctionProtoType::ExtProtoInfo());
1505
1506 CXXDestructorDecl *DtorD = Record->getDestructor();
1507 Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
1508 Dtor = CGM.getFunctionPointer(Dtor, DtorTy);
1509 }
1510 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1511
1512 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1513 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1514 }
1515
1516 static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1517 // void *__dynamic_cast(const void *sub,
1518 // global_as const abi::__class_type_info *src,
1519 // global_as const abi::__class_type_info *dst,
1520 // std::ptrdiff_t src2dst_offset);
1521
1522 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1523 llvm::Type *GlobInt8PtrTy = CGF.GlobalsInt8PtrTy;
1524 llvm::Type *PtrDiffTy =
1525 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1526
1527 llvm::Type *Args[4] = { Int8PtrTy, GlobInt8PtrTy, GlobInt8PtrTy, PtrDiffTy };
1528
1529 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1530
1531 // Mark the function as nounwind willreturn readonly.
1532 llvm::AttrBuilder FuncAttrs(CGF.getLLVMContext());
1533 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1534 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
1535 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
1536 llvm::AttributeList Attrs = llvm::AttributeList::get(
1537 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
1538
1539 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1540 }
1541
1542 static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
1543 // void __cxa_bad_cast();
1544 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1545 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1546 }
1547
1548 /// Compute the src2dst_offset hint as described in the
1549 /// Itanium C++ ABI [2.9.7]
1550 static CharUnits computeOffsetHint(ASTContext &Context,
1551 const CXXRecordDecl *Src,
1552 const CXXRecordDecl *Dst) {
1553 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1554 /*DetectVirtual=*/false);
1555
1556 // If Dst is not derived from Src we can skip the whole computation below and
1557 // return that Src is not a public base of Dst. Record all inheritance paths.
1558 if (!Dst->isDerivedFrom(Src, Paths))
1559 return CharUnits::fromQuantity(-2ULL);
1560
1561 unsigned NumPublicPaths = 0;
1562 CharUnits Offset;
1563
1564 // Now walk all possible inheritance paths.
1565 for (const CXXBasePath &Path : Paths) {
1566 if (Path.Access != AS_public) // Ignore non-public inheritance.
1567 continue;
1568
1569 ++NumPublicPaths;
1570
1571 for (const CXXBasePathElement &PathElement : Path) {
1572 // If the path contains a virtual base class we can't give any hint.
1573 // -1: no hint.
1574 if (PathElement.Base->isVirtual())
1575 return CharUnits::fromQuantity(-1ULL);
1576
1577 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1578 continue;
1579
1580 // Accumulate the base class offsets.
1581 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1582 Offset += L.getBaseClassOffset(
1583 PathElement.Base->getType()->getAsCXXRecordDecl());
1584 }
1585 }
1586
1587 // -2: Src is not a public base of Dst.
1588 if (NumPublicPaths == 0)
1589 return CharUnits::fromQuantity(-2ULL);
1590
1591 // -3: Src is a multiple public base type but never a virtual base type.
1592 if (NumPublicPaths > 1)
1593 return CharUnits::fromQuantity(-3ULL);
1594
1595 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1596 // Return the offset of Src from the origin of Dst.
1597 return Offset;
1598 }
1599
1600 static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
1601 // void __cxa_bad_typeid();
1602 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1603
1604 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1605 }
1606
1607 bool ItaniumCXXABI::shouldTypeidBeNullChecked(QualType SrcRecordTy) {
1608 return true;
1609 }
1610
1611 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1612 llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
1613 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1614 Call->setDoesNotReturn();
1615 CGF.Builder.CreateUnreachable();
1616 }
1617
1618 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1619 QualType SrcRecordTy,
1620 Address ThisPtr,
1621 llvm::Type *StdTypeInfoPtrTy) {
1622 auto *ClassDecl = SrcRecordTy->castAsCXXRecordDecl();
1623 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr, CGM.GlobalsInt8PtrTy,
1624 ClassDecl);
1625
1626 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
1627 // Load the type info.
1628 Value = CGF.Builder.CreateCall(
1629 CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
1630 {Value, llvm::ConstantInt::getSigned(CGM.Int32Ty, -4)});
1631 } else {
1632 // Load the type info.
1633 Value =
1634 CGF.Builder.CreateConstInBoundsGEP1_64(StdTypeInfoPtrTy, Value, -1ULL);
1635 }
1636 return CGF.Builder.CreateAlignedLoad(StdTypeInfoPtrTy, Value,
1637 CGF.getPointerAlign());
1638 }
1639
1640 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1641 QualType SrcRecordTy) {
1642 return SrcIsPtr;
1643 }
1644
1645 llvm::Value *ItaniumCXXABI::emitDynamicCastCall(
1646 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1647 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1648 llvm::Type *PtrDiffLTy =
1649 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1650
1651 llvm::Value *SrcRTTI =
1652 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1653 llvm::Value *DestRTTI =
1654 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1655
1656 // Compute the offset hint.
1657 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1658 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1659 llvm::Value *OffsetHint = llvm::ConstantInt::getSigned(
1660 PtrDiffLTy,
1661 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1662
1663 // Emit the call to __dynamic_cast.
1664 llvm::Value *Value = ThisAddr.emitRawPointer(CGF);
1665 if (CGM.getCodeGenOpts().PointerAuth.CXXVTablePointers) {
1666 // We perform a no-op load of the vtable pointer here to force an
1667 // authentication. In environments that do not support pointer
1668 // authentication this is a an actual no-op that will be elided. When
1669 // pointer authentication is supported and enforced on vtable pointers this
1670 // load can trap.
1671 llvm::Value *Vtable =
1672 CGF.GetVTablePtr(ThisAddr, CGM.Int8PtrTy, SrcDecl,
1673 CodeGenFunction::VTableAuthMode::MustTrap);
1674 assert(Vtable);
1675 (void)Vtable;
1676 }
1677
1678 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1679 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1680
1681 /// C++ [expr.dynamic.cast]p9:
1682 /// A failed cast to reference type throws std::bad_cast
1683 if (DestTy->isReferenceType()) {
1684 llvm::BasicBlock *BadCastBlock =
1685 CGF.createBasicBlock("dynamic_cast.bad_cast");
1686
1687 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1688 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1689
1690 CGF.EmitBlock(BadCastBlock);
1691 EmitBadCastCall(CGF);
1692 }
1693
1694 return Value;
1695 }
1696
1697 std::optional<CGCXXABI::ExactDynamicCastInfo>
1698 ItaniumCXXABI::getExactDynamicCastInfo(QualType SrcRecordTy, QualType DestTy,
1699 QualType DestRecordTy) {
1700 assert(shouldEmitExactDynamicCast(DestRecordTy));
1701
1702 ASTContext &Context = getContext();
1703
1704 // Find all the inheritance paths.
1705 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1706 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1707 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1708 /*DetectVirtual=*/false);
1709 (void)DestDecl->isDerivedFrom(SrcDecl, Paths);
1710
1711 // Find an offset within `DestDecl` where a `SrcDecl` instance and its vptr
1712 // might appear.
1713 std::optional<CharUnits> Offset;
1714 for (const CXXBasePath &Path : Paths) {
1715 // dynamic_cast only finds public inheritance paths.
1716 if (Path.Access != AS_public)
1717 continue;
1718
1719 CharUnits PathOffset;
1720 for (const CXXBasePathElement &PathElement : Path) {
1721 // Find the offset along this inheritance step.
1722 const CXXRecordDecl *Base =
1723 PathElement.Base->getType()->getAsCXXRecordDecl();
1724 if (PathElement.Base->isVirtual()) {
1725 // For a virtual base class, we know that the derived class is exactly
1726 // DestDecl, so we can use the vbase offset from its layout.
1727 const ASTRecordLayout &L = Context.getASTRecordLayout(DestDecl);
1728 PathOffset = L.getVBaseClassOffset(Base);
1729 } else {
1730 const ASTRecordLayout &L =
1731 Context.getASTRecordLayout(PathElement.Class);
1732 PathOffset += L.getBaseClassOffset(Base);
1733 }
1734 }
1735
1736 if (!Offset)
1737 Offset = PathOffset;
1738 else if (Offset != PathOffset) {
1739 // Base appears in at least two different places.
1740 return ExactDynamicCastInfo{/*RequiresCastToPrimaryBase=*/true,
1741 CharUnits::Zero()};
1742 }
1743 }
1744 if (!Offset)
1745 return std::nullopt;
1746 return ExactDynamicCastInfo{/*RequiresCastToPrimaryBase=*/false, *Offset};
1747 }
1748
1749 llvm::Value *ItaniumCXXABI::emitExactDynamicCast(
1750 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1751 QualType DestTy, QualType DestRecordTy,
1752 const ExactDynamicCastInfo &ExactCastInfo, llvm::BasicBlock *CastSuccess,
1753 llvm::BasicBlock *CastFail) {
1754 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1755 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1756 auto AuthenticateVTable = [&](Address ThisAddr, const CXXRecordDecl *Decl) {
1757 if (!CGF.getLangOpts().PointerAuthCalls)
1758 return;
1759 (void)CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, Decl,
1760 CodeGenFunction::VTableAuthMode::MustTrap);
1761 };
1762
1763 bool PerformPostCastAuthentication = false;
1764 llvm::Value *VTable = nullptr;
1765 if (ExactCastInfo.RequiresCastToPrimaryBase) {
1766 // Base appears in at least two different places. Find the most-derived
1767 // object and see if it's a DestDecl. Note that the most-derived object
1768 // must be at least as aligned as this base class subobject, and must
1769 // have a vptr at offset 0.
1770 llvm::Value *PrimaryBase =
1771 emitDynamicCastToVoid(CGF, ThisAddr, SrcRecordTy);
1772 ThisAddr = Address(PrimaryBase, CGF.VoidPtrTy, ThisAddr.getAlignment());
1773 SrcDecl = DestDecl;
1774 // This unauthenticated load is unavoidable, so we're relying on the
1775 // authenticated load in the dynamic cast to void, and we'll manually
1776 // authenticate the resulting v-table at the end of the cast check.
1777 PerformPostCastAuthentication = CGF.getLangOpts().PointerAuthCalls;
1778 CGPointerAuthInfo StrippingAuthInfo(0, PointerAuthenticationMode::Strip,
1779 false, false, nullptr);
1780 Address VTablePtrPtr = ThisAddr.withElementType(CGF.VoidPtrPtrTy);
1781 VTable = CGF.Builder.CreateLoad(VTablePtrPtr, "vtable");
1782 if (PerformPostCastAuthentication)
1783 VTable = CGF.EmitPointerAuthAuth(StrippingAuthInfo, VTable);
1784 } else
1785 VTable = CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, SrcDecl);
1786
1787 // Compare the vptr against the expected vptr for the destination type at
1788 // this offset.
1789 llvm::Constant *ExpectedVTable = getVTableAddressPoint(
1790 BaseSubobject(SrcDecl, ExactCastInfo.Offset), DestDecl);
1791 llvm::Value *Success = CGF.Builder.CreateICmpEQ(VTable, ExpectedVTable);
1792 llvm::Value *AdjustedThisPtr = ThisAddr.emitRawPointer(CGF);
1793
1794 if (!ExactCastInfo.Offset.isZero()) {
1795 CharUnits::QuantityType Offset = ExactCastInfo.Offset.getQuantity();
1796 llvm::Constant *OffsetConstant =
1797 llvm::ConstantInt::get(CGF.PtrDiffTy, -Offset);
1798 AdjustedThisPtr = CGF.Builder.CreateInBoundsGEP(CGF.CharTy, AdjustedThisPtr,
1799 OffsetConstant);
1800 PerformPostCastAuthentication = CGF.getLangOpts().PointerAuthCalls;
1801 }
1802
1803 if (PerformPostCastAuthentication) {
1804 // If we've changed the object pointer we authenticate the vtable pointer
1805 // of the resulting object.
1806 llvm::BasicBlock *NonNullBlock = CGF.Builder.GetInsertBlock();
1807 llvm::BasicBlock *PostCastAuthSuccess =
1808 CGF.createBasicBlock("dynamic_cast.postauth.success");
1809 llvm::BasicBlock *PostCastAuthComplete =
1810 CGF.createBasicBlock("dynamic_cast.postauth.complete");
1811 CGF.Builder.CreateCondBr(Success, PostCastAuthSuccess,
1812 PostCastAuthComplete);
1813 CGF.EmitBlock(PostCastAuthSuccess);
1814 Address AdjustedThisAddr =
1815 Address(AdjustedThisPtr, CGF.IntPtrTy, CGF.getPointerAlign());
1816 AuthenticateVTable(AdjustedThisAddr, DestDecl);
1817 CGF.EmitBranch(PostCastAuthComplete);
1818 CGF.EmitBlock(PostCastAuthComplete);
1819 llvm::PHINode *PHI = CGF.Builder.CreatePHI(AdjustedThisPtr->getType(), 2);
1820 PHI->addIncoming(AdjustedThisPtr, PostCastAuthSuccess);
1821 llvm::Value *NullValue =
1822 llvm::Constant::getNullValue(AdjustedThisPtr->getType());
1823 PHI->addIncoming(NullValue, NonNullBlock);
1824 AdjustedThisPtr = PHI;
1825 }
1826 CGF.Builder.CreateCondBr(Success, CastSuccess, CastFail);
1827 return AdjustedThisPtr;
1828 }
1829
1830 llvm::Value *ItaniumCXXABI::emitDynamicCastToVoid(CodeGenFunction &CGF,
1831 Address ThisAddr,
1832 QualType SrcRecordTy) {
1833 auto *ClassDecl = SrcRecordTy->castAsCXXRecordDecl();
1834 llvm::Value *OffsetToTop;
1835 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
1836 // Get the vtable pointer.
1837 llvm::Value *VTable =
1838 CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, ClassDecl);
1839
1840 // Get the offset-to-top from the vtable.
1841 OffsetToTop =
1842 CGF.Builder.CreateConstInBoundsGEP1_32(CGM.Int32Ty, VTable, -2U);
1843 OffsetToTop = CGF.Builder.CreateAlignedLoad(
1844 CGM.Int32Ty, OffsetToTop, CharUnits::fromQuantity(4), "offset.to.top");
1845 } else {
1846 llvm::Type *PtrDiffLTy =
1847 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1848
1849 // Get the vtable pointer.
1850 llvm::Value *VTable =
1851 CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, ClassDecl);
1852
1853 // Get the offset-to-top from the vtable.
1854 OffsetToTop =
1855 CGF.Builder.CreateConstInBoundsGEP1_64(PtrDiffLTy, VTable, -2ULL);
1856 OffsetToTop = CGF.Builder.CreateAlignedLoad(
1857 PtrDiffLTy, OffsetToTop, CGF.getPointerAlign(), "offset.to.top");
1858 }
1859 // Finally, add the offset to the pointer.
1860 return CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, ThisAddr.emitRawPointer(CGF),
1861 OffsetToTop);
1862 }
1863
1864 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1865 llvm::FunctionCallee Fn = getBadCastFn(CGF);
1866 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1867 Call->setDoesNotReturn();
1868 CGF.Builder.CreateUnreachable();
1869 return true;
1870 }
1871
1872 llvm::Value *
1873 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1874 Address This,
1875 const CXXRecordDecl *ClassDecl,
1876 const CXXRecordDecl *BaseClassDecl) {
1877 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
1878 CharUnits VBaseOffsetOffset =
1879 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1880 BaseClassDecl);
1881 llvm::Value *VBaseOffsetPtr =
1882 CGF.Builder.CreateConstGEP1_64(
1883 CGF.Int8Ty, VTablePtr, VBaseOffsetOffset.getQuantity(),
1884 "vbase.offset.ptr");
1885
1886 llvm::Value *VBaseOffset;
1887 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
1888 VBaseOffset = CGF.Builder.CreateAlignedLoad(
1889 CGF.Int32Ty, VBaseOffsetPtr, CharUnits::fromQuantity(4),
1890 "vbase.offset");
1891 } else {
1892 VBaseOffset = CGF.Builder.CreateAlignedLoad(
1893 CGM.PtrDiffTy, VBaseOffsetPtr, CGF.getPointerAlign(), "vbase.offset");
1894 }
1895 return VBaseOffset;
1896 }
1897
1898 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1899 // Just make sure we're in sync with TargetCXXABI.
1900 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1901
1902 // The constructor used for constructing this as a base class;
1903 // ignores virtual bases.
1904 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1905
1906 // The constructor used for constructing this as a complete class;
1907 // constructs the virtual bases, then calls the base constructor.
1908 if (!D->getParent()->isAbstract()) {
1909 // We don't need to emit the complete ctor if the class is abstract.
1910 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1911 }
1912 }
1913
1914 CGCXXABI::AddedStructorArgCounts
1915 ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
1916 SmallVectorImpl<CanQualType> &ArgTys) {
1917 ASTContext &Context = getContext();
1918
1919 // All parameters are already in place except VTT, which goes after 'this'.
1920 // These are Clang types, so we don't need to worry about sret yet.
1921
1922 // Check if we need to add a VTT parameter (which has type global void **).
1923 if ((isa<CXXConstructorDecl>(GD.getDecl()) ? GD.getCtorType() == Ctor_Base
1924 : GD.getDtorType() == Dtor_Base) &&
1925 cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
1926 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
1927 QualType Q = Context.getAddrSpaceQualType(Context.VoidPtrTy, AS);
1928 ArgTys.insert(ArgTys.begin() + 1,
1929 Context.getPointerType(CanQualType::CreateUnsafe(Q)));
1930 return AddedStructorArgCounts::prefix(1);
1931 }
1932 return AddedStructorArgCounts{};
1933 }
1934
1935 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1936 // The destructor used for destructing this as a base class; ignores
1937 // virtual bases.
1938 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1939
1940 // The destructor used for destructing this as a most-derived class;
1941 // call the base destructor and then destructs any virtual bases.
1942 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1943
1944 // The destructor in a virtual table is always a 'deleting'
1945 // destructor, which calls the complete destructor and then uses the
1946 // appropriate operator delete.
1947 if (D->isVirtual())
1948 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1949 }
1950
1951 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1952 QualType &ResTy,
1953 FunctionArgList &Params) {
1954 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1955 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1956
1957 // Check if we need a VTT parameter as well.
1958 if (NeedsVTTParameter(CGF.CurGD)) {
1959 ASTContext &Context = getContext();
1960
1961 // FIXME: avoid the fake decl
1962 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
1963 QualType Q = Context.getAddrSpaceQualType(Context.VoidPtrTy, AS);
1964 QualType T = Context.getPointerType(Q);
1965 auto *VTTDecl = ImplicitParamDecl::Create(
1966 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1967 T, ImplicitParamKind::CXXVTT);
1968 Params.insert(Params.begin() + 1, VTTDecl);
1969 getStructorImplicitParamDecl(CGF) = VTTDecl;
1970 }
1971 }
1972
1973 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1974 // Naked functions have no prolog.
1975 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1976 return;
1977
1978 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
1979 /// adjustments are required, because they are all handled by thunks.
1980 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
1981
1982 /// Initialize the 'vtt' slot if needed.
1983 if (getStructorImplicitParamDecl(CGF)) {
1984 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1985 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1986 }
1987
1988 /// If this is a function that the ABI specifies returns 'this', initialize
1989 /// the return slot to 'this' at the start of the function.
1990 ///
1991 /// Unlike the setting of return types, this is done within the ABI
1992 /// implementation instead of by clients of CGCXXABI because:
1993 /// 1) getThisValue is currently protected
1994 /// 2) in theory, an ABI could implement 'this' returns some other way;
1995 /// HasThisReturn only specifies a contract, not the implementation
1996 if (HasThisReturn(CGF.CurGD))
1997 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1998 }
1999
2000 CGCXXABI::AddedStructorArgs ItaniumCXXABI::getImplicitConstructorArgs(
2001 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
2002 bool ForVirtualBase, bool Delegating) {
2003 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
2004 return AddedStructorArgs{};
2005
2006 // Insert the implicit 'vtt' argument as the second argument. Make sure to
2007 // correctly reflect its address space, which can differ from generic on
2008 // some targets.
2009 llvm::Value *VTT =
2010 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
2011 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
2012 QualType Q = getContext().getAddrSpaceQualType(getContext().VoidPtrTy, AS);
2013 QualType VTTTy = getContext().getPointerType(Q);
2014 return AddedStructorArgs::prefix({{VTT, VTTTy}});
2015 }
2016
2017 llvm::Value *ItaniumCXXABI::getCXXDestructorImplicitParam(
2018 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
2019 bool ForVirtualBase, bool Delegating) {
2020 GlobalDecl GD(DD, Type);
2021 return CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
2022 }
2023
2024 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
2025 const CXXDestructorDecl *DD,
2026 CXXDtorType Type, bool ForVirtualBase,
2027 bool Delegating, Address This,
2028 QualType ThisTy) {
2029 GlobalDecl GD(DD, Type);
2030 llvm::Value *VTT =
2031 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase, Delegating);
2032 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
2033
2034 CGCallee Callee;
2035 if (getContext().getLangOpts().AppleKext &&
2036 Type != Dtor_Base && DD->isVirtual())
2037 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
2038 else
2039 Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
2040
2041 CGF.EmitCXXDestructorCall(GD, Callee, CGF.getAsNaturalPointerTo(This, ThisTy),
2042 ThisTy, VTT, VTTTy, nullptr);
2043 }
2044
2045 // Check if any non-inline method has the specified attribute.
2046 template <typename T>
2047 static bool CXXRecordNonInlineHasAttr(const CXXRecordDecl *RD) {
2048 for (const auto *D : RD->noload_decls()) {
2049 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2050 if (FD->isInlined() || FD->doesThisDeclarationHaveABody() ||
2051 FD->isPureVirtual())
2052 continue;
2053 if (D->hasAttr<T>())
2054 return true;
2055 }
2056 }
2057
2058 return false;
2059 }
2060
2061 static void setVTableSelectiveDLLImportExport(CodeGenModule &CGM,
2062 llvm::GlobalVariable *VTable,
2063 const CXXRecordDecl *RD) {
2064 if (VTable->getDLLStorageClass() !=
2065 llvm::GlobalVariable::DefaultStorageClass ||
2066 RD->hasAttr<DLLImportAttr>() || RD->hasAttr<DLLExportAttr>())
2067 return;
2068
2069 if (CGM.getVTables().isVTableExternal(RD)) {
2070 if (CXXRecordNonInlineHasAttr<DLLImportAttr>(RD))
2071 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2072 } else if (CXXRecordNonInlineHasAttr<DLLExportAttr>(RD))
2073 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2074 }
2075
2076 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
2077 const CXXRecordDecl *RD) {
2078 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
2079 if (VTable->hasInitializer())
2080 return;
2081
2082 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
2083 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
2084 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2085 llvm::Constant *RTTI =
2086 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getCanonicalTagType(RD));
2087
2088 // Create and set the initializer.
2089 ConstantInitBuilder builder(CGM);
2090 auto components = builder.beginStruct();
2091 CGVT.createVTableInitializer(components, VTLayout, RTTI,
2092 llvm::GlobalValue::isLocalLinkage(Linkage));
2093 components.finishAndSetAsInitializer(VTable);
2094
2095 // Set the correct linkage.
2096 VTable->setLinkage(Linkage);
2097
2098 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
2099 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
2100
2101 if (CGM.getTarget().hasPS4DLLImportExport())
2102 setVTableSelectiveDLLImportExport(CGM, VTable, RD);
2103
2104 // Set the right visibility.
2105 CGM.setGVProperties(VTable, RD);
2106
2107 // If this is the magic class __cxxabiv1::__fundamental_type_info,
2108 // we will emit the typeinfo for the fundamental types. This is the
2109 // same behaviour as GCC.
2110 const DeclContext *DC = RD->getDeclContext();
2111 if (RD->getIdentifier() &&
2112 RD->getIdentifier()->isStr("__fundamental_type_info") &&
2113 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
2114 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
2115 DC->getParent()->isTranslationUnit())
2116 EmitFundamentalRTTIDescriptors(RD);
2117
2118 // Always emit type metadata on non-available_externally definitions, and on
2119 // available_externally definitions if we are performing whole program
2120 // devirtualization or speculative devirtualization. We need the type metadata
2121 // on all vtable definitions to ensure we associate derived classes with base
2122 // classes defined in headers but with a strong definition only in a shared
2123 // library.
2124 if (!VTable->isDeclarationForLinker() ||
2125 CGM.getCodeGenOpts().WholeProgramVTables ||
2126 CGM.getCodeGenOpts().DevirtualizeSpeculatively) {
2127 CGM.EmitVTableTypeMetadata(RD, VTable, VTLayout);
2128 // For available_externally definitions, add the vtable to
2129 // @llvm.compiler.used so that it isn't deleted before whole program
2130 // analysis.
2131 if (VTable->isDeclarationForLinker()) {
2132 assert(CGM.getCodeGenOpts().WholeProgramVTables ||
2133 CGM.getCodeGenOpts().DevirtualizeSpeculatively);
2134 CGM.addCompilerUsedGlobal(VTable);
2135 }
2136 }
2137
2138 if (VTContext.isRelativeLayout()) {
2139 CGVT.RemoveHwasanMetadata(VTable);
2140 if (!VTable->isDSOLocal())
2141 CGVT.GenerateRelativeVTableAlias(VTable, VTable->getName());
2142 }
2143
2144 // Emit symbol for debugger only if requested debug info.
2145 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
2146 DI->emitVTableSymbol(VTable, RD);
2147 }
2148
2149 bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
2150 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
2151 if (Vptr.NearestVBase == nullptr)
2152 return false;
2153 return NeedsVTTParameter(CGF.CurGD);
2154 }
2155
2156 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
2157 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
2158 const CXXRecordDecl *NearestVBase) {
2159
2160 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
2161 NeedsVTTParameter(CGF.CurGD)) {
2162 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
2163 NearestVBase);
2164 }
2165 return getVTableAddressPoint(Base, VTableClass);
2166 }
2167
2168 llvm::Constant *
2169 ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
2170 const CXXRecordDecl *VTableClass) {
2171 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
2172
2173 // Find the appropriate vtable within the vtable group, and the address point
2174 // within that vtable.
2175 const VTableLayout &Layout =
2176 CGM.getItaniumVTableContext().getVTableLayout(VTableClass);
2177 VTableLayout::AddressPointLocation AddressPoint =
2178 Layout.getAddressPoint(Base);
2179 llvm::Value *Indices[] = {
2180 llvm::ConstantInt::get(CGM.Int32Ty, 0),
2181 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
2182 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
2183 };
2184
2185 // Add inrange attribute to indicate that only the VTableIndex can be
2186 // accessed.
2187 unsigned ComponentSize =
2188 CGM.getDataLayout().getTypeAllocSize(CGM.getVTableComponentType());
2189 unsigned VTableSize =
2190 ComponentSize * Layout.getVTableSize(AddressPoint.VTableIndex);
2191 unsigned Offset = ComponentSize * AddressPoint.AddressPointIndex;
2192 llvm::ConstantRange InRange(
2193 llvm::APInt(32, (int)-Offset, true),
2194 llvm::APInt(32, (int)(VTableSize - Offset), true));
2195 return llvm::ConstantExpr::getGetElementPtr(
2196 VTable->getValueType(), VTable, Indices, /*InBounds=*/true, InRange);
2197 }
2198
2199 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
2200 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
2201 const CXXRecordDecl *NearestVBase) {
2202 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
2203 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
2204
2205 // Get the secondary vpointer index.
2206 uint64_t VirtualPointerIndex =
2207 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
2208
2209 /// Load the VTT.
2210 llvm::Value *VTT = CGF.LoadCXXVTT();
2211 if (VirtualPointerIndex)
2212 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(CGF.GlobalsVoidPtrTy, VTT,
2213 VirtualPointerIndex);
2214
2215 // And load the address point from the VTT.
2216 llvm::Value *AP =
2217 CGF.Builder.CreateAlignedLoad(CGF.GlobalsVoidPtrTy, VTT,
2218 CGF.getPointerAlign());
2219
2220 if (auto &Schema = CGF.CGM.getCodeGenOpts().PointerAuth.CXXVTTVTablePointers) {
2221 CGPointerAuthInfo PointerAuth = CGF.EmitPointerAuthInfo(Schema, VTT,
2222 GlobalDecl(),
2223 QualType());
2224 AP = CGF.EmitPointerAuthAuth(PointerAuth, AP);
2225 }
2226
2227 return AP;
2228 }
2229
2230 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
2231 CharUnits VPtrOffset) {
2232 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
2233
2234 llvm::GlobalVariable *&VTable = VTables[RD];
2235 if (VTable)
2236 return VTable;
2237
2238 // Queue up this vtable for possible deferred emission.
2239 CGM.addDeferredVTable(RD);
2240
2241 SmallString<256> Name;
2242 llvm::raw_svector_ostream Out(Name);
2243 getMangleContext().mangleCXXVTable(RD, Out);
2244
2245 const VTableLayout &VTLayout =
2246 CGM.getItaniumVTableContext().getVTableLayout(RD);
2247 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
2248
2249 // Use pointer to global alignment for the vtable. Otherwise we would align
2250 // them based on the size of the initializer which doesn't make sense as only
2251 // single values are read.
2252 unsigned PAlign = CGM.getVtableGlobalVarAlignment();
2253
2254 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
2255 Name, VTableType, llvm::GlobalValue::ExternalLinkage,
2256 getContext().toCharUnitsFromBits(PAlign).getAsAlign());
2257 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2258
2259 if (CGM.getTarget().hasPS4DLLImportExport())
2260 setVTableSelectiveDLLImportExport(CGM, VTable, RD);
2261
2262 CGM.setGVProperties(VTable, RD);
2263 return VTable;
2264 }
2265
2266 CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
2267 GlobalDecl GD,
2268 Address This,
2269 llvm::Type *Ty,
2270 SourceLocation Loc) {
2271 llvm::Type *PtrTy = CGM.GlobalsInt8PtrTy;
2272 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
2273 llvm::Value *VTable = CGF.GetVTablePtr(This, PtrTy, MethodDecl->getParent());
2274
2275 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
2276 llvm::Value *VFunc, *VTableSlotPtr = nullptr;
2277 auto &Schema = CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers;
2278
2279 llvm::Type *ComponentTy = CGM.getVTables().getVTableComponentType();
2280 uint64_t ByteOffset =
2281 VTableIndex * CGM.getDataLayout().getTypeSizeInBits(ComponentTy) / 8;
2282
2283 if (!Schema && CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
2284 VFunc = CGF.EmitVTableTypeCheckedLoad(MethodDecl->getParent(), VTable,
2285 PtrTy, ByteOffset);
2286 } else {
2287 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
2288
2289 llvm::Value *VFuncLoad;
2290 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
2291 VFuncLoad = CGF.Builder.CreateCall(
2292 CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
2293 {VTable, llvm::ConstantInt::get(CGM.Int32Ty, ByteOffset)});
2294 } else {
2295 VTableSlotPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2296 PtrTy, VTable, VTableIndex, "vfn");
2297 VFuncLoad = CGF.Builder.CreateAlignedLoad(PtrTy, VTableSlotPtr,
2298 CGF.getPointerAlign());
2299 }
2300
2301 // Add !invariant.load md to virtual function load to indicate that
2302 // function didn't change inside vtable.
2303 // It's safe to add it without -fstrict-vtable-pointers, but it would not
2304 // help in devirtualization because it will only matter if we will have 2
2305 // the same virtual function loads from the same vtable load, which won't
2306 // happen without enabled devirtualization with -fstrict-vtable-pointers.
2307 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2308 CGM.getCodeGenOpts().StrictVTablePointers) {
2309 if (auto *VFuncLoadInstr = dyn_cast<llvm::Instruction>(VFuncLoad)) {
2310 VFuncLoadInstr->setMetadata(
2311 llvm::LLVMContext::MD_invariant_load,
2312 llvm::MDNode::get(CGM.getLLVMContext(),
2313 llvm::ArrayRef<llvm::Metadata *>()));
2314 }
2315 }
2316 VFunc = VFuncLoad;
2317 }
2318
2319 CGPointerAuthInfo PointerAuth;
2320 if (Schema) {
2321 assert(VTableSlotPtr && "virtual function pointer not set");
2322 GD = CGM.getItaniumVTableContext().findOriginalMethod(GD.getCanonicalDecl());
2323 PointerAuth = CGF.EmitPointerAuthInfo(Schema, VTableSlotPtr, GD, QualType());
2324 }
2325 CGCallee Callee(GD, VFunc, PointerAuth);
2326 return Callee;
2327 }
2328
2329 llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
2330 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
2331 Address This, DeleteOrMemberCallExpr E, llvm::CallBase **CallOrInvoke) {
2332 auto *CE = dyn_cast<const CXXMemberCallExpr *>(E);
2333 auto *D = dyn_cast<const CXXDeleteExpr *>(E);
2334 assert((CE != nullptr) ^ (D != nullptr));
2335 assert(CE == nullptr || CE->arguments().empty());
2336 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
2337
2338 GlobalDecl GD(Dtor, DtorType);
2339 const CGFunctionInfo *FInfo =
2340 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
2341 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
2342 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
2343
2344 QualType ThisTy;
2345 if (CE) {
2346 ThisTy = CE->getObjectType();
2347 } else {
2348 ThisTy = D->getDestroyedType();
2349 }
2350
2351 CGF.EmitCXXDestructorCall(GD, Callee, This.emitRawPointer(CGF), ThisTy,
2352 nullptr, QualType(), nullptr, CallOrInvoke);
2353 return nullptr;
2354 }
2355
2356 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2357 CodeGenVTables &VTables = CGM.getVTables();
2358 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
2359 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
2360 }
2361
2362 bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
2363 const CXXRecordDecl *RD) const {
2364 // We don't emit available_externally vtables if we are in -fapple-kext mode
2365 // because kext mode does not permit devirtualization.
2366 if (CGM.getLangOpts().AppleKext)
2367 return false;
2368
2369 // If the vtable is hidden then it is not safe to emit an available_externally
2370 // copy of vtable.
2371 if (isVTableHidden(RD))
2372 return false;
2373
2374 if (CGM.getCodeGenOpts().ForceEmitVTables)
2375 return true;
2376
2377 // A speculative vtable can only be generated if all virtual inline functions
2378 // defined by this class are emitted. The vtable in the final program contains
2379 // for each virtual inline function not used in the current TU a function that
2380 // is equivalent to the unused function. The function in the actual vtable
2381 // does not have to be declared under the same symbol (e.g., a virtual
2382 // destructor that can be substituted with its base class's destructor). Since
2383 // inline functions are emitted lazily and this emissions does not account for
2384 // speculative emission of a vtable, we might generate a speculative vtable
2385 // with references to inline functions that are not emitted under that name.
2386 // This can lead to problems when devirtualizing a call to such a function,
2387 // that result in linking errors. Hence, if there are any unused virtual
2388 // inline function, we cannot emit the speculative vtable.
2389 // FIXME we can still emit a copy of the vtable if we
2390 // can emit definition of the inline functions.
2391 if (hasAnyUnusedVirtualInlineFunction(RD))
2392 return false;
2393
2394 // For a class with virtual bases, we must also be able to speculatively
2395 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
2396 // the vtable" and "can emit the VTT". For a base subobject, this means we
2397 // need to be able to emit non-virtual base vtables.
2398 if (RD->getNumVBases()) {
2399 for (const auto &B : RD->bases()) {
2400 auto *BRD = B.getType()->getAsCXXRecordDecl();
2401 assert(BRD && "no class for base specifier");
2402 if (B.isVirtual() || !BRD->isDynamicClass())
2403 continue;
2404 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
2405 return false;
2406 }
2407 }
2408
2409 return true;
2410 }
2411
2412 bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
2413 if (!canSpeculativelyEmitVTableAsBaseClass(RD))
2414 return false;
2415
2416 if (RD->shouldEmitInExternalSource())
2417 return false;
2418
2419 // For a complete-object vtable (or more specifically, for the VTT), we need
2420 // to be able to speculatively emit the vtables of all dynamic virtual bases.
2421 for (const auto &B : RD->vbases()) {
2422 auto *BRD = B.getType()->getAsCXXRecordDecl();
2423 assert(BRD && "no class for base specifier");
2424 if (!BRD->isDynamicClass())
2425 continue;
2426 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
2427 return false;
2428 }
2429
2430 return true;
2431 }
2432 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
2433 Address InitialPtr,
2434 const CXXRecordDecl *UnadjustedClass,
2435 int64_t NonVirtualAdjustment,
2436 int64_t VirtualAdjustment,
2437 bool IsReturnAdjustment) {
2438 if (!NonVirtualAdjustment && !VirtualAdjustment)
2439 return InitialPtr.emitRawPointer(CGF);
2440
2441 Address V = InitialPtr.withElementType(CGF.Int8Ty);
2442
2443 // In a base-to-derived cast, the non-virtual adjustment is applied first.
2444 if (NonVirtualAdjustment && !IsReturnAdjustment) {
2445 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
2446 CharUnits::fromQuantity(NonVirtualAdjustment));
2447 }
2448
2449 // Perform the virtual adjustment if we have one.
2450 llvm::Value *ResultPtr;
2451 if (VirtualAdjustment) {
2452 llvm::Value *VTablePtr =
2453 CGF.GetVTablePtr(V, CGF.Int8PtrTy, UnadjustedClass);
2454
2455 llvm::Value *Offset;
2456 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2457 CGF.Int8Ty, VTablePtr, VirtualAdjustment);
2458 if (CGF.CGM.getItaniumVTableContext().isRelativeLayout()) {
2459 // Load the adjustment offset from the vtable as a 32-bit int.
2460 Offset =
2461 CGF.Builder.CreateAlignedLoad(CGF.Int32Ty, OffsetPtr,
2462 CharUnits::fromQuantity(4));
2463 } else {
2464 llvm::Type *PtrDiffTy =
2465 CGF.ConvertType(CGF.getContext().getPointerDiffType());
2466
2467 // Load the adjustment offset from the vtable.
2468 Offset = CGF.Builder.CreateAlignedLoad(PtrDiffTy, OffsetPtr,
2469 CGF.getPointerAlign());
2470 }
2471 // Adjust our pointer.
2472 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getElementType(),
2473 V.emitRawPointer(CGF), Offset);
2474 } else {
2475 ResultPtr = V.emitRawPointer(CGF);
2476 }
2477
2478 // In a derived-to-base conversion, the non-virtual adjustment is
2479 // applied second.
2480 if (NonVirtualAdjustment && IsReturnAdjustment) {
2481 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(CGF.Int8Ty, ResultPtr,
2482 NonVirtualAdjustment);
2483 }
2484
2485 return ResultPtr;
2486 }
2487
2488 llvm::Value *
2489 ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, Address This,
2490 const CXXRecordDecl *UnadjustedClass,
2491 const ThunkInfo &TI) {
2492 return performTypeAdjustment(CGF, This, UnadjustedClass, TI.This.NonVirtual,
2493 TI.This.Virtual.Itanium.VCallOffsetOffset,
2494 /*IsReturnAdjustment=*/false);
2495 }
2496
2497 llvm::Value *
2498 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2499 const CXXRecordDecl *UnadjustedClass,
2500 const ReturnAdjustment &RA) {
2501 return performTypeAdjustment(CGF, Ret, UnadjustedClass, RA.NonVirtual,
2502 RA.Virtual.Itanium.VBaseOffsetOffset,
2503 /*IsReturnAdjustment=*/true);
2504 }
2505
2506 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
2507 RValue RV, QualType ResultType) {
2508 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
2509 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
2510
2511 // Destructor thunks in the ARM ABI have indeterminate results.
2512 llvm::Type *T = CGF.ReturnValue.getElementType();
2513 RValue Undef = RValue::get(llvm::UndefValue::get(T));
2514 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
2515 }
2516
2517 /************************** Array allocation cookies **************************/
2518
2519 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2520 // The array cookie is a size_t; pad that up to the element alignment.
2521 // The cookie is actually right-justified in that space.
2522 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
2523 CGM.getContext().getPreferredTypeAlignInChars(elementType));
2524 }
2525
2526 Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2527 Address NewPtr,
2528 llvm::Value *NumElements,
2529 const CXXNewExpr *expr,
2530 QualType ElementType) {
2531 assert(requiresArrayCookie(expr));
2532
2533 unsigned AS = NewPtr.getAddressSpace();
2534
2535 ASTContext &Ctx = getContext();
2536 CharUnits SizeSize = CGF.getSizeSize();
2537
2538 // The size of the cookie.
2539 CharUnits CookieSize =
2540 std::max(SizeSize, Ctx.getPreferredTypeAlignInChars(ElementType));
2541 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
2542
2543 // Compute an offset to the cookie.
2544 Address CookiePtr = NewPtr;
2545 CharUnits CookieOffset = CookieSize - SizeSize;
2546 if (!CookieOffset.isZero())
2547 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
2548
2549 // Write the number of elements into the appropriate slot.
2550 Address NumElementsPtr = CookiePtr.withElementType(CGF.SizeTy);
2551 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
2552
2553 // Handle the array cookie specially in ASan.
2554 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
2555 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
2556 CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
2557 // The store to the CookiePtr does not need to be instrumented.
2558 SI->setNoSanitizeMetadata();
2559 llvm::FunctionType *FTy =
2560 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
2561 llvm::FunctionCallee F =
2562 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
2563 CGF.Builder.CreateCall(F, NumElementsPtr.emitRawPointer(CGF));
2564 }
2565
2566 // Finally, compute a pointer to the actual data buffer by skipping
2567 // over the cookie completely.
2568 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
2569 }
2570
2571 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2572 Address allocPtr,
2573 CharUnits cookieSize) {
2574 // The element size is right-justified in the cookie.
2575 Address numElementsPtr = allocPtr;
2576 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
2577 if (!numElementsOffset.isZero())
2578 numElementsPtr =
2579 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
2580
2581 unsigned AS = allocPtr.getAddressSpace();
2582 numElementsPtr = numElementsPtr.withElementType(CGF.SizeTy);
2583 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
2584 return CGF.Builder.CreateLoad(numElementsPtr);
2585 // In asan mode emit a function call instead of a regular load and let the
2586 // run-time deal with it: if the shadow is properly poisoned return the
2587 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
2588 // We can't simply ignore this load using nosanitize metadata because
2589 // the metadata may be lost.
2590 llvm::FunctionType *FTy =
2591 llvm::FunctionType::get(CGF.SizeTy, CGF.DefaultPtrTy, false);
2592 llvm::FunctionCallee F =
2593 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
2594 return CGF.Builder.CreateCall(F, numElementsPtr.emitRawPointer(CGF));
2595 }
2596
2597 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2598 // ARM says that the cookie is always:
2599 // struct array_cookie {
2600 // std::size_t element_size; // element_size != 0
2601 // std::size_t element_count;
2602 // };
2603 // But the base ABI doesn't give anything an alignment greater than
2604 // 8, so we can dismiss this as typical ABI-author blindness to
2605 // actual language complexity and round up to the element alignment.
2606 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
2607 CGM.getContext().getTypeAlignInChars(elementType));
2608 }
2609
2610 Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2611 Address newPtr,
2612 llvm::Value *numElements,
2613 const CXXNewExpr *expr,
2614 QualType elementType) {
2615 assert(requiresArrayCookie(expr));
2616
2617 // The cookie is always at the start of the buffer.
2618 Address cookie = newPtr;
2619
2620 // The first element is the element size.
2621 cookie = cookie.withElementType(CGF.SizeTy);
2622 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2623 getContext().getTypeSizeInChars(elementType).getQuantity());
2624 CGF.Builder.CreateStore(elementSize, cookie);
2625
2626 // The second element is the element count.
2627 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
2628 CGF.Builder.CreateStore(numElements, cookie);
2629
2630 // Finally, compute a pointer to the actual data buffer by skipping
2631 // over the cookie completely.
2632 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
2633 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2634 }
2635
2636 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2637 Address allocPtr,
2638 CharUnits cookieSize) {
2639 // The number of elements is at offset sizeof(size_t) relative to
2640 // the allocated pointer.
2641 Address numElementsPtr
2642 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
2643
2644 numElementsPtr = numElementsPtr.withElementType(CGF.SizeTy);
2645 return CGF.Builder.CreateLoad(numElementsPtr);
2646 }
2647
2648 /*********************** Static local initialization **************************/
2649
2650 static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2651 llvm::PointerType *GuardPtrTy) {
2652 // int __cxa_guard_acquire(__guard *guard_object);
2653 llvm::FunctionType *FTy =
2654 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
2655 GuardPtrTy, /*isVarArg=*/false);
2656 return CGM.CreateRuntimeFunction(
2657 FTy, "__cxa_guard_acquire",
2658 llvm::AttributeList::get(CGM.getLLVMContext(),
2659 llvm::AttributeList::FunctionIndex,
2660 llvm::Attribute::NoUnwind));
2661 }
2662
2663 static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2664 llvm::PointerType *GuardPtrTy) {
2665 // void __cxa_guard_release(__guard *guard_object);
2666 llvm::FunctionType *FTy =
2667 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2668 return CGM.CreateRuntimeFunction(
2669 FTy, "__cxa_guard_release",
2670 llvm::AttributeList::get(CGM.getLLVMContext(),
2671 llvm::AttributeList::FunctionIndex,
2672 llvm::Attribute::NoUnwind));
2673 }
2674
2675 static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2676 llvm::PointerType *GuardPtrTy) {
2677 // void __cxa_guard_abort(__guard *guard_object);
2678 llvm::FunctionType *FTy =
2679 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2680 return CGM.CreateRuntimeFunction(
2681 FTy, "__cxa_guard_abort",
2682 llvm::AttributeList::get(CGM.getLLVMContext(),
2683 llvm::AttributeList::FunctionIndex,
2684 llvm::Attribute::NoUnwind));
2685 }
2686
2687 namespace {
2688 struct CallGuardAbort final : EHScopeStack::Cleanup {
2689 llvm::GlobalVariable *Guard;
2690 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
2691
2692 void Emit(CodeGenFunction &CGF, Flags flags) override {
2693 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2694 Guard);
2695 }
2696 };
2697 }
2698
2699 /// The ARM code here follows the Itanium code closely enough that we
2700 /// just special-case it at particular places.
2701 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2702 const VarDecl &D,
2703 llvm::GlobalVariable *var,
2704 bool shouldPerformInit) {
2705 CGBuilderTy &Builder = CGF.Builder;
2706
2707 // Inline variables that weren't instantiated from variable templates have
2708 // partially-ordered initialization within their translation unit.
2709 bool NonTemplateInline =
2710 D.isInline() &&
2711 !isTemplateInstantiation(D.getTemplateSpecializationKind());
2712
2713 // We only need to use thread-safe statics for local non-TLS variables and
2714 // inline variables; other global initialization is always single-threaded
2715 // or (through lazy dynamic loading in multiple threads) unsequenced.
2716 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
2717 (D.isLocalVarDecl() || NonTemplateInline) &&
2718 !D.getTLSKind();
2719
2720 // If we have a global variable with internal linkage and thread-safe statics
2721 // are disabled, we can just let the guard variable be of type i8.
2722 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2723
2724 llvm::IntegerType *guardTy;
2725 CharUnits guardAlignment;
2726 if (useInt8GuardVariable) {
2727 guardTy = CGF.Int8Ty;
2728 guardAlignment = CharUnits::One();
2729 } else {
2730 // Guard variables are 64 bits in the generic ABI and size width on ARM
2731 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
2732 if (UseARMGuardVarABI) {
2733 guardTy = CGF.SizeTy;
2734 guardAlignment = CGF.getSizeAlign();
2735 } else {
2736 guardTy = CGF.Int64Ty;
2737 guardAlignment =
2738 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlign(guardTy));
2739 }
2740 }
2741 llvm::PointerType *guardPtrTy = llvm::PointerType::get(
2742 CGF.CGM.getLLVMContext(),
2743 CGF.CGM.getDataLayout().getDefaultGlobalsAddressSpace());
2744
2745 // Create the guard variable if we don't already have it (as we
2746 // might if we're double-emitting this function body).
2747 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2748 if (!guard) {
2749 // Mangle the name for the guard.
2750 SmallString<256> guardName;
2751 {
2752 llvm::raw_svector_ostream out(guardName);
2753 getMangleContext().mangleStaticGuardVariable(&D, out);
2754 }
2755
2756 // Create the guard variable with a zero-initializer.
2757 // Just absorb linkage, visibility and dll storage class from the guarded
2758 // variable.
2759 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2760 false, var->getLinkage(),
2761 llvm::ConstantInt::get(guardTy, 0),
2762 guardName.str());
2763 guard->setDSOLocal(var->isDSOLocal());
2764 guard->setVisibility(var->getVisibility());
2765 guard->setDLLStorageClass(var->getDLLStorageClass());
2766 // If the variable is thread-local, so is its guard variable.
2767 guard->setThreadLocalMode(var->getThreadLocalMode());
2768 guard->setAlignment(guardAlignment.getAsAlign());
2769
2770 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2771 // group as the associated data object." In practice, this doesn't work for
2772 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
2773 llvm::Comdat *C = var->getComdat();
2774 if (!D.isLocalVarDecl() && C &&
2775 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2776 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
2777 guard->setComdat(C);
2778 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2779 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
2780 }
2781
2782 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2783 }
2784
2785 Address guardAddr = Address(guard, guard->getValueType(), guardAlignment);
2786
2787 // Test whether the variable has completed initialization.
2788 //
2789 // Itanium C++ ABI 3.3.2:
2790 // The following is pseudo-code showing how these functions can be used:
2791 // if (obj_guard.first_byte == 0) {
2792 // if ( __cxa_guard_acquire (&obj_guard) ) {
2793 // try {
2794 // ... initialize the object ...;
2795 // } catch (...) {
2796 // __cxa_guard_abort (&obj_guard);
2797 // throw;
2798 // }
2799 // ... queue object destructor with __cxa_atexit() ...;
2800 // __cxa_guard_release (&obj_guard);
2801 // }
2802 // }
2803 //
2804 // If threadsafe statics are enabled, but we don't have inline atomics, just
2805 // call __cxa_guard_acquire unconditionally. The "inline" check isn't
2806 // actually inline, and the user might not expect calls to __atomic libcalls.
2807
2808 unsigned MaxInlineWidthInBits = CGF.getTarget().getMaxAtomicInlineWidth();
2809 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2810 if (!threadsafe || MaxInlineWidthInBits) {
2811 // Load the first byte of the guard variable.
2812 llvm::LoadInst *LI =
2813 Builder.CreateLoad(guardAddr.withElementType(CGM.Int8Ty));
2814
2815 // Itanium ABI:
2816 // An implementation supporting thread-safety on multiprocessor
2817 // systems must also guarantee that references to the initialized
2818 // object do not occur before the load of the initialization flag.
2819 //
2820 // In LLVM, we do this by marking the load Acquire.
2821 if (threadsafe)
2822 LI->setAtomic(llvm::AtomicOrdering::Acquire);
2823
2824 // For ARM, we should only check the first bit, rather than the entire byte:
2825 //
2826 // ARM C++ ABI 3.2.3.1:
2827 // To support the potential use of initialization guard variables
2828 // as semaphores that are the target of ARM SWP and LDREX/STREX
2829 // synchronizing instructions we define a static initialization
2830 // guard variable to be a 4-byte aligned, 4-byte word with the
2831 // following inline access protocol.
2832 // #define INITIALIZED 1
2833 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2834 // if (__cxa_guard_acquire(&obj_guard))
2835 // ...
2836 // }
2837 //
2838 // and similarly for ARM64:
2839 //
2840 // ARM64 C++ ABI 3.2.2:
2841 // This ABI instead only specifies the value bit 0 of the static guard
2842 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2843 // variable is not initialized and 1 when it is.
2844 llvm::Value *V =
2845 (UseARMGuardVarABI && !useInt8GuardVariable)
2846 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2847 : LI;
2848 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
2849
2850 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2851
2852 // Check if the first byte of the guard variable is zero.
2853 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2854 CodeGenFunction::GuardKind::VariableGuard, &D);
2855
2856 CGF.EmitBlock(InitCheckBlock);
2857 }
2858
2859 // The semantics of dynamic initialization of variables with static or thread
2860 // storage duration depends on whether they are declared at block-scope. The
2861 // initialization of such variables at block-scope can be aborted with an
2862 // exception and later retried (per C++20 [stmt.dcl]p4), and recursive entry
2863 // to their initialization has undefined behavior (also per C++20
2864 // [stmt.dcl]p4). For such variables declared at non-block scope, exceptions
2865 // lead to termination (per C++20 [except.terminate]p1), and recursive
2866 // references to the variables are governed only by the lifetime rules (per
2867 // C++20 [class.cdtor]p2), which means such references are perfectly fine as
2868 // long as they avoid touching memory. As a result, block-scope variables must
2869 // not be marked as initialized until after initialization completes (unless
2870 // the mark is reverted following an exception), but non-block-scope variables
2871 // must be marked prior to initialization so that recursive accesses during
2872 // initialization do not restart initialization.
2873
2874 // Variables used when coping with thread-safe statics and exceptions.
2875 if (threadsafe) {
2876 // Call __cxa_guard_acquire.
2877 llvm::Value *V
2878 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
2879
2880 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2881
2882 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2883 InitBlock, EndBlock);
2884
2885 // Call __cxa_guard_abort along the exceptional edge.
2886 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
2887
2888 CGF.EmitBlock(InitBlock);
2889 } else if (!D.isLocalVarDecl()) {
2890 // For non-local variables, store 1 into the first byte of the guard
2891 // variable before the object initialization begins so that references
2892 // to the variable during initialization don't restart initialization.
2893 Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
2894 guardAddr.withElementType(CGM.Int8Ty));
2895 }
2896
2897 // Emit the initializer and add a global destructor if appropriate.
2898 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
2899
2900 if (threadsafe) {
2901 // Pop the guard-abort cleanup if we pushed one.
2902 CGF.PopCleanupBlock();
2903
2904 // Call __cxa_guard_release. This cannot throw.
2905 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2906 guardAddr.emitRawPointer(CGF));
2907 } else if (D.isLocalVarDecl()) {
2908 // For local variables, store 1 into the first byte of the guard variable
2909 // after the object initialization completes so that initialization is
2910 // retried if initialization is interrupted by an exception.
2911 Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
2912 guardAddr.withElementType(CGM.Int8Ty));
2913 }
2914
2915 CGF.EmitBlock(EndBlock);
2916 }
2917
2918 /// Register a global destructor using __cxa_atexit.
2919 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2920 llvm::FunctionCallee dtor,
2921 llvm::Constant *addr, bool TLS) {
2922 assert(!CGF.getTarget().getTriple().isOSAIX() &&
2923 "unexpected call to emitGlobalDtorWithCXAAtExit");
2924 assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2925 "__cxa_atexit is disabled");
2926 const char *Name = "__cxa_atexit";
2927 if (TLS) {
2928 const llvm::Triple &T = CGF.getTarget().getTriple();
2929 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
2930 }
2931
2932 // We're assuming that the destructor function is something we can
2933 // reasonably call with the default CC.
2934 llvm::Type *dtorTy = CGF.DefaultPtrTy;
2935
2936 // Preserve address space of addr.
2937 auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
2938 auto AddrPtrTy = AddrAS ? llvm::PointerType::get(CGF.getLLVMContext(), AddrAS)
2939 : CGF.Int8PtrTy;
2940
2941 // Create a variable that binds the atexit to this shared object.
2942 llvm::Constant *handle =
2943 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2944 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2945 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2946
2947 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2948 llvm::Type *paramTys[] = {dtorTy, AddrPtrTy, handle->getType()};
2949 llvm::FunctionType *atexitTy =
2950 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2951
2952 // Fetch the actual function.
2953 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2954 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
2955 fn->setDoesNotThrow();
2956
2957 const auto &Context = CGF.CGM.getContext();
2958 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2959 /*IsVariadic=*/false, /*IsCXXMethod=*/false));
2960 QualType fnType =
2961 Context.getFunctionType(Context.VoidTy, {Context.VoidPtrTy}, EPI);
2962 llvm::Constant *dtorCallee = cast<llvm::Constant>(dtor.getCallee());
2963 dtorCallee = CGF.CGM.getFunctionPointer(dtorCallee, fnType);
2964
2965 if (!addr)
2966 // addr is null when we are trying to register a dtor annotated with
2967 // __attribute__((destructor)) in a constructor function. Using null here is
2968 // okay because this argument is just passed back to the destructor
2969 // function.
2970 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2971
2972 llvm::Value *args[] = {dtorCallee, addr, handle};
2973 CGF.EmitNounwindRuntimeCall(atexit, args);
2974 }
2975
2976 static llvm::Function *createGlobalInitOrCleanupFn(CodeGen::CodeGenModule &CGM,
2977 StringRef FnName) {
2978 // Create a function that registers/unregisters destructors that have the same
2979 // priority.
2980 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
2981 llvm::Function *GlobalInitOrCleanupFn = CGM.CreateGlobalInitOrCleanUpFunction(
2982 FTy, FnName, CGM.getTypes().arrangeNullaryFunction(), SourceLocation());
2983
2984 return GlobalInitOrCleanupFn;
2985 }
2986
2987 void CodeGenModule::unregisterGlobalDtorsWithUnAtExit() {
2988 for (const auto &I : DtorsUsingAtExit) {
2989 int Priority = I.first;
2990 std::string GlobalCleanupFnName =
2991 std::string("__GLOBAL_cleanup_") + llvm::to_string(Priority);
2992
2993 llvm::Function *GlobalCleanupFn =
2994 createGlobalInitOrCleanupFn(*this, GlobalCleanupFnName);
2995
2996 CodeGenFunction CGF(*this);
2997 CGF.StartFunction(GlobalDecl(), getContext().VoidTy, GlobalCleanupFn,
2998 getTypes().arrangeNullaryFunction(), FunctionArgList(),
2999 SourceLocation(), SourceLocation());
3000 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
3001
3002 // Get the destructor function type, void(*)(void).
3003 llvm::FunctionType *dtorFuncTy = llvm::FunctionType::get(CGF.VoidTy, false);
3004
3005 // Destructor functions are run/unregistered in non-ascending
3006 // order of their priorities.
3007 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
3008 auto itv = Dtors.rbegin();
3009 while (itv != Dtors.rend()) {
3010 llvm::Function *Dtor = *itv;
3011
3012 // We're assuming that the destructor function is something we can
3013 // reasonably call with the correct CC.
3014 llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(Dtor);
3015 llvm::Value *NeedsDestruct =
3016 CGF.Builder.CreateIsNull(V, "needs_destruct");
3017
3018 llvm::BasicBlock *DestructCallBlock =
3019 CGF.createBasicBlock("destruct.call");
3020 llvm::BasicBlock *EndBlock = CGF.createBasicBlock(
3021 (itv + 1) != Dtors.rend() ? "unatexit.call" : "destruct.end");
3022 // Check if unatexit returns a value of 0. If it does, jump to
3023 // DestructCallBlock, otherwise jump to EndBlock directly.
3024 CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
3025
3026 CGF.EmitBlock(DestructCallBlock);
3027
3028 // Emit the call to casted Dtor.
3029 llvm::CallInst *CI = CGF.Builder.CreateCall(dtorFuncTy, Dtor);
3030 // Make sure the call and the callee agree on calling convention.
3031 CI->setCallingConv(Dtor->getCallingConv());
3032
3033 CGF.EmitBlock(EndBlock);
3034
3035 itv++;
3036 }
3037
3038 CGF.FinishFunction();
3039 AddGlobalDtor(GlobalCleanupFn, Priority);
3040 }
3041 }
3042
3043 void CodeGenModule::registerGlobalDtorsWithAtExit() {
3044 for (const auto &I : DtorsUsingAtExit) {
3045 int Priority = I.first;
3046 std::string GlobalInitFnName =
3047 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
3048 llvm::Function *GlobalInitFn =
3049 createGlobalInitOrCleanupFn(*this, GlobalInitFnName);
3050
3051 CodeGenFunction CGF(*this);
3052 CGF.StartFunction(GlobalDecl(), getContext().VoidTy, GlobalInitFn,
3053 getTypes().arrangeNullaryFunction(), FunctionArgList(),
3054 SourceLocation(), SourceLocation());
3055 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
3056
3057 // Since constructor functions are run in non-descending order of their
3058 // priorities, destructors are registered in non-descending order of their
3059 // priorities, and since destructor functions are run in the reverse order
3060 // of their registration, destructor functions are run in non-ascending
3061 // order of their priorities.
3062 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
3063 for (auto *Dtor : Dtors) {
3064 // Register the destructor function calling __cxa_atexit if it is
3065 // available. Otherwise fall back on calling atexit.
3066 if (getCodeGenOpts().CXAAtExit) {
3067 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
3068 } else {
3069 // We're assuming that the destructor function is something we can
3070 // reasonably call with the correct CC.
3071 CGF.registerGlobalDtorWithAtExit(Dtor);
3072 }
3073 }
3074
3075 CGF.FinishFunction();
3076 AddGlobalCtor(GlobalInitFn, Priority);
3077 }
3078
3079 if (getCXXABI().useSinitAndSterm())
3080 unregisterGlobalDtorsWithUnAtExit();
3081 }
3082
3083 /// Register a global destructor as best as we know how.
3084 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
3085 llvm::FunctionCallee dtor,
3086 llvm::Constant *addr) {
3087 if (D.isNoDestroy(CGM.getContext()))
3088 return;
3089
3090 // HLSL doesn't support atexit.
3091 if (CGM.getLangOpts().HLSL)
3092 return CGM.AddCXXDtorEntry(dtor, addr);
3093
3094 // OpenMP offloading supports C++ constructors and destructors but we do not
3095 // always have 'atexit' available. Instead lower these to use the LLVM global
3096 // destructors which we can handle directly in the runtime. Note that this is
3097 // not strictly 1-to-1 with using `atexit` because we no longer tear down
3098 // globals in reverse order of when they were constructed.
3099 if (!CGM.getLangOpts().hasAtExit() && !D.isStaticLocal())
3100 return CGF.registerGlobalDtorWithLLVM(D, dtor, addr);
3101
3102 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
3103 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
3104 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
3105 // We can always use __cxa_thread_atexit.
3106 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
3107 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
3108
3109 // In Apple kexts, we want to add a global destructor entry.
3110 // FIXME: shouldn't this be guarded by some variable?
3111 if (CGM.getLangOpts().AppleKext) {
3112 // Generate a global destructor entry.
3113 return CGM.AddCXXDtorEntry(dtor, addr);
3114 }
3115
3116 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
3117 }
3118
3119 static bool isThreadWrapperReplaceable(const VarDecl *VD,
3120 CodeGen::CodeGenModule &CGM) {
3121 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
3122 // Darwin prefers to have references to thread local variables to go through
3123 // the thread wrapper instead of directly referencing the backing variable.
3124 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3125 CGM.getTarget().getTriple().isOSDarwin();
3126 }
3127
3128 /// Get the appropriate linkage for the wrapper function. This is essentially
3129 /// the weak form of the variable's linkage; every translation unit which needs
3130 /// the wrapper emits a copy, and we want the linker to merge them.
3131 static llvm::GlobalValue::LinkageTypes
3132 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
3133 llvm::GlobalValue::LinkageTypes VarLinkage =
3134 CGM.getLLVMLinkageVarDefinition(VD);
3135
3136 // For internal linkage variables, we don't need an external or weak wrapper.
3137 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
3138 return VarLinkage;
3139
3140 // If the thread wrapper is replaceable, give it appropriate linkage.
3141 if (isThreadWrapperReplaceable(VD, CGM))
3142 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
3143 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
3144 return VarLinkage;
3145 return llvm::GlobalValue::WeakODRLinkage;
3146 }
3147
3148 llvm::Function *
3149 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
3150 llvm::Value *Val) {
3151 // Mangle the name for the thread_local wrapper function.
3152 SmallString<256> WrapperName;
3153 {
3154 llvm::raw_svector_ostream Out(WrapperName);
3155 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
3156 }
3157
3158 // FIXME: If VD is a definition, we should regenerate the function attributes
3159 // before returning.
3160 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
3161 return cast<llvm::Function>(V);
3162
3163 QualType RetQT = VD->getType();
3164 if (RetQT->isReferenceType())
3165 RetQT = RetQT.getNonReferenceType();
3166
3167 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
3168 getContext().getPointerType(RetQT), FunctionArgList());
3169
3170 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
3171 llvm::Function *Wrapper =
3172 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
3173 WrapperName.str(), &CGM.getModule());
3174
3175 if (CGM.supportsCOMDAT() && Wrapper->isWeakForLinker())
3176 Wrapper->setComdat(CGM.getModule().getOrInsertComdat(Wrapper->getName()));
3177
3178 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper, /*IsThunk=*/false);
3179
3180 // Always resolve references to the wrapper at link time.
3181 if (!Wrapper->hasLocalLinkage())
3182 if (!isThreadWrapperReplaceable(VD, CGM) ||
3183 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
3184 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
3185 VD->getVisibility() == HiddenVisibility)
3186 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
3187
3188 if (isThreadWrapperReplaceable(VD, CGM)) {
3189 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3190 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
3191 }
3192
3193 ThreadWrappers.push_back({VD, Wrapper});
3194 return Wrapper;
3195 }
3196
3197 void ItaniumCXXABI::EmitThreadLocalInitFuncs(
3198 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
3199 ArrayRef<llvm::Function *> CXXThreadLocalInits,
3200 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
3201 llvm::Function *InitFunc = nullptr;
3202
3203 // Separate initializers into those with ordered (or partially-ordered)
3204 // initialization and those with unordered initialization.
3205 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
3206 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
3207 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
3208 if (isTemplateInstantiation(
3209 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
3210 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
3211 CXXThreadLocalInits[I];
3212 else
3213 OrderedInits.push_back(CXXThreadLocalInits[I]);
3214 }
3215
3216 if (!OrderedInits.empty()) {
3217 // Generate a guarded initialization function.
3218 llvm::FunctionType *FTy =
3219 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
3220 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3221 InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(FTy, "__tls_init", FI,
3222 SourceLocation(),
3223 /*TLS=*/true);
3224 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
3225 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
3226 llvm::GlobalVariable::InternalLinkage,
3227 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
3228 Guard->setThreadLocal(true);
3229 Guard->setThreadLocalMode(CGM.GetDefaultLLVMTLSModel());
3230
3231 CharUnits GuardAlign = CharUnits::One();
3232 Guard->setAlignment(GuardAlign.getAsAlign());
3233
3234 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
3235 InitFunc, OrderedInits, ConstantAddress(Guard, CGM.Int8Ty, GuardAlign));
3236 // On Darwin platforms, use CXX_FAST_TLS calling convention.
3237 if (CGM.getTarget().getTriple().isOSDarwin()) {
3238 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3239 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
3240 }
3241 }
3242
3243 // Create declarations for thread wrappers for all thread-local variables
3244 // with non-discardable definitions in this translation unit.
3245 for (const VarDecl *VD : CXXThreadLocals) {
3246 if (VD->hasDefinition() &&
3247 !isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))) {
3248 llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
3249 getOrCreateThreadLocalWrapper(VD, GV);
3250 }
3251 }
3252
3253 // Emit all referenced thread wrappers.
3254 for (auto VDAndWrapper : ThreadWrappers) {
3255 const VarDecl *VD = VDAndWrapper.first;
3256 llvm::GlobalVariable *Var =
3257 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
3258 llvm::Function *Wrapper = VDAndWrapper.second;
3259
3260 // Some targets require that all access to thread local variables go through
3261 // the thread wrapper. This means that we cannot attempt to create a thread
3262 // wrapper or a thread helper.
3263 if (!VD->hasDefinition()) {
3264 if (isThreadWrapperReplaceable(VD, CGM)) {
3265 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
3266 continue;
3267 }
3268
3269 // If this isn't a TU in which this variable is defined, the thread
3270 // wrapper is discardable.
3271 if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
3272 Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
3273 }
3274
3275 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
3276
3277 // Mangle the name for the thread_local initialization function.
3278 SmallString<256> InitFnName;
3279 {
3280 llvm::raw_svector_ostream Out(InitFnName);
3281 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
3282 }
3283
3284 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
3285
3286 // If we have a definition for the variable, emit the initialization
3287 // function as an alias to the global Init function (if any). Otherwise,
3288 // produce a declaration of the initialization function.
3289 llvm::GlobalValue *Init = nullptr;
3290 bool InitIsInitFunc = false;
3291 bool HasConstantInitialization = false;
3292 if (!usesThreadWrapperFunction(VD)) {
3293 HasConstantInitialization = true;
3294 } else if (VD->hasDefinition()) {
3295 InitIsInitFunc = true;
3296 llvm::Function *InitFuncToUse = InitFunc;
3297 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
3298 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
3299 if (InitFuncToUse)
3300 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
3301 InitFuncToUse);
3302 } else {
3303 // Emit a weak global function referring to the initialization function.
3304 // This function will not exist if the TU defining the thread_local
3305 // variable in question does not need any dynamic initialization for
3306 // its thread_local variables.
3307 Init = llvm::Function::Create(InitFnTy,
3308 llvm::GlobalVariable::ExternalWeakLinkage,
3309 InitFnName.str(), &CGM.getModule());
3310 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3311 CGM.SetLLVMFunctionAttributes(
3312 GlobalDecl(), FI, cast<llvm::Function>(Init), /*IsThunk=*/false);
3313 }
3314
3315 if (Init) {
3316 Init->setVisibility(Var->getVisibility());
3317 // Don't mark an extern_weak function DSO local on windows.
3318 if (!CGM.getTriple().isOSWindows() || !Init->hasExternalWeakLinkage())
3319 Init->setDSOLocal(Var->isDSOLocal());
3320 }
3321
3322 llvm::LLVMContext &Context = CGM.getModule().getContext();
3323
3324 // The linker on AIX is not happy with missing weak symbols. However,
3325 // other TUs will not know whether the initialization routine exists
3326 // so create an empty, init function to satisfy the linker.
3327 // This is needed whenever a thread wrapper function is not used, and
3328 // also when the symbol is weak.
3329 if (CGM.getTriple().isOSAIX() && VD->hasDefinition() &&
3330 isEmittedWithConstantInitializer(VD, true) &&
3331 !mayNeedDestruction(VD)) {
3332 // Init should be null. If it were non-null, then the logic above would
3333 // either be defining the function to be an alias or declaring the
3334 // function with the expectation that the definition of the variable
3335 // is elsewhere.
3336 assert(Init == nullptr && "Expected Init to be null.");
3337
3338 llvm::Function *Func = llvm::Function::Create(
3339 InitFnTy, Var->getLinkage(), InitFnName.str(), &CGM.getModule());
3340 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3341 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
3342 cast<llvm::Function>(Func),
3343 /*IsThunk=*/false);
3344 // Create a function body that just returns
3345 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Func);
3346 CGBuilderTy Builder(CGM, Entry);
3347 Builder.CreateRetVoid();
3348 }
3349
3350 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
3351 CGBuilderTy Builder(CGM, Entry);
3352 if (HasConstantInitialization) {
3353 // No dynamic initialization to invoke.
3354 } else if (InitIsInitFunc) {
3355 if (Init) {
3356 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
3357 if (isThreadWrapperReplaceable(VD, CGM)) {
3358 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3359 llvm::Function *Fn =
3360 cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
3361 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3362 }
3363 }
3364 } else if (CGM.getTriple().isOSAIX()) {
3365 // On AIX, except if constinit and also neither of class type or of
3366 // (possibly multi-dimensional) array of class type, thread_local vars
3367 // will have init routines regardless of whether they are
3368 // const-initialized. Since the routine is guaranteed to exist, we can
3369 // unconditionally call it without testing for its existance. This
3370 // avoids potentially unresolved weak symbols which the AIX linker
3371 // isn't happy with.
3372 Builder.CreateCall(InitFnTy, Init);
3373 } else {
3374 // Don't know whether we have an init function. Call it if it exists.
3375 llvm::Value *Have = Builder.CreateIsNotNull(Init);
3376 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
3377 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
3378 Builder.CreateCondBr(Have, InitBB, ExitBB);
3379
3380 Builder.SetInsertPoint(InitBB);
3381 Builder.CreateCall(InitFnTy, Init);
3382 Builder.CreateBr(ExitBB);
3383
3384 Builder.SetInsertPoint(ExitBB);
3385 }
3386
3387 // For a reference, the result of the wrapper function is a pointer to
3388 // the referenced object.
3389 llvm::Value *Val = Builder.CreateThreadLocalAddress(Var);
3390
3391 if (VD->getType()->isReferenceType()) {
3392 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3393 Val = Builder.CreateAlignedLoad(Var->getValueType(), Val, Align);
3394 }
3395 Val = Builder.CreateAddrSpaceCast(Val, Wrapper->getReturnType());
3396
3397 Builder.CreateRet(Val);
3398 }
3399 }
3400
3401 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
3402 const VarDecl *VD,
3403 QualType LValType) {
3404 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
3405 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
3406
3407 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
3408 CallVal->setCallingConv(Wrapper->getCallingConv());
3409
3410 LValue LV;
3411 if (VD->getType()->isReferenceType())
3412 LV = CGF.MakeNaturalAlignRawAddrLValue(CallVal, LValType);
3413 else
3414 LV = CGF.MakeRawAddrLValue(CallVal, LValType,
3415 CGF.getContext().getDeclAlign(VD));
3416 // FIXME: need setObjCGCLValueClass?
3417 return LV;
3418 }
3419
3420 /// Return whether the given global decl needs a VTT parameter, which it does
3421 /// if it's a base constructor or destructor with virtual bases.
3422 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
3423 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
3424
3425 // We don't have any virtual bases, just return early.
3426 if (!MD->getParent()->getNumVBases())
3427 return false;
3428
3429 // Check if we have a base constructor.
3430 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
3431 return true;
3432
3433 // Check if we have a base destructor.
3434 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
3435 return true;
3436
3437 return false;
3438 }
3439
3440 llvm::Constant *
3441 ItaniumCXXABI::getOrCreateVirtualFunctionPointerThunk(const CXXMethodDecl *MD) {
3442 SmallString<256> MethodName;
3443 llvm::raw_svector_ostream Out(MethodName);
3444 getMangleContext().mangleCXXName(MD, Out);
3445 MethodName += "_vfpthunk_";
3446 StringRef ThunkName = MethodName.str();
3447 llvm::Function *ThunkFn;
3448 if ((ThunkFn = cast_or_null<llvm::Function>(
3449 CGM.getModule().getNamedValue(ThunkName))))
3450 return ThunkFn;
3451
3452 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeCXXMethodDeclaration(MD);
3453 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3454 llvm::GlobalValue::LinkageTypes Linkage =
3455 MD->isExternallyVisible() ? llvm::GlobalValue::LinkOnceODRLinkage
3456 : llvm::GlobalValue::InternalLinkage;
3457 ThunkFn =
3458 llvm::Function::Create(ThunkTy, Linkage, ThunkName, &CGM.getModule());
3459 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3460 ThunkFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3461 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
3462
3463 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/true);
3464 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
3465
3466 // Stack protection sometimes gets inserted after the musttail call.
3467 ThunkFn->removeFnAttr(llvm::Attribute::StackProtect);
3468 ThunkFn->removeFnAttr(llvm::Attribute::StackProtectStrong);
3469 ThunkFn->removeFnAttr(llvm::Attribute::StackProtectReq);
3470
3471 // Start codegen.
3472 CodeGenFunction CGF(CGM);
3473 CGF.CurGD = GlobalDecl(MD);
3474 CGF.CurFuncIsThunk = true;
3475
3476 // Build FunctionArgs.
3477 FunctionArgList FunctionArgs;
3478 CGF.BuildFunctionArgList(CGF.CurGD, FunctionArgs);
3479
3480 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3481 FunctionArgs, MD->getLocation(), SourceLocation());
3482
3483 // Emit an artificial location for this function.
3484 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
3485
3486 llvm::Value *ThisVal = loadIncomingCXXThis(CGF);
3487 setCXXABIThisValue(CGF, ThisVal);
3488
3489 CallArgList CallArgs;
3490 for (const VarDecl *VD : FunctionArgs)
3491 CGF.EmitDelegateCallArg(CallArgs, VD, SourceLocation());
3492
3493 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
3494 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, /*this*/ 1);
3495 const CGFunctionInfo &CallInfo =
3496 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT, Required, 0);
3497 CGCallee Callee = CGCallee::forVirtual(nullptr, GlobalDecl(MD),
3498 getThisAddress(CGF), ThunkTy);
3499 llvm::CallBase *CallOrInvoke;
3500 CGF.EmitCall(CallInfo, Callee, ReturnValueSlot(), CallArgs, &CallOrInvoke,
3501 /*IsMustTail=*/true, SourceLocation(), true);
3502 auto *Call = cast<llvm::CallInst>(CallOrInvoke);
3503 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
3504 if (Call->getType()->isVoidTy())
3505 CGF.Builder.CreateRetVoid();
3506 else
3507 CGF.Builder.CreateRet(Call);
3508
3509 // Finish the function to maintain CodeGenFunction invariants.
3510 // FIXME: Don't emit unreachable code.
3511 CGF.EmitBlock(CGF.createBasicBlock());
3512 CGF.FinishFunction();
3513 return ThunkFn;
3514 }
3515
3516 namespace {
3517 class ItaniumRTTIBuilder {
3518 CodeGenModule &CGM; // Per-module state.
3519 llvm::LLVMContext &VMContext;
3520 const ItaniumCXXABI &CXXABI; // Per-module state.
3521
3522 /// Fields - The fields of the RTTI descriptor currently being built.
3523 SmallVector<llvm::Constant *, 16> Fields;
3524
3525 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
3526 llvm::GlobalVariable *
3527 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
3528
3529 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
3530 /// descriptor of the given type.
3531 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
3532
3533 /// BuildVTablePointer - Build the vtable pointer for the given type.
3534 void BuildVTablePointer(const Type *Ty, llvm::Constant *StorageAddress);
3535
3536 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3537 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
3538 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
3539
3540 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3541 /// classes with bases that do not satisfy the abi::__si_class_type_info
3542 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3543 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
3544
3545 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
3546 /// for pointer types.
3547 void BuildPointerTypeInfo(QualType PointeeTy);
3548
3549 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
3550 /// type_info for an object type.
3551 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
3552
3553 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3554 /// struct, used for member pointer types.
3555 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
3556
3557 public:
3558 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
3559 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
3560
3561 // Pointer type info flags.
3562 enum {
3563 /// PTI_Const - Type has const qualifier.
3564 PTI_Const = 0x1,
3565
3566 /// PTI_Volatile - Type has volatile qualifier.
3567 PTI_Volatile = 0x2,
3568
3569 /// PTI_Restrict - Type has restrict qualifier.
3570 PTI_Restrict = 0x4,
3571
3572 /// PTI_Incomplete - Type is incomplete.
3573 PTI_Incomplete = 0x8,
3574
3575 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
3576 /// (in pointer to member).
3577 PTI_ContainingClassIncomplete = 0x10,
3578
3579 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
3580 //PTI_TransactionSafe = 0x20,
3581
3582 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
3583 PTI_Noexcept = 0x40,
3584 };
3585
3586 // VMI type info flags.
3587 enum {
3588 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
3589 VMI_NonDiamondRepeat = 0x1,
3590
3591 /// VMI_DiamondShaped - Class is diamond shaped.
3592 VMI_DiamondShaped = 0x2
3593 };
3594
3595 // Base class type info flags.
3596 enum {
3597 /// BCTI_Virtual - Base class is virtual.
3598 BCTI_Virtual = 0x1,
3599
3600 /// BCTI_Public - Base class is public.
3601 BCTI_Public = 0x2
3602 };
3603
3604 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
3605 /// link to an existing RTTI descriptor if one already exists.
3606 llvm::Constant *BuildTypeInfo(QualType Ty);
3607
3608 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
3609 llvm::Constant *BuildTypeInfo(
3610 QualType Ty,
3611 llvm::GlobalVariable::LinkageTypes Linkage,
3612 llvm::GlobalValue::VisibilityTypes Visibility,
3613 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
3614 };
3615 }
3616
3617 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
3618 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
3619 SmallString<256> Name;
3620 llvm::raw_svector_ostream Out(Name);
3621 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
3622
3623 // We know that the mangled name of the type starts at index 4 of the
3624 // mangled name of the typename, so we can just index into it in order to
3625 // get the mangled name of the type.
3626 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
3627 Name.substr(4));
3628 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
3629
3630 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
3631 Name, Init->getType(), Linkage, Align.getAsAlign());
3632
3633 GV->setInitializer(Init);
3634
3635 return GV;
3636 }
3637
3638 llvm::Constant *
3639 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
3640 // Mangle the RTTI name.
3641 SmallString<256> Name;
3642 llvm::raw_svector_ostream Out(Name);
3643 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
3644
3645 // Look for an existing global.
3646 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
3647
3648 if (!GV) {
3649 // Create a new global variable.
3650 // Note for the future: If we would ever like to do deferred emission of
3651 // RTTI, check if emitting vtables opportunistically need any adjustment.
3652
3653 GV = new llvm::GlobalVariable(
3654 CGM.getModule(), CGM.GlobalsInt8PtrTy,
3655 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, Name);
3656 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
3657 CGM.setGVProperties(GV, RD);
3658 // Import the typeinfo symbol when all non-inline virtual methods are
3659 // imported.
3660 if (CGM.getTarget().hasPS4DLLImportExport()) {
3661 if (RD && CXXRecordNonInlineHasAttr<DLLImportAttr>(RD)) {
3662 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3663 CGM.setDSOLocal(GV);
3664 }
3665 }
3666 }
3667
3668 return GV;
3669 }
3670
3671 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
3672 /// info for that type is defined in the standard library.
3673 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
3674 // Itanium C++ ABI 2.9.2:
3675 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
3676 // the run-time support library. Specifically, the run-time support
3677 // library should contain type_info objects for the types X, X* and
3678 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
3679 // unsigned char, signed char, short, unsigned short, int, unsigned int,
3680 // long, unsigned long, long long, unsigned long long, float, double,
3681 // long double, char16_t, char32_t, and the IEEE 754r decimal and
3682 // half-precision floating point types.
3683 //
3684 // GCC also emits RTTI for __int128.
3685 // FIXME: We do not emit RTTI information for decimal types here.
3686
3687 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
3688 switch (Ty->getKind()) {
3689 case BuiltinType::Void:
3690 case BuiltinType::NullPtr:
3691 case BuiltinType::Bool:
3692 case BuiltinType::WChar_S:
3693 case BuiltinType::WChar_U:
3694 case BuiltinType::Char_U:
3695 case BuiltinType::Char_S:
3696 case BuiltinType::UChar:
3697 case BuiltinType::SChar:
3698 case BuiltinType::Short:
3699 case BuiltinType::UShort:
3700 case BuiltinType::Int:
3701 case BuiltinType::UInt:
3702 case BuiltinType::Long:
3703 case BuiltinType::ULong:
3704 case BuiltinType::LongLong:
3705 case BuiltinType::ULongLong:
3706 case BuiltinType::Half:
3707 case BuiltinType::Float:
3708 case BuiltinType::Double:
3709 case BuiltinType::LongDouble:
3710 case BuiltinType::Float16:
3711 case BuiltinType::Float128:
3712 case BuiltinType::Ibm128:
3713 case BuiltinType::Char8:
3714 case BuiltinType::Char16:
3715 case BuiltinType::Char32:
3716 case BuiltinType::Int128:
3717 case BuiltinType::UInt128:
3718 return true;
3719
3720 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3721 case BuiltinType::Id:
3722 #include "clang/Basic/OpenCLImageTypes.def"
3723 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3724 case BuiltinType::Id:
3725 #include "clang/Basic/OpenCLExtensionTypes.def"
3726 case BuiltinType::OCLSampler:
3727 case BuiltinType::OCLEvent:
3728 case BuiltinType::OCLClkEvent:
3729 case BuiltinType::OCLQueue:
3730 case BuiltinType::OCLReserveID:
3731 #define SVE_TYPE(Name, Id, SingletonId) \
3732 case BuiltinType::Id:
3733 #include "clang/Basic/AArch64ACLETypes.def"
3734 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3735 case BuiltinType::Id:
3736 #include "clang/Basic/PPCTypes.def"
3737 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3738 #include "clang/Basic/RISCVVTypes.def"
3739 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3740 #include "clang/Basic/WebAssemblyReferenceTypes.def"
3741 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3742 #include "clang/Basic/AMDGPUTypes.def"
3743 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3744 #include "clang/Basic/HLSLIntangibleTypes.def"
3745 case BuiltinType::ShortAccum:
3746 case BuiltinType::Accum:
3747 case BuiltinType::LongAccum:
3748 case BuiltinType::UShortAccum:
3749 case BuiltinType::UAccum:
3750 case BuiltinType::ULongAccum:
3751 case BuiltinType::ShortFract:
3752 case BuiltinType::Fract:
3753 case BuiltinType::LongFract:
3754 case BuiltinType::UShortFract:
3755 case BuiltinType::UFract:
3756 case BuiltinType::ULongFract:
3757 case BuiltinType::SatShortAccum:
3758 case BuiltinType::SatAccum:
3759 case BuiltinType::SatLongAccum:
3760 case BuiltinType::SatUShortAccum:
3761 case BuiltinType::SatUAccum:
3762 case BuiltinType::SatULongAccum:
3763 case BuiltinType::SatShortFract:
3764 case BuiltinType::SatFract:
3765 case BuiltinType::SatLongFract:
3766 case BuiltinType::SatUShortFract:
3767 case BuiltinType::SatUFract:
3768 case BuiltinType::SatULongFract:
3769 case BuiltinType::BFloat16:
3770 return false;
3771
3772 case BuiltinType::Dependent:
3773 #define BUILTIN_TYPE(Id, SingletonId)
3774 #define PLACEHOLDER_TYPE(Id, SingletonId) \
3775 case BuiltinType::Id:
3776 #include "clang/AST/BuiltinTypes.def"
3777 llvm_unreachable("asking for RRTI for a placeholder type!");
3778
3779 case BuiltinType::ObjCId:
3780 case BuiltinType::ObjCClass:
3781 case BuiltinType::ObjCSel:
3782 llvm_unreachable("FIXME: Objective-C types are unsupported!");
3783 }
3784
3785 llvm_unreachable("Invalid BuiltinType Kind!");
3786 }
3787
3788 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
3789 QualType PointeeTy = PointerTy->getPointeeType();
3790 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
3791 if (!BuiltinTy)
3792 return false;
3793
3794 // Check the qualifiers.
3795 Qualifiers Quals = PointeeTy.getQualifiers();
3796 Quals.removeConst();
3797
3798 if (!Quals.empty())
3799 return false;
3800
3801 return TypeInfoIsInStandardLibrary(BuiltinTy);
3802 }
3803
3804 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
3805 /// information for the given type exists in the standard library.
3806 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
3807 // Type info for builtin types is defined in the standard library.
3808 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
3809 return TypeInfoIsInStandardLibrary(BuiltinTy);
3810
3811 // Type info for some pointer types to builtin types is defined in the
3812 // standard library.
3813 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3814 return TypeInfoIsInStandardLibrary(PointerTy);
3815
3816 return false;
3817 }
3818
3819 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
3820 /// the given type exists somewhere else, and that we should not emit the type
3821 /// information in this translation unit. Assumes that it is not a
3822 /// standard-library type.
3823 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
3824 QualType Ty) {
3825 ASTContext &Context = CGM.getContext();
3826
3827 // If RTTI is disabled, assume it might be disabled in the
3828 // translation unit that defines any potential key function, too.
3829 if (!Context.getLangOpts().RTTI) return false;
3830
3831 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3832 const CXXRecordDecl *RD =
3833 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
3834 if (!RD->hasDefinition())
3835 return false;
3836
3837 if (!RD->isDynamicClass())
3838 return false;
3839
3840 // FIXME: this may need to be reconsidered if the key function
3841 // changes.
3842 // N.B. We must always emit the RTTI data ourselves if there exists a key
3843 // function.
3844 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
3845
3846 // Don't import the RTTI but emit it locally.
3847 if (CGM.getTriple().isOSCygMing())
3848 return false;
3849
3850 if (CGM.getVTables().isVTableExternal(RD)) {
3851 if (CGM.getTarget().hasPS4DLLImportExport())
3852 return true;
3853
3854 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
3855 ? false
3856 : true;
3857 }
3858 if (IsDLLImport)
3859 return true;
3860 }
3861
3862 return false;
3863 }
3864
3865 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
3866 static bool IsIncompleteClassType(const RecordType *RecordTy) {
3867 return !RecordTy->getDecl()->getDefinitionOrSelf()->isCompleteDefinition();
3868 }
3869
3870 /// ContainsIncompleteClassType - Returns whether the given type contains an
3871 /// incomplete class type. This is true if
3872 ///
3873 /// * The given type is an incomplete class type.
3874 /// * The given type is a pointer type whose pointee type contains an
3875 /// incomplete class type.
3876 /// * The given type is a member pointer type whose class is an incomplete
3877 /// class type.
3878 /// * The given type is a member pointer type whoise pointee type contains an
3879 /// incomplete class type.
3880 /// is an indirect or direct pointer to an incomplete class type.
3881 static bool ContainsIncompleteClassType(QualType Ty) {
3882 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3883 if (IsIncompleteClassType(RecordTy))
3884 return true;
3885 }
3886
3887 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3888 return ContainsIncompleteClassType(PointerTy->getPointeeType());
3889
3890 if (const MemberPointerType *MemberPointerTy =
3891 dyn_cast<MemberPointerType>(Ty)) {
3892 // Check if the class type is incomplete.
3893 if (!MemberPointerTy->getMostRecentCXXRecordDecl()->hasDefinition())
3894 return true;
3895
3896 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3897 }
3898
3899 return false;
3900 }
3901
3902 // CanUseSingleInheritance - Return whether the given record decl has a "single,
3903 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
3904 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3905 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
3906 // Check the number of bases.
3907 if (RD->getNumBases() != 1)
3908 return false;
3909
3910 // Get the base.
3911 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
3912
3913 // Check that the base is not virtual.
3914 if (Base->isVirtual())
3915 return false;
3916
3917 // Check that the base is public.
3918 if (Base->getAccessSpecifier() != AS_public)
3919 return false;
3920
3921 // Check that the class is dynamic iff the base is.
3922 auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
3923 if (!BaseDecl->isEmpty() &&
3924 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3925 return false;
3926
3927 return true;
3928 }
3929
3930 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty,
3931 llvm::Constant *StorageAddress) {
3932 // abi::__class_type_info.
3933 static const char * const ClassTypeInfo =
3934 "_ZTVN10__cxxabiv117__class_type_infoE";
3935 // abi::__si_class_type_info.
3936 static const char * const SIClassTypeInfo =
3937 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3938 // abi::__vmi_class_type_info.
3939 static const char * const VMIClassTypeInfo =
3940 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3941
3942 const char *VTableName = nullptr;
3943
3944 switch (Ty->getTypeClass()) {
3945 #define TYPE(Class, Base)
3946 #define ABSTRACT_TYPE(Class, Base)
3947 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3948 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3949 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3950 #include "clang/AST/TypeNodes.inc"
3951 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3952
3953 case Type::LValueReference:
3954 case Type::RValueReference:
3955 llvm_unreachable("References shouldn't get here");
3956
3957 case Type::Auto:
3958 case Type::DeducedTemplateSpecialization:
3959 llvm_unreachable("Undeduced type shouldn't get here");
3960
3961 case Type::Pipe:
3962 llvm_unreachable("Pipe types shouldn't get here");
3963
3964 case Type::ArrayParameter:
3965 llvm_unreachable("Array Parameter types should not get here.");
3966
3967 case Type::Builtin:
3968 case Type::BitInt:
3969 // GCC treats vector and complex types as fundamental types.
3970 case Type::Vector:
3971 case Type::ExtVector:
3972 case Type::ConstantMatrix:
3973 case Type::Complex:
3974 case Type::Atomic:
3975 // FIXME: GCC treats block pointers as fundamental types?!
3976 case Type::BlockPointer:
3977 // abi::__fundamental_type_info.
3978 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
3979 break;
3980
3981 case Type::ConstantArray:
3982 case Type::IncompleteArray:
3983 case Type::VariableArray:
3984 // abi::__array_type_info.
3985 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
3986 break;
3987
3988 case Type::FunctionNoProto:
3989 case Type::FunctionProto:
3990 // abi::__function_type_info.
3991 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
3992 break;
3993
3994 case Type::Enum:
3995 // abi::__enum_type_info.
3996 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
3997 break;
3998
3999 case Type::Record: {
4000 const auto *RD = cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl())
4001 ->getDefinitionOrSelf();
4002
4003 if (!RD->hasDefinition() || !RD->getNumBases()) {
4004 VTableName = ClassTypeInfo;
4005 } else if (CanUseSingleInheritance(RD)) {
4006 VTableName = SIClassTypeInfo;
4007 } else {
4008 VTableName = VMIClassTypeInfo;
4009 }
4010
4011 break;
4012 }
4013
4014 case Type::ObjCObject:
4015 // Ignore protocol qualifiers.
4016 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
4017
4018 // Handle id and Class.
4019 if (isa<BuiltinType>(Ty)) {
4020 VTableName = ClassTypeInfo;
4021 break;
4022 }
4023
4024 assert(isa<ObjCInterfaceType>(Ty));
4025 [[fallthrough]];
4026
4027 case Type::ObjCInterface:
4028 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
4029 VTableName = SIClassTypeInfo;
4030 } else {
4031 VTableName = ClassTypeInfo;
4032 }
4033 break;
4034
4035 case Type::ObjCObjectPointer:
4036 case Type::Pointer:
4037 // abi::__pointer_type_info.
4038 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
4039 break;
4040
4041 case Type::MemberPointer:
4042 // abi::__pointer_to_member_type_info.
4043 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
4044 break;
4045
4046 case Type::HLSLAttributedResource:
4047 case Type::HLSLInlineSpirv:
4048 llvm_unreachable("HLSL doesn't support virtual functions");
4049 }
4050
4051 llvm::Constant *VTable = nullptr;
4052
4053 // Check if the alias exists. If it doesn't, then get or create the global.
4054 if (CGM.getItaniumVTableContext().isRelativeLayout())
4055 VTable = CGM.getModule().getNamedAlias(VTableName);
4056 if (!VTable) {
4057 llvm::Type *Ty = llvm::ArrayType::get(CGM.GlobalsInt8PtrTy, 0);
4058 VTable = CGM.getModule().getOrInsertGlobal(VTableName, Ty);
4059 }
4060
4061 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
4062
4063 llvm::Type *PtrDiffTy =
4064 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
4065
4066 // The vtable address point is 2.
4067 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
4068 // The vtable address point is 8 bytes after its start:
4069 // 4 for the offset to top + 4 for the relative offset to rtti.
4070 llvm::Constant *Eight = llvm::ConstantInt::get(CGM.Int32Ty, 8);
4071 VTable =
4072 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8Ty, VTable, Eight);
4073 } else {
4074 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
4075 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.GlobalsInt8PtrTy,
4076 VTable, Two);
4077 }
4078
4079 if (const auto &Schema =
4080 CGM.getCodeGenOpts().PointerAuth.CXXTypeInfoVTablePointer)
4081 VTable = CGM.getConstantSignedPointer(
4082 VTable, Schema,
4083 Schema.isAddressDiscriminated() ? StorageAddress : nullptr,
4084 GlobalDecl(), QualType(Ty, 0));
4085
4086 Fields.push_back(VTable);
4087 }
4088
4089 /// Return the linkage that the type info and type info name constants
4090 /// should have for the given type.
4091 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
4092 QualType Ty) {
4093 // Itanium C++ ABI 2.9.5p7:
4094 // In addition, it and all of the intermediate abi::__pointer_type_info
4095 // structs in the chain down to the abi::__class_type_info for the
4096 // incomplete class type must be prevented from resolving to the
4097 // corresponding type_info structs for the complete class type, possibly
4098 // by making them local static objects. Finally, a dummy class RTTI is
4099 // generated for the incomplete type that will not resolve to the final
4100 // complete class RTTI (because the latter need not exist), possibly by
4101 // making it a local static object.
4102 if (ContainsIncompleteClassType(Ty))
4103 return llvm::GlobalValue::InternalLinkage;
4104
4105 switch (Ty->getLinkage()) {
4106 case Linkage::Invalid:
4107 llvm_unreachable("Linkage hasn't been computed!");
4108
4109 case Linkage::None:
4110 case Linkage::Internal:
4111 case Linkage::UniqueExternal:
4112 return llvm::GlobalValue::InternalLinkage;
4113
4114 case Linkage::VisibleNone:
4115 case Linkage::Module:
4116 case Linkage::External:
4117 // RTTI is not enabled, which means that this type info struct is going
4118 // to be used for exception handling. Give it linkonce_odr linkage.
4119 if (!CGM.getLangOpts().RTTI)
4120 return llvm::GlobalValue::LinkOnceODRLinkage;
4121
4122 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
4123 const auto *RD =
4124 cast<CXXRecordDecl>(Record->getDecl())->getDefinitionOrSelf();
4125 if (RD->hasAttr<WeakAttr>())
4126 return llvm::GlobalValue::WeakODRLinkage;
4127 if (CGM.getTriple().isWindowsItaniumEnvironment())
4128 if (RD->hasAttr<DLLImportAttr>() &&
4129 ShouldUseExternalRTTIDescriptor(CGM, Ty))
4130 return llvm::GlobalValue::ExternalLinkage;
4131 // MinGW always uses LinkOnceODRLinkage for type info.
4132 if (RD->isDynamicClass() &&
4133 !CGM.getContext().getTargetInfo().getTriple().isOSCygMing())
4134 return CGM.getVTableLinkage(RD);
4135 }
4136
4137 return llvm::GlobalValue::LinkOnceODRLinkage;
4138 }
4139
4140 llvm_unreachable("Invalid linkage!");
4141 }
4142
4143 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
4144 // We want to operate on the canonical type.
4145 Ty = Ty.getCanonicalType();
4146
4147 // Check if we've already emitted an RTTI descriptor for this type.
4148 SmallString<256> Name;
4149 llvm::raw_svector_ostream Out(Name);
4150 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
4151
4152 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
4153 if (OldGV && !OldGV->isDeclaration()) {
4154 assert(!OldGV->hasAvailableExternallyLinkage() &&
4155 "available_externally typeinfos not yet implemented");
4156
4157 return OldGV;
4158 }
4159
4160 // Check if there is already an external RTTI descriptor for this type.
4161 if (IsStandardLibraryRTTIDescriptor(Ty) ||
4162 ShouldUseExternalRTTIDescriptor(CGM, Ty))
4163 return GetAddrOfExternalRTTIDescriptor(Ty);
4164
4165 // Emit the standard library with external linkage.
4166 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
4167
4168 // Give the type_info object and name the formal visibility of the
4169 // type itself.
4170 llvm::GlobalValue::VisibilityTypes llvmVisibility;
4171 if (llvm::GlobalValue::isLocalLinkage(Linkage))
4172 // If the linkage is local, only default visibility makes sense.
4173 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
4174 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
4175 ItaniumCXXABI::RUK_NonUniqueHidden)
4176 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
4177 else
4178 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
4179
4180 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
4181 llvm::GlobalValue::DefaultStorageClass;
4182 if (auto RD = Ty->getAsCXXRecordDecl()) {
4183 if ((CGM.getTriple().isWindowsItaniumEnvironment() &&
4184 RD->hasAttr<DLLExportAttr>()) ||
4185 (CGM.shouldMapVisibilityToDLLExport(RD) &&
4186 !llvm::GlobalValue::isLocalLinkage(Linkage) &&
4187 llvmVisibility == llvm::GlobalValue::DefaultVisibility))
4188 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
4189 }
4190 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
4191 }
4192
4193 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
4194 QualType Ty,
4195 llvm::GlobalVariable::LinkageTypes Linkage,
4196 llvm::GlobalValue::VisibilityTypes Visibility,
4197 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
4198 SmallString<256> Name;
4199 llvm::raw_svector_ostream Out(Name);
4200 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
4201 llvm::Module &M = CGM.getModule();
4202 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
4203 // int8 is an arbitrary type to be replaced later with replaceInitializer.
4204 llvm::GlobalVariable *GV =
4205 new llvm::GlobalVariable(M, CGM.Int8Ty, /*isConstant=*/true, Linkage,
4206 /*Initializer=*/nullptr, Name);
4207
4208 // Add the vtable pointer.
4209 BuildVTablePointer(cast<Type>(Ty), GV);
4210
4211 // And the name.
4212 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
4213 llvm::Constant *TypeNameField;
4214
4215 // If we're supposed to demote the visibility, be sure to set a flag
4216 // to use a string comparison for type_info comparisons.
4217 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
4218 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
4219 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
4220 // The flag is the sign bit, which on ARM64 is defined to be clear
4221 // for global pointers. This is very ARM64-specific.
4222 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
4223 llvm::Constant *flag =
4224 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
4225 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
4226 TypeNameField =
4227 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.GlobalsInt8PtrTy);
4228 } else {
4229 TypeNameField = TypeName;
4230 }
4231 Fields.push_back(TypeNameField);
4232
4233 switch (Ty->getTypeClass()) {
4234 #define TYPE(Class, Base)
4235 #define ABSTRACT_TYPE(Class, Base)
4236 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4237 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4238 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4239 #include "clang/AST/TypeNodes.inc"
4240 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
4241
4242 // GCC treats vector types as fundamental types.
4243 case Type::Builtin:
4244 case Type::Vector:
4245 case Type::ExtVector:
4246 case Type::ConstantMatrix:
4247 case Type::Complex:
4248 case Type::BlockPointer:
4249 // Itanium C++ ABI 2.9.5p4:
4250 // abi::__fundamental_type_info adds no data members to std::type_info.
4251 break;
4252
4253 case Type::LValueReference:
4254 case Type::RValueReference:
4255 llvm_unreachable("References shouldn't get here");
4256
4257 case Type::Auto:
4258 case Type::DeducedTemplateSpecialization:
4259 llvm_unreachable("Undeduced type shouldn't get here");
4260
4261 case Type::Pipe:
4262 break;
4263
4264 case Type::BitInt:
4265 break;
4266
4267 case Type::ConstantArray:
4268 case Type::IncompleteArray:
4269 case Type::VariableArray:
4270 case Type::ArrayParameter:
4271 // Itanium C++ ABI 2.9.5p5:
4272 // abi::__array_type_info adds no data members to std::type_info.
4273 break;
4274
4275 case Type::FunctionNoProto:
4276 case Type::FunctionProto:
4277 // Itanium C++ ABI 2.9.5p5:
4278 // abi::__function_type_info adds no data members to std::type_info.
4279 break;
4280
4281 case Type::Enum:
4282 // Itanium C++ ABI 2.9.5p5:
4283 // abi::__enum_type_info adds no data members to std::type_info.
4284 break;
4285
4286 case Type::Record: {
4287 const auto *RD = cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl())
4288 ->getDefinitionOrSelf();
4289 if (!RD->hasDefinition() || !RD->getNumBases()) {
4290 // We don't need to emit any fields.
4291 break;
4292 }
4293
4294 if (CanUseSingleInheritance(RD))
4295 BuildSIClassTypeInfo(RD);
4296 else
4297 BuildVMIClassTypeInfo(RD);
4298
4299 break;
4300 }
4301
4302 case Type::ObjCObject:
4303 case Type::ObjCInterface:
4304 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
4305 break;
4306
4307 case Type::ObjCObjectPointer:
4308 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
4309 break;
4310
4311 case Type::Pointer:
4312 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
4313 break;
4314
4315 case Type::MemberPointer:
4316 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
4317 break;
4318
4319 case Type::Atomic:
4320 // No fields, at least for the moment.
4321 break;
4322
4323 case Type::HLSLAttributedResource:
4324 case Type::HLSLInlineSpirv:
4325 llvm_unreachable("HLSL doesn't support RTTI");
4326 }
4327
4328 GV->replaceInitializer(llvm::ConstantStruct::getAnon(Fields));
4329
4330 // Export the typeinfo in the same circumstances as the vtable is exported.
4331 auto GVDLLStorageClass = DLLStorageClass;
4332 if (CGM.getTarget().hasPS4DLLImportExport() &&
4333 GVDLLStorageClass != llvm::GlobalVariable::DLLExportStorageClass) {
4334 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
4335 const auto *RD =
4336 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
4337 if (RD->hasAttr<DLLExportAttr>() ||
4338 CXXRecordNonInlineHasAttr<DLLExportAttr>(RD))
4339 GVDLLStorageClass = llvm::GlobalVariable::DLLExportStorageClass;
4340 }
4341 }
4342
4343 // If there's already an old global variable, replace it with the new one.
4344 if (OldGV) {
4345 GV->takeName(OldGV);
4346 OldGV->replaceAllUsesWith(GV);
4347 OldGV->eraseFromParent();
4348 }
4349
4350 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
4351 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4352
4353 CharUnits Align = CGM.getContext().toCharUnitsFromBits(
4354 CGM.getTarget().getPointerAlign(CGM.GetGlobalVarAddressSpace(nullptr)));
4355 GV->setAlignment(Align.getAsAlign());
4356
4357 // The Itanium ABI specifies that type_info objects must be globally
4358 // unique, with one exception: if the type is an incomplete class
4359 // type or a (possibly indirect) pointer to one. That exception
4360 // affects the general case of comparing type_info objects produced
4361 // by the typeid operator, which is why the comparison operators on
4362 // std::type_info generally use the type_info name pointers instead
4363 // of the object addresses. However, the language's built-in uses
4364 // of RTTI generally require class types to be complete, even when
4365 // manipulating pointers to those class types. This allows the
4366 // implementation of dynamic_cast to rely on address equality tests,
4367 // which is much faster.
4368
4369 // All of this is to say that it's important that both the type_info
4370 // object and the type_info name be uniqued when weakly emitted.
4371
4372 TypeName->setVisibility(Visibility);
4373 CGM.setDSOLocal(TypeName);
4374
4375 GV->setVisibility(Visibility);
4376 CGM.setDSOLocal(GV);
4377
4378 TypeName->setDLLStorageClass(DLLStorageClass);
4379 GV->setDLLStorageClass(GVDLLStorageClass);
4380
4381 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
4382 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
4383
4384 return GV;
4385 }
4386
4387 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
4388 /// for the given Objective-C object type.
4389 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
4390 // Drop qualifiers.
4391 const Type *T = OT->getBaseType().getTypePtr();
4392 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
4393
4394 // The builtin types are abi::__class_type_infos and don't require
4395 // extra fields.
4396 if (isa<BuiltinType>(T)) return;
4397
4398 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
4399 ObjCInterfaceDecl *Super = Class->getSuperClass();
4400
4401 // Root classes are also __class_type_info.
4402 if (!Super) return;
4403
4404 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
4405
4406 // Everything else is single inheritance.
4407 llvm::Constant *BaseTypeInfo =
4408 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
4409 Fields.push_back(BaseTypeInfo);
4410 }
4411
4412 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
4413 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
4414 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
4415 // Itanium C++ ABI 2.9.5p6b:
4416 // It adds to abi::__class_type_info a single member pointing to the
4417 // type_info structure for the base type,
4418 llvm::Constant *BaseTypeInfo =
4419 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
4420 Fields.push_back(BaseTypeInfo);
4421 }
4422
4423 namespace {
4424 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
4425 /// a class hierarchy.
4426 struct SeenBases {
4427 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
4428 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
4429 };
4430 }
4431
4432 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
4433 /// abi::__vmi_class_type_info.
4434 ///
4435 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
4436 SeenBases &Bases) {
4437
4438 unsigned Flags = 0;
4439
4440 auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
4441 if (Base->isVirtual()) {
4442 // Mark the virtual base as seen.
4443 if (!Bases.VirtualBases.insert(BaseDecl).second) {
4444 // If this virtual base has been seen before, then the class is diamond
4445 // shaped.
4446 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
4447 } else {
4448 if (Bases.NonVirtualBases.count(BaseDecl))
4449 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4450 }
4451 } else {
4452 // Mark the non-virtual base as seen.
4453 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
4454 // If this non-virtual base has been seen before, then the class has non-
4455 // diamond shaped repeated inheritance.
4456 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4457 } else {
4458 if (Bases.VirtualBases.count(BaseDecl))
4459 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4460 }
4461 }
4462
4463 // Walk all bases.
4464 for (const auto &I : BaseDecl->bases())
4465 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
4466
4467 return Flags;
4468 }
4469
4470 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
4471 unsigned Flags = 0;
4472 SeenBases Bases;
4473
4474 // Walk all bases.
4475 for (const auto &I : RD->bases())
4476 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
4477
4478 return Flags;
4479 }
4480
4481 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
4482 /// classes with bases that do not satisfy the abi::__si_class_type_info
4483 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
4484 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
4485 llvm::Type *UnsignedIntLTy =
4486 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
4487
4488 // Itanium C++ ABI 2.9.5p6c:
4489 // __flags is a word with flags describing details about the class
4490 // structure, which may be referenced by using the __flags_masks
4491 // enumeration. These flags refer to both direct and indirect bases.
4492 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
4493 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4494
4495 // Itanium C++ ABI 2.9.5p6c:
4496 // __base_count is a word with the number of direct proper base class
4497 // descriptions that follow.
4498 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
4499
4500 if (!RD->getNumBases())
4501 return;
4502
4503 // Now add the base class descriptions.
4504
4505 // Itanium C++ ABI 2.9.5p6c:
4506 // __base_info[] is an array of base class descriptions -- one for every
4507 // direct proper base. Each description is of the type:
4508 //
4509 // struct abi::__base_class_type_info {
4510 // public:
4511 // const __class_type_info *__base_type;
4512 // long __offset_flags;
4513 //
4514 // enum __offset_flags_masks {
4515 // __virtual_mask = 0x1,
4516 // __public_mask = 0x2,
4517 // __offset_shift = 8
4518 // };
4519 // };
4520
4521 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
4522 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
4523 // LLP64 platforms.
4524 // FIXME: Consider updating libc++abi to match, and extend this logic to all
4525 // LLP64 platforms.
4526 QualType OffsetFlagsTy = CGM.getContext().LongTy;
4527 const TargetInfo &TI = CGM.getContext().getTargetInfo();
4528 if (TI.getTriple().isOSCygMing() &&
4529 TI.getPointerWidth(LangAS::Default) > TI.getLongWidth())
4530 OffsetFlagsTy = CGM.getContext().LongLongTy;
4531 llvm::Type *OffsetFlagsLTy =
4532 CGM.getTypes().ConvertType(OffsetFlagsTy);
4533
4534 for (const auto &Base : RD->bases()) {
4535 // The __base_type member points to the RTTI for the base type.
4536 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
4537
4538 auto *BaseDecl = Base.getType()->castAsCXXRecordDecl();
4539 int64_t OffsetFlags = 0;
4540
4541 // All but the lower 8 bits of __offset_flags are a signed offset.
4542 // For a non-virtual base, this is the offset in the object of the base
4543 // subobject. For a virtual base, this is the offset in the virtual table of
4544 // the virtual base offset for the virtual base referenced (negative).
4545 CharUnits Offset;
4546 if (Base.isVirtual())
4547 Offset =
4548 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
4549 else {
4550 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
4551 Offset = Layout.getBaseClassOffset(BaseDecl);
4552 };
4553
4554 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
4555
4556 // The low-order byte of __offset_flags contains flags, as given by the
4557 // masks from the enumeration __offset_flags_masks.
4558 if (Base.isVirtual())
4559 OffsetFlags |= BCTI_Virtual;
4560 if (Base.getAccessSpecifier() == AS_public)
4561 OffsetFlags |= BCTI_Public;
4562
4563 Fields.push_back(llvm::ConstantInt::getSigned(OffsetFlagsLTy, OffsetFlags));
4564 }
4565 }
4566
4567 /// Compute the flags for a __pbase_type_info, and remove the corresponding
4568 /// pieces from \p Type.
4569 static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
4570 unsigned Flags = 0;
4571
4572 if (Type.isConstQualified())
4573 Flags |= ItaniumRTTIBuilder::PTI_Const;
4574 if (Type.isVolatileQualified())
4575 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
4576 if (Type.isRestrictQualified())
4577 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
4578 Type = Type.getUnqualifiedType();
4579
4580 // Itanium C++ ABI 2.9.5p7:
4581 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
4582 // incomplete class type, the incomplete target type flag is set.
4583 if (ContainsIncompleteClassType(Type))
4584 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
4585
4586 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
4587 if (Proto->isNothrow()) {
4588 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
4589 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
4590 }
4591 }
4592
4593 return Flags;
4594 }
4595
4596 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
4597 /// used for pointer types.
4598 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
4599 // Itanium C++ ABI 2.9.5p7:
4600 // __flags is a flag word describing the cv-qualification and other
4601 // attributes of the type pointed to
4602 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
4603
4604 llvm::Type *UnsignedIntLTy =
4605 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
4606 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4607
4608 // Itanium C++ ABI 2.9.5p7:
4609 // __pointee is a pointer to the std::type_info derivation for the
4610 // unqualified type being pointed to.
4611 llvm::Constant *PointeeTypeInfo =
4612 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
4613 Fields.push_back(PointeeTypeInfo);
4614 }
4615
4616 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
4617 /// struct, used for member pointer types.
4618 void
4619 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
4620 QualType PointeeTy = Ty->getPointeeType();
4621
4622 // Itanium C++ ABI 2.9.5p7:
4623 // __flags is a flag word describing the cv-qualification and other
4624 // attributes of the type pointed to.
4625 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
4626
4627 const auto *RD = Ty->getMostRecentCXXRecordDecl();
4628 if (!RD->hasDefinition())
4629 Flags |= PTI_ContainingClassIncomplete;
4630
4631 llvm::Type *UnsignedIntLTy =
4632 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
4633 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4634
4635 // Itanium C++ ABI 2.9.5p7:
4636 // __pointee is a pointer to the std::type_info derivation for the
4637 // unqualified type being pointed to.
4638 llvm::Constant *PointeeTypeInfo =
4639 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
4640 Fields.push_back(PointeeTypeInfo);
4641
4642 // Itanium C++ ABI 2.9.5p9:
4643 // __context is a pointer to an abi::__class_type_info corresponding to the
4644 // class type containing the member pointed to
4645 // (e.g., the "A" in "int A::*").
4646 CanQualType T = CGM.getContext().getCanonicalTagType(RD);
4647 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(T));
4648 }
4649
4650 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
4651 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
4652 }
4653
4654 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
4655 // Types added here must also be added to TypeInfoIsInStandardLibrary.
4656 QualType FundamentalTypes[] = {
4657 getContext().VoidTy, getContext().NullPtrTy,
4658 getContext().BoolTy, getContext().WCharTy,
4659 getContext().CharTy, getContext().UnsignedCharTy,
4660 getContext().SignedCharTy, getContext().ShortTy,
4661 getContext().UnsignedShortTy, getContext().IntTy,
4662 getContext().UnsignedIntTy, getContext().LongTy,
4663 getContext().UnsignedLongTy, getContext().LongLongTy,
4664 getContext().UnsignedLongLongTy, getContext().Int128Ty,
4665 getContext().UnsignedInt128Ty, getContext().HalfTy,
4666 getContext().FloatTy, getContext().DoubleTy,
4667 getContext().LongDoubleTy, getContext().Float128Ty,
4668 getContext().Char8Ty, getContext().Char16Ty,
4669 getContext().Char32Ty
4670 };
4671 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
4672 RD->hasAttr<DLLExportAttr>() || CGM.shouldMapVisibilityToDLLExport(RD)
4673 ? llvm::GlobalValue::DLLExportStorageClass
4674 : llvm::GlobalValue::DefaultStorageClass;
4675 llvm::GlobalValue::VisibilityTypes Visibility =
4676 CodeGenModule::GetLLVMVisibility(RD->getVisibility());
4677 for (const QualType &FundamentalType : FundamentalTypes) {
4678 QualType PointerType = getContext().getPointerType(FundamentalType);
4679 QualType PointerTypeConst = getContext().getPointerType(
4680 FundamentalType.withConst());
4681 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
4682 ItaniumRTTIBuilder(*this).BuildTypeInfo(
4683 Type, llvm::GlobalValue::ExternalLinkage,
4684 Visibility, DLLStorageClass);
4685 }
4686 }
4687
4688 /// What sort of uniqueness rules should we use for the RTTI for the
4689 /// given type?
4690 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
4691 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
4692 if (shouldRTTIBeUnique())
4693 return RUK_Unique;
4694
4695 // It's only necessary for linkonce_odr or weak_odr linkage.
4696 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
4697 Linkage != llvm::GlobalValue::WeakODRLinkage)
4698 return RUK_Unique;
4699
4700 // It's only necessary with default visibility.
4701 if (CanTy->getVisibility() != DefaultVisibility)
4702 return RUK_Unique;
4703
4704 // If we're not required to publish this symbol, hide it.
4705 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
4706 return RUK_NonUniqueHidden;
4707
4708 // If we're required to publish this symbol, as we might be under an
4709 // explicit instantiation, leave it with default visibility but
4710 // enable string-comparisons.
4711 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
4712 return RUK_NonUniqueVisible;
4713 }
4714
4715 // Find out how to codegen the complete destructor and constructor
4716 namespace {
4717 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
4718 }
4719 static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
4720 const CXXMethodDecl *MD) {
4721 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
4722 return StructorCodegen::Emit;
4723
4724 // The complete and base structors are not equivalent if there are any virtual
4725 // bases, so emit separate functions.
4726 if (MD->getParent()->getNumVBases())
4727 return StructorCodegen::Emit;
4728
4729 GlobalDecl AliasDecl;
4730 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
4731 AliasDecl = GlobalDecl(DD, Dtor_Complete);
4732 } else {
4733 const auto *CD = cast<CXXConstructorDecl>(MD);
4734 AliasDecl = GlobalDecl(CD, Ctor_Complete);
4735 }
4736 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
4737
4738 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
4739 return StructorCodegen::RAUW;
4740
4741 // FIXME: Should we allow available_externally aliases?
4742 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
4743 return StructorCodegen::RAUW;
4744
4745 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
4746 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
4747 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
4748 CGM.getTarget().getTriple().isOSBinFormatWasm())
4749 return StructorCodegen::COMDAT;
4750 return StructorCodegen::Emit;
4751 }
4752
4753 return StructorCodegen::Alias;
4754 }
4755
4756 static void emitConstructorDestructorAlias(CodeGenModule &CGM,
4757 GlobalDecl AliasDecl,
4758 GlobalDecl TargetDecl) {
4759 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
4760
4761 StringRef MangledName = CGM.getMangledName(AliasDecl);
4762 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
4763 if (Entry && !Entry->isDeclaration())
4764 return;
4765
4766 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
4767
4768 // Create the alias with no name.
4769 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
4770
4771 // Constructors and destructors are always unnamed_addr.
4772 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4773
4774 // Switch any previous uses to the alias.
4775 if (Entry) {
4776 assert(Entry->getType() == Aliasee->getType() &&
4777 "declaration exists with different type");
4778 Alias->takeName(Entry);
4779 Entry->replaceAllUsesWith(Alias);
4780 Entry->eraseFromParent();
4781 } else {
4782 Alias->setName(MangledName);
4783 }
4784
4785 // Finally, set up the alias with its proper name and attributes.
4786 CGM.SetCommonAttributes(AliasDecl, Alias);
4787 }
4788
4789 void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
4790 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
4791 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
4792 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
4793
4794 StructorCodegen CGType = getCodegenToUse(CGM, MD);
4795
4796 if (CD ? GD.getCtorType() == Ctor_Complete
4797 : GD.getDtorType() == Dtor_Complete) {
4798 GlobalDecl BaseDecl;
4799 if (CD)
4800 BaseDecl = GD.getWithCtorType(Ctor_Base);
4801 else
4802 BaseDecl = GD.getWithDtorType(Dtor_Base);
4803
4804 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
4805 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
4806 return;
4807 }
4808
4809 if (CGType == StructorCodegen::RAUW) {
4810 StringRef MangledName = CGM.getMangledName(GD);
4811 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
4812 CGM.addReplacement(MangledName, Aliasee);
4813 return;
4814 }
4815 }
4816
4817 // The base destructor is equivalent to the base destructor of its
4818 // base class if there is exactly one non-virtual base class with a
4819 // non-trivial destructor, there are no fields with a non-trivial
4820 // destructor, and the body of the destructor is trivial.
4821 if (DD && GD.getDtorType() == Dtor_Base &&
4822 CGType != StructorCodegen::COMDAT &&
4823 !CGM.TryEmitBaseDestructorAsAlias(DD))
4824 return;
4825
4826 // FIXME: The deleting destructor is equivalent to the selected operator
4827 // delete if:
4828 // * either the delete is a destroying operator delete or the destructor
4829 // would be trivial if it weren't virtual,
4830 // * the conversion from the 'this' parameter to the first parameter of the
4831 // destructor is equivalent to a bitcast,
4832 // * the destructor does not have an implicit "this" return, and
4833 // * the operator delete has the same calling convention and IR function type
4834 // as the destructor.
4835 // In such cases we should try to emit the deleting dtor as an alias to the
4836 // selected 'operator delete'.
4837
4838 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4839
4840 if (CGType == StructorCodegen::COMDAT) {
4841 SmallString<256> Buffer;
4842 llvm::raw_svector_ostream Out(Buffer);
4843 if (DD)
4844 getMangleContext().mangleCXXDtorComdat(DD, Out);
4845 else
4846 getMangleContext().mangleCXXCtorComdat(CD, Out);
4847 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
4848 Fn->setComdat(C);
4849 } else {
4850 CGM.maybeSetTrivialComdat(*MD, *Fn);
4851 }
4852 }
4853
4854 static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
4855 // void *__cxa_begin_catch(void*);
4856 llvm::FunctionType *FTy = llvm::FunctionType::get(
4857 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4858
4859 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
4860 }
4861
4862 static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
4863 // void __cxa_end_catch();
4864 llvm::FunctionType *FTy =
4865 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
4866
4867 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
4868 }
4869
4870 static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
4871 // void *__cxa_get_exception_ptr(void*);
4872 llvm::FunctionType *FTy = llvm::FunctionType::get(
4873 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4874
4875 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
4876 }
4877
4878 namespace {
4879 /// A cleanup to call __cxa_end_catch. In many cases, the caught
4880 /// exception type lets us state definitively that the thrown exception
4881 /// type does not have a destructor. In particular:
4882 /// - Catch-alls tell us nothing, so we have to conservatively
4883 /// assume that the thrown exception might have a destructor.
4884 /// - Catches by reference behave according to their base types.
4885 /// - Catches of non-record types will only trigger for exceptions
4886 /// of non-record types, which never have destructors.
4887 /// - Catches of record types can trigger for arbitrary subclasses
4888 /// of the caught type, so we have to assume the actual thrown
4889 /// exception type might have a throwing destructor, even if the
4890 /// caught type's destructor is trivial or nothrow.
4891 struct CallEndCatch final : EHScopeStack::Cleanup {
4892 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
4893 bool MightThrow;
4894
4895 void Emit(CodeGenFunction &CGF, Flags flags) override {
4896 if (!MightThrow) {
4897 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
4898 return;
4899 }
4900
4901 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
4902 }
4903 };
4904 }
4905
4906 /// Emits a call to __cxa_begin_catch and enters a cleanup to call
4907 /// __cxa_end_catch. If -fassume-nothrow-exception-dtor is specified, we assume
4908 /// that the exception object's dtor is nothrow, therefore the __cxa_end_catch
4909 /// call can be marked as nounwind even if EndMightThrow is true.
4910 ///
4911 /// \param EndMightThrow - true if __cxa_end_catch might throw
4912 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
4913 llvm::Value *Exn,
4914 bool EndMightThrow) {
4915 llvm::CallInst *call =
4916 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
4917
4918 CGF.EHStack.pushCleanup<CallEndCatch>(
4919 NormalAndEHCleanup,
4920 EndMightThrow && !CGF.CGM.getLangOpts().AssumeNothrowExceptionDtor);
4921
4922 return call;
4923 }
4924
4925 /// A "special initializer" callback for initializing a catch
4926 /// parameter during catch initialization.
4927 static void InitCatchParam(CodeGenFunction &CGF,
4928 const VarDecl &CatchParam,
4929 Address ParamAddr,
4930 SourceLocation Loc) {
4931 // Load the exception from where the landing pad saved it.
4932 llvm::Value *Exn = CGF.getExceptionFromSlot();
4933
4934 CanQualType CatchType =
4935 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
4936 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
4937
4938 // If we're catching by reference, we can just cast the object
4939 // pointer to the appropriate pointer.
4940 if (isa<ReferenceType>(CatchType)) {
4941 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
4942 bool EndCatchMightThrow = CaughtType->isRecordType();
4943
4944 // __cxa_begin_catch returns the adjusted object pointer.
4945 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
4946
4947 // We have no way to tell the personality function that we're
4948 // catching by reference, so if we're catching a pointer,
4949 // __cxa_begin_catch will actually return that pointer by value.
4950 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
4951 QualType PointeeType = PT->getPointeeType();
4952
4953 // When catching by reference, generally we should just ignore
4954 // this by-value pointer and use the exception object instead.
4955 if (!PointeeType->isRecordType()) {
4956
4957 // Exn points to the struct _Unwind_Exception header, which
4958 // we have to skip past in order to reach the exception data.
4959 unsigned HeaderSize =
4960 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
4961 AdjustedExn =
4962 CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, Exn, HeaderSize);
4963
4964 // However, if we're catching a pointer-to-record type that won't
4965 // work, because the personality function might have adjusted
4966 // the pointer. There's actually no way for us to fully satisfy
4967 // the language/ABI contract here: we can't use Exn because it
4968 // might have the wrong adjustment, but we can't use the by-value
4969 // pointer because it's off by a level of abstraction.
4970 //
4971 // The current solution is to dump the adjusted pointer into an
4972 // alloca, which breaks language semantics (because changing the
4973 // pointer doesn't change the exception) but at least works.
4974 // The better solution would be to filter out non-exact matches
4975 // and rethrow them, but this is tricky because the rethrow
4976 // really needs to be catchable by other sites at this landing
4977 // pad. The best solution is to fix the personality function.
4978 } else {
4979 // Pull the pointer for the reference type off.
4980 llvm::Type *PtrTy = CGF.ConvertTypeForMem(CaughtType);
4981
4982 // Create the temporary and write the adjusted pointer into it.
4983 Address ExnPtrTmp =
4984 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
4985 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
4986 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
4987
4988 // Bind the reference to the temporary.
4989 AdjustedExn = ExnPtrTmp.emitRawPointer(CGF);
4990 }
4991 }
4992
4993 llvm::Value *ExnCast =
4994 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
4995 CGF.Builder.CreateStore(ExnCast, ParamAddr);
4996 return;
4997 }
4998
4999 // Scalars and complexes.
5000 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
5001 if (TEK != TEK_Aggregate) {
5002 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
5003
5004 // If the catch type is a pointer type, __cxa_begin_catch returns
5005 // the pointer by value.
5006 if (CatchType->hasPointerRepresentation()) {
5007 llvm::Value *CastExn =
5008 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
5009
5010 switch (CatchType.getQualifiers().getObjCLifetime()) {
5011 case Qualifiers::OCL_Strong:
5012 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
5013 [[fallthrough]];
5014
5015 case Qualifiers::OCL_None:
5016 case Qualifiers::OCL_ExplicitNone:
5017 case Qualifiers::OCL_Autoreleasing:
5018 CGF.Builder.CreateStore(CastExn, ParamAddr);
5019 return;
5020
5021 case Qualifiers::OCL_Weak:
5022 CGF.EmitARCInitWeak(ParamAddr, CastExn);
5023 return;
5024 }
5025 llvm_unreachable("bad ownership qualifier!");
5026 }
5027
5028 // Otherwise, it returns a pointer into the exception object.
5029
5030 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(AdjustedExn, CatchType);
5031 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
5032 switch (TEK) {
5033 case TEK_Complex:
5034 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
5035 /*init*/ true);
5036 return;
5037 case TEK_Scalar: {
5038 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
5039 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
5040 return;
5041 }
5042 case TEK_Aggregate:
5043 llvm_unreachable("evaluation kind filtered out!");
5044 }
5045 llvm_unreachable("bad evaluation kind");
5046 }
5047
5048 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
5049 auto catchRD = CatchType->getAsCXXRecordDecl();
5050 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
5051
5052 llvm::Type *PtrTy = CGF.DefaultPtrTy;
5053
5054 // Check for a copy expression. If we don't have a copy expression,
5055 // that means a trivial copy is okay.
5056 const Expr *copyExpr = CatchParam.getInit();
5057 if (!copyExpr) {
5058 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
5059 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
5060 LLVMCatchTy, caughtExnAlignment);
5061 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
5062 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
5063 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
5064 return;
5065 }
5066
5067 // We have to call __cxa_get_exception_ptr to get the adjusted
5068 // pointer before copying.
5069 llvm::CallInst *rawAdjustedExn =
5070 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
5071
5072 // Cast that to the appropriate type.
5073 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
5074 LLVMCatchTy, caughtExnAlignment);
5075
5076 // The copy expression is defined in terms of an OpaqueValueExpr.
5077 // Find it and map it to the adjusted expression.
5078 CodeGenFunction::OpaqueValueMapping
5079 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
5080 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
5081
5082 // Call the copy ctor in a terminate scope.
5083 CGF.EHStack.pushTerminate();
5084
5085 // Perform the copy construction.
5086 CGF.EmitAggExpr(copyExpr,
5087 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
5088 AggValueSlot::IsNotDestructed,
5089 AggValueSlot::DoesNotNeedGCBarriers,
5090 AggValueSlot::IsNotAliased,
5091 AggValueSlot::DoesNotOverlap));
5092
5093 // Leave the terminate scope.
5094 CGF.EHStack.popTerminate();
5095
5096 // Undo the opaque value mapping.
5097 opaque.pop();
5098
5099 // Finally we can call __cxa_begin_catch.
5100 CallBeginCatch(CGF, Exn, true);
5101 }
5102
5103 /// Begins a catch statement by initializing the catch variable and
5104 /// calling __cxa_begin_catch.
5105 void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
5106 const CXXCatchStmt *S) {
5107 // We have to be very careful with the ordering of cleanups here:
5108 // C++ [except.throw]p4:
5109 // The destruction [of the exception temporary] occurs
5110 // immediately after the destruction of the object declared in
5111 // the exception-declaration in the handler.
5112 //
5113 // So the precise ordering is:
5114 // 1. Construct catch variable.
5115 // 2. __cxa_begin_catch
5116 // 3. Enter __cxa_end_catch cleanup
5117 // 4. Enter dtor cleanup
5118 //
5119 // We do this by using a slightly abnormal initialization process.
5120 // Delegation sequence:
5121 // - ExitCXXTryStmt opens a RunCleanupsScope
5122 // - EmitAutoVarAlloca creates the variable and debug info
5123 // - InitCatchParam initializes the variable from the exception
5124 // - CallBeginCatch calls __cxa_begin_catch
5125 // - CallBeginCatch enters the __cxa_end_catch cleanup
5126 // - EmitAutoVarCleanups enters the variable destructor cleanup
5127 // - EmitCXXTryStmt emits the code for the catch body
5128 // - EmitCXXTryStmt close the RunCleanupsScope
5129
5130 VarDecl *CatchParam = S->getExceptionDecl();
5131 if (!CatchParam) {
5132 llvm::Value *Exn = CGF.getExceptionFromSlot();
5133 CallBeginCatch(CGF, Exn, true);
5134 return;
5135 }
5136
5137 // Emit the local.
5138 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
5139 {
5140 ApplyAtomGroup Grp(CGF.getDebugInfo());
5141 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF),
5142 S->getBeginLoc());
5143 }
5144 CGF.EmitAutoVarCleanups(var);
5145 }
5146
5147 /// Get or define the following function:
5148 /// void @__clang_call_terminate(i8* %exn) nounwind noreturn
5149 /// This code is used only in C++.
5150 static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
5151 ASTContext &C = CGM.getContext();
5152 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
5153 C.VoidTy, {C.getPointerType(C.CharTy)});
5154 llvm::FunctionType *fnTy = CGM.getTypes().GetFunctionType(FI);
5155 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
5156 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
5157 llvm::Function *fn =
5158 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
5159 if (fn->empty()) {
5160 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, fn, /*IsThunk=*/false);
5161 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, fn);
5162 fn->setDoesNotThrow();
5163 fn->setDoesNotReturn();
5164
5165 // What we really want is to massively penalize inlining without
5166 // forbidding it completely. The difference between that and
5167 // 'noinline' is negligible.
5168 fn->addFnAttr(llvm::Attribute::NoInline);
5169
5170 // Allow this function to be shared across translation units, but
5171 // we don't want it to turn into an exported symbol.
5172 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
5173 fn->setVisibility(llvm::Function::HiddenVisibility);
5174 if (CGM.supportsCOMDAT())
5175 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
5176
5177 // Set up the function.
5178 llvm::BasicBlock *entry =
5179 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
5180 CGBuilderTy builder(CGM, entry);
5181
5182 // Pull the exception pointer out of the parameter list.
5183 llvm::Value *exn = &*fn->arg_begin();
5184
5185 // Call __cxa_begin_catch(exn).
5186 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
5187 catchCall->setDoesNotThrow();
5188 catchCall->setCallingConv(CGM.getRuntimeCC());
5189
5190 // Call std::terminate().
5191 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
5192 termCall->setDoesNotThrow();
5193 termCall->setDoesNotReturn();
5194 termCall->setCallingConv(CGM.getRuntimeCC());
5195
5196 // std::terminate cannot return.
5197 builder.CreateUnreachable();
5198 }
5199 return fnRef;
5200 }
5201
5202 llvm::CallInst *
5203 ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
5204 llvm::Value *Exn) {
5205 // In C++, we want to call __cxa_begin_catch() before terminating.
5206 if (Exn) {
5207 assert(CGF.CGM.getLangOpts().CPlusPlus);
5208 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
5209 }
5210 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
5211 }
5212
5213 std::pair<llvm::Value *, const CXXRecordDecl *>
5214 ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
5215 const CXXRecordDecl *RD) {
5216 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
5217 }
5218
5219 llvm::Constant *
5220 ItaniumCXXABI::getSignedVirtualMemberFunctionPointer(const CXXMethodDecl *MD) {
5221 const CXXMethodDecl *origMD =
5222 cast<CXXMethodDecl>(CGM.getItaniumVTableContext()
5223 .findOriginalMethod(MD->getCanonicalDecl())
5224 .getDecl());
5225 llvm::Constant *thunk = getOrCreateVirtualFunctionPointerThunk(origMD);
5226 QualType funcType = CGM.getContext().getMemberPointerType(
5227 MD->getType(), /*Qualifier=*/std::nullopt, MD->getParent());
5228 return CGM.getMemberFunctionPointer(thunk, funcType);
5229 }
5230
5231 void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
5232 const CXXCatchStmt *C) {
5233 if (CGF.getTarget().hasFeature("exception-handling"))
5234 CGF.EHStack.pushCleanup<CatchRetScope>(
5235 NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
5236 ItaniumCXXABI::emitBeginCatch(CGF, C);
5237 }
5238
5239 llvm::CallInst *
5240 WebAssemblyCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
5241 llvm::Value *Exn) {
5242 // Itanium ABI calls __clang_call_terminate(), which __cxa_begin_catch() on
5243 // the violating exception to mark it handled, but it is currently hard to do
5244 // with wasm EH instruction structure with catch/catch_all, we just call
5245 // std::terminate and ignore the violating exception as in CGCXXABI in Wasm EH
5246 // and call __clang_call_terminate only in Emscripten EH.
5247 // TODO Consider code transformation that makes calling __clang_call_terminate
5248 // in Wasm EH possible.
5249 if (Exn && !EHPersonality::get(CGF).isWasmPersonality()) {
5250 assert(CGF.CGM.getLangOpts().CPlusPlus);
5251 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
5252 }
5253 return CGCXXABI::emitTerminateForUnexpectedException(CGF, Exn);
5254 }
5255
5256 /// Register a global destructor as best as we know how.
5257 void XLCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
5258 llvm::FunctionCallee Dtor,
5259 llvm::Constant *Addr) {
5260 if (D.getTLSKind() != VarDecl::TLS_None) {
5261 llvm::PointerType *PtrTy = CGF.DefaultPtrTy;
5262
5263 // extern "C" int __pt_atexit_np(int flags, int(*)(int,...), ...);
5264 llvm::FunctionType *AtExitTy =
5265 llvm::FunctionType::get(CGM.IntTy, {CGM.IntTy, PtrTy}, true);
5266
5267 // Fetch the actual function.
5268 llvm::FunctionCallee AtExit =
5269 CGM.CreateRuntimeFunction(AtExitTy, "__pt_atexit_np");
5270
5271 // Create __dtor function for the var decl.
5272 llvm::Function *DtorStub = CGF.createTLSAtExitStub(D, Dtor, Addr, AtExit);
5273
5274 // Register above __dtor with atexit().
5275 // First param is flags and must be 0, second param is function ptr
5276 llvm::Value *NV = llvm::Constant::getNullValue(CGM.IntTy);
5277 CGF.EmitNounwindRuntimeCall(AtExit, {NV, DtorStub});
5278
5279 // Cannot unregister TLS __dtor so done
5280 return;
5281 }
5282
5283 // Create __dtor function for the var decl.
5284 llvm::Function *DtorStub =
5285 cast<llvm::Function>(CGF.createAtExitStub(D, Dtor, Addr));
5286
5287 // Register above __dtor with atexit().
5288 CGF.registerGlobalDtorWithAtExit(DtorStub);
5289
5290 // Emit __finalize function to unregister __dtor and (as appropriate) call
5291 // __dtor.
5292 emitCXXStermFinalizer(D, DtorStub, Addr);
5293 }
5294
5295 void XLCXXABI::emitCXXStermFinalizer(const VarDecl &D, llvm::Function *dtorStub,
5296 llvm::Constant *addr) {
5297 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
5298 SmallString<256> FnName;
5299 {
5300 llvm::raw_svector_ostream Out(FnName);
5301 getMangleContext().mangleDynamicStermFinalizer(&D, Out);
5302 }
5303
5304 // Create the finalization action associated with a variable.
5305 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
5306 llvm::Function *StermFinalizer = CGM.CreateGlobalInitOrCleanUpFunction(
5307 FTy, FnName.str(), FI, D.getLocation());
5308
5309 CodeGenFunction CGF(CGM);
5310
5311 CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, StermFinalizer, FI,
5312 FunctionArgList(), D.getLocation(),
5313 D.getInit()->getExprLoc());
5314
5315 // The unatexit subroutine unregisters __dtor functions that were previously
5316 // registered by the atexit subroutine. If the referenced function is found,
5317 // the unatexit returns a value of 0, meaning that the cleanup is still
5318 // pending (and we should call the __dtor function).
5319 llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(dtorStub);
5320
5321 llvm::Value *NeedsDestruct = CGF.Builder.CreateIsNull(V, "needs_destruct");
5322
5323 llvm::BasicBlock *DestructCallBlock = CGF.createBasicBlock("destruct.call");
5324 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("destruct.end");
5325
5326 // Check if unatexit returns a value of 0. If it does, jump to
5327 // DestructCallBlock, otherwise jump to EndBlock directly.
5328 CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
5329
5330 CGF.EmitBlock(DestructCallBlock);
5331
5332 // Emit the call to dtorStub.
5333 llvm::CallInst *CI = CGF.Builder.CreateCall(dtorStub);
5334
5335 // Make sure the call and the callee agree on calling convention.
5336 CI->setCallingConv(dtorStub->getCallingConv());
5337
5338 CGF.EmitBlock(EndBlock);
5339
5340 CGF.FinishFunction();
5341
5342 if (auto *IPA = D.getAttr<InitPriorityAttr>()) {
5343 CGM.AddCXXPrioritizedStermFinalizerEntry(StermFinalizer,
5344 IPA->getPriority());
5345 } else if (isTemplateInstantiation(D.getTemplateSpecializationKind()) ||
5346 getContext().GetGVALinkageForVariable(&D) == GVA_DiscardableODR) {
5347 // According to C++ [basic.start.init]p2, class template static data
5348 // members (i.e., implicitly or explicitly instantiated specializations)
5349 // have unordered initialization. As a consequence, we can put them into
5350 // their own llvm.global_dtors entry.
5351 CGM.AddCXXStermFinalizerToGlobalDtor(StermFinalizer, 65535);
5352 } else {
5353 CGM.AddCXXStermFinalizerEntry(StermFinalizer);
5354 }
5355 }