Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TClingCallFunc.cxx
Go to the documentation of this file.
1// root/core/meta
2// vim: sw=3
3// Author: Paul Russo 30/07/2012
4// Author: Vassil Vassilev 9/02/2013
5
6/*************************************************************************
7 * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. *
8 * All rights reserved. *
9 * *
10 * For the licensing terms see $ROOTSYS/LICENSE. *
11 * For the list of contributors see $ROOTSYS/README/CREDITS. *
12 *************************************************************************/
13
14/** \class TClingCallFunc
15Emulation of the CINT CallFunc class.
16
17The CINT C++ interpreter provides an interface for calling
18functions through the generated wrappers in dictionaries with
19the CallFunc class. This class provides the same functionality,
20using an interface as close as possible to CallFunc but the
21function metadata and calling service comes from the Cling
22C++ interpreter and the Clang C++ compiler, not CINT.
23*/
24
25#include "TClingCallFunc.h"
26
27#include "TClingClassInfo.h"
28#include "TClingMethodInfo.h"
29#include "TInterpreterValue.h"
30#include "TClingUtils.h"
31
32#include "TError.h"
33#include "TCling.h"
34
35#include "cling/Interpreter/CompilationOptions.h"
36#include "cling/Interpreter/Interpreter.h"
37#include "cling/Interpreter/LookupHelper.h"
38#include "cling/Interpreter/Transaction.h"
39#include "cling/Interpreter/Value.h"
40#include "cling/Utils/AST.h"
41
42#include "clang/AST/ASTContext.h"
43#include "clang/AST/Decl.h"
44#include "clang/AST/DeclCXX.h"
45#include "clang/AST/GlobalDecl.h"
46#include "clang/AST/PrettyPrinter.h"
47#include "clang/AST/RecordLayout.h"
48#include "clang/AST/Type.h"
49#include "clang/Frontend/CompilerInstance.h"
50#include "clang/Lex/Preprocessor.h"
51#include "clang/Sema/Sema.h"
52#include "clang/Sema/Lookup.h"
53
54#include "llvm/ADT/APInt.h"
55#include "llvm/ExecutionEngine/ExecutionEngine.h"
56#include "llvm/ExecutionEngine/GenericValue.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/DerivedTypes.h"
61#include "llvm/IR/Function.h"
62#include "llvm/IR/GlobalValue.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/Type.h"
65
66#include "clang/Sema/SemaInternal.h"
67
68#include <map>
69#include <string>
70#include <sstream>
71
72using namespace ROOT;
73using namespace llvm;
74using namespace clang;
75using namespace std;
76
77static unsigned long long gWrapperSerial = 0LL;
78static const string kIndentString(" ");
79
80static map<const Decl *, void *> gWrapperStore;
81static map<const Decl *, void *> gCtorWrapperStore;
82static map<const Decl *, void *> gDtorWrapperStore;
83
84static
85inline
86void
87indent(ostringstream &buf, int indent_level)
88{
89 for (int i = 0; i < indent_level; ++i) {
90 buf << kIndentString;
91 }
92}
93
94static
95void
96EvaluateExpr(cling::Interpreter &interp, const Expr *E, cling::Value &V)
97{
98 // Evaluate an Expr* and return its cling::Value
99 ASTContext &C = interp.getCI()->getASTContext();
100 clang::Expr::EvalResult evalRes;
101 if (E->EvaluateAsInt(evalRes, C, /*AllowSideEffects*/Expr::SE_NoSideEffects)) {
102 APSInt res = evalRes.Val.getInt();
103 // IntTy or maybe better E->getType()?
104 V = cling::Value(C.IntTy, interp);
105 // We must use the correct signedness otherwise the zero extension
106 // fails if the actual type is strictly less than long long.
107 if (res.isSigned())
108 V.getLL() = res.getSExtValue();
109 else
110 V.getULL() = res.getZExtValue();
111 return;
112 }
113 // TODO: Build a wrapper around the expression to avoid decompilation and
114 // compilation and other string operations.
115 PrintingPolicy Policy(C.getPrintingPolicy());
116 Policy.SuppressTagKeyword = true;
117 Policy.SuppressUnwrittenScope = false;
118 Policy.SuppressInitializers = false;
119 Policy.AnonymousTagLocations = false;
120 string buf;
121 raw_string_ostream out(buf);
122 E->printPretty(out, /*Helper=*/0, Policy, /*Indentation=*/0);
123 out << ';'; // no value printing
124 out.flush();
125 // Evaluate() will set V to invalid if evaluation fails.
126 interp.evaluate(buf, V);
127}
128
129namespace {
130 template <typename returnType>
131 returnType sv_to(const cling::Value &val)
132 {
133 QualType QT = val.getType().getCanonicalType();
134 if (const BuiltinType *BT =
135 dyn_cast<BuiltinType>(&*QT)) {
136 //
137 // WARNING!!!
138 //
139 // This switch is organized in order-of-declaration
140 // so that the produced assembly code is optimal.
141 // Do not reorder!
142 //
143 switch (BT->getKind()) {
144 case BuiltinType::Void:
145 // CINT used to expect a result of 0.
146 return (returnType) 0;
147 break;
148 //
149 // Unsigned Types
150 //
151 case BuiltinType::Bool:
152 case BuiltinType::Char_U: // char on targets where it is unsigned
153 case BuiltinType::UChar:
154 return (returnType) val.getULL();
155 break;
156
157 case BuiltinType::WChar_U:
158 // wchar_t on targets where it is unsigned
159 // The standard doesn't allow to specify signednedd of wchar_t
160 // thus this maps simply to wchar_t.
161 return (returnType)(wchar_t) val.getULL();
162 break;
163
164 case BuiltinType::Char16:
165 case BuiltinType::Char32:
166 case BuiltinType::UShort:
167 case BuiltinType::UInt:
168 case BuiltinType::ULong:
169 case BuiltinType::ULongLong:
170 return (returnType) val.getULL();
171 break;
172
173 case BuiltinType::UInt128:
174 // __uint128_t
175 break;
176
177 //
178 // Signed Types
179 //
180 case BuiltinType::Char_S: // char on targets where it is signed
181 case BuiltinType::SChar:
182 return (returnType) val.getLL();
183 break;
184
185 case BuiltinType::WChar_S:
186 // wchar_t on targets where it is signed
187 // The standard doesn't allow to specify signednedd of wchar_t
188 // thus this maps simply to wchar_t.
189 return (returnType)(wchar_t) val.getLL();
190 break;
191
192 case BuiltinType::Short:
193 case BuiltinType::Int:
194 case BuiltinType::Long:
195 case BuiltinType::LongLong:
196 return (returnType) val.getLL();
197 break;
198
199 case BuiltinType::Int128:
200 break;
201
202 case BuiltinType::Half:
203 // half in OpenCL, __fp16 in ARM NEON
204 break;
205
206 case BuiltinType::Float:
207 return (returnType) val.getFloat();
208 break;
209 case BuiltinType::Double:
210 return (returnType) val.getDouble();
211 break;
212 case BuiltinType::LongDouble:
213 return (returnType) val.getLongDouble();
214 break;
215
216 case BuiltinType::NullPtr:
217 return (returnType) 0;
218 break;
219
220 default:
221 break;
222 }
223 }
224 if (QT->isPointerType() || QT->isArrayType() || QT->isRecordType() ||
225 QT->isReferenceType()) {
226 return (returnType)(long) val.getPtr();
227 }
228 if (const EnumType *ET = dyn_cast<EnumType>(&*QT)) {
229 if (ET->getDecl()->getIntegerType()->hasSignedIntegerRepresentation())
230 return (returnType) val.getLL();
231 else
232 return (returnType) val.getULL();
233 }
234 if (QT->isMemberPointerType()) {
235 const MemberPointerType *MPT = QT->getAs<MemberPointerType>();
236 if (MPT->isMemberDataPointer()) {
237 return (returnType)(ptrdiff_t)val.getPtr();
238 }
239 return (returnType)(long) val.getPtr();
240 }
241 ::Error("TClingCallFunc::sv_to", "Invalid Type!");
242 QT->dump();
243 return 0;
244 }
245
246 static
247 long long sv_to_long_long(const cling::Value &val)
248 {
249 return sv_to<long long>(val);
250 }
251 static
252 unsigned long long sv_to_ulong_long(const cling::Value &val)
253 {
254 return sv_to<unsigned long long>(val);
255 }
256
257} // unnamed namespace.
258
260{
261 // This function is non-const to use caching overload of GetDecl()!
262 return GetDecl()->getMinRequiredArguments();
263}
264
265void *TClingCallFunc::compile_wrapper(const string &wrapper_name, const string &wrapper,
266 bool withAccessControl/*=true*/)
267{
268 return fInterp->compileFunction(wrapper_name, wrapper, false /*ifUnique*/,
269 withAccessControl);
270}
271
272void TClingCallFunc::collect_type_info(QualType &QT, ostringstream &typedefbuf, std::ostringstream &callbuf,
273 string &type_name, EReferenceType &refType, bool &isPointer, int indent_level,
274 bool forArgument)
275{
276 //
277 // Collect information about type type of a function parameter
278 // needed for building the wrapper function.
279 //
280 const FunctionDecl *FD = GetDecl();
281 PrintingPolicy Policy(FD->getASTContext().getPrintingPolicy());
282 refType = kNotReference;
283 if (QT->isRecordType() && forArgument) {
285 return;
286 }
287 if (QT->isFunctionPointerType()) {
288 string fp_typedef_name;
289 {
290 ostringstream nm;
291 nm << "FP" << gWrapperSerial++;
292 type_name = nm.str();
293 raw_string_ostream OS(fp_typedef_name);
294 QT.print(OS, Policy, type_name);
295 OS.flush();
296 }
297 for (int i = 0; i < indent_level; ++i) {
298 typedefbuf << kIndentString;
299 }
300 typedefbuf << "typedef " << fp_typedef_name << ";\n";
301 return;
302 } else if (QT->isMemberPointerType()) {
303 string mp_typedef_name;
304 {
305 ostringstream nm;
306 nm << "MP" << gWrapperSerial++;
307 type_name = nm.str();
308 raw_string_ostream OS(mp_typedef_name);
309 QT.print(OS, Policy, type_name);
310 OS.flush();
311 }
312 for (int i = 0; i < indent_level; ++i) {
313 typedefbuf << kIndentString;
314 }
315 typedefbuf << "typedef " << mp_typedef_name << ";\n";
316 return;
317 } else if (QT->isPointerType()) {
318 isPointer = true;
319 QT = cast<clang::PointerType>(QT)->getPointeeType();
320 } else if (QT->isReferenceType()) {
321 if (QT->isRValueReferenceType()) refType = kRValueReference;
322 else refType = kLValueReference;
323 QT = cast<ReferenceType>(QT)->getPointeeType();
324 }
325 // Fall through for the array type to deal with reference/pointer ro array type.
326 if (QT->isArrayType()) {
327 string ar_typedef_name;
328 {
329 ostringstream ar;
330 ar << "AR" << gWrapperSerial++;
331 type_name = ar.str();
332 raw_string_ostream OS(ar_typedef_name);
333 QT.print(OS, Policy, type_name);
334 OS.flush();
335 }
336 for (int i = 0; i < indent_level; ++i) {
337 typedefbuf << kIndentString;
338 }
339 typedefbuf << "typedef " << ar_typedef_name << ";\n";
340 return;
341 }
343}
344
345void TClingCallFunc::make_narg_ctor(const unsigned N, ostringstream &typedefbuf,
346 ostringstream &callbuf, const string &class_name,
347 int indent_level)
348{
349 // Make a code string that follows this pattern:
350 //
351 // new ClassName(args...)
352 //
353 const FunctionDecl *FD = GetDecl();
354
355 callbuf << "new " << class_name << "(";
356 for (unsigned i = 0U; i < N; ++i) {
357 const ParmVarDecl *PVD = FD->getParamDecl(i);
358 QualType Ty = PVD->getType();
359 QualType QT = Ty.getCanonicalType();
360 string type_name;
362 bool isPointer = false;
363 collect_type_info(QT, typedefbuf, callbuf, type_name,
364 refType, isPointer, indent_level, true);
365 if (i) {
366 callbuf << ',';
367 if (i % 2) {
368 callbuf << ' ';
369 } else {
370 callbuf << "\n";
371 for (int j = 0; j <= indent_level; ++j) {
372 callbuf << kIndentString;
373 }
374 }
375 }
376 if (refType != kNotReference) {
377 callbuf << "(" << type_name.c_str() <<
378 (refType == kLValueReference ? "&" : "&&") << ")*(" << type_name.c_str() << "*)args["
379 << i << "]";
380 } else if (isPointer) {
381 callbuf << "*(" << type_name.c_str() << "**)args["
382 << i << "]";
383 } else {
384 callbuf << "*(" << type_name.c_str() << "*)args[" << i << "]";
385 }
386 }
387 callbuf << ")";
388}
389
390void TClingCallFunc::make_narg_call(const std::string &return_type, const unsigned N, ostringstream &typedefbuf,
391 ostringstream &callbuf, const string &class_name, int indent_level)
392{
393 //
394 // Make a code string that follows this pattern:
395 //
396 // ((<class>*)obj)-><method>(*(<arg-i-type>*)args[i], ...)
397 //
398 const FunctionDecl *FD = GetDecl();
399
400 // Sometimes it's necessary that we cast the function we want to call first
401 // to its explicit function type before calling it. This is supposed to prevent
402 // that we accidentially ending up in a function that is not the one we're
403 // supposed to call here (e.g. because the C++ function lookup decides to take
404 // another function that better fits).
405 // This method has some problems, e.g. when we call a function with default
406 // arguments and we don't provide all arguments, we would fail with this pattern.
407 // Same applies with member methods which seem to cause parse failures even when
408 // we supply the object parameter.
409 // Therefore we only use it in cases where we know it works and set this variable
410 // to true when we do.
411 bool ShouldCastFunction = !isa<CXXMethodDecl>(FD) && N == FD->getNumParams();
412 if (ShouldCastFunction) {
413 callbuf << "(";
414 callbuf << "(";
415 callbuf << return_type << " (&)";
416 {
417 callbuf << "(";
418 for (unsigned i = 0U; i < N; ++i) {
419 if (i) {
420 callbuf << ',';
421 if (i % 2) {
422 callbuf << ' ';
423 } else {
424 callbuf << "\n";
425 for (int j = 0; j <= indent_level; ++j) {
426 callbuf << kIndentString;
427 }
428 }
429 }
430 const ParmVarDecl *PVD = FD->getParamDecl(i);
431 QualType Ty = PVD->getType();
432 QualType QT = Ty.getCanonicalType();
433 std::string arg_type;
435 callbuf << arg_type;
436 }
437 if (FD->isVariadic())
438 callbuf << ", ...";
439 callbuf << ")";
440 }
441
442 callbuf << ")";
443 }
444
445 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
446 // This is a class, struct, or union member.
447 if (MD->isConst())
448 callbuf << "((const " << class_name << "*)obj)->";
449 else
450 callbuf << "((" << class_name << "*)obj)->";
451 } else if (const NamedDecl *ND =
452 dyn_cast<NamedDecl>(GetDeclContext())) {
453 // This is a namespace member.
454 (void) ND;
455 callbuf << class_name << "::";
456 }
457 // callbuf << fMethod->Name() << "(";
458 {
459 std::string name;
460 {
461 llvm::raw_string_ostream stream(name);
462 FD->getNameForDiagnostic(stream, FD->getASTContext().getPrintingPolicy(), /*Qualified=*/false);
463 }
464 callbuf << name;
465 }
466 if (ShouldCastFunction) callbuf << ")";
467
468 callbuf << "(";
469 for (unsigned i = 0U; i < N; ++i) {
470 const ParmVarDecl *PVD = FD->getParamDecl(i);
471 QualType Ty = PVD->getType();
472 QualType QT = Ty.getCanonicalType();
473 string type_name;
475 bool isPointer = false;
476 collect_type_info(QT, typedefbuf, callbuf, type_name, refType, isPointer, indent_level, true);
477
478 if (i) {
479 callbuf << ',';
480 if (i % 2) {
481 callbuf << ' ';
482 } else {
483 callbuf << "\n";
484 for (int j = 0; j <= indent_level; ++j) {
485 callbuf << kIndentString;
486 }
487 }
488 }
489
490 if (refType != kNotReference) {
491 callbuf << "(" << type_name.c_str() <<
492 (refType == kLValueReference ? "&" : "&&") << ")*(" << type_name.c_str() << "*)args["
493 << i << "]";
494 } else if (isPointer) {
495 callbuf << "*(" << type_name.c_str() << "**)args["
496 << i << "]";
497 } else {
498 // pointer falls back to non-pointer case; the argument preserves
499 // the "pointerness" (i.e. doesn't reference the value).
500 callbuf << "*(" << type_name.c_str() << "*)args[" << i << "]";
501 }
502 }
503 callbuf << ")";
504}
505
506void TClingCallFunc::make_narg_ctor_with_return(const unsigned N, const string &class_name,
507 ostringstream &buf, int indent_level)
508{
509 // Make a code string that follows this pattern:
510 //
511 // if (ret) {
512 // (*(ClassName**)ret) = new ClassName(args...);
513 // }
514 // else {
515 // new ClassName(args...);
516 // }
517 //
518 for (int i = 0; i < indent_level; ++i) {
519 buf << kIndentString;
520 }
521 buf << "if (ret) {\n";
522 ++indent_level;
523 {
524 ostringstream typedefbuf;
525 ostringstream callbuf;
526 //
527 // Write the return value assignment part.
528 //
529 for (int i = 0; i < indent_level; ++i) {
530 callbuf << kIndentString;
531 }
532 callbuf << "(*(" << class_name << "**)ret) = ";
533 //
534 // Write the actual new expression.
535 //
536 make_narg_ctor(N, typedefbuf, callbuf, class_name, indent_level);
537 //
538 // End the new expression statement.
539 //
540 callbuf << ";\n";
541 for (int i = 0; i < indent_level; ++i) {
542 callbuf << kIndentString;
543 }
544 callbuf << "return;\n";
545 //
546 // Output the whole new expression and return statement.
547 //
548 buf << typedefbuf.str() << callbuf.str();
549 }
550 --indent_level;
551 for (int i = 0; i < indent_level; ++i) {
552 buf << kIndentString;
553 }
554 buf << "}\n";
555 for (int i = 0; i < indent_level; ++i) {
556 buf << kIndentString;
557 }
558 buf << "else {\n";
559 ++indent_level;
560 {
561 ostringstream typedefbuf;
562 ostringstream callbuf;
563 for (int i = 0; i < indent_level; ++i) {
564 callbuf << kIndentString;
565 }
566 make_narg_ctor(N, typedefbuf, callbuf, class_name, indent_level);
567 callbuf << ";\n";
568 for (int i = 0; i < indent_level; ++i) {
569 callbuf << kIndentString;
570 }
571 callbuf << "return;\n";
572 buf << typedefbuf.str() << callbuf.str();
573 }
574 --indent_level;
575 for (int i = 0; i < indent_level; ++i) {
576 buf << kIndentString;
577 }
578 buf << "}\n";
579}
580
581///////////////////////////////////////////////////////////////////////////////
582// Returns the DeclContext corresponding to fMethod's Decl.
583// \Note that this might be a FunctionDecl or a UsingShadowDecl; we use the
584// DeclContext of the UsingShadowDecl e.g. for constructing a derived class
585// object, even if invoking a function made available by a using declaration
586// of a constructor of a base class (ROOT-11010).
587
588const clang::DeclContext *TClingCallFunc::GetDeclContext() const {
589 return fMethod->GetDecl()->getDeclContext();
590}
591
592int TClingCallFunc::get_wrapper_code(std::string &wrapper_name, std::string &wrapper)
593{
594 const FunctionDecl *FD = GetDecl();
595 assert(FD && "generate_wrapper called without a function decl!");
596 ASTContext &Context = FD->getASTContext();
597 PrintingPolicy Policy(Context.getPrintingPolicy());
598 //
599 // Get the class or namespace name.
600 //
601 string class_name;
602 const clang::DeclContext *DC = GetDeclContext();
603 if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC)) {
604 // This is a class, struct, or union member.
605 QualType QT(TD->getTypeForDecl(), 0);
607 } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
608 // This is a namespace member.
609 raw_string_ostream stream(class_name);
610 ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
611 stream.flush();
612 }
613 //
614 // Check to make sure that we can
615 // instantiate and codegen this function.
616 //
617 bool needInstantiation = false;
618 const FunctionDecl *Definition = 0;
619 if (!FD->isDefined(Definition)) {
620 FunctionDecl::TemplatedKind TK = FD->getTemplatedKind();
621 switch (TK) {
622 case FunctionDecl::TK_NonTemplate: {
623 // Ordinary function, not a template specialization.
624 // Note: This might be ok, the body might be defined
625 // in a library, and all we have seen is the
626 // header file.
627 //::Error("TClingCallFunc::make_wrapper",
628 // "Cannot make wrapper for a function which is "
629 // "declared but not defined!");
630 // return 0;
631 } break;
632 case FunctionDecl::TK_FunctionTemplate: {
633 // This decl is actually a function template,
634 // not a function at all.
635 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template!");
636 return 0;
637 } break;
638 case FunctionDecl::TK_MemberSpecialization: {
639 // This function is the result of instantiating an ordinary
640 // member function of a class template, or of instantiating
641 // an ordinary member function of a class member of a class
642 // template, or of specializing a member function template
643 // of a class template, or of specializing a member function
644 // template of a class member of a class template.
645 if (!FD->isTemplateInstantiation()) {
646 // We are either TSK_Undeclared or
647 // TSK_ExplicitSpecialization.
648 // Note: This might be ok, the body might be defined
649 // in a library, and all we have seen is the
650 // header file.
651 //::Error("TClingCallFunc::make_wrapper",
652 // "Cannot make wrapper for a function template "
653 // "explicit specialization which is declared "
654 // "but not defined!");
655 // return 0;
656 break;
657 }
658 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
659 if (!Pattern) {
660 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a member function "
661 "instantiation with no pattern!");
662 return 0;
663 }
664 FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
665 TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
666 if (
667 // The pattern is an ordinary member function.
668 (PTK == FunctionDecl::TK_NonTemplate) ||
669 // The pattern is an explicit specialization, and
670 // so is not a template.
671 ((PTK != FunctionDecl::TK_FunctionTemplate) &&
672 ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
673 // Note: This might be ok, the body might be defined
674 // in a library, and all we have seen is the
675 // header file.
676 break;
677 } else if (!Pattern->hasBody()) {
678 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a member function "
679 "instantiation with no body!");
680 return 0;
681 }
682 if (FD->isImplicitlyInstantiable()) {
683 needInstantiation = true;
684 }
685 } break;
686 case FunctionDecl::TK_FunctionTemplateSpecialization: {
687 // This function is the result of instantiating a function
688 // template or possibly an explicit specialization of a
689 // function template. Could be a namespace scope function or a
690 // member function.
691 if (!FD->isTemplateInstantiation()) {
692 // We are either TSK_Undeclared or
693 // TSK_ExplicitSpecialization.
694 // Note: This might be ok, the body might be defined
695 // in a library, and all we have seen is the
696 // header file.
697 //::Error("TClingCallFunc::make_wrapper",
698 // "Cannot make wrapper for a function template "
699 // "explicit specialization which is declared "
700 // "but not defined!");
701 // return 0;
702 break;
703 }
704 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
705 if (!Pattern) {
706 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template"
707 "instantiation with no pattern!");
708 return 0;
709 }
710 FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
711 TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
712 if (
713 // The pattern is an ordinary member function.
714 (PTK == FunctionDecl::TK_NonTemplate) ||
715 // The pattern is an explicit specialization, and
716 // so is not a template.
717 ((PTK != FunctionDecl::TK_FunctionTemplate) &&
718 ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
719 // Note: This might be ok, the body might be defined
720 // in a library, and all we have seen is the
721 // header file.
722 break;
723 }
724 if (!Pattern->hasBody()) {
725 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template"
726 "instantiation with no body!");
727 return 0;
728 }
729 if (FD->isImplicitlyInstantiable()) {
730 needInstantiation = true;
731 }
732 } break;
733 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
734 // This function is the result of instantiating or
735 // specializing a member function of a class template,
736 // or a member function of a class member of a class template,
737 // or a member function template of a class template, or a
738 // member function template of a class member of a class
739 // template where at least some part of the function is
740 // dependent on a template argument.
741 if (!FD->isTemplateInstantiation()) {
742 // We are either TSK_Undeclared or
743 // TSK_ExplicitSpecialization.
744 // Note: This might be ok, the body might be defined
745 // in a library, and all we have seen is the
746 // header file.
747 //::Error("TClingCallFunc::make_wrapper",
748 // "Cannot make wrapper for a dependent function "
749 // "template explicit specialization which is declared "
750 // "but not defined!");
751 // return 0;
752 break;
753 }
754 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
755 if (!Pattern) {
756 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a dependent function template"
757 "instantiation with no pattern!");
758 return 0;
759 }
760 FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
761 TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
762 if (
763 // The pattern is an ordinary member function.
764 (PTK == FunctionDecl::TK_NonTemplate) ||
765 // The pattern is an explicit specialization, and
766 // so is not a template.
767 ((PTK != FunctionDecl::TK_FunctionTemplate) &&
768 ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
769 // Note: This might be ok, the body might be defined
770 // in a library, and all we have seen is the
771 // header file.
772 break;
773 }
774 if (!Pattern->hasBody()) {
775 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a dependent function template"
776 "instantiation with no body!");
777 return 0;
778 }
779 if (FD->isImplicitlyInstantiable()) {
780 needInstantiation = true;
781 }
782 } break;
783 default: {
784 // Will only happen if clang implementation changes.
785 // Protect ourselves in case that happens.
786 ::Error("TClingCallFunc::make_wrapper", "Unhandled template kind!");
787 return 0;
788 } break;
789 }
790 // We do not set needInstantiation to true in these cases:
791 //
792 // isInvalidDecl()
793 // TSK_Undeclared
794 // TSK_ExplicitInstantiationDefinition
795 // TSK_ExplicitSpecialization && !getClassScopeSpecializationPattern()
796 // TSK_ExplicitInstantiationDeclaration &&
797 // getTemplateInstantiationPattern() &&
798 // PatternDecl->hasBody() &&
799 // !PatternDecl->isInlined()
800 //
801 // Set it true in these cases:
802 //
803 // TSK_ImplicitInstantiation
804 // TSK_ExplicitInstantiationDeclaration && (!getPatternDecl() ||
805 // !PatternDecl->hasBody() || PatternDecl->isInlined())
806 //
807 }
808 if (needInstantiation) {
809 clang::FunctionDecl *FDmod = const_cast<clang::FunctionDecl *>(FD);
810 clang::Sema &S = fInterp->getSema();
811 // Could trigger deserialization of decls.
812 cling::Interpreter::PushTransactionRAII RAII(fInterp);
813 S.InstantiateFunctionDefinition(SourceLocation(), FDmod,
814 /*Recursive=*/true,
815 /*DefinitionRequired=*/true);
816 if (!FD->isDefined(Definition)) {
817 ::Error("TClingCallFunc::make_wrapper", "Failed to force template instantiation!");
818 return 0;
819 }
820 }
821 if (Definition) {
822 FunctionDecl::TemplatedKind TK = Definition->getTemplatedKind();
823 switch (TK) {
824 case FunctionDecl::TK_NonTemplate: {
825 // Ordinary function, not a template specialization.
826 if (Definition->isDeleted()) {
827 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted function!");
828 return 0;
829 } else if (Definition->isLateTemplateParsed()) {
830 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
831 "function!");
832 return 0;
833 }
834 // else if (Definition->isDefaulted()) {
835 // // Might not have a body, but we can still use it.
836 //}
837 // else {
838 // // Has a body.
839 //}
840 } break;
841 case FunctionDecl::TK_FunctionTemplate: {
842 // This decl is actually a function template,
843 // not a function at all.
844 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template!");
845 return 0;
846 } break;
847 case FunctionDecl::TK_MemberSpecialization: {
848 // This function is the result of instantiating an ordinary
849 // member function of a class template or of a member class
850 // of a class template.
851 if (Definition->isDeleted()) {
852 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted member function "
853 "of a specialization!");
854 return 0;
855 } else if (Definition->isLateTemplateParsed()) {
856 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
857 "member function of a specialization!");
858 return 0;
859 }
860 // else if (Definition->isDefaulted()) {
861 // // Might not have a body, but we can still use it.
862 //}
863 // else {
864 // // Has a body.
865 //}
866 } break;
867 case FunctionDecl::TK_FunctionTemplateSpecialization: {
868 // This function is the result of instantiating a function
869 // template or possibly an explicit specialization of a
870 // function template. Could be a namespace scope function or a
871 // member function.
872 if (Definition->isDeleted()) {
873 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted function "
874 "template specialization!");
875 return 0;
876 } else if (Definition->isLateTemplateParsed()) {
877 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
878 "function template specialization!");
879 return 0;
880 }
881 // else if (Definition->isDefaulted()) {
882 // // Might not have a body, but we can still use it.
883 //}
884 // else {
885 // // Has a body.
886 //}
887 } break;
888 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
889 // This function is the result of instantiating or
890 // specializing a member function of a class template,
891 // or a member function of a class member of a class template,
892 // or a member function template of a class template, or a
893 // member function template of a class member of a class
894 // template where at least some part of the function is
895 // dependent on a template argument.
896 if (Definition->isDeleted()) {
897 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted dependent function "
898 "template specialization!");
899 return 0;
900 } else if (Definition->isLateTemplateParsed()) {
901 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
902 "dependent function template specialization!");
903 return 0;
904 }
905 // else if (Definition->isDefaulted()) {
906 // // Might not have a body, but we can still use it.
907 //}
908 // else {
909 // // Has a body.
910 //}
911 } break;
912 default: {
913 // Will only happen if clang implementation changes.
914 // Protect ourselves in case that happens.
915 ::Error("TClingCallFunc::make_wrapper", "Unhandled template kind!");
916 return 0;
917 } break;
918 }
919 }
920 unsigned min_args = GetMinRequiredArguments();
921 unsigned num_params = FD->getNumParams();
922 //
923 // Make the wrapper name.
924 //
925 {
926 ostringstream buf;
927 buf << "__cf";
928 // const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
929 // string mn;
930 // fInterp->maybeMangleDeclName(ND, mn);
931 // buf << '_' << mn;
932 buf << '_' << gWrapperSerial++;
933 wrapper_name = buf.str();
934 }
935 //
936 // Write the wrapper code.
937 // FIXME: this should be synthesized into the AST!
938 //
939 int indent_level = 0;
940 ostringstream buf;
941 buf << "#pragma clang diagnostic push\n"
942 "#pragma clang diagnostic ignored \"-Wformat-security\"\n"
943 "__attribute__((used)) "
944 "extern \"C\" void ";
945 buf << wrapper_name;
946 buf << "(void* obj, int nargs, void** args, void* ret)\n"
947 "{\n";
948 ++indent_level;
949 if (min_args == num_params) {
950 // No parameters with defaults.
951 make_narg_call_with_return(num_params, class_name, buf, indent_level);
952 } else {
953 // We need one function call clause compiled for every
954 // possible number of arguments per call.
955 for (unsigned N = min_args; N <= num_params; ++N) {
956 for (int i = 0; i < indent_level; ++i) {
957 buf << kIndentString;
958 }
959 buf << "if (nargs == " << N << ") {\n";
960 ++indent_level;
961 make_narg_call_with_return(N, class_name, buf, indent_level);
962 --indent_level;
963 for (int i = 0; i < indent_level; ++i) {
964 buf << kIndentString;
965 }
966 buf << "}\n";
967 }
968 }
969 --indent_level;
970 buf << "}\n"
971 "#pragma clang diagnostic pop";
972 wrapper = buf.str();
973 return 1;
974}
975
976void TClingCallFunc::make_narg_call_with_return(const unsigned N, const string &class_name,
977 ostringstream &buf, int indent_level)
978{
979 // Make a code string that follows this pattern:
980 //
981 // if (ret) {
982 // new (ret) (return_type) ((class_name*)obj)->func(args...);
983 // }
984 // else {
985 // (void)(((class_name*)obj)->func(args...));
986 // }
987 //
988 const FunctionDecl *FD = GetDecl();
989 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
990 if (N <= 1 && llvm::isa<UsingShadowDecl>(GetFunctionOrShadowDecl())) {
991 auto SpecMemKind = fInterp->getSema().getSpecialMember(CD);
992 if ((N == 0 && SpecMemKind == clang::Sema::CXXDefaultConstructor) ||
993 (N == 1 &&
994 (SpecMemKind == clang::Sema::CXXCopyConstructor || SpecMemKind == clang::Sema::CXXMoveConstructor))) {
995 // Using declarations cannot inject special members; do not call them
996 // as such. This might happen by using `Base(Base&, int = 12)`, which
997 // is fine to be called as `Derived d(someBase, 42)` but not as
998 // copy constructor of `Derived`.
999 return;
1000 }
1001 }
1002 make_narg_ctor_with_return(N, class_name, buf, indent_level);
1003 return;
1004 }
1005 QualType QT = FD->getReturnType().getCanonicalType();
1006 if (QT->isVoidType()) {
1007 ostringstream typedefbuf;
1008 ostringstream callbuf;
1009 for (int i = 0; i < indent_level; ++i) {
1010 callbuf << kIndentString;
1011 }
1012 make_narg_call("void", N, typedefbuf, callbuf, class_name, indent_level);
1013 callbuf << ";\n";
1014 for (int i = 0; i < indent_level; ++i) {
1015 callbuf << kIndentString;
1016 }
1017 callbuf << "return;\n";
1018 buf << typedefbuf.str() << callbuf.str();
1019 } else {
1020 for (int i = 0; i < indent_level; ++i) {
1021 buf << kIndentString;
1022 }
1023
1024 string type_name;
1025 EReferenceType refType = kNotReference;
1026 bool isPointer = false;
1027
1028 buf << "if (ret) {\n";
1029 ++indent_level;
1030 {
1031 ostringstream typedefbuf;
1032 ostringstream callbuf;
1033 //
1034 // Write the placement part of the placement new.
1035 //
1036 for (int i = 0; i < indent_level; ++i) {
1037 callbuf << kIndentString;
1038 }
1039 callbuf << "new (ret) ";
1040 collect_type_info(QT, typedefbuf, callbuf, type_name,
1041 refType, isPointer, indent_level, false);
1042 //
1043 // Write the type part of the placement new.
1044 //
1045 callbuf << "(" << type_name.c_str();
1046 if (refType != kNotReference) {
1047 callbuf << "*) (&";
1048 type_name += "&";
1049 } else if (isPointer) {
1050 callbuf << "*) (";
1051 type_name += "*";
1052 } else {
1053 callbuf << ") (";
1054 }
1055 //
1056 // Write the actual function call.
1057 //
1058 make_narg_call(type_name, N, typedefbuf, callbuf, class_name, indent_level);
1059 //
1060 // End the placement new.
1061 //
1062 callbuf << ");\n";
1063 for (int i = 0; i < indent_level; ++i) {
1064 callbuf << kIndentString;
1065 }
1066 callbuf << "return;\n";
1067 //
1068 // Output the whole placement new expression and return statement.
1069 //
1070 buf << typedefbuf.str() << callbuf.str();
1071 }
1072 --indent_level;
1073 for (int i = 0; i < indent_level; ++i) {
1074 buf << kIndentString;
1075 }
1076 buf << "}\n";
1077 for (int i = 0; i < indent_level; ++i) {
1078 buf << kIndentString;
1079 }
1080 buf << "else {\n";
1081 ++indent_level;
1082 {
1083 ostringstream typedefbuf;
1084 ostringstream callbuf;
1085 for (int i = 0; i < indent_level; ++i) {
1086 callbuf << kIndentString;
1087 }
1088 callbuf << "(void)(";
1089 make_narg_call(type_name, N, typedefbuf, callbuf, class_name, indent_level);
1090 callbuf << ");\n";
1091 for (int i = 0; i < indent_level; ++i) {
1092 callbuf << kIndentString;
1093 }
1094 callbuf << "return;\n";
1095 buf << typedefbuf.str() << callbuf.str();
1096 }
1097 --indent_level;
1098 for (int i = 0; i < indent_level; ++i) {
1099 buf << kIndentString;
1100 }
1101 buf << "}\n";
1102 }
1103}
1104
1106{
1108
1109 const Decl *D = GetFunctionOrShadowDecl();
1110 string wrapper_name;
1111 string wrapper;
1112
1113 if (get_wrapper_code(wrapper_name, wrapper) == 0) return 0;
1114
1115 //fprintf(stderr, "%s\n", wrapper.c_str());
1116 //
1117 // Compile the wrapper code.
1118 //
1119 void *F = compile_wrapper(wrapper_name, wrapper);
1120 if (F) {
1121 gWrapperStore.insert(make_pair(D, F));
1122 } else {
1123 ::Error("TClingCallFunc::make_wrapper",
1124 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1125 wrapper.c_str());
1126 }
1128}
1129
1131 ROOT::TMetaUtils::EIOCtorCategory kind, const std::string &type_name)
1132{
1133 // Make a code string that follows this pattern:
1134 //
1135 // void
1136 // unique_wrapper_ddd(void** ret, void* arena, unsigned long nary)
1137 // {
1138 // if (!arena) {
1139 // if (!nary) {
1140 // *ret = new ClassName;
1141 // }
1142 // else {
1143 // *ret = new ClassName[nary];
1144 // }
1145 // }
1146 // else {
1147 // if (!nary) {
1148 // *ret = new (arena) ClassName;
1149 // }
1150 // else {
1151 // *ret = new (arena) ClassName[nary];
1152 // }
1153 // }
1154 // }
1155 //
1156 // When I/O constructor used:
1157 //
1158 // void
1159 // unique_wrapper_ddd(void** ret, void* arena, unsigned long nary)
1160 // {
1161 // if (!arena) {
1162 // if (!nary) {
1163 // *ret = new ClassName((TRootIOCtor*)nullptr);
1164 // }
1165 // else {
1166 // char *buf = malloc(nary * sizeof(ClassName));
1167 // for (int k=0;k<nary;++k)
1168 // new (buf + k * sizeof(ClassName)) ClassName((TRootIOCtor*)nullptr);
1169 // *ret = buf;
1170 // }
1171 // }
1172 // else {
1173 // if (!nary) {
1174 // *ret = new (arena) ClassName((TRootIOCtor*)nullptr);
1175 // }
1176 // else {
1177 // for (int k=0;k<nary;++k)
1178 // new ((char *) arena + k * sizeof(ClassName)) ClassName((TRootIOCtor*)nullptr);
1179 // *ret = arena;
1180 // }
1181 // }
1182 // }
1183 //
1184 //
1185 // Note:
1186 //
1187 // If the class is of POD type, the form:
1188 //
1189 // new ClassName;
1190 //
1191 // does not initialize the object at all, and the form:
1192 //
1193 // new ClassName();
1194 //
1195 // default-initializes the object.
1196 //
1197 // We are using the form without parentheses because that is what
1198 // CINT did.
1199 //
1200 //--
1201 ASTContext &Context = info->GetDecl()->getASTContext();
1202 PrintingPolicy Policy(Context.getPrintingPolicy());
1203 Policy.SuppressTagKeyword = true;
1204 Policy.SuppressUnwrittenScope = true;
1205 //
1206 // Get the class or namespace name.
1207 //
1208 string class_name;
1209 if (const TypeDecl *TD = dyn_cast<TypeDecl>(info->GetDecl())) {
1210 // This is a class, struct, or union member.
1211 QualType QT(TD->getTypeForDecl(), 0);
1213 } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(info->GetDecl())) {
1214 // This is a namespace member.
1215 raw_string_ostream stream(class_name);
1216 ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
1217 stream.flush();
1218 }
1219
1220
1221 //
1222 // Make the wrapper name.
1223 //
1224 string wrapper_name;
1225 {
1226 ostringstream buf;
1227 buf << "__ctor";
1228 //const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
1229 //string mn;
1230 //fInterp->maybeMangleDeclName(ND, mn);
1231 //buf << '_dtor_' << mn;
1232 buf << '_' << gWrapperSerial++;
1233 wrapper_name = buf.str();
1234 }
1235
1236 string constr_arg;
1238 constr_arg = string("((") + type_name + "*)nullptr)";
1240 constr_arg = string("(*((") + type_name + "*)arena))";
1241
1242 //
1243 // Write the wrapper code.
1244 //
1245 int indent_level = 0;
1246 ostringstream buf;
1247 buf << "__attribute__((used)) ";
1248 buf << "extern \"C\" void ";
1249 buf << wrapper_name;
1250 buf << "(void** ret, void* arena, unsigned long nary)\n";
1251 buf << "{\n";
1252
1253 // if (!arena) {
1254 // if (!nary) {
1255 // *ret = new ClassName;
1256 // }
1257 // else {
1258 // *ret = new ClassName[nary];
1259 // }
1260 // }
1261 indent(buf, ++indent_level);
1262 buf << "if (!arena) {\n";
1263 indent(buf, ++indent_level);
1264 buf << "if (!nary) {\n";
1265 indent(buf, ++indent_level);
1266 buf << "*ret = new " << class_name << constr_arg << ";\n";
1267 indent(buf, --indent_level);
1268 buf << "}\n";
1269 indent(buf, indent_level);
1270 buf << "else {\n";
1271 indent(buf, ++indent_level);
1272 if (constr_arg.empty()) {
1273 buf << "*ret = new " << class_name << "[nary];\n";
1274 } else {
1275 buf << "char *buf = (char *) malloc(nary * sizeof(" << class_name << "));\n";
1276 indent(buf, indent_level);
1277 buf << "for (int k=0;k<nary;++k)\n";
1278 indent(buf, ++indent_level);
1279 buf << "new (buf + k * sizeof(" << class_name << ")) " << class_name << constr_arg << ";\n";
1280 indent(buf, --indent_level);
1281 buf << "*ret = buf;\n";
1282 }
1283 indent(buf, --indent_level);
1284 buf << "}\n";
1285 indent(buf, --indent_level);
1286 buf << "}\n";
1287 // else {
1288 // if (!nary) {
1289 // *ret = new (arena) ClassName;
1290 // }
1291 // else {
1292 // *ret = new (arena) ClassName[nary];
1293 // }
1294 // }
1295 indent(buf, indent_level);
1296 buf << "else {\n";
1297 indent(buf, ++indent_level);
1298 buf << "if (!nary) {\n";
1299 indent(buf, ++indent_level);
1300 buf << "*ret = new (arena) " << class_name << constr_arg << ";\n";
1301 indent(buf, --indent_level);
1302 buf << "}\n";
1303 indent(buf, indent_level);
1304 buf << "else {\n";
1305 indent(buf, ++indent_level);
1306 if (constr_arg.empty()) {
1307 buf << "*ret = new (arena) " << class_name << "[nary];\n";
1308 } else {
1309 buf << "for (int k=0;k<nary;++k)\n";
1310 indent(buf, ++indent_level);
1311 buf << "new ((char *) arena + k * sizeof(" << class_name << ")) " << class_name << constr_arg << ";\n";
1312 indent(buf, --indent_level);
1313 buf << "*ret = arena;\n";
1314 }
1315 indent(buf, --indent_level);
1316 buf << "}\n";
1317 indent(buf, --indent_level);
1318 buf << "}\n";
1319 // End wrapper.
1320 --indent_level;
1321 buf << "}\n";
1322 // Done.
1323 string wrapper(buf.str());
1324 //fprintf(stderr, "%s\n", wrapper.c_str());
1325 //
1326 // Compile the wrapper code.
1327 //
1328 void *F = compile_wrapper(wrapper_name, wrapper,
1329 /*withAccessControl=*/false);
1330 if (F) {
1331 gCtorWrapperStore.insert(make_pair(info->GetDecl(), F));
1332 } else {
1333 ::Error("TClingCallFunc::make_ctor_wrapper",
1334 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1335 wrapper.c_str());
1336 }
1338}
1339
1342{
1343 // Make a code string that follows this pattern:
1344 //
1345 // void
1346 // unique_wrapper_ddd(void* obj, unsigned long nary, int withFree)
1347 // {
1348 // if (withFree) {
1349 // if (!nary) {
1350 // delete (ClassName*) obj;
1351 // }
1352 // else {
1353 // delete[] (ClassName*) obj;
1354 // }
1355 // }
1356 // else {
1357 // typedef ClassName DtorName;
1358 // if (!nary) {
1359 // ((ClassName*)obj)->~DtorName();
1360 // }
1361 // else {
1362 // for (unsigned long i = nary - 1; i > -1; --i) {
1363 // (((ClassName*)obj)+i)->~DtorName();
1364 // }
1365 // }
1366 // }
1367 // }
1368 //
1369 //--
1370 ASTContext &Context = info->GetDecl()->getASTContext();
1371 PrintingPolicy Policy(Context.getPrintingPolicy());
1372 Policy.SuppressTagKeyword = true;
1373 Policy.SuppressUnwrittenScope = true;
1374 //
1375 // Get the class or namespace name.
1376 //
1377 string class_name;
1378 if (const TypeDecl *TD = dyn_cast<TypeDecl>(info->GetDecl())) {
1379 // This is a class, struct, or union member.
1380 QualType QT(TD->getTypeForDecl(), 0);
1382 } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(info->GetDecl())) {
1383 // This is a namespace member.
1384 raw_string_ostream stream(class_name);
1385 ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
1386 stream.flush();
1387 }
1388 //
1389 // Make the wrapper name.
1390 //
1391 string wrapper_name;
1392 {
1393 ostringstream buf;
1394 buf << "__dtor";
1395 //const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
1396 //string mn;
1397 //fInterp->maybeMangleDeclName(ND, mn);
1398 //buf << '_dtor_' << mn;
1399 buf << '_' << gWrapperSerial++;
1400 wrapper_name = buf.str();
1401 }
1402 //
1403 // Write the wrapper code.
1404 //
1405 int indent_level = 0;
1406 ostringstream buf;
1407 buf << "__attribute__((used)) ";
1408 buf << "extern \"C\" void ";
1409 buf << wrapper_name;
1410 buf << "(void* obj, unsigned long nary, int withFree)\n";
1411 buf << "{\n";
1412 // if (withFree) {
1413 // if (!nary) {
1414 // delete (ClassName*) obj;
1415 // }
1416 // else {
1417 // delete[] (ClassName*) obj;
1418 // }
1419 // }
1420 ++indent_level;
1421 indent(buf, indent_level);
1422 buf << "if (withFree) {\n";
1423 ++indent_level;
1424 indent(buf, indent_level);
1425 buf << "if (!nary) {\n";
1426 ++indent_level;
1427 indent(buf, indent_level);
1428 buf << "delete (" << class_name << "*) obj;\n";
1429 --indent_level;
1430 indent(buf, indent_level);
1431 buf << "}\n";
1432 indent(buf, indent_level);
1433 buf << "else {\n";
1434 ++indent_level;
1435 indent(buf, indent_level);
1436 buf << "delete[] (" << class_name << "*) obj;\n";
1437 --indent_level;
1438 indent(buf, indent_level);
1439 buf << "}\n";
1440 --indent_level;
1441 indent(buf, indent_level);
1442 buf << "}\n";
1443 // else {
1444 // typedef ClassName Nm;
1445 // if (!nary) {
1446 // ((Nm*)obj)->~Nm();
1447 // }
1448 // else {
1449 // for (unsigned long i = nary - 1; i > -1; --i) {
1450 // (((Nm*)obj)+i)->~Nm();
1451 // }
1452 // }
1453 // }
1454 indent(buf, indent_level);
1455 buf << "else {\n";
1456 ++indent_level;
1457 indent(buf, indent_level);
1458 buf << "typedef " << class_name << " Nm;\n";
1459 buf << "if (!nary) {\n";
1460 ++indent_level;
1461 indent(buf, indent_level);
1462 buf << "((Nm*)obj)->~Nm();\n";
1463 --indent_level;
1464 indent(buf, indent_level);
1465 buf << "}\n";
1466 indent(buf, indent_level);
1467 buf << "else {\n";
1468 ++indent_level;
1469 indent(buf, indent_level);
1470 buf << "do {\n";
1471 ++indent_level;
1472 indent(buf, indent_level);
1473 buf << "(((Nm*)obj)+(--nary))->~Nm();\n";
1474 --indent_level;
1475 indent(buf, indent_level);
1476 buf << "} while (nary);\n";
1477 --indent_level;
1478 indent(buf, indent_level);
1479 buf << "}\n";
1480 --indent_level;
1481 indent(buf, indent_level);
1482 buf << "}\n";
1483 // End wrapper.
1484 --indent_level;
1485 buf << "}\n";
1486 // Done.
1487 string wrapper(buf.str());
1488 //fprintf(stderr, "%s\n", wrapper.c_str());
1489 //
1490 // Compile the wrapper code.
1491 //
1492 void *F = compile_wrapper(wrapper_name, wrapper,
1493 /*withAccessControl=*/false);
1494 if (F) {
1495 gDtorWrapperStore.insert(make_pair(info->GetDecl(), F));
1496 } else {
1497 ::Error("TClingCallFunc::make_dtor_wrapper",
1498 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1499 wrapper.c_str());
1500 }
1501
1503}
1504
1505class ValHolder {
1506public:
1507 union {
1508 long double ldbl;
1509 double dbl;
1510 float flt;
1511 //__uint128_t ui128;
1512 //__int128_t i128;
1513 unsigned long long ull;
1514 long long ll;
1515 unsigned long ul;
1516 long l;
1517 unsigned int ui;
1518 int i;
1519 unsigned short us;
1520 short s;
1521 //char32_t c32;
1522 //char16_t c16;
1523 //unsigned wchar_t uwc; - non-standard
1524 wchar_t wc;
1525 unsigned char uc;
1526 signed char sc;
1527 char c;
1528 bool b;
1529 void *vp;
1530 } u;
1531};
1532
1533void TClingCallFunc::exec(void *address, void *ret)
1534{
1535 SmallVector<ValHolder, 8> vh_ary;
1536 SmallVector<void *, 8> vp_ary;
1537
1538 unsigned num_args = fArgVals.size();
1539 {
1541
1542 const FunctionDecl *FD = GetDecl();
1543
1544 //
1545 // Convert the arguments from cling::Value to their
1546 // actual type and store them in a holder for passing to the
1547 // wrapper function by pointer to value.
1548 //
1549 unsigned num_params = FD->getNumParams();
1550
1551 if (num_args < GetMinRequiredArguments()) {
1552 ::Error("TClingCallFunc::exec",
1553 "Not enough arguments provided for %s (%d instead of the minimum %d)",
1554 fMethod->Name(),
1555 num_args, (int)GetMinRequiredArguments());
1556 return;
1557 }
1558 if (address == 0 && dyn_cast<CXXMethodDecl>(FD)
1559 && !(dyn_cast<CXXMethodDecl>(FD))->isStatic()
1560 && !dyn_cast<CXXConstructorDecl>(FD)) {
1561 ::Error("TClingCallFunc::exec",
1562 "The method %s is called without an object.",
1563 fMethod->Name());
1564 return;
1565 }
1566 vh_ary.reserve(num_args);
1567 vp_ary.reserve(num_args);
1568 for (unsigned i = 0U; i < num_args; ++i) {
1569 QualType Ty;
1570 if (i < num_params) {
1571 const ParmVarDecl *PVD = FD->getParamDecl(i);
1572 Ty = PVD->getType();
1573 } else {
1574 Ty = fArgVals[i].getType();
1575 }
1576 QualType QT = Ty.getCanonicalType();
1577 if (const BuiltinType *BT =
1578 dyn_cast<BuiltinType>(&*QT)) {
1579 //
1580 // WARNING!!!
1581 //
1582 // This switch is organized in order-of-declaration
1583 // so that the produced assembly code is optimal.
1584 // Do not reorder!
1585 //
1586 switch (BT->getKind()) {
1587 //
1588 // Builtin Types
1589 //
1590 case BuiltinType::Void: {
1591 // void
1592 ::Error("TClingCallFunc::exec(void*)",
1593 "Invalid type 'Void'!");
1594 return;
1595 }
1596 break;
1597 //
1598 // Unsigned Types
1599 //
1600 case BuiltinType::Bool: {
1601 // bool
1602 ValHolder vh;
1603 vh.u.b = (bool) sv_to_ulong_long(fArgVals[i]);
1604 vh_ary.push_back(vh);
1605 vp_ary.push_back(&vh_ary.back());
1606 }
1607 break;
1608 case BuiltinType::Char_U: {
1609 // char on targets where it is unsigned
1610 ValHolder vh;
1611 vh.u.c = (char) sv_to_ulong_long(fArgVals[i]);
1612 vh_ary.push_back(vh);
1613 vp_ary.push_back(&vh_ary.back());
1614 }
1615 break;
1616 case BuiltinType::UChar: {
1617 // unsigned char
1618 ValHolder vh;
1619 vh.u.uc = (unsigned char) sv_to_ulong_long(fArgVals[i]);
1620 vh_ary.push_back(vh);
1621 vp_ary.push_back(&vh_ary.back());
1622 }
1623 break;
1624 case BuiltinType::WChar_U: {
1625 // wchar_t on targets where it is unsigned.
1626 // The standard doesn't allow to specify signednedd of wchar_t
1627 // thus this maps simply to wchar_t.
1628 ValHolder vh;
1629 vh.u.wc = (wchar_t) sv_to_ulong_long(fArgVals[i]);
1630 vh_ary.push_back(vh);
1631 vp_ary.push_back(&vh_ary.back());
1632 }
1633 break;
1634 case BuiltinType::Char16: {
1635 // char16_t
1636 //ValHolder vh;
1637 //vh.u.c16 = (char16_t) sv_to_ulong_long(fArgVals[i]);
1638 //vh_ary.push_back(vh);
1639 //vp_ary.push_back(&vh_ary.back());
1640 }
1641 break;
1642 case BuiltinType::Char32: {
1643 // char32_t
1644 //ValHolder vh;
1645 //vh.u.c32 = (char32_t) sv_to_ulong_long(fArgVals[i]);
1646 //vh_ary.push_back(vh);
1647 //vp_ary.push_back(&vh_ary.back());
1648 }
1649 break;
1650 case BuiltinType::UShort: {
1651 // unsigned short
1652 ValHolder vh;
1653 vh.u.us = (unsigned short) sv_to_ulong_long(fArgVals[i]);
1654 vh_ary.push_back(vh);
1655 vp_ary.push_back(&vh_ary.back());
1656 }
1657 break;
1658 case BuiltinType::UInt: {
1659 // unsigned int
1660 ValHolder vh;
1661 vh.u.ui = (unsigned int) sv_to_ulong_long(fArgVals[i]);
1662 vh_ary.push_back(vh);
1663 vp_ary.push_back(&vh_ary.back());
1664 }
1665 break;
1666 case BuiltinType::ULong: {
1667 // unsigned long
1668 ValHolder vh;
1669 vh.u.ul = (unsigned long) sv_to_ulong_long(fArgVals[i]);
1670 vh_ary.push_back(vh);
1671 vp_ary.push_back(&vh_ary.back());
1672 }
1673 break;
1674 case BuiltinType::ULongLong: {
1675 // unsigned long long
1676 ValHolder vh;
1677 vh.u.ull = (unsigned long long) sv_to_ulong_long(fArgVals[i]);
1678 vh_ary.push_back(vh);
1679 vp_ary.push_back(&vh_ary.back());
1680 }
1681 break;
1682 case BuiltinType::UInt128: {
1683 // __uint128_t
1684 }
1685 break;
1686 //
1687 // Signed Types
1688 //
1689 //
1690 // Signed Types
1691 //
1692 case BuiltinType::Char_S: {
1693 // char on targets where it is signed
1694 ValHolder vh;
1695 vh.u.c = (char) sv_to_long_long(fArgVals[i]);
1696 vh_ary.push_back(vh);
1697 vp_ary.push_back(&vh_ary.back());
1698 }
1699 break;
1700 case BuiltinType::SChar: {
1701 // signed char
1702 ValHolder vh;
1703 vh.u.sc = (signed char) sv_to_long_long(fArgVals[i]);
1704 vh_ary.push_back(vh);
1705 vp_ary.push_back(&vh_ary.back());
1706 }
1707 break;
1708 case BuiltinType::WChar_S: {
1709 // wchar_t on targets where it is signed.
1710 // The standard doesn't allow to specify signednedd of wchar_t
1711 // thus this maps simply to wchar_t.
1712 ValHolder vh;
1713 vh.u.wc = (wchar_t) sv_to_long_long(fArgVals[i]);
1714 vh_ary.push_back(vh);
1715 vp_ary.push_back(&vh_ary.back());
1716 }
1717 break;
1718 case BuiltinType::Short: {
1719 // short
1720 ValHolder vh;
1721 vh.u.s = (short) sv_to_long_long(fArgVals[i]);
1722 vh_ary.push_back(vh);
1723 vp_ary.push_back(&vh_ary.back());
1724 }
1725 break;
1726 case BuiltinType::Int: {
1727 // int
1728 ValHolder vh;
1729 vh.u.i = (int) sv_to_long_long(fArgVals[i]);
1730 vh_ary.push_back(vh);
1731 vp_ary.push_back(&vh_ary.back());
1732 }
1733 break;
1734 case BuiltinType::Long: {
1735 // long
1736 ValHolder vh;
1737 vh.u.l = (long) sv_to_long_long(fArgVals[i]);
1738 vh_ary.push_back(vh);
1739 vp_ary.push_back(&vh_ary.back());
1740 }
1741 break;
1742 case BuiltinType::LongLong: {
1743 // long long
1744 ValHolder vh;
1745 vh.u.ll = (long long) sv_to_long_long(fArgVals[i]);
1746 vh_ary.push_back(vh);
1747 vp_ary.push_back(&vh_ary.back());
1748 }
1749 break;
1750 case BuiltinType::Int128: {
1751 // __int128_t
1752 ::Error("TClingCallFunc::exec(void*)",
1753 "Invalid type 'Int128'!");
1754 return;
1755 }
1756 break;
1757 case BuiltinType::Half: {
1758 // half in OpenCL, __fp16 in ARM NEON
1759 ::Error("TClingCallFunc::exec(void*)",
1760 "Invalid type 'Half'!");
1761 return;
1762 }
1763 break;
1764 case BuiltinType::Float: {
1765 // float
1766 ValHolder vh;
1767 vh.u.flt = sv_to<float>(fArgVals[i]);
1768 vh_ary.push_back(vh);
1769 vp_ary.push_back(&vh_ary.back());
1770 }
1771 break;
1772 case BuiltinType::Double: {
1773 // double
1774 ValHolder vh;
1775 vh.u.dbl = sv_to<double>(fArgVals[i]);
1776 vh_ary.push_back(vh);
1777 vp_ary.push_back(&vh_ary.back());
1778 }
1779 break;
1780 case BuiltinType::LongDouble: {
1781 // long double
1782 ValHolder vh;
1783 vh.u.ldbl = sv_to<long double>(fArgVals[i]);
1784 vh_ary.push_back(vh);
1785 vp_ary.push_back(&vh_ary.back());
1786 }
1787 break;
1788 //
1789 // Language-Specific Types
1790 //
1791 case BuiltinType::NullPtr: {
1792 // C++11 nullptr
1793 ValHolder vh;
1794 vh.u.vp = fArgVals[i].getPtr();
1795 vh_ary.push_back(vh);
1796 vp_ary.push_back(&vh_ary.back());
1797 }
1798 break;
1799 default: {
1800 // There should be no others. This is here in case
1801 // this changes in the future.
1802 ::Error("TClingCallFunc::exec(void*)",
1803 "Unhandled builtin type!");
1804 QT->dump();
1805 return;
1806 }
1807 break;
1808 }
1809 } else if (QT->isReferenceType()) {
1810 // the argument is already a pointer value (point to the same thing
1811 // as the reference.
1812 vp_ary.push_back((void *) sv_to_ulong_long(fArgVals[i]));
1813 } else if (QT->isPointerType() || QT->isArrayType()) {
1814 ValHolder vh;
1815 vh.u.vp = (void *) sv_to_ulong_long(fArgVals[i]);
1816 vh_ary.push_back(vh);
1817 vp_ary.push_back(&vh_ary.back());
1818 } else if (QT->isRecordType()) {
1819 // the argument is already a pointer value (pointing to object passed
1820 // by value).
1821 vp_ary.push_back((void *) sv_to_ulong_long(fArgVals[i]));
1822 } else if (const EnumType *ET =
1823 dyn_cast<EnumType>(&*QT)) {
1824 // Note: We may need to worry about the underlying type
1825 // of the enum here.
1826 (void) ET;
1827 ValHolder vh;
1828 vh.u.i = (int) sv_to_long_long(fArgVals[i]);
1829 vh_ary.push_back(vh);
1830 vp_ary.push_back(&vh_ary.back());
1831 } else if (QT->isMemberPointerType()) {
1832 ValHolder vh;
1833 vh.u.vp = (void *) sv_to_ulong_long(fArgVals[i]);
1834 vh_ary.push_back(vh);
1835 vp_ary.push_back(&vh_ary.back());
1836 } else {
1837 ::Error("TClingCallFunc::exec(void*)",
1838 "Invalid type (unrecognized)!");
1839 QT->dump();
1840 return;
1841 }
1842 }
1843 } // End of scope holding the lock
1844 (*fWrapper)(address, (int)num_args, (void **)vp_ary.data(), ret);
1845}
1846
1847template <typename T>
1848void TClingCallFunc::execWithLL(void *address, cling::Value *val)
1849{
1850 T ret; // leave uninit for valgrind's sake!
1851 exec(address, &ret);
1852 val->getLL() = ret;
1853}
1854
1855template <typename T>
1856void TClingCallFunc::execWithULL(void *address, cling::Value *val)
1857{
1858 T ret; // leave uninit for valgrind's sake!
1859 exec(address, &ret);
1860 val->getULL() = ret;
1861}
1862
1863// Handle integral types.
1864template <class T>
1866{
1867 ret = cling::Value::Create<T>(QT.getAsOpaquePtr(), *fInterp);
1868 static_assert(std::is_integral<T>::value, "Must be called with integral T");
1869 if (std::is_signed<T>::value)
1870 return [this](void* address, cling::Value& ret) { execWithLL<T>(address, &ret); };
1871 else
1872 return [this](void* address, cling::Value& ret) { execWithULL<T>(address, &ret); };
1873}
1874
1875// Handle builtin types.
1877TClingCallFunc::InitRetAndExecBuiltin(QualType QT, const clang::BuiltinType *BT, cling::Value &ret) {
1878 switch (BT->getKind()) {
1879 case BuiltinType::Void: {
1880 ret = cling::Value::Create<void>(QT.getAsOpaquePtr(), *fInterp);
1881 return [this](void* address, cling::Value& ret) { exec(address, 0); };
1882 break;
1883 }
1884
1885 //
1886 // Unsigned Types
1887 //
1888 case BuiltinType::Bool:
1889 return InitRetAndExecIntegral<bool>(QT, ret);
1890 break;
1891 case BuiltinType::Char_U: // char on targets where it is unsigned
1892 case BuiltinType::UChar:
1893 return InitRetAndExecIntegral<char>(QT, ret);
1894 break;
1895 case BuiltinType::WChar_U:
1896 return InitRetAndExecIntegral<wchar_t>(QT, ret);
1897 break;
1898 case BuiltinType::Char16:
1899 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1900 "Invalid type 'char16_t'!");
1901 return {};
1902 break;
1903 case BuiltinType::Char32:
1904 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1905 "Invalid type 'char32_t'!");
1906 return {};
1907 break;
1908 case BuiltinType::UShort:
1909 return InitRetAndExecIntegral<unsigned short>(QT, ret);
1910 break;
1911 case BuiltinType::UInt:
1912 return InitRetAndExecIntegral<unsigned int>(QT, ret);
1913 break;
1914 case BuiltinType::ULong:
1915 return InitRetAndExecIntegral<unsigned long>(QT, ret);
1916 break;
1917 case BuiltinType::ULongLong:
1918 return InitRetAndExecIntegral<unsigned long long>(QT, ret);
1919 break;
1920 case BuiltinType::UInt128: {
1921 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1922 "Invalid type '__uint128_t'!");
1923 return {};
1924 }
1925 break;
1926
1927 //
1928 // Signed Types
1929 //
1930 case BuiltinType::Char_S: // char on targets where it is signed
1931 case BuiltinType::SChar:
1932 return InitRetAndExecIntegral<signed char>(QT, ret);
1933 break;
1934 case BuiltinType::WChar_S:
1935 // wchar_t on targets where it is signed.
1936 // The standard doesn't allow to specify signednedd of wchar_t
1937 // thus this maps simply to wchar_t.
1938 return InitRetAndExecIntegral<wchar_t>(QT, ret);
1939 break;
1940 case BuiltinType::Short:
1941 return InitRetAndExecIntegral<short>(QT, ret);
1942 break;
1943 case BuiltinType::Int:
1944 return InitRetAndExecIntegral<int>(QT, ret);
1945 break;
1946 case BuiltinType::Long:
1947 return InitRetAndExecIntegral<long>(QT, ret);
1948 break;
1949 case BuiltinType::LongLong:
1950 return InitRetAndExecIntegral<long long>(QT, ret);
1951 break;
1952 case BuiltinType::Int128:
1953 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1954 "Invalid type '__int128_t'!");
1955 return {};
1956 break;
1957 case BuiltinType::Half:
1958 // half in OpenCL, __fp16 in ARM NEON
1959 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1960 "Invalid type 'Half'!");
1961 return {};
1962 break;
1963 case BuiltinType::Float: {
1964 ret = cling::Value::Create<float>(QT.getAsOpaquePtr(), *fInterp);
1965 return [this](void* address, cling::Value& ret) { exec(address, &ret.getFloat()); };
1966 break;
1967 }
1968 case BuiltinType::Double: {
1969 ret = cling::Value::Create<double>(QT.getAsOpaquePtr(), *fInterp);
1970 return [this](void* address, cling::Value& ret) { exec(address, &ret.getDouble()); };
1971 break;
1972 }
1973 case BuiltinType::LongDouble: {
1974 ret = cling::Value::Create<long double>(QT.getAsOpaquePtr(), *fInterp);
1975 return [this](void* address, cling::Value& ret) { exec(address, &ret.getLongDouble()); };
1976 break;
1977 }
1978 //
1979 // Language-Specific Types
1980 //
1981 case BuiltinType::NullPtr:
1982 // C++11 nullptr
1983 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1984 "Invalid type 'nullptr'!");
1985 return {};
1986 break;
1987 default:
1988 break;
1989 }
1990 return {};
1991}
1992
1993
1995TClingCallFunc::InitRetAndExecNoCtor(clang::QualType QT, cling::Value &ret) {
1996 if (QT->isReferenceType()) {
1997 ret = cling::Value(QT, *fInterp);
1998 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
1999 } else if (QT->isMemberPointerType()) {
2000 const MemberPointerType *MPT = QT->getAs<MemberPointerType>();
2001 if (MPT->isMemberDataPointer()) {
2002 // A member data pointer is a actually a struct with one
2003 // member of ptrdiff_t, the offset from the base of the object
2004 // storage to the storage for the designated data member.
2005 // But that's not relevant: we use it as a non-builtin, allocated
2006 // type.
2007 ret = cling::Value(QT, *fInterp);
2008 return [this](void* address, cling::Value& ret) { exec(address, ret.getPtr()); };
2009 }
2010 // We are a function member pointer.
2011 ret = cling::Value(QT, *fInterp);
2012 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2013 } else if (QT->isPointerType() || QT->isArrayType()) {
2014 // Note: ArrayType is an illegal function return value type.
2015 ret = cling::Value::Create<void*>(QT.getAsOpaquePtr(), *fInterp);
2016 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2017 } else if (QT->isRecordType()) {
2018 ret = cling::Value(QT, *fInterp);
2019 return [this](void* address, cling::Value& ret) { exec(address, ret.getPtr()); };
2020 } else if (const EnumType *ET = dyn_cast<EnumType>(&*QT)) {
2021 // Note: We may need to worry about the underlying type
2022 // of the enum here.
2023 (void) ET;
2024 ret = cling::Value(QT, *fInterp);
2025 return [this](void* address, cling::Value& ret) { execWithLL<int>(address, &ret); };
2026 } else if (const BuiltinType *BT = dyn_cast<BuiltinType>(&*QT)) {
2027 return InitRetAndExecBuiltin(QT, BT, ret);
2028 }
2029 ::Error("TClingCallFunc::exec_with_valref_return",
2030 "Unrecognized return type!");
2031 QT->dump();
2032 return {};
2033}
2034
2036TClingCallFunc::InitRetAndExec(const clang::FunctionDecl *FD, cling::Value &ret) {
2037 if (llvm::isa<CXXConstructorDecl>(FD)) {
2038 ASTContext &Context = FD->getASTContext();
2039 const TypeDecl *TD = dyn_cast<TypeDecl>(GetDeclContext());
2040 QualType ClassTy(TD->getTypeForDecl(), 0);
2041 QualType QT = Context.getLValueReferenceType(ClassTy);
2042 ret = cling::Value(QT, *fInterp);
2043 // Store the new()'ed address in getPtr()
2044 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2045 } else {
2046 QualType QT = FD->getReturnType().getCanonicalType();
2047 return InitRetAndExecNoCtor(QT, ret);
2048 }
2049}
2050
2051void TClingCallFunc::exec_with_valref_return(void *address, cling::Value *ret)
2052{
2053 if (!ret) {
2054 exec(address, 0);
2055 return;
2056 }
2057 std::function<void(void*, cling::Value&)> execFunc;
2058
2059 /* Release lock during user function execution*/
2060 {
2062 execFunc = InitRetAndExec(GetDecl(), *ret);
2063 }
2064
2065 if (execFunc)
2066 execFunc(address, *ret);
2067 return;
2068}
2069
2070void TClingCallFunc::EvaluateArgList(const string &ArgList)
2071{
2073
2074 SmallVector<Expr *, 4> exprs;
2075 fInterp->getLookupHelper().findArgList(ArgList, exprs,
2076 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
2077 : cling::LookupHelper::NoDiagnostics);
2078 for (SmallVectorImpl<Expr *>::const_iterator I = exprs.begin(),
2079 E = exprs.end(); I != E; ++I) {
2080 cling::Value val;
2081 EvaluateExpr(*fInterp, *I, val);
2082 if (!val.isValid()) {
2083 // Bad expression, all done.
2084 ::Error("TClingCallFunc::EvaluateArgList",
2085 "Bad expression in parameter %d of '%s'!",
2086 (int)(I - exprs.begin()),
2087 ArgList.c_str());
2088 return;
2089 }
2090 fArgVals.push_back(val);
2091 }
2092}
2093
2094void TClingCallFunc::Exec(void *address, TInterpreterValue *interpVal/*=0*/)
2095{
2096 IFacePtr();
2097 if (!fWrapper) {
2098 ::Error("TClingCallFunc::Exec(address, interpVal)",
2099 "Called with no wrapper, not implemented!");
2100 return;
2101 }
2102 if (!interpVal) {
2103 exec(address, 0);
2104 return;
2105 }
2106 cling::Value *val = reinterpret_cast<cling::Value *>(interpVal->GetValAddr());
2107 exec_with_valref_return(address, val);
2108}
2109
2110template <typename T>
2112{
2113 IFacePtr();
2114 if (!fWrapper) {
2115 ::Error("TClingCallFunc::ExecT",
2116 "Called with no wrapper, not implemented!");
2117 return 0;
2118 }
2119 cling::Value ret;
2120 exec_with_valref_return(address, &ret);
2121 if (!ret.isValid()) {
2122 // Sometimes we are called on a function returning void!
2123 return 0;
2124 }
2125
2127 ((TCling *)gCling)->RegisterTemporary(ret);
2128 return sv_to<T>(ret);
2129}
2130
2132{
2133 return ExecT<long>(address);
2134}
2135
2136long long TClingCallFunc::ExecInt64(void *address)
2137{
2138 return ExecT<long long>(address);
2139}
2140
2141double TClingCallFunc::ExecDouble(void *address)
2142{
2143 return ExecT<double>(address);
2144}
2145
2146void TClingCallFunc::ExecWithArgsAndReturn(void *address, const void *args[] /*= 0*/,
2147 int nargs /*= 0*/, void *ret/*= 0*/)
2148{
2149 IFacePtr();
2150 if (!fWrapper) {
2151 ::Error("TClingCallFunc::ExecWithArgsAndReturn(address, args, ret)",
2152 "Called with no wrapper, not implemented!");
2153 return;
2154 }
2155 (*fWrapper)(address, nargs, const_cast<void **>(args), ret);
2156}
2157
2158void TClingCallFunc::ExecWithReturn(void *address, void *ret/*= 0*/)
2159{
2160 IFacePtr();
2161 if (!fWrapper) {
2162 ::Error("TClingCallFunc::ExecWithReturn(address, ret)",
2163 "Called with no wrapper, not implemented!");
2164 return;
2165 }
2166 exec(address, ret);
2167}
2168
2171 const std::string &type_name,
2172 void *address /*=0*/, unsigned long nary /*= 0UL*/)
2173{
2174 if (!info->IsValid()) {
2175 ::Error("TClingCallFunc::ExecDefaultConstructor", "Invalid class info!");
2176 return nullptr;
2177 }
2178 tcling_callfunc_ctor_Wrapper_t wrapper = nullptr;
2179 {
2181 auto D = info->GetDecl();
2182 //if (!info->HasDefaultConstructor()) {
2183 // // FIXME: We might have a ROOT ioctor, we might
2184 // // have to check for that here.
2185 // ::Error("TClingCallFunc::ExecDefaultConstructor",
2186 // "Class has no default constructor: %s",
2187 // info->Name());
2188 // return 0;
2189 //}
2190 auto I = gCtorWrapperStore.find(D);
2191 if (I != gCtorWrapperStore.end()) {
2192 wrapper = (tcling_callfunc_ctor_Wrapper_t) I->second;
2193 } else {
2194 wrapper = make_ctor_wrapper(info, kind, type_name);
2195 }
2196 }
2197 if (!wrapper) {
2198 ::Error("TClingCallFunc::ExecDefaultConstructor",
2199 "Called with no wrapper, not implemented!");
2200 return nullptr;
2201 }
2202 void *obj = 0;
2203 (*wrapper)(&obj, address, nary);
2204 return obj;
2205}
2206
2207void TClingCallFunc::ExecDestructor(const TClingClassInfo *info, void *address /*=0*/,
2208 unsigned long nary /*= 0UL*/, bool withFree /*= true*/)
2209{
2210 if (!info->IsValid()) {
2211 ::Error("TClingCallFunc::ExecDestructor", "Invalid class info!");
2212 return;
2213 }
2214
2216 {
2218 const Decl *D = info->GetDecl();
2219 map<const Decl *, void *>::iterator I = gDtorWrapperStore.find(D);
2220 if (I != gDtorWrapperStore.end()) {
2221 wrapper = (tcling_callfunc_dtor_Wrapper_t) I->second;
2222 } else {
2223 wrapper = make_dtor_wrapper(info);
2224 }
2225 }
2226 if (!wrapper) {
2227 ::Error("TClingCallFunc::ExecDestructor",
2228 "Called with no wrapper, not implemented!");
2229 return;
2230 }
2231 (*wrapper)(address, nary, withFree);
2232}
2233
2236{
2237 return new TClingMethodInfo(*fMethod);
2238}
2239
2241{
2242 fMethod.reset();
2243 fWrapper = 0;
2244 fDecl = nullptr;
2246 ResetArg();
2247}
2248
2250{
2251 Init();
2252 fMethod = std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(minfo));
2253}
2254
2255void TClingCallFunc::Init(std::unique_ptr<TClingMethodInfo> minfo)
2256{
2257 Init();
2258 fMethod = std::move(minfo);
2259}
2260
2262{
2263 if (!IsValid()) {
2264 return 0;
2265 }
2266 if (!fWrapper) {
2267 const Decl *decl = GetFunctionOrShadowDecl();
2268
2270 map<const Decl *, void *>::iterator I = gWrapperStore.find(decl);
2271 if (I != gWrapperStore.end()) {
2273 } else {
2275 }
2276 }
2277 return (void *)fWrapper;
2278}
2279
2281{
2282 if (!fMethod) {
2283 return false;
2284 }
2285 return fMethod->IsValid();
2286}
2287
2289{
2290 if (!IsValid()) {
2291 ::Error("TClingCallFunc::IFacePtr(kind)",
2292 "Attempt to get interface while invalid.");
2294 }
2295 if (!fWrapper) {
2296 const Decl *decl = GetFunctionOrShadowDecl();
2297
2299 map<const Decl *, void *>::iterator I = gWrapperStore.find(decl);
2300 if (I != gWrapperStore.end()) {
2302 } else {
2304 }
2305
2306 fReturnIsRecordType = GetDecl()->getReturnType().getCanonicalType()->isRecordType();
2307 }
2309}
2310
2311
2313{
2314 fArgVals.clear();
2315}
2316
2317void TClingCallFunc::SetArg(unsigned long param)
2318{
2319 const ASTContext &C = fInterp->getCI()->getASTContext();
2320 fArgVals.push_back(cling::Value(C.UnsignedLongTy, *fInterp));
2321 fArgVals.back().getLL() = param;
2322}
2323
2325{
2326 const ASTContext &C = fInterp->getCI()->getASTContext();
2327 fArgVals.push_back(cling::Value(C.LongTy, *fInterp));
2328 fArgVals.back().getLL() = param;
2329}
2330
2331void TClingCallFunc::SetArg(float param)
2332{
2333 const ASTContext &C = fInterp->getCI()->getASTContext();
2334 fArgVals.push_back(cling::Value(C.FloatTy, *fInterp));
2335 fArgVals.back().getFloat() = param;
2336}
2337
2338void TClingCallFunc::SetArg(double param)
2339{
2340 const ASTContext &C = fInterp->getCI()->getASTContext();
2341 fArgVals.push_back(cling::Value(C.DoubleTy, *fInterp));
2342 fArgVals.back().getDouble() = param;
2343}
2344
2345void TClingCallFunc::SetArg(long long param)
2346{
2347 const ASTContext &C = fInterp->getCI()->getASTContext();
2348 fArgVals.push_back(cling::Value(C.LongLongTy, *fInterp));
2349 fArgVals.back().getLL() = param;
2350}
2351
2352void TClingCallFunc::SetArg(unsigned long long param)
2353{
2354 const ASTContext &C = fInterp->getCI()->getASTContext();
2355 fArgVals.push_back(cling::Value(C.UnsignedLongLongTy, *fInterp));
2356 fArgVals.back().getULL() = param;
2357}
2358
2359void TClingCallFunc::SetArgArray(long *paramArr, int nparam)
2360{
2361 ResetArg();
2362 for (int i = 0; i < nparam; ++i) {
2363 SetArg(paramArr[i]);
2364 }
2365}
2366
2367void TClingCallFunc::SetArgs(const char *params)
2368{
2369 ResetArg();
2370 EvaluateArgList(params);
2371}
2372
2373void TClingCallFunc::SetFunc(const TClingClassInfo *info, const char *method, const char *arglist,
2374 long *poffset)
2375{
2376 SetFunc(info, method, arglist, false, poffset);
2377}
2378
2379void TClingCallFunc::SetFunc(const TClingClassInfo *info, const char *method, const char *arglist,
2380 bool objectIsConst, long *poffset)
2381{
2382 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2383 if (poffset) {
2384 *poffset = 0L;
2385 }
2386 ResetArg();
2387 if (!info->IsValid()) {
2388 ::Error("TClingCallFunc::SetFunc", "Class info is invalid!");
2389 return;
2390 }
2391 if (!strcmp(arglist, ")")) {
2392 // CINT accepted a single right paren as meaning no arguments.
2393 arglist = "";
2394 }
2395 *fMethod = info->GetMethodWithArgs(method, arglist, objectIsConst, poffset);
2396 if (!fMethod->IsValid()) {
2397 //::Error("TClingCallFunc::SetFunc", "Could not find method %s(%s)", method,
2398 // arglist);
2399 return;
2400 }
2401 // FIXME: The arglist was already parsed by the lookup, we should
2402 // enhance the lookup to return the resulting expression
2403 // list so we do not need to parse it again here.
2404 EvaluateArgList(arglist);
2405}
2406
2408{
2409 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(*info)));
2410 ResetArg();
2411 if (!fMethod->IsValid()) {
2412 return;
2413 }
2414}
2415
2416void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2417 const char *proto, long *poffset,
2418 EFunctionMatchMode mode/*=kConversionMatch*/)
2419{
2420 SetFuncProto(info, method, proto, false, poffset, mode);
2421}
2422
2423void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2424 const char *proto, bool objectIsConst, long *poffset,
2425 EFunctionMatchMode mode/*=kConversionMatch*/)
2426{
2427 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2428 if (poffset) {
2429 *poffset = 0L;
2430 }
2431 ResetArg();
2432 if (!info->IsValid()) {
2433 ::Error("TClingCallFunc::SetFuncProto", "Class info is invalid!");
2434 return;
2435 }
2436 *fMethod = info->GetMethod(method, proto, objectIsConst, poffset, mode);
2437 if (!fMethod->IsValid()) {
2438 //::Error("TClingCallFunc::SetFuncProto", "Could not find method %s(%s)",
2439 // method, proto);
2440 return;
2441 }
2442}
2443
2444void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2445 const llvm::SmallVectorImpl<clang::QualType> &proto, long *poffset,
2446 EFunctionMatchMode mode/*=kConversionMatch*/)
2447{
2448 SetFuncProto(info, method, proto, false, poffset, mode);
2449}
2450
2451void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2452 const llvm::SmallVectorImpl<clang::QualType> &proto,
2453 bool objectIsConst, long *poffset,
2454 EFunctionMatchMode mode/*=kConversionMatch*/)
2455{
2456 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2457 if (poffset) {
2458 *poffset = 0L;
2459 }
2460 ResetArg();
2461 if (!info->IsValid()) {
2462 ::Error("TClingCallFunc::SetFuncProto", "Class info is invalid!");
2463 return;
2464 }
2465 *fMethod = info->GetMethod(method, proto, objectIsConst, poffset, mode);
2466 if (!fMethod->IsValid()) {
2467 //::Error("TClingCallFunc::SetFuncProto", "Could not find method %s(%s)",
2468 // method, proto);
2469 return;
2470 }
2471}
2472
l unsigned short
long
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
long Long_t
Definition RtypesCore.h:54
static void EvaluateExpr(cling::Interpreter &interp, const Expr *E, cling::Value &V)
static unsigned long long gWrapperSerial
static map< const Decl *, void * > gCtorWrapperStore
static const string kIndentString(" ")
static void indent(ostringstream &buf, int indent_level)
static map< const Decl *, void * > gDtorWrapperStore
static map< const Decl *, void * > gWrapperStore
void(* tcling_callfunc_ctor_Wrapper_t)(void **, void *, unsigned long)
void(* tcling_callfunc_Wrapper_t)(void *, int, void **, void *)
void(* tcling_callfunc_dtor_Wrapper_t)(void *, unsigned long, int)
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:187
#define N
char name[80]
Definition TGX11.cxx:110
R__EXTERN TVirtualMutex * gInterpreterMutex
#define R__LOCKGUARD_CLING(mutex)
R__EXTERN TInterpreter * gCling
Int_t gDebug
Definition TROOT.cxx:590
typedef void((*Func_t)())
const char * proto
Definition civetweb.c:16604
void * ExecDefaultConstructor(const TClingClassInfo *info, ROOT::TMetaUtils::EIOCtorCategory kind, const std::string &type_name, void *address=nullptr, unsigned long nary=0UL)
void ExecWithReturn(void *address, void *ret=nullptr)
long ExecInt(void *address)
std::unique_ptr< TClingMethodInfo > fMethod
Current method, we own.
ExecWithRetFunc_t InitRetAndExec(const clang::FunctionDecl *FD, cling::Value &ret)
void collect_type_info(clang::QualType &QT, std::ostringstream &typedefbuf, std::ostringstream &callbuf, std::string &type_name, EReferenceType &refType, bool &isPointer, int indent_level, bool forArgument)
void SetArgs(const char *args)
size_t fMinRequiredArguments
Number of required arguments.
T ExecT(void *address)
size_t CalculateMinRequiredArguments()
double ExecDouble(void *address)
void SetFunc(const TClingClassInfo *info, const char *method, const char *arglist, long *poffset)
tcling_callfunc_Wrapper_t make_wrapper()
ExecWithRetFunc_t InitRetAndExecNoCtor(clang::QualType QT, cling::Value &ret)
bool IsValid() const
tcling_callfunc_dtor_Wrapper_t make_dtor_wrapper(const TClingClassInfo *info)
std::function< void(void *address, cling::Value &ret)> ExecWithRetFunc_t
void ExecDestructor(const TClingClassInfo *info, void *address=nullptr, unsigned long nary=0UL, bool withFree=true)
void execWithLL(void *address, cling::Value *val)
const clang::DeclContext * GetDeclContext() const
void SetFuncProto(const TClingClassInfo *info, const char *method, const char *proto, long *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
void * compile_wrapper(const std::string &wrapper_name, const std::string &wrapper, bool withAccessControl=true)
TInterpreter::CallFuncIFacePtr_t IFacePtr()
void exec(void *address, void *ret)
void exec_with_valref_return(void *address, cling::Value *ret)
void make_narg_ctor(const unsigned N, std::ostringstream &typedefbuf, std::ostringstream &callbuf, const std::string &class_name, int indent_level)
const clang::FunctionDecl * GetDecl()
void execWithULL(void *address, cling::Value *val)
void EvaluateArgList(const std::string &ArgList)
const clang::Decl * GetFunctionOrShadowDecl() const
void ExecWithArgsAndReturn(void *address, const void *args[]=0, int nargs=0, void *ret=0)
void SetArgArray(long *argArr, int narg)
void Exec(void *address, TInterpreterValue *interpVal=0)
TClingMethodInfo * FactoryMethod() const
ExecWithRetFunc_t InitRetAndExecIntegral(clang::QualType QT, cling::Value &ret)
int get_wrapper_code(std::string &wrapper_name, std::string &wrapper)
size_t GetMinRequiredArguments()
tcling_callfunc_ctor_Wrapper_t make_ctor_wrapper(const TClingClassInfo *, ROOT::TMetaUtils::EIOCtorCategory, const std::string &)
const ROOT::TMetaUtils::TNormalizedCtxt & fNormCtxt
ROOT normalized context for that interpreter.
tcling_callfunc_Wrapper_t fWrapper
Pointer to compiled wrapper, we do not own.
long long ExecInt64(void *address)
cling::Interpreter * fInterp
Cling interpreter, we do not own.
void make_narg_call(const std::string &return_type, const unsigned N, std::ostringstream &typedefbuf, std::ostringstream &callbuf, const std::string &class_name, int indent_level)
void SetArg(long arg)
const clang::FunctionDecl * fDecl
Decl for the method.
void make_narg_call_with_return(const unsigned N, const std::string &class_name, std::ostringstream &buf, int indent_level)
llvm::SmallVector< cling::Value, 8 > fArgVals
Stored function arguments, we own.
void make_narg_ctor_with_return(const unsigned N, const std::string &class_name, std::ostringstream &buf, int indent_level)
ExecWithRetFunc_t InitRetAndExecBuiltin(clang::QualType QT, const clang::BuiltinType *BT, cling::Value &ret)
Emulation of the CINT ClassInfo class.
TClingMethodInfo GetMethodWithArgs(const char *fname, const char *arglist, long *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch, EInheritanceMode imode=kWithInheritance) const
TClingMethodInfo GetMethod(const char *fname) const
virtual bool IsValid() const
virtual const clang::Decl * GetDecl() const
Emulation of the CINT MethodInfo class.
This class defines an interface to the cling C++ interpreter.
Definition TCling.h:102
virtual const void * GetValAddr() const =0
#define F(x, y, z)
#define I(x, y, z)
void GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
Return the type name normalized for ROOT, keeping only the ROOT opaque typedef (Double32_t,...
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
EFunctionMatchMode
auto * l
Definition textangle.C:4