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