Coverage Report

Created: 2022-01-18 06:27

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