This repository was archived by the owner on Nov 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathMicrosoftCXXABI.cpp
2037 lines (1738 loc) · 83.3 KB
/
MicrosoftCXXABI.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
// The class in this file generates structures that follow the Microsoft
// Visual C++ ABI, which is actually not very well documented at all outside
// of Microsoft.
//
//===----------------------------------------------------------------------===//
#include "CGCXXABI.h"
#include "CGVTables.h"
#include "CodeGenModule.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/VTableBuilder.h"
#include "llvm/ADT/StringSet.h"
using namespace clang;
using namespace CodeGen;
namespace {
/// Holds all the vbtable globals for a given class.
struct VBTableGlobals {
const VPtrInfoVector *VBTables;
SmallVector<llvm::GlobalVariable *, 2> Globals;
};
class MicrosoftCXXABI : public CGCXXABI {
public:
MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
bool HasThisReturn(GlobalDecl GD) const;
bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
// Structures that are not C++03 PODs are always indirect.
return !RD->isPOD();
}
RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor()) {
llvm::Triple::ArchType Arch = CGM.getTarget().getTriple().getArch();
if (Arch == llvm::Triple::x86)
return RAA_DirectInMemory;
// On x64, pass non-trivial records indirectly.
// FIXME: Test other Windows architectures.
return RAA_Indirect;
}
return RAA_Default;
}
StringRef GetPureVirtualCallName() { return "_purecall"; }
// No known support for deleted functions in MSVC yet, so this choice is
// arbitrary.
StringRef GetDeletedVirtualCallName() { return "_purecall"; }
bool isInlineInitializedStaticDataMemberLinkOnce() { return true; }
llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
llvm::Value *ptr,
QualType type);
llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
llvm::Value *This,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl);
void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
CXXCtorType Type,
CanQualType &ResTy,
SmallVectorImpl<CanQualType> &ArgTys);
llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
const CXXRecordDecl *RD);
void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
const CXXRecordDecl *RD);
void EmitCXXConstructors(const CXXConstructorDecl *D);
// Background on MSVC destructors
// ==============================
//
// Both Itanium and MSVC ABIs have destructor variants. The variant names
// roughly correspond in the following way:
// Itanium Microsoft
// Base -> no name, just ~Class
// Complete -> vbase destructor
// Deleting -> scalar deleting destructor
// vector deleting destructor
//
// The base and complete destructors are the same as in Itanium, although the
// complete destructor does not accept a VTT parameter when there are virtual
// bases. A separate mechanism involving vtordisps is used to ensure that
// virtual methods of destroyed subobjects are not called.
//
// The deleting destructors accept an i32 bitfield as a second parameter. Bit
// 1 indicates if the memory should be deleted. Bit 2 indicates if the this
// pointer points to an array. The scalar deleting destructor assumes that
// bit 2 is zero, and therefore does not contain a loop.
//
// For virtual destructors, only one entry is reserved in the vftable, and it
// always points to the vector deleting destructor. The vector deleting
// destructor is the most general, so it can be used to destroy objects in
// place, delete single heap objects, or delete arrays.
//
// A TU defining a non-inline destructor is only guaranteed to emit a base
// destructor, and all of the other variants are emitted on an as-needed basis
// in COMDATs. Because a non-base destructor can be emitted in a TU that
// lacks a definition for the destructor, non-base destructors must always
// delegate to or alias the base destructor.
void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
CXXDtorType Type,
CanQualType &ResTy,
SmallVectorImpl<CanQualType> &ArgTys);
/// Non-base dtors should be emitted as delegating thunks in this ABI.
bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
CXXDtorType DT) const {
return DT != Dtor_Base;
}
void EmitCXXDestructors(const CXXDestructorDecl *D);
const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
MD = MD->getCanonicalDecl();
if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
MicrosoftVTableContext::MethodVFTableLocation ML =
CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
// The vbases might be ordered differently in the final overrider object
// and the complete object, so the "this" argument may sometimes point to
// memory that has no particular type (e.g. past the complete object).
// In this case, we just use a generic pointer type.
// FIXME: might want to have a more precise type in the non-virtual
// multiple inheritance case.
if (ML.VBase || !ML.VFPtrOffset.isZero())
return 0;
}
return MD->getParent();
}
llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
GlobalDecl GD,
llvm::Value *This);
void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
FunctionArgList &Params);
llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
const CXXConstructorDecl *D,
CXXCtorType Type, bool ForVirtualBase,
bool Delegating, CallArgList &Args);
void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
CXXDtorType Type, bool ForVirtualBase,
bool Delegating, llvm::Value *This);
void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
llvm::Value *getVTableAddressPointInStructor(
CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
BaseSubobject Base, const CXXRecordDecl *NearestVBase,
bool &NeedsVirtualOffset);
llvm::Constant *
getVTableAddressPointForConstExpr(BaseSubobject Base,
const CXXRecordDecl *VTableClass);
llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
CharUnits VPtrOffset);
llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
llvm::Value *This, llvm::Type *Ty);
void EmitVirtualDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *Dtor,
CXXDtorType DtorType, SourceLocation CallLoc,
llvm::Value *This);
void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
CallArgList &CallArgs) {
assert(GD.getDtorType() == Dtor_Deleting &&
"Only deleting destructor thunks are available in this ABI");
CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
CGM.getContext().IntTy);
}
void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
llvm::GlobalVariable *
getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
llvm::GlobalVariable::LinkageTypes Linkage);
void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
llvm::GlobalVariable *GV) const;
void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
}
llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
const ThisAdjustment &TA);
llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
const ReturnAdjustment &RA);
void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
llvm::GlobalVariable *DeclPtr,
bool PerformInit);
// ==== Notes on array cookies =========
//
// MSVC seems to only use cookies when the class has a destructor; a
// two-argument usual array deallocation function isn't sufficient.
//
// For example, this code prints "100" and "1":
// struct A {
// char x;
// void *operator new[](size_t sz) {
// printf("%u\n", sz);
// return malloc(sz);
// }
// void operator delete[](void *p, size_t sz) {
// printf("%u\n", sz);
// free(p);
// }
// };
// int main() {
// A *p = new A[100];
// delete[] p;
// }
// Whereas it prints "104" and "104" if you give A a destructor.
bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
bool requiresArrayCookie(const CXXNewExpr *expr);
CharUnits getArrayCookieSizeImpl(QualType type);
llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
llvm::Value *NewPtr,
llvm::Value *NumElements,
const CXXNewExpr *expr,
QualType ElementType);
llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
llvm::Value *allocPtr,
CharUnits cookieSize);
private:
MicrosoftMangleContext &getMangleContext() {
return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
}
llvm::Constant *getZeroInt() {
return llvm::ConstantInt::get(CGM.IntTy, 0);
}
llvm::Constant *getAllOnesInt() {
return llvm::Constant::getAllOnesValue(CGM.IntTy);
}
llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
return C ? C : getZeroInt();
}
llvm::Value *getValueOrZeroInt(llvm::Value *C) {
return C ? C : getZeroInt();
}
void
GetNullMemberPointerFields(const MemberPointerType *MPT,
llvm::SmallVectorImpl<llvm::Constant *> &fields);
/// \brief Shared code for virtual base adjustment. Returns the offset from
/// the vbptr to the virtual base. Optionally returns the address of the
/// vbptr itself.
llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
llvm::Value *Base,
llvm::Value *VBPtrOffset,
llvm::Value *VBTableOffset,
llvm::Value **VBPtr = 0);
llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
llvm::Value *Base,
int32_t VBPtrOffset,
int32_t VBTableOffset,
llvm::Value **VBPtr = 0) {
llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
*VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
}
/// \brief Performs a full virtual base adjustment. Used to dereference
/// pointers to members of virtual bases.
llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
const CXXRecordDecl *RD, llvm::Value *Base,
llvm::Value *VirtualBaseAdjustmentOffset,
llvm::Value *VBPtrOffset /* optional */);
/// \brief Emits a full member pointer with the fields common to data and
/// function member pointers.
llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
bool IsMemberFunction,
const CXXRecordDecl *RD,
CharUnits NonVirtualBaseAdjustment);
llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
const CXXMethodDecl *MD,
CharUnits NonVirtualBaseAdjustment);
bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
llvm::Constant *MP);
/// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
/// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
/// \brief Generate a thunk for calling a virtual member function MD.
llvm::Function *EmitVirtualMemPtrThunk(
const CXXMethodDecl *MD,
const MicrosoftVTableContext::MethodVFTableLocation &ML);
public:
virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
virtual bool isZeroInitializable(const MemberPointerType *MPT);
virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
CharUnits offset);
virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
llvm::Value *L,
llvm::Value *R,
const MemberPointerType *MPT,
bool Inequality);
virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
llvm::Value *MemPtr,
const MemberPointerType *MPT);
virtual llvm::Value *
EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
llvm::Value *Base, llvm::Value *MemPtr,
const MemberPointerType *MPT);
virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
const CastExpr *E,
llvm::Value *Src);
virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
llvm::Constant *Src);
virtual llvm::Value *
EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
llvm::Value *&This, llvm::Value *MemPtr,
const MemberPointerType *MPT);
private:
typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
/// \brief All the vftables that have been referenced.
VFTablesMapTy VFTablesMap;
/// \brief This set holds the record decls we've deferred vtable emission for.
llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
/// \brief All the vbtables which have been referenced.
llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
/// Info on the global variable used to guard initialization of static locals.
/// The BitIndex field is only used for externally invisible declarations.
struct GuardInfo {
GuardInfo() : Guard(0), BitIndex(0) {}
llvm::GlobalVariable *Guard;
unsigned BitIndex;
};
/// Map from DeclContext to the current guard variable. We assume that the
/// AST is visited in source code order.
llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
};
}
llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
llvm::Value *ptr,
QualType type) {
// FIXME: implement
return ptr;
}
llvm::Value *
MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
llvm::Value *This,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) {
int64_t VBPtrChars =
getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
CharUnits VBTableChars =
IntSize *
CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
llvm::Value *VBTableOffset =
llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
llvm::Value *VBPtrToNewBase =
GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
VBPtrToNewBase =
CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
}
bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
return isa<CXXConstructorDecl>(GD.getDecl());
}
void MicrosoftCXXABI::BuildConstructorSignature(
const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy,
SmallVectorImpl<CanQualType> &ArgTys) {
// All parameters are already in place except is_most_derived, which goes
// after 'this' if it's variadic and last if it's not.
const CXXRecordDecl *Class = Ctor->getParent();
const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>();
if (Class->getNumVBases()) {
if (FPT->isVariadic())
ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
else
ArgTys.push_back(CGM.getContext().IntTy);
}
}
llvm::BasicBlock *
MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
const CXXRecordDecl *RD) {
llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
assert(IsMostDerivedClass &&
"ctor for a class with virtual bases must have an implicit parameter");
llvm::Value *IsCompleteObject =
CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
CGF.Builder.CreateCondBr(IsCompleteObject,
CallVbaseCtorsBB, SkipVbaseCtorsBB);
CGF.EmitBlock(CallVbaseCtorsBB);
// Fill in the vbtable pointers here.
EmitVBPtrStores(CGF, RD);
// CGF will put the base ctor calls in this basic block for us later.
return SkipVbaseCtorsBB;
}
void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
CodeGenFunction &CGF, const CXXRecordDecl *RD) {
// In most cases, an override for a vbase virtual method can adjust
// the "this" parameter by applying a constant offset.
// However, this is not enough while a constructor or a destructor of some
// class X is being executed if all the following conditions are met:
// - X has virtual bases, (1)
// - X overrides a virtual method M of a vbase Y, (2)
// - X itself is a vbase of the most derived class.
//
// If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
// which holds the extra amount of "this" adjustment we must do when we use
// the X vftables (i.e. during X ctor or dtor).
// Outside the ctors and dtors, the values of vtorDisps are zero.
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
CGBuilderTy &Builder = CGF.Builder;
unsigned AS =
cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
llvm::Value *Int8This = 0; // Initialize lazily.
for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
I != E; ++I) {
if (!I->second.hasVtorDisp())
continue;
llvm::Value *VBaseOffset =
GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
// FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
// just to Trunc back immediately.
VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
uint64_t ConstantVBaseOffset =
Layout.getVBaseClassOffset(I->first).getQuantity();
// vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
llvm::Value *VtorDispValue = Builder.CreateSub(
VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
"vtordisp.value");
if (!Int8This)
Int8This = Builder.CreateBitCast(getThisValue(CGF),
CGF.Int8Ty->getPointerTo(AS));
llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
// vtorDisp is always the 32-bits before the vbase in the class layout.
VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
VtorDispPtr = Builder.CreateBitCast(
VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
Builder.CreateStore(VtorDispValue, VtorDispPtr);
}
}
void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
// There's only one constructor type in this ABI.
CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
}
void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
const CXXRecordDecl *RD) {
llvm::Value *ThisInt8Ptr =
CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
llvm::GlobalVariable *GV = VBGlobals.Globals[I];
const ASTRecordLayout &SubobjectLayout =
CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr);
CharUnits Offs = VBT->NonVirtualOffset;
Offs += SubobjectLayout.getVBPtrOffset();
if (VBT->getVBaseWithVPtr())
Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
llvm::Value *VBPtr =
CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0),
"vbptr." + VBT->ReusingBase->getName());
CGF.Builder.CreateStore(GV, VBPtr);
}
}
void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
CXXDtorType Type,
CanQualType &ResTy,
SmallVectorImpl<CanQualType> &ArgTys) {
// 'this' is already in place
// TODO: 'for base' flag
if (Type == Dtor_Deleting) {
// The scalar deleting destructor takes an implicit int parameter.
ArgTys.push_back(CGM.getContext().IntTy);
}
}
void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
// The TU defining a dtor is only guaranteed to emit a base destructor. All
// other destructor variants are delegating thunks.
CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
}
llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
GD = GD.getCanonicalDecl();
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
// FIXME: consider splitting the vdtor vs regular method code into two
// functions.
GlobalDecl LookupGD = GD;
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
// Complete dtors take a pointer to the complete object,
// thus don't need adjustment.
if (GD.getDtorType() == Dtor_Complete)
return This;
// There's only Dtor_Deleting in vftable but it shares the this adjustment
// with the base one, so look up the deleting one instead.
LookupGD = GlobalDecl(DD, Dtor_Deleting);
}
MicrosoftVTableContext::MethodVFTableLocation ML =
CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
CharUnits StaticOffset = ML.VFPtrOffset;
// Base destructors expect 'this' to point to the beginning of the base
// subobject, not the first vfptr that happens to contain the virtual dtor.
// However, we still need to apply the virtual base adjustment.
if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
StaticOffset = CharUnits::Zero();
if (ML.VBase) {
bool AvoidVirtualOffset = false;
if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
// A base destructor can only be called from a complete destructor of the
// same record type or another destructor of a more derived type;
// or a constructor of the same record type if an exception is thrown.
assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
const CXXRecordDecl *CurRD =
cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
if (MD->getParent() == CurRD) {
if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
assert(CGF.CurGD.getDtorType() == Dtor_Complete);
if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
assert(CGF.CurGD.getCtorType() == Ctor_Complete);
// We're calling the main base dtor from a complete structor,
// so we know the "this" offset statically.
AvoidVirtualOffset = true;
} else {
// Let's see if we try to call a destructor of a non-virtual base.
for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
E = CurRD->bases_end(); I != E; ++I) {
if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
continue;
// If we call a base destructor for a non-virtual base, we statically
// know where it expects the vfptr and "this" to be.
// The total offset should reflect the adjustment done by
// adjustThisParameterInVirtualFunctionPrologue().
AvoidVirtualOffset = true;
break;
}
}
}
if (AvoidVirtualOffset) {
const ASTRecordLayout &Layout =
CGF.getContext().getASTRecordLayout(MD->getParent());
StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
} else {
This = CGF.Builder.CreateBitCast(This, charPtrTy);
llvm::Value *VBaseOffset =
GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
}
}
if (!StaticOffset.isZero()) {
assert(StaticOffset.isPositive());
This = CGF.Builder.CreateBitCast(This, charPtrTy);
if (ML.VBase) {
// Non-virtual adjustment might result in a pointer outside the allocated
// object, e.g. if the final overrider class is laid out after the virtual
// base that declares a method in the most derived class.
// FIXME: Update the code that emits this adjustment in thunks prologues.
This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
} else {
This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
StaticOffset.getQuantity());
}
}
return This;
}
static bool IsDeletingDtor(GlobalDecl GD) {
const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
if (isa<CXXDestructorDecl>(MD)) {
return GD.getDtorType() == Dtor_Deleting;
}
return false;
}
void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
QualType &ResTy,
FunctionArgList &Params) {
ASTContext &Context = getContext();
const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
ImplicitParamDecl *IsMostDerived
= ImplicitParamDecl::Create(Context, 0,
CGF.CurGD.getDecl()->getLocation(),
&Context.Idents.get("is_most_derived"),
Context.IntTy);
// The 'most_derived' parameter goes second if the ctor is variadic and last
// if it's not. Dtors can't be variadic.
const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
if (FPT->isVariadic())
Params.insert(Params.begin() + 1, IsMostDerived);
else
Params.push_back(IsMostDerived);
getStructorImplicitParamDecl(CGF) = IsMostDerived;
} else if (IsDeletingDtor(CGF.CurGD)) {
ImplicitParamDecl *ShouldDelete
= ImplicitParamDecl::Create(Context, 0,
CGF.CurGD.getDecl()->getLocation(),
&Context.Idents.get("should_call_delete"),
Context.IntTy);
Params.push_back(ShouldDelete);
getStructorImplicitParamDecl(CGF) = ShouldDelete;
}
}
llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
GD = GD.getCanonicalDecl();
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
GlobalDecl LookupGD = GD;
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
// Complete destructors take a pointer to the complete object as a
// parameter, thus don't need this adjustment.
if (GD.getDtorType() == Dtor_Complete)
return This;
// There's no Dtor_Base in vftable but it shares the this adjustment with
// the deleting one, so look it up instead.
LookupGD = GlobalDecl(DD, Dtor_Deleting);
}
// In this ABI, every virtual function takes a pointer to one of the
// subobjects that first defines it as the 'this' parameter, rather than a
// pointer to the final overrider subobject. Thus, we need to adjust it back
// to the final overrider subobject before use.
// See comments in the MicrosoftVFTableContext implementation for the details.
MicrosoftVTableContext::MethodVFTableLocation ML =
CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
CharUnits Adjustment = ML.VFPtrOffset;
// Normal virtual instance methods need to adjust from the vfptr that first
// defined the virtual method to the virtual base subobject, but destructors
// do not. The vector deleting destructor thunk applies this adjustment for
// us if necessary.
if (isa<CXXDestructorDecl>(MD))
Adjustment = CharUnits::Zero();
if (ML.VBase) {
const ASTRecordLayout &DerivedLayout =
CGF.getContext().getASTRecordLayout(MD->getParent());
Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
}
if (Adjustment.isZero())
return This;
unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
*thisTy = This->getType();
This = CGF.Builder.CreateBitCast(This, charPtrTy);
assert(Adjustment.isPositive());
This =
CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
return CGF.Builder.CreateBitCast(This, thisTy);
}
void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
EmitThisParam(CGF);
/// If this is a function that the ABI specifies returns 'this', initialize
/// the return slot to 'this' at the start of the function.
///
/// Unlike the setting of return types, this is done within the ABI
/// implementation instead of by clients of CGCXXABI because:
/// 1) getThisValue is currently protected
/// 2) in theory, an ABI could implement 'this' returns some other way;
/// HasThisReturn only specifies a contract, not the implementation
if (HasThisReturn(CGF.CurGD))
CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
assert(getStructorImplicitParamDecl(CGF) &&
"no implicit parameter for a constructor with virtual bases?");
getStructorImplicitParamValue(CGF)
= CGF.Builder.CreateLoad(
CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
"is_most_derived");
}
if (IsDeletingDtor(CGF.CurGD)) {
assert(getStructorImplicitParamDecl(CGF) &&
"no implicit parameter for a deleting destructor?");
getStructorImplicitParamValue(CGF)
= CGF.Builder.CreateLoad(
CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
"should_call_delete");
}
}
unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
bool ForVirtualBase, bool Delegating, CallArgList &Args) {
assert(Type == Ctor_Complete || Type == Ctor_Base);
// Check if we need a 'most_derived' parameter.
if (!D->getParent()->getNumVBases())
return 0;
// Add the 'most_derived' argument second if we are variadic or last if not.
const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
llvm::Value *MostDerivedArg =
llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
RValue RV = RValue::get(MostDerivedArg);
if (MostDerivedArg) {
if (FPT->isVariadic())
Args.insert(Args.begin() + 1,
CallArg(RV, getContext().IntTy, /*needscopy=*/false));
else
Args.add(RV, getContext().IntTy);
}
return 1; // Added one arg.
}
void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *DD,
CXXDtorType Type, bool ForVirtualBase,
bool Delegating, llvm::Value *This) {
llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
if (DD->isVirtual())
This = adjustThisArgumentForVirtualCall(CGF, GlobalDecl(DD, Type), This);
// FIXME: Provide a source location here.
CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
/*ImplicitParam=*/0, /*ImplicitParamTy=*/QualType(), 0, 0);
}
void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
const CXXRecordDecl *RD) {
MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
VPtrInfoVector VFPtrs = VFTContext.getVFPtrOffsets(RD);
llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
for (VPtrInfoVector::iterator I = VFPtrs.begin(), E = VFPtrs.end(); I != E;
++I) {
llvm::GlobalVariable *VTable = getAddrOfVTable(RD, (*I)->FullOffsetInMDC);
if (VTable->hasInitializer())
continue;
const VTableLayout &VTLayout =
VFTContext.getVFTableLayout(RD, (*I)->FullOffsetInMDC);
llvm::Constant *Init = CGVT.CreateVTableInitializer(
RD, VTLayout.vtable_component_begin(),
VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
VTLayout.getNumVTableThunks());
VTable->setInitializer(Init);
VTable->setLinkage(Linkage);
CGM.setGlobalVisibility(VTable, RD);
}
}
llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
NeedsVirtualOffset = (NearestVBase != 0);
llvm::Value *VTableAddressPoint =
getAddrOfVTable(VTableClass, Base.getBaseOffset());
if (!VTableAddressPoint) {
assert(Base.getBase()->getNumVBases() &&
!CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
}
return VTableAddressPoint;
}
static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
SmallString<256> &Name) {
llvm::raw_svector_ostream Out(Name);
MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
}
llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
BaseSubobject Base, const CXXRecordDecl *VTableClass) {
llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
assert(VTable && "Couldn't find a vftable for the given base?");
return VTable;
}
llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
CharUnits VPtrOffset) {
// getAddrOfVTable may return 0 if asked to get an address of a vtable which
// shouldn't be used in the given record type. We want to cache this result in
// VFTablesMap, thus a simple zero check is not sufficient.
VFTableIdTy ID(RD, VPtrOffset);
VFTablesMapTy::iterator I;
bool Inserted;
std::tie(I, Inserted) = VFTablesMap.insert(
std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
if (!Inserted)
return I->second;
llvm::GlobalVariable *&VTable = I->second;
MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
if (DeferredVFTables.insert(RD)) {
// We haven't processed this record type before.
// Queue up this v-table for possible deferred emission.
CGM.addDeferredVTable(RD);
#ifndef NDEBUG
// Create all the vftables at once in order to make sure each vftable has
// a unique mangled name.
llvm::StringSet<> ObservedMangledNames;
for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
SmallString<256> Name;
mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
if (!ObservedMangledNames.insert(Name.str()))
llvm_unreachable("Already saw this mangling before?");
}
#endif
}
for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset)
continue;
llvm::ArrayType *ArrayType = llvm::ArrayType::get(
CGM.Int8PtrTy,
VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC)
.getNumVTableComponents());
SmallString<256> Name;
mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
VTable->setUnnamedAddr(true);
break;
}
return VTable;
}
llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
GlobalDecl GD,
llvm::Value *This,
llvm::Type *Ty) {
GD = GD.getCanonicalDecl();
CGBuilderTy &Builder = CGF.Builder;
Ty = Ty->getPointerTo()->getPointerTo();
llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
MicrosoftVTableContext::MethodVFTableLocation ML =
CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
llvm::Value *VFuncPtr =
Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
return Builder.CreateLoad(VFuncPtr);
}
void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *Dtor,
CXXDtorType DtorType,
SourceLocation CallLoc,
llvm::Value *This) {
assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
// We have only one destructor in the vftable but can get both behaviors
// by passing an implicit int parameter.
GlobalDecl GD(Dtor, Dtor_Deleting);
const CGFunctionInfo *FInfo =
&CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
ASTContext &Context = CGF.getContext();
llvm::Value *ImplicitParam =
llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
DtorType == Dtor_Deleting);
This = adjustThisArgumentForVirtualCall(CGF, GD, This);
CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
ImplicitParam, Context.IntTy, 0, 0);
}
const VBTableGlobals &
MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
// At this layer, we can key the cache off of a single class, which is much
// easier than caching each vbtable individually.
llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
bool Added;
std::tie(Entry, Added) =
VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
VBTableGlobals &VBGlobals = Entry->second;