handle rename of getLocStart to getBeginLoc and getLocEnd to getEndLoc
[pet.git] / pet.cc
blob5e2a0a72c53046473ca46e5b8850dc8a2798326c
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 #include <llvm/Support/raw_ostream.h>
47 #include <llvm/Support/ManagedStatic.h>
48 #include <llvm/Support/Host.h>
49 #include <clang/Basic/Version.h>
50 #include <clang/Basic/FileSystemOptions.h>
51 #include <clang/Basic/FileManager.h>
52 #include <clang/Basic/TargetOptions.h>
53 #include <clang/Basic/TargetInfo.h>
54 #include <clang/Driver/Compilation.h>
55 #include <clang/Driver/Driver.h>
56 #include <clang/Driver/Tool.h>
57 #include <clang/Frontend/CompilerInstance.h>
58 #include <clang/Frontend/CompilerInvocation.h>
59 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
60 #include <clang/Basic/DiagnosticOptions.h>
61 #else
62 #include <clang/Frontend/DiagnosticOptions.h>
63 #endif
64 #include <clang/Frontend/TextDiagnosticPrinter.h>
65 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
66 #include <clang/Lex/HeaderSearchOptions.h>
67 #else
68 #include <clang/Frontend/HeaderSearchOptions.h>
69 #endif
70 #include <clang/Frontend/LangStandard.h>
71 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
72 #include <clang/Lex/PreprocessorOptions.h>
73 #else
74 #include <clang/Frontend/PreprocessorOptions.h>
75 #endif
76 #include <clang/Frontend/FrontendOptions.h>
77 #include <clang/Frontend/Utils.h>
78 #include <clang/Lex/HeaderSearch.h>
79 #include <clang/Lex/Preprocessor.h>
80 #include <clang/Lex/Pragma.h>
81 #include <clang/AST/ASTContext.h>
82 #include <clang/AST/ASTConsumer.h>
83 #include <clang/Sema/Sema.h>
84 #include <clang/Sema/SemaDiagnostic.h>
85 #include <clang/Parse/Parser.h>
86 #include <clang/Parse/ParseAST.h>
88 #include <isl/ctx.h>
89 #include <isl/constraint.h>
91 #include <pet.h>
93 #include "clang_compatibility.h"
94 #include "id.h"
95 #include "options.h"
96 #include "scan.h"
97 #include "print.h"
99 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
101 using namespace std;
102 using namespace clang;
103 using namespace clang::driver;
105 #ifdef HAVE_ADT_OWNINGPTR_H
106 #define unique_ptr llvm::OwningPtr
107 #endif
109 /* Called if we found something we didn't expect in one of the pragmas.
110 * We'll provide more informative warnings later.
112 static void unsupported(Preprocessor &PP, SourceLocation loc)
114 DiagnosticsEngine &diag = PP.getDiagnostics();
115 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
116 "unsupported");
117 DiagnosticBuilder B = diag.Report(loc, id);
120 static int get_int(const char *s)
122 return s[0] == '"' ? atoi(s + 1) : atoi(s);
125 static ValueDecl *get_value_decl(Sema &sema, Token &token)
127 IdentifierInfo *name;
128 Decl *decl;
130 if (token.isNot(tok::identifier))
131 return NULL;
133 name = token.getIdentifierInfo();
134 decl = sema.LookupSingleName(sema.TUScope, name,
135 token.getLocation(), Sema::LookupOrdinaryName);
136 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
139 /* Handle pragmas of the form
141 * #pragma value_bounds identifier lower_bound upper_bound
143 * For each such pragma, add a mapping
144 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
145 * to value_bounds.
147 struct PragmaValueBoundsHandler : public PragmaHandler {
148 Sema &sema;
149 isl_ctx *ctx;
150 isl_union_map *value_bounds;
152 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema) :
153 PragmaHandler("value_bounds"), sema(sema), ctx(ctx) {
154 isl_space *space = isl_space_params_alloc(ctx, 0);
155 value_bounds = isl_union_map_empty(space);
158 ~PragmaValueBoundsHandler() {
159 isl_union_map_free(value_bounds);
162 virtual void HandlePragma(Preprocessor &PP,
163 PragmaIntroducerKind Introducer,
164 Token &ScopTok) {
165 isl_id *id;
166 isl_space *dim;
167 isl_map *map;
168 ValueDecl *vd;
169 Token token;
170 int lb;
171 int ub;
173 PP.Lex(token);
174 vd = get_value_decl(sema, token);
175 if (!vd) {
176 unsupported(PP, token.getLocation());
177 return;
180 PP.Lex(token);
181 if (!token.isLiteral()) {
182 unsupported(PP, token.getLocation());
183 return;
186 lb = get_int(token.getLiteralData());
188 PP.Lex(token);
189 if (!token.isLiteral()) {
190 unsupported(PP, token.getLocation());
191 return;
194 ub = get_int(token.getLiteralData());
196 dim = isl_space_alloc(ctx, 0, 0, 1);
197 map = isl_map_universe(dim);
198 map = isl_map_lower_bound_si(map, isl_dim_out, 0, lb);
199 map = isl_map_upper_bound_si(map, isl_dim_out, 0, ub);
200 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
201 map = isl_map_set_tuple_id(map, isl_dim_in, id);
203 value_bounds = isl_union_map_add_map(value_bounds, map);
207 /* Given a variable declaration, check if it has an integer initializer
208 * and if so, add a parameter corresponding to the variable to "value"
209 * with its value fixed to the integer initializer and return the result.
211 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
212 ValueDecl *decl)
214 VarDecl *vd;
215 Expr *expr;
216 IntegerLiteral *il;
217 isl_val *v;
218 isl_ctx *ctx;
219 isl_id *id;
220 isl_space *space;
221 isl_set *set;
223 vd = cast<VarDecl>(decl);
224 if (!vd)
225 return value;
226 if (!vd->getType()->isIntegerType())
227 return value;
228 expr = vd->getInit();
229 if (!expr)
230 return value;
231 il = cast<IntegerLiteral>(expr);
232 if (!il)
233 return value;
235 ctx = isl_set_get_ctx(value);
236 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
237 space = isl_space_params_alloc(ctx, 1);
238 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
239 set = isl_set_universe(space);
241 v = PetScan::extract_int(ctx, il);
242 set = isl_set_fix_val(set, isl_dim_param, 0, v);
244 return isl_set_intersect(value, set);
247 /* Handle pragmas of the form
249 * #pragma parameter identifier lower_bound
250 * and
251 * #pragma parameter identifier lower_bound upper_bound
253 * For each such pragma, intersect the context with the set
254 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
256 struct PragmaParameterHandler : public PragmaHandler {
257 Sema &sema;
258 isl_set *&context;
259 isl_set *&context_value;
261 PragmaParameterHandler(Sema &sema, isl_set *&context,
262 isl_set *&context_value) :
263 PragmaHandler("parameter"), sema(sema), context(context),
264 context_value(context_value) {}
266 virtual void HandlePragma(Preprocessor &PP,
267 PragmaIntroducerKind Introducer,
268 Token &ScopTok) {
269 isl_id *id;
270 isl_ctx *ctx = isl_set_get_ctx(context);
271 isl_space *dim;
272 isl_set *set;
273 ValueDecl *vd;
274 Token token;
275 int lb;
276 int ub;
277 bool has_ub = false;
279 PP.Lex(token);
280 vd = get_value_decl(sema, token);
281 if (!vd) {
282 unsupported(PP, token.getLocation());
283 return;
286 PP.Lex(token);
287 if (!token.isLiteral()) {
288 unsupported(PP, token.getLocation());
289 return;
292 lb = get_int(token.getLiteralData());
294 PP.Lex(token);
295 if (token.isLiteral()) {
296 has_ub = true;
297 ub = get_int(token.getLiteralData());
298 } else if (token.isNot(tok::eod)) {
299 unsupported(PP, token.getLocation());
300 return;
303 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
304 dim = isl_space_params_alloc(ctx, 1);
305 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
307 set = isl_set_universe(dim);
309 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
310 if (has_ub)
311 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
313 context = isl_set_intersect(context, set);
315 context_value = extract_initialization(context_value, vd);
319 /* Handle pragmas of the form
321 * #pragma pencil independent
323 * For each such pragma, add an entry to the "independent" vector.
325 struct PragmaPencilHandler : public PragmaHandler {
326 std::vector<Independent> &independent;
328 PragmaPencilHandler(std::vector<Independent> &independent) :
329 PragmaHandler("pencil"), independent(independent) {}
331 virtual void HandlePragma(Preprocessor &PP,
332 PragmaIntroducerKind Introducer,
333 Token &PencilTok) {
334 Token token;
335 IdentifierInfo *info;
337 PP.Lex(token);
338 if (token.isNot(tok::identifier))
339 return;
341 info = token.getIdentifierInfo();
342 if (!info->isStr("independent"))
343 return;
345 PP.Lex(token);
346 if (token.isNot(tok::eod))
347 return;
349 SourceManager &SM = PP.getSourceManager();
350 SourceLocation sloc = PencilTok.getLocation();
351 unsigned line = SM.getExpansionLineNumber(sloc);
352 independent.push_back(Independent(line));
356 #ifdef HAVE_TRANSLATELINECOL
358 /* Return a SourceLocation for line "line", column "col" of file "FID".
360 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
361 unsigned col)
363 return SM.translateLineCol(FID, line, col);
366 #else
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.getLocation(SM.getFileEntryForID(FID), line, col);
376 #endif
378 /* List of pairs of #pragma scop and #pragma endscop locations.
380 struct ScopLocList {
381 std::vector<ScopLoc> list;
383 /* Add a new start (#pragma scop) location to the list.
384 * If the last #pragma scop did not have a matching
385 * #pragma endscop then overwrite it.
386 * "start" points to the location of the scop pragma.
388 void add_start(SourceManager &SM, SourceLocation start) {
389 ScopLoc loc;
391 loc.scop = start;
392 int line = SM.getExpansionLineNumber(start);
393 start = translateLineCol(SM, SM.getFileID(start), line, 1);
394 loc.start_line = line;
395 loc.start = SM.getFileOffset(start);
396 if (list.size() == 0 || list[list.size() - 1].end != 0)
397 list.push_back(loc);
398 else
399 list[list.size() - 1] = loc;
402 /* Set the end location (#pragma endscop) of the last pair
403 * in the list.
404 * If there is no such pair of if the end of that pair
405 * is already set, then ignore the spurious #pragma endscop.
406 * "end" points to the location of the endscop pragma.
408 void add_end(SourceManager &SM, SourceLocation end) {
409 if (list.size() == 0 || list[list.size() - 1].end != 0)
410 return;
411 list[list.size() - 1].endscop = end;
412 int line = SM.getExpansionLineNumber(end);
413 end = translateLineCol(SM, SM.getFileID(end), line + 1, 1);
414 list[list.size() - 1].end = SM.getFileOffset(end);
418 /* Handle pragmas of the form
420 * #pragma scop
422 * In particular, store the location of the line containing
423 * the pragma in the list "scops".
425 struct PragmaScopHandler : public PragmaHandler {
426 ScopLocList &scops;
428 PragmaScopHandler(ScopLocList &scops) :
429 PragmaHandler("scop"), scops(scops) {}
431 virtual void HandlePragma(Preprocessor &PP,
432 PragmaIntroducerKind Introducer,
433 Token &ScopTok) {
434 SourceManager &SM = PP.getSourceManager();
435 SourceLocation sloc = ScopTok.getLocation();
436 scops.add_start(SM, sloc);
440 /* Handle pragmas of the form
442 * #pragma endscop
444 * In particular, store the location of the line following the one containing
445 * the pragma in the list "scops".
447 struct PragmaEndScopHandler : public PragmaHandler {
448 ScopLocList &scops;
450 PragmaEndScopHandler(ScopLocList &scops) :
451 PragmaHandler("endscop"), scops(scops) {}
453 virtual void HandlePragma(Preprocessor &PP,
454 PragmaIntroducerKind Introducer,
455 Token &EndScopTok) {
456 SourceManager &SM = PP.getSourceManager();
457 SourceLocation sloc = EndScopTok.getLocation();
458 scops.add_end(SM, sloc);
462 /* Handle pragmas of the form
464 * #pragma live-out identifier, identifier, ...
466 * Each identifier on the line is stored in live_out.
468 struct PragmaLiveOutHandler : public PragmaHandler {
469 Sema &sema;
470 set<ValueDecl *> &live_out;
472 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
473 PragmaHandler("live"), sema(sema), live_out(live_out) {}
475 virtual void HandlePragma(Preprocessor &PP,
476 PragmaIntroducerKind Introducer,
477 Token &ScopTok) {
478 Token token;
480 PP.Lex(token);
481 if (token.isNot(tok::minus))
482 return;
483 PP.Lex(token);
484 if (token.isNot(tok::identifier) ||
485 !token.getIdentifierInfo()->isStr("out"))
486 return;
488 PP.Lex(token);
489 while (token.isNot(tok::eod)) {
490 ValueDecl *vd;
492 vd = get_value_decl(sema, token);
493 if (!vd) {
494 unsupported(PP, token.getLocation());
495 return;
497 live_out.insert(vd);
498 PP.Lex(token);
499 if (token.is(tok::comma))
500 PP.Lex(token);
505 /* For each array in "scop", set its value_bounds property
506 * based on the information in "value_bounds" and
507 * mark it as live_out if it appears in "live_out".
509 static void update_arrays(struct pet_scop *scop,
510 __isl_take isl_union_map *value_bounds, set<ValueDecl *> &live_out)
512 set<ValueDecl *>::iterator lo_it;
513 isl_ctx *ctx = isl_union_map_get_ctx(value_bounds);
515 if (!scop) {
516 isl_union_map_free(value_bounds);
517 return;
520 for (int i = 0; i < scop->n_array; ++i) {
521 isl_id *id;
522 isl_space *space;
523 isl_map *bounds;
524 ValueDecl *decl;
525 pet_array *array = scop->arrays[i];
527 id = isl_set_get_tuple_id(array->extent);
528 decl = pet_id_get_decl(id);
530 space = isl_space_alloc(ctx, 0, 0, 1);
531 space = isl_space_set_tuple_id(space, isl_dim_in, id);
533 bounds = isl_union_map_extract_map(value_bounds, space);
534 if (!isl_map_plain_is_empty(bounds))
535 array->value_bounds = isl_map_range(bounds);
536 else
537 isl_map_free(bounds);
539 lo_it = live_out.find(decl);
540 if (lo_it != live_out.end())
541 array->live_out = 1;
544 isl_union_map_free(value_bounds);
547 /* Extract a pet_scop (if any) from each appropriate function.
548 * Each detected scop is passed to "fn".
549 * When autodetecting, at most one scop is extracted from each function.
550 * If "function" is not NULL, then we only extract a pet_scop if the
551 * name of the function matches.
552 * If "autodetect" is false, then we only extract if we have seen
553 * scop and endscop pragmas and if these are situated inside the function
554 * body.
556 struct PetASTConsumer : public ASTConsumer {
557 Preprocessor &PP;
558 ASTContext &ast_context;
559 DiagnosticsEngine &diags;
560 ScopLocList &scops;
561 std::vector<Independent> independent;
562 const char *function;
563 pet_options *options;
564 isl_ctx *ctx;
565 isl_set *context;
566 isl_set *context_value;
567 set<ValueDecl *> live_out;
568 PragmaValueBoundsHandler *vb_handler;
569 isl_stat (*fn)(struct pet_scop *scop, void *user);
570 void *user;
571 bool error;
573 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
574 DiagnosticsEngine &diags, ScopLocList &scops,
575 const char *function, pet_options *options,
576 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user) :
577 PP(PP), ast_context(ast_context), diags(diags),
578 scops(scops), function(function), options(options),
579 ctx(ctx),
580 vb_handler(NULL), fn(fn), user(user), error(false)
582 isl_space *space;
583 space = isl_space_params_alloc(ctx, 0);
584 context = isl_set_universe(isl_space_copy(space));
585 context_value = isl_set_universe(space);
588 ~PetASTConsumer() {
589 isl_set_free(context);
590 isl_set_free(context_value);
593 void handle_value_bounds(Sema *sema) {
594 vb_handler = new PragmaValueBoundsHandler(ctx, *sema);
595 PP.AddPragmaHandler(vb_handler);
598 /* Add all pragma handlers to this->PP.
599 * The pencil pragmas are only handled if the pencil option is set.
601 void add_pragma_handlers(Sema *sema) {
602 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
603 context_value));
604 if (options->pencil) {
605 PragmaHandler *PH;
606 PH = new PragmaPencilHandler(independent);
607 PP.AddPragmaHandler(PH);
609 handle_value_bounds(sema);
612 __isl_give isl_union_map *get_value_bounds() {
613 return isl_union_map_copy(vb_handler->value_bounds);
616 /* Pass "scop" to "fn" after performing some postprocessing.
617 * In particular, add the context and value_bounds constraints
618 * speficied through pragmas, add reference identifiers and
619 * reset user pointers on parameters and tuple ids.
621 * If "scop" does not contain any statements and autodetect
622 * is turned on, then skip it.
624 void call_fn(pet_scop *scop) {
625 if (!scop) {
626 error = true;
627 return;
629 if (diags.hasErrorOccurred()) {
630 error = true;
631 pet_scop_free(scop);
632 return;
634 if (options->autodetect && scop->n_stmt == 0) {
635 pet_scop_free(scop);
636 return;
638 scop->context = isl_set_intersect(scop->context,
639 isl_set_copy(context));
640 scop->context_value = isl_set_intersect(scop->context_value,
641 isl_set_copy(context_value));
643 update_arrays(scop, get_value_bounds(), live_out);
645 scop = pet_scop_add_ref_ids(scop);
646 scop = pet_scop_anonymize(scop);
648 if (fn(scop, user) < 0)
649 error = true;
652 /* For each explicitly marked scop (using pragmas),
653 * extract the scop and call "fn" on it if it is inside "fd".
655 void scan_scops(FunctionDecl *fd) {
656 unsigned start, end;
657 vector<ScopLoc>::iterator it;
658 isl_union_map *vb = vb_handler->value_bounds;
659 SourceManager &SM = PP.getSourceManager();
660 pet_scop *scop;
662 if (scops.list.size() == 0)
663 return;
665 start = SM.getFileOffset(begin_loc(fd));
666 end = SM.getFileOffset(end_loc(fd));
668 for (it = scops.list.begin(); it != scops.list.end(); ++it) {
669 ScopLoc loc = *it;
670 if (!loc.end)
671 continue;
672 if (start > loc.end)
673 continue;
674 if (end < loc.start)
675 continue;
676 PetScan ps(PP, ast_context, fd, loc, options,
677 isl_union_map_copy(vb), independent);
678 scop = ps.scan(fd);
679 call_fn(scop);
683 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef dg) {
684 DeclGroupRef::iterator it;
686 if (error)
687 return HandleTopLevelDeclContinue;
689 for (it = dg.begin(); it != dg.end(); ++it) {
690 isl_union_map *vb = vb_handler->value_bounds;
691 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
692 if (!fd)
693 continue;
694 if (!fd->hasBody())
695 continue;
696 if (function &&
697 fd->getNameInfo().getAsString() != function)
698 continue;
699 if (options->autodetect) {
700 ScopLoc loc;
701 pet_scop *scop;
702 PetScan ps(PP, ast_context, fd, loc, options,
703 isl_union_map_copy(vb),
704 independent);
705 scop = ps.scan(fd);
706 call_fn(scop);
707 continue;
709 scan_scops(fd);
712 return HandleTopLevelDeclContinue;
716 static const char *ResourceDir =
717 CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
719 static const char *implicit_functions[] = {
720 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
722 static const char *pencil_implicit_functions[] = {
723 "imin", "umin", "imax", "umax", "__pencil_kill"
726 /* Should "ident" be treated as an implicit function?
727 * If "pencil" is set, then also allow pencil specific builtins.
729 static bool is_implicit(const IdentifierInfo *ident, int pencil)
731 const char *name = ident->getNameStart();
732 for (size_t i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
733 if (!strcmp(name, implicit_functions[i]))
734 return true;
735 if (!pencil)
736 return false;
737 for (size_t i = 0; i < ARRAY_SIZE(pencil_implicit_functions); ++i)
738 if (!strcmp(name, pencil_implicit_functions[i]))
739 return true;
740 return false;
743 /* Ignore implicit function declaration warnings on
744 * "min", "max", "ceild" and "floord" as we detect and handle these
745 * in PetScan.
746 * If "pencil" is set, then also ignore them on pencil specific
747 * builtins.
749 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
750 const DiagnosticOptions *DiagOpts;
751 int pencil;
752 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
753 MyDiagnosticPrinter(DiagnosticOptions *DO, int pencil) :
754 TextDiagnosticPrinter(llvm::errs(), DO), pencil(pencil) {}
755 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
756 return new MyDiagnosticPrinter(&Diags.getDiagnosticOptions(),
757 pencil);
759 #else
760 MyDiagnosticPrinter(const DiagnosticOptions &DO, int pencil) :
761 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO),
762 pencil(pencil) {}
763 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
764 return new MyDiagnosticPrinter(*DiagOpts, pencil);
766 #endif
767 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
768 const DiagnosticInfo &info) {
769 if (info.getID() == diag::ext_implicit_function_decl &&
770 info.getNumArgs() >= 1 &&
771 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
772 is_implicit(info.getArgIdentifier(0), pencil))
773 /* ignore warning */;
774 else
775 TextDiagnosticPrinter::HandleDiagnostic(level, info);
779 #ifdef USE_ARRAYREF
781 #ifdef HAVE_CXXISPRODUCTION
782 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
784 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
785 "", false, false, Diags);
787 #elif defined(HAVE_ISPRODUCTION)
788 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
790 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
791 "", false, Diags);
793 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
794 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
796 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
797 "", Diags);
799 #else
800 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
802 return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
804 #endif
806 namespace clang { namespace driver { class Job; } }
808 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
809 * We fix this with a simple overloaded function here.
811 struct ClangAPI {
812 static Job *command(Job *J) { return J; }
813 static Job *command(Job &J) { return &J; }
814 static Command *command(Command &C) { return &C; }
817 /* Create a CompilerInvocation object that stores the command line
818 * arguments constructed by the driver.
819 * The arguments are mainly useful for setting up the system include
820 * paths on newer clangs and on some platforms.
822 static CompilerInvocation *construct_invocation(const char *filename,
823 DiagnosticsEngine &Diags)
825 const char *binary = CLANG_PREFIX"/bin/clang";
826 const unique_ptr<Driver> driver(construct_driver(binary, Diags));
827 std::vector<const char *> Argv;
828 Argv.push_back(binary);
829 Argv.push_back(filename);
830 const unique_ptr<Compilation> compilation(
831 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
832 JobList &Jobs = compilation->getJobs();
833 if (Jobs.size() < 1)
834 return NULL;
836 Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
837 if (strcmp(cmd->getCreator().getName(), "clang"))
838 return NULL;
840 const ArgStringList *args = &cmd->getArguments();
842 CompilerInvocation *invocation = new CompilerInvocation;
843 CompilerInvocation::CreateFromArgs(*invocation, args->data() + 1,
844 args->data() + args->size(),
845 Diags);
846 return invocation;
849 #else
851 static CompilerInvocation *construct_invocation(const char *filename,
852 DiagnosticsEngine &Diags)
854 return NULL;
857 #endif
859 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
861 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
862 int pencil)
864 return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil);
867 #else
869 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
870 int pencil)
872 return new MyDiagnosticPrinter(Clang->getDiagnosticOpts(), pencil);
875 #endif
877 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
879 static TargetInfo *create_target_info(CompilerInstance *Clang,
880 DiagnosticsEngine &Diags)
882 shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
883 TO->Triple = llvm::sys::getDefaultTargetTriple();
884 return TargetInfo::CreateTargetInfo(Diags, TO);
887 #elif defined(CREATETARGETINFO_TAKES_POINTER)
889 static TargetInfo *create_target_info(CompilerInstance *Clang,
890 DiagnosticsEngine &Diags)
892 TargetOptions &TO = Clang->getTargetOpts();
893 TO.Triple = llvm::sys::getDefaultTargetTriple();
894 return TargetInfo::CreateTargetInfo(Diags, &TO);
897 #else
899 static TargetInfo *create_target_info(CompilerInstance *Clang,
900 DiagnosticsEngine &Diags)
902 TargetOptions &TO = Clang->getTargetOpts();
903 TO.Triple = llvm::sys::getDefaultTargetTriple();
904 return TargetInfo::CreateTargetInfo(Diags, TO);
907 #endif
909 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
911 static void create_diagnostics(CompilerInstance *Clang)
913 Clang->createDiagnostics(0, NULL);
916 #else
918 static void create_diagnostics(CompilerInstance *Clang)
920 Clang->createDiagnostics();
923 #endif
925 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
927 static void create_preprocessor(CompilerInstance *Clang)
929 Clang->createPreprocessor(TU_Complete);
932 #else
934 static void create_preprocessor(CompilerInstance *Clang)
936 Clang->createPreprocessor();
939 #endif
941 #ifdef ADDPATH_TAKES_4_ARGUMENTS
943 void add_path(HeaderSearchOptions &HSO, string Path)
945 HSO.AddPath(Path, frontend::Angled, false, false);
948 #else
950 void add_path(HeaderSearchOptions &HSO, string Path)
952 HSO.AddPath(Path, frontend::Angled, true, false, false);
955 #endif
957 #ifdef HAVE_SETMAINFILEID
959 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
961 SM.setMainFileID(SM.createFileID(file, SourceLocation(),
962 SrcMgr::C_User));
965 #else
967 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
969 SM.createMainFileID(file);
972 #endif
974 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
976 static void set_lang_defaults(CompilerInstance *Clang)
978 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
979 TargetOptions &TO = Clang->getTargetOpts();
980 llvm::Triple T(TO.Triple);
981 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C, T, PO,
982 LangStandard::lang_unspecified);
985 #else
987 static void set_lang_defaults(CompilerInstance *Clang)
989 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
990 LangStandard::lang_unspecified);
993 #endif
995 #ifdef SETINVOCATION_TAKES_SHARED_PTR
997 static void set_invocation(CompilerInstance *Clang,
998 CompilerInvocation *invocation)
1000 Clang->setInvocation(std::shared_ptr<CompilerInvocation>(invocation));
1003 #else
1005 static void set_invocation(CompilerInstance *Clang,
1006 CompilerInvocation *invocation)
1008 Clang->setInvocation(invocation);
1011 #endif
1013 /* Add pet specific predefines to the preprocessor.
1014 * Currently, these are all pencil specific, so they are only
1015 * added if "pencil" is set.
1017 * We mimic the way <command line> is handled inside clang.
1019 void add_predefines(Preprocessor &PP, int pencil)
1021 string s;
1023 if (!pencil)
1024 return;
1026 s = PP.getPredefines();
1027 s += "# 1 \"<pet>\" 1\n"
1028 "void __pencil_assume(int assumption);\n"
1029 "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n"
1030 "# 1 \"<built-in>\" 2\n";
1031 PP.setPredefines(s);
1034 /* Extract a pet_scop from each function in the C source file called "filename".
1035 * Each detected scop is passed to "fn".
1036 * If "function" is not NULL, only extract a pet_scop from the function
1037 * with that name.
1038 * If "autodetect" is set, extract any pet_scop we can find.
1039 * Otherwise, extract the pet_scop from the region delimited
1040 * by "scop" and "endscop" pragmas.
1042 * We first set up the clang parser and then try to extract the
1043 * pet_scop from the appropriate function(s) in PetASTConsumer.
1045 static isl_stat foreach_scop_in_C_source(isl_ctx *ctx,
1046 const char *filename, const char *function, pet_options *options,
1047 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user)
1049 CompilerInstance *Clang = new CompilerInstance();
1050 create_diagnostics(Clang);
1051 DiagnosticsEngine &Diags = Clang->getDiagnostics();
1052 Diags.setSuppressSystemWarnings(true);
1053 CompilerInvocation *invocation = construct_invocation(filename, Diags);
1054 if (invocation)
1055 set_invocation(Clang, invocation);
1056 Diags.setClient(construct_printer(Clang, options->pencil));
1057 Clang->createFileManager();
1058 Clang->createSourceManager(Clang->getFileManager());
1059 TargetInfo *target = create_target_info(Clang, Diags);
1060 Clang->setTarget(target);
1061 set_lang_defaults(Clang);
1062 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
1063 HSO.ResourceDir = ResourceDir;
1064 for (int i = 0; i < options->n_path; ++i)
1065 add_path(HSO, options->paths[i]);
1066 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
1067 for (int i = 0; i < options->n_define; ++i)
1068 PO.addMacroDef(options->defines[i]);
1069 create_preprocessor(Clang);
1070 Preprocessor &PP = Clang->getPreprocessor();
1071 add_predefines(PP, options->pencil);
1072 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
1073 PP.getLangOpts());
1075 ScopLocList scops;
1077 const FileEntry *file = Clang->getFileManager().getFile(filename);
1078 if (!file)
1079 isl_die(ctx, isl_error_unknown, "unable to open file",
1080 do { delete Clang; return isl_stat_error; } while (0));
1081 create_main_file_id(Clang->getSourceManager(), file);
1083 Clang->createASTContext();
1084 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(), Diags,
1085 scops, function, options, fn, user);
1086 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
1088 if (!options->autodetect) {
1089 PP.AddPragmaHandler(new PragmaScopHandler(scops));
1090 PP.AddPragmaHandler(new PragmaEndScopHandler(scops));
1091 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema,
1092 consumer.live_out));
1095 consumer.add_pragma_handlers(sema);
1097 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
1098 ParseAST(*sema);
1099 Diags.getClient()->EndSourceFile();
1101 delete sema;
1102 delete Clang;
1104 return consumer.error ? isl_stat_error : isl_stat_ok;
1107 /* Extract a pet_scop from each function in the C source file called "filename".
1108 * Each detected scop is passed to "fn".
1110 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1111 * that all objects on the stack (of that function) are destroyed before we
1112 * call llvm_shutdown.
1114 static isl_stat pet_foreach_scop_in_C_source(isl_ctx *ctx,
1115 const char *filename, const char *function,
1116 isl_stat (*fn)(struct pet_scop *scop, void *user), void *user)
1118 isl_stat r;
1119 pet_options *options;
1120 bool allocated = false;
1122 options = isl_ctx_peek_pet_options(ctx);
1123 if (!options) {
1124 options = pet_options_new_with_defaults();
1125 allocated = true;
1128 r = foreach_scop_in_C_source(ctx, filename, function, options,
1129 fn, user);
1130 llvm::llvm_shutdown();
1132 if (allocated)
1133 pet_options_free(options);
1135 return r;
1138 /* Store "scop" into the address pointed to by "user".
1139 * Return -1 to indicate that we are not interested in any further scops.
1140 * This function should therefore not be called a second call
1141 * so in principle there is no need to check if we have already set *user.
1143 static isl_stat set_first_scop(pet_scop *scop, void *user)
1145 pet_scop **p = (pet_scop **) user;
1147 if (!*p)
1148 *p = scop;
1149 else
1150 pet_scop_free(scop);
1152 return isl_stat_error;
1155 /* Extract a pet_scop from the C source file called "filename".
1156 * If "function" is not NULL, extract the pet_scop from the function
1157 * with that name.
1159 * We start extracting scops from every function and then abort
1160 * as soon as we have extracted one scop.
1162 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
1163 const char *filename, const char *function)
1165 pet_scop *scop = NULL;
1167 pet_foreach_scop_in_C_source(ctx, filename, function,
1168 &set_first_scop, &scop);
1170 return scop;
1173 /* Internal data structure for pet_transform_C_source
1175 * transform is the function that should be called to print a scop
1176 * in is the input source file
1177 * out is the output source file
1178 * end is the offset of the end of the previous scop (zero if we have not
1179 * found any scop yet)
1180 * p is a printer that prints to out.
1182 struct pet_transform_data {
1183 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1184 struct pet_scop *scop, void *user);
1185 void *user;
1187 FILE *in;
1188 FILE *out;
1189 unsigned end;
1190 isl_printer *p;
1193 /* This function is called each time a scop is detected.
1195 * We first copy the input text code from the end of the previous scop
1196 * until the start of "scop" and then print the scop itself through
1197 * a call to data->transform. We set up the printer to print
1198 * the transformed code with the same (initial) indentation as
1199 * the original code.
1200 * Finally, we keep track of the end of "scop" so that we can
1201 * continue copying when we find the next scop.
1203 * Before calling data->transform, we store a pointer to the original
1204 * input file in the extended scop in case the user wants to call
1205 * pet_scop_print_original from the callback.
1207 static isl_stat pet_transform(struct pet_scop *scop, void *user)
1209 struct pet_transform_data *data = (struct pet_transform_data *) user;
1210 unsigned start;
1212 if (!scop)
1213 return isl_stat_error;
1214 start = pet_loc_get_start(scop->loc);
1215 if (copy(data->in, data->out, data->end, start) < 0)
1216 goto error;
1217 data->end = pet_loc_get_end(scop->loc);
1218 scop = pet_scop_set_input_file(scop, data->in);
1219 data->p = isl_printer_set_indent_prefix(data->p,
1220 pet_loc_get_indent(scop->loc));
1221 data->p = data->transform(data->p, scop, data->user);
1222 if (!data->p)
1223 return isl_stat_error;
1224 return isl_stat_ok;
1225 error:
1226 pet_scop_free(scop);
1227 return isl_stat_error;
1230 /* Transform the C source file "input" by rewriting each scop
1231 * through a call to "transform".
1232 * When autodetecting scops, at most one scop per function is rewritten.
1233 * The transformed C code is written to "output".
1235 * For each scop we find, we first copy the input text code
1236 * from the end of the previous scop (or the beginning of the file
1237 * in case of the first scop) until the start of the scop
1238 * and then print the scop itself through a call to "transform".
1239 * At the end we copy everything from the end of the final scop
1240 * until the end of the input file to "output".
1242 int pet_transform_C_source(isl_ctx *ctx, const char *input, FILE *out,
1243 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1244 struct pet_scop *scop, void *user), void *user)
1246 struct pet_transform_data data;
1247 int r;
1249 data.in = stdin;
1250 data.out = out;
1251 if (input && strcmp(input, "-")) {
1252 data.in = fopen(input, "r");
1253 if (!data.in)
1254 isl_die(ctx, isl_error_unknown, "unable to open file",
1255 return -1);
1258 data.p = isl_printer_to_file(ctx, data.out);
1259 data.p = isl_printer_set_output_format(data.p, ISL_FORMAT_C);
1261 data.transform = transform;
1262 data.user = user;
1263 data.end = 0;
1264 r = pet_foreach_scop_in_C_source(ctx, input, NULL,
1265 &pet_transform, &data);
1267 isl_printer_free(data.p);
1268 if (!data.p)
1269 r = -1;
1270 if (r == 0 && copy(data.in, data.out, data.end, -1) < 0)
1271 r = -1;
1273 if (data.in != stdin)
1274 fclose(data.in);
1276 return r;