rerun configure when llvm-config is updated
[pet.git] / pet.cc
blobda476417d50efbcc1f70e95099c72afbb58d48d9
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"
36 #undef PACKAGE
38 #include <stdlib.h>
39 #include <map>
40 #include <vector>
41 #include <iostream>
42 #ifdef HAVE_ADT_OWNINGPTR_H
43 #include <llvm/ADT/OwningPtr.h>
44 #else
45 #include <memory>
46 #endif
47 #ifdef HAVE_LLVM_OPTION_ARG_H
48 #include <llvm/Option/Arg.h>
49 #endif
50 #include <llvm/Support/raw_ostream.h>
51 #include <llvm/Support/ManagedStatic.h>
52 #include <llvm/Support/Host.h>
53 #include <clang/Basic/Version.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/Driver/Compilation.h>
60 #include <clang/Driver/Driver.h>
61 #include <clang/Driver/Tool.h>
62 #include <clang/Frontend/CompilerInstance.h>
63 #include <clang/Frontend/CompilerInvocation.h>
64 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
65 #include <clang/Basic/DiagnosticOptions.h>
66 #else
67 #include <clang/Frontend/DiagnosticOptions.h>
68 #endif
69 #include <clang/Frontend/TextDiagnosticPrinter.h>
70 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
71 #include <clang/Lex/HeaderSearchOptions.h>
72 #else
73 #include <clang/Frontend/HeaderSearchOptions.h>
74 #endif
75 #ifdef HAVE_CLANG_BASIC_LANGSTANDARD_H
76 #include <clang/Basic/LangStandard.h>
77 #else
78 #include <clang/Frontend/LangStandard.h>
79 #endif
80 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
81 #include <clang/Lex/PreprocessorOptions.h>
82 #else
83 #include <clang/Frontend/PreprocessorOptions.h>
84 #endif
85 #include <clang/Frontend/FrontendOptions.h>
86 #include <clang/Frontend/Utils.h>
87 #include <clang/Lex/HeaderSearch.h>
88 #include <clang/Lex/Preprocessor.h>
89 #include <clang/Lex/Pragma.h>
90 #include <clang/AST/ASTContext.h>
91 #include <clang/AST/ASTConsumer.h>
92 #include <clang/Sema/Sema.h>
93 #include <clang/Sema/SemaDiagnostic.h>
94 #include <clang/Parse/Parser.h>
95 #include <clang/Parse/ParseAST.h>
97 #include <isl/ctx.h>
98 #include <isl/constraint.h>
100 #include <pet.h>
102 #include "clang_compatibility.h"
103 #include "id.h"
104 #include "options.h"
105 #include "scan.h"
106 #include "print.h"
108 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
110 using namespace std;
111 using namespace clang;
112 using namespace clang::driver;
113 #ifdef HAVE_LLVM_OPTION_ARG_H
114 using namespace llvm::opt;
115 #endif
117 #ifdef HAVE_ADT_OWNINGPTR_H
118 #define unique_ptr llvm::OwningPtr
119 #endif
121 /* Called if we found something we didn't expect in one of the pragmas.
122 * We'll provide more informative warnings later.
124 static void unsupported(Preprocessor &PP, SourceLocation loc)
126 DiagnosticsEngine &diag = PP.getDiagnostics();
127 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
128 "unsupported");
129 DiagnosticBuilder B = diag.Report(loc, id);
132 static int get_int(const char *s)
134 return s[0] == '"' ? atoi(s + 1) : atoi(s);
137 static ValueDecl *get_value_decl(Sema &sema, Token &token)
139 IdentifierInfo *name;
140 Decl *decl;
142 if (token.isNot(tok::identifier))
143 return NULL;
145 name = token.getIdentifierInfo();
146 decl = sema.LookupSingleName(sema.TUScope, name,
147 token.getLocation(), Sema::LookupOrdinaryName);
148 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
151 /* Handle pragmas of the form
153 * #pragma value_bounds identifier lower_bound upper_bound
155 * For each such pragma, add a mapping
156 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
157 * to value_bounds.
159 struct PragmaValueBoundsHandler : public PragmaHandler {
160 Sema &sema;
161 isl_ctx *ctx;
162 isl_union_map *value_bounds;
164 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema) :
165 PragmaHandler("value_bounds"), sema(sema), ctx(ctx) {
166 isl_space *space = isl_space_params_alloc(ctx, 0);
167 value_bounds = isl_union_map_empty(space);
170 ~PragmaValueBoundsHandler() {
171 isl_union_map_free(value_bounds);
174 virtual void HandlePragma(Preprocessor &PP,
175 PragmaIntroducer Introducer,
176 Token &ScopTok) {
177 isl_id *id;
178 isl_space *dim;
179 isl_map *map;
180 ValueDecl *vd;
181 Token token;
182 int lb;
183 int ub;
185 PP.Lex(token);
186 vd = get_value_decl(sema, token);
187 if (!vd) {
188 unsupported(PP, token.getLocation());
189 return;
192 PP.Lex(token);
193 if (!token.isLiteral()) {
194 unsupported(PP, token.getLocation());
195 return;
198 lb = get_int(token.getLiteralData());
200 PP.Lex(token);
201 if (!token.isLiteral()) {
202 unsupported(PP, token.getLocation());
203 return;
206 ub = get_int(token.getLiteralData());
208 dim = isl_space_alloc(ctx, 0, 0, 1);
209 map = isl_map_universe(dim);
210 map = isl_map_lower_bound_si(map, isl_dim_out, 0, lb);
211 map = isl_map_upper_bound_si(map, isl_dim_out, 0, ub);
212 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
213 map = isl_map_set_tuple_id(map, isl_dim_in, id);
215 value_bounds = isl_union_map_add_map(value_bounds, map);
219 /* Given a variable declaration, check if it has an integer initializer
220 * and if so, add a parameter corresponding to the variable to "value"
221 * with its value fixed to the integer initializer and return the result.
223 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
224 ValueDecl *decl)
226 VarDecl *vd;
227 Expr *expr;
228 IntegerLiteral *il;
229 isl_val *v;
230 isl_ctx *ctx;
231 isl_id *id;
232 isl_space *space;
233 isl_set *set;
235 vd = cast<VarDecl>(decl);
236 if (!vd)
237 return value;
238 if (!vd->getType()->isIntegerType())
239 return value;
240 expr = vd->getInit();
241 if (!expr)
242 return value;
243 il = cast<IntegerLiteral>(expr);
244 if (!il)
245 return value;
247 ctx = isl_set_get_ctx(value);
248 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
249 space = isl_space_params_alloc(ctx, 1);
250 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
251 set = isl_set_universe(space);
253 v = PetScan::extract_int(ctx, il);
254 set = isl_set_fix_val(set, isl_dim_param, 0, v);
256 return isl_set_intersect(value, set);
259 /* Handle pragmas of the form
261 * #pragma parameter identifier lower_bound
262 * and
263 * #pragma parameter identifier lower_bound upper_bound
265 * For each such pragma, intersect the context with the set
266 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
268 struct PragmaParameterHandler : public PragmaHandler {
269 Sema &sema;
270 isl_set *&context;
271 isl_set *&context_value;
273 PragmaParameterHandler(Sema &sema, isl_set *&context,
274 isl_set *&context_value) :
275 PragmaHandler("parameter"), sema(sema), context(context),
276 context_value(context_value) {}
278 virtual void HandlePragma(Preprocessor &PP,
279 PragmaIntroducer Introducer,
280 Token &ScopTok) {
281 isl_id *id;
282 isl_ctx *ctx = isl_set_get_ctx(context);
283 isl_space *dim;
284 isl_set *set;
285 ValueDecl *vd;
286 Token token;
287 int lb;
288 int ub;
289 bool has_ub = false;
291 PP.Lex(token);
292 vd = get_value_decl(sema, token);
293 if (!vd) {
294 unsupported(PP, token.getLocation());
295 return;
298 PP.Lex(token);
299 if (!token.isLiteral()) {
300 unsupported(PP, token.getLocation());
301 return;
304 lb = get_int(token.getLiteralData());
306 PP.Lex(token);
307 if (token.isLiteral()) {
308 has_ub = true;
309 ub = get_int(token.getLiteralData());
310 } else if (token.isNot(tok::eod)) {
311 unsupported(PP, token.getLocation());
312 return;
315 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
316 dim = isl_space_params_alloc(ctx, 1);
317 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
319 set = isl_set_universe(dim);
321 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
322 if (has_ub)
323 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
325 context = isl_set_intersect(context, set);
327 context_value = extract_initialization(context_value, vd);
331 /* Handle pragmas of the form
333 * #pragma pencil independent
335 * For each such pragma, add an entry to the "independent" vector.
337 struct PragmaPencilHandler : public PragmaHandler {
338 std::vector<Independent> &independent;
340 PragmaPencilHandler(std::vector<Independent> &independent) :
341 PragmaHandler("pencil"), independent(independent) {}
343 virtual void HandlePragma(Preprocessor &PP,
344 PragmaIntroducer Introducer,
345 Token &PencilTok) {
346 Token token;
347 IdentifierInfo *info;
349 PP.Lex(token);
350 if (token.isNot(tok::identifier))
351 return;
353 info = token.getIdentifierInfo();
354 if (!info->isStr("independent"))
355 return;
357 PP.Lex(token);
358 if (token.isNot(tok::eod))
359 return;
361 SourceManager &SM = PP.getSourceManager();
362 SourceLocation sloc = PencilTok.getLocation();
363 unsigned line = SM.getExpansionLineNumber(sloc);
364 independent.push_back(Independent(line));
368 #ifdef HAVE_TRANSLATELINECOL
370 /* Return a SourceLocation for line "line", column "col" of file "FID".
372 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
373 unsigned col)
375 return SM.translateLineCol(FID, line, col);
378 #else
380 /* Return a SourceLocation for line "line", column "col" of file "FID".
382 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
383 unsigned col)
385 return SM.getLocation(SM.getFileEntryForID(FID), line, col);
388 #endif
390 /* List of pairs of #pragma scop and #pragma endscop locations.
392 struct ScopLocList {
393 std::vector<ScopLoc> list;
395 /* Add a new start (#pragma scop) location to the list.
396 * If the last #pragma scop did not have a matching
397 * #pragma endscop then overwrite it.
398 * "start" points to the location of the scop pragma.
400 void add_start(SourceManager &SM, SourceLocation start) {
401 ScopLoc loc;
403 loc.scop = start;
404 int line = SM.getExpansionLineNumber(start);
405 start = translateLineCol(SM, SM.getFileID(start), line, 1);
406 loc.start_line = line;
407 loc.start = SM.getFileOffset(start);
408 if (list.size() == 0 || list[list.size() - 1].end != 0)
409 list.push_back(loc);
410 else
411 list[list.size() - 1] = loc;
414 /* Set the end location (#pragma endscop) of the last pair
415 * in the list.
416 * If there is no such pair of if the end of that pair
417 * is already set, then ignore the spurious #pragma endscop.
418 * "end" points to the location of the endscop pragma.
420 void add_end(SourceManager &SM, SourceLocation end) {
421 if (list.size() == 0 || list[list.size() - 1].end != 0)
422 return;
423 list[list.size() - 1].endscop = end;
424 int line = SM.getExpansionLineNumber(end);
425 end = translateLineCol(SM, SM.getFileID(end), line + 1, 1);
426 list[list.size() - 1].end = SM.getFileOffset(end);
430 /* Handle pragmas of the form
432 * #pragma scop
434 * In particular, store the location of the line containing
435 * the pragma in the list "scops".
437 struct PragmaScopHandler : public PragmaHandler {
438 ScopLocList &scops;
440 PragmaScopHandler(ScopLocList &scops) :
441 PragmaHandler("scop"), scops(scops) {}
443 virtual void HandlePragma(Preprocessor &PP,
444 PragmaIntroducer Introducer,
445 Token &ScopTok) {
446 SourceManager &SM = PP.getSourceManager();
447 SourceLocation sloc = ScopTok.getLocation();
448 scops.add_start(SM, sloc);
452 /* Handle pragmas of the form
454 * #pragma endscop
456 * In particular, store the location of the line following the one containing
457 * the pragma in the list "scops".
459 struct PragmaEndScopHandler : public PragmaHandler {
460 ScopLocList &scops;
462 PragmaEndScopHandler(ScopLocList &scops) :
463 PragmaHandler("endscop"), scops(scops) {}
465 virtual void HandlePragma(Preprocessor &PP,
466 PragmaIntroducer Introducer,
467 Token &EndScopTok) {
468 SourceManager &SM = PP.getSourceManager();
469 SourceLocation sloc = EndScopTok.getLocation();
470 scops.add_end(SM, sloc);
474 /* Handle pragmas of the form
476 * #pragma live-out identifier, identifier, ...
478 * Each identifier on the line is stored in live_out.
480 struct PragmaLiveOutHandler : public PragmaHandler {
481 Sema &sema;
482 set<ValueDecl *> &live_out;
484 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
485 PragmaHandler("live"), sema(sema), live_out(live_out) {}
487 virtual void HandlePragma(Preprocessor &PP,
488 PragmaIntroducer Introducer,
489 Token &ScopTok) {
490 Token token;
492 PP.Lex(token);
493 if (token.isNot(tok::minus))
494 return;
495 PP.Lex(token);
496 if (token.isNot(tok::identifier) ||
497 !token.getIdentifierInfo()->isStr("out"))
498 return;
500 PP.Lex(token);
501 while (token.isNot(tok::eod)) {
502 ValueDecl *vd;
504 vd = get_value_decl(sema, token);
505 if (!vd) {
506 unsupported(PP, token.getLocation());
507 return;
509 live_out.insert(vd);
510 PP.Lex(token);
511 if (token.is(tok::comma))
512 PP.Lex(token);
517 /* For each array in "scop", set its value_bounds property
518 * based on the information in "value_bounds" and
519 * mark it as live_out if it appears in "live_out".
521 static void update_arrays(struct pet_scop *scop,
522 __isl_take isl_union_map *value_bounds, set<ValueDecl *> &live_out)
524 set<ValueDecl *>::iterator lo_it;
525 isl_ctx *ctx = isl_union_map_get_ctx(value_bounds);
527 if (!scop) {
528 isl_union_map_free(value_bounds);
529 return;
532 for (int i = 0; i < scop->n_array; ++i) {
533 isl_id *id;
534 isl_space *space;
535 isl_map *bounds;
536 ValueDecl *decl;
537 pet_array *array = scop->arrays[i];
539 id = isl_set_get_tuple_id(array->extent);
540 decl = pet_id_get_decl(id);
542 space = isl_space_alloc(ctx, 0, 0, 1);
543 space = isl_space_set_tuple_id(space, isl_dim_in, id);
545 bounds = isl_union_map_extract_map(value_bounds, space);
546 if (!isl_map_plain_is_empty(bounds))
547 array->value_bounds = isl_map_range(bounds);
548 else
549 isl_map_free(bounds);
551 lo_it = live_out.find(decl);
552 if (lo_it != live_out.end())
553 array->live_out = 1;
556 isl_union_map_free(value_bounds);
559 /* Extract a pet_scop (if any) from each appropriate function.
560 * Each detected scop is passed to "fn".
561 * When autodetecting, at most one scop is extracted from each function.
562 * If "function" is not NULL, then we only extract a pet_scop if the
563 * name of the function matches.
564 * If "autodetect" is false, then we only extract if we have seen
565 * scop and endscop pragmas and if these are situated inside the function
566 * body.
568 struct PetASTConsumer : public ASTConsumer {
569 Preprocessor &PP;
570 ASTContext &ast_context;
571 DiagnosticsEngine &diags;
572 ScopLocList &scops;
573 std::vector<Independent> independent;
574 const char *function;
575 pet_options *options;
576 isl_ctx *ctx;
577 isl_set *context;
578 isl_set *context_value;
579 set<ValueDecl *> live_out;
580 PragmaValueBoundsHandler *vb_handler;
581 isl_stat (*fn)(struct pet_scop *scop, void *user);
582 void *user;
583 bool error;
585 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
586 DiagnosticsEngine &diags, ScopLocList &scops,
587 const char *function, pet_options *options,
588 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user) :
589 PP(PP), ast_context(ast_context), diags(diags),
590 scops(scops), function(function), options(options),
591 ctx(ctx),
592 vb_handler(NULL), fn(fn), user(user), error(false)
594 isl_space *space;
595 space = isl_space_params_alloc(ctx, 0);
596 context = isl_set_universe(isl_space_copy(space));
597 context_value = isl_set_universe(space);
600 ~PetASTConsumer() {
601 isl_set_free(context);
602 isl_set_free(context_value);
605 void handle_value_bounds(Sema *sema) {
606 vb_handler = new PragmaValueBoundsHandler(ctx, *sema);
607 PP.AddPragmaHandler(vb_handler);
610 /* Add all pragma handlers to this->PP.
611 * The pencil pragmas are only handled if the pencil option is set.
613 void add_pragma_handlers(Sema *sema) {
614 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
615 context_value));
616 if (options->pencil) {
617 PragmaHandler *PH;
618 PH = new PragmaPencilHandler(independent);
619 PP.AddPragmaHandler(PH);
621 handle_value_bounds(sema);
624 __isl_give isl_union_map *get_value_bounds() {
625 return isl_union_map_copy(vb_handler->value_bounds);
628 /* Pass "scop" to "fn" after performing some postprocessing.
629 * In particular, add the context and value_bounds constraints
630 * speficied through pragmas, add reference identifiers and
631 * reset user pointers on parameters and tuple ids.
633 * If "scop" does not contain any statements and autodetect
634 * is turned on, then skip it.
636 void call_fn(pet_scop *scop) {
637 if (!scop) {
638 error = true;
639 return;
641 if (diags.hasErrorOccurred()) {
642 error = true;
643 pet_scop_free(scop);
644 return;
646 if (options->autodetect && scop->n_stmt == 0) {
647 pet_scop_free(scop);
648 return;
650 scop->context = isl_set_intersect(scop->context,
651 isl_set_copy(context));
652 scop->context_value = isl_set_intersect(scop->context_value,
653 isl_set_copy(context_value));
655 update_arrays(scop, get_value_bounds(), live_out);
657 scop = pet_scop_add_ref_ids(scop);
658 scop = pet_scop_anonymize(scop);
660 if (fn(scop, user) < 0)
661 error = true;
664 /* For each explicitly marked scop (using pragmas),
665 * extract the scop and call "fn" on it if it is inside "fd".
667 void scan_scops(FunctionDecl *fd) {
668 unsigned start, end;
669 vector<ScopLoc>::iterator it;
670 isl_union_map *vb = vb_handler->value_bounds;
671 SourceManager &SM = PP.getSourceManager();
672 pet_scop *scop;
674 if (scops.list.size() == 0)
675 return;
677 start = SM.getFileOffset(begin_loc(fd));
678 end = SM.getFileOffset(end_loc(fd));
680 for (it = scops.list.begin(); it != scops.list.end(); ++it) {
681 ScopLoc loc = *it;
682 if (!loc.end)
683 continue;
684 if (start > loc.end)
685 continue;
686 if (end < loc.start)
687 continue;
688 PetScan ps(PP, ast_context, fd, loc, options,
689 isl_union_map_copy(vb), independent);
690 scop = ps.scan(fd);
691 call_fn(scop);
695 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef dg) {
696 DeclGroupRef::iterator it;
698 if (error)
699 return HandleTopLevelDeclContinue;
701 for (it = dg.begin(); it != dg.end(); ++it) {
702 isl_union_map *vb = vb_handler->value_bounds;
703 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
704 if (!fd)
705 continue;
706 if (!fd->hasBody())
707 continue;
708 if (function &&
709 fd->getNameInfo().getAsString() != function)
710 continue;
711 if (options->autodetect) {
712 ScopLoc loc;
713 pet_scop *scop;
714 PetScan ps(PP, ast_context, fd, loc, options,
715 isl_union_map_copy(vb),
716 independent);
717 scop = ps.scan(fd);
718 if (!scop)
719 continue;
720 call_fn(scop);
721 continue;
723 scan_scops(fd);
726 return HandleTopLevelDeclContinue;
730 static const char *ResourceDir =
731 CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
733 static const char *implicit_functions[] = {
734 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
736 static const char *pencil_implicit_functions[] = {
737 "imin", "umin", "imax", "umax", "__pencil_kill"
740 /* Should "ident" be treated as an implicit function?
741 * If "pencil" is set, then also allow pencil specific builtins.
743 static bool is_implicit(const IdentifierInfo *ident, int pencil)
745 const char *name = ident->getNameStart();
746 for (size_t i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
747 if (!strcmp(name, implicit_functions[i]))
748 return true;
749 if (!pencil)
750 return false;
751 for (size_t i = 0; i < ARRAY_SIZE(pencil_implicit_functions); ++i)
752 if (!strcmp(name, pencil_implicit_functions[i]))
753 return true;
754 return false;
757 /* Ignore implicit function declaration warnings on
758 * "min", "max", "ceild" and "floord" as we detect and handle these
759 * in PetScan.
760 * If "pencil" is set, then also ignore them on pencil specific
761 * builtins.
763 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
764 const DiagnosticOptions *DiagOpts;
765 int pencil;
766 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
767 MyDiagnosticPrinter(DiagnosticOptions *DO, int pencil) :
768 TextDiagnosticPrinter(llvm::errs(), DO), pencil(pencil) {}
769 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
770 return new MyDiagnosticPrinter(&Diags.getDiagnosticOptions(),
771 pencil);
773 #else
774 MyDiagnosticPrinter(const DiagnosticOptions &DO, int pencil) :
775 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO),
776 pencil(pencil) {}
777 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
778 return new MyDiagnosticPrinter(*DiagOpts, pencil);
780 #endif
781 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
782 const DiagnosticInfo &info) {
783 if (info.getID() == diag::ext_implicit_function_decl &&
784 info.getNumArgs() >= 1 &&
785 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
786 is_implicit(info.getArgIdentifier(0), pencil))
787 /* ignore warning */;
788 else
789 TextDiagnosticPrinter::HandleDiagnostic(level, info);
793 #ifdef USE_ARRAYREF
795 #ifdef HAVE_CXXISPRODUCTION
796 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
798 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
799 "", false, false, Diags);
801 #elif defined(HAVE_ISPRODUCTION)
802 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
804 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
805 "", false, Diags);
807 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
808 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
810 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
811 "", Diags);
813 #else
814 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
816 return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
818 #endif
820 namespace clang { namespace driver { class Job; } }
822 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
823 * We fix this with a simple overloaded function here.
825 struct ClangAPI {
826 static Job *command(Job *J) { return J; }
827 static Job *command(Job &J) { return &J; }
828 static Command *command(Command &C) { return &C; }
831 #ifdef CREATE_FROM_ARGS_TAKES_ARRAYREF
833 /* Call CompilerInvocation::CreateFromArgs with the right arguments.
834 * In this case, an ArrayRef<const char *>.
836 static void create_from_args(CompilerInvocation &invocation,
837 const ArgStringList *args, DiagnosticsEngine &Diags)
839 CompilerInvocation::CreateFromArgs(invocation, *args, Diags);
842 #else
844 /* Call CompilerInvocation::CreateFromArgs with the right arguments.
845 * In this case, two "const char *" pointers.
847 static void create_from_args(CompilerInvocation &invocation,
848 const ArgStringList *args, DiagnosticsEngine &Diags)
850 CompilerInvocation::CreateFromArgs(invocation, args->data() + 1,
851 args->data() + args->size(),
852 Diags);
855 #endif
857 /* Create a CompilerInvocation object that stores the command line
858 * arguments constructed by the driver.
859 * The arguments are mainly useful for setting up the system include
860 * paths on newer clangs and on some platforms.
862 static CompilerInvocation *construct_invocation(const char *filename,
863 DiagnosticsEngine &Diags)
865 const char *binary = CLANG_PREFIX"/bin/clang";
866 const unique_ptr<Driver> driver(construct_driver(binary, Diags));
867 std::vector<const char *> Argv;
868 Argv.push_back(binary);
869 Argv.push_back(filename);
870 const unique_ptr<Compilation> compilation(
871 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
872 JobList &Jobs = compilation->getJobs();
873 if (Jobs.size() < 1)
874 return NULL;
876 Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
877 if (strcmp(cmd->getCreator().getName(), "clang"))
878 return NULL;
880 const ArgStringList *args = &cmd->getArguments();
882 CompilerInvocation *invocation = new CompilerInvocation;
883 create_from_args(*invocation, args, Diags);
884 return invocation;
887 #else
889 static CompilerInvocation *construct_invocation(const char *filename,
890 DiagnosticsEngine &Diags)
892 return NULL;
895 #endif
897 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
899 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
900 int pencil)
902 return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil);
905 #else
907 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
908 int pencil)
910 return new MyDiagnosticPrinter(Clang->getDiagnosticOpts(), pencil);
913 #endif
915 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
917 static TargetInfo *create_target_info(CompilerInstance *Clang,
918 DiagnosticsEngine &Diags)
920 shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
921 TO->Triple = llvm::sys::getDefaultTargetTriple();
922 return TargetInfo::CreateTargetInfo(Diags, TO);
925 #elif defined(CREATETARGETINFO_TAKES_POINTER)
927 static TargetInfo *create_target_info(CompilerInstance *Clang,
928 DiagnosticsEngine &Diags)
930 TargetOptions &TO = Clang->getTargetOpts();
931 TO.Triple = llvm::sys::getDefaultTargetTriple();
932 return TargetInfo::CreateTargetInfo(Diags, &TO);
935 #else
937 static TargetInfo *create_target_info(CompilerInstance *Clang,
938 DiagnosticsEngine &Diags)
940 TargetOptions &TO = Clang->getTargetOpts();
941 TO.Triple = llvm::sys::getDefaultTargetTriple();
942 return TargetInfo::CreateTargetInfo(Diags, TO);
945 #endif
947 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
949 static void create_diagnostics(CompilerInstance *Clang)
951 Clang->createDiagnostics(0, NULL);
954 #else
956 static void create_diagnostics(CompilerInstance *Clang)
958 Clang->createDiagnostics();
961 #endif
963 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
965 static void create_preprocessor(CompilerInstance *Clang)
967 Clang->createPreprocessor(TU_Complete);
970 #else
972 static void create_preprocessor(CompilerInstance *Clang)
974 Clang->createPreprocessor();
977 #endif
979 #ifdef ADDPATH_TAKES_4_ARGUMENTS
981 void add_path(HeaderSearchOptions &HSO, string Path)
983 HSO.AddPath(Path, frontend::Angled, false, false);
986 #else
988 void add_path(HeaderSearchOptions &HSO, string Path)
990 HSO.AddPath(Path, frontend::Angled, true, false, false);
993 #endif
995 #ifdef HAVE_SETMAINFILEID
997 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
999 SM.setMainFileID(SM.createFileID(file, SourceLocation(),
1000 SrcMgr::C_User));
1003 #else
1005 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
1007 SM.createMainFileID(file);
1010 #endif
1012 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
1014 static void set_lang_defaults(CompilerInstance *Clang)
1016 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
1017 TargetOptions &TO = Clang->getTargetOpts();
1018 llvm::Triple T(TO.Triple);
1019 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C, T, PO,
1020 LangStandard::lang_unspecified);
1023 #else
1025 static void set_lang_defaults(CompilerInstance *Clang)
1027 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
1028 LangStandard::lang_unspecified);
1031 #endif
1033 #ifdef SETINVOCATION_TAKES_SHARED_PTR
1035 static void set_invocation(CompilerInstance *Clang,
1036 CompilerInvocation *invocation)
1038 Clang->setInvocation(std::shared_ptr<CompilerInvocation>(invocation));
1041 #else
1043 static void set_invocation(CompilerInstance *Clang,
1044 CompilerInvocation *invocation)
1046 Clang->setInvocation(invocation);
1049 #endif
1051 /* Helper function for ignore_error that only gets enabled if T
1052 * (which is either const FileEntry * or llvm::ErrorOr<const FileEntry *>)
1053 * has getError method, i.e., if it is llvm::ErrorOr<const FileEntry *>.
1055 template <class T>
1056 static const FileEntry *ignore_error_helper(const T obj, int,
1057 int[1][sizeof(obj.getError())])
1059 return *obj;
1062 /* Helper function for ignore_error that is always enabled,
1063 * but that only gets selected if the variant above is not enabled,
1064 * i.e., if T is const FileEntry *.
1066 template <class T>
1067 static const FileEntry *ignore_error_helper(const T obj, long, void *)
1069 return obj;
1072 /* Given either a const FileEntry * or a llvm::ErrorOr<const FileEntry *>,
1073 * extract out the const FileEntry *.
1075 template <class T>
1076 static const FileEntry *ignore_error(const T obj)
1078 return ignore_error_helper(obj, 0, NULL);
1081 /* Return the FileEntry corresponding to the given file name
1082 * in the given compiler instances, ignoring any error.
1084 static const FileEntry *getFile(CompilerInstance *Clang, std::string Filename)
1086 return ignore_error(Clang->getFileManager().getFile(Filename));
1089 /* Add pet specific predefines to the preprocessor.
1090 * Currently, these are all pencil specific, so they are only
1091 * added if "pencil" is set.
1093 * We mimic the way <command line> is handled inside clang.
1095 void add_predefines(Preprocessor &PP, int pencil)
1097 string s;
1099 if (!pencil)
1100 return;
1102 s = PP.getPredefines();
1103 s += "# 1 \"<pet>\" 1\n"
1104 "void __pencil_assume(int assumption);\n"
1105 "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n"
1106 "# 1 \"<built-in>\" 2\n";
1107 PP.setPredefines(s);
1110 /* Extract a pet_scop from each function in the C source file called "filename".
1111 * Each detected scop is passed to "fn".
1112 * If "function" is not NULL, only extract a pet_scop from the function
1113 * with that name.
1114 * If "autodetect" is set, extract any pet_scop we can find.
1115 * Otherwise, extract the pet_scop from the region delimited
1116 * by "scop" and "endscop" pragmas.
1118 * We first set up the clang parser and then try to extract the
1119 * pet_scop from the appropriate function(s) in PetASTConsumer.
1121 static isl_stat foreach_scop_in_C_source(isl_ctx *ctx,
1122 const char *filename, const char *function, pet_options *options,
1123 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user)
1125 CompilerInstance *Clang = new CompilerInstance();
1126 create_diagnostics(Clang);
1127 DiagnosticsEngine &Diags = Clang->getDiagnostics();
1128 Diags.setSuppressSystemWarnings(true);
1129 TargetInfo *target = create_target_info(Clang, Diags);
1130 Clang->setTarget(target);
1131 set_lang_defaults(Clang);
1132 CompilerInvocation *invocation = construct_invocation(filename, Diags);
1133 if (invocation)
1134 set_invocation(Clang, invocation);
1135 Diags.setClient(construct_printer(Clang, options->pencil));
1136 Clang->createFileManager();
1137 Clang->createSourceManager(Clang->getFileManager());
1138 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
1139 HSO.ResourceDir = ResourceDir;
1140 for (int i = 0; i < options->n_path; ++i)
1141 add_path(HSO, options->paths[i]);
1142 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
1143 for (int i = 0; i < options->n_define; ++i)
1144 PO.addMacroDef(options->defines[i]);
1145 create_preprocessor(Clang);
1146 Preprocessor &PP = Clang->getPreprocessor();
1147 add_predefines(PP, options->pencil);
1148 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
1149 PP.getLangOpts());
1151 ScopLocList scops;
1153 const FileEntry *file = getFile(Clang, filename);
1154 if (!file)
1155 isl_die(ctx, isl_error_unknown, "unable to open file",
1156 do { delete Clang; return isl_stat_error; } while (0));
1157 create_main_file_id(Clang->getSourceManager(), file);
1159 Clang->createASTContext();
1160 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(), Diags,
1161 scops, function, options, fn, user);
1162 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
1164 if (!options->autodetect) {
1165 PP.AddPragmaHandler(new PragmaScopHandler(scops));
1166 PP.AddPragmaHandler(new PragmaEndScopHandler(scops));
1167 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema,
1168 consumer.live_out));
1171 consumer.add_pragma_handlers(sema);
1173 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
1174 ParseAST(*sema);
1175 Diags.getClient()->EndSourceFile();
1177 delete sema;
1178 delete Clang;
1180 return consumer.error ? isl_stat_error : isl_stat_ok;
1183 /* Extract a pet_scop from each function in the C source file called "filename".
1184 * Each detected scop is passed to "fn".
1186 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1187 * that all objects on the stack (of that function) are destroyed before we
1188 * call llvm_shutdown.
1190 static isl_stat pet_foreach_scop_in_C_source(isl_ctx *ctx,
1191 const char *filename, const char *function,
1192 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user)
1194 isl_stat r;
1195 pet_options *options;
1196 bool allocated = false;
1198 options = isl_ctx_peek_pet_options(ctx);
1199 if (!options) {
1200 options = pet_options_new_with_defaults();
1201 allocated = true;
1204 r = foreach_scop_in_C_source(ctx, filename, function, options,
1205 fn, user);
1206 llvm::llvm_shutdown();
1208 if (allocated)
1209 pet_options_free(options);
1211 return r;
1214 /* Store "scop" into the address pointed to by "user".
1215 * Return -1 to indicate that we are not interested in any further scops.
1216 * This function should therefore not be called a second call
1217 * so in principle there is no need to check if we have already set *user.
1219 static isl_stat set_first_scop(pet_scop *scop, void *user)
1221 pet_scop **p = (pet_scop **) user;
1223 if (!*p)
1224 *p = scop;
1225 else
1226 pet_scop_free(scop);
1228 return isl_stat_error;
1231 /* Extract a pet_scop from the C source file called "filename".
1232 * If "function" is not NULL, extract the pet_scop from the function
1233 * with that name.
1235 * We start extracting scops from every function and then abort
1236 * as soon as we have extracted one scop.
1238 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
1239 const char *filename, const char *function)
1241 pet_scop *scop = NULL;
1243 pet_foreach_scop_in_C_source(ctx, filename, function,
1244 &set_first_scop, &scop);
1246 return scop;
1249 /* Internal data structure for pet_transform_C_source
1251 * transform is the function that should be called to print a scop
1252 * in is the input source file
1253 * out is the output source file
1254 * end is the offset of the end of the previous scop (zero if we have not
1255 * found any scop yet)
1256 * p is a printer that prints to out.
1258 struct pet_transform_data {
1259 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1260 struct pet_scop *scop, void *user);
1261 void *user;
1263 FILE *in;
1264 FILE *out;
1265 unsigned end;
1266 isl_printer *p;
1269 /* This function is called each time a scop is detected.
1271 * We first copy the input text code from the end of the previous scop
1272 * until the start of "scop" and then print the scop itself through
1273 * a call to data->transform. We set up the printer to print
1274 * the transformed code with the same (initial) indentation as
1275 * the original code.
1276 * Finally, we keep track of the end of "scop" so that we can
1277 * continue copying when we find the next scop.
1279 * Before calling data->transform, we store a pointer to the original
1280 * input file in the extended scop in case the user wants to call
1281 * pet_scop_print_original from the callback.
1283 static isl_stat pet_transform(struct pet_scop *scop, void *user)
1285 struct pet_transform_data *data = (struct pet_transform_data *) user;
1286 unsigned start;
1288 if (!scop)
1289 return isl_stat_error;
1290 start = pet_loc_get_start(scop->loc);
1291 if (copy(data->in, data->out, data->end, start) < 0)
1292 goto error;
1293 data->end = pet_loc_get_end(scop->loc);
1294 scop = pet_scop_set_input_file(scop, data->in);
1295 data->p = isl_printer_set_indent_prefix(data->p,
1296 pet_loc_get_indent(scop->loc));
1297 data->p = data->transform(data->p, scop, data->user);
1298 if (!data->p)
1299 return isl_stat_error;
1300 return isl_stat_ok;
1301 error:
1302 pet_scop_free(scop);
1303 return isl_stat_error;
1306 /* Transform the C source file "input" by rewriting each scop
1307 * through a call to "transform".
1308 * When autodetecting scops, at most one scop per function is rewritten.
1309 * The transformed C code is written to "output".
1311 * For each scop we find, we first copy the input text code
1312 * from the end of the previous scop (or the beginning of the file
1313 * in case of the first scop) until the start of the scop
1314 * and then print the scop itself through a call to "transform".
1315 * At the end we copy everything from the end of the final scop
1316 * until the end of the input file to "output".
1318 int pet_transform_C_source(isl_ctx *ctx, const char *input, FILE *out,
1319 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1320 struct pet_scop *scop, void *user), void *user)
1322 struct pet_transform_data data;
1323 int r;
1325 data.in = stdin;
1326 data.out = out;
1327 if (input && strcmp(input, "-")) {
1328 data.in = fopen(input, "r");
1329 if (!data.in)
1330 isl_die(ctx, isl_error_unknown, "unable to open file",
1331 return -1);
1334 data.p = isl_printer_to_file(ctx, data.out);
1335 data.p = isl_printer_set_output_format(data.p, ISL_FORMAT_C);
1337 data.transform = transform;
1338 data.user = user;
1339 data.end = 0;
1340 r = pet_foreach_scop_in_C_source(ctx, input, NULL,
1341 &pet_transform, &data);
1343 isl_printer_free(data.p);
1344 if (!data.p)
1345 r = -1;
1346 if (r == 0 && copy(data.in, data.out, data.end, -1) < 0)
1347 r = -1;
1349 if (data.in != stdin)
1350 fclose(data.in);
1352 return r;