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 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
82 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
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
)
97 if (token
.isNot(tok::identifier
))
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
{
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
,
135 vd
= get_value_decl(sema
, token
);
137 unsupported(PP
, token
.getLocation());
142 if (!token
.isLiteral()) {
143 unsupported(PP
, token
.getLocation());
147 lb
= get_int(token
.getLiteralData());
150 if (!token
.isLiteral()) {
151 unsupported(PP
, token
.getLocation());
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
,
182 vd
= cast
<VarDecl
>(decl
);
185 if (!vd
->getType()->isIntegerType())
187 expr
= vd
->getInit();
190 il
= cast
<IntegerLiteral
>(expr
);
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
);
201 PetScan::extract_int(il
, &v
);
202 set
= isl_set_fix(set
, isl_dim_param
, 0, v
);
205 return isl_set_intersect(value
, set
);
208 /* Handle pragmas of the form
210 * #pragma parameter identifier lower_bound
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
{
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
,
231 isl_ctx
*ctx
= isl_set_get_ctx(context
);
241 vd
= get_value_decl(sema
, token
);
243 unsupported(PP
, token
.getLocation());
248 if (!token
.isLiteral()) {
249 unsupported(PP
, token
.getLocation());
253 lb
= get_int(token
.getLiteralData());
256 if (token
.isLiteral()) {
258 ub
= get_int(token
.getLiteralData());
259 } else if (token
.isNot(tok::eod
)) {
260 unsupported(PP
, token
.getLocation());
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
);
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
284 * In particular, store the current location in loc.start.
286 struct PragmaScopHandler
: public PragmaHandler
{
289 PragmaScopHandler(ScopLoc
&loc
) : PragmaHandler("scop"), loc(loc
) {}
291 virtual void HandlePragma(Preprocessor
&PP
,
292 PragmaIntroducerKind Introducer
,
294 SourceManager
&SM
= PP
.getSourceManager();
295 loc
.start
= SM
.getFileOffset(ScopTok
.getLocation());
299 /* Handle pragmas of the form
303 * In particular, store the current location in loc.end.
305 struct PragmaEndScopHandler
: public PragmaHandler
{
308 PragmaEndScopHandler(ScopLoc
&loc
) :
309 PragmaHandler("endscop"), loc(loc
) {}
311 virtual void HandlePragma(Preprocessor
&PP
,
312 PragmaIntroducerKind Introducer
,
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
{
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
,
338 if (token
.isNot(tok::minus
))
341 if (token
.isNot(tok::identifier
) ||
342 !token
.getIdentifierInfo()->isStr("out"))
346 while (token
.isNot(tok::eod
)) {
349 vd
= get_value_decl(sema
, token
);
351 unsupported(PP
, token
.getLocation());
356 if (token
.is(tok::comma
))
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
369 struct PetASTConsumer
: public ASTConsumer
{
371 ASTContext
&ast_context
;
373 const char *function
;
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
;
388 for (it
= dg
.begin(); it
!= dg
.end(); ++it
) {
389 FunctionDecl
*fd
= dyn_cast
<clang::FunctionDecl
>(*it
);
395 fd
->getNameInfo().getAsString() != function
)
398 PetScan
ps(ctx
, PP
, ast_context
, loc
, 1);
407 SourceManager
&SM
= PP
.getSourceManager();
408 if (SM
.getFileOffset(fd
->getLocStart()) > loc
.end
)
410 if (SM
.getFileOffset(fd
->getLocEnd()) < loc
.start
)
412 PetScan
ps(ctx
, PP
, ast_context
, loc
, 0);
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
]))
434 /* Ignore implicit function declaration warnings on
435 * "min", "max", "ceild" and "floord" as we detect and handle these
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 */;
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
;
467 for (int i
= 0; i
< scop
->n_array
; ++i
) {
470 pet_array
*array
= scop
->arrays
[i
];
472 id
= isl_set_get_tuple_id(array
->extent
);
473 decl
= (ValueDecl
*)isl_id_get_user(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())
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
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
)
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());
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();
527 const FileEntry
*file
= Clang
->getFileManager().getFile(filename
);
529 isl_die(ctx
, isl_error_unknown
, "unable to open file",
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
);
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
,
549 PP
.AddPragmaHandler(new PragmaValueBoundsHandler(ctx
, *sema
, value_bounds
));
551 Diags
.getClient()->BeginSourceFile(Clang
->getLangOpts(), &PP
);
553 Diags
.getClient()->EndSourceFile();
557 llvm::llvm_shutdown();
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
);
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
;