Coverage Report

Created: 2019-07-24 05:18

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