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