induction variable of for loop should be considered a parameter inside the loop
[pet.git] / pet.cc
blob91f9fb183470ab8438008d709b54b6613b8825ea
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
31 * Leiden University.
32 */
34 #include <stdlib.h>
35 #include <map>
36 #include <iostream>
37 #include <llvm/Support/raw_ostream.h>
38 #include <llvm/Support/ManagedStatic.h>
39 #include <llvm/Support/Host.h>
40 #include <clang/Basic/Version.h>
41 #include <clang/Basic/FileSystemOptions.h>
42 #include <clang/Basic/FileManager.h>
43 #include <clang/Basic/TargetOptions.h>
44 #include <clang/Basic/TargetInfo.h>
45 #include <clang/Frontend/CompilerInstance.h>
46 #include <clang/Frontend/CompilerInvocation.h>
47 #include <clang/Frontend/DiagnosticOptions.h>
48 #include <clang/Frontend/TextDiagnosticPrinter.h>
49 #include <clang/Frontend/HeaderSearchOptions.h>
50 #include <clang/Frontend/LangStandard.h>
51 #include <clang/Frontend/PreprocessorOptions.h>
52 #include <clang/Frontend/FrontendOptions.h>
53 #include <clang/Frontend/Utils.h>
54 #include <clang/Lex/HeaderSearch.h>
55 #include <clang/Lex/Preprocessor.h>
56 #include <clang/Lex/Pragma.h>
57 #include <clang/AST/ASTContext.h>
58 #include <clang/AST/ASTConsumer.h>
59 #include <clang/Sema/Sema.h>
60 #include <clang/Sema/SemaDiagnostic.h>
61 #include <clang/Parse/Parser.h>
62 #include <clang/Parse/ParseAST.h>
64 #include <isl/ctx.h>
65 #include <isl/constraint.h>
67 #include "scan.h"
69 #include "config.h"
71 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
73 using namespace std;
74 using namespace clang;
76 /* Called if we found something we didn't expect in one of the pragmas.
77 * We'll provide more informative warnings later.
79 static void unsupported(Preprocessor &PP, SourceLocation loc)
81 DiagnosticsEngine &diag = PP.getDiagnostics();
82 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
83 "unsupported");
84 DiagnosticBuilder B = diag.Report(loc, id);
87 static int get_int(const char *s)
89 return s[0] == '"' ? atoi(s + 1) : atoi(s);
92 static ValueDecl *get_value_decl(Sema &sema, Token &token)
94 IdentifierInfo *name;
95 Decl *decl;
97 if (token.isNot(tok::identifier))
98 return NULL;
100 name = token.getIdentifierInfo();
101 decl = sema.LookupSingleName(sema.TUScope, name,
102 token.getLocation(), Sema::LookupOrdinaryName);
103 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
106 /* Handle pragmas of the form
108 * #pragma value_bounds identifier lower_bound upper_bound
110 * For each such pragma, add a mapping from the ValueDecl corresponding
111 * to "identifier" to a set { [i] : lower_bound <= i <= upper_bound }
112 * to the map value_bounds.
114 struct PragmaValueBoundsHandler : public PragmaHandler {
115 Sema &sema;
116 isl_ctx *ctx;
117 map<ValueDecl *, isl_set *> &value_bounds;
119 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema,
120 map<ValueDecl *, isl_set *> &value_bounds) :
121 PragmaHandler("value_bounds"), ctx(ctx), sema(sema),
122 value_bounds(value_bounds) {}
124 virtual void HandlePragma(Preprocessor &PP,
125 PragmaIntroducerKind Introducer,
126 Token &ScopTok) {
127 isl_space *dim;
128 isl_set *set;
129 ValueDecl *vd;
130 Token token;
131 int lb;
132 int ub;
134 PP.Lex(token);
135 vd = get_value_decl(sema, token);
136 if (!vd) {
137 unsupported(PP, token.getLocation());
138 return;
141 PP.Lex(token);
142 if (!token.isLiteral()) {
143 unsupported(PP, token.getLocation());
144 return;
147 lb = get_int(token.getLiteralData());
149 PP.Lex(token);
150 if (!token.isLiteral()) {
151 unsupported(PP, token.getLocation());
152 return;
155 ub = get_int(token.getLiteralData());
157 dim = isl_space_set_alloc(ctx, 0, 1);
158 set = isl_set_universe(dim);
159 set = isl_set_lower_bound_si(set, isl_dim_set, 0, lb);
160 set = isl_set_upper_bound_si(set, isl_dim_set, 0, ub);
162 value_bounds[vd] = set;
166 /* Given a variable declaration, check if it has an integer initializer
167 * and if so, add a parameter corresponding to the variable to "value"
168 * with its value fixed to the integer initializer and return the result.
170 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
171 ValueDecl *decl)
173 VarDecl *vd;
174 Expr *expr;
175 IntegerLiteral *il;
176 isl_int v;
177 isl_ctx *ctx;
178 isl_id *id;
179 isl_space *space;
180 isl_set *set;
182 vd = cast<VarDecl>(decl);
183 if (!vd)
184 return value;
185 if (!vd->getType()->isIntegerType())
186 return value;
187 expr = vd->getInit();
188 if (!expr)
189 return value;
190 il = cast<IntegerLiteral>(expr);
191 if (!il)
192 return value;
194 ctx = isl_set_get_ctx(value);
195 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
196 space = isl_space_params_alloc(ctx, 1);
197 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
198 set = isl_set_universe(space);
200 isl_int_init(v);
201 PetScan::extract_int(il, &v);
202 set = isl_set_fix(set, isl_dim_param, 0, v);
203 isl_int_clear(v);
205 return isl_set_intersect(value, set);
208 /* Handle pragmas of the form
210 * #pragma parameter identifier lower_bound
211 * and
212 * #pragma parameter identifier lower_bound upper_bound
214 * For each such pragma, intersect the context with the set
215 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
217 struct PragmaParameterHandler : public PragmaHandler {
218 Sema &sema;
219 isl_set *&context;
220 isl_set *&context_value;
222 PragmaParameterHandler(Sema &sema, isl_set *&context,
223 isl_set *&context_value) :
224 PragmaHandler("parameter"), sema(sema), context(context),
225 context_value(context_value) {}
227 virtual void HandlePragma(Preprocessor &PP,
228 PragmaIntroducerKind Introducer,
229 Token &ScopTok) {
230 isl_id *id;
231 isl_ctx *ctx = isl_set_get_ctx(context);
232 isl_space *dim;
233 isl_set *set;
234 ValueDecl *vd;
235 Token token;
236 int lb;
237 int ub;
238 bool has_ub = false;
240 PP.Lex(token);
241 vd = get_value_decl(sema, token);
242 if (!vd) {
243 unsupported(PP, token.getLocation());
244 return;
247 PP.Lex(token);
248 if (!token.isLiteral()) {
249 unsupported(PP, token.getLocation());
250 return;
253 lb = get_int(token.getLiteralData());
255 PP.Lex(token);
256 if (token.isLiteral()) {
257 has_ub = true;
258 ub = get_int(token.getLiteralData());
259 } else if (token.isNot(tok::eod)) {
260 unsupported(PP, token.getLocation());
261 return;
264 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
265 dim = isl_space_params_alloc(ctx, 1);
266 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
268 set = isl_set_universe(dim);
270 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
271 if (has_ub)
272 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
274 context = isl_set_intersect(context, set);
276 context_value = extract_initialization(context_value, vd);
280 /* Handle pragmas of the form
282 * #pragma scop
284 * In particular, store the current location in loc.start.
286 struct PragmaScopHandler : public PragmaHandler {
287 ScopLoc &loc;
289 PragmaScopHandler(ScopLoc &loc) : PragmaHandler("scop"), loc(loc) {}
291 virtual void HandlePragma(Preprocessor &PP,
292 PragmaIntroducerKind Introducer,
293 Token &ScopTok) {
294 SourceManager &SM = PP.getSourceManager();
295 loc.start = SM.getFileOffset(ScopTok.getLocation());
299 /* Handle pragmas of the form
301 * #pragma endscop
303 * In particular, store the current location in loc.end.
305 struct PragmaEndScopHandler : public PragmaHandler {
306 ScopLoc &loc;
308 PragmaEndScopHandler(ScopLoc &loc) :
309 PragmaHandler("endscop"), loc(loc) {}
311 virtual void HandlePragma(Preprocessor &PP,
312 PragmaIntroducerKind Introducer,
313 Token &EndScopTok) {
314 SourceManager &SM = PP.getSourceManager();
315 loc.end = SM.getFileOffset(EndScopTok.getLocation());
319 /* Handle pragmas of the form
321 * #pragma live-out identifier, identifier, ...
323 * Each identifier on the line is stored in live_out.
325 struct PragmaLiveOutHandler : public PragmaHandler {
326 Sema &sema;
327 set<ValueDecl *> &live_out;
329 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
330 PragmaHandler("live"), sema(sema), live_out(live_out) {}
332 virtual void HandlePragma(Preprocessor &PP,
333 PragmaIntroducerKind Introducer,
334 Token &ScopTok) {
335 Token token;
337 PP.Lex(token);
338 if (token.isNot(tok::minus))
339 return;
340 PP.Lex(token);
341 if (token.isNot(tok::identifier) ||
342 !token.getIdentifierInfo()->isStr("out"))
343 return;
345 PP.Lex(token);
346 while (token.isNot(tok::eod)) {
347 ValueDecl *vd;
349 vd = get_value_decl(sema, token);
350 if (!vd) {
351 unsupported(PP, token.getLocation());
352 return;
354 live_out.insert(vd);
355 PP.Lex(token);
356 if (token.is(tok::comma))
357 PP.Lex(token);
362 /* Extract a pet_scop from the appropriate function.
363 * If "function" is not NULL, then we only extract a pet_scop if the
364 * name of the function matches.
365 * If "autodetect" is false, then we only extract if we have seen
366 * scop and endscop pragmas and if these are situated inside the function
367 * body.
369 struct PetASTConsumer : public ASTConsumer {
370 Preprocessor &PP;
371 ASTContext &ast_context;
372 ScopLoc &loc;
373 const char *function;
374 bool autodetect;
375 isl_ctx *ctx;
376 struct pet_scop *scop;
378 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
379 ScopLoc &loc, const char *function, bool autodetect) :
380 ctx(ctx), PP(PP), ast_context(ast_context), loc(loc),
381 scop(NULL), function(function), autodetect(autodetect) { }
383 virtual void HandleTopLevelDecl(DeclGroupRef dg) {
384 DeclGroupRef::iterator it;
386 if (scop)
387 return;
388 for (it = dg.begin(); it != dg.end(); ++it) {
389 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
390 if (!fd)
391 continue;
392 if (!fd->hasBody())
393 continue;
394 if (function &&
395 fd->getNameInfo().getAsString() != function)
396 continue;
397 if (autodetect) {
398 PetScan ps(ctx, PP, ast_context, loc, 1);
399 scop = ps.scan(fd);
400 if (scop)
401 break;
402 else
403 continue;
405 if (!loc.end)
406 continue;
407 SourceManager &SM = PP.getSourceManager();
408 if (SM.getFileOffset(fd->getLocStart()) > loc.end)
409 continue;
410 if (SM.getFileOffset(fd->getLocEnd()) < loc.start)
411 continue;
412 PetScan ps(ctx, PP, ast_context, loc, 0);
413 scop = ps.scan(fd);
414 break;
419 static const char *ResourceDir = CLANG_PREFIX"/lib/clang/"CLANG_VERSION_STRING;
421 static const char *implicit_functions[] = {
422 "min", "max", "ceild", "floord"
425 static bool is_implicit(const IdentifierInfo *ident)
427 const char *name = ident->getNameStart();
428 for (int i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
429 if (!strcmp(name, implicit_functions[i]))
430 return true;
431 return false;
434 /* Ignore implicit function declaration warnings on
435 * "min", "max", "ceild" and "floord" as we detect and handle these
436 * in PetScan.
438 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
439 const DiagnosticOptions *DiagOpts;
440 MyDiagnosticPrinter(const DiagnosticOptions &DO) :
441 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO) {}
442 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
443 return new MyDiagnosticPrinter(*DiagOpts);
445 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
446 const DiagnosticInfo &info) {
447 if (info.getID() == diag::ext_implicit_function_decl &&
448 info.getNumArgs() == 1 &&
449 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
450 is_implicit(info.getArgIdentifier(0)))
451 /* ignore warning */;
452 else
453 TextDiagnosticPrinter::HandleDiagnostic(level, info);
457 static void update_arrays(struct pet_scop *scop,
458 map<ValueDecl *, isl_set *> &value_bounds,
459 set<ValueDecl *> &live_out)
461 map<ValueDecl *, isl_set *>::iterator vb_it;
462 set<ValueDecl *>::iterator lo_it;
464 if (!scop)
465 return;
467 for (int i = 0; i < scop->n_array; ++i) {
468 isl_id *id;
469 ValueDecl *decl;
470 pet_array *array = scop->arrays[i];
472 id = isl_set_get_tuple_id(array->extent);
473 decl = (ValueDecl *)isl_id_get_user(id);
474 isl_id_free(id);
476 vb_it = value_bounds.find(decl);
477 if (vb_it != value_bounds.end())
478 array->value_bounds = isl_set_copy(vb_it->second);
480 lo_it = live_out.find(decl);
481 if (lo_it != live_out.end())
482 array->live_out = 1;
486 /* Extract a pet_scop from the C source file called "filename".
487 * If "function" is not NULL, extract the pet_scop from the function
488 * with that name.
489 * If "autodetect" is set, extract any pet_scop we can find.
490 * Otherwise, extract the pet_scop from the region delimited
491 * by "scop" and "endscop" pragmas.
493 * We first set up the clang parser and then try to extract the
494 * pet_scop from the appropriate function in PetASTConsumer.
495 * If we have found a pet_scop, we add the context and value_bounds
496 * constraints specified through pragmas.
498 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
499 const char *filename, const char *function, int autodetect)
501 isl_space *dim;
502 isl_set *context;
503 isl_set *context_value;
504 set<ValueDecl *> live_out;
505 map<ValueDecl *, isl_set *> value_bounds;
506 map<ValueDecl *, isl_set *>::iterator vb_it;
508 CompilerInstance *Clang = new CompilerInstance();
509 DiagnosticOptions DO;
510 Clang->createDiagnostics(0, NULL, new MyDiagnosticPrinter(DO));
511 DiagnosticsEngine &Diags = Clang->getDiagnostics();
512 Diags.setSuppressSystemWarnings(true);
513 Clang->createFileManager();
514 Clang->createSourceManager(Clang->getFileManager());
515 TargetOptions TO;
516 TO.Triple = llvm::sys::getHostTriple();
517 TargetInfo *target = TargetInfo::CreateTargetInfo(Diags, TO);
518 Clang->setTarget(target);
519 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
520 LangStandard::lang_unspecified);
521 Clang->getHeaderSearchOpts().ResourceDir = ResourceDir;
522 Clang->createPreprocessor();
523 Preprocessor &PP = Clang->getPreprocessor();
525 ScopLoc loc;
527 const FileEntry *file = Clang->getFileManager().getFile(filename);
528 if (!file)
529 isl_die(ctx, isl_error_unknown, "unable to open file",
530 return NULL);
531 Clang->getSourceManager().createMainFileID(file);
533 Clang->createASTContext();
534 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(),
535 loc, function, autodetect);
536 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
538 if (!autodetect) {
539 PP.AddPragmaHandler(new PragmaScopHandler(loc));
540 PP.AddPragmaHandler(new PragmaEndScopHandler(loc));
541 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema, live_out));
544 dim = isl_space_params_alloc(ctx, 0);
545 context = isl_set_universe(isl_space_copy(dim));
546 context_value = isl_set_universe(dim);
547 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
548 context_value));
549 PP.AddPragmaHandler(new PragmaValueBoundsHandler(ctx, *sema, value_bounds));
551 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
552 ParseAST(*sema);
553 Diags.getClient()->EndSourceFile();
555 delete sema;
556 delete Clang;
557 llvm::llvm_shutdown();
559 if (consumer.scop) {
560 consumer.scop->context = isl_set_intersect(context,
561 consumer.scop->context);
562 consumer.scop->context_value = isl_set_intersect(context_value,
563 consumer.scop->context_value);
564 } else {
565 isl_set_free(context);
566 isl_set_free(context_value);
569 update_arrays(consumer.scop, value_bounds, live_out);
571 for (vb_it = value_bounds.begin(); vb_it != value_bounds.end(); vb_it++)
572 isl_set_free(vb_it->second);
574 return consumer.scop;