update for change in arguments of CompilerInstance::createPreprocessor
[pet.git] / pet.cc
blobc8e4a05eafba8d9eea698a4a69aca47d21c065ac
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 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 <vector>
40 #include <iostream>
41 #include <llvm/Support/raw_ostream.h>
42 #include <llvm/Support/ManagedStatic.h>
43 #include <llvm/Support/Host.h>
44 #include <clang/Basic/Version.h>
45 #include <clang/Basic/FileSystemOptions.h>
46 #include <clang/Basic/FileManager.h>
47 #include <clang/Basic/TargetOptions.h>
48 #include <clang/Basic/TargetInfo.h>
49 #include <clang/Driver/Compilation.h>
50 #include <clang/Driver/Driver.h>
51 #include <clang/Driver/Tool.h>
52 #include <clang/Frontend/CompilerInstance.h>
53 #include <clang/Frontend/CompilerInvocation.h>
54 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
55 #include <clang/Basic/DiagnosticOptions.h>
56 #else
57 #include <clang/Frontend/DiagnosticOptions.h>
58 #endif
59 #include <clang/Frontend/TextDiagnosticPrinter.h>
60 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
61 #include <clang/Lex/HeaderSearchOptions.h>
62 #else
63 #include <clang/Frontend/HeaderSearchOptions.h>
64 #endif
65 #include <clang/Frontend/LangStandard.h>
66 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
67 #include <clang/Lex/PreprocessorOptions.h>
68 #else
69 #include <clang/Frontend/PreprocessorOptions.h>
70 #endif
71 #include <clang/Frontend/FrontendOptions.h>
72 #include <clang/Frontend/Utils.h>
73 #include <clang/Lex/HeaderSearch.h>
74 #include <clang/Lex/Preprocessor.h>
75 #include <clang/Lex/Pragma.h>
76 #include <clang/AST/ASTContext.h>
77 #include <clang/AST/ASTConsumer.h>
78 #include <clang/Sema/Sema.h>
79 #include <clang/Sema/SemaDiagnostic.h>
80 #include <clang/Parse/Parser.h>
81 #include <clang/Parse/ParseAST.h>
83 #include <isl/ctx.h>
84 #include <isl/constraint.h>
86 #include <pet.h>
88 #include "options.h"
89 #include "scan.h"
90 #include "print.h"
92 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
94 using namespace std;
95 using namespace clang;
96 using namespace clang::driver;
98 /* Called if we found something we didn't expect in one of the pragmas.
99 * We'll provide more informative warnings later.
101 static void unsupported(Preprocessor &PP, SourceLocation loc)
103 DiagnosticsEngine &diag = PP.getDiagnostics();
104 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
105 "unsupported");
106 DiagnosticBuilder B = diag.Report(loc, id);
109 static int get_int(const char *s)
111 return s[0] == '"' ? atoi(s + 1) : atoi(s);
114 static ValueDecl *get_value_decl(Sema &sema, Token &token)
116 IdentifierInfo *name;
117 Decl *decl;
119 if (token.isNot(tok::identifier))
120 return NULL;
122 name = token.getIdentifierInfo();
123 decl = sema.LookupSingleName(sema.TUScope, name,
124 token.getLocation(), Sema::LookupOrdinaryName);
125 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
128 /* Handle pragmas of the form
130 * #pragma value_bounds identifier lower_bound upper_bound
132 * For each such pragma, add a mapping
133 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
134 * to value_bounds.
136 struct PragmaValueBoundsHandler : public PragmaHandler {
137 Sema &sema;
138 isl_ctx *ctx;
139 isl_union_map *value_bounds;
141 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema) :
142 PragmaHandler("value_bounds"), ctx(ctx), sema(sema) {
143 isl_space *space = isl_space_params_alloc(ctx, 0);
144 value_bounds = isl_union_map_empty(space);
147 ~PragmaValueBoundsHandler() {
148 isl_union_map_free(value_bounds);
151 virtual void HandlePragma(Preprocessor &PP,
152 PragmaIntroducerKind Introducer,
153 Token &ScopTok) {
154 isl_id *id;
155 isl_space *dim;
156 isl_map *map;
157 ValueDecl *vd;
158 Token token;
159 int lb;
160 int ub;
162 PP.Lex(token);
163 vd = get_value_decl(sema, token);
164 if (!vd) {
165 unsupported(PP, token.getLocation());
166 return;
169 PP.Lex(token);
170 if (!token.isLiteral()) {
171 unsupported(PP, token.getLocation());
172 return;
175 lb = get_int(token.getLiteralData());
177 PP.Lex(token);
178 if (!token.isLiteral()) {
179 unsupported(PP, token.getLocation());
180 return;
183 ub = get_int(token.getLiteralData());
185 dim = isl_space_alloc(ctx, 0, 0, 1);
186 map = isl_map_universe(dim);
187 map = isl_map_lower_bound_si(map, isl_dim_out, 0, lb);
188 map = isl_map_upper_bound_si(map, isl_dim_out, 0, ub);
189 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
190 map = isl_map_set_tuple_id(map, isl_dim_in, id);
192 value_bounds = isl_union_map_add_map(value_bounds, map);
196 /* Given a variable declaration, check if it has an integer initializer
197 * and if so, add a parameter corresponding to the variable to "value"
198 * with its value fixed to the integer initializer and return the result.
200 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
201 ValueDecl *decl)
203 VarDecl *vd;
204 Expr *expr;
205 IntegerLiteral *il;
206 isl_val *v;
207 isl_ctx *ctx;
208 isl_id *id;
209 isl_space *space;
210 isl_set *set;
212 vd = cast<VarDecl>(decl);
213 if (!vd)
214 return value;
215 if (!vd->getType()->isIntegerType())
216 return value;
217 expr = vd->getInit();
218 if (!expr)
219 return value;
220 il = cast<IntegerLiteral>(expr);
221 if (!il)
222 return value;
224 ctx = isl_set_get_ctx(value);
225 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
226 space = isl_space_params_alloc(ctx, 1);
227 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
228 set = isl_set_universe(space);
230 v = PetScan::extract_int(ctx, il);
231 set = isl_set_fix_val(set, isl_dim_param, 0, v);
233 return isl_set_intersect(value, set);
236 /* Handle pragmas of the form
238 * #pragma parameter identifier lower_bound
239 * and
240 * #pragma parameter identifier lower_bound upper_bound
242 * For each such pragma, intersect the context with the set
243 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
245 struct PragmaParameterHandler : public PragmaHandler {
246 Sema &sema;
247 isl_set *&context;
248 isl_set *&context_value;
250 PragmaParameterHandler(Sema &sema, isl_set *&context,
251 isl_set *&context_value) :
252 PragmaHandler("parameter"), sema(sema), context(context),
253 context_value(context_value) {}
255 virtual void HandlePragma(Preprocessor &PP,
256 PragmaIntroducerKind Introducer,
257 Token &ScopTok) {
258 isl_id *id;
259 isl_ctx *ctx = isl_set_get_ctx(context);
260 isl_space *dim;
261 isl_set *set;
262 ValueDecl *vd;
263 Token token;
264 int lb;
265 int ub;
266 bool has_ub = false;
268 PP.Lex(token);
269 vd = get_value_decl(sema, token);
270 if (!vd) {
271 unsupported(PP, token.getLocation());
272 return;
275 PP.Lex(token);
276 if (!token.isLiteral()) {
277 unsupported(PP, token.getLocation());
278 return;
281 lb = get_int(token.getLiteralData());
283 PP.Lex(token);
284 if (token.isLiteral()) {
285 has_ub = true;
286 ub = get_int(token.getLiteralData());
287 } else if (token.isNot(tok::eod)) {
288 unsupported(PP, token.getLocation());
289 return;
292 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
293 dim = isl_space_params_alloc(ctx, 1);
294 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
296 set = isl_set_universe(dim);
298 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
299 if (has_ub)
300 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
302 context = isl_set_intersect(context, set);
304 context_value = extract_initialization(context_value, vd);
308 /* Handle pragmas of the form
310 * #pragma pencil independent
312 * For each such pragma, add an entry to the "independent" vector.
314 struct PragmaPencilHandler : public PragmaHandler {
315 std::vector<Independent> &independent;
317 PragmaPencilHandler(std::vector<Independent> &independent) :
318 PragmaHandler("pencil"), independent(independent) {}
320 virtual void HandlePragma(Preprocessor &PP,
321 PragmaIntroducerKind Introducer,
322 Token &PencilTok) {
323 Token token;
324 IdentifierInfo *info;
326 PP.Lex(token);
327 if (token.isNot(tok::identifier))
328 return;
330 info = token.getIdentifierInfo();
331 if (!info->isStr("independent"))
332 return;
334 PP.Lex(token);
335 if (token.isNot(tok::eod))
336 return;
338 SourceManager &SM = PP.getSourceManager();
339 SourceLocation sloc = PencilTok.getLocation();
340 unsigned line = SM.getExpansionLineNumber(sloc);
341 independent.push_back(Independent(line));
345 #ifdef HAVE_TRANSLATELINECOL
347 /* Return a SourceLocation for line "line", column "col" of file "FID".
349 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
350 unsigned col)
352 return SM.translateLineCol(FID, line, col);
355 #else
357 /* Return a SourceLocation for line "line", column "col" of file "FID".
359 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
360 unsigned col)
362 return SM.getLocation(SM.getFileEntryForID(FID), line, col);
365 #endif
367 /* List of pairs of #pragma scop and #pragma endscop locations.
369 struct ScopLocList {
370 std::vector<ScopLoc> list;
372 /* Add a new start (#pragma scop) location to the list.
373 * If the last #pragma scop did not have a matching
374 * #pragma endscop then overwrite it.
376 void add_start(unsigned line, unsigned start) {
377 ScopLoc loc;
379 loc.start_line = line;
380 loc.start = start;
381 if (list.size() == 0 || list[list.size() - 1].end != 0)
382 list.push_back(loc);
383 else
384 list[list.size() - 1] = loc;
387 /* Set the end location (#pragma endscop) of the last pair
388 * in the list.
389 * If there is no such pair of if the end of that pair
390 * is already set, then ignore the spurious #pragma endscop.
392 void add_end(unsigned end) {
393 if (list.size() == 0 || list[list.size() - 1].end != 0)
394 return;
395 list[list.size() - 1].end = end;
399 /* Handle pragmas of the form
401 * #pragma scop
403 * In particular, store the location of the line containing
404 * the pragma in the list "scops".
406 struct PragmaScopHandler : public PragmaHandler {
407 ScopLocList &scops;
409 PragmaScopHandler(ScopLocList &scops) :
410 PragmaHandler("scop"), scops(scops) {}
412 virtual void HandlePragma(Preprocessor &PP,
413 PragmaIntroducerKind Introducer,
414 Token &ScopTok) {
415 SourceManager &SM = PP.getSourceManager();
416 SourceLocation sloc = ScopTok.getLocation();
417 int line = SM.getExpansionLineNumber(sloc);
418 sloc = translateLineCol(SM, SM.getFileID(sloc), line, 1);
419 scops.add_start(line, SM.getFileOffset(sloc));
423 /* Handle pragmas of the form
425 * #pragma endscop
427 * In particular, store the location of the line following the one containing
428 * the pragma in the list "scops".
430 struct PragmaEndScopHandler : public PragmaHandler {
431 ScopLocList &scops;
433 PragmaEndScopHandler(ScopLocList &scops) :
434 PragmaHandler("endscop"), scops(scops) {}
436 virtual void HandlePragma(Preprocessor &PP,
437 PragmaIntroducerKind Introducer,
438 Token &EndScopTok) {
439 SourceManager &SM = PP.getSourceManager();
440 SourceLocation sloc = EndScopTok.getLocation();
441 int line = SM.getExpansionLineNumber(sloc);
442 sloc = translateLineCol(SM, SM.getFileID(sloc), line + 1, 1);
443 scops.add_end(SM.getFileOffset(sloc));
447 /* Handle pragmas of the form
449 * #pragma live-out identifier, identifier, ...
451 * Each identifier on the line is stored in live_out.
453 struct PragmaLiveOutHandler : public PragmaHandler {
454 Sema &sema;
455 set<ValueDecl *> &live_out;
457 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
458 PragmaHandler("live"), sema(sema), live_out(live_out) {}
460 virtual void HandlePragma(Preprocessor &PP,
461 PragmaIntroducerKind Introducer,
462 Token &ScopTok) {
463 Token token;
465 PP.Lex(token);
466 if (token.isNot(tok::minus))
467 return;
468 PP.Lex(token);
469 if (token.isNot(tok::identifier) ||
470 !token.getIdentifierInfo()->isStr("out"))
471 return;
473 PP.Lex(token);
474 while (token.isNot(tok::eod)) {
475 ValueDecl *vd;
477 vd = get_value_decl(sema, token);
478 if (!vd) {
479 unsupported(PP, token.getLocation());
480 return;
482 live_out.insert(vd);
483 PP.Lex(token);
484 if (token.is(tok::comma))
485 PP.Lex(token);
490 /* For each array in "scop", set its value_bounds property
491 * based on the infofrmation in "value_bounds" and
492 * mark it as live_out if it appears in "live_out".
494 static void update_arrays(struct pet_scop *scop,
495 __isl_take isl_union_map *value_bounds, set<ValueDecl *> &live_out)
497 set<ValueDecl *>::iterator lo_it;
498 isl_ctx *ctx = isl_union_map_get_ctx(value_bounds);
500 if (!scop) {
501 isl_union_map_free(value_bounds);
502 return;
505 for (int i = 0; i < scop->n_array; ++i) {
506 isl_id *id;
507 isl_space *space;
508 isl_map *bounds;
509 ValueDecl *decl;
510 pet_array *array = scop->arrays[i];
512 id = isl_set_get_tuple_id(array->extent);
513 decl = (ValueDecl *)isl_id_get_user(id);
515 space = isl_space_alloc(ctx, 0, 0, 1);
516 space = isl_space_set_tuple_id(space, isl_dim_in, id);
518 bounds = isl_union_map_extract_map(value_bounds, space);
519 if (!isl_map_plain_is_empty(bounds))
520 array->value_bounds = isl_map_range(bounds);
521 else
522 isl_map_free(bounds);
524 lo_it = live_out.find(decl);
525 if (lo_it != live_out.end())
526 array->live_out = 1;
529 isl_union_map_free(value_bounds);
532 /* Extract a pet_scop (if any) from each appropriate function.
533 * Each detected scop is passed to "fn".
534 * When autodetecting, at most one scop is extracted from each function.
535 * If "function" is not NULL, then we only extract a pet_scop if the
536 * name of the function matches.
537 * If "autodetect" is false, then we only extract if we have seen
538 * scop and endscop pragmas and if these are situated inside the function
539 * body.
541 struct PetASTConsumer : public ASTConsumer {
542 Preprocessor &PP;
543 ASTContext &ast_context;
544 DiagnosticsEngine &diags;
545 ScopLocList &scops;
546 std::vector<Independent> independent;
547 const char *function;
548 pet_options *options;
549 isl_ctx *ctx;
550 isl_set *context;
551 isl_set *context_value;
552 set<ValueDecl *> live_out;
553 PragmaValueBoundsHandler *vb_handler;
554 int (*fn)(struct pet_scop *scop, void *user);
555 void *user;
556 bool error;
558 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
559 DiagnosticsEngine &diags, ScopLocList &scops,
560 const char *function, pet_options *options,
561 int (*fn)(struct pet_scop *scop, void *user), void *user) :
562 ctx(ctx), PP(PP), ast_context(ast_context), diags(diags),
563 scops(scops), function(function), options(options),
564 vb_handler(NULL), fn(fn), user(user), error(false)
566 isl_space *space;
567 space = isl_space_params_alloc(ctx, 0);
568 context = isl_set_universe(isl_space_copy(space));
569 context_value = isl_set_universe(space);
572 ~PetASTConsumer() {
573 isl_set_free(context);
574 isl_set_free(context_value);
577 void handle_value_bounds(Sema *sema) {
578 vb_handler = new PragmaValueBoundsHandler(ctx, *sema);
579 PP.AddPragmaHandler(vb_handler);
582 /* Add all pragma handlers to this->PP.
584 void add_pragma_handlers(Sema *sema) {
585 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
586 context_value));
587 PP.AddPragmaHandler(new PragmaPencilHandler(independent));
588 handle_value_bounds(sema);
591 __isl_give isl_union_map *get_value_bounds() {
592 return isl_union_map_copy(vb_handler->value_bounds);
595 /* Pass "scop" to "fn" after performing some postprocessing.
596 * In particular, add the context and value_bounds constraints
597 * speficied through pragmas, add reference identifiers and
598 * reset user pointers on parameters and tuple ids.
600 void call_fn(pet_scop *scop) {
601 if (!scop)
602 return;
603 if (diags.hasErrorOccurred()) {
604 pet_scop_free(scop);
605 return;
607 scop->context = isl_set_intersect(scop->context,
608 isl_set_copy(context));
609 scop->context_value = isl_set_intersect(scop->context_value,
610 isl_set_copy(context_value));
612 update_arrays(scop, get_value_bounds(), live_out);
614 scop = pet_scop_add_ref_ids(scop);
615 scop = pet_scop_anonymize(scop);
617 if (fn(scop, user) < 0)
618 error = true;
621 /* For each explicitly marked scop (using pragmas),
622 * extract the scop and call "fn" on it if it is inside "fd".
624 void scan_scops(FunctionDecl *fd) {
625 unsigned start, end;
626 vector<ScopLoc>::iterator it;
627 isl_union_map *vb = vb_handler->value_bounds;
628 SourceManager &SM = PP.getSourceManager();
629 pet_scop *scop;
631 if (scops.list.size() == 0)
632 return;
634 start = SM.getFileOffset(fd->getLocStart());
635 end = SM.getFileOffset(fd->getLocEnd());
637 for (it = scops.list.begin(); it != scops.list.end(); ++it) {
638 ScopLoc loc = *it;
639 if (!loc.end)
640 continue;
641 if (start > loc.end)
642 continue;
643 if (end < loc.start)
644 continue;
645 PetScan ps(PP, ast_context, loc, options,
646 isl_union_map_copy(vb), independent);
647 scop = ps.scan(fd);
648 call_fn(scop);
652 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef dg) {
653 DeclGroupRef::iterator it;
655 if (error)
656 return HandleTopLevelDeclContinue;
658 for (it = dg.begin(); it != dg.end(); ++it) {
659 isl_union_map *vb = vb_handler->value_bounds;
660 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
661 if (!fd)
662 continue;
663 if (!fd->hasBody())
664 continue;
665 if (function &&
666 fd->getNameInfo().getAsString() != function)
667 continue;
668 if (options->autodetect) {
669 ScopLoc loc;
670 pet_scop *scop;
671 PetScan ps(PP, ast_context, loc, options,
672 isl_union_map_copy(vb),
673 independent);
674 scop = ps.scan(fd);
675 call_fn(scop);
676 continue;
678 scan_scops(fd);
681 return HandleTopLevelDeclContinue;
685 static const char *ResourceDir =
686 CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
688 static const char *implicit_functions[] = {
689 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
692 static bool is_implicit(const IdentifierInfo *ident)
694 const char *name = ident->getNameStart();
695 for (int i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
696 if (!strcmp(name, implicit_functions[i]))
697 return true;
698 return false;
701 /* Ignore implicit function declaration warnings on
702 * "min", "max", "ceild" and "floord" as we detect and handle these
703 * in PetScan.
705 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
706 const DiagnosticOptions *DiagOpts;
707 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
708 MyDiagnosticPrinter(DiagnosticOptions *DO) :
709 TextDiagnosticPrinter(llvm::errs(), DO) {}
710 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
711 return new MyDiagnosticPrinter(&Diags.getDiagnosticOptions());
713 #else
714 MyDiagnosticPrinter(const DiagnosticOptions &DO) :
715 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO) {}
716 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
717 return new MyDiagnosticPrinter(*DiagOpts);
719 #endif
720 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
721 const DiagnosticInfo &info) {
722 if (info.getID() == diag::ext_implicit_function_decl &&
723 info.getNumArgs() == 1 &&
724 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
725 is_implicit(info.getArgIdentifier(0)))
726 /* ignore warning */;
727 else
728 TextDiagnosticPrinter::HandleDiagnostic(level, info);
732 #ifdef USE_ARRAYREF
734 #ifdef HAVE_CXXISPRODUCTION
735 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
737 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
738 "", false, false, Diags);
740 #elif defined(HAVE_ISPRODUCTION)
741 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
743 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
744 "", false, Diags);
746 #else
747 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
749 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
750 "", Diags);
752 #endif
754 /* Create a CompilerInvocation object that stores the command line
755 * arguments constructed by the driver.
756 * The arguments are mainly useful for setting up the system include
757 * paths on newer clangs and on some platforms.
759 static CompilerInvocation *construct_invocation(const char *filename,
760 DiagnosticsEngine &Diags)
762 const char *binary = CLANG_PREFIX"/bin/clang";
763 const llvm::OwningPtr<Driver> driver(construct_driver(binary, Diags));
764 std::vector<const char *> Argv;
765 Argv.push_back(binary);
766 Argv.push_back(filename);
767 const llvm::OwningPtr<Compilation> compilation(
768 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
769 JobList &Jobs = compilation->getJobs();
770 if (Jobs.size() < 1)
771 return NULL;
773 Command *cmd = cast<Command>(*Jobs.begin());
774 if (strcmp(cmd->getCreator().getName(), "clang"))
775 return NULL;
777 const ArgStringList *args = &cmd->getArguments();
779 CompilerInvocation *invocation = new CompilerInvocation;
780 CompilerInvocation::CreateFromArgs(*invocation, args->data() + 1,
781 args->data() + args->size(),
782 Diags);
783 return invocation;
786 #else
788 static CompilerInvocation *construct_invocation(const char *filename,
789 DiagnosticsEngine &Diags)
791 return NULL;
794 #endif
796 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
798 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang)
800 return new MyDiagnosticPrinter(new DiagnosticOptions());
803 #else
805 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang)
807 return new MyDiagnosticPrinter(Clang->getDiagnosticOpts());
810 #endif
812 #ifdef CREATETARGETINFO_TAKES_POINTER
814 static TargetInfo *create_target_info(CompilerInstance *Clang,
815 DiagnosticsEngine &Diags)
817 TargetOptions &TO = Clang->getTargetOpts();
818 TO.Triple = llvm::sys::getDefaultTargetTriple();
819 return TargetInfo::CreateTargetInfo(Diags, &TO);
822 #else
824 static TargetInfo *create_target_info(CompilerInstance *Clang,
825 DiagnosticsEngine &Diags)
827 TargetOptions &TO = Clang->getTargetOpts();
828 TO.Triple = llvm::sys::getDefaultTargetTriple();
829 return TargetInfo::CreateTargetInfo(Diags, TO);
832 #endif
834 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
836 static void create_diagnostics(CompilerInstance *Clang)
838 Clang->createDiagnostics(0, NULL);
841 #else
843 static void create_diagnostics(CompilerInstance *Clang)
845 Clang->createDiagnostics();
848 #endif
850 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
852 static void create_preprocessor(CompilerInstance *Clang)
854 Clang->createPreprocessor(TU_Complete);
857 #else
859 static void create_preprocessor(CompilerInstance *Clang)
861 Clang->createPreprocessor();
864 #endif
866 #ifdef ADDPATH_TAKES_4_ARGUMENTS
868 void add_path(HeaderSearchOptions &HSO, string Path)
870 HSO.AddPath(Path, frontend::Angled, false, false);
873 #else
875 void add_path(HeaderSearchOptions &HSO, string Path)
877 HSO.AddPath(Path, frontend::Angled, true, false, false);
880 #endif
882 /* Add pet specific predefines to the preprocessor.
884 * We mimic the way <command line> is handled inside clang.
886 void add_predefines(Preprocessor &PP)
888 string s;
890 s = PP.getPredefines();
891 s += "# 1 \"<pet>\" 1\n"
892 "void __pencil_assume(int assumption);\n"
893 "# 1 \"<built-in>\" 2\n";
894 PP.setPredefines(s);
897 /* Extract a pet_scop from each function in the C source file called "filename".
898 * Each detected scop is passed to "fn".
899 * If "function" is not NULL, only extract a pet_scop from the function
900 * with that name.
901 * If "autodetect" is set, extract any pet_scop we can find.
902 * Otherwise, extract the pet_scop from the region delimited
903 * by "scop" and "endscop" pragmas.
905 * We first set up the clang parser and then try to extract the
906 * pet_scop from the appropriate function(s) in PetASTConsumer.
908 static int foreach_scop_in_C_source(isl_ctx *ctx,
909 const char *filename, const char *function, pet_options *options,
910 int (*fn)(struct pet_scop *scop, void *user), void *user)
912 CompilerInstance *Clang = new CompilerInstance();
913 create_diagnostics(Clang);
914 DiagnosticsEngine &Diags = Clang->getDiagnostics();
915 Diags.setSuppressSystemWarnings(true);
916 CompilerInvocation *invocation = construct_invocation(filename, Diags);
917 if (invocation)
918 Clang->setInvocation(invocation);
919 Diags.setClient(construct_printer(Clang));
920 Clang->createFileManager();
921 Clang->createSourceManager(Clang->getFileManager());
922 TargetInfo *target = create_target_info(Clang, Diags);
923 Clang->setTarget(target);
924 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
925 LangStandard::lang_unspecified);
926 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
927 HSO.ResourceDir = ResourceDir;
928 for (int i = 0; i < options->n_path; ++i)
929 add_path(HSO, options->paths[i]);
930 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
931 for (int i = 0; i < options->n_define; ++i)
932 PO.addMacroDef(options->defines[i]);
933 create_preprocessor(Clang);
934 Preprocessor &PP = Clang->getPreprocessor();
935 add_predefines(PP);
937 ScopLocList scops;
939 const FileEntry *file = Clang->getFileManager().getFile(filename);
940 if (!file)
941 isl_die(ctx, isl_error_unknown, "unable to open file",
942 do { delete Clang; return -1; } while (0));
943 Clang->getSourceManager().createMainFileID(file);
945 Clang->createASTContext();
946 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(), Diags,
947 scops, function, options, fn, user);
948 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
950 if (!options->autodetect) {
951 PP.AddPragmaHandler(new PragmaScopHandler(scops));
952 PP.AddPragmaHandler(new PragmaEndScopHandler(scops));
953 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema,
954 consumer.live_out));
957 consumer.add_pragma_handlers(sema);
959 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
960 ParseAST(*sema);
961 Diags.getClient()->EndSourceFile();
963 delete sema;
964 delete Clang;
966 return consumer.error ? -1 : 0;
969 /* Extract a pet_scop from each function in the C source file called "filename".
970 * Each detected scop is passed to "fn".
972 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
973 * that all objects on the stack (of that function) are destroyed before we
974 * call llvm_shutdown.
976 static int pet_foreach_scop_in_C_source(isl_ctx *ctx,
977 const char *filename, const char *function,
978 int (*fn)(struct pet_scop *scop, void *user), void *user)
980 int r;
981 pet_options *options;
982 bool allocated = false;
984 options = isl_ctx_peek_pet_options(ctx);
985 if (!options) {
986 options = pet_options_new_with_defaults();
987 allocated = true;
990 r = foreach_scop_in_C_source(ctx, filename, function, options,
991 fn, user);
992 llvm::llvm_shutdown();
994 if (allocated)
995 pet_options_free(options);
997 return r;
1000 /* Store "scop" into the address pointed to by "user".
1001 * Return -1 to indicate that we are not interested in any further scops.
1002 * This function should therefore not be called a second call
1003 * so in principle there is no need to check if we have already set *user.
1005 static int set_first_scop(pet_scop *scop, void *user)
1007 pet_scop **p = (pet_scop **) user;
1009 if (!*p)
1010 *p = scop;
1011 else
1012 pet_scop_free(scop);
1014 return -1;
1017 /* Extract a pet_scop from the C source file called "filename".
1018 * If "function" is not NULL, extract the pet_scop from the function
1019 * with that name.
1021 * We start extracting scops from every function and then abort
1022 * as soon as we have extracted one scop.
1024 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
1025 const char *filename, const char *function)
1027 pet_scop *scop = NULL;
1029 pet_foreach_scop_in_C_source(ctx, filename, function,
1030 &set_first_scop, &scop);
1032 return scop;
1035 /* Internal data structure for pet_transform_C_source
1037 * transform is the function that should be called to print a scop
1038 * in is the input source file
1039 * out is the output source file
1040 * end is the offset of the end of the previous scop (zero if we have not
1041 * found any scop yet)
1042 * p is a printer that prints to out.
1044 struct pet_transform_data {
1045 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1046 struct pet_scop *scop, void *user);
1047 void *user;
1049 FILE *in;
1050 FILE *out;
1051 unsigned end;
1052 isl_printer *p;
1055 /* This function is called each time a scop is detected.
1057 * We first copy the input text code from the end of the previous scop
1058 * until the start of "scop" and then print the scop itself through
1059 * a call to data->transform. We set up the printer to print
1060 * the transformed code with the same (initial) indentation as
1061 * the original code.
1062 * Finally, we keep track of the end of "scop" so that we can
1063 * continue copying when we find the next scop.
1065 * Before calling data->transform, we store a pointer to the original
1066 * input file in the extended scop in case the user wants to call
1067 * pet_scop_print_original from the callback.
1069 static int pet_transform(struct pet_scop *scop, void *user)
1071 struct pet_transform_data *data = (struct pet_transform_data *) user;
1072 unsigned start;
1074 start = pet_loc_get_start(scop->loc);
1075 if (copy(data->in, data->out, data->end, start) < 0)
1076 goto error;
1077 data->end = pet_loc_get_end(scop->loc);
1078 scop = pet_scop_set_input_file(scop, data->in);
1079 data->p = isl_printer_set_indent_prefix(data->p,
1080 pet_loc_get_indent(scop->loc));
1081 data->p = data->transform(data->p, scop, data->user);
1082 if (!data->p)
1083 return -1;
1084 return 0;
1085 error:
1086 pet_scop_free(scop);
1087 return -1;
1090 /* Transform the C source file "input" by rewriting each scop
1091 * through a call to "transform".
1092 * When autodetecting scops, at most one scop per function is rewritten.
1093 * The transformed C code is written to "output".
1095 * For each scop we find, we first copy the input text code
1096 * from the end of the previous scop (or the beginning of the file
1097 * in case of the first scop) until the start of the scop
1098 * and then print the scop itself through a call to "transform".
1099 * At the end we copy everything from the end of the final scop
1100 * until the end of the input file to "output".
1102 int pet_transform_C_source(isl_ctx *ctx, const char *input, FILE *out,
1103 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1104 struct pet_scop *scop, void *user), void *user)
1106 struct pet_transform_data data;
1107 int r;
1109 data.in = stdin;
1110 data.out = out;
1111 if (input && strcmp(input, "-")) {
1112 data.in = fopen(input, "r");
1113 if (!data.in)
1114 isl_die(ctx, isl_error_unknown, "unable to open file",
1115 return -1);
1118 data.p = isl_printer_to_file(ctx, data.out);
1119 data.p = isl_printer_set_output_format(data.p, ISL_FORMAT_C);
1121 data.transform = transform;
1122 data.user = user;
1123 data.end = 0;
1124 r = pet_foreach_scop_in_C_source(ctx, input, NULL,
1125 &pet_transform, &data);
1127 isl_printer_free(data.p);
1128 if (!data.p)
1129 r = -1;
1130 if (r == 0 && copy(data.in, data.out, data.end, -1) < 0)
1131 r = -1;
1133 if (data.in != stdin)
1134 fclose(data.in);
1136 return r;