• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2011 Sven Verdoolaege. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  *    1. Redistributions of source code must retain the above copyright
9  *       notice, this list of conditions and the following disclaimer.
10  *
11  *    2. Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY SVEN VERDOOLAEGE ''AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SVEN VERDOOLAEGE OR
20  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * The views and conclusions contained in the software and documentation
29  * are those of the authors and should not be interpreted as
30  * representing official policies, either expressed or implied, of
31  * Sven Verdoolaege.
32  */
33 
34 #include "isl_config.h"
35 #undef PACKAGE
36 
37 #include <assert.h>
38 #include <iostream>
39 #include <stdlib.h>
40 #ifdef HAVE_ADT_OWNINGPTR_H
41 #include <llvm/ADT/OwningPtr.h>
42 #else
43 #include <memory>
44 #endif
45 #ifdef HAVE_LLVM_OPTION_ARG_H
46 #include <llvm/Option/Arg.h>
47 #endif
48 #include <llvm/Support/raw_ostream.h>
49 #include <llvm/Support/CommandLine.h>
50 #include <llvm/Support/Host.h>
51 #include <llvm/Support/ManagedStatic.h>
52 #include <clang/AST/ASTContext.h>
53 #include <clang/AST/ASTConsumer.h>
54 #include <clang/Basic/Builtins.h>
55 #include <clang/Basic/FileSystemOptions.h>
56 #include <clang/Basic/FileManager.h>
57 #include <clang/Basic/TargetOptions.h>
58 #include <clang/Basic/TargetInfo.h>
59 #include <clang/Basic/Version.h>
60 #include <clang/Driver/Compilation.h>
61 #include <clang/Driver/Driver.h>
62 #include <clang/Driver/Tool.h>
63 #include <clang/Frontend/CompilerInstance.h>
64 #include <clang/Frontend/CompilerInvocation.h>
65 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
66 #include <clang/Basic/DiagnosticOptions.h>
67 #else
68 #include <clang/Frontend/DiagnosticOptions.h>
69 #endif
70 #include <clang/Frontend/TextDiagnosticPrinter.h>
71 #include <clang/Frontend/Utils.h>
72 #include <clang/Lex/HeaderSearch.h>
73 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
74 #include <clang/Lex/PreprocessorOptions.h>
75 #else
76 #include <clang/Frontend/PreprocessorOptions.h>
77 #endif
78 #include <clang/Lex/Preprocessor.h>
79 #include <clang/Parse/ParseAST.h>
80 #include <clang/Sema/Sema.h>
81 
82 #include "extract_interface.h"
83 #include "generator.h"
84 #include "python.h"
85 #include "cpp.h"
86 #include "cpp_conversion.h"
87 
88 using namespace std;
89 using namespace clang;
90 using namespace clang::driver;
91 #ifdef HAVE_LLVM_OPTION_ARG_H
92 using namespace llvm::opt;
93 #endif
94 
95 #ifdef HAVE_ADT_OWNINGPTR_H
96 #define unique_ptr	llvm::OwningPtr
97 #endif
98 
99 static llvm::cl::opt<string> InputFilename(llvm::cl::Positional,
100 			llvm::cl::Required, llvm::cl::desc("<input file>"));
101 static llvm::cl::list<string> Includes("I",
102 			llvm::cl::desc("Header search path"),
103 			llvm::cl::value_desc("path"), llvm::cl::Prefix);
104 
105 static llvm::cl::opt<string> OutputLanguage(llvm::cl::Required,
106 	llvm::cl::ValueRequired, "language",
107 	llvm::cl::desc("Bindings to generate"),
108 	llvm::cl::value_desc("name"));
109 
110 static const char *ResourceDir =
111 	CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
112 
113 /* Does decl have an attribute of the following form?
114  *
115  *	__attribute__((annotate("name")))
116  */
has_annotation(Decl * decl,const char * name)117 bool has_annotation(Decl *decl, const char *name)
118 {
119 	if (!decl->hasAttrs())
120 		return false;
121 
122 	AttrVec attrs = decl->getAttrs();
123 	for (AttrVec::const_iterator i = attrs.begin() ; i != attrs.end(); ++i) {
124 		const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
125 		if (!ann)
126 			continue;
127 		if (ann->getAnnotation().str() == name)
128 			return true;
129 	}
130 
131 	return false;
132 }
133 
134 /* Is decl marked as exported?
135  */
is_exported(Decl * decl)136 static bool is_exported(Decl *decl)
137 {
138 	return has_annotation(decl, "isl_export");
139 }
140 
141 /* Collect all types and functions that are annotated "isl_export"
142  * in "exported_types" and "exported_function".  Collect all function
143  * declarations in "functions".
144  *
145  * We currently only consider single declarations.
146  */
147 struct MyASTConsumer : public ASTConsumer {
148 	set<RecordDecl *> exported_types;
149 	set<FunctionDecl *> exported_functions;
150 	set<FunctionDecl *> functions;
151 
HandleTopLevelDeclMyASTConsumer152 	virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef D) {
153 		Decl *decl;
154 
155 		if (!D.isSingleDecl())
156 			return HandleTopLevelDeclContinue;
157 		decl = D.getSingleDecl();
158 		if (isa<FunctionDecl>(decl))
159 			functions.insert(cast<FunctionDecl>(decl));
160 		if (!is_exported(decl))
161 			return HandleTopLevelDeclContinue;
162 		switch (decl->getKind()) {
163 		case Decl::Record:
164 			exported_types.insert(cast<RecordDecl>(decl));
165 			break;
166 		case Decl::Function:
167 			exported_functions.insert(cast<FunctionDecl>(decl));
168 			break;
169 		default:
170 			break;
171 		}
172 		return HandleTopLevelDeclContinue;
173 	}
174 };
175 
176 #ifdef USE_ARRAYREF
177 
178 #ifdef HAVE_CXXISPRODUCTION
construct_driver(const char * binary,DiagnosticsEngine & Diags)179 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
180 {
181 	return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
182 			    "", false, false, Diags);
183 }
184 #elif defined(HAVE_ISPRODUCTION)
construct_driver(const char * binary,DiagnosticsEngine & Diags)185 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
186 {
187 	return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
188 			    "", false, Diags);
189 }
190 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
construct_driver(const char * binary,DiagnosticsEngine & Diags)191 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
192 {
193 	return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
194 			    "", Diags);
195 }
196 #else
construct_driver(const char * binary,DiagnosticsEngine & Diags)197 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
198 {
199 	return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
200 }
201 #endif
202 
203 namespace clang { namespace driver { class Job; } }
204 
205 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
206  * We fix this with a simple overloaded function here.
207  */
208 struct ClangAPI {
commandClangAPI209 	static Job *command(Job *J) { return J; }
commandClangAPI210 	static Job *command(Job &J) { return &J; }
commandClangAPI211 	static Command *command(Command &C) { return &C; }
212 };
213 
214 #ifdef CREATE_FROM_ARGS_TAKES_ARRAYREF
215 
216 /* Call CompilerInvocation::CreateFromArgs with the right arguments.
217  * In this case, an ArrayRef<const char *>.
218  */
create_from_args(CompilerInvocation & invocation,const ArgStringList * args,DiagnosticsEngine & Diags)219 static void create_from_args(CompilerInvocation &invocation,
220 	const ArgStringList *args, DiagnosticsEngine &Diags)
221 {
222 	CompilerInvocation::CreateFromArgs(invocation, *args, Diags);
223 }
224 
225 #else
226 
227 /* Call CompilerInvocation::CreateFromArgs with the right arguments.
228  * In this case, two "const char *" pointers.
229  */
create_from_args(CompilerInvocation & invocation,const ArgStringList * args,DiagnosticsEngine & Diags)230 static void create_from_args(CompilerInvocation &invocation,
231 	const ArgStringList *args, DiagnosticsEngine &Diags)
232 {
233 	CompilerInvocation::CreateFromArgs(invocation, args->data() + 1,
234 						args->data() + args->size(),
235 						Diags);
236 }
237 
238 #endif
239 
240 #ifdef CLANG_SYSROOT
241 /* Set sysroot if required.
242  *
243  * If CLANG_SYSROOT is defined, then set it to this value.
244  */
set_sysroot(ArgStringList & args)245 static void set_sysroot(ArgStringList &args)
246 {
247 	args.push_back("-isysroot");
248 	args.push_back(CLANG_SYSROOT);
249 }
250 #else
251 /* Set sysroot if required.
252  *
253  * If CLANG_SYSROOT is not defined, then it does not need to be set.
254  */
set_sysroot(ArgStringList & args)255 static void set_sysroot(ArgStringList &args)
256 {
257 }
258 #endif
259 
260 /* Create a CompilerInvocation object that stores the command line
261  * arguments constructed by the driver.
262  * The arguments are mainly useful for setting up the system include
263  * paths on newer clangs and on some platforms.
264  */
construct_invocation(const char * filename,DiagnosticsEngine & Diags)265 static CompilerInvocation *construct_invocation(const char *filename,
266 	DiagnosticsEngine &Diags)
267 {
268 	const char *binary = CLANG_PREFIX"/bin/clang";
269 	const unique_ptr<Driver> driver(construct_driver(binary, Diags));
270 	std::vector<const char *> Argv;
271 	Argv.push_back(binary);
272 	Argv.push_back(filename);
273 	const unique_ptr<Compilation> compilation(
274 		driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
275 	JobList &Jobs = compilation->getJobs();
276 
277 	Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
278 	if (strcmp(cmd->getCreator().getName(), "clang"))
279 		return NULL;
280 
281 	ArgStringList args = cmd->getArguments();
282 	set_sysroot(args);
283 
284 	CompilerInvocation *invocation = new CompilerInvocation;
285 	create_from_args(*invocation, &args, Diags);
286 	return invocation;
287 }
288 
289 #else
290 
construct_invocation(const char * filename,DiagnosticsEngine & Diags)291 static CompilerInvocation *construct_invocation(const char *filename,
292 	DiagnosticsEngine &Diags)
293 {
294 	return NULL;
295 }
296 
297 #endif
298 
299 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
300 
construct_printer(void)301 static TextDiagnosticPrinter *construct_printer(void)
302 {
303 	return new TextDiagnosticPrinter(llvm::errs(), new DiagnosticOptions());
304 }
305 
306 #else
307 
construct_printer(void)308 static TextDiagnosticPrinter *construct_printer(void)
309 {
310 	DiagnosticOptions DO;
311 	return new TextDiagnosticPrinter(llvm::errs(), DO);
312 }
313 
314 #endif
315 
316 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
317 
create_target_info(CompilerInstance * Clang,DiagnosticsEngine & Diags)318 static TargetInfo *create_target_info(CompilerInstance *Clang,
319 	DiagnosticsEngine &Diags)
320 {
321 	shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
322 	TO->Triple = llvm::sys::getDefaultTargetTriple();
323 	return TargetInfo::CreateTargetInfo(Diags, TO);
324 }
325 
326 #elif defined(CREATETARGETINFO_TAKES_POINTER)
327 
create_target_info(CompilerInstance * Clang,DiagnosticsEngine & Diags)328 static TargetInfo *create_target_info(CompilerInstance *Clang,
329 	DiagnosticsEngine &Diags)
330 {
331 	TargetOptions &TO = Clang->getTargetOpts();
332 	TO.Triple = llvm::sys::getDefaultTargetTriple();
333 	return TargetInfo::CreateTargetInfo(Diags, &TO);
334 }
335 
336 #else
337 
create_target_info(CompilerInstance * Clang,DiagnosticsEngine & Diags)338 static TargetInfo *create_target_info(CompilerInstance *Clang,
339 	DiagnosticsEngine &Diags)
340 {
341 	TargetOptions &TO = Clang->getTargetOpts();
342 	TO.Triple = llvm::sys::getDefaultTargetTriple();
343 	return TargetInfo::CreateTargetInfo(Diags, TO);
344 }
345 
346 #endif
347 
348 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
349 
create_diagnostics(CompilerInstance * Clang)350 static void create_diagnostics(CompilerInstance *Clang)
351 {
352 	Clang->createDiagnostics(0, NULL, construct_printer());
353 }
354 
355 #else
356 
create_diagnostics(CompilerInstance * Clang)357 static void create_diagnostics(CompilerInstance *Clang)
358 {
359 	Clang->createDiagnostics(construct_printer());
360 }
361 
362 #endif
363 
364 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
365 
create_preprocessor(CompilerInstance * Clang)366 static void create_preprocessor(CompilerInstance *Clang)
367 {
368 	Clang->createPreprocessor(TU_Complete);
369 }
370 
371 #else
372 
create_preprocessor(CompilerInstance * Clang)373 static void create_preprocessor(CompilerInstance *Clang)
374 {
375 	Clang->createPreprocessor();
376 }
377 
378 #endif
379 
380 #ifdef ADDPATH_TAKES_4_ARGUMENTS
381 
382 /* Add "Path" to the header search options.
383  *
384  * Do not take into account sysroot, i.e., set ignoreSysRoot to true.
385  */
add_path(HeaderSearchOptions & HSO,string Path)386 void add_path(HeaderSearchOptions &HSO, string Path)
387 {
388 	HSO.AddPath(Path, frontend::Angled, false, true);
389 }
390 
391 #else
392 
393 /* Add "Path" to the header search options.
394  *
395  * Do not take into account sysroot, i.e., set IsSysRootRelative to false.
396  */
add_path(HeaderSearchOptions & HSO,string Path)397 void add_path(HeaderSearchOptions &HSO, string Path)
398 {
399 	HSO.AddPath(Path, frontend::Angled, true, false, false);
400 }
401 
402 #endif
403 
404 #ifdef HAVE_SETMAINFILEID
405 
create_main_file_id(SourceManager & SM,const FileEntry * file)406 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
407 {
408 	SM.setMainFileID(SM.createFileID(file, SourceLocation(),
409 					SrcMgr::C_User));
410 }
411 
412 #else
413 
create_main_file_id(SourceManager & SM,const FileEntry * file)414 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
415 {
416 	SM.createMainFileID(file);
417 }
418 
419 #endif
420 
421 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
422 
set_lang_defaults(CompilerInstance * Clang)423 static void set_lang_defaults(CompilerInstance *Clang)
424 {
425 	PreprocessorOptions &PO = Clang->getPreprocessorOpts();
426 	TargetOptions &TO = Clang->getTargetOpts();
427 	llvm::Triple T(TO.Triple);
428 	CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C, T, PO,
429 					    LangStandard::lang_unspecified);
430 }
431 
432 #else
433 
set_lang_defaults(CompilerInstance * Clang)434 static void set_lang_defaults(CompilerInstance *Clang)
435 {
436 	CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
437 					    LangStandard::lang_unspecified);
438 }
439 
440 #endif
441 
442 #ifdef SETINVOCATION_TAKES_SHARED_PTR
443 
set_invocation(CompilerInstance * Clang,CompilerInvocation * invocation)444 static void set_invocation(CompilerInstance *Clang,
445 	CompilerInvocation *invocation)
446 {
447 	Clang->setInvocation(std::make_shared<CompilerInvocation>(*invocation));
448 }
449 
450 #else
451 
set_invocation(CompilerInstance * Clang,CompilerInvocation * invocation)452 static void set_invocation(CompilerInstance *Clang,
453 	CompilerInvocation *invocation)
454 {
455 	Clang->setInvocation(invocation);
456 }
457 
458 #endif
459 
460 /* Helper function for ignore_error that only gets enabled if T
461  * (which is either const FileEntry * or llvm::ErrorOr<const FileEntry *>)
462  * has getError method, i.e., if it is llvm::ErrorOr<const FileEntry *>.
463  */
464 template <class T>
ignore_error_helper(const T obj,int,int[1][sizeof (obj.getError ())])465 static const FileEntry *ignore_error_helper(const T obj, int,
466 	int[1][sizeof(obj.getError())])
467 {
468 	return *obj;
469 }
470 
471 /* Helper function for ignore_error that is always enabled,
472  * but that only gets selected if the variant above is not enabled,
473  * i.e., if T is const FileEntry *.
474  */
475 template <class T>
ignore_error_helper(const T obj,long,void *)476 static const FileEntry *ignore_error_helper(const T obj, long, void *)
477 {
478 	return obj;
479 }
480 
481 /* Given either a const FileEntry * or a llvm::ErrorOr<const FileEntry *>,
482  * extract out the const FileEntry *.
483  */
484 template <class T>
ignore_error(const T obj)485 static const FileEntry *ignore_error(const T obj)
486 {
487 	return ignore_error_helper(obj, 0, NULL);
488 }
489 
490 /* Return the FileEntry corresponding to the given file name
491  * in the given compiler instances, ignoring any error.
492  */
getFile(CompilerInstance * Clang,std::string Filename)493 static const FileEntry *getFile(CompilerInstance *Clang, std::string Filename)
494 {
495 	return ignore_error(Clang->getFileManager().getFile(Filename));
496 }
497 
498 /* Create an interface generator for the selected language and
499  * then use it to generate the interface.
500  */
generate(MyASTConsumer & consumer,SourceManager & SM)501 static void generate(MyASTConsumer &consumer, SourceManager &SM)
502 {
503 	generator *gen;
504 
505 	if (OutputLanguage.compare("python") == 0) {
506 		gen = new python_generator(SM, consumer.exported_types,
507 			consumer.exported_functions, consumer.functions);
508 	} else if (OutputLanguage.compare("cpp") == 0) {
509 		gen = new cpp_generator(SM, consumer.exported_types,
510 			consumer.exported_functions, consumer.functions);
511 	} else if (OutputLanguage.compare("cpp-checked") == 0) {
512 		gen = new cpp_generator(SM, consumer.exported_types,
513 			consumer.exported_functions, consumer.functions, true);
514 	} else if (OutputLanguage.compare("cpp-checked-conversion") == 0) {
515 		gen = new cpp_conversion_generator(SM, consumer.exported_types,
516 			consumer.exported_functions, consumer.functions);
517 	} else {
518 		cerr << "Language '" << OutputLanguage
519 		     << "' not recognized." << endl
520 		     << "Not generating bindings." << endl;
521 		exit(EXIT_FAILURE);
522 	}
523 
524 	gen->generate();
525 }
526 
main(int argc,char * argv[])527 int main(int argc, char *argv[])
528 {
529 	llvm::cl::ParseCommandLineOptions(argc, argv);
530 
531 	CompilerInstance *Clang = new CompilerInstance();
532 	create_diagnostics(Clang);
533 	DiagnosticsEngine &Diags = Clang->getDiagnostics();
534 	Diags.setSuppressSystemWarnings(true);
535 	TargetInfo *target = create_target_info(Clang, Diags);
536 	Clang->setTarget(target);
537 	set_lang_defaults(Clang);
538 	CompilerInvocation *invocation =
539 		construct_invocation(InputFilename.c_str(), Diags);
540 	if (invocation)
541 		set_invocation(Clang, invocation);
542 	Clang->createFileManager();
543 	Clang->createSourceManager(Clang->getFileManager());
544 	HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
545 	LangOptions &LO = Clang->getLangOpts();
546 	PreprocessorOptions &PO = Clang->getPreprocessorOpts();
547 	HSO.ResourceDir = ResourceDir;
548 
549 	for (llvm::cl::list<string>::size_type i = 0; i < Includes.size(); ++i)
550 		add_path(HSO, Includes[i]);
551 
552 	PO.addMacroDef("__isl_give=__attribute__((annotate(\"isl_give\")))");
553 	PO.addMacroDef("__isl_keep=__attribute__((annotate(\"isl_keep\")))");
554 	PO.addMacroDef("__isl_take=__attribute__((annotate(\"isl_take\")))");
555 	PO.addMacroDef("__isl_export=__attribute__((annotate(\"isl_export\")))");
556 	PO.addMacroDef("__isl_overload="
557 	    "__attribute__((annotate(\"isl_overload\"))) "
558 	    "__attribute__((annotate(\"isl_export\")))");
559 	PO.addMacroDef("__isl_constructor=__attribute__((annotate(\"isl_constructor\"))) __attribute__((annotate(\"isl_export\")))");
560 	PO.addMacroDef("__isl_subclass(super)=__attribute__((annotate(\"isl_subclass(\" #super \")\"))) __attribute__((annotate(\"isl_export\")))");
561 
562 	create_preprocessor(Clang);
563 	Preprocessor &PP = Clang->getPreprocessor();
564 
565 	PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), LO);
566 
567 	const FileEntry *file = getFile(Clang, InputFilename);
568 	assert(file);
569 	create_main_file_id(Clang->getSourceManager(), file);
570 
571 	Clang->createASTContext();
572 	MyASTConsumer consumer;
573 	Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
574 
575 	Diags.getClient()->BeginSourceFile(LO, &PP);
576 	ParseAST(*sema);
577 	Diags.getClient()->EndSourceFile();
578 
579 	generate(consumer, Clang->getSourceManager());
580 
581 	delete sema;
582 	delete Clang;
583 	llvm::llvm_shutdown();
584 
585 	if (Diags.hasErrorOccurred())
586 		return EXIT_FAILURE;
587 	return EXIT_SUCCESS;
588 }
589