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