Coverage Report

Created: 2021-09-21 08:58

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