forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPathogenExtensions.cpp
2025 lines (1739 loc) · 75.5 KB
/
PathogenExtensions.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
//===----------------------------------------------------------------------===//
//
// Pathogen Studios extensions to libclang
// Provides functions for reading the memory and vtable layout of a type
// (Among other things)
//
// Useful references:
// * lib/AST/RecordLayoutBuilder.cpp (Used for -fdump-record-layouts)
// * lib/AST/VTableBuilder.cpp (Used for -fdump-vtable-layouts)
//
//===----------------------------------------------------------------------===//
// clang-format off
#include "CIndexer.h"
#include "CXCursor.h"
#include "CXSourceLocation.h"
#include "CXString.h"
#include "CXTranslationUnit.h"
#include "CXType.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/Type.h"
#include "clang/AST/VTableBuilder.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/PreprocessingRecord.h"
#include "clang/Sema/Sema.h"
#include "llvm/IR/LLVMContext.h"
// These APIs are technically private to the CodeGen module
#include "../lib/CodeGen/CodeGenModule.h"
#include "../lib/CodeGen/CGCXXABI.h"
#include <limits>
#include <memory>
using namespace clang;
using ABIArgInfo = CodeGen::ABIArgInfo;
#define PATHOGEN_EXPORT extern "C" CINDEX_LINKAGE
// This is incomplete but good enough for our purposes
#define PATHOGEN_FLAGS(ENUM_TYPE) \
inline ENUM_TYPE operator|(ENUM_TYPE a, ENUM_TYPE b) \
{ \
return static_cast<ENUM_TYPE>(static_cast<std::underlying_type<ENUM_TYPE>::type>(a) | static_cast<std::underlying_type<ENUM_TYPE>::type>(b)); \
} \
\
inline ENUM_TYPE& operator|=(ENUM_TYPE& a, ENUM_TYPE b) \
{ \
a = a | b; \
return a; \
}
typedef unsigned char interop_bool;
enum class PathogenRecordFieldKind : int32_t
{
Normal,
VTablePtr,
NonVirtualBase,
VirtualBaseTablePtr, //!< Only appears in Microsoft ABI
VTorDisp, //!< Only appears in Microsoft ABI
VirtualBase,
};
struct PathogenRecordField
{
PathogenRecordFieldKind Kind;
int64_t Offset;
PathogenRecordField* NextField;
CXString Name;
//! When Kind == Normal, this is the type of the field
//! When Kind == NonVirtualBase, VTorDisp, or VirtualBase, this is the type of the base
//! When Kind == VTablePtr, this is void**
//! When Kind == VirtualBaseTablePtr, this is void*
CXType Type;
// Only relevant when Kind == Normal
CXCursor FieldDeclaration;
interop_bool IsBitField;
// Only relevant when IsBitField == true
unsigned int BitFieldStart;
unsigned int BitFieldWidth;
// Only relevant when Kind == NonVirtualBase or VirtialBase
interop_bool IsPrimaryBase;
};
enum class PathogenVTableEntryKind : int32_t
{
VCallOffset,
VBaseOffset,
OffsetToTop,
RTTI,
FunctionPointer,
CompleteDestructorPointer,
DeletingDestructorPointer,
UnusedFunctionPointer,
};
// We verify the enums match manually because we need a stable definition here to reflect on the C# side of things.
#define verify_vtable_entry_kind(PATHOGEN_KIND, CLANG_KIND) static_assert((int)(PathogenVTableEntryKind::PATHOGEN_KIND) == (int)(VTableComponent::CLANG_KIND), #PATHOGEN_KIND " must match " #CLANG_KIND);
verify_vtable_entry_kind(VCallOffset, CK_VCallOffset)
verify_vtable_entry_kind(VBaseOffset, CK_VBaseOffset)
verify_vtable_entry_kind(OffsetToTop, CK_OffsetToTop)
verify_vtable_entry_kind(RTTI, CK_RTTI)
verify_vtable_entry_kind(FunctionPointer, CK_FunctionPointer)
verify_vtable_entry_kind(CompleteDestructorPointer, CK_CompleteDtorPointer)
verify_vtable_entry_kind(DeletingDestructorPointer, CK_DeletingDtorPointer)
verify_vtable_entry_kind(UnusedFunctionPointer, CK_UnusedFunctionPointer)
//TODO: It'd be nice to know which entry of the table corresponds with a vtable pointer in the associated record.
// Unfortunately this is non-trivial to get. For simple inheritance trees with no multi-inheritance this should simply the first entry after the RTTI pointer.
// Clang will dump this with -fdump-vtable-layouts on Itanium platforms. Ctrl+F for "vtable address --" in VTableBuilder.cpp
// This is also hard to model with the way we present record layouts since bases are referenced rather than embedded.
struct PathogenVTableEntry
{
PathogenVTableEntryKind Kind;
//! Only relevant when Kind == FunctionPointer, CompleteDestructorPointer, DeletingDestructorPointer, or UnusedFunctionPointer
CXCursor MethodDeclaration;
//! Only relevant when Kind == RTTI
CXCursor RttiType;
//! Only relevant when Kind == VCallOffset, VBaseOffset, or OffsetToTop
int64_t Offset;
PathogenVTableEntry(CXTranslationUnit translationUnit, const VTableComponent& component)
{
Kind = (PathogenVTableEntryKind)component.getKind();
MethodDeclaration = {};
RttiType = {};
Offset = 0;
switch (Kind)
{
case PathogenVTableEntryKind::VCallOffset:
Offset = component.getVCallOffset().getQuantity();
break;
case PathogenVTableEntryKind::VBaseOffset:
Offset = component.getVBaseOffset().getQuantity();
break;
case PathogenVTableEntryKind::OffsetToTop:
Offset = component.getOffsetToTop().getQuantity();
break;
case PathogenVTableEntryKind::RTTI:
RttiType = cxcursor::MakeCXCursor(component.getRTTIDecl(), translationUnit);
break;
case PathogenVTableEntryKind::FunctionPointer:
case PathogenVTableEntryKind::CompleteDestructorPointer:
case PathogenVTableEntryKind::DeletingDestructorPointer:
case PathogenVTableEntryKind::UnusedFunctionPointer:
MethodDeclaration = cxcursor::MakeCXCursor(component.getFunctionDecl(), translationUnit);
break;
}
}
};
struct PathogenVTable
{
int32_t EntryCount;
PathogenVTableEntry* Entries;
//! Only relevant on Microsoft ABI
PathogenVTable* NextVTable;
PathogenVTable(CXTranslationUnit translationUnit, const VTableLayout& layout)
{
NextVTable = nullptr;
ArrayRef<VTableComponent> components = layout.vtable_components();
EntryCount = (int32_t)components.size();
Entries = (PathogenVTableEntry*)malloc(sizeof(PathogenVTableEntry) * EntryCount);
for (int32_t i = 0; i < EntryCount; i++)
{
Entries[i] = PathogenVTableEntry(translationUnit, components[i]);
}
}
~PathogenVTable()
{
free(Entries);
}
};
struct PathogenRecordLayout
{
PathogenRecordField* FirstField;
PathogenVTable* FirstVTable;
int64_t Size;
int64_t Alignment;
// For C++ records only
interop_bool IsCppRecord;
int64_t NonVirtualSize;
int64_t NonVirtualAlignment;
PathogenRecordField* AddField(PathogenRecordFieldKind kind, int64_t offset, CXString name, CXType type)
{
// Find the insertion point for the field
PathogenRecordField** insertPoint = &FirstField;
while (*insertPoint != nullptr && (*insertPoint)->Offset <= offset)
{ insertPoint = &((*insertPoint)->NextField); }
// Insert the new field
PathogenRecordField* field = new PathogenRecordField();
field->Kind = kind;
field->Offset = offset;
field->Name = name;
field->Type = type;
field->NextField = *insertPoint;
*insertPoint = field;
return field;
}
PathogenRecordField* AddField(PathogenRecordFieldKind kind, int64_t offset, CXTranslationUnit translationUnit, const FieldDecl& field)
{
CXType type = cxtype::MakeCXType(field.getType(), translationUnit);
PathogenRecordField* ret = AddField(kind, offset, cxstring::createDup(field.getName()), type);
ret->FieldDeclaration = cxcursor::MakeCXCursor(&field, translationUnit);
return ret;
}
PathogenVTable* AddVTableLayout(CXTranslationUnit translationUnit, const VTableLayout& layout)
{
// Find insertion point for the new table
PathogenVTable** insertPoint = &FirstVTable;
while (*insertPoint != nullptr)
{ insertPoint = &((*insertPoint)->NextVTable); }
// Insert the new table
PathogenVTable* vTable = new PathogenVTable(translationUnit, layout);
vTable->NextVTable = *insertPoint;
*insertPoint = vTable;
return vTable;
}
~PathogenRecordLayout()
{
// Delete all fields
for (PathogenRecordField* field = FirstField; field;)
{
PathogenRecordField* nextField = field->NextField;
clang_disposeString(field->Name);
delete field;
field = nextField;
}
// Delete all VTables
for (PathogenVTable* vTable = FirstVTable; vTable;)
{
PathogenVTable* nextVTable = vTable->NextVTable;
delete vTable;
vTable = nextVTable;
}
}
};
static bool IsMsLayout(const ASTContext& context)
{
return context.getTargetInfo().getCXXABI().isMicrosoft();
}
PATHOGEN_EXPORT PathogenRecordLayout* pathogen_GetRecordLayout(CXCursor cursor)
{
// The cursor must be a declaration
if (!clang_isDeclaration(cursor.kind))
{
return nullptr;
}
// Get the record declaration
const Decl* declaration = cxcursor::getCursorDecl(cursor);
const RecordDecl* record = dyn_cast_or_null<RecordDecl>(declaration);
// The cursor must be a record declaration
if (record == nullptr)
{
return nullptr;
}
// The cursor must have a definition (IE: it can't be a forward-declaration.)
if (record->getDefinition() == nullptr)
{
return nullptr;
}
// Get the AST context
ASTContext& context = cxcursor::getCursorContext(cursor);
// Get the translation unit
CXTranslationUnit translationUnit = clang_Cursor_getTranslationUnit(cursor);
// Get the void* and void** types
CXType voidPointerType = cxtype::MakeCXType(context.VoidPtrTy, translationUnit);
CXType voidPointerPointerType = cxtype::MakeCXType(context.getPointerType(context.VoidPtrTy), translationUnit);
// Get the record layout
const ASTRecordLayout& layout = context.getASTRecordLayout(record);
// Get the C++ record if applicable
const CXXRecordDecl* cxxRecord = dyn_cast<CXXRecordDecl>(record);
// Create the record layout
PathogenRecordLayout* ret = new PathogenRecordLayout();
ret->Size = layout.getSize().getQuantity();
ret->Alignment = layout.getAlignment().getQuantity();
if (cxxRecord)
{
ret->IsCppRecord = true;
ret->NonVirtualSize = layout.getNonVirtualSize().getQuantity();
ret->NonVirtualAlignment = layout.getNonVirtualAlignment().getQuantity();
}
// C++-specific fields
if (cxxRecord)
{
const CXXRecordDecl* primaryBase = layout.getPrimaryBase();
bool hasOwnVFPtr = layout.hasOwnVFPtr();
bool hasOwnVBPtr = layout.hasOwnVBPtr();
// Add vtable pointer
if (cxxRecord->isDynamicClass() && !primaryBase && !IsMsLayout(context))
{
// Itanium-style VTable pointer
ret->AddField(PathogenRecordFieldKind::VTablePtr, 0, cxstring::createRef("vtable_pointer"), voidPointerPointerType);
}
else if (hasOwnVFPtr)
{
// Microsoft C++ ABI VFTable pointer
ret->AddField(PathogenRecordFieldKind::VTablePtr, 0, cxstring::createRef("vftable_pointer"), voidPointerPointerType);
}
// Add non-virtual bases
for (const CXXBaseSpecifier& base : cxxRecord->bases())
{
assert(!base.getType()->isDependentType() && "Cannot layout class with dependent bases.");
// Ignore virtual bases, they come up later.
if (base.isVirtual())
{ continue; }
QualType baseType = base.getType();
CXType cxType = cxtype::MakeCXType(baseType, translationUnit);
CXXRecordDecl* baseRecord = baseType->getAsCXXRecordDecl();
bool isPrimary = baseRecord == primaryBase;
int64_t offset = layout.getBaseClassOffset(baseRecord).getQuantity();
PathogenRecordField* field = ret->AddField(PathogenRecordFieldKind::NonVirtualBase, offset, cxstring::createRef(isPrimary ? "primary_base" : "base"), cxType);
field->IsPrimaryBase = isPrimary;
}
// Vbptr - Microsoft C++ ABI
if (hasOwnVBPtr)
{
ret->AddField(PathogenRecordFieldKind::VirtualBaseTablePtr, layout.getVBPtrOffset().getQuantity(), cxstring::createRef("vbtable_pointer"), voidPointerType);
}
}
// Add normal fields
uint64_t fieldIndex = 0;
for (RecordDecl::field_iterator it = record->field_begin(), end = record->field_end(); it != end; it++, fieldIndex++)
{
const FieldDecl& field = **it;
uint64_t offsetBits = layout.getFieldOffset(fieldIndex);
CharUnits offsetChars = context.toCharUnitsFromBits(offsetBits);
int64_t offset = offsetChars.getQuantity();
PathogenRecordField* pathogenField = ret->AddField(PathogenRecordFieldKind::Normal, offset, translationUnit, field);
// If the field is a bitfield, mark it as such.
// This relies on the fields being offset-sequential since AddField doesn't know about bitfields.
if (field.isBitField())
{
pathogenField->IsBitField = true;
pathogenField->BitFieldStart = offsetBits - context.toBits(offsetChars);
pathogenField->BitFieldWidth = field.getBitWidthValue(context);
}
}
// Add virtual bases
if (cxxRecord)
{
const ASTRecordLayout::VBaseOffsetsMapTy& vtorDisps = layout.getVBaseOffsetsMap();
const CXXRecordDecl* primaryBase = layout.getPrimaryBase();
for (const CXXBaseSpecifier& base : cxxRecord->vbases())
{
assert(base.isVirtual() && "Bases must be virtual.");
QualType baseType = base.getType();
CXType baseCxType = cxtype::MakeCXType(baseType, translationUnit);
const CXXRecordDecl* vbase = baseType->getAsCXXRecordDecl();
int64_t offset = layout.getVBaseClassOffset(vbase).getQuantity();
if (vtorDisps.find(vbase)->second.hasVtorDisp())
{
ret->AddField(PathogenRecordFieldKind::VTorDisp, offset - 4, cxstring::createRef("vtordisp"), baseCxType);
}
bool isPrimary = vbase == primaryBase;
PathogenRecordField* field = ret->AddField(PathogenRecordFieldKind::VirtualBase, offset, cxstring::createRef(isPrimary ? "primary_virtual_base" : "virtual_base"), baseCxType);
field->IsPrimaryBase = isPrimary;
}
}
// Add VTable layouts
if (cxxRecord && cxxRecord->isDynamicClass())
{
if (context.getVTableContext()->isMicrosoft())
{
MicrosoftVTableContext& vtableContext = *cast<MicrosoftVTableContext>(context.getVTableContext());
const VPtrInfoVector& offsets = vtableContext.getVFPtrOffsets(cxxRecord);
for (const std::unique_ptr<VPtrInfo>& offset : offsets)
{
const VTableLayout& layout = vtableContext.getVFTableLayout(cxxRecord, offset->FullOffsetInMDC);
ret->AddVTableLayout(translationUnit, layout);
}
}
else
{
ItaniumVTableContext& vtableContext = *cast<ItaniumVTableContext>(context.getVTableContext());
const VTableLayout& layout = vtableContext.getVTableLayout(cxxRecord);
ret->AddVTableLayout(translationUnit, layout);
}
}
return ret;
}
PATHOGEN_EXPORT void pathogen_DeleteRecordLayout(PathogenRecordLayout* layout)
{
delete layout;
}
//-------------------------------------------------------------------------------------------------
// Location helpers
//-------------------------------------------------------------------------------------------------
//! This is essentially the same as clang_Location_isFromMainFile, but it uses SourceManager::isInMainFile instead of SourceManager::isWrittenInMainFile
//! The libclang function suffers from some quirks, namely:
//! * It is possible for the start and end locations for a cursor's extent to have different values.
//! * Cursors which are the result of a macro expansion will be considered to be outside of the main file.
//! These quirks are not good for our usecase of rejecting cursors from included files, so we provide this alternative.
PATHOGEN_EXPORT interop_bool pathogen_Location_isFromMainFile(CXSourceLocation cxLocation)
{
const SourceLocation location = SourceLocation::getFromRawEncoding(cxLocation.int_data);
if (location.isInvalid())
{ return false; }
const SourceManager& sourceManager = *static_cast<const SourceManager*>(cxLocation.ptr_data[0]);
return sourceManager.isInMainFile(location);
}
//-------------------------------------------------------------------------------------------------
// Operator overload helpers
//-------------------------------------------------------------------------------------------------
enum class PathogenOperatorOverloadKind : int32_t
{
None,
New,
Delete,
Array_New,
Array_Delete,
Plus,
Minus,
Star,
Slash,
Percent,
Caret,
Amp,
Pipe,
Tilde,
Exclaim,
Equal,
Less,
Greater,
PlusEqual,
MinusEqual,
StarEqual,
SlashEqual,
PercentEqual,
CaretEqual,
AmpEqual,
PipeEqual,
LessLess,
GreaterGreater,
LessLessEqual,
GreaterGreaterEqual,
EqualEqual,
ExclaimEqual,
LessEqual,
GreaterEqual,
Spaceship,
AmpAmp,
PipePipe,
PlusPlus,
MinusMinus,
Comma,
ArrowStar,
Arrow,
Call,
Subscript,
Conditional,
Coawait,
Invalid
};
// We verify the enums match manually because we need a stable definition here to reflect on the C# side of things.
#define verify_operator_overload_kind(PATHOGEN_KIND, CLANG_KIND) static_assert((int)(PathogenOperatorOverloadKind::PATHOGEN_KIND) == (int)(CLANG_KIND), #PATHOGEN_KIND " must match " #CLANG_KIND);
verify_operator_overload_kind(None, OO_None)
verify_operator_overload_kind(New, OO_New)
verify_operator_overload_kind(Delete, OO_Delete)
verify_operator_overload_kind(Array_New, OO_Array_New)
verify_operator_overload_kind(Array_Delete, OO_Array_Delete)
verify_operator_overload_kind(Plus, OO_Plus)
verify_operator_overload_kind(Minus, OO_Minus)
verify_operator_overload_kind(Star, OO_Star)
verify_operator_overload_kind(Slash, OO_Slash)
verify_operator_overload_kind(Percent, OO_Percent)
verify_operator_overload_kind(Caret, OO_Caret)
verify_operator_overload_kind(Amp, OO_Amp)
verify_operator_overload_kind(Pipe, OO_Pipe)
verify_operator_overload_kind(Tilde, OO_Tilde)
verify_operator_overload_kind(Exclaim, OO_Exclaim)
verify_operator_overload_kind(Equal, OO_Equal)
verify_operator_overload_kind(Less, OO_Less)
verify_operator_overload_kind(Greater, OO_Greater)
verify_operator_overload_kind(PlusEqual, OO_PlusEqual)
verify_operator_overload_kind(MinusEqual, OO_MinusEqual)
verify_operator_overload_kind(StarEqual, OO_StarEqual)
verify_operator_overload_kind(SlashEqual, OO_SlashEqual)
verify_operator_overload_kind(PercentEqual, OO_PercentEqual)
verify_operator_overload_kind(CaretEqual, OO_CaretEqual)
verify_operator_overload_kind(AmpEqual, OO_AmpEqual)
verify_operator_overload_kind(PipeEqual, OO_PipeEqual)
verify_operator_overload_kind(LessLess, OO_LessLess)
verify_operator_overload_kind(GreaterGreater, OO_GreaterGreater)
verify_operator_overload_kind(LessLessEqual, OO_LessLessEqual)
verify_operator_overload_kind(GreaterGreaterEqual, OO_GreaterGreaterEqual)
verify_operator_overload_kind(EqualEqual, OO_EqualEqual)
verify_operator_overload_kind(ExclaimEqual, OO_ExclaimEqual)
verify_operator_overload_kind(LessEqual, OO_LessEqual)
verify_operator_overload_kind(GreaterEqual, OO_GreaterEqual)
verify_operator_overload_kind(Spaceship, OO_Spaceship)
verify_operator_overload_kind(AmpAmp, OO_AmpAmp)
verify_operator_overload_kind(PipePipe, OO_PipePipe)
verify_operator_overload_kind(PlusPlus, OO_PlusPlus)
verify_operator_overload_kind(MinusMinus, OO_MinusMinus)
verify_operator_overload_kind(Comma, OO_Comma)
verify_operator_overload_kind(ArrowStar, OO_ArrowStar)
verify_operator_overload_kind(Arrow, OO_Arrow)
verify_operator_overload_kind(Call, OO_Call)
verify_operator_overload_kind(Subscript, OO_Subscript)
verify_operator_overload_kind(Conditional, OO_Conditional)
verify_operator_overload_kind(Coawait, OO_Coawait)
verify_operator_overload_kind(Invalid, NUM_OVERLOADED_OPERATORS)
struct PathogenOperatorOverloadInfo
{
PathogenOperatorOverloadKind Kind;
const char* Name;
const char* Spelling;
interop_bool IsUnary;
interop_bool IsBinary;
interop_bool IsMemberOnly;
};
static PathogenOperatorOverloadInfo OperatorInformation[] =
{
{ PathogenOperatorOverloadKind::None, nullptr, nullptr, false, false, false }, // OO_None
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) { PathogenOperatorOverloadKind::Name, #Name, Spelling, Unary, Binary, MemberOnly },
#include "clang/Basic/OperatorKinds.def"
// This entry takes the slot for NUM_OVERLOADED_OPERATORS and is returned when an unexpected operator overload is encountered
{ PathogenOperatorOverloadKind::Invalid, nullptr, nullptr, false, false, false },
};
PATHOGEN_EXPORT PathogenOperatorOverloadInfo* pathogen_getOperatorOverloadInfo(CXCursor cursor)
{
// The cursor must be a declaration
if (!clang_isDeclaration(cursor.kind))
{
return nullptr;
}
// Get the function declaration
const Decl* declaration = cxcursor::getCursorDecl(cursor);
const FunctionDecl* function = dyn_cast_or_null<FunctionDecl>(declaration);
// The cursor must be a function declaration
if (function == nullptr)
{
return nullptr;
}
// Get the overloaded operator
OverloadedOperatorKind operatorKind = function->getOverloadedOperator();
// Ensure the operator kind is within bounds
if (operatorKind < 0 || operatorKind > NUM_OVERLOADED_OPERATORS)
{
// NUM_OVERLOADED_OPERATORS is used for the invalid kind slot.
operatorKind = NUM_OVERLOADED_OPERATORS;
}
// Return the operator information
return &OperatorInformation[operatorKind];
}
//-------------------------------------------------------------------------------------------------
// Record arg passing kind
//-------------------------------------------------------------------------------------------------
enum class PathogenArgPassingKind : int32_t
{
CanPassInRegisters,
CannotPassInRegisters,
CanNeverPassInRegisters,
Invalid
};
#define verify_arg_passing_kind(PATHOGEN_KIND, CLANG_KIND) static_assert((int)(PathogenArgPassingKind::PATHOGEN_KIND) == (int)(RecordArgPassingKind::CLANG_KIND), #PATHOGEN_KIND " must match " #CLANG_KIND);
verify_arg_passing_kind(CanPassInRegisters, CanPassInRegs)
verify_arg_passing_kind(CannotPassInRegisters, CannotPassInRegs)
verify_arg_passing_kind(CanNeverPassInRegisters, CanNeverPassInRegs)
PATHOGEN_EXPORT PathogenArgPassingKind pathogen_getArgPassingRestrictions(CXCursor cursor)
{
// The cursor must be a declaration
if (!clang_isDeclaration(cursor.kind))
{
return PathogenArgPassingKind::Invalid;
}
// Get the record declaration
const Decl* declaration = cxcursor::getCursorDecl(cursor);
const RecordDecl* record = dyn_cast_or_null<RecordDecl>(declaration);
// Return the value
return (PathogenArgPassingKind)record->getArgPassingRestrictions();
}
//-------------------------------------------------------------------------------------------------
// Computing the constant value an expression of a variable's initializer
//-------------------------------------------------------------------------------------------------
enum class PathogenConstantValueKind : int
{
Unknown,
NullPointer,
UnsignedInteger,
SignedInteger,
FloatingPoint,
String,
};
enum class PathogenStringConstantKind : int
{
Ascii,
//! Never actually used. We replace this with the more appropriate UTF equivalent with WideCharBit set instead.
WideChar,
Utf8,
Utf16,
Utf32,
//! When combined with one of the UTF values, indicates that the constant was originally a wchar_t string.
WideCharBit = 1 << 31,
};
PATHOGEN_FLAGS(PathogenStringConstantKind);
static_assert((int)PathogenStringConstantKind::Ascii == (int)CharacterLiteralKind::Ascii, "ASCII string kinds must match.");
static_assert((int)PathogenStringConstantKind::WideChar == (int)CharacterLiteralKind::Wide, "Wide character string kinds must match.");
static_assert((int)PathogenStringConstantKind::Utf8 == (int)CharacterLiteralKind::UTF8, "UTF8 string kinds must match.");
static_assert((int)PathogenStringConstantKind::Utf16 == (int)CharacterLiteralKind::UTF16, "UTF16 string kinds must match.");
static_assert((int)PathogenStringConstantKind::Utf32 == (int)CharacterLiteralKind::UTF32, "UTF32 string kinds must match.");
struct PathogenConstantString
{
uint64_t SizeBytes;
unsigned char FirstByte;
};
struct PathogenConstantValueInfo
{
bool HasSideEffects;
bool HasUndefinedBehavior;
PathogenConstantValueKind Kind;
//! If Kind is UnsignedInteger, SignedInteger, or FloatingPoint: This is the size of the value in bits
//! If Kind is String: This is one of PathogenStringConstantKind, potentially with WideCharBit set in the case of wchar_t.
//! If Kind is Unknown, this is the Clang kind (APValue::ValueKind)
int SubKind;
//! The value of the constant
//! If Kind is NullPointer, this is 0
//! If Kind is UnsignedInteger, this is zero-extended
//! If Kind is SignedInteger, this is sign-extended
//! If Kind is FloatingPoint, this is the floating point value as bits and unused bits are 0
//! If Kind is String, this is a pointer to a PathogenConstantString representing the string
uint64_t Value;
};
static_assert(sizeof(PathogenConstantValueInfo::Value) >= sizeof(void*), "PathogenConstantValueInfo::Value must be able to hold a pointer.");
//! Tries to compute the constant value of the specified variable declaration or expression
//! Returns false if Clang could not determine the constant value of the specified cursor.
//! Error is never set when this function returns true.
PATHOGEN_EXPORT bool pathogen_ComputeConstantValue(CXCursor cursor, PathogenConstantValueInfo* info, const char** error)
{
// Get the expression
const Expr* expression;
if (clang_isDeclaration(cursor.kind))
{
// Get the variable declaration
const Decl* declaration = cxcursor::getCursorDecl(cursor);
const VarDecl* variableDeclaration = dyn_cast_or_null<VarDecl>(declaration);
// The declaration cursor must be a variable declaration
if (variableDeclaration == nullptr)
{
*error = "The cursor is not a variable declaration or expression.";
return false;
}
// If the variable has no initializer, there's no value to get
if (!variableDeclaration->hasInit())
{ return false; }
expression = variableDeclaration->getAnyInitializer();
}
else if (clang_isExpression(cursor.kind))
{
expression = cxcursor::getCursorExpr(cursor);
}
else
{
*error = "The cursor is not a variable declaration or expression.";
return false;
}
// Try and evaluate the constant
ASTContext& context = cxcursor::getCursorContext(cursor);
Expr::EvalResult result;
bool hasConstantValue = expression->EvaluateAsRValue(result, context);
if (!hasConstantValue)
{
if (result.Diag != nullptr && result.Diag->size() > 0)
{ *error = "EvaluateAsRValue returned diagnostics."; }
return false;
}
memset(info, 0, sizeof(*info));
info->HasSideEffects = result.HasSideEffects;
info->HasUndefinedBehavior = result.HasUndefinedBehavior;
APValue value = result.Val;
// Default values to unknown, will be replaced by more specific type if possible.
info->Kind = PathogenConstantValueKind::Unknown;
info->SubKind = (int)value.getKind();
info->Value = 0;
if (value.isInt())
{
llvm::APSInt intValue = value.getInt();
info->Kind = intValue.isSigned() ? PathogenConstantValueKind::SignedInteger : PathogenConstantValueKind::UnsignedInteger;
info->SubKind = (int)intValue.getBitWidth();
info->Value = (uint64_t)intValue.getExtValue();
}
else if (value.isFloat())
{
llvm::APFloat floatValue = value.getFloat();
info->Kind = PathogenConstantValueKind::FloatingPoint;
info->SubKind = (int)floatValue.getSizeInBits(floatValue.getSemantics());
info->Value = floatValue.bitcastToAPInt().getZExtValue();
}
else if (value.isLValue() && value.isNullPointer())
{
info->Kind = PathogenConstantValueKind::NullPointer;
info->SubKind = 0;
info->Value = 0;
}
else if (value.isLValue())
{
APValue::LValueBase lValue = value.getLValueBase();
if (const Expr* lValueExpr = lValue.dyn_cast<const Expr*>())
{
if (lValueExpr->getStmtClass() == Stmt::StmtClass::StringLiteralClass)
{
const StringLiteral* stringLiteral = (const StringLiteral*)lValueExpr;
info->Kind = PathogenConstantValueKind::String;
PathogenStringConstantKind* stringKind = (PathogenStringConstantKind*)&info->SubKind;
*stringKind = (PathogenStringConstantKind)stringLiteral->getKind();
if (*stringKind == PathogenStringConstantKind::WideChar)
{
switch (stringLiteral->getCharByteWidth())
{
case 1:
*stringKind = PathogenStringConstantKind::Utf8 | PathogenStringConstantKind::WideCharBit;
break;
case 2:
*stringKind = PathogenStringConstantKind::Utf16 | PathogenStringConstantKind::WideCharBit;
break;
case 4:
*stringKind = PathogenStringConstantKind::Utf32 | PathogenStringConstantKind::WideCharBit;
break;
default:
assert(false && "wchar_t string literal has an unexpected char width.");
break;
}
}
PathogenConstantString* string = (PathogenConstantString*)malloc(sizeof(PathogenConstantString) + stringLiteral->getByteLength() - 1);
string->SizeBytes = stringLiteral->getByteLength();
memcpy(&string->FirstByte, stringLiteral->getBytes().data(), string->SizeBytes);
info->Value = (uint64_t)string;
}
}
}
return true;
}
//! Cleans up any extra memory allocated for the give constant value info.
PATHOGEN_EXPORT void pathogen_DeletePathogenConstantValueInfo(PathogenConstantValueInfo* info)
{
if (info && info->Kind == PathogenConstantValueKind::String && info->Value != 0)
{
free((void*)info->Value);
info->Value = 0;
}
}
//-------------------------------------------------------------------------------------------------
// Macro Information
//-------------------------------------------------------------------------------------------------
enum class PathogenMacroVardicKind : int
{
None,
C99,
Gnu
};
struct PathogenMacroInformation
{
const char* Name;
uint64_t NameLength;
CXSourceLocation Location;
//! True if this macro was defined at some point but was later undefined.
interop_bool WasUndefined;
interop_bool IsFunctionLike;
//! True if this macro is a built-in.
//! (IE: __FILE__ or __LINE__. Does not include macros from the "<built-in>" memory buffer.)
interop_bool IsBuiltInMacro;
//! True if this macro contains the sequence ", ## __VA_ARGS__"
interop_bool HasCommaPasting;
interop_bool IsUsedForHeaderGuard;
PathogenMacroVardicKind VardicKind;
int ParameterCount;
const char** ParameterNames;
uint64_t* ParameterNameLengths;
int TokenCount;
const char* RawValueSourceString;
uint64_t RawValueSourceStringLength;
};
typedef void (*MacroEnumeratorFunction)(PathogenMacroInformation* macroInfo, void* userData);
PATHOGEN_EXPORT unsigned int pathogen_GetPreprocessorIdentifierCount(CXTranslationUnit translationUnit)
{
ASTUnit* astUnit = cxtu::getASTUnit(translationUnit);
const Preprocessor& preprocessor = astUnit->getPreprocessor();
const IdentifierTable& idTable = preprocessor.getIdentifierTable();
return idTable.size();
}
PATHOGEN_EXPORT void pathogen_EnumerateMacros(CXTranslationUnit translationUnit, MacroEnumeratorFunction enumerator, void* userData)
{
ASTUnit* astUnit = cxtu::getASTUnit(translationUnit);
const Preprocessor& preprocessor = astUnit->getPreprocessor();
const IdentifierTable& idTable = preprocessor.getIdentifierTable();
const int stackParameterListCount = 16;
SmallVector<const char*, stackParameterListCount> parameterNames;
SmallVector<uint64_t, stackParameterListCount> parameterNameLengths;
SmallString<128> rawValueSourceStringStorage;
for (auto it = idTable.begin(); it != idTable.end(); it++)
{
const MacroDirective* macro = preprocessor.getLocalMacroDirectiveHistory(it->getValue());
// Skip non-macro preprocessor identifiers
if (macro == nullptr)
{
continue;
}
const MacroDirective::DefInfo definition = macro->getDefinition();
const MacroInfo* macroInfo = definition.getMacroInfo();
PathogenMacroInformation pathogenInfo;
pathogenInfo.Name = it->getKey().data();
pathogenInfo.NameLength = it->getKey().size();
pathogenInfo.Location = cxloc::translateSourceLocation(astUnit->getASTContext(), definition.getLocation());
pathogenInfo.WasUndefined = definition.isUndefined();
pathogenInfo.IsFunctionLike = macroInfo->isFunctionLike();
pathogenInfo.IsBuiltInMacro = macroInfo->isBuiltinMacro();
pathogenInfo.HasCommaPasting = macroInfo->hasCommaPasting();
pathogenInfo.IsUsedForHeaderGuard = macroInfo->isUsedForHeaderGuard();
pathogenInfo.VardicKind = macroInfo->isC99Varargs() ? PathogenMacroVardicKind::C99 : macroInfo->isGNUVarargs() ? PathogenMacroVardicKind::Gnu : PathogenMacroVardicKind::None;
pathogenInfo.ParameterCount = macroInfo->getNumParams();
pathogenInfo.TokenCount = macroInfo->getNumTokens();
// Create array of parameter names
parameterNames.clear();
parameterNameLengths.clear();
parameterNames.reserve(pathogenInfo.ParameterCount);
parameterNameLengths.reserve(pathogenInfo.ParameterCount);
for (const IdentifierInfo* parameter : macroInfo->params())
{
parameterNames.push_back(parameter->getName().data());
parameterNameLengths.push_back(parameter->getName().size());
}
pathogenInfo.ParameterNames = parameterNames.data();
pathogenInfo.ParameterNameLengths = parameterNameLengths.data();
// Create a string for the value of the macro
// (This is based on the logic in MacroInfo::dump)
rawValueSourceStringStorage.clear();
llvm::raw_svector_ostream rawValueSourceString(rawValueSourceStringStorage);
for (const Token& token : macroInfo->tokens())
{
if (token.hasLeadingSpace())
{ rawValueSourceString << " "; }
if (const char* punctuator = tok::getPunctuatorSpelling(token.getKind()))
{ rawValueSourceString << punctuator; }
else if (token.isLiteral() && token.getLiteralData())
{ rawValueSourceString << StringRef(token.getLiteralData(), token.getLength()); }
else if (clang::IdentifierInfo* identifierInfo = token.getIdentifierInfo())
{ rawValueSourceString << identifierInfo->getName(); }
else
{ rawValueSourceString << token.getName(); }
}
llvm::StringRef rawValueSourceStringRef = rawValueSourceString.str();
pathogenInfo.RawValueSourceString = rawValueSourceStringRef.data();
pathogenInfo.RawValueSourceStringLength = rawValueSourceStringRef.size();
// Enumerate the macro
enumerator(&pathogenInfo, userData);
}
}
//-------------------------------------------------------------------------------------------------
// Extended Attribute Information
//-------------------------------------------------------------------------------------------------
PATHOGEN_EXPORT CXString pathogen_GetUuidAttrGuid(CXCursor cursor)
{
if (!clang_isAttribute(cursor.kind))
{
return cxstring::createNull();
}
const Attr* attribute = cxcursor::getCursorAttr(cursor);
const UuidAttr* uuidAttribute = dyn_cast_or_null<UuidAttr>(attribute);
if (uuidAttribute == nullptr)
{
return cxstring::createNull();
}