m4/ax_detect_clang.m4: check presence of clang/Basic/LangStandard.h
[pet.git] / pet.cc
blob03e962338f266412e5862c0d44d4f1e9539f333e
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 #ifdef HAVE_ADT_OWNINGPTR_H
42 #include <llvm/ADT/OwningPtr.h>
43 #else
44 #include <memory>
45 #endif
46 #ifdef HAVE_LLVM_OPTION_ARG_H
47 #include <llvm/Option/Arg.h>
48 #endif
49 #include <llvm/Support/raw_ostream.h>
50 #include <llvm/Support/ManagedStatic.h>
51 #include <llvm/Support/Host.h>
52 #include <clang/Basic/Version.h>
53 #include <clang/Basic/FileSystemOptions.h>
54 #include <clang/Basic/FileManager.h>
55 #include <clang/Basic/TargetOptions.h>
56 #include <clang/Basic/TargetInfo.h>
57 #include <clang/Driver/Compilation.h>
58 #include <clang/Driver/Driver.h>
59 #include <clang/Driver/Tool.h>
60 #include <clang/Frontend/CompilerInstance.h>
61 #include <clang/Frontend/CompilerInvocation.h>
62 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
63 #include <clang/Basic/DiagnosticOptions.h>
64 #else
65 #include <clang/Frontend/DiagnosticOptions.h>
66 #endif
67 #include <clang/Frontend/TextDiagnosticPrinter.h>
68 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
69 #include <clang/Lex/HeaderSearchOptions.h>
70 #else
71 #include <clang/Frontend/HeaderSearchOptions.h>
72 #endif
73 #ifdef HAVE_CLANG_BASIC_LANGSTANDARD_H
74 #include <clang/Basic/LangStandard.h>
75 #else
76 #include <clang/Frontend/LangStandard.h>
77 #endif
78 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
79 #include <clang/Lex/PreprocessorOptions.h>
80 #else
81 #include <clang/Frontend/PreprocessorOptions.h>
82 #endif
83 #include <clang/Frontend/FrontendOptions.h>
84 #include <clang/Frontend/Utils.h>
85 #include <clang/Lex/HeaderSearch.h>
86 #include <clang/Lex/Preprocessor.h>
87 #include <clang/Lex/Pragma.h>
88 #include <clang/AST/ASTContext.h>
89 #include <clang/AST/ASTConsumer.h>
90 #include <clang/Sema/Sema.h>
91 #include <clang/Sema/SemaDiagnostic.h>
92 #include <clang/Parse/Parser.h>
93 #include <clang/Parse/ParseAST.h>
95 #include <isl/ctx.h>
96 #include <isl/constraint.h>
98 #include <pet.h>
100 #include "clang_compatibility.h"
101 #include "id.h"
102 #include "options.h"
103 #include "scan.h"
104 #include "print.h"
106 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
108 using namespace std;
109 using namespace clang;
110 using namespace clang::driver;
111 #ifdef HAVE_LLVM_OPTION_ARG_H
112 using namespace llvm::opt;
113 #endif
115 #ifdef HAVE_ADT_OWNINGPTR_H
116 #define unique_ptr llvm::OwningPtr
117 #endif
119 /* Called if we found something we didn't expect in one of the pragmas.
120 * We'll provide more informative warnings later.
122 static void unsupported(Preprocessor &PP, SourceLocation loc)
124 DiagnosticsEngine &diag = PP.getDiagnostics();
125 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
126 "unsupported");
127 DiagnosticBuilder B = diag.Report(loc, id);
130 static int get_int(const char *s)
132 return s[0] == '"' ? atoi(s + 1) : atoi(s);
135 static ValueDecl *get_value_decl(Sema &sema, Token &token)
137 IdentifierInfo *name;
138 Decl *decl;
140 if (token.isNot(tok::identifier))
141 return NULL;
143 name = token.getIdentifierInfo();
144 decl = sema.LookupSingleName(sema.TUScope, name,
145 token.getLocation(), Sema::LookupOrdinaryName);
146 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
149 /* Handle pragmas of the form
151 * #pragma value_bounds identifier lower_bound upper_bound
153 * For each such pragma, add a mapping
154 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
155 * to value_bounds.
157 struct PragmaValueBoundsHandler : public PragmaHandler {
158 Sema &sema;
159 isl_ctx *ctx;
160 isl_union_map *value_bounds;
162 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema) :
163 PragmaHandler("value_bounds"), sema(sema), ctx(ctx) {
164 isl_space *space = isl_space_params_alloc(ctx, 0);
165 value_bounds = isl_union_map_empty(space);
168 ~PragmaValueBoundsHandler() {
169 isl_union_map_free(value_bounds);
172 virtual void HandlePragma(Preprocessor &PP,
173 PragmaIntroducer Introducer,
174 Token &ScopTok) {
175 isl_id *id;
176 isl_space *dim;
177 isl_map *map;
178 ValueDecl *vd;
179 Token token;
180 int lb;
181 int ub;
183 PP.Lex(token);
184 vd = get_value_decl(sema, token);
185 if (!vd) {
186 unsupported(PP, token.getLocation());
187 return;
190 PP.Lex(token);
191 if (!token.isLiteral()) {
192 unsupported(PP, token.getLocation());
193 return;
196 lb = get_int(token.getLiteralData());
198 PP.Lex(token);
199 if (!token.isLiteral()) {
200 unsupported(PP, token.getLocation());
201 return;
204 ub = get_int(token.getLiteralData());
206 dim = isl_space_alloc(ctx, 0, 0, 1);
207 map = isl_map_universe(dim);
208 map = isl_map_lower_bound_si(map, isl_dim_out, 0, lb);
209 map = isl_map_upper_bound_si(map, isl_dim_out, 0, ub);
210 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
211 map = isl_map_set_tuple_id(map, isl_dim_in, id);
213 value_bounds = isl_union_map_add_map(value_bounds, map);
217 /* Given a variable declaration, check if it has an integer initializer
218 * and if so, add a parameter corresponding to the variable to "value"
219 * with its value fixed to the integer initializer and return the result.
221 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
222 ValueDecl *decl)
224 VarDecl *vd;
225 Expr *expr;
226 IntegerLiteral *il;
227 isl_val *v;
228 isl_ctx *ctx;
229 isl_id *id;
230 isl_space *space;
231 isl_set *set;
233 vd = cast<VarDecl>(decl);
234 if (!vd)
235 return value;
236 if (!vd->getType()->isIntegerType())
237 return value;
238 expr = vd->getInit();
239 if (!expr)
240 return value;
241 il = cast<IntegerLiteral>(expr);
242 if (!il)
243 return value;
245 ctx = isl_set_get_ctx(value);
246 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
247 space = isl_space_params_alloc(ctx, 1);
248 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
249 set = isl_set_universe(space);
251 v = PetScan::extract_int(ctx, il);
252 set = isl_set_fix_val(set, isl_dim_param, 0, v);
254 return isl_set_intersect(value, set);
257 /* Handle pragmas of the form
259 * #pragma parameter identifier lower_bound
260 * and
261 * #pragma parameter identifier lower_bound upper_bound
263 * For each such pragma, intersect the context with the set
264 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
266 struct PragmaParameterHandler : public PragmaHandler {
267 Sema &sema;
268 isl_set *&context;
269 isl_set *&context_value;
271 PragmaParameterHandler(Sema &sema, isl_set *&context,
272 isl_set *&context_value) :
273 PragmaHandler("parameter"), sema(sema), context(context),
274 context_value(context_value) {}
276 virtual void HandlePragma(Preprocessor &PP,
277 PragmaIntroducer Introducer,
278 Token &ScopTok) {
279 isl_id *id;
280 isl_ctx *ctx = isl_set_get_ctx(context);
281 isl_space *dim;
282 isl_set *set;
283 ValueDecl *vd;
284 Token token;
285 int lb;
286 int ub;
287 bool has_ub = false;
289 PP.Lex(token);
290 vd = get_value_decl(sema, token);
291 if (!vd) {
292 unsupported(PP, token.getLocation());
293 return;
296 PP.Lex(token);
297 if (!token.isLiteral()) {
298 unsupported(PP, token.getLocation());
299 return;
302 lb = get_int(token.getLiteralData());
304 PP.Lex(token);
305 if (token.isLiteral()) {
306 has_ub = true;
307 ub = get_int(token.getLiteralData());
308 } else if (token.isNot(tok::eod)) {
309 unsupported(PP, token.getLocation());
310 return;
313 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
314 dim = isl_space_params_alloc(ctx, 1);
315 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
317 set = isl_set_universe(dim);
319 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
320 if (has_ub)
321 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
323 context = isl_set_intersect(context, set);
325 context_value = extract_initialization(context_value, vd);
329 /* Handle pragmas of the form
331 * #pragma pencil independent
333 * For each such pragma, add an entry to the "independent" vector.
335 struct PragmaPencilHandler : public PragmaHandler {
336 std::vector<Independent> &independent;
338 PragmaPencilHandler(std::vector<Independent> &independent) :
339 PragmaHandler("pencil"), independent(independent) {}
341 virtual void HandlePragma(Preprocessor &PP,
342 PragmaIntroducer Introducer,
343 Token &PencilTok) {
344 Token token;
345 IdentifierInfo *info;
347 PP.Lex(token);
348 if (token.isNot(tok::identifier))
349 return;
351 info = token.getIdentifierInfo();
352 if (!info->isStr("independent"))
353 return;
355 PP.Lex(token);
356 if (token.isNot(tok::eod))
357 return;
359 SourceManager &SM = PP.getSourceManager();
360 SourceLocation sloc = PencilTok.getLocation();
361 unsigned line = SM.getExpansionLineNumber(sloc);
362 independent.push_back(Independent(line));
366 #ifdef HAVE_TRANSLATELINECOL
368 /* Return a SourceLocation for line "line", column "col" of file "FID".
370 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
371 unsigned col)
373 return SM.translateLineCol(FID, line, col);
376 #else
378 /* Return a SourceLocation for line "line", column "col" of file "FID".
380 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
381 unsigned col)
383 return SM.getLocation(SM.getFileEntryForID(FID), line, col);
386 #endif
388 /* List of pairs of #pragma scop and #pragma endscop locations.
390 struct ScopLocList {
391 std::vector<ScopLoc> list;
393 /* Add a new start (#pragma scop) location to the list.
394 * If the last #pragma scop did not have a matching
395 * #pragma endscop then overwrite it.
396 * "start" points to the location of the scop pragma.
398 void add_start(SourceManager &SM, SourceLocation start) {
399 ScopLoc loc;
401 loc.scop = start;
402 int line = SM.getExpansionLineNumber(start);
403 start = translateLineCol(SM, SM.getFileID(start), line, 1);
404 loc.start_line = line;
405 loc.start = SM.getFileOffset(start);
406 if (list.size() == 0 || list[list.size() - 1].end != 0)
407 list.push_back(loc);
408 else
409 list[list.size() - 1] = loc;
412 /* Set the end location (#pragma endscop) of the last pair
413 * in the list.
414 * If there is no such pair of if the end of that pair
415 * is already set, then ignore the spurious #pragma endscop.
416 * "end" points to the location of the endscop pragma.
418 void add_end(SourceManager &SM, SourceLocation end) {
419 if (list.size() == 0 || list[list.size() - 1].end != 0)
420 return;
421 list[list.size() - 1].endscop = end;
422 int line = SM.getExpansionLineNumber(end);
423 end = translateLineCol(SM, SM.getFileID(end), line + 1, 1);
424 list[list.size() - 1].end = SM.getFileOffset(end);
428 /* Handle pragmas of the form
430 * #pragma scop
432 * In particular, store the location of the line containing
433 * the pragma in the list "scops".
435 struct PragmaScopHandler : public PragmaHandler {
436 ScopLocList &scops;
438 PragmaScopHandler(ScopLocList &scops) :
439 PragmaHandler("scop"), scops(scops) {}
441 virtual void HandlePragma(Preprocessor &PP,
442 PragmaIntroducer Introducer,
443 Token &ScopTok) {
444 SourceManager &SM = PP.getSourceManager();
445 SourceLocation sloc = ScopTok.getLocation();
446 scops.add_start(SM, sloc);
450 /* Handle pragmas of the form
452 * #pragma endscop
454 * In particular, store the location of the line following the one containing
455 * the pragma in the list "scops".
457 struct PragmaEndScopHandler : public PragmaHandler {
458 ScopLocList &scops;
460 PragmaEndScopHandler(ScopLocList &scops) :
461 PragmaHandler("endscop"), scops(scops) {}
463 virtual void HandlePragma(Preprocessor &PP,
464 PragmaIntroducer Introducer,
465 Token &EndScopTok) {
466 SourceManager &SM = PP.getSourceManager();
467 SourceLocation sloc = EndScopTok.getLocation();
468 scops.add_end(SM, sloc);
472 /* Handle pragmas of the form
474 * #pragma live-out identifier, identifier, ...
476 * Each identifier on the line is stored in live_out.
478 struct PragmaLiveOutHandler : public PragmaHandler {
479 Sema &sema;
480 set<ValueDecl *> &live_out;
482 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
483 PragmaHandler("live"), sema(sema), live_out(live_out) {}
485 virtual void HandlePragma(Preprocessor &PP,
486 PragmaIntroducer Introducer,
487 Token &ScopTok) {
488 Token token;
490 PP.Lex(token);
491 if (token.isNot(tok::minus))
492 return;
493 PP.Lex(token);
494 if (token.isNot(tok::identifier) ||
495 !token.getIdentifierInfo()->isStr("out"))
496 return;
498 PP.Lex(token);
499 while (token.isNot(tok::eod)) {
500 ValueDecl *vd;
502 vd = get_value_decl(sema, token);
503 if (!vd) {
504 unsupported(PP, token.getLocation());
505 return;
507 live_out.insert(vd);
508 PP.Lex(token);
509 if (token.is(tok::comma))
510 PP.Lex(token);
515 /* For each array in "scop", set its value_bounds property
516 * based on the information in "value_bounds" and
517 * mark it as live_out if it appears in "live_out".
519 static void update_arrays(struct pet_scop *scop,
520 __isl_take isl_union_map *value_bounds, set<ValueDecl *> &live_out)
522 set<ValueDecl *>::iterator lo_it;
523 isl_ctx *ctx = isl_union_map_get_ctx(value_bounds);
525 if (!scop) {
526 isl_union_map_free(value_bounds);
527 return;
530 for (int i = 0; i < scop->n_array; ++i) {
531 isl_id *id;
532 isl_space *space;
533 isl_map *bounds;
534 ValueDecl *decl;
535 pet_array *array = scop->arrays[i];
537 id = isl_set_get_tuple_id(array->extent);
538 decl = pet_id_get_decl(id);
540 space = isl_space_alloc(ctx, 0, 0, 1);
541 space = isl_space_set_tuple_id(space, isl_dim_in, id);
543 bounds = isl_union_map_extract_map(value_bounds, space);
544 if (!isl_map_plain_is_empty(bounds))
545 array->value_bounds = isl_map_range(bounds);
546 else
547 isl_map_free(bounds);
549 lo_it = live_out.find(decl);
550 if (lo_it != live_out.end())
551 array->live_out = 1;
554 isl_union_map_free(value_bounds);
557 /* Extract a pet_scop (if any) from each appropriate function.
558 * Each detected scop is passed to "fn".
559 * When autodetecting, at most one scop is extracted from each function.
560 * If "function" is not NULL, then we only extract a pet_scop if the
561 * name of the function matches.
562 * If "autodetect" is false, then we only extract if we have seen
563 * scop and endscop pragmas and if these are situated inside the function
564 * body.
566 struct PetASTConsumer : public ASTConsumer {
567 Preprocessor &PP;
568 ASTContext &ast_context;
569 DiagnosticsEngine &diags;
570 ScopLocList &scops;
571 std::vector<Independent> independent;
572 const char *function;
573 pet_options *options;
574 isl_ctx *ctx;
575 isl_set *context;
576 isl_set *context_value;
577 set<ValueDecl *> live_out;
578 PragmaValueBoundsHandler *vb_handler;
579 isl_stat (*fn)(struct pet_scop *scop, void *user);
580 void *user;
581 bool error;
583 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
584 DiagnosticsEngine &diags, ScopLocList &scops,
585 const char *function, pet_options *options,
586 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user) :
587 PP(PP), ast_context(ast_context), diags(diags),
588 scops(scops), function(function), options(options),
589 ctx(ctx),
590 vb_handler(NULL), fn(fn), user(user), error(false)
592 isl_space *space;
593 space = isl_space_params_alloc(ctx, 0);
594 context = isl_set_universe(isl_space_copy(space));
595 context_value = isl_set_universe(space);
598 ~PetASTConsumer() {
599 isl_set_free(context);
600 isl_set_free(context_value);
603 void handle_value_bounds(Sema *sema) {
604 vb_handler = new PragmaValueBoundsHandler(ctx, *sema);
605 PP.AddPragmaHandler(vb_handler);
608 /* Add all pragma handlers to this->PP.
609 * The pencil pragmas are only handled if the pencil option is set.
611 void add_pragma_handlers(Sema *sema) {
612 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
613 context_value));
614 if (options->pencil) {
615 PragmaHandler *PH;
616 PH = new PragmaPencilHandler(independent);
617 PP.AddPragmaHandler(PH);
619 handle_value_bounds(sema);
622 __isl_give isl_union_map *get_value_bounds() {
623 return isl_union_map_copy(vb_handler->value_bounds);
626 /* Pass "scop" to "fn" after performing some postprocessing.
627 * In particular, add the context and value_bounds constraints
628 * speficied through pragmas, add reference identifiers and
629 * reset user pointers on parameters and tuple ids.
631 * If "scop" does not contain any statements and autodetect
632 * is turned on, then skip it.
634 void call_fn(pet_scop *scop) {
635 if (!scop) {
636 error = true;
637 return;
639 if (diags.hasErrorOccurred()) {
640 error = true;
641 pet_scop_free(scop);
642 return;
644 if (options->autodetect && scop->n_stmt == 0) {
645 pet_scop_free(scop);
646 return;
648 scop->context = isl_set_intersect(scop->context,
649 isl_set_copy(context));
650 scop->context_value = isl_set_intersect(scop->context_value,
651 isl_set_copy(context_value));
653 update_arrays(scop, get_value_bounds(), live_out);
655 scop = pet_scop_add_ref_ids(scop);
656 scop = pet_scop_anonymize(scop);
658 if (fn(scop, user) < 0)
659 error = true;
662 /* For each explicitly marked scop (using pragmas),
663 * extract the scop and call "fn" on it if it is inside "fd".
665 void scan_scops(FunctionDecl *fd) {
666 unsigned start, end;
667 vector<ScopLoc>::iterator it;
668 isl_union_map *vb = vb_handler->value_bounds;
669 SourceManager &SM = PP.getSourceManager();
670 pet_scop *scop;
672 if (scops.list.size() == 0)
673 return;
675 start = SM.getFileOffset(begin_loc(fd));
676 end = SM.getFileOffset(end_loc(fd));
678 for (it = scops.list.begin(); it != scops.list.end(); ++it) {
679 ScopLoc loc = *it;
680 if (!loc.end)
681 continue;
682 if (start > loc.end)
683 continue;
684 if (end < loc.start)
685 continue;
686 PetScan ps(PP, ast_context, fd, loc, options,
687 isl_union_map_copy(vb), independent);
688 scop = ps.scan(fd);
689 call_fn(scop);
693 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef dg) {
694 DeclGroupRef::iterator it;
696 if (error)
697 return HandleTopLevelDeclContinue;
699 for (it = dg.begin(); it != dg.end(); ++it) {
700 isl_union_map *vb = vb_handler->value_bounds;
701 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
702 if (!fd)
703 continue;
704 if (!fd->hasBody())
705 continue;
706 if (function &&
707 fd->getNameInfo().getAsString() != function)
708 continue;
709 if (options->autodetect) {
710 ScopLoc loc;
711 pet_scop *scop;
712 PetScan ps(PP, ast_context, fd, loc, options,
713 isl_union_map_copy(vb),
714 independent);
715 scop = ps.scan(fd);
716 if (!scop)
717 continue;
718 call_fn(scop);
719 continue;
721 scan_scops(fd);
724 return HandleTopLevelDeclContinue;
728 static const char *ResourceDir =
729 CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
731 static const char *implicit_functions[] = {
732 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
734 static const char *pencil_implicit_functions[] = {
735 "imin", "umin", "imax", "umax", "__pencil_kill"
738 /* Should "ident" be treated as an implicit function?
739 * If "pencil" is set, then also allow pencil specific builtins.
741 static bool is_implicit(const IdentifierInfo *ident, int pencil)
743 const char *name = ident->getNameStart();
744 for (size_t i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
745 if (!strcmp(name, implicit_functions[i]))
746 return true;
747 if (!pencil)
748 return false;
749 for (size_t i = 0; i < ARRAY_SIZE(pencil_implicit_functions); ++i)
750 if (!strcmp(name, pencil_implicit_functions[i]))
751 return true;
752 return false;
755 /* Ignore implicit function declaration warnings on
756 * "min", "max", "ceild" and "floord" as we detect and handle these
757 * in PetScan.
758 * If "pencil" is set, then also ignore them on pencil specific
759 * builtins.
761 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
762 const DiagnosticOptions *DiagOpts;
763 int pencil;
764 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
765 MyDiagnosticPrinter(DiagnosticOptions *DO, int pencil) :
766 TextDiagnosticPrinter(llvm::errs(), DO), pencil(pencil) {}
767 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
768 return new MyDiagnosticPrinter(&Diags.getDiagnosticOptions(),
769 pencil);
771 #else
772 MyDiagnosticPrinter(const DiagnosticOptions &DO, int pencil) :
773 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO),
774 pencil(pencil) {}
775 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
776 return new MyDiagnosticPrinter(*DiagOpts, pencil);
778 #endif
779 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
780 const DiagnosticInfo &info) {
781 if (info.getID() == diag::ext_implicit_function_decl &&
782 info.getNumArgs() >= 1 &&
783 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
784 is_implicit(info.getArgIdentifier(0), pencil))
785 /* ignore warning */;
786 else
787 TextDiagnosticPrinter::HandleDiagnostic(level, info);
791 #ifdef USE_ARRAYREF
793 #ifdef HAVE_CXXISPRODUCTION
794 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
796 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
797 "", false, false, Diags);
799 #elif defined(HAVE_ISPRODUCTION)
800 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
802 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
803 "", false, Diags);
805 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
806 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
808 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
809 "", Diags);
811 #else
812 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
814 return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
816 #endif
818 namespace clang { namespace driver { class Job; } }
820 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
821 * We fix this with a simple overloaded function here.
823 struct ClangAPI {
824 static Job *command(Job *J) { return J; }
825 static Job *command(Job &J) { return &J; }
826 static Command *command(Command &C) { return &C; }
829 /* Create a CompilerInvocation object that stores the command line
830 * arguments constructed by the driver.
831 * The arguments are mainly useful for setting up the system include
832 * paths on newer clangs and on some platforms.
834 static CompilerInvocation *construct_invocation(const char *filename,
835 DiagnosticsEngine &Diags)
837 const char *binary = CLANG_PREFIX"/bin/clang";
838 const unique_ptr<Driver> driver(construct_driver(binary, Diags));
839 std::vector<const char *> Argv;
840 Argv.push_back(binary);
841 Argv.push_back(filename);
842 const unique_ptr<Compilation> compilation(
843 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
844 JobList &Jobs = compilation->getJobs();
845 if (Jobs.size() < 1)
846 return NULL;
848 Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
849 if (strcmp(cmd->getCreator().getName(), "clang"))
850 return NULL;
852 const ArgStringList *args = &cmd->getArguments();
854 CompilerInvocation *invocation = new CompilerInvocation;
855 CompilerInvocation::CreateFromArgs(*invocation, args->data() + 1,
856 args->data() + args->size(),
857 Diags);
858 return invocation;
861 #else
863 static CompilerInvocation *construct_invocation(const char *filename,
864 DiagnosticsEngine &Diags)
866 return NULL;
869 #endif
871 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
873 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
874 int pencil)
876 return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil);
879 #else
881 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
882 int pencil)
884 return new MyDiagnosticPrinter(Clang->getDiagnosticOpts(), pencil);
887 #endif
889 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
891 static TargetInfo *create_target_info(CompilerInstance *Clang,
892 DiagnosticsEngine &Diags)
894 shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
895 TO->Triple = llvm::sys::getDefaultTargetTriple();
896 return TargetInfo::CreateTargetInfo(Diags, TO);
899 #elif defined(CREATETARGETINFO_TAKES_POINTER)
901 static TargetInfo *create_target_info(CompilerInstance *Clang,
902 DiagnosticsEngine &Diags)
904 TargetOptions &TO = Clang->getTargetOpts();
905 TO.Triple = llvm::sys::getDefaultTargetTriple();
906 return TargetInfo::CreateTargetInfo(Diags, &TO);
909 #else
911 static TargetInfo *create_target_info(CompilerInstance *Clang,
912 DiagnosticsEngine &Diags)
914 TargetOptions &TO = Clang->getTargetOpts();
915 TO.Triple = llvm::sys::getDefaultTargetTriple();
916 return TargetInfo::CreateTargetInfo(Diags, TO);
919 #endif
921 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
923 static void create_diagnostics(CompilerInstance *Clang)
925 Clang->createDiagnostics(0, NULL);
928 #else
930 static void create_diagnostics(CompilerInstance *Clang)
932 Clang->createDiagnostics();
935 #endif
937 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
939 static void create_preprocessor(CompilerInstance *Clang)
941 Clang->createPreprocessor(TU_Complete);
944 #else
946 static void create_preprocessor(CompilerInstance *Clang)
948 Clang->createPreprocessor();
951 #endif
953 #ifdef ADDPATH_TAKES_4_ARGUMENTS
955 void add_path(HeaderSearchOptions &HSO, string Path)
957 HSO.AddPath(Path, frontend::Angled, false, false);
960 #else
962 void add_path(HeaderSearchOptions &HSO, string Path)
964 HSO.AddPath(Path, frontend::Angled, true, false, false);
967 #endif
969 #ifdef HAVE_SETMAINFILEID
971 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
973 SM.setMainFileID(SM.createFileID(file, SourceLocation(),
974 SrcMgr::C_User));
977 #else
979 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
981 SM.createMainFileID(file);
984 #endif
986 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
988 static void set_lang_defaults(CompilerInstance *Clang)
990 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
991 TargetOptions &TO = Clang->getTargetOpts();
992 llvm::Triple T(TO.Triple);
993 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C, T, PO,
994 LangStandard::lang_unspecified);
997 #else
999 static void set_lang_defaults(CompilerInstance *Clang)
1001 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
1002 LangStandard::lang_unspecified);
1005 #endif
1007 #ifdef SETINVOCATION_TAKES_SHARED_PTR
1009 static void set_invocation(CompilerInstance *Clang,
1010 CompilerInvocation *invocation)
1012 Clang->setInvocation(std::shared_ptr<CompilerInvocation>(invocation));
1015 #else
1017 static void set_invocation(CompilerInstance *Clang,
1018 CompilerInvocation *invocation)
1020 Clang->setInvocation(invocation);
1023 #endif
1025 /* Add pet specific predefines to the preprocessor.
1026 * Currently, these are all pencil specific, so they are only
1027 * added if "pencil" is set.
1029 * We mimic the way <command line> is handled inside clang.
1031 void add_predefines(Preprocessor &PP, int pencil)
1033 string s;
1035 if (!pencil)
1036 return;
1038 s = PP.getPredefines();
1039 s += "# 1 \"<pet>\" 1\n"
1040 "void __pencil_assume(int assumption);\n"
1041 "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n"
1042 "# 1 \"<built-in>\" 2\n";
1043 PP.setPredefines(s);
1046 /* Extract a pet_scop from each function in the C source file called "filename".
1047 * Each detected scop is passed to "fn".
1048 * If "function" is not NULL, only extract a pet_scop from the function
1049 * with that name.
1050 * If "autodetect" is set, extract any pet_scop we can find.
1051 * Otherwise, extract the pet_scop from the region delimited
1052 * by "scop" and "endscop" pragmas.
1054 * We first set up the clang parser and then try to extract the
1055 * pet_scop from the appropriate function(s) in PetASTConsumer.
1057 static isl_stat foreach_scop_in_C_source(isl_ctx *ctx,
1058 const char *filename, const char *function, pet_options *options,
1059 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user)
1061 CompilerInstance *Clang = new CompilerInstance();
1062 create_diagnostics(Clang);
1063 DiagnosticsEngine &Diags = Clang->getDiagnostics();
1064 Diags.setSuppressSystemWarnings(true);
1065 CompilerInvocation *invocation = construct_invocation(filename, Diags);
1066 if (invocation)
1067 set_invocation(Clang, invocation);
1068 Diags.setClient(construct_printer(Clang, options->pencil));
1069 Clang->createFileManager();
1070 Clang->createSourceManager(Clang->getFileManager());
1071 TargetInfo *target = create_target_info(Clang, Diags);
1072 Clang->setTarget(target);
1073 set_lang_defaults(Clang);
1074 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
1075 HSO.ResourceDir = ResourceDir;
1076 for (int i = 0; i < options->n_path; ++i)
1077 add_path(HSO, options->paths[i]);
1078 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
1079 for (int i = 0; i < options->n_define; ++i)
1080 PO.addMacroDef(options->defines[i]);
1081 create_preprocessor(Clang);
1082 Preprocessor &PP = Clang->getPreprocessor();
1083 add_predefines(PP, options->pencil);
1084 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
1085 PP.getLangOpts());
1087 ScopLocList scops;
1089 const FileEntry *file = Clang->getFileManager().getFile(filename);
1090 if (!file)
1091 isl_die(ctx, isl_error_unknown, "unable to open file",
1092 do { delete Clang; return isl_stat_error; } while (0));
1093 create_main_file_id(Clang->getSourceManager(), file);
1095 Clang->createASTContext();
1096 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(), Diags,
1097 scops, function, options, fn, user);
1098 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
1100 if (!options->autodetect) {
1101 PP.AddPragmaHandler(new PragmaScopHandler(scops));
1102 PP.AddPragmaHandler(new PragmaEndScopHandler(scops));
1103 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema,
1104 consumer.live_out));
1107 consumer.add_pragma_handlers(sema);
1109 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
1110 ParseAST(*sema);
1111 Diags.getClient()->EndSourceFile();
1113 delete sema;
1114 delete Clang;
1116 return consumer.error ? isl_stat_error : isl_stat_ok;
1119 /* Extract a pet_scop from each function in the C source file called "filename".
1120 * Each detected scop is passed to "fn".
1122 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1123 * that all objects on the stack (of that function) are destroyed before we
1124 * call llvm_shutdown.
1126 static isl_stat pet_foreach_scop_in_C_source(isl_ctx *ctx,
1127 const char *filename, const char *function,
1128 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user)
1130 isl_stat r;
1131 pet_options *options;
1132 bool allocated = false;
1134 options = isl_ctx_peek_pet_options(ctx);
1135 if (!options) {
1136 options = pet_options_new_with_defaults();
1137 allocated = true;
1140 r = foreach_scop_in_C_source(ctx, filename, function, options,
1141 fn, user);
1142 llvm::llvm_shutdown();
1144 if (allocated)
1145 pet_options_free(options);
1147 return r;
1150 /* Store "scop" into the address pointed to by "user".
1151 * Return -1 to indicate that we are not interested in any further scops.
1152 * This function should therefore not be called a second call
1153 * so in principle there is no need to check if we have already set *user.
1155 static isl_stat set_first_scop(pet_scop *scop, void *user)
1157 pet_scop **p = (pet_scop **) user;
1159 if (!*p)
1160 *p = scop;
1161 else
1162 pet_scop_free(scop);
1164 return isl_stat_error;
1167 /* Extract a pet_scop from the C source file called "filename".
1168 * If "function" is not NULL, extract the pet_scop from the function
1169 * with that name.
1171 * We start extracting scops from every function and then abort
1172 * as soon as we have extracted one scop.
1174 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
1175 const char *filename, const char *function)
1177 pet_scop *scop = NULL;
1179 pet_foreach_scop_in_C_source(ctx, filename, function,
1180 &set_first_scop, &scop);
1182 return scop;
1185 /* Internal data structure for pet_transform_C_source
1187 * transform is the function that should be called to print a scop
1188 * in is the input source file
1189 * out is the output source file
1190 * end is the offset of the end of the previous scop (zero if we have not
1191 * found any scop yet)
1192 * p is a printer that prints to out.
1194 struct pet_transform_data {
1195 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1196 struct pet_scop *scop, void *user);
1197 void *user;
1199 FILE *in;
1200 FILE *out;
1201 unsigned end;
1202 isl_printer *p;
1205 /* This function is called each time a scop is detected.
1207 * We first copy the input text code from the end of the previous scop
1208 * until the start of "scop" and then print the scop itself through
1209 * a call to data->transform. We set up the printer to print
1210 * the transformed code with the same (initial) indentation as
1211 * the original code.
1212 * Finally, we keep track of the end of "scop" so that we can
1213 * continue copying when we find the next scop.
1215 * Before calling data->transform, we store a pointer to the original
1216 * input file in the extended scop in case the user wants to call
1217 * pet_scop_print_original from the callback.
1219 static isl_stat pet_transform(struct pet_scop *scop, void *user)
1221 struct pet_transform_data *data = (struct pet_transform_data *) user;
1222 unsigned start;
1224 if (!scop)
1225 return isl_stat_error;
1226 start = pet_loc_get_start(scop->loc);
1227 if (copy(data->in, data->out, data->end, start) < 0)
1228 goto error;
1229 data->end = pet_loc_get_end(scop->loc);
1230 scop = pet_scop_set_input_file(scop, data->in);
1231 data->p = isl_printer_set_indent_prefix(data->p,
1232 pet_loc_get_indent(scop->loc));
1233 data->p = data->transform(data->p, scop, data->user);
1234 if (!data->p)
1235 return isl_stat_error;
1236 return isl_stat_ok;
1237 error:
1238 pet_scop_free(scop);
1239 return isl_stat_error;
1242 /* Transform the C source file "input" by rewriting each scop
1243 * through a call to "transform".
1244 * When autodetecting scops, at most one scop per function is rewritten.
1245 * The transformed C code is written to "output".
1247 * For each scop we find, we first copy the input text code
1248 * from the end of the previous scop (or the beginning of the file
1249 * in case of the first scop) until the start of the scop
1250 * and then print the scop itself through a call to "transform".
1251 * At the end we copy everything from the end of the final scop
1252 * until the end of the input file to "output".
1254 int pet_transform_C_source(isl_ctx *ctx, const char *input, FILE *out,
1255 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1256 struct pet_scop *scop, void *user), void *user)
1258 struct pet_transform_data data;
1259 int r;
1261 data.in = stdin;
1262 data.out = out;
1263 if (input && strcmp(input, "-")) {
1264 data.in = fopen(input, "r");
1265 if (!data.in)
1266 isl_die(ctx, isl_error_unknown, "unable to open file",
1267 return -1);
1270 data.p = isl_printer_to_file(ctx, data.out);
1271 data.p = isl_printer_set_output_format(data.p, ISL_FORMAT_C);
1273 data.transform = transform;
1274 data.user = user;
1275 data.end = 0;
1276 r = pet_foreach_scop_in_C_source(ctx, input, NULL,
1277 &pet_transform, &data);
1279 isl_printer_free(data.p);
1280 if (!data.p)
1281 r = -1;
1282 if (r == 0 && copy(data.in, data.out, data.end, -1) < 0)
1283 r = -1;
1285 if (data.in != stdin)
1286 fclose(data.in);
1288 return r;