isl 0.16
[isl.git] / interface / extract_interface.cc
blob83b81319671578be7d1ae3c15ed2cfe5a5266e8f
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.
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.
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.
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 */
34 #include "isl_config.h"
36 #include <assert.h>
37 #include <iostream>
38 #ifdef HAVE_ADT_OWNINGPTR_H
39 #include <llvm/ADT/OwningPtr.h>
40 #else
41 #include <memory>
42 #endif
43 #include <llvm/Support/raw_ostream.h>
44 #include <llvm/Support/CommandLine.h>
45 #include <llvm/Support/Host.h>
46 #include <llvm/Support/ManagedStatic.h>
47 #include <clang/AST/ASTContext.h>
48 #include <clang/AST/ASTConsumer.h>
49 #include <clang/Basic/FileSystemOptions.h>
50 #include <clang/Basic/FileManager.h>
51 #include <clang/Basic/TargetOptions.h>
52 #include <clang/Basic/TargetInfo.h>
53 #include <clang/Basic/Version.h>
54 #include <clang/Driver/Compilation.h>
55 #include <clang/Driver/Driver.h>
56 #include <clang/Driver/Tool.h>
57 #include <clang/Frontend/CompilerInstance.h>
58 #include <clang/Frontend/CompilerInvocation.h>
59 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
60 #include <clang/Basic/DiagnosticOptions.h>
61 #else
62 #include <clang/Frontend/DiagnosticOptions.h>
63 #endif
64 #include <clang/Frontend/TextDiagnosticPrinter.h>
65 #include <clang/Frontend/Utils.h>
66 #include <clang/Lex/HeaderSearch.h>
67 #include <clang/Lex/Preprocessor.h>
68 #include <clang/Parse/ParseAST.h>
69 #include <clang/Sema/Sema.h>
71 #include "extract_interface.h"
72 #include "python.h"
74 using namespace std;
75 using namespace clang;
76 using namespace clang::driver;
78 #ifdef HAVE_ADT_OWNINGPTR_H
79 #define unique_ptr llvm::OwningPtr
80 #endif
82 static llvm::cl::opt<string> InputFilename(llvm::cl::Positional,
83 llvm::cl::Required, llvm::cl::desc("<input file>"));
84 static llvm::cl::list<string> Includes("I",
85 llvm::cl::desc("Header search path"),
86 llvm::cl::value_desc("path"), llvm::cl::Prefix);
88 static const char *ResourceDir =
89 CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
91 /* Does decl have an attribute of the following form?
93 * __attribute__((annotate("name")))
95 bool has_annotation(Decl *decl, const char *name)
97 if (!decl->hasAttrs())
98 return false;
100 AttrVec attrs = decl->getAttrs();
101 for (AttrVec::const_iterator i = attrs.begin() ; i != attrs.end(); ++i) {
102 const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
103 if (!ann)
104 continue;
105 if (ann->getAnnotation().str() == name)
106 return true;
109 return false;
112 /* Is decl marked as exported?
114 static bool is_exported(Decl *decl)
116 return has_annotation(decl, "isl_export");
119 /* Collect all types and functions that are annotated "isl_export"
120 * in "types" and "function".
122 * We currently only consider single declarations.
124 struct MyASTConsumer : public ASTConsumer {
125 set<RecordDecl *> types;
126 set<FunctionDecl *> functions;
128 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef D) {
129 Decl *decl;
131 if (!D.isSingleDecl())
132 return HandleTopLevelDeclContinue;
133 decl = D.getSingleDecl();
134 if (!is_exported(decl))
135 return HandleTopLevelDeclContinue;
136 switch (decl->getKind()) {
137 case Decl::Record:
138 types.insert(cast<RecordDecl>(decl));
139 break;
140 case Decl::Function:
141 functions.insert(cast<FunctionDecl>(decl));
142 break;
143 default:
144 break;
146 return HandleTopLevelDeclContinue;
150 #ifdef USE_ARRAYREF
152 #ifdef HAVE_CXXISPRODUCTION
153 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
155 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
156 "", false, false, Diags);
158 #elif defined(HAVE_ISPRODUCTION)
159 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
161 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
162 "", false, Diags);
164 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
165 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
167 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
168 "", Diags);
170 #else
171 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
173 return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
175 #endif
177 namespace clang { namespace driver { class Job; } }
179 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
180 * We fix this with a simple overloaded function here.
182 struct ClangAPI {
183 static Job *command(Job *J) { return J; }
184 static Job *command(Job &J) { return &J; }
185 static Command *command(Command &C) { return &C; }
188 /* Create a CompilerInvocation object that stores the command line
189 * arguments constructed by the driver.
190 * The arguments are mainly useful for setting up the system include
191 * paths on newer clangs and on some platforms.
193 static CompilerInvocation *construct_invocation(const char *filename,
194 DiagnosticsEngine &Diags)
196 const char *binary = CLANG_PREFIX"/bin/clang";
197 const unique_ptr<Driver> driver(construct_driver(binary, Diags));
198 std::vector<const char *> Argv;
199 Argv.push_back(binary);
200 Argv.push_back(filename);
201 const unique_ptr<Compilation> compilation(
202 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
203 JobList &Jobs = compilation->getJobs();
205 Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
206 if (strcmp(cmd->getCreator().getName(), "clang"))
207 return NULL;
209 const ArgStringList *args = &cmd->getArguments();
211 CompilerInvocation *invocation = new CompilerInvocation;
212 CompilerInvocation::CreateFromArgs(*invocation, args->data() + 1,
213 args->data() + args->size(),
214 Diags);
215 return invocation;
218 #else
220 static CompilerInvocation *construct_invocation(const char *filename,
221 DiagnosticsEngine &Diags)
223 return NULL;
226 #endif
228 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
230 static TextDiagnosticPrinter *construct_printer(void)
232 return new TextDiagnosticPrinter(llvm::errs(), new DiagnosticOptions());
235 #else
237 static TextDiagnosticPrinter *construct_printer(void)
239 DiagnosticOptions DO;
240 return new TextDiagnosticPrinter(llvm::errs(), DO);
243 #endif
245 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
247 static TargetInfo *create_target_info(CompilerInstance *Clang,
248 DiagnosticsEngine &Diags)
250 shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
251 TO->Triple = llvm::sys::getDefaultTargetTriple();
252 return TargetInfo::CreateTargetInfo(Diags, TO);
255 #elif defined(CREATETARGETINFO_TAKES_POINTER)
257 static TargetInfo *create_target_info(CompilerInstance *Clang,
258 DiagnosticsEngine &Diags)
260 TargetOptions &TO = Clang->getTargetOpts();
261 TO.Triple = llvm::sys::getDefaultTargetTriple();
262 return TargetInfo::CreateTargetInfo(Diags, &TO);
265 #else
267 static TargetInfo *create_target_info(CompilerInstance *Clang,
268 DiagnosticsEngine &Diags)
270 TargetOptions &TO = Clang->getTargetOpts();
271 TO.Triple = llvm::sys::getDefaultTargetTriple();
272 return TargetInfo::CreateTargetInfo(Diags, TO);
275 #endif
277 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
279 static void create_diagnostics(CompilerInstance *Clang)
281 Clang->createDiagnostics(0, NULL, construct_printer());
284 #else
286 static void create_diagnostics(CompilerInstance *Clang)
288 Clang->createDiagnostics(construct_printer());
291 #endif
293 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
295 static void create_preprocessor(CompilerInstance *Clang)
297 Clang->createPreprocessor(TU_Complete);
300 #else
302 static void create_preprocessor(CompilerInstance *Clang)
304 Clang->createPreprocessor();
307 #endif
309 #ifdef ADDPATH_TAKES_4_ARGUMENTS
311 void add_path(HeaderSearchOptions &HSO, string Path)
313 HSO.AddPath(Path, frontend::Angled, false, false);
316 #else
318 void add_path(HeaderSearchOptions &HSO, string Path)
320 HSO.AddPath(Path, frontend::Angled, true, false, false);
323 #endif
325 #ifdef HAVE_SETMAINFILEID
327 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
329 SM.setMainFileID(SM.createFileID(file, SourceLocation(),
330 SrcMgr::C_User));
333 #else
335 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
337 SM.createMainFileID(file);
340 #endif
342 int main(int argc, char *argv[])
344 llvm::cl::ParseCommandLineOptions(argc, argv);
346 CompilerInstance *Clang = new CompilerInstance();
347 create_diagnostics(Clang);
348 DiagnosticsEngine &Diags = Clang->getDiagnostics();
349 Diags.setSuppressSystemWarnings(true);
350 CompilerInvocation *invocation =
351 construct_invocation(InputFilename.c_str(), Diags);
352 if (invocation)
353 Clang->setInvocation(invocation);
354 Clang->createFileManager();
355 Clang->createSourceManager(Clang->getFileManager());
356 TargetInfo *target = create_target_info(Clang, Diags);
357 Clang->setTarget(target);
358 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
359 LangStandard::lang_unspecified);
360 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
361 LangOptions &LO = Clang->getLangOpts();
362 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
363 HSO.ResourceDir = ResourceDir;
365 for (int i = 0; i < Includes.size(); ++i)
366 add_path(HSO, Includes[i]);
368 PO.addMacroDef("__isl_give=__attribute__((annotate(\"isl_give\")))");
369 PO.addMacroDef("__isl_keep=__attribute__((annotate(\"isl_keep\")))");
370 PO.addMacroDef("__isl_take=__attribute__((annotate(\"isl_take\")))");
371 PO.addMacroDef("__isl_export=__attribute__((annotate(\"isl_export\")))");
372 PO.addMacroDef("__isl_overload="
373 "__attribute__((annotate(\"isl_overload\"))) "
374 "__attribute__((annotate(\"isl_export\")))");
375 PO.addMacroDef("__isl_subclass(super)=__attribute__((annotate(\"isl_subclass(\" #super \")\"))) __attribute__((annotate(\"isl_export\")))");
376 PO.addMacroDef("__isl_constructor=__attribute__((annotate(\"isl_constructor\"))) __attribute__((annotate(\"isl_export\")))");
377 PO.addMacroDef("__isl_subclass(super)=__attribute__((annotate(\"isl_subclass(\" #super \")\"))) __attribute__((annotate(\"isl_export\")))");
379 create_preprocessor(Clang);
380 Preprocessor &PP = Clang->getPreprocessor();
382 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), LO);
384 const FileEntry *file = Clang->getFileManager().getFile(InputFilename);
385 assert(file);
386 create_main_file_id(Clang->getSourceManager(), file);
388 Clang->createASTContext();
389 MyASTConsumer consumer;
390 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
392 Diags.getClient()->BeginSourceFile(LO, &PP);
393 ParseAST(*sema);
394 Diags.getClient()->EndSourceFile();
396 generate_python(consumer.types, consumer.functions);
398 delete sema;
399 delete Clang;
400 llvm::llvm_shutdown();
402 return 0;