forked from compiler-research/CppInterOp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCppInterOp.cpp
3517 lines (3076 loc) · 117 KB
/
CppInterOp.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
//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "clang/Interpreter/CppInterOp.h"
#include "Compatibility.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/QualTypeNames.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/DiagnosticSema.h"
#include "clang/Basic/Linkage.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#if CLANG_VERSION_MAJOR >= 19
#include "clang/Sema/Redeclaration.h"
#endif
#include "clang/Sema/TemplateDeduction.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_os_ostream.h"
#include <map>
#include <set>
#include <sstream>
#include <string>
// Stream redirect.
#ifdef _WIN32
#include <io.h>
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
// For exec().
#include <stdio.h>
#define popen(x, y) (_popen(x, y))
#define pclose (_pclose)
#endif
#else
#include <dlfcn.h>
#include <unistd.h>
#endif // WIN32
#include <stack>
namespace Cpp {
using namespace clang;
using namespace llvm;
using namespace std;
// Flag to indicate ownership when an external interpreter instance is used.
static bool OwningSInterpreter = true;
static compat::Interpreter* sInterpreter = nullptr;
// Valgrind complains about __cxa_pure_virtual called when deleting
// llvm::SectionMemoryManager::~SectionMemoryManager as part of the dtor chain
// of the Interpreter.
// This might fix the issue https://reviews.llvm.org/D107087
// FIXME: For now we just leak the Interpreter.
struct InterpDeleter {
~InterpDeleter() = default;
} Deleter;
static compat::Interpreter& getInterp() {
assert(sInterpreter &&
"Interpreter instance must be set before calling this!");
return *sInterpreter;
}
static clang::Sema& getSema() { return getInterp().getCI()->getSema(); }
static clang::ASTContext& getASTContext() { return getSema().getASTContext(); }
#define DEBUG_TYPE "jitcall"
bool JitCall::AreArgumentsValid(void* result, ArgList args,
void* self) const {
bool Valid = true;
if (Cpp::IsConstructor(m_FD)) {
assert(result && "Must pass the location of the created object!");
Valid &= (bool)result;
}
if (Cpp::GetFunctionRequiredArgs(m_FD) > args.m_ArgSize) {
assert(0 && "Must pass at least the minimal number of args!");
Valid = false;
}
if (args.m_ArgSize) {
assert(args.m_Args != nullptr && "Must pass an argument list!");
Valid &= (bool)args.m_Args;
}
if (!Cpp::IsConstructor(m_FD) && !Cpp::IsDestructor(m_FD) &&
Cpp::IsMethod(m_FD) && !Cpp::IsStaticMethod(m_FD)) {
assert(self && "Must pass the pointer to object");
Valid &= (bool)self;
}
const auto* FD = cast<FunctionDecl>((const Decl*)m_FD);
if (!FD->getReturnType()->isVoidType() && !result) {
assert(0 && "We are discarding the return type of the function!");
Valid = false;
}
assert(m_Kind != kDestructorCall && "Wrong overload!");
Valid &= m_Kind != kDestructorCall;
return Valid;
}
void JitCall::ReportInvokeStart(void* result, ArgList args, void* self) const{
std::string Name;
llvm::raw_string_ostream OS(Name);
auto FD = (const FunctionDecl*) m_FD;
FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
/*Qualified=*/true);
LLVM_DEBUG(dbgs() << "Run '" << Name
<< "', compiled at: " << (void*) m_GenericCall
<< " with result at: " << result
<< " , args at: " << args.m_Args
<< " , arg count: " << args.m_ArgSize
<< " , self at: " << self << "\n";
);
}
void JitCall::ReportInvokeStart(void* object, unsigned long nary,
int withFree) const {
std::string Name;
llvm::raw_string_ostream OS(Name);
auto FD = (const FunctionDecl*) m_FD;
FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
/*Qualified=*/true);
LLVM_DEBUG(dbgs() << "Finish '" << Name
<< "', compiled at: " << (void*) m_DestructorCall);
}
#undef DEBUG_TYPE
std::string GetVersion() {
const char* const VERSION = CPPINTEROP_VERSION;
std::string fullVersion = "CppInterOp version";
fullVersion += VERSION;
fullVersion += "\n (based on "
#ifdef USE_CLING
"cling ";
#else
"clang-repl";
#endif // USE_CLING
return fullVersion + "[" + clang::getClangFullVersion() + "])\n";
}
void EnableDebugOutput(bool value/* =true*/) {
llvm::DebugFlag = value;
}
bool IsDebugOutputEnabled() {
return llvm::DebugFlag;
}
bool IsAggregate(TCppScope_t scope) {
Decl *D = static_cast<Decl*>(scope);
// Aggregates are only arrays or tag decls.
if (ValueDecl *ValD = dyn_cast<ValueDecl>(D))
if (ValD->getType()->isArrayType())
return true;
// struct, class, union
if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(D))
return CXXRD->isAggregate();
return false;
}
bool IsNamespace(TCppScope_t scope) {
Decl *D = static_cast<Decl*>(scope);
return isa<NamespaceDecl>(D);
}
bool IsClass(TCppScope_t scope) {
Decl *D = static_cast<Decl*>(scope);
return isa<CXXRecordDecl>(D);
}
static SourceLocation GetValidSLoc(Sema& semaRef) {
auto& SM = semaRef.getSourceManager();
return SM.getLocForStartOfFile(SM.getMainFileID());
}
// See TClingClassInfo::IsLoaded
bool IsComplete(TCppScope_t scope) {
if (!scope)
return false;
Decl *D = static_cast<Decl*>(scope);
if (isa<ClassTemplateSpecializationDecl>(D)) {
QualType QT = QualType::getFromOpaquePtr(GetTypeFromScope(scope));
clang::Sema &S = getSema();
SourceLocation fakeLoc = GetValidSLoc(S);
#ifdef USE_CLING
cling::Interpreter::PushTransactionRAII RAII(&getInterp());
#endif // USE_CLING
return S.isCompleteType(fakeLoc, QT);
}
if (auto *CXXRD = dyn_cast<CXXRecordDecl>(D))
return CXXRD->hasDefinition();
else if (auto *TD = dyn_cast<TagDecl>(D))
return TD->getDefinition();
// Everything else is considered complete.
return true;
}
size_t SizeOf(TCppScope_t scope) {
assert (scope);
if (!IsComplete(scope))
return 0;
if (auto *RD = dyn_cast<RecordDecl>(static_cast<Decl*>(scope))) {
ASTContext &Context = RD->getASTContext();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
return Layout.getSize().getQuantity();
}
return 0;
}
bool IsBuiltin(TCppType_t type) {
QualType Ty = QualType::getFromOpaquePtr(type);
if (Ty->isBuiltinType() || Ty->isAnyComplexType())
return true;
// FIXME: Figure out how to avoid the string comparison.
return llvm::StringRef(Ty.getAsString()).contains("complex");
}
bool IsTemplate(TCppScope_t handle) {
auto *D = (clang::Decl *)handle;
return llvm::isa_and_nonnull<clang::TemplateDecl>(D);
}
bool IsTemplateSpecialization(TCppScope_t handle) {
auto *D = (clang::Decl *)handle;
return llvm::isa_and_nonnull<clang::ClassTemplateSpecializationDecl>(D);
}
bool IsTypedefed(TCppScope_t handle) {
auto *D = (clang::Decl *)handle;
return llvm::isa_and_nonnull<clang::TypedefNameDecl>(D);
}
bool IsAbstract(TCppType_t klass) {
auto *D = (clang::Decl *)klass;
if (auto *CXXRD = llvm::dyn_cast_or_null<clang::CXXRecordDecl>(D))
return CXXRD->isAbstract();
return false;
}
bool IsEnumScope(TCppScope_t handle) {
auto *D = (clang::Decl *)handle;
return llvm::isa_and_nonnull<clang::EnumDecl>(D);
}
bool IsEnumConstant(TCppScope_t handle) {
auto *D = (clang::Decl *)handle;
return llvm::isa_and_nonnull<clang::EnumConstantDecl>(D);
}
bool IsEnumType(TCppType_t type) {
QualType QT = QualType::getFromOpaquePtr(type);
return QT->isEnumeralType();
}
static bool isSmartPointer(const RecordType* RT) {
auto IsUseCountPresent = [](const RecordDecl *Record) {
ASTContext &C = Record->getASTContext();
return !Record->lookup(&C.Idents.get("use_count")).empty();
};
auto IsOverloadedOperatorPresent = [](const RecordDecl *Record,
OverloadedOperatorKind Op) {
ASTContext &C = Record->getASTContext();
DeclContextLookupResult Result =
Record->lookup(C.DeclarationNames.getCXXOperatorName(Op));
return !Result.empty();
};
const RecordDecl *Record = RT->getDecl();
if (IsUseCountPresent(Record))
return true;
bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
if (foundStarOperator && foundArrowOperator)
return true;
const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
if (!CXXRecord)
return false;
auto FindOverloadedOperators = [&](const CXXRecordDecl *Base) {
// If we find use_count, we are done.
if (IsUseCountPresent(Base))
return false; // success.
if (!foundStarOperator)
foundStarOperator = IsOverloadedOperatorPresent(Base, OO_Star);
if (!foundArrowOperator)
foundArrowOperator = IsOverloadedOperatorPresent(Base, OO_Arrow);
if (foundStarOperator && foundArrowOperator)
return false; // success.
return true;
};
return !CXXRecord->forallBases(FindOverloadedOperators);
}
bool IsSmartPtrType(TCppType_t type) {
QualType QT = QualType::getFromOpaquePtr(type);
if (const RecordType *RT = QT->getAs<RecordType>()) {
// Add quick checks for the std smart prts to cover most of the cases.
std::string typeString = GetTypeAsString(type);
llvm::StringRef tsRef(typeString);
if (tsRef.starts_with("std::unique_ptr") ||
tsRef.starts_with("std::shared_ptr") ||
tsRef.starts_with("std::weak_ptr"))
return true;
return isSmartPointer(RT);
}
return false;
}
TCppType_t GetIntegerTypeFromEnumScope(TCppScope_t handle) {
auto *D = (clang::Decl *)handle;
if (auto *ED = llvm::dyn_cast_or_null<clang::EnumDecl>(D)) {
return ED->getIntegerType().getAsOpaquePtr();
}
return 0;
}
TCppType_t GetIntegerTypeFromEnumType(TCppType_t enum_type) {
if (!enum_type)
return nullptr;
QualType QT = QualType::getFromOpaquePtr(enum_type);
if (auto *ET = QT->getAs<EnumType>())
return ET->getDecl()->getIntegerType().getAsOpaquePtr();
return nullptr;
}
std::vector<TCppScope_t> GetEnumConstants(TCppScope_t handle) {
auto *D = (clang::Decl *)handle;
if (auto *ED = llvm::dyn_cast_or_null<clang::EnumDecl>(D)) {
std::vector<TCppScope_t> enum_constants;
for (auto *ECD : ED->enumerators()) {
enum_constants.push_back((TCppScope_t) ECD);
}
return enum_constants;
}
return {};
}
TCppType_t GetEnumConstantType(TCppScope_t handle) {
if (!handle)
return nullptr;
auto *D = (clang::Decl *)handle;
if (auto *ECD = llvm::dyn_cast<clang::EnumConstantDecl>(D))
return ECD->getType().getAsOpaquePtr();
return 0;
}
TCppIndex_t GetEnumConstantValue(TCppScope_t handle) {
auto *D = (clang::Decl *)handle;
if (auto *ECD = llvm::dyn_cast_or_null<clang::EnumConstantDecl>(D)) {
const llvm::APSInt& Val = ECD->getInitVal();
return Val.getExtValue();
}
return 0;
}
size_t GetSizeOfType(TCppType_t type) {
QualType QT = QualType::getFromOpaquePtr(type);
if (const TagType *TT = QT->getAs<TagType>())
return SizeOf(TT->getDecl());
// FIXME: Can we get the size of a non-tag type?
auto TI = getSema().getASTContext().getTypeInfo(QT);
size_t TypeSize = TI.Width;
return TypeSize/8;
}
bool IsVariable(TCppScope_t scope) {
auto *D = (clang::Decl *)scope;
return llvm::isa_and_nonnull<clang::VarDecl>(D);
}
std::string GetName(TCppType_t klass) {
auto *D = (clang::NamedDecl *) klass;
if (llvm::isa_and_nonnull<TranslationUnitDecl>(D)) {
return "";
}
if (auto *ND = llvm::dyn_cast_or_null<NamedDecl>(D)) {
return ND->getNameAsString();
}
return "<unnamed>";
}
std::string GetCompleteName(TCppType_t klass)
{
auto &C = getSema().getASTContext();
auto *D = (Decl *) klass;
if (auto *ND = llvm::dyn_cast_or_null<NamedDecl>(D)) {
if (auto *TD = llvm::dyn_cast<TagDecl>(ND)) {
std::string type_name;
QualType QT = C.getTagDeclType(TD);
PrintingPolicy Policy = C.getPrintingPolicy();
Policy.SuppressUnwrittenScope = true;
Policy.SuppressScope = true;
Policy.AnonymousTagLocations = false;
QT.getAsStringInternal(type_name, Policy);
return type_name;
}
return ND->getNameAsString();
}
if (llvm::isa_and_nonnull<TranslationUnitDecl>(D)) {
return "";
}
return "<unnamed>";
}
std::string GetQualifiedName(TCppType_t klass)
{
auto *D = (Decl *) klass;
if (auto *ND = llvm::dyn_cast_or_null<NamedDecl>(D)) {
return ND->getQualifiedNameAsString();
}
if (llvm::isa_and_nonnull<TranslationUnitDecl>(D)) {
return "";
}
return "<unnamed>";
}
//FIXME: Figure out how to merge with GetCompleteName.
std::string GetQualifiedCompleteName(TCppType_t klass)
{
auto &C = getSema().getASTContext();
auto *D = (Decl *) klass;
if (auto *ND = llvm::dyn_cast_or_null<NamedDecl>(D)) {
if (auto *TD = llvm::dyn_cast<TagDecl>(ND)) {
std::string type_name;
QualType QT = C.getTagDeclType(TD);
QT.getAsStringInternal(type_name, C.getPrintingPolicy());
return type_name;
}
return ND->getQualifiedNameAsString();
}
if (llvm::isa_and_nonnull<TranslationUnitDecl>(D)) {
return "";
}
return "<unnamed>";
}
std::vector<TCppScope_t> GetUsingNamespaces(TCppScope_t scope) {
auto *D = (clang::Decl *) scope;
if (auto *DC = llvm::dyn_cast_or_null<clang::DeclContext>(D)) {
std::vector<TCppScope_t> namespaces;
for (auto UD : DC->using_directives()) {
namespaces.push_back((TCppScope_t) UD->getNominatedNamespace());
}
return namespaces;
}
return {};
}
TCppScope_t GetGlobalScope()
{
return getSema().getASTContext().getTranslationUnitDecl()->getFirstDecl();
}
static Decl *GetScopeFromType(QualType QT) {
if (auto* Type = QT.getCanonicalType().getTypePtrOrNull()) {
Type = Type->getPointeeOrArrayElementType();
Type = Type->getUnqualifiedDesugaredType();
if (auto *ET = llvm::dyn_cast<EnumType>(Type))
return ET->getDecl();
if (auto* FnType = llvm::dyn_cast<FunctionProtoType>(Type))
Type = const_cast<clang::Type*>(FnType->getReturnType().getTypePtr());
return Type->getAsCXXRecordDecl();
}
return 0;
}
TCppScope_t GetScopeFromType(TCppType_t type)
{
QualType QT = QualType::getFromOpaquePtr(type);
return (TCppScope_t) GetScopeFromType(QT);
}
static clang::Decl* GetUnderlyingScope(clang::Decl * D) {
if (auto *TND = dyn_cast_or_null<TypedefNameDecl>(D)) {
if (auto* Scope = GetScopeFromType(TND->getUnderlyingType()))
D = Scope;
} else if (auto* USS = dyn_cast_or_null<UsingShadowDecl>(D)) {
if (auto* Scope = USS->getTargetDecl())
D = Scope;
}
return D;
}
TCppScope_t GetUnderlyingScope(TCppScope_t scope) {
if (!scope)
return 0;
return GetUnderlyingScope((clang::Decl *) scope);
}
TCppScope_t GetScope(const std::string &name, TCppScope_t parent)
{
// FIXME: GetScope should be replaced by a general purpose lookup
// and filter function. The function should be like GetNamed but
// also take in a filter parameter which determines which results
// to pass back
if (name == "")
return GetGlobalScope();
auto *ND = (NamedDecl*)GetNamed(name, parent);
if (!ND || ND == (NamedDecl *) -1)
return 0;
if (llvm::isa<NamespaceDecl>(ND) ||
llvm::isa<RecordDecl>(ND) ||
llvm::isa<ClassTemplateDecl>(ND) ||
llvm::isa<TypedefNameDecl>(ND))
return (TCppScope_t)(ND->getCanonicalDecl());
return 0;
}
TCppScope_t GetScopeFromCompleteName(const std::string &name)
{
std::string delim = "::";
size_t start = 0;
size_t end = name.find(delim);
TCppScope_t curr_scope = 0;
while (end != std::string::npos)
{
curr_scope = GetScope(name.substr(start, end - start), curr_scope);
start = end + delim.length();
end = name.find(delim, start);
}
return GetScope(name.substr(start, end), curr_scope);
}
TCppScope_t GetNamed(const std::string &name,
TCppScope_t parent /*= nullptr*/)
{
clang::DeclContext *Within = 0;
if (parent) {
auto *D = (clang::Decl *)parent;
D = GetUnderlyingScope(D);
Within = llvm::dyn_cast<clang::DeclContext>(D);
}
auto *ND = Cpp_utils::Lookup::Named(&getSema(), name, Within);
if (ND && ND != (clang::NamedDecl*) -1) {
return (TCppScope_t)(ND->getCanonicalDecl());
}
return 0;
}
TCppScope_t GetParentScope(TCppScope_t scope)
{
auto *D = (clang::Decl *) scope;
if (llvm::isa_and_nonnull<TranslationUnitDecl>(D)) {
return 0;
}
auto *ParentDC = D->getDeclContext();
if (!ParentDC)
return 0;
auto* P = clang::Decl::castFromDeclContext(ParentDC)->getCanonicalDecl();
if (auto* TU = llvm::dyn_cast_or_null<TranslationUnitDecl>(P))
return (TCppScope_t)TU->getFirstDecl();
return (TCppScope_t)P;
}
TCppIndex_t GetNumBases(TCppScope_t klass)
{
auto *D = (Decl *) klass;
if (auto *CXXRD = llvm::dyn_cast_or_null<CXXRecordDecl>(D)) {
if (CXXRD->hasDefinition())
return CXXRD->getNumBases();
}
return 0;
}
TCppScope_t GetBaseClass(TCppScope_t klass, TCppIndex_t ibase)
{
auto *D = (Decl *) klass;
auto *CXXRD = llvm::dyn_cast_or_null<CXXRecordDecl>(D);
if (!CXXRD || CXXRD->getNumBases() <= ibase) return 0;
auto type = (CXXRD->bases_begin() + ibase)->getType();
if (auto RT = type->getAs<RecordType>())
return (TCppScope_t)RT->getDecl();
return 0;
}
// FIXME: Consider dropping this interface as it seems the same as
// IsTypeDerivedFrom.
bool IsSubclass(TCppScope_t derived, TCppScope_t base)
{
if (derived == base)
return true;
if (!derived || !base)
return false;
auto *derived_D = (clang::Decl *) derived;
auto *base_D = (clang::Decl *) base;
if (!isa<CXXRecordDecl>(derived_D) || !isa<CXXRecordDecl>(base_D))
return false;
auto Derived = cast<CXXRecordDecl>(derived_D);
auto Base = cast<CXXRecordDecl>(base_D);
return IsTypeDerivedFrom(GetTypeFromScope(Derived),
GetTypeFromScope(Base));
}
// Copied from VTableBuilder.cpp
// This is an internal helper function for the CppInterOp library (as evident
// by the 'static' declaration), while the similar GetBaseClassOffset()
// function below is exposed to library users.
static unsigned ComputeBaseOffset(const ASTContext &Context,
const CXXRecordDecl *DerivedRD,
const CXXBasePath &Path) {
CharUnits NonVirtualOffset = CharUnits::Zero();
unsigned NonVirtualStart = 0;
const CXXRecordDecl *VirtualBase = nullptr;
// First, look for the virtual base class.
for (int I = Path.size(), E = 0; I != E; --I) {
const CXXBasePathElement &Element = Path[I - 1];
if (Element.Base->isVirtual()) {
NonVirtualStart = I;
QualType VBaseType = Element.Base->getType();
VirtualBase = VBaseType->getAsCXXRecordDecl();
break;
}
}
// Now compute the non-virtual offset.
for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
const CXXBasePathElement &Element = Path[I];
// Check the base class offset.
const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
NonVirtualOffset += Layout.getBaseClassOffset(Base);
}
// FIXME: This should probably use CharUnits or something. Maybe we should
// even change the base offsets in ASTRecordLayout to be specified in
// CharUnits.
//return BaseOffset(DerivedRD, VirtuaBose, aBlnVirtualOffset);
if (VirtualBase) {
const ASTRecordLayout &Layout = Context.getASTRecordLayout(DerivedRD);
CharUnits VirtualOffset = Layout.getVBaseClassOffset(VirtualBase);
return (NonVirtualOffset + VirtualOffset).getQuantity();
}
return NonVirtualOffset.getQuantity();
}
int64_t GetBaseClassOffset(TCppScope_t derived, TCppScope_t base) {
if (base == derived)
return 0;
assert(derived || base);
auto *DD = (Decl *) derived;
auto *BD = (Decl *) base;
if (!isa<CXXRecordDecl>(DD) || !isa<CXXRecordDecl>(BD))
return -1;
CXXRecordDecl *DCXXRD = cast<CXXRecordDecl>(DD);
CXXRecordDecl *BCXXRD = cast<CXXRecordDecl>(BD);
CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true,
/*DetectVirtual=*/false);
DCXXRD->isDerivedFrom(BCXXRD, Paths);
// FIXME: We might want to cache these requests as they seem expensive.
return ComputeBaseOffset(getSema().getASTContext(), DCXXRD, Paths.front());
}
template <typename DeclType>
static void GetClassDecls(TCppScope_t klass,
std::vector<TCppFunction_t>& methods) {
if (!klass)
return;
auto* D = (clang::Decl*)klass;
if (auto* TD = dyn_cast<TypedefNameDecl>(D))
D = GetScopeFromType(TD->getUnderlyingType());
if (!D || !isa<CXXRecordDecl>(D))
return;
auto* CXXRD = dyn_cast<CXXRecordDecl>(D);
#ifdef USE_CLING
cling::Interpreter::PushTransactionRAII RAII(&getInterp());
#endif // USE_CLING
getSema().ForceDeclarationOfImplicitMembers(CXXRD);
for (Decl* DI : CXXRD->decls()) {
if (auto* MD = dyn_cast<DeclType>(DI))
methods.push_back(MD);
else if (auto* USD = dyn_cast<UsingShadowDecl>(DI))
if (auto* MD = dyn_cast<DeclType>(USD->getTargetDecl()))
methods.push_back(MD);
}
}
void GetClassMethods(TCppScope_t klass,
std::vector<TCppFunction_t>& methods) {
GetClassDecls<CXXMethodDecl>(klass, methods);
}
void GetFunctionTemplatedDecls(TCppScope_t klass,
std::vector<TCppFunction_t>& methods) {
GetClassDecls<FunctionTemplateDecl>(klass, methods);
}
bool HasDefaultConstructor(TCppScope_t scope) {
auto *D = (clang::Decl *) scope;
if (auto* CXXRD = llvm::dyn_cast_or_null<CXXRecordDecl>(D))
return CXXRD->hasDefaultConstructor();
return false;
}
TCppFunction_t GetDefaultConstructor(TCppScope_t scope) {
if (!HasDefaultConstructor(scope))
return nullptr;
auto *CXXRD = (clang::CXXRecordDecl*)scope;
return getSema().LookupDefaultConstructor(CXXRD);
}
TCppFunction_t GetDestructor(TCppScope_t scope) {
auto *D = (clang::Decl *) scope;
if (auto *CXXRD = llvm::dyn_cast_or_null<CXXRecordDecl>(D)) {
getSema().ForceDeclarationOfImplicitMembers(CXXRD);
return CXXRD->getDestructor();
}
return 0;
}
void DumpScope(TCppScope_t scope)
{
auto *D = (clang::Decl *) scope;
D->dump();
}
std::vector<TCppFunction_t> GetFunctionsUsingName(
TCppScope_t scope, const std::string& name)
{
auto *D = (Decl *) scope;
if (!scope || name.empty())
return {};
D = GetUnderlyingScope(D);
std::vector<TCppFunction_t> funcs;
llvm::StringRef Name(name);
auto &S = getSema();
DeclarationName DName = &getASTContext().Idents.get(name);
clang::LookupResult R(S, DName, SourceLocation(), Sema::LookupOrdinaryName,
For_Visible_Redeclaration);
Cpp_utils::Lookup::Named(&S, R, Decl::castToDeclContext(D));
if (R.empty())
return funcs;
R.resolveKind();
for (auto *Found : R)
if (llvm::isa<FunctionDecl>(Found))
funcs.push_back(Found);
return funcs;
}
TCppType_t GetFunctionReturnType(TCppFunction_t func)
{
auto *D = (clang::Decl *) func;
if (auto* FD = llvm::dyn_cast_or_null<clang::FunctionDecl>(D))
return FD->getReturnType().getAsOpaquePtr();
if (auto* FD = llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>(D))
return (FD->getTemplatedDecl())->getReturnType().getAsOpaquePtr();
return 0;
}
TCppIndex_t GetFunctionNumArgs(TCppFunction_t func)
{
auto *D = (clang::Decl *) func;
if (auto* FD = llvm::dyn_cast_or_null<FunctionDecl>(D))
return FD->getNumParams();
if (auto* FD = llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>(D))
return (FD->getTemplatedDecl())->getNumParams();
return 0;
}
TCppIndex_t GetFunctionRequiredArgs(TCppConstFunction_t func)
{
const auto* D = static_cast<const clang::Decl*>(func);
if (auto* FD = llvm::dyn_cast_or_null<FunctionDecl>(D))
return FD->getMinRequiredArguments();
if (auto* FD = llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>(D))
return (FD->getTemplatedDecl())->getMinRequiredArguments();
return 0;
}
TCppType_t GetFunctionArgType(TCppFunction_t func, TCppIndex_t iarg)
{
auto *D = (clang::Decl *) func;
if (auto *FD = llvm::dyn_cast_or_null<clang::FunctionDecl>(D)) {
if (iarg < FD->getNumParams()) {
auto *PVD = FD->getParamDecl(iarg);
return PVD->getOriginalType().getAsOpaquePtr();
}
}
return 0;
}
std::string GetFunctionSignature(TCppFunction_t func) {
if (!func)
return "<unknown>";
auto *D = (clang::Decl *) func;
if (auto *FD = llvm::dyn_cast<FunctionDecl>(D)) {
std::string Signature;
raw_string_ostream SS(Signature);
PrintingPolicy Policy = getASTContext().getPrintingPolicy();
// Skip printing the body
Policy.TerseOutput = true;
Policy.FullyQualifiedName = true;
Policy.SuppressDefaultTemplateArgs = false;
FD->print(SS, Policy);
SS.flush();
return Signature;
}
return "<unknown>";
}
// Internal functions that are not needed outside the library are
// encompassed in an anonymous namespace as follows.
namespace {
bool IsTemplatedFunction(Decl *D) {
if (llvm::isa_and_nonnull<FunctionTemplateDecl>(D))
return true;
if (auto *FD = llvm::dyn_cast_or_null<FunctionDecl>(D)) {
auto TK = FD->getTemplatedKind();
return TK == FunctionDecl::TemplatedKind::
TK_FunctionTemplateSpecialization
|| TK == FunctionDecl::TemplatedKind::
TK_DependentFunctionTemplateSpecialization
|| TK == FunctionDecl::TemplatedKind::TK_FunctionTemplate;
}
return false;
}
}
bool IsFunctionDeleted(TCppConstFunction_t function) {
const auto* FD =
cast<const FunctionDecl>(static_cast<const clang::Decl*>(function));
return FD->isDeleted();
}
bool IsTemplatedFunction(TCppFunction_t func)
{
auto *D = (Decl *) func;
return IsTemplatedFunction(D);
}
bool ExistsFunctionTemplate(const std::string& name,
TCppScope_t parent)
{
DeclContext *Within = 0;
if (parent) {
auto* D = (Decl*)parent;
Within = llvm::dyn_cast<DeclContext>(D);
}
auto *ND = Cpp_utils::Lookup::Named(&getSema(), name, Within);
if ((intptr_t) ND == (intptr_t) 0)
return false;
if ((intptr_t) ND != (intptr_t) -1)
return IsTemplatedFunction(ND);
// FIXME: Cycle through the Decls and check if there is a templated function
return true;
}
void GetClassTemplatedMethods(const std::string& name, TCppScope_t parent,
std::vector<TCppFunction_t>& funcs) {
auto* D = (Decl*)parent;
if (!parent || name.empty())
return;
D = GetUnderlyingScope(D);
llvm::StringRef Name(name);
auto& S = getSema();
DeclarationName DName = &getASTContext().Idents.get(name);
clang::LookupResult R(S, DName, SourceLocation(), Sema::LookupOrdinaryName,
For_Visible_Redeclaration);
Cpp_utils::Lookup::Named(&S, R, Decl::castToDeclContext(D));
if (R.empty())
return;
R.resolveKind();
for (auto* Found : R)
if (llvm::isa<FunctionTemplateDecl>(Found))
funcs.push_back(Found);
}
TCppFunction_t
BestTemplateFunctionMatch(const std::vector<TCppFunction_t>& candidates,
const std::vector<TemplateArgInfo>& explicit_types,
const std::vector<TemplateArgInfo>& arg_types) {
for (const auto& candidate : candidates) {
auto* TFD = (FunctionTemplateDecl*)candidate;