scan.cc: fix typos in comments
[pet.git] / pet.cc
blob18ff822902a53c55d7dc42fe3029ee8f6a375636
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include "config.h"
37 #include <stdlib.h>
38 #include <map>
39 #include <iostream>
40 #include <llvm/Support/raw_ostream.h>
41 #include <llvm/Support/ManagedStatic.h>
42 #include <llvm/Support/Host.h>
43 #include <clang/Basic/Version.h>
44 #include <clang/Basic/FileSystemOptions.h>
45 #include <clang/Basic/FileManager.h>
46 #include <clang/Basic/TargetOptions.h>
47 #include <clang/Basic/TargetInfo.h>
48 #include <clang/Driver/Compilation.h>
49 #include <clang/Driver/Driver.h>
50 #include <clang/Driver/Tool.h>
51 #include <clang/Frontend/CompilerInstance.h>
52 #include <clang/Frontend/CompilerInvocation.h>
53 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
54 #include <clang/Basic/DiagnosticOptions.h>
55 #else
56 #include <clang/Frontend/DiagnosticOptions.h>
57 #endif
58 #include <clang/Frontend/TextDiagnosticPrinter.h>
59 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
60 #include <clang/Lex/HeaderSearchOptions.h>
61 #else
62 #include <clang/Frontend/HeaderSearchOptions.h>
63 #endif
64 #include <clang/Frontend/LangStandard.h>
65 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
66 #include <clang/Lex/PreprocessorOptions.h>
67 #else
68 #include <clang/Frontend/PreprocessorOptions.h>
69 #endif
70 #include <clang/Frontend/FrontendOptions.h>
71 #include <clang/Frontend/Utils.h>
72 #include <clang/Lex/HeaderSearch.h>
73 #include <clang/Lex/Preprocessor.h>
74 #include <clang/Lex/Pragma.h>
75 #include <clang/AST/ASTContext.h>
76 #include <clang/AST/ASTConsumer.h>
77 #include <clang/Sema/Sema.h>
78 #include <clang/Sema/SemaDiagnostic.h>
79 #include <clang/Parse/Parser.h>
80 #include <clang/Parse/ParseAST.h>
82 #include <isl/ctx.h>
83 #include <isl/constraint.h>
85 #include "options.h"
86 #include "scan.h"
88 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
90 using namespace std;
91 using namespace clang;
92 using namespace clang::driver;
94 /* Called if we found something we didn't expect in one of the pragmas.
95 * We'll provide more informative warnings later.
97 static void unsupported(Preprocessor &PP, SourceLocation loc)
99 DiagnosticsEngine &diag = PP.getDiagnostics();
100 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
101 "unsupported");
102 DiagnosticBuilder B = diag.Report(loc, id);
105 static int get_int(const char *s)
107 return s[0] == '"' ? atoi(s + 1) : atoi(s);
110 static ValueDecl *get_value_decl(Sema &sema, Token &token)
112 IdentifierInfo *name;
113 Decl *decl;
115 if (token.isNot(tok::identifier))
116 return NULL;
118 name = token.getIdentifierInfo();
119 decl = sema.LookupSingleName(sema.TUScope, name,
120 token.getLocation(), Sema::LookupOrdinaryName);
121 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
124 /* Handle pragmas of the form
126 * #pragma value_bounds identifier lower_bound upper_bound
128 * For each such pragma, add a mapping
129 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
130 * to value_bounds.
132 struct PragmaValueBoundsHandler : public PragmaHandler {
133 Sema &sema;
134 isl_ctx *ctx;
135 isl_union_map *value_bounds;
137 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema) :
138 PragmaHandler("value_bounds"), ctx(ctx), sema(sema) {
139 isl_space *space = isl_space_params_alloc(ctx, 0);
140 value_bounds = isl_union_map_empty(space);
143 ~PragmaValueBoundsHandler() {
144 isl_union_map_free(value_bounds);
147 virtual void HandlePragma(Preprocessor &PP,
148 PragmaIntroducerKind Introducer,
149 Token &ScopTok) {
150 isl_id *id;
151 isl_space *dim;
152 isl_map *map;
153 ValueDecl *vd;
154 Token token;
155 int lb;
156 int ub;
158 PP.Lex(token);
159 vd = get_value_decl(sema, token);
160 if (!vd) {
161 unsupported(PP, token.getLocation());
162 return;
165 PP.Lex(token);
166 if (!token.isLiteral()) {
167 unsupported(PP, token.getLocation());
168 return;
171 lb = get_int(token.getLiteralData());
173 PP.Lex(token);
174 if (!token.isLiteral()) {
175 unsupported(PP, token.getLocation());
176 return;
179 ub = get_int(token.getLiteralData());
181 dim = isl_space_alloc(ctx, 0, 0, 1);
182 map = isl_map_universe(dim);
183 map = isl_map_lower_bound_si(map, isl_dim_out, 0, lb);
184 map = isl_map_upper_bound_si(map, isl_dim_out, 0, ub);
185 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
186 map = isl_map_set_tuple_id(map, isl_dim_in, id);
188 value_bounds = isl_union_map_add_map(value_bounds, map);
192 /* Given a variable declaration, check if it has an integer initializer
193 * and if so, add a parameter corresponding to the variable to "value"
194 * with its value fixed to the integer initializer and return the result.
196 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
197 ValueDecl *decl)
199 VarDecl *vd;
200 Expr *expr;
201 IntegerLiteral *il;
202 isl_val *v;
203 isl_ctx *ctx;
204 isl_id *id;
205 isl_space *space;
206 isl_set *set;
208 vd = cast<VarDecl>(decl);
209 if (!vd)
210 return value;
211 if (!vd->getType()->isIntegerType())
212 return value;
213 expr = vd->getInit();
214 if (!expr)
215 return value;
216 il = cast<IntegerLiteral>(expr);
217 if (!il)
218 return value;
220 ctx = isl_set_get_ctx(value);
221 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
222 space = isl_space_params_alloc(ctx, 1);
223 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
224 set = isl_set_universe(space);
226 v = PetScan::extract_int(ctx, il);
227 set = isl_set_fix_val(set, isl_dim_param, 0, v);
229 return isl_set_intersect(value, set);
232 /* Handle pragmas of the form
234 * #pragma parameter identifier lower_bound
235 * and
236 * #pragma parameter identifier lower_bound upper_bound
238 * For each such pragma, intersect the context with the set
239 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
241 struct PragmaParameterHandler : public PragmaHandler {
242 Sema &sema;
243 isl_set *&context;
244 isl_set *&context_value;
246 PragmaParameterHandler(Sema &sema, isl_set *&context,
247 isl_set *&context_value) :
248 PragmaHandler("parameter"), sema(sema), context(context),
249 context_value(context_value) {}
251 virtual void HandlePragma(Preprocessor &PP,
252 PragmaIntroducerKind Introducer,
253 Token &ScopTok) {
254 isl_id *id;
255 isl_ctx *ctx = isl_set_get_ctx(context);
256 isl_space *dim;
257 isl_set *set;
258 ValueDecl *vd;
259 Token token;
260 int lb;
261 int ub;
262 bool has_ub = false;
264 PP.Lex(token);
265 vd = get_value_decl(sema, token);
266 if (!vd) {
267 unsupported(PP, token.getLocation());
268 return;
271 PP.Lex(token);
272 if (!token.isLiteral()) {
273 unsupported(PP, token.getLocation());
274 return;
277 lb = get_int(token.getLiteralData());
279 PP.Lex(token);
280 if (token.isLiteral()) {
281 has_ub = true;
282 ub = get_int(token.getLiteralData());
283 } else if (token.isNot(tok::eod)) {
284 unsupported(PP, token.getLocation());
285 return;
288 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
289 dim = isl_space_params_alloc(ctx, 1);
290 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
292 set = isl_set_universe(dim);
294 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
295 if (has_ub)
296 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
298 context = isl_set_intersect(context, set);
300 context_value = extract_initialization(context_value, vd);
304 #ifdef HAVE_TRANSLATELINECOL
306 /* Return a SourceLocation for line "line", column "col" of file "FID".
308 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
309 unsigned col)
311 return SM.translateLineCol(FID, line, col);
314 #else
316 /* Return a SourceLocation for line "line", column "col" of file "FID".
318 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
319 unsigned col)
321 return SM.getLocation(SM.getFileEntryForID(FID), line, col);
324 #endif
326 /* Handle pragmas of the form
328 * #pragma scop
330 * In particular, store the location of the line containing
331 * the pragma in loc.start.
333 struct PragmaScopHandler : public PragmaHandler {
334 ScopLoc &loc;
336 PragmaScopHandler(ScopLoc &loc) : PragmaHandler("scop"), loc(loc) {}
338 virtual void HandlePragma(Preprocessor &PP,
339 PragmaIntroducerKind Introducer,
340 Token &ScopTok) {
341 SourceManager &SM = PP.getSourceManager();
342 SourceLocation sloc = ScopTok.getLocation();
343 int line = SM.getExpansionLineNumber(sloc);
344 sloc = translateLineCol(SM, SM.getFileID(sloc), line, 1);
345 loc.start = SM.getFileOffset(sloc);
349 /* Handle pragmas of the form
351 * #pragma endscop
353 * In particular, store the location of the line following the one containing
354 * the pragma in loc.end.
356 struct PragmaEndScopHandler : public PragmaHandler {
357 ScopLoc &loc;
359 PragmaEndScopHandler(ScopLoc &loc) :
360 PragmaHandler("endscop"), loc(loc) {}
362 virtual void HandlePragma(Preprocessor &PP,
363 PragmaIntroducerKind Introducer,
364 Token &EndScopTok) {
365 SourceManager &SM = PP.getSourceManager();
366 SourceLocation sloc = EndScopTok.getLocation();
367 int line = SM.getExpansionLineNumber(sloc);
368 sloc = translateLineCol(SM, SM.getFileID(sloc), line + 1, 1);
369 loc.end = SM.getFileOffset(sloc);
373 /* Handle pragmas of the form
375 * #pragma live-out identifier, identifier, ...
377 * Each identifier on the line is stored in live_out.
379 struct PragmaLiveOutHandler : public PragmaHandler {
380 Sema &sema;
381 set<ValueDecl *> &live_out;
383 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
384 PragmaHandler("live"), sema(sema), live_out(live_out) {}
386 virtual void HandlePragma(Preprocessor &PP,
387 PragmaIntroducerKind Introducer,
388 Token &ScopTok) {
389 Token token;
391 PP.Lex(token);
392 if (token.isNot(tok::minus))
393 return;
394 PP.Lex(token);
395 if (token.isNot(tok::identifier) ||
396 !token.getIdentifierInfo()->isStr("out"))
397 return;
399 PP.Lex(token);
400 while (token.isNot(tok::eod)) {
401 ValueDecl *vd;
403 vd = get_value_decl(sema, token);
404 if (!vd) {
405 unsupported(PP, token.getLocation());
406 return;
408 live_out.insert(vd);
409 PP.Lex(token);
410 if (token.is(tok::comma))
411 PP.Lex(token);
416 /* Extract a pet_scop from the appropriate function.
417 * If "function" is not NULL, then we only extract a pet_scop if the
418 * name of the function matches.
419 * If "autodetect" is false, then we only extract if we have seen
420 * scop and endscop pragmas and if these are situated inside the function
421 * body.
423 struct PetASTConsumer : public ASTConsumer {
424 Preprocessor &PP;
425 ASTContext &ast_context;
426 ScopLoc &loc;
427 const char *function;
428 pet_options *options;
429 isl_ctx *ctx;
430 struct pet_scop *scop;
431 PragmaValueBoundsHandler *vb_handler;
433 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
434 ScopLoc &loc, const char *function, pet_options *options) :
435 ctx(ctx), PP(PP), ast_context(ast_context), loc(loc),
436 scop(NULL), function(function), options(options),
437 vb_handler(NULL) { }
439 void handle_value_bounds(Sema *sema) {
440 vb_handler = new PragmaValueBoundsHandler(ctx, *sema);
441 PP.AddPragmaHandler(vb_handler);
444 __isl_give isl_union_map *get_value_bounds() {
445 return isl_union_map_copy(vb_handler->value_bounds);
448 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef dg) {
449 DeclGroupRef::iterator it;
451 if (scop)
452 return HandleTopLevelDeclContinue;
453 for (it = dg.begin(); it != dg.end(); ++it) {
454 isl_union_map *vb = vb_handler->value_bounds;
455 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
456 if (!fd)
457 continue;
458 if (!fd->hasBody())
459 continue;
460 if (function &&
461 fd->getNameInfo().getAsString() != function)
462 continue;
463 if (options->autodetect) {
464 PetScan ps(PP, ast_context, loc, options,
465 isl_union_map_copy(vb));
466 scop = ps.scan(fd);
467 if (scop)
468 break;
469 else
470 continue;
472 if (!loc.end)
473 continue;
474 SourceManager &SM = PP.getSourceManager();
475 if (SM.getFileOffset(fd->getLocStart()) > loc.end)
476 continue;
477 if (SM.getFileOffset(fd->getLocEnd()) < loc.start)
478 continue;
479 PetScan ps(PP, ast_context, loc, options,
480 isl_union_map_copy(vb));
481 scop = ps.scan(fd);
482 break;
485 return HandleTopLevelDeclContinue;
489 static const char *ResourceDir = CLANG_PREFIX"/lib/clang/"CLANG_VERSION_STRING;
491 static const char *implicit_functions[] = {
492 "min", "max", "ceild", "floord"
495 static bool is_implicit(const IdentifierInfo *ident)
497 const char *name = ident->getNameStart();
498 for (int i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
499 if (!strcmp(name, implicit_functions[i]))
500 return true;
501 return false;
504 /* Ignore implicit function declaration warnings on
505 * "min", "max", "ceild" and "floord" as we detect and handle these
506 * in PetScan.
508 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
509 const DiagnosticOptions *DiagOpts;
510 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
511 MyDiagnosticPrinter(DiagnosticOptions *DO) :
512 TextDiagnosticPrinter(llvm::errs(), DO) {}
513 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
514 return new MyDiagnosticPrinter(&Diags.getDiagnosticOptions());
516 #else
517 MyDiagnosticPrinter(const DiagnosticOptions &DO) :
518 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO) {}
519 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
520 return new MyDiagnosticPrinter(*DiagOpts);
522 #endif
523 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
524 const DiagnosticInfo &info) {
525 if (info.getID() == diag::ext_implicit_function_decl &&
526 info.getNumArgs() == 1 &&
527 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
528 is_implicit(info.getArgIdentifier(0)))
529 /* ignore warning */;
530 else
531 TextDiagnosticPrinter::HandleDiagnostic(level, info);
535 /* For each array in "scop", set its value_bounds property
536 * based on the infofrmation in "value_bounds" and
537 * mark it as live_out if it appears in "live_out".
539 static void update_arrays(struct pet_scop *scop,
540 __isl_take isl_union_map *value_bounds, set<ValueDecl *> &live_out)
542 set<ValueDecl *>::iterator lo_it;
543 isl_ctx *ctx = isl_union_map_get_ctx(value_bounds);
545 if (!scop) {
546 isl_union_map_free(value_bounds);
547 return;
550 for (int i = 0; i < scop->n_array; ++i) {
551 isl_id *id;
552 isl_space *space;
553 isl_map *bounds;
554 ValueDecl *decl;
555 pet_array *array = scop->arrays[i];
557 id = isl_set_get_tuple_id(array->extent);
558 decl = (ValueDecl *)isl_id_get_user(id);
560 space = isl_space_alloc(ctx, 0, 0, 1);
561 space = isl_space_set_tuple_id(space, isl_dim_in, id);
563 bounds = isl_union_map_extract_map(value_bounds, space);
564 if (!isl_map_plain_is_empty(bounds))
565 array->value_bounds = isl_map_range(bounds);
566 else
567 isl_map_free(bounds);
569 lo_it = live_out.find(decl);
570 if (lo_it != live_out.end())
571 array->live_out = 1;
574 isl_union_map_free(value_bounds);
577 #ifdef USE_ARRAYREF
579 #ifdef HAVE_CXXISPRODUCTION
580 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
582 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
583 "", false, false, Diags);
585 #elif defined(HAVE_ISPRODUCTION)
586 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
588 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
589 "", false, Diags);
591 #else
592 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
594 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
595 "", Diags);
597 #endif
599 /* Create a CompilerInvocation object that stores the command line
600 * arguments constructed by the driver.
601 * The arguments are mainly useful for setting up the system include
602 * paths on newer clangs and on some platforms.
604 static CompilerInvocation *construct_invocation(const char *filename,
605 DiagnosticsEngine &Diags)
607 const char *binary = CLANG_PREFIX"/bin/clang";
608 const llvm::OwningPtr<Driver> driver(construct_driver(binary, Diags));
609 std::vector<const char *> Argv;
610 Argv.push_back(binary);
611 Argv.push_back(filename);
612 const llvm::OwningPtr<Compilation> compilation(
613 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
614 JobList &Jobs = compilation->getJobs();
615 if (Jobs.size() < 1)
616 return NULL;
618 Command *cmd = cast<Command>(*Jobs.begin());
619 if (strcmp(cmd->getCreator().getName(), "clang"))
620 return NULL;
622 const ArgStringList *args = &cmd->getArguments();
624 CompilerInvocation *invocation = new CompilerInvocation;
625 CompilerInvocation::CreateFromArgs(*invocation, args->data() + 1,
626 args->data() + args->size(),
627 Diags);
628 return invocation;
631 #else
633 static CompilerInvocation *construct_invocation(const char *filename,
634 DiagnosticsEngine &Diags)
636 return NULL;
639 #endif
641 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
643 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang)
645 return new MyDiagnosticPrinter(new DiagnosticOptions());
648 #else
650 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang)
652 return new MyDiagnosticPrinter(Clang->getDiagnosticOpts());
655 #endif
657 #ifdef CREATETARGETINFO_TAKES_POINTER
659 static TargetInfo *create_target_info(CompilerInstance *Clang,
660 DiagnosticsEngine &Diags)
662 TargetOptions &TO = Clang->getTargetOpts();
663 TO.Triple = llvm::sys::getDefaultTargetTriple();
664 return TargetInfo::CreateTargetInfo(Diags, &TO);
667 #else
669 static TargetInfo *create_target_info(CompilerInstance *Clang,
670 DiagnosticsEngine &Diags)
672 TargetOptions &TO = Clang->getTargetOpts();
673 TO.Triple = llvm::sys::getDefaultTargetTriple();
674 return TargetInfo::CreateTargetInfo(Diags, TO);
677 #endif
679 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
681 static void create_diagnostics(CompilerInstance *Clang)
683 Clang->createDiagnostics(0, NULL);
686 #else
688 static void create_diagnostics(CompilerInstance *Clang)
690 Clang->createDiagnostics();
693 #endif
695 #ifdef ADDPATH_TAKES_4_ARGUMENTS
697 void add_path(HeaderSearchOptions &HSO, string Path)
699 HSO.AddPath(Path, frontend::Angled, false, false);
702 #else
704 void add_path(HeaderSearchOptions &HSO, string Path)
706 HSO.AddPath(Path, frontend::Angled, true, false, false);
709 #endif
711 /* Extract a pet_scop from the C source file called "filename".
712 * If "function" is not NULL, extract the pet_scop from the function
713 * with that name.
714 * If "autodetect" is set, extract any pet_scop we can find.
715 * Otherwise, extract the pet_scop from the region delimited
716 * by "scop" and "endscop" pragmas.
718 * We first set up the clang parser and then try to extract the
719 * pet_scop from the appropriate function in PetASTConsumer.
720 * If we have found a pet_scop, we add the context and value_bounds
721 * constraints specified through pragmas.
723 static struct pet_scop *scop_extract_from_C_source(isl_ctx *ctx,
724 const char *filename, const char *function, pet_options *options)
726 isl_space *dim;
727 isl_set *context;
728 isl_set *context_value;
729 pet_scop *scop;
730 set<ValueDecl *> live_out;
731 isl_union_map *value_bounds;
733 CompilerInstance *Clang = new CompilerInstance();
734 create_diagnostics(Clang);
735 DiagnosticsEngine &Diags = Clang->getDiagnostics();
736 Diags.setSuppressSystemWarnings(true);
737 CompilerInvocation *invocation = construct_invocation(filename, Diags);
738 if (invocation)
739 Clang->setInvocation(invocation);
740 Diags.setClient(construct_printer(Clang));
741 Clang->createFileManager();
742 Clang->createSourceManager(Clang->getFileManager());
743 TargetInfo *target = create_target_info(Clang, Diags);
744 Clang->setTarget(target);
745 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
746 LangStandard::lang_unspecified);
747 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
748 HSO.ResourceDir = ResourceDir;
749 for (int i = 0; i < options->n_path; ++i)
750 add_path(HSO, options->paths[i]);
751 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
752 for (int i = 0; i < options->n_define; ++i)
753 PO.addMacroDef(options->defines[i]);
754 Clang->createPreprocessor();
755 Preprocessor &PP = Clang->getPreprocessor();
757 ScopLoc loc;
759 const FileEntry *file = Clang->getFileManager().getFile(filename);
760 if (!file)
761 isl_die(ctx, isl_error_unknown, "unable to open file",
762 do { delete Clang; return NULL; } while (0));
763 Clang->getSourceManager().createMainFileID(file);
765 Clang->createASTContext();
766 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(),
767 loc, function, options);
768 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
770 if (!options->autodetect) {
771 PP.AddPragmaHandler(new PragmaScopHandler(loc));
772 PP.AddPragmaHandler(new PragmaEndScopHandler(loc));
773 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema, live_out));
776 dim = isl_space_params_alloc(ctx, 0);
777 context = isl_set_universe(isl_space_copy(dim));
778 context_value = isl_set_universe(dim);
779 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
780 context_value));
781 consumer.handle_value_bounds(sema);
783 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
784 ParseAST(*sema);
785 Diags.getClient()->EndSourceFile();
787 scop = consumer.scop;
788 if (Diags.hasErrorOccurred()) {
789 pet_scop_free(scop);
790 scop = NULL;
793 if (scop) {
794 scop->context = isl_set_intersect(context, scop->context);
795 scop->context_value = isl_set_intersect(context_value,
796 scop->context_value);
797 } else {
798 isl_set_free(context);
799 isl_set_free(context_value);
802 update_arrays(scop, consumer.get_value_bounds(), live_out);
804 scop = pet_scop_anonymize(scop);
806 delete sema;
807 delete Clang;
809 return scop;
812 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
813 const char *filename, const char *function)
815 pet_scop *scop;
816 pet_options *options;
817 bool allocated = false;
819 options = isl_ctx_peek_pet_options(ctx);
820 if (!options) {
821 options = pet_options_new_with_defaults();
822 allocated = true;
825 scop = scop_extract_from_C_source(ctx, filename, function, options);
826 llvm::llvm_shutdown();
828 if (allocated)
829 pet_options_free(options);
831 return scop;