2 * Copyright 2011 Leiden University. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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
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>
65 #include <isl/constraint.h>
71 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
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 Diagnostic
&diag
= PP
.getDiagnostics();
82 unsigned id
= diag
.getCustomDiagID(Diagnostic::Warning
, "unsupported");
83 DiagnosticBuilder B
= diag
.Report(loc
, id
);
86 /* Set the lower and upper bounds on the given dimension of "set"
89 static __isl_give isl_set
*set_bounds(__isl_take isl_set
*set
,
90 enum isl_dim_type type
, int pos
, int lb
, int ub
)
95 ls
= isl_local_space_from_space(isl_set_get_space(set
));
97 c
= isl_inequality_alloc(isl_local_space_copy(ls
));
98 c
= isl_constraint_set_coefficient_si(c
, type
, pos
, 1);
99 c
= isl_constraint_set_constant_si(c
, -lb
);
100 set
= isl_set_add_constraint(set
, c
);
102 c
= isl_inequality_alloc(ls
);
103 c
= isl_constraint_set_coefficient_si(c
, type
, pos
, -1);
104 c
= isl_constraint_set_constant_si(c
, ub
);
105 set
= isl_set_add_constraint(set
, c
);
110 static int get_int(const char *s
)
112 return s
[0] == '"' ? atoi(s
+ 1) : atoi(s
);
115 static ValueDecl
*get_value_decl(Sema
&sema
, Token
&token
)
117 IdentifierInfo
*name
;
120 if (token
.isNot(tok::identifier
))
123 name
= token
.getIdentifierInfo();
124 decl
= sema
.LookupSingleName(sema
.TUScope
, name
,
125 token
.getLocation(), Sema::LookupOrdinaryName
);
126 return decl
? cast_or_null
<ValueDecl
>(decl
) : NULL
;
129 /* Handle pragmas of the form
131 * #pragma value_bounds identifier lower_bound upper_bound
133 * For each such pragma, add a mapping from the ValueDecl corresponding
134 * to "identifier" to a set { [i] : lower_bound <= i <= upper_bound }
135 * to the map value_bounds.
137 struct PragmaValueBoundsHandler
: public PragmaHandler
{
140 map
<ValueDecl
*, isl_set
*> &value_bounds
;
142 PragmaValueBoundsHandler(isl_ctx
*ctx
, Sema
&sema
,
143 map
<ValueDecl
*, isl_set
*> &value_bounds
) :
144 PragmaHandler("value_bounds"), ctx(ctx
), sema(sema
),
145 value_bounds(value_bounds
) {}
147 virtual void HandlePragma(Preprocessor
&PP
,
148 PragmaIntroducerKind Introducer
,
158 vd
= get_value_decl(sema
, token
);
160 unsupported(PP
, token
.getLocation());
165 if (!token
.isLiteral()) {
166 unsupported(PP
, token
.getLocation());
170 lb
= get_int(token
.getLiteralData());
173 if (!token
.isLiteral()) {
174 unsupported(PP
, token
.getLocation());
178 ub
= get_int(token
.getLiteralData());
180 dim
= isl_space_set_alloc(ctx
, 0, 1);
181 set
= isl_set_universe(dim
);
182 set
= set_bounds(set
, isl_dim_set
, 0, lb
, ub
);
184 value_bounds
[vd
] = set
;
188 /* Handle pragmas of the form
190 * #pragma parameter identifier lower_bound upper_bound
192 * For each such pragma, intersect the context with the set
193 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
195 struct PragmaParameterHandler
: public PragmaHandler
{
199 PragmaParameterHandler(Sema
&sema
, isl_set
*&context
) :
200 PragmaHandler("parameter"), sema(sema
), context(context
) {}
202 virtual void HandlePragma(Preprocessor
&PP
,
203 PragmaIntroducerKind Introducer
,
206 isl_ctx
*ctx
= isl_set_get_ctx(context
);
215 vd
= get_value_decl(sema
, token
);
217 unsupported(PP
, token
.getLocation());
222 if (!token
.isLiteral()) {
223 unsupported(PP
, token
.getLocation());
227 lb
= get_int(token
.getLiteralData());
230 if (!token
.isLiteral()) {
231 unsupported(PP
, token
.getLocation());
235 ub
= get_int(token
.getLiteralData());
237 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
238 dim
= isl_space_params_alloc(ctx
, 1);
239 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
241 set
= isl_set_universe(dim
);
243 set
= set_bounds(set
, isl_dim_param
, 0, lb
, ub
);
245 context
= isl_set_intersect(context
, set
);
249 /* Handle pragmas of the form
253 * In particular, store the current location in loc.start.
255 struct PragmaScopHandler
: public PragmaHandler
{
258 PragmaScopHandler(ScopLoc
&loc
) : PragmaHandler("scop"), loc(loc
) {}
260 virtual void HandlePragma(Preprocessor
&PP
,
261 PragmaIntroducerKind Introducer
,
263 SourceManager
&SM
= PP
.getSourceManager();
264 loc
.start
= SM
.getFileOffset(ScopTok
.getLocation());
268 /* Handle pragmas of the form
272 * In particular, store the current location in loc.end.
274 struct PragmaEndScopHandler
: public PragmaHandler
{
277 PragmaEndScopHandler(ScopLoc
&loc
) :
278 PragmaHandler("endscop"), loc(loc
) {}
280 virtual void HandlePragma(Preprocessor
&PP
,
281 PragmaIntroducerKind Introducer
,
283 SourceManager
&SM
= PP
.getSourceManager();
284 loc
.end
= SM
.getFileOffset(EndScopTok
.getLocation());
288 /* Handle pragmas of the form
290 * #pragma live-out identifier, identifier, ...
292 * Each identifier on the line is stored in live_out.
294 struct PragmaLiveOutHandler
: public PragmaHandler
{
296 set
<ValueDecl
*> &live_out
;
298 PragmaLiveOutHandler(Sema
&sema
, set
<ValueDecl
*> &live_out
) :
299 PragmaHandler("live"), sema(sema
), live_out(live_out
) {}
301 virtual void HandlePragma(Preprocessor
&PP
,
302 PragmaIntroducerKind Introducer
,
307 if (token
.isNot(tok::minus
))
310 if (token
.isNot(tok::identifier
) ||
311 !token
.getIdentifierInfo()->isStr("out"))
315 while (token
.isNot(tok::eod
)) {
318 vd
= get_value_decl(sema
, token
);
320 unsupported(PP
, token
.getLocation());
325 if (token
.is(tok::comma
))
331 /* Extract a pet_scop from the appropriate function.
332 * If "function" is not NULL, then we only extract a pet_scop if the
333 * name of the function matches.
334 * If "autodetect" is false, then we only extract if we have seen
335 * scop and endscop pragmas and if these are situated inside the function
338 struct PetASTConsumer
: public ASTConsumer
{
340 ASTContext
&ast_context
;
342 const char *function
;
345 struct pet_scop
*scop
;
347 PetASTConsumer(isl_ctx
*ctx
, Preprocessor
&PP
, ASTContext
&ast_context
,
348 ScopLoc
&loc
, const char *function
, bool autodetect
) :
349 ctx(ctx
), PP(PP
), ast_context(ast_context
), loc(loc
),
350 scop(NULL
), function(function
), autodetect(autodetect
) { }
352 virtual void HandleTopLevelDecl(DeclGroupRef dg
) {
353 DeclGroupRef::iterator it
;
357 for (it
= dg
.begin(); it
!= dg
.end(); ++it
) {
358 FunctionDecl
*fd
= dyn_cast
<clang::FunctionDecl
>(*it
);
364 fd
->getNameInfo().getAsString() != function
)
367 PetScan
ps(ctx
, PP
, ast_context
, loc
, 1);
376 SourceManager
&SM
= PP
.getSourceManager();
377 if (SM
.getFileOffset(fd
->getLocStart()) > loc
.end
)
379 if (SM
.getFileOffset(fd
->getLocEnd()) < loc
.start
)
381 PetScan
ps(ctx
, PP
, ast_context
, loc
, 0);
388 static const char *ResourceDir
= CLANG_PREFIX
"/lib/clang/"CLANG_VERSION_STRING
;
390 static const char *implicit_functions
[] = {
391 "min", "max", "ceild", "floord"
394 static bool is_implicit(const IdentifierInfo
*ident
)
396 const char *name
= ident
->getNameStart();
397 for (int i
= 0; i
< ARRAY_SIZE(implicit_functions
); ++i
)
398 if (!strcmp(name
, implicit_functions
[i
]))
403 /* Ignore implicit function declaration warnings on
404 * "min", "max", "ceild" and "floord" as we detect and handle these
407 struct MyDiagnosticPrinter
: public TextDiagnosticPrinter
{
408 MyDiagnosticPrinter(const DiagnosticOptions
&DO
) :
409 TextDiagnosticPrinter(llvm::errs(), DO
) {}
410 virtual void HandleDiagnostic(Diagnostic::Level level
,
411 const DiagnosticInfo
&info
) {
412 if (info
.getID() == diag::ext_implicit_function_decl
&&
413 info
.getNumArgs() == 1 &&
414 info
.getArgKind(0) == Diagnostic::ak_identifierinfo
&&
415 is_implicit(info
.getArgIdentifier(0)))
416 /* ignore warning */;
418 TextDiagnosticPrinter::HandleDiagnostic(level
, info
);
422 static void update_arrays(struct pet_scop
*scop
,
423 map
<ValueDecl
*, isl_set
*> &value_bounds
,
424 set
<ValueDecl
*> &live_out
)
426 map
<ValueDecl
*, isl_set
*>::iterator vb_it
;
427 set
<ValueDecl
*>::iterator lo_it
;
432 for (int i
= 0; i
< scop
->n_array
; ++i
) {
435 pet_array
*array
= scop
->arrays
[i
];
437 id
= isl_set_get_tuple_id(array
->extent
);
438 decl
= (ValueDecl
*)isl_id_get_user(id
);
441 vb_it
= value_bounds
.find(decl
);
442 if (vb_it
!= value_bounds
.end())
443 array
->value_bounds
= isl_set_copy(vb_it
->second
);
445 lo_it
= live_out
.find(decl
);
446 if (lo_it
!= live_out
.end())
451 /* Extract a pet_scop from the C source file called "filename".
452 * If "function" is not NULL, extract the pet_scop from the function
454 * If "autodetect" is set, extract any pet_scop we can find.
455 * Otherwise, extract the pet_scop from the region delimited
456 * by "scop" and "endscop" pragmas.
458 * We first set up the clang parser and then try to extract the
459 * pet_scop from the appropriate function in PetASTConsumer.
460 * If we have found a pet_scop, we add the context and value_bounds
461 * constraints specified through pragmas.
463 struct pet_scop
*pet_scop_extract_from_C_source(isl_ctx
*ctx
,
464 const char *filename
, const char *function
, int autodetect
)
468 set
<ValueDecl
*> live_out
;
469 map
<ValueDecl
*, isl_set
*> value_bounds
;
470 map
<ValueDecl
*, isl_set
*>::iterator vb_it
;
472 CompilerInstance
*Clang
= new CompilerInstance();
473 DiagnosticOptions DO
;
474 Clang
->createDiagnostics(0, NULL
, new MyDiagnosticPrinter(DO
));
475 Diagnostic
&Diags
= Clang
->getDiagnostics();
476 Diags
.setSuppressSystemWarnings(true);
477 Clang
->createFileManager();
478 Clang
->createSourceManager(Clang
->getFileManager());
480 TO
.Triple
= llvm::sys::getHostTriple();
481 TargetInfo
*target
= TargetInfo::CreateTargetInfo(Diags
, TO
);
482 Clang
->setTarget(target
);
483 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
,
484 LangStandard::lang_unspecified
);
485 Clang
->getHeaderSearchOpts().ResourceDir
= ResourceDir
;
486 Clang
->createPreprocessor();
487 Preprocessor
&PP
= Clang
->getPreprocessor();
491 const FileEntry
*file
= Clang
->getFileManager().getFile(filename
);
493 isl_die(ctx
, isl_error_unknown
, "unable to open file",
495 Clang
->getSourceManager().createMainFileID(file
);
497 Clang
->createASTContext();
498 PetASTConsumer
consumer(ctx
, PP
, Clang
->getASTContext(),
499 loc
, function
, autodetect
);
500 Sema
*sema
= new Sema(PP
, Clang
->getASTContext(), consumer
);
503 PP
.AddPragmaHandler(new PragmaScopHandler(loc
));
504 PP
.AddPragmaHandler(new PragmaEndScopHandler(loc
));
505 PP
.AddPragmaHandler(new PragmaLiveOutHandler(*sema
, live_out
));
508 dim
= isl_space_params_alloc(ctx
, 0);
509 context
= isl_set_universe(dim
);
510 PP
.AddPragmaHandler(new PragmaParameterHandler(*sema
, context
));
511 PP
.AddPragmaHandler(new PragmaValueBoundsHandler(ctx
, *sema
, value_bounds
));
513 Diags
.getClient()->BeginSourceFile(Clang
->getLangOpts(), &PP
);
515 Diags
.getClient()->EndSourceFile();
519 llvm::llvm_shutdown();
522 consumer
.scop
->context
= isl_set_intersect(context
,
523 consumer
.scop
->context
);
525 isl_set_free(context
);
527 update_arrays(consumer
.scop
, value_bounds
, live_out
);
529 for (vb_it
= value_bounds
.begin(); vb_it
!= value_bounds
.end(); vb_it
++)
530 isl_set_free(vb_it
->second
);
532 return consumer
.scop
;