Logo ROOT  
Reference Guide
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 //
152 case BuiltinType::Char_U: // char on targets where it is unsigned
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:
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
193 case BuiltinType::Int:
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
207 return (returnType) val.getFloat();
208 break;
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)(Longptr_t) 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 && MPT->isMemberDataPointer()) {
237 return (returnType)(ptrdiff_t)val.getPtr();
238 }
239 return (returnType)(Longptr_t) 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 // ((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 make_narg_call(type_name, N, typedefbuf, callbuf, class_name, indent_level);
1089 callbuf << ";\n";
1090 for (int i = 0; i < indent_level; ++i) {
1091 callbuf << kIndentString;
1092 }
1093 callbuf << "return;\n";
1094 buf << typedefbuf.str() << callbuf.str();
1095 }
1096 --indent_level;
1097 for (int i = 0; i < indent_level; ++i) {
1098 buf << kIndentString;
1099 }
1100 buf << "}\n";
1101 }
1102}
1103
1105{
1107
1108 const Decl *D = GetFunctionOrShadowDecl();
1109 string wrapper_name;
1110 string wrapper;
1111
1112 if (get_wrapper_code(wrapper_name, wrapper) == 0) return 0;
1113
1114 //fprintf(stderr, "%s\n", wrapper.c_str());
1115 //
1116 // Compile the wrapper code.
1117 //
1118 void *F = compile_wrapper(wrapper_name, wrapper);
1119 if (F) {
1120 gWrapperStore.insert(make_pair(D, F));
1121 } else {
1122 ::Error("TClingCallFunc::make_wrapper",
1123 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1124 wrapper.c_str());
1125 }
1127}
1128
1130 ROOT::TMetaUtils::EIOCtorCategory kind, const std::string &type_name)
1131{
1132 // Make a code string that follows this pattern:
1133 //
1134 // void
1135 // unique_wrapper_ddd(void** ret, void* arena, unsigned long nary)
1136 // {
1137 // if (!arena) {
1138 // if (!nary) {
1139 // *ret = new ClassName;
1140 // }
1141 // else {
1142 // *ret = new ClassName[nary];
1143 // }
1144 // }
1145 // else {
1146 // if (!nary) {
1147 // *ret = new (arena) ClassName;
1148 // }
1149 // else {
1150 // *ret = new (arena) ClassName[nary];
1151 // }
1152 // }
1153 // }
1154 //
1155 // When I/O constructor used:
1156 //
1157 // void
1158 // unique_wrapper_ddd(void** ret, void* arena, unsigned long nary)
1159 // {
1160 // if (!arena) {
1161 // if (!nary) {
1162 // *ret = new ClassName((TRootIOCtor*)nullptr);
1163 // }
1164 // else {
1165 // char *buf = malloc(nary * sizeof(ClassName));
1166 // for (int k=0;k<nary;++k)
1167 // new (buf + k * sizeof(ClassName)) ClassName((TRootIOCtor*)nullptr);
1168 // *ret = buf;
1169 // }
1170 // }
1171 // else {
1172 // if (!nary) {
1173 // *ret = new (arena) ClassName((TRootIOCtor*)nullptr);
1174 // }
1175 // else {
1176 // for (int k=0;k<nary;++k)
1177 // new ((char *) arena + k * sizeof(ClassName)) ClassName((TRootIOCtor*)nullptr);
1178 // *ret = arena;
1179 // }
1180 // }
1181 // }
1182 //
1183 //
1184 // Note:
1185 //
1186 // If the class is of POD type, the form:
1187 //
1188 // new ClassName;
1189 //
1190 // does not initialize the object at all, and the form:
1191 //
1192 // new ClassName();
1193 //
1194 // default-initializes the object.
1195 //
1196 // We are using the form without parentheses because that is what
1197 // CINT did.
1198 //
1199 //--
1200 ASTContext &Context = info->GetDecl()->getASTContext();
1201 PrintingPolicy Policy(Context.getPrintingPolicy());
1202 Policy.SuppressTagKeyword = true;
1203 Policy.SuppressUnwrittenScope = true;
1204 //
1205 // Get the class or namespace name.
1206 //
1207 string class_name;
1208 if (const TypeDecl *TD = dyn_cast<TypeDecl>(info->GetDecl())) {
1209 // This is a class, struct, or union member.
1210 QualType QT(TD->getTypeForDecl(), 0);
1212 } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(info->GetDecl())) {
1213 // This is a namespace member.
1214 raw_string_ostream stream(class_name);
1215 ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
1216 stream.flush();
1217 }
1218
1219
1220 //
1221 // Make the wrapper name.
1222 //
1223 string wrapper_name;
1224 {
1225 ostringstream buf;
1226 buf << "__ctor";
1227 //const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
1228 //string mn;
1229 //fInterp->maybeMangleDeclName(ND, mn);
1230 //buf << '_dtor_' << mn;
1231 buf << '_' << gWrapperSerial++;
1232 wrapper_name = buf.str();
1233 }
1234
1235 string constr_arg;
1237 constr_arg = string("((") + type_name + "*)nullptr)";
1239 constr_arg = string("(*((") + type_name + "*)arena))";
1240
1241 //
1242 // Write the wrapper code.
1243 //
1244 int indent_level = 0;
1245 ostringstream buf;
1246 buf << "__attribute__((used)) ";
1247 buf << "extern \"C\" void ";
1248 buf << wrapper_name;
1249 buf << "(void** ret, void* arena, unsigned long nary)\n";
1250 buf << "{\n";
1251
1252 // if (!arena) {
1253 // if (!nary) {
1254 // *ret = new ClassName;
1255 // }
1256 // else {
1257 // *ret = new ClassName[nary];
1258 // }
1259 // }
1260 indent(buf, ++indent_level);
1261 buf << "if (!arena) {\n";
1262 indent(buf, ++indent_level);
1263 buf << "if (!nary) {\n";
1264 indent(buf, ++indent_level);
1265 buf << "*ret = new " << class_name << constr_arg << ";\n";
1266 indent(buf, --indent_level);
1267 buf << "}\n";
1268 indent(buf, indent_level);
1269 buf << "else {\n";
1270 indent(buf, ++indent_level);
1271 if (constr_arg.empty()) {
1272 buf << "*ret = new " << class_name << "[nary];\n";
1273 } else {
1274 buf << "char *buf = (char *) malloc(nary * sizeof(" << class_name << "));\n";
1275 indent(buf, indent_level);
1276 buf << "for (int k=0;k<nary;++k)\n";
1277 indent(buf, ++indent_level);
1278 buf << "new (buf + k * sizeof(" << class_name << ")) " << class_name << constr_arg << ";\n";
1279 indent(buf, --indent_level);
1280 buf << "*ret = buf;\n";
1281 }
1282 indent(buf, --indent_level);
1283 buf << "}\n";
1284 indent(buf, --indent_level);
1285 buf << "}\n";
1286 // else {
1287 // if (!nary) {
1288 // *ret = new (arena) ClassName;
1289 // }
1290 // else {
1291 // *ret = new (arena) ClassName[nary];
1292 // }
1293 // }
1294 indent(buf, indent_level);
1295 buf << "else {\n";
1296 indent(buf, ++indent_level);
1297 buf << "if (!nary) {\n";
1298 indent(buf, ++indent_level);
1299 buf << "*ret = new (arena) " << class_name << constr_arg << ";\n";
1300 indent(buf, --indent_level);
1301 buf << "}\n";
1302 indent(buf, indent_level);
1303 buf << "else {\n";
1304 indent(buf, ++indent_level);
1305 if (constr_arg.empty()) {
1306 buf << "*ret = new (arena) " << class_name << "[nary];\n";
1307 } else {
1308 buf << "for (int k=0;k<nary;++k)\n";
1309 indent(buf, ++indent_level);
1310 buf << "new ((char *) arena + k * sizeof(" << class_name << ")) " << class_name << constr_arg << ";\n";
1311 indent(buf, --indent_level);
1312 buf << "*ret = arena;\n";
1313 }
1314 indent(buf, --indent_level);
1315 buf << "}\n";
1316 indent(buf, --indent_level);
1317 buf << "}\n";
1318 // End wrapper.
1319 --indent_level;
1320 buf << "}\n";
1321 // Done.
1322 string wrapper(buf.str());
1323 //fprintf(stderr, "%s\n", wrapper.c_str());
1324 //
1325 // Compile the wrapper code.
1326 //
1327 void *F = compile_wrapper(wrapper_name, wrapper,
1328 /*withAccessControl=*/false);
1329 if (F) {
1330 gCtorWrapperStore.insert(make_pair(info->GetDecl(), F));
1331 } else {
1332 ::Error("TClingCallFunc::make_ctor_wrapper",
1333 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1334 wrapper.c_str());
1335 }
1337}
1338
1341{
1342 // Make a code string that follows this pattern:
1343 //
1344 // void
1345 // unique_wrapper_ddd(void* obj, unsigned long nary, int withFree)
1346 // {
1347 // if (withFree) {
1348 // if (!nary) {
1349 // delete (ClassName*) obj;
1350 // }
1351 // else {
1352 // delete[] (ClassName*) obj;
1353 // }
1354 // }
1355 // else {
1356 // typedef ClassName DtorName;
1357 // if (!nary) {
1358 // ((ClassName*)obj)->~DtorName();
1359 // }
1360 // else {
1361 // for (unsigned long i = nary - 1; i > -1; --i) {
1362 // (((ClassName*)obj)+i)->~DtorName();
1363 // }
1364 // }
1365 // }
1366 // }
1367 //
1368 //--
1369 ASTContext &Context = info->GetDecl()->getASTContext();
1370 PrintingPolicy Policy(Context.getPrintingPolicy());
1371 Policy.SuppressTagKeyword = true;
1372 Policy.SuppressUnwrittenScope = true;
1373 //
1374 // Get the class or namespace name.
1375 //
1376 string class_name;
1377 if (const TypeDecl *TD = dyn_cast<TypeDecl>(info->GetDecl())) {
1378 // This is a class, struct, or union member.
1379 QualType QT(TD->getTypeForDecl(), 0);
1381 } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(info->GetDecl())) {
1382 // This is a namespace member.
1383 raw_string_ostream stream(class_name);
1384 ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
1385 stream.flush();
1386 }
1387 //
1388 // Make the wrapper name.
1389 //
1390 string wrapper_name;
1391 {
1392 ostringstream buf;
1393 buf << "__dtor";
1394 //const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
1395 //string mn;
1396 //fInterp->maybeMangleDeclName(ND, mn);
1397 //buf << '_dtor_' << mn;
1398 buf << '_' << gWrapperSerial++;
1399 wrapper_name = buf.str();
1400 }
1401 //
1402 // Write the wrapper code.
1403 //
1404 int indent_level = 0;
1405 ostringstream buf;
1406 buf << "__attribute__((used)) ";
1407 buf << "extern \"C\" void ";
1408 buf << wrapper_name;
1409 buf << "(void* obj, unsigned long nary, int withFree)\n";
1410 buf << "{\n";
1411 // if (withFree) {
1412 // if (!nary) {
1413 // delete (ClassName*) obj;
1414 // }
1415 // else {
1416 // delete[] (ClassName*) obj;
1417 // }
1418 // }
1419 ++indent_level;
1420 indent(buf, indent_level);
1421 buf << "if (withFree) {\n";
1422 ++indent_level;
1423 indent(buf, indent_level);
1424 buf << "if (!nary) {\n";
1425 ++indent_level;
1426 indent(buf, indent_level);
1427 buf << "delete (" << class_name << "*) obj;\n";
1428 --indent_level;
1429 indent(buf, indent_level);
1430 buf << "}\n";
1431 indent(buf, indent_level);
1432 buf << "else {\n";
1433 ++indent_level;
1434 indent(buf, indent_level);
1435 buf << "delete[] (" << class_name << "*) obj;\n";
1436 --indent_level;
1437 indent(buf, indent_level);
1438 buf << "}\n";
1439 --indent_level;
1440 indent(buf, indent_level);
1441 buf << "}\n";
1442 // else {
1443 // typedef ClassName Nm;
1444 // if (!nary) {
1445 // ((Nm*)obj)->~Nm();
1446 // }
1447 // else {
1448 // for (unsigned long i = nary - 1; i > -1; --i) {
1449 // (((Nm*)obj)+i)->~Nm();
1450 // }
1451 // }
1452 // }
1453 indent(buf, indent_level);
1454 buf << "else {\n";
1455 ++indent_level;
1456 indent(buf, indent_level);
1457 buf << "typedef " << class_name << " Nm;\n";
1458 buf << "if (!nary) {\n";
1459 ++indent_level;
1460 indent(buf, indent_level);
1461 buf << "((Nm*)obj)->~Nm();\n";
1462 --indent_level;
1463 indent(buf, indent_level);
1464 buf << "}\n";
1465 indent(buf, indent_level);
1466 buf << "else {\n";
1467 ++indent_level;
1468 indent(buf, indent_level);
1469 buf << "do {\n";
1470 ++indent_level;
1471 indent(buf, indent_level);
1472 buf << "(((Nm*)obj)+(--nary))->~Nm();\n";
1473 --indent_level;
1474 indent(buf, indent_level);
1475 buf << "} while (nary);\n";
1476 --indent_level;
1477 indent(buf, indent_level);
1478 buf << "}\n";
1479 --indent_level;
1480 indent(buf, indent_level);
1481 buf << "}\n";
1482 // End wrapper.
1483 --indent_level;
1484 buf << "}\n";
1485 // Done.
1486 string wrapper(buf.str());
1487 //fprintf(stderr, "%s\n", wrapper.c_str());
1488 //
1489 // Compile the wrapper code.
1490 //
1491 void *F = compile_wrapper(wrapper_name, wrapper,
1492 /*withAccessControl=*/false);
1493 if (F) {
1494 gDtorWrapperStore.insert(make_pair(info->GetDecl(), F));
1495 } else {
1496 ::Error("TClingCallFunc::make_dtor_wrapper",
1497 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1498 wrapper.c_str());
1499 }
1500
1502}
1503
1505public:
1506 union {
1507 long double ldbl;
1508 double dbl;
1509 float flt;
1510 //__uint128_t ui128;
1511 //__int128_t i128;
1512 unsigned long long ull;
1513 long long ll;
1514 unsigned long ul;
1515 long l;
1516 unsigned int ui;
1517 int i;
1518 unsigned short us;
1519 short s;
1520 //char32_t c32;
1521 //char16_t c16;
1522 //unsigned wchar_t uwc; - non-standard
1523 wchar_t wc;
1524 unsigned char uc;
1525 signed char sc;
1526 char c;
1527 bool b;
1528 void *vp;
1529 } u;
1530};
1531
1532void TClingCallFunc::exec(void *address, void *ret)
1533{
1534 SmallVector<ValHolder, 8> vh_ary;
1535 SmallVector<void *, 8> vp_ary;
1536
1537 unsigned num_args = fArgVals.size();
1538 {
1540
1541 const FunctionDecl *FD = GetDecl();
1542
1543 //
1544 // Convert the arguments from cling::Value to their
1545 // actual type and store them in a holder for passing to the
1546 // wrapper function by pointer to value.
1547 //
1548 unsigned num_params = FD->getNumParams();
1549
1550 if (num_args < GetMinRequiredArguments()) {
1551 ::Error("TClingCallFunc::exec",
1552 "Not enough arguments provided for %s (%d instead of the minimum %d)",
1553 fMethod->Name(),
1554 num_args, (int)GetMinRequiredArguments());
1555 return;
1556 }
1557 if (address == 0 && dyn_cast<CXXMethodDecl>(FD)
1558 && !(dyn_cast<CXXMethodDecl>(FD))->isStatic()
1559 && !dyn_cast<CXXConstructorDecl>(FD)) {
1560 ::Error("TClingCallFunc::exec",
1561 "The method %s is called without an object.",
1562 fMethod->Name());
1563 return;
1564 }
1565 vh_ary.reserve(num_args);
1566 vp_ary.reserve(num_args);
1567 for (unsigned i = 0U; i < num_args; ++i) {
1568 QualType Ty;
1569 if (i < num_params) {
1570 const ParmVarDecl *PVD = FD->getParamDecl(i);
1571 Ty = PVD->getType();
1572 } else {
1573 Ty = fArgVals[i].getType();
1574 }
1575 QualType QT = Ty.getCanonicalType();
1576 if (const BuiltinType *BT =
1577 dyn_cast<BuiltinType>(&*QT)) {
1578 //
1579 // WARNING!!!
1580 //
1581 // This switch is organized in order-of-declaration
1582 // so that the produced assembly code is optimal.
1583 // Do not reorder!
1584 //
1585 switch (BT->getKind()) {
1586 //
1587 // Builtin Types
1588 //
1589 case BuiltinType::Void: {
1590 // void
1591 ::Error("TClingCallFunc::exec(void*)",
1592 "Invalid type 'Void'!");
1593 return;
1594 }
1595 break;
1596 //
1597 // Unsigned Types
1598 //
1599 case BuiltinType::Bool: {
1600 // bool
1601 ValHolder vh;
1602 vh.u.b = (bool) sv_to_ulong_long(fArgVals[i]);
1603 vh_ary.push_back(vh);
1604 vp_ary.push_back(&vh_ary.back());
1605 }
1606 break;
1607 case BuiltinType::Char_U: {
1608 // char on targets where it is unsigned
1609 ValHolder vh;
1610 vh.u.c = (char) sv_to_ulong_long(fArgVals[i]);
1611 vh_ary.push_back(vh);
1612 vp_ary.push_back(&vh_ary.back());
1613 }
1614 break;
1615 case BuiltinType::UChar: {
1616 // unsigned char
1617 ValHolder vh;
1618 vh.u.uc = (unsigned char) sv_to_ulong_long(fArgVals[i]);
1619 vh_ary.push_back(vh);
1620 vp_ary.push_back(&vh_ary.back());
1621 }
1622 break;
1623 case BuiltinType::WChar_U: {
1624 // wchar_t on targets where it is unsigned.
1625 // The standard doesn't allow to specify signednedd of wchar_t
1626 // thus this maps simply to wchar_t.
1627 ValHolder vh;
1628 vh.u.wc = (wchar_t) sv_to_ulong_long(fArgVals[i]);
1629 vh_ary.push_back(vh);
1630 vp_ary.push_back(&vh_ary.back());
1631 }
1632 break;
1633 case BuiltinType::Char16: {
1634 // char16_t
1635 //ValHolder vh;
1636 //vh.u.c16 = (char16_t) sv_to_ulong_long(fArgVals[i]);
1637 //vh_ary.push_back(vh);
1638 //vp_ary.push_back(&vh_ary.back());
1639 }
1640 break;
1641 case BuiltinType::Char32: {
1642 // char32_t
1643 //ValHolder vh;
1644 //vh.u.c32 = (char32_t) sv_to_ulong_long(fArgVals[i]);
1645 //vh_ary.push_back(vh);
1646 //vp_ary.push_back(&vh_ary.back());
1647 }
1648 break;
1649 case BuiltinType::UShort: {
1650 // unsigned short
1651 ValHolder vh;
1652 vh.u.us = (unsigned short) sv_to_ulong_long(fArgVals[i]);
1653 vh_ary.push_back(vh);
1654 vp_ary.push_back(&vh_ary.back());
1655 }
1656 break;
1657 case BuiltinType::UInt: {
1658 // unsigned int
1659 ValHolder vh;
1660 vh.u.ui = (unsigned int) sv_to_ulong_long(fArgVals[i]);
1661 vh_ary.push_back(vh);
1662 vp_ary.push_back(&vh_ary.back());
1663 }
1664 break;
1665 case BuiltinType::ULong: {
1666 // unsigned long
1667 ValHolder vh;
1668 vh.u.ul = (unsigned long) sv_to_ulong_long(fArgVals[i]);
1669 vh_ary.push_back(vh);
1670 vp_ary.push_back(&vh_ary.back());
1671 }
1672 break;
1673 case BuiltinType::ULongLong: {
1674 // unsigned long long
1675 ValHolder vh;
1676 vh.u.ull = (unsigned long long) sv_to_ulong_long(fArgVals[i]);
1677 vh_ary.push_back(vh);
1678 vp_ary.push_back(&vh_ary.back());
1679 }
1680 break;
1681 case BuiltinType::UInt128: {
1682 // __uint128_t
1683 }
1684 break;
1685 //
1686 // Signed Types
1687 //
1688 //
1689 // Signed Types
1690 //
1691 case BuiltinType::Char_S: {
1692 // char on targets where it is signed
1693 ValHolder vh;
1694 vh.u.c = (char) sv_to_long_long(fArgVals[i]);
1695 vh_ary.push_back(vh);
1696 vp_ary.push_back(&vh_ary.back());
1697 }
1698 break;
1699 case BuiltinType::SChar: {
1700 // signed char
1701 ValHolder vh;
1702 vh.u.sc = (signed char) sv_to_long_long(fArgVals[i]);
1703 vh_ary.push_back(vh);
1704 vp_ary.push_back(&vh_ary.back());
1705 }
1706 break;
1707 case BuiltinType::WChar_S: {
1708 // wchar_t on targets where it is signed.
1709 // The standard doesn't allow to specify signednedd of wchar_t
1710 // thus this maps simply to wchar_t.
1711 ValHolder vh;
1712 vh.u.wc = (wchar_t) sv_to_long_long(fArgVals[i]);
1713 vh_ary.push_back(vh);
1714 vp_ary.push_back(&vh_ary.back());
1715 }
1716 break;
1717 case BuiltinType::Short: {
1718 // short
1719 ValHolder vh;
1720 vh.u.s = (short) sv_to_long_long(fArgVals[i]);
1721 vh_ary.push_back(vh);
1722 vp_ary.push_back(&vh_ary.back());
1723 }
1724 break;
1725 case BuiltinType::Int: {
1726 // int
1727 ValHolder vh;
1728 vh.u.i = (int) sv_to_long_long(fArgVals[i]);
1729 vh_ary.push_back(vh);
1730 vp_ary.push_back(&vh_ary.back());
1731 }
1732 break;
1733 case BuiltinType::Long: {
1734 // long
1735 ValHolder vh;
1736 vh.u.l = (long) sv_to_long_long(fArgVals[i]);
1737 vh_ary.push_back(vh);
1738 vp_ary.push_back(&vh_ary.back());
1739 }
1740 break;
1741 case BuiltinType::LongLong: {
1742 // long long
1743 ValHolder vh;
1744 vh.u.ll = (long long) sv_to_long_long(fArgVals[i]);
1745 vh_ary.push_back(vh);
1746 vp_ary.push_back(&vh_ary.back());
1747 }
1748 break;
1749 case BuiltinType::Int128: {
1750 // __int128_t
1751 ::Error("TClingCallFunc::exec(void*)",
1752 "Invalid type 'Int128'!");
1753 return;
1754 }
1755 break;
1756 case BuiltinType::Half: {
1757 // half in OpenCL, __fp16 in ARM NEON
1758 ::Error("TClingCallFunc::exec(void*)",
1759 "Invalid type 'Half'!");
1760 return;
1761 }
1762 break;
1763 case BuiltinType::Float: {
1764 // float
1765 ValHolder vh;
1766 vh.u.flt = sv_to<float>(fArgVals[i]);
1767 vh_ary.push_back(vh);
1768 vp_ary.push_back(&vh_ary.back());
1769 }
1770 break;
1771 case BuiltinType::Double: {
1772 // double
1773 ValHolder vh;
1774 vh.u.dbl = sv_to<double>(fArgVals[i]);
1775 vh_ary.push_back(vh);
1776 vp_ary.push_back(&vh_ary.back());
1777 }
1778 break;
1779 case BuiltinType::LongDouble: {
1780 // long double
1781 ValHolder vh;
1782 vh.u.ldbl = sv_to<long double>(fArgVals[i]);
1783 vh_ary.push_back(vh);
1784 vp_ary.push_back(&vh_ary.back());
1785 }
1786 break;
1787 //
1788 // Language-Specific Types
1789 //
1790 case BuiltinType::NullPtr: {
1791 // C++11 nullptr
1792 ValHolder vh;
1793 vh.u.vp = fArgVals[i].getPtr();
1794 vh_ary.push_back(vh);
1795 vp_ary.push_back(&vh_ary.back());
1796 }
1797 break;
1798 default: {
1799 // There should be no others. This is here in case
1800 // this changes in the future.
1801 ::Error("TClingCallFunc::exec(void*)",
1802 "Unhandled builtin type!");
1803 QT->dump();
1804 return;
1805 }
1806 break;
1807 }
1808 } else if (QT->isReferenceType()) {
1809 // the argument is already a pointer value (point to the same thing
1810 // as the reference.
1811 vp_ary.push_back((void *) sv_to_ulong_long(fArgVals[i]));
1812 } else if (QT->isPointerType() || QT->isArrayType()) {
1813 ValHolder vh;
1814 vh.u.vp = (void *) sv_to_ulong_long(fArgVals[i]);
1815 vh_ary.push_back(vh);
1816 vp_ary.push_back(&vh_ary.back());
1817 } else if (QT->isRecordType()) {
1818 // the argument is already a pointer value (pointing to object passed
1819 // by value).
1820 vp_ary.push_back((void *) sv_to_ulong_long(fArgVals[i]));
1821 } else if (const EnumType *ET =
1822 dyn_cast<EnumType>(&*QT)) {
1823 // Note: We may need to worry about the underlying type
1824 // of the enum here.
1825 (void) ET;
1826 ValHolder vh;
1827 vh.u.i = (int) sv_to_long_long(fArgVals[i]);
1828 vh_ary.push_back(vh);
1829 vp_ary.push_back(&vh_ary.back());
1830 } else if (QT->isMemberPointerType()) {
1831 ValHolder vh;
1832 vh.u.vp = (void *) sv_to_ulong_long(fArgVals[i]);
1833 vh_ary.push_back(vh);
1834 vp_ary.push_back(&vh_ary.back());
1835 } else {
1836 ::Error("TClingCallFunc::exec(void*)",
1837 "Invalid type (unrecognized)!");
1838 QT->dump();
1839 return;
1840 }
1841 }
1842 } // End of scope holding the lock
1843 (*fWrapper)(address, (int)num_args, (void **)vp_ary.data(), ret);
1844}
1845
1846template <typename T>
1848{
1849 T ret; // leave uninit for valgrind's sake!
1850 exec(address, &ret);
1851 val->getLL() = ret;
1852}
1853
1854template <typename T>
1856{
1857 T ret; // leave uninit for valgrind's sake!
1858 exec(address, &ret);
1859 val->getULL() = ret;
1860}
1861
1862// Handle integral types.
1863template <class T>
1865{
1866 ret = cling::Value::Create<T>(QT.getAsOpaquePtr(), *fInterp);
1867 static_assert(std::is_integral<T>::value, "Must be called with integral T");
1868 if (std::is_signed<T>::value)
1869 return [this](void* address, cling::Value& ret) { execWithLL<T>(address, &ret); };
1870 else
1871 return [this](void* address, cling::Value& ret) { execWithULL<T>(address, &ret); };
1872}
1873
1874// Handle builtin types.
1876TClingCallFunc::InitRetAndExecBuiltin(QualType QT, const clang::BuiltinType *BT, cling::Value &ret) {
1877 switch (BT->getKind()) {
1878 case BuiltinType::Void: {
1879 ret = cling::Value::Create<void>(QT.getAsOpaquePtr(), *fInterp);
1880 return [this](void* address, cling::Value& ret) { exec(address, 0); };
1881 break;
1882 }
1883
1884 //
1885 // Unsigned Types
1886 //
1887 case BuiltinType::Bool:
1888 return InitRetAndExecIntegral<bool>(QT, ret);
1889 break;
1890 case BuiltinType::Char_U: // char on targets where it is unsigned
1891 case BuiltinType::UChar:
1892 return InitRetAndExecIntegral<char>(QT, ret);
1893 break;
1894 case BuiltinType::WChar_U:
1895 return InitRetAndExecIntegral<wchar_t>(QT, ret);
1896 break;
1897 case BuiltinType::Char16:
1898 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1899 "Invalid type 'char16_t'!");
1900 return {};
1901 break;
1902 case BuiltinType::Char32:
1903 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1904 "Invalid type 'char32_t'!");
1905 return {};
1906 break;
1908 return InitRetAndExecIntegral<unsigned short>(QT, ret);
1909 break;
1910 case BuiltinType::UInt:
1911 return InitRetAndExecIntegral<unsigned int>(QT, ret);
1912 break;
1913 case BuiltinType::ULong:
1914 return InitRetAndExecIntegral<unsigned long>(QT, ret);
1915 break;
1916 case BuiltinType::ULongLong:
1917 return InitRetAndExecIntegral<unsigned long long>(QT, ret);
1918 break;
1919 case BuiltinType::UInt128: {
1920 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1921 "Invalid type '__uint128_t'!");
1922 return {};
1923 }
1924 break;
1925
1926 //
1927 // Signed Types
1928 //
1929 case BuiltinType::Char_S: // char on targets where it is signed
1930 case BuiltinType::SChar:
1931 return InitRetAndExecIntegral<signed char>(QT, ret);
1932 break;
1933 case BuiltinType::WChar_S:
1934 // wchar_t on targets where it is signed.
1935 // The standard doesn't allow to specify signednedd of wchar_t
1936 // thus this maps simply to wchar_t.
1937 return InitRetAndExecIntegral<wchar_t>(QT, ret);
1938 break;
1939 case BuiltinType::Short:
1940 return InitRetAndExecIntegral<short>(QT, ret);
1941 break;
1942 case BuiltinType::Int:
1943 return InitRetAndExecIntegral<int>(QT, ret);
1944 break;
1945 case BuiltinType::Long:
1946 return InitRetAndExecIntegral<long>(QT, ret);
1947 break;
1948 case BuiltinType::LongLong:
1949 return InitRetAndExecIntegral<long long>(QT, ret);
1950 break;
1951 case BuiltinType::Int128:
1952 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1953 "Invalid type '__int128_t'!");
1954 return {};
1955 break;
1956 case BuiltinType::Half:
1957 // half in OpenCL, __fp16 in ARM NEON
1958 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1959 "Invalid type 'Half'!");
1960 return {};
1961 break;
1962 case BuiltinType::Float: {
1963 ret = cling::Value::Create<float>(QT.getAsOpaquePtr(), *fInterp);
1964 return [this](void* address, cling::Value& ret) { exec(address, &ret.getFloat()); };
1965 break;
1966 }
1967 case BuiltinType::Double: {
1968 ret = cling::Value::Create<double>(QT.getAsOpaquePtr(), *fInterp);
1969 return [this](void* address, cling::Value& ret) { exec(address, &ret.getDouble()); };
1970 break;
1971 }
1972 case BuiltinType::LongDouble: {
1973 ret = cling::Value::Create<long double>(QT.getAsOpaquePtr(), *fInterp);
1974 return [this](void* address, cling::Value& ret) { exec(address, &ret.getLongDouble()); };
1975 break;
1976 }
1977 //
1978 // Language-Specific Types
1979 //
1980 case BuiltinType::NullPtr:
1981 // C++11 nullptr
1982 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1983 "Invalid type 'nullptr'!");
1984 return {};
1985 break;
1986 default:
1987 break;
1988 }
1989 return {};
1990}
1991
1992
1995 if (QT->isReferenceType()) {
1996 ret = cling::Value(QT, *fInterp);
1997 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
1998 } else if (QT->isMemberPointerType()) {
1999 const MemberPointerType *MPT = QT->getAs<MemberPointerType>();
2000 if (MPT && MPT->isMemberDataPointer()) {
2001 // A member data pointer is a actually a struct with one
2002 // member of ptrdiff_t, the offset from the base of the object
2003 // storage to the storage for the designated data member.
2004 // But that's not relevant: we use it as a non-builtin, allocated
2005 // type.
2006 ret = cling::Value(QT, *fInterp);
2007 return [this](void* address, cling::Value& ret) { exec(address, ret.getPtr()); };
2008 }
2009 // We are a function member pointer.
2010 ret = cling::Value(QT, *fInterp);
2011 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2012 } else if (QT->isPointerType() || QT->isArrayType()) {
2013 // Note: ArrayType is an illegal function return value type.
2014 ret = cling::Value::Create<void*>(QT.getAsOpaquePtr(), *fInterp);
2015 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2016 } else if (QT->isRecordType()) {
2017 ret = cling::Value(QT, *fInterp);
2018 return [this](void* address, cling::Value& ret) { exec(address, ret.getPtr()); };
2019 } else if (const EnumType *ET = dyn_cast<EnumType>(&*QT)) {
2020 // Note: We may need to worry about the underlying type
2021 // of the enum here.
2022 (void) ET;
2023 ret = cling::Value(QT, *fInterp);
2024 return [this](void* address, cling::Value& ret) { execWithLL<int>(address, &ret); };
2025 } else if (const BuiltinType *BT = dyn_cast<BuiltinType>(&*QT)) {
2026 return InitRetAndExecBuiltin(QT, BT, ret);
2027 }
2028 ::Error("TClingCallFunc::exec_with_valref_return",
2029 "Unrecognized return type!");
2030 QT->dump();
2031 return {};
2032}
2033
2035TClingCallFunc::InitRetAndExec(const clang::FunctionDecl *FD, cling::Value &ret) {
2036 if (llvm::isa<CXXConstructorDecl>(FD)) {
2037 ASTContext &Context = FD->getASTContext();
2038 const TypeDecl *TD = dyn_cast<TypeDecl>(GetDeclContext());
2039 QualType ClassTy(TD->getTypeForDecl(), 0);
2040 QualType QT = Context.getLValueReferenceType(ClassTy);
2041 ret = cling::Value(QT, *fInterp);
2042 // Store the new()'ed address in getPtr()
2043 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2044 } else {
2045 QualType QT = FD->getReturnType().getCanonicalType();
2046 return InitRetAndExecNoCtor(QT, ret);
2047 }
2048}
2049
2051{
2052 if (!ret) {
2053 exec(address, 0);
2054 return;
2055 }
2056 std::function<void(void*, cling::Value&)> execFunc;
2057
2058 /* Release lock during user function execution*/
2059 {
2061 execFunc = InitRetAndExec(GetDecl(), *ret);
2062 }
2063
2064 if (execFunc)
2065 execFunc(address, *ret);
2066 return;
2067}
2068
2069void TClingCallFunc::EvaluateArgList(const string &ArgList)
2070{
2072
2073 SmallVector<Expr *, 4> exprs;
2074 fInterp->getLookupHelper().findArgList(ArgList, exprs,
2075 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
2076 : cling::LookupHelper::NoDiagnostics);
2077 for (SmallVectorImpl<Expr *>::const_iterator I = exprs.begin(),
2078 E = exprs.end(); I != E; ++I) {
2079 cling::Value val;
2080 EvaluateExpr(*fInterp, *I, val);
2081 if (!val.isValid()) {
2082 // Bad expression, all done.
2083 ::Error("TClingCallFunc::EvaluateArgList",
2084 "Bad expression in parameter %d of '%s'!",
2085 (int)(I - exprs.begin()),
2086 ArgList.c_str());
2087 return;
2088 }
2089 fArgVals.push_back(val);
2090 }
2091}
2092
2093void TClingCallFunc::Exec(void *address, TInterpreterValue *interpVal/*=0*/)
2094{
2095 IFacePtr();
2096 if (!fWrapper) {
2097 ::Error("TClingCallFunc::Exec(address, interpVal)",
2098 "Called with no wrapper, not implemented!");
2099 return;
2100 }
2101 if (!interpVal) {
2102 exec(address, 0);
2103 return;
2104 }
2105 cling::Value *val = reinterpret_cast<cling::Value *>(interpVal->GetValAddr());
2106 exec_with_valref_return(address, val);
2107}
2108
2109template <typename T>
2111{
2112 IFacePtr();
2113 if (!fWrapper) {
2114 ::Error("TClingCallFunc::ExecT",
2115 "Called with no wrapper, not implemented!");
2116 return 0;
2117 }
2118 cling::Value ret;
2119 exec_with_valref_return(address, &ret);
2120 if (!ret.isValid()) {
2121 // Sometimes we are called on a function returning void!
2122 return 0;
2123 }
2124
2126 ((TCling *)gCling)->RegisterTemporary(ret);
2127 return sv_to<T>(ret);
2128}
2129
2131{
2132 return ExecT<Longptr_t>(address);
2133}
2134
2135long long TClingCallFunc::ExecInt64(void *address)
2136{
2137 return ExecT<long long>(address);
2138}
2139
2140double TClingCallFunc::ExecDouble(void *address)
2141{
2142 return ExecT<double>(address);
2143}
2144
2145void TClingCallFunc::ExecWithArgsAndReturn(void *address, const void *args[] /*= 0*/,
2146 int nargs /*= 0*/, void *ret/*= 0*/)
2147{
2148 IFacePtr();
2149 if (!fWrapper) {
2150 ::Error("TClingCallFunc::ExecWithArgsAndReturn(address, args, ret)",
2151 "Called with no wrapper, not implemented!");
2152 return;
2153 }
2154 (*fWrapper)(address, nargs, const_cast<void **>(args), ret);
2155}
2156
2157void TClingCallFunc::ExecWithReturn(void *address, void *ret/*= 0*/)
2158{
2159 IFacePtr();
2160 if (!fWrapper) {
2161 ::Error("TClingCallFunc::ExecWithReturn(address, ret)",
2162 "Called with no wrapper, not implemented!");
2163 return;
2164 }
2165 exec(address, ret);
2166}
2167
2170 const std::string &type_name,
2171 void *address /*=0*/, unsigned long nary /*= 0UL*/)
2172{
2173 if (!info->IsValid()) {
2174 ::Error("TClingCallFunc::ExecDefaultConstructor", "Invalid class info!");
2175 return nullptr;
2176 }
2177 tcling_callfunc_ctor_Wrapper_t wrapper = nullptr;
2178 {
2180 auto D = info->GetDecl();
2181 //if (!info->HasDefaultConstructor()) {
2182 // // FIXME: We might have a ROOT ioctor, we might
2183 // // have to check for that here.
2184 // ::Error("TClingCallFunc::ExecDefaultConstructor",
2185 // "Class has no default constructor: %s",
2186 // info->Name());
2187 // return 0;
2188 //}
2189 auto I = gCtorWrapperStore.find(D);
2190 if (I != gCtorWrapperStore.end()) {
2191 wrapper = (tcling_callfunc_ctor_Wrapper_t) I->second;
2192 } else {
2193 wrapper = make_ctor_wrapper(info, kind, type_name);
2194 }
2195 }
2196 if (!wrapper) {
2197 ::Error("TClingCallFunc::ExecDefaultConstructor",
2198 "Called with no wrapper, not implemented!");
2199 return nullptr;
2200 }
2201 void *obj = 0;
2202 (*wrapper)(&obj, address, nary);
2203 return obj;
2204}
2205
2206void TClingCallFunc::ExecDestructor(const TClingClassInfo *info, void *address /*=0*/,
2207 unsigned long nary /*= 0UL*/, bool withFree /*= true*/)
2208{
2209 if (!info->IsValid()) {
2210 ::Error("TClingCallFunc::ExecDestructor", "Invalid class info!");
2211 return;
2212 }
2213
2215 {
2217 const Decl *D = info->GetDecl();
2218 map<const Decl *, void *>::iterator I = gDtorWrapperStore.find(D);
2219 if (I != gDtorWrapperStore.end()) {
2220 wrapper = (tcling_callfunc_dtor_Wrapper_t) I->second;
2221 } else {
2222 wrapper = make_dtor_wrapper(info);
2223 }
2224 }
2225 if (!wrapper) {
2226 ::Error("TClingCallFunc::ExecDestructor",
2227 "Called with no wrapper, not implemented!");
2228 return;
2229 }
2230 (*wrapper)(address, nary, withFree);
2231}
2232
2235{
2236 return new TClingMethodInfo(*fMethod);
2237}
2238
2240{
2241 fMethod.reset();
2242 fWrapper = 0;
2243 fDecl = nullptr;
2245 ResetArg();
2246}
2247
2249{
2250 Init();
2251 fMethod = std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(minfo));
2252}
2253
2254void TClingCallFunc::Init(std::unique_ptr<TClingMethodInfo> minfo)
2255{
2256 Init();
2257 fMethod = std::move(minfo);
2258}
2259
2261{
2262 if (!IsValid()) {
2263 return 0;
2264 }
2265 if (!fWrapper) {
2266 const Decl *decl = GetFunctionOrShadowDecl();
2267
2269 map<const Decl *, void *>::iterator I = gWrapperStore.find(decl);
2270 if (I != gWrapperStore.end()) {
2272 } else {
2274 }
2275 }
2276 return (void *)fWrapper;
2277}
2278
2280{
2281 if (!fMethod) {
2282 return false;
2283 }
2284 return fMethod->IsValid();
2285}
2286
2288{
2289 if (!IsValid()) {
2290 ::Error("TClingCallFunc::IFacePtr(kind)",
2291 "Attempt to get interface while invalid.");
2293 }
2294 if (!fWrapper) {
2295 const Decl *decl = GetFunctionOrShadowDecl();
2296
2298 map<const Decl *, void *>::iterator I = gWrapperStore.find(decl);
2299 if (I != gWrapperStore.end()) {
2301 } else {
2303 }
2304
2305 fReturnIsRecordType = GetDecl()->getReturnType().getCanonicalType()->isRecordType();
2306 }
2308}
2309
2310
2312{
2313 fArgVals.clear();
2314}
2315
2316void TClingCallFunc::SetArg(unsigned long param)
2317{
2318 const ASTContext &C = fInterp->getCI()->getASTContext();
2319 fArgVals.push_back(cling::Value(C.UnsignedLongTy, *fInterp));
2320 fArgVals.back().getLL() = param;
2321}
2322
2324{
2325 const ASTContext &C = fInterp->getCI()->getASTContext();
2326 fArgVals.push_back(cling::Value(C.LongTy, *fInterp));
2327 fArgVals.back().getLL() = param;
2328}
2329
2330void TClingCallFunc::SetArg(float param)
2331{
2332 const ASTContext &C = fInterp->getCI()->getASTContext();
2333 fArgVals.push_back(cling::Value(C.FloatTy, *fInterp));
2334 fArgVals.back().getFloat() = param;
2335}
2336
2337void TClingCallFunc::SetArg(double param)
2338{
2339 const ASTContext &C = fInterp->getCI()->getASTContext();
2340 fArgVals.push_back(cling::Value(C.DoubleTy, *fInterp));
2341 fArgVals.back().getDouble() = param;
2342}
2343
2344void TClingCallFunc::SetArg(long long param)
2345{
2346 const ASTContext &C = fInterp->getCI()->getASTContext();
2347 fArgVals.push_back(cling::Value(C.LongLongTy, *fInterp));
2348 fArgVals.back().getLL() = param;
2349}
2350
2351void TClingCallFunc::SetArg(unsigned long long param)
2352{
2353 const ASTContext &C = fInterp->getCI()->getASTContext();
2354 fArgVals.push_back(cling::Value(C.UnsignedLongLongTy, *fInterp));
2355 fArgVals.back().getULL() = param;
2356}
2357
2358void TClingCallFunc::SetArgArray(Longptr_t *paramArr, int nparam)
2359{
2360 ResetArg();
2361 for (int i = 0; i < nparam; ++i) {
2362 SetArg(paramArr[i]);
2363 }
2364}
2365
2366void TClingCallFunc::SetArgs(const char *params)
2367{
2368 ResetArg();
2369 EvaluateArgList(params);
2370}
2371
2372void TClingCallFunc::SetFunc(const TClingClassInfo *info, const char *method, const char *arglist,
2373 Longptr_t *poffset)
2374{
2375 SetFunc(info, method, arglist, false, poffset);
2376}
2377
2378void TClingCallFunc::SetFunc(const TClingClassInfo *info, const char *method, const char *arglist,
2379 bool objectIsConst, Longptr_t *poffset)
2380{
2381 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2382 if (poffset) {
2383 *poffset = 0L;
2384 }
2385 ResetArg();
2386 if (!info->IsValid()) {
2387 ::Error("TClingCallFunc::SetFunc", "Class info is invalid!");
2388 return;
2389 }
2390 if (!strcmp(arglist, ")")) {
2391 // CINT accepted a single right paren as meaning no arguments.
2392 arglist = "";
2393 }
2394 *fMethod = info->GetMethodWithArgs(method, arglist, objectIsConst, poffset);
2395 if (!fMethod->IsValid()) {
2396 //::Error("TClingCallFunc::SetFunc", "Could not find method %s(%s)", method,
2397 // arglist);
2398 return;
2399 }
2400 // FIXME: The arglist was already parsed by the lookup, we should
2401 // enhance the lookup to return the resulting expression
2402 // list so we do not need to parse it again here.
2403 EvaluateArgList(arglist);
2404}
2405
2407{
2408 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(*info)));
2409 ResetArg();
2410 if (!fMethod->IsValid()) {
2411 return;
2412 }
2413}
2414
2415void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2416 const char *proto, Longptr_t *poffset,
2417 EFunctionMatchMode mode/*=kConversionMatch*/)
2418{
2419 SetFuncProto(info, method, proto, false, poffset, mode);
2420}
2421
2422void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2423 const char *proto, bool objectIsConst, Longptr_t *poffset,
2424 EFunctionMatchMode mode/*=kConversionMatch*/)
2425{
2426 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2427 if (poffset) {
2428 *poffset = 0L;
2429 }
2430 ResetArg();
2431 if (!info->IsValid()) {
2432 ::Error("TClingCallFunc::SetFuncProto", "Class info is invalid!");
2433 return;
2434 }
2435 *fMethod = info->GetMethod(method, proto, objectIsConst, poffset, mode);
2436 if (!fMethod->IsValid()) {
2437 //::Error("TClingCallFunc::SetFuncProto", "Could not find method %s(%s)",
2438 // method, proto);
2439 return;
2440 }
2441}
2442
2443void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2444 const llvm::SmallVectorImpl<clang::QualType> &proto, Longptr_t *poffset,
2445 EFunctionMatchMode mode/*=kConversionMatch*/)
2446{
2447 SetFuncProto(info, method, proto, false, poffset, mode);
2448}
2449
2450void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2451 const llvm::SmallVectorImpl<clang::QualType> &proto,
2452 bool objectIsConst, Longptr_t *poffset,
2453 EFunctionMatchMode mode/*=kConversionMatch*/)
2454{
2455 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2456 if (poffset) {
2457 *poffset = 0L;
2458 }
2459 ResetArg();
2460 if (!info->IsValid()) {
2461 ::Error("TClingCallFunc::SetFuncProto", "Class info is invalid!");
2462 return;
2463 }
2464 *fMethod = info->GetMethod(method, proto, objectIsConst, poffset, mode);
2465 if (!fMethod->IsValid()) {
2466 //::Error("TClingCallFunc::SetFuncProto", "Could not find method %s(%s)",
2467 // method, proto);
2468 return;
2469 }
2470}
2471
l unsigned short
Definition: Converters.cxx:880
long
Definition: Converters.cxx:876
typedef void(GLAPIENTRYP _GLUfuncptr)(void)
long Longptr_t
Definition: RtypesCore.h:82
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
Definition: TInterpreter.h:44
#define R__LOCKGUARD_CLING(mutex)
Definition: TInterpreter.h:51
R__EXTERN TInterpreter * gCling
Definition: TInterpreter.h:563
Int_t gDebug
Definition: TROOT.cxx:592
const char * proto
Definition: civetweb.c:16604
Definition: Pattern.h:8
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)
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 SetArgArray(Longptr_t *argArr, int narg)
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)
Longptr_t ExecInt(void *address)
void execWithLL(void *address, cling::Value *val)
const clang::DeclContext * GetDeclContext() const
void * compile_wrapper(const std::string &wrapper_name, const std::string &wrapper, bool withAccessControl=true)
void SetFuncProto(const TClingClassInfo *info, const char *method, const char *proto, Longptr_t *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
TInterpreter::CallFuncIFacePtr_t IFacePtr()
void exec(void *address, void *ret)
bool fReturnIsRecordType
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)
void SetFunc(const TClingClassInfo *info, const char *method, const char *arglist, Longptr_t *poffset)
const clang::FunctionDecl * GetDecl()
void execWithULL(void *address, cling::Value *val)
void * InterfaceMethod()
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 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, Longptr_t *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
long double ldbl
unsigned long ul
union ValHolder::@28 u
long long ll
unsigned long long ull
unsigned int ui
signed char sc
unsigned short us
unsigned char uc
#define F(x, y, z)
#define I(x, y, z)
static double C[]
double T(double x)
Definition: ChebyshevPol.h:34
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
Definition: RExports.h:152
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
Definition: TDictionary.h:160
RooArgSet S(Args_t &&... args)
Definition: RooArgSet.h:215
static constexpr double nm
static constexpr double L
constexpr Double_t E()
Base of natural log:
Definition: TMath.h:96
Definition: TString.h:850
const char * Long
const char * ULong
const char * Float
const char * Double
const char * UChar
const char * Short
const char * Int
const char * UInt
const char * UShort
const char * Bool
const char * Value
Definition: TXMLSetup.cxx:73