PetScan::extract_argument: extract out extract_addr_of_arg
[pet.git] / pet.cc
bloba76853f7e08b11c2d90f6a82d877e5b943c26e39
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 "id.h"
94 #include "options.h"
95 #include "scan.h"
96 #include "print.h"
98 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
100 using namespace std;
101 using namespace clang;
102 using namespace clang::driver;
104 #ifdef HAVE_ADT_OWNINGPTR_H
105 #define unique_ptr llvm::OwningPtr
106 #endif
108 /* Called if we found something we didn't expect in one of the pragmas.
109 * We'll provide more informative warnings later.
111 static void unsupported(Preprocessor &PP, SourceLocation loc)
113 DiagnosticsEngine &diag = PP.getDiagnostics();
114 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
115 "unsupported");
116 DiagnosticBuilder B = diag.Report(loc, id);
119 static int get_int(const char *s)
121 return s[0] == '"' ? atoi(s + 1) : atoi(s);
124 static ValueDecl *get_value_decl(Sema &sema, Token &token)
126 IdentifierInfo *name;
127 Decl *decl;
129 if (token.isNot(tok::identifier))
130 return NULL;
132 name = token.getIdentifierInfo();
133 decl = sema.LookupSingleName(sema.TUScope, name,
134 token.getLocation(), Sema::LookupOrdinaryName);
135 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
138 /* Handle pragmas of the form
140 * #pragma value_bounds identifier lower_bound upper_bound
142 * For each such pragma, add a mapping
143 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
144 * to value_bounds.
146 struct PragmaValueBoundsHandler : public PragmaHandler {
147 Sema &sema;
148 isl_ctx *ctx;
149 isl_union_map *value_bounds;
151 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema) :
152 PragmaHandler("value_bounds"), ctx(ctx), sema(sema) {
153 isl_space *space = isl_space_params_alloc(ctx, 0);
154 value_bounds = isl_union_map_empty(space);
157 ~PragmaValueBoundsHandler() {
158 isl_union_map_free(value_bounds);
161 virtual void HandlePragma(Preprocessor &PP,
162 PragmaIntroducerKind Introducer,
163 Token &ScopTok) {
164 isl_id *id;
165 isl_space *dim;
166 isl_map *map;
167 ValueDecl *vd;
168 Token token;
169 int lb;
170 int ub;
172 PP.Lex(token);
173 vd = get_value_decl(sema, token);
174 if (!vd) {
175 unsupported(PP, token.getLocation());
176 return;
179 PP.Lex(token);
180 if (!token.isLiteral()) {
181 unsupported(PP, token.getLocation());
182 return;
185 lb = get_int(token.getLiteralData());
187 PP.Lex(token);
188 if (!token.isLiteral()) {
189 unsupported(PP, token.getLocation());
190 return;
193 ub = get_int(token.getLiteralData());
195 dim = isl_space_alloc(ctx, 0, 0, 1);
196 map = isl_map_universe(dim);
197 map = isl_map_lower_bound_si(map, isl_dim_out, 0, lb);
198 map = isl_map_upper_bound_si(map, isl_dim_out, 0, ub);
199 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
200 map = isl_map_set_tuple_id(map, isl_dim_in, id);
202 value_bounds = isl_union_map_add_map(value_bounds, map);
206 /* Given a variable declaration, check if it has an integer initializer
207 * and if so, add a parameter corresponding to the variable to "value"
208 * with its value fixed to the integer initializer and return the result.
210 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
211 ValueDecl *decl)
213 VarDecl *vd;
214 Expr *expr;
215 IntegerLiteral *il;
216 isl_val *v;
217 isl_ctx *ctx;
218 isl_id *id;
219 isl_space *space;
220 isl_set *set;
222 vd = cast<VarDecl>(decl);
223 if (!vd)
224 return value;
225 if (!vd->getType()->isIntegerType())
226 return value;
227 expr = vd->getInit();
228 if (!expr)
229 return value;
230 il = cast<IntegerLiteral>(expr);
231 if (!il)
232 return value;
234 ctx = isl_set_get_ctx(value);
235 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
236 space = isl_space_params_alloc(ctx, 1);
237 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
238 set = isl_set_universe(space);
240 v = PetScan::extract_int(ctx, il);
241 set = isl_set_fix_val(set, isl_dim_param, 0, v);
243 return isl_set_intersect(value, set);
246 /* Handle pragmas of the form
248 * #pragma parameter identifier lower_bound
249 * and
250 * #pragma parameter identifier lower_bound upper_bound
252 * For each such pragma, intersect the context with the set
253 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
255 struct PragmaParameterHandler : public PragmaHandler {
256 Sema &sema;
257 isl_set *&context;
258 isl_set *&context_value;
260 PragmaParameterHandler(Sema &sema, isl_set *&context,
261 isl_set *&context_value) :
262 PragmaHandler("parameter"), sema(sema), context(context),
263 context_value(context_value) {}
265 virtual void HandlePragma(Preprocessor &PP,
266 PragmaIntroducerKind Introducer,
267 Token &ScopTok) {
268 isl_id *id;
269 isl_ctx *ctx = isl_set_get_ctx(context);
270 isl_space *dim;
271 isl_set *set;
272 ValueDecl *vd;
273 Token token;
274 int lb;
275 int ub;
276 bool has_ub = false;
278 PP.Lex(token);
279 vd = get_value_decl(sema, token);
280 if (!vd) {
281 unsupported(PP, token.getLocation());
282 return;
285 PP.Lex(token);
286 if (!token.isLiteral()) {
287 unsupported(PP, token.getLocation());
288 return;
291 lb = get_int(token.getLiteralData());
293 PP.Lex(token);
294 if (token.isLiteral()) {
295 has_ub = true;
296 ub = get_int(token.getLiteralData());
297 } else if (token.isNot(tok::eod)) {
298 unsupported(PP, token.getLocation());
299 return;
302 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
303 dim = isl_space_params_alloc(ctx, 1);
304 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
306 set = isl_set_universe(dim);
308 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
309 if (has_ub)
310 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
312 context = isl_set_intersect(context, set);
314 context_value = extract_initialization(context_value, vd);
318 /* Handle pragmas of the form
320 * #pragma pencil independent
322 * For each such pragma, add an entry to the "independent" vector.
324 struct PragmaPencilHandler : public PragmaHandler {
325 std::vector<Independent> &independent;
327 PragmaPencilHandler(std::vector<Independent> &independent) :
328 PragmaHandler("pencil"), independent(independent) {}
330 virtual void HandlePragma(Preprocessor &PP,
331 PragmaIntroducerKind Introducer,
332 Token &PencilTok) {
333 Token token;
334 IdentifierInfo *info;
336 PP.Lex(token);
337 if (token.isNot(tok::identifier))
338 return;
340 info = token.getIdentifierInfo();
341 if (!info->isStr("independent"))
342 return;
344 PP.Lex(token);
345 if (token.isNot(tok::eod))
346 return;
348 SourceManager &SM = PP.getSourceManager();
349 SourceLocation sloc = PencilTok.getLocation();
350 unsigned line = SM.getExpansionLineNumber(sloc);
351 independent.push_back(Independent(line));
355 #ifdef HAVE_TRANSLATELINECOL
357 /* Return a SourceLocation for line "line", column "col" of file "FID".
359 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
360 unsigned col)
362 return SM.translateLineCol(FID, line, col);
365 #else
367 /* Return a SourceLocation for line "line", column "col" of file "FID".
369 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
370 unsigned col)
372 return SM.getLocation(SM.getFileEntryForID(FID), line, col);
375 #endif
377 /* List of pairs of #pragma scop and #pragma endscop locations.
379 struct ScopLocList {
380 std::vector<ScopLoc> list;
382 /* Add a new start (#pragma scop) location to the list.
383 * If the last #pragma scop did not have a matching
384 * #pragma endscop then overwrite it.
386 void add_start(unsigned line, unsigned start) {
387 ScopLoc loc;
389 loc.start_line = line;
390 loc.start = start;
391 if (list.size() == 0 || list[list.size() - 1].end != 0)
392 list.push_back(loc);
393 else
394 list[list.size() - 1] = loc;
397 /* Set the end location (#pragma endscop) of the last pair
398 * in the list.
399 * If there is no such pair of if the end of that pair
400 * is already set, then ignore the spurious #pragma endscop.
402 void add_end(unsigned end) {
403 if (list.size() == 0 || list[list.size() - 1].end != 0)
404 return;
405 list[list.size() - 1].end = end;
409 /* Handle pragmas of the form
411 * #pragma scop
413 * In particular, store the location of the line containing
414 * the pragma in the list "scops".
416 struct PragmaScopHandler : public PragmaHandler {
417 ScopLocList &scops;
419 PragmaScopHandler(ScopLocList &scops) :
420 PragmaHandler("scop"), scops(scops) {}
422 virtual void HandlePragma(Preprocessor &PP,
423 PragmaIntroducerKind Introducer,
424 Token &ScopTok) {
425 SourceManager &SM = PP.getSourceManager();
426 SourceLocation sloc = ScopTok.getLocation();
427 int line = SM.getExpansionLineNumber(sloc);
428 sloc = translateLineCol(SM, SM.getFileID(sloc), line, 1);
429 scops.add_start(line, SM.getFileOffset(sloc));
433 /* Handle pragmas of the form
435 * #pragma endscop
437 * In particular, store the location of the line following the one containing
438 * the pragma in the list "scops".
440 struct PragmaEndScopHandler : public PragmaHandler {
441 ScopLocList &scops;
443 PragmaEndScopHandler(ScopLocList &scops) :
444 PragmaHandler("endscop"), scops(scops) {}
446 virtual void HandlePragma(Preprocessor &PP,
447 PragmaIntroducerKind Introducer,
448 Token &EndScopTok) {
449 SourceManager &SM = PP.getSourceManager();
450 SourceLocation sloc = EndScopTok.getLocation();
451 int line = SM.getExpansionLineNumber(sloc);
452 sloc = translateLineCol(SM, SM.getFileID(sloc), line + 1, 1);
453 scops.add_end(SM.getFileOffset(sloc));
457 /* Handle pragmas of the form
459 * #pragma live-out identifier, identifier, ...
461 * Each identifier on the line is stored in live_out.
463 struct PragmaLiveOutHandler : public PragmaHandler {
464 Sema &sema;
465 set<ValueDecl *> &live_out;
467 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
468 PragmaHandler("live"), sema(sema), live_out(live_out) {}
470 virtual void HandlePragma(Preprocessor &PP,
471 PragmaIntroducerKind Introducer,
472 Token &ScopTok) {
473 Token token;
475 PP.Lex(token);
476 if (token.isNot(tok::minus))
477 return;
478 PP.Lex(token);
479 if (token.isNot(tok::identifier) ||
480 !token.getIdentifierInfo()->isStr("out"))
481 return;
483 PP.Lex(token);
484 while (token.isNot(tok::eod)) {
485 ValueDecl *vd;
487 vd = get_value_decl(sema, token);
488 if (!vd) {
489 unsupported(PP, token.getLocation());
490 return;
492 live_out.insert(vd);
493 PP.Lex(token);
494 if (token.is(tok::comma))
495 PP.Lex(token);
500 /* For each array in "scop", set its value_bounds property
501 * based on the information in "value_bounds" and
502 * mark it as live_out if it appears in "live_out".
504 static void update_arrays(struct pet_scop *scop,
505 __isl_take isl_union_map *value_bounds, set<ValueDecl *> &live_out)
507 set<ValueDecl *>::iterator lo_it;
508 isl_ctx *ctx = isl_union_map_get_ctx(value_bounds);
510 if (!scop) {
511 isl_union_map_free(value_bounds);
512 return;
515 for (int i = 0; i < scop->n_array; ++i) {
516 isl_id *id;
517 isl_space *space;
518 isl_map *bounds;
519 ValueDecl *decl;
520 pet_array *array = scop->arrays[i];
522 id = isl_set_get_tuple_id(array->extent);
523 decl = pet_id_get_decl(id);
525 space = isl_space_alloc(ctx, 0, 0, 1);
526 space = isl_space_set_tuple_id(space, isl_dim_in, id);
528 bounds = isl_union_map_extract_map(value_bounds, space);
529 if (!isl_map_plain_is_empty(bounds))
530 array->value_bounds = isl_map_range(bounds);
531 else
532 isl_map_free(bounds);
534 lo_it = live_out.find(decl);
535 if (lo_it != live_out.end())
536 array->live_out = 1;
539 isl_union_map_free(value_bounds);
542 /* Extract a pet_scop (if any) from each appropriate function.
543 * Each detected scop is passed to "fn".
544 * When autodetecting, at most one scop is extracted from each function.
545 * If "function" is not NULL, then we only extract a pet_scop if the
546 * name of the function matches.
547 * If "autodetect" is false, then we only extract if we have seen
548 * scop and endscop pragmas and if these are situated inside the function
549 * body.
551 struct PetASTConsumer : public ASTConsumer {
552 Preprocessor &PP;
553 ASTContext &ast_context;
554 DiagnosticsEngine &diags;
555 ScopLocList &scops;
556 std::vector<Independent> independent;
557 const char *function;
558 pet_options *options;
559 isl_ctx *ctx;
560 isl_set *context;
561 isl_set *context_value;
562 set<ValueDecl *> live_out;
563 PragmaValueBoundsHandler *vb_handler;
564 int (*fn)(struct pet_scop *scop, void *user);
565 void *user;
566 bool error;
568 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
569 DiagnosticsEngine &diags, ScopLocList &scops,
570 const char *function, pet_options *options,
571 int (*fn)(struct pet_scop *scop, void *user), void *user) :
572 ctx(ctx), PP(PP), ast_context(ast_context), diags(diags),
573 scops(scops), function(function), options(options),
574 vb_handler(NULL), fn(fn), user(user), error(false)
576 isl_space *space;
577 space = isl_space_params_alloc(ctx, 0);
578 context = isl_set_universe(isl_space_copy(space));
579 context_value = isl_set_universe(space);
582 ~PetASTConsumer() {
583 isl_set_free(context);
584 isl_set_free(context_value);
587 void handle_value_bounds(Sema *sema) {
588 vb_handler = new PragmaValueBoundsHandler(ctx, *sema);
589 PP.AddPragmaHandler(vb_handler);
592 /* Add all pragma handlers to this->PP.
593 * The pencil pragmas are only handled if the pencil option is set.
595 void add_pragma_handlers(Sema *sema) {
596 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
597 context_value));
598 if (options->pencil) {
599 PragmaHandler *PH;
600 PH = new PragmaPencilHandler(independent);
601 PP.AddPragmaHandler(PH);
603 handle_value_bounds(sema);
606 __isl_give isl_union_map *get_value_bounds() {
607 return isl_union_map_copy(vb_handler->value_bounds);
610 /* Pass "scop" to "fn" after performing some postprocessing.
611 * In particular, add the context and value_bounds constraints
612 * speficied through pragmas, add reference identifiers and
613 * reset user pointers on parameters and tuple ids.
615 * If "scop" does not contain any statements and autodetect
616 * is turned on, then skip it.
618 void call_fn(pet_scop *scop) {
619 if (!scop)
620 return;
621 if (diags.hasErrorOccurred()) {
622 pet_scop_free(scop);
623 return;
625 if (options->autodetect && scop->n_stmt == 0) {
626 pet_scop_free(scop);
627 return;
629 scop->context = isl_set_intersect(scop->context,
630 isl_set_copy(context));
631 scop->context_value = isl_set_intersect(scop->context_value,
632 isl_set_copy(context_value));
634 update_arrays(scop, get_value_bounds(), live_out);
636 scop = pet_scop_add_ref_ids(scop);
637 scop = pet_scop_anonymize(scop);
639 if (fn(scop, user) < 0)
640 error = true;
643 /* For each explicitly marked scop (using pragmas),
644 * extract the scop and call "fn" on it if it is inside "fd".
646 void scan_scops(FunctionDecl *fd) {
647 unsigned start, end;
648 vector<ScopLoc>::iterator it;
649 isl_union_map *vb = vb_handler->value_bounds;
650 SourceManager &SM = PP.getSourceManager();
651 pet_scop *scop;
653 if (scops.list.size() == 0)
654 return;
656 start = SM.getFileOffset(fd->getLocStart());
657 end = SM.getFileOffset(fd->getLocEnd());
659 for (it = scops.list.begin(); it != scops.list.end(); ++it) {
660 ScopLoc loc = *it;
661 if (!loc.end)
662 continue;
663 if (start > loc.end)
664 continue;
665 if (end < loc.start)
666 continue;
667 PetScan ps(PP, ast_context, fd, loc, options,
668 isl_union_map_copy(vb), independent);
669 scop = ps.scan(fd);
670 call_fn(scop);
674 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef dg) {
675 DeclGroupRef::iterator it;
677 if (error)
678 return HandleTopLevelDeclContinue;
680 for (it = dg.begin(); it != dg.end(); ++it) {
681 isl_union_map *vb = vb_handler->value_bounds;
682 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
683 if (!fd)
684 continue;
685 if (!fd->hasBody())
686 continue;
687 if (function &&
688 fd->getNameInfo().getAsString() != function)
689 continue;
690 if (options->autodetect) {
691 ScopLoc loc;
692 pet_scop *scop;
693 PetScan ps(PP, ast_context, fd, loc, options,
694 isl_union_map_copy(vb),
695 independent);
696 scop = ps.scan(fd);
697 call_fn(scop);
698 continue;
700 scan_scops(fd);
703 return HandleTopLevelDeclContinue;
707 static const char *ResourceDir =
708 CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
710 static const char *implicit_functions[] = {
711 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
713 static const char *pencil_implicit_functions[] = {
714 "imin", "umin", "imax", "umax", "__pencil_kill"
717 /* Should "ident" be treated as an implicit function?
718 * If "pencil" is set, then also allow pencil specific builtins.
720 static bool is_implicit(const IdentifierInfo *ident, int pencil)
722 const char *name = ident->getNameStart();
723 for (int i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
724 if (!strcmp(name, implicit_functions[i]))
725 return true;
726 if (!pencil)
727 return false;
728 for (int i = 0; i < ARRAY_SIZE(pencil_implicit_functions); ++i)
729 if (!strcmp(name, pencil_implicit_functions[i]))
730 return true;
731 return false;
734 /* Ignore implicit function declaration warnings on
735 * "min", "max", "ceild" and "floord" as we detect and handle these
736 * in PetScan.
737 * If "pencil" is set, then also ignore them on pencil specific
738 * builtins.
740 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
741 const DiagnosticOptions *DiagOpts;
742 int pencil;
743 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
744 MyDiagnosticPrinter(DiagnosticOptions *DO, int pencil) :
745 TextDiagnosticPrinter(llvm::errs(), DO), pencil(pencil) {}
746 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
747 return new MyDiagnosticPrinter(&Diags.getDiagnosticOptions(),
748 pencil);
750 #else
751 MyDiagnosticPrinter(const DiagnosticOptions &DO, int pencil) :
752 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO),
753 pencil(pencil) {}
754 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
755 return new MyDiagnosticPrinter(*DiagOpts, pencil);
757 #endif
758 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
759 const DiagnosticInfo &info) {
760 if (info.getID() == diag::ext_implicit_function_decl &&
761 info.getNumArgs() == 1 &&
762 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
763 is_implicit(info.getArgIdentifier(0), pencil))
764 /* ignore warning */;
765 else
766 TextDiagnosticPrinter::HandleDiagnostic(level, info);
770 #ifdef USE_ARRAYREF
772 #ifdef HAVE_CXXISPRODUCTION
773 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
775 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
776 "", false, false, Diags);
778 #elif defined(HAVE_ISPRODUCTION)
779 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
781 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
782 "", false, Diags);
784 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
785 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
787 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
788 "", Diags);
790 #else
791 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
793 return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
795 #endif
797 namespace clang { namespace driver { class Job; } }
799 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
800 * We fix this with a simple overloaded function here.
802 struct ClangAPI {
803 static Job *command(Job *J) { return J; }
804 static Job *command(Job &J) { return &J; }
805 static Command *command(Command &C) { return &C; }
808 /* Create a CompilerInvocation object that stores the command line
809 * arguments constructed by the driver.
810 * The arguments are mainly useful for setting up the system include
811 * paths on newer clangs and on some platforms.
813 static CompilerInvocation *construct_invocation(const char *filename,
814 DiagnosticsEngine &Diags)
816 const char *binary = CLANG_PREFIX"/bin/clang";
817 const unique_ptr<Driver> driver(construct_driver(binary, Diags));
818 std::vector<const char *> Argv;
819 Argv.push_back(binary);
820 Argv.push_back(filename);
821 const unique_ptr<Compilation> compilation(
822 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
823 JobList &Jobs = compilation->getJobs();
824 if (Jobs.size() < 1)
825 return NULL;
827 Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
828 if (strcmp(cmd->getCreator().getName(), "clang"))
829 return NULL;
831 const ArgStringList *args = &cmd->getArguments();
833 CompilerInvocation *invocation = new CompilerInvocation;
834 CompilerInvocation::CreateFromArgs(*invocation, args->data() + 1,
835 args->data() + args->size(),
836 Diags);
837 return invocation;
840 #else
842 static CompilerInvocation *construct_invocation(const char *filename,
843 DiagnosticsEngine &Diags)
845 return NULL;
848 #endif
850 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
852 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
853 int pencil)
855 return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil);
858 #else
860 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
861 int pencil)
863 return new MyDiagnosticPrinter(Clang->getDiagnosticOpts(), pencil);
866 #endif
868 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
870 static TargetInfo *create_target_info(CompilerInstance *Clang,
871 DiagnosticsEngine &Diags)
873 shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
874 TO->Triple = llvm::sys::getDefaultTargetTriple();
875 return TargetInfo::CreateTargetInfo(Diags, TO);
878 #elif defined(CREATETARGETINFO_TAKES_POINTER)
880 static TargetInfo *create_target_info(CompilerInstance *Clang,
881 DiagnosticsEngine &Diags)
883 TargetOptions &TO = Clang->getTargetOpts();
884 TO.Triple = llvm::sys::getDefaultTargetTriple();
885 return TargetInfo::CreateTargetInfo(Diags, &TO);
888 #else
890 static TargetInfo *create_target_info(CompilerInstance *Clang,
891 DiagnosticsEngine &Diags)
893 TargetOptions &TO = Clang->getTargetOpts();
894 TO.Triple = llvm::sys::getDefaultTargetTriple();
895 return TargetInfo::CreateTargetInfo(Diags, TO);
898 #endif
900 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
902 static void create_diagnostics(CompilerInstance *Clang)
904 Clang->createDiagnostics(0, NULL);
907 #else
909 static void create_diagnostics(CompilerInstance *Clang)
911 Clang->createDiagnostics();
914 #endif
916 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
918 static void create_preprocessor(CompilerInstance *Clang)
920 Clang->createPreprocessor(TU_Complete);
923 #else
925 static void create_preprocessor(CompilerInstance *Clang)
927 Clang->createPreprocessor();
930 #endif
932 #ifdef ADDPATH_TAKES_4_ARGUMENTS
934 void add_path(HeaderSearchOptions &HSO, string Path)
936 HSO.AddPath(Path, frontend::Angled, false, false);
939 #else
941 void add_path(HeaderSearchOptions &HSO, string Path)
943 HSO.AddPath(Path, frontend::Angled, true, false, false);
946 #endif
948 #ifdef HAVE_SETMAINFILEID
950 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
952 SM.setMainFileID(SM.createFileID(file, SourceLocation(),
953 SrcMgr::C_User));
956 #else
958 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
960 SM.createMainFileID(file);
963 #endif
965 /* Add pet specific predefines to the preprocessor.
966 * Currently, these are all pencil specific, so they are only
967 * added if "pencil" is set.
969 * We mimic the way <command line> is handled inside clang.
971 void add_predefines(Preprocessor &PP, int pencil)
973 string s;
975 if (!pencil)
976 return;
978 s = PP.getPredefines();
979 s += "# 1 \"<pet>\" 1\n"
980 "void __pencil_assume(int assumption);\n"
981 "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n"
982 "# 1 \"<built-in>\" 2\n";
983 PP.setPredefines(s);
986 /* Extract a pet_scop from each function in the C source file called "filename".
987 * Each detected scop is passed to "fn".
988 * If "function" is not NULL, only extract a pet_scop from the function
989 * with that name.
990 * If "autodetect" is set, extract any pet_scop we can find.
991 * Otherwise, extract the pet_scop from the region delimited
992 * by "scop" and "endscop" pragmas.
994 * We first set up the clang parser and then try to extract the
995 * pet_scop from the appropriate function(s) in PetASTConsumer.
997 static int foreach_scop_in_C_source(isl_ctx *ctx,
998 const char *filename, const char *function, pet_options *options,
999 int (*fn)(struct pet_scop *scop, void *user), void *user)
1001 CompilerInstance *Clang = new CompilerInstance();
1002 create_diagnostics(Clang);
1003 DiagnosticsEngine &Diags = Clang->getDiagnostics();
1004 Diags.setSuppressSystemWarnings(true);
1005 CompilerInvocation *invocation = construct_invocation(filename, Diags);
1006 if (invocation)
1007 Clang->setInvocation(invocation);
1008 Diags.setClient(construct_printer(Clang, options->pencil));
1009 Clang->createFileManager();
1010 Clang->createSourceManager(Clang->getFileManager());
1011 TargetInfo *target = create_target_info(Clang, Diags);
1012 Clang->setTarget(target);
1013 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
1014 LangStandard::lang_unspecified);
1015 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
1016 HSO.ResourceDir = ResourceDir;
1017 for (int i = 0; i < options->n_path; ++i)
1018 add_path(HSO, options->paths[i]);
1019 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
1020 for (int i = 0; i < options->n_define; ++i)
1021 PO.addMacroDef(options->defines[i]);
1022 create_preprocessor(Clang);
1023 Preprocessor &PP = Clang->getPreprocessor();
1024 add_predefines(PP, options->pencil);
1025 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
1026 PP.getLangOpts());
1028 ScopLocList scops;
1030 const FileEntry *file = Clang->getFileManager().getFile(filename);
1031 if (!file)
1032 isl_die(ctx, isl_error_unknown, "unable to open file",
1033 do { delete Clang; return -1; } while (0));
1034 create_main_file_id(Clang->getSourceManager(), file);
1036 Clang->createASTContext();
1037 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(), Diags,
1038 scops, function, options, fn, user);
1039 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
1041 if (!options->autodetect) {
1042 PP.AddPragmaHandler(new PragmaScopHandler(scops));
1043 PP.AddPragmaHandler(new PragmaEndScopHandler(scops));
1044 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema,
1045 consumer.live_out));
1048 consumer.add_pragma_handlers(sema);
1050 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
1051 ParseAST(*sema);
1052 Diags.getClient()->EndSourceFile();
1054 delete sema;
1055 delete Clang;
1057 return consumer.error ? -1 : 0;
1060 /* Extract a pet_scop from each function in the C source file called "filename".
1061 * Each detected scop is passed to "fn".
1063 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1064 * that all objects on the stack (of that function) are destroyed before we
1065 * call llvm_shutdown.
1067 static int pet_foreach_scop_in_C_source(isl_ctx *ctx,
1068 const char *filename, const char *function,
1069 int (*fn)(struct pet_scop *scop, void *user), void *user)
1071 int r;
1072 pet_options *options;
1073 bool allocated = false;
1075 options = isl_ctx_peek_pet_options(ctx);
1076 if (!options) {
1077 options = pet_options_new_with_defaults();
1078 allocated = true;
1081 r = foreach_scop_in_C_source(ctx, filename, function, options,
1082 fn, user);
1083 llvm::llvm_shutdown();
1085 if (allocated)
1086 pet_options_free(options);
1088 return r;
1091 /* Store "scop" into the address pointed to by "user".
1092 * Return -1 to indicate that we are not interested in any further scops.
1093 * This function should therefore not be called a second call
1094 * so in principle there is no need to check if we have already set *user.
1096 static int set_first_scop(pet_scop *scop, void *user)
1098 pet_scop **p = (pet_scop **) user;
1100 if (!*p)
1101 *p = scop;
1102 else
1103 pet_scop_free(scop);
1105 return -1;
1108 /* Extract a pet_scop from the C source file called "filename".
1109 * If "function" is not NULL, extract the pet_scop from the function
1110 * with that name.
1112 * We start extracting scops from every function and then abort
1113 * as soon as we have extracted one scop.
1115 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
1116 const char *filename, const char *function)
1118 pet_scop *scop = NULL;
1120 pet_foreach_scop_in_C_source(ctx, filename, function,
1121 &set_first_scop, &scop);
1123 return scop;
1126 /* Internal data structure for pet_transform_C_source
1128 * transform is the function that should be called to print a scop
1129 * in is the input source file
1130 * out is the output source file
1131 * end is the offset of the end of the previous scop (zero if we have not
1132 * found any scop yet)
1133 * p is a printer that prints to out.
1135 struct pet_transform_data {
1136 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1137 struct pet_scop *scop, void *user);
1138 void *user;
1140 FILE *in;
1141 FILE *out;
1142 unsigned end;
1143 isl_printer *p;
1146 /* This function is called each time a scop is detected.
1148 * We first copy the input text code from the end of the previous scop
1149 * until the start of "scop" and then print the scop itself through
1150 * a call to data->transform. We set up the printer to print
1151 * the transformed code with the same (initial) indentation as
1152 * the original code.
1153 * Finally, we keep track of the end of "scop" so that we can
1154 * continue copying when we find the next scop.
1156 * Before calling data->transform, we store a pointer to the original
1157 * input file in the extended scop in case the user wants to call
1158 * pet_scop_print_original from the callback.
1160 static int pet_transform(struct pet_scop *scop, void *user)
1162 struct pet_transform_data *data = (struct pet_transform_data *) user;
1163 unsigned start;
1165 start = pet_loc_get_start(scop->loc);
1166 if (copy(data->in, data->out, data->end, start) < 0)
1167 goto error;
1168 data->end = pet_loc_get_end(scop->loc);
1169 scop = pet_scop_set_input_file(scop, data->in);
1170 data->p = isl_printer_set_indent_prefix(data->p,
1171 pet_loc_get_indent(scop->loc));
1172 data->p = data->transform(data->p, scop, data->user);
1173 if (!data->p)
1174 return -1;
1175 return 0;
1176 error:
1177 pet_scop_free(scop);
1178 return -1;
1181 /* Transform the C source file "input" by rewriting each scop
1182 * through a call to "transform".
1183 * When autodetecting scops, at most one scop per function is rewritten.
1184 * The transformed C code is written to "output".
1186 * For each scop we find, we first copy the input text code
1187 * from the end of the previous scop (or the beginning of the file
1188 * in case of the first scop) until the start of the scop
1189 * and then print the scop itself through a call to "transform".
1190 * At the end we copy everything from the end of the final scop
1191 * until the end of the input file to "output".
1193 int pet_transform_C_source(isl_ctx *ctx, const char *input, FILE *out,
1194 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1195 struct pet_scop *scop, void *user), void *user)
1197 struct pet_transform_data data;
1198 int r;
1200 data.in = stdin;
1201 data.out = out;
1202 if (input && strcmp(input, "-")) {
1203 data.in = fopen(input, "r");
1204 if (!data.in)
1205 isl_die(ctx, isl_error_unknown, "unable to open file",
1206 return -1);
1209 data.p = isl_printer_to_file(ctx, data.out);
1210 data.p = isl_printer_set_output_format(data.p, ISL_FORMAT_C);
1212 data.transform = transform;
1213 data.user = user;
1214 data.end = 0;
1215 r = pet_foreach_scop_in_C_source(ctx, input, NULL,
1216 &pet_transform, &data);
1218 isl_printer_free(data.p);
1219 if (!data.p)
1220 r = -1;
1221 if (r == 0 && copy(data.in, data.out, data.end, -1) < 0)
1222 r = -1;
1224 if (data.in != stdin)
1225 fclose(data.in);
1227 return r;