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 upper_bound
212 * For each such pragma, intersect the context with the set
213 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
215 struct PragmaParameterHandler
: public PragmaHandler
{
218 isl_set
*&context_value
;
220 PragmaParameterHandler(Sema
&sema
, isl_set
*&context
,
221 isl_set
*&context_value
) :
222 PragmaHandler("parameter"), sema(sema
), context(context
),
223 context_value(context_value
) {}
225 virtual void HandlePragma(Preprocessor
&PP
,
226 PragmaIntroducerKind Introducer
,
229 isl_ctx
*ctx
= isl_set_get_ctx(context
);
238 vd
= get_value_decl(sema
, token
);
240 unsupported(PP
, token
.getLocation());
245 if (!token
.isLiteral()) {
246 unsupported(PP
, token
.getLocation());
250 lb
= get_int(token
.getLiteralData());
253 if (!token
.isLiteral()) {
254 unsupported(PP
, token
.getLocation());
258 ub
= get_int(token
.getLiteralData());
260 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
261 dim
= isl_space_params_alloc(ctx
, 1);
262 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
264 set
= isl_set_universe(dim
);
266 set
= isl_set_lower_bound_si(set
, isl_dim_param
, 0, lb
);
267 set
= isl_set_upper_bound_si(set
, isl_dim_param
, 0, ub
);
269 context
= isl_set_intersect(context
, set
);
271 context_value
= extract_initialization(context_value
, vd
);
275 /* Handle pragmas of the form
279 * In particular, store the current location in loc.start.
281 struct PragmaScopHandler
: public PragmaHandler
{
284 PragmaScopHandler(ScopLoc
&loc
) : PragmaHandler("scop"), loc(loc
) {}
286 virtual void HandlePragma(Preprocessor
&PP
,
287 PragmaIntroducerKind Introducer
,
289 SourceManager
&SM
= PP
.getSourceManager();
290 loc
.start
= SM
.getFileOffset(ScopTok
.getLocation());
294 /* Handle pragmas of the form
298 * In particular, store the current location in loc.end.
300 struct PragmaEndScopHandler
: public PragmaHandler
{
303 PragmaEndScopHandler(ScopLoc
&loc
) :
304 PragmaHandler("endscop"), loc(loc
) {}
306 virtual void HandlePragma(Preprocessor
&PP
,
307 PragmaIntroducerKind Introducer
,
309 SourceManager
&SM
= PP
.getSourceManager();
310 loc
.end
= SM
.getFileOffset(EndScopTok
.getLocation());
314 /* Handle pragmas of the form
316 * #pragma live-out identifier, identifier, ...
318 * Each identifier on the line is stored in live_out.
320 struct PragmaLiveOutHandler
: public PragmaHandler
{
322 set
<ValueDecl
*> &live_out
;
324 PragmaLiveOutHandler(Sema
&sema
, set
<ValueDecl
*> &live_out
) :
325 PragmaHandler("live"), sema(sema
), live_out(live_out
) {}
327 virtual void HandlePragma(Preprocessor
&PP
,
328 PragmaIntroducerKind Introducer
,
333 if (token
.isNot(tok::minus
))
336 if (token
.isNot(tok::identifier
) ||
337 !token
.getIdentifierInfo()->isStr("out"))
341 while (token
.isNot(tok::eod
)) {
344 vd
= get_value_decl(sema
, token
);
346 unsupported(PP
, token
.getLocation());
351 if (token
.is(tok::comma
))
357 /* Extract a pet_scop from the appropriate function.
358 * If "function" is not NULL, then we only extract a pet_scop if the
359 * name of the function matches.
360 * If "autodetect" is false, then we only extract if we have seen
361 * scop and endscop pragmas and if these are situated inside the function
364 struct PetASTConsumer
: public ASTConsumer
{
366 ASTContext
&ast_context
;
368 const char *function
;
371 struct pet_scop
*scop
;
373 PetASTConsumer(isl_ctx
*ctx
, Preprocessor
&PP
, ASTContext
&ast_context
,
374 ScopLoc
&loc
, const char *function
, bool autodetect
) :
375 ctx(ctx
), PP(PP
), ast_context(ast_context
), loc(loc
),
376 scop(NULL
), function(function
), autodetect(autodetect
) { }
378 virtual void HandleTopLevelDecl(DeclGroupRef dg
) {
379 DeclGroupRef::iterator it
;
383 for (it
= dg
.begin(); it
!= dg
.end(); ++it
) {
384 FunctionDecl
*fd
= dyn_cast
<clang::FunctionDecl
>(*it
);
390 fd
->getNameInfo().getAsString() != function
)
393 PetScan
ps(ctx
, PP
, ast_context
, loc
, 1);
402 SourceManager
&SM
= PP
.getSourceManager();
403 if (SM
.getFileOffset(fd
->getLocStart()) > loc
.end
)
405 if (SM
.getFileOffset(fd
->getLocEnd()) < loc
.start
)
407 PetScan
ps(ctx
, PP
, ast_context
, loc
, 0);
414 static const char *ResourceDir
= CLANG_PREFIX
"/lib/clang/"CLANG_VERSION_STRING
;
416 static const char *implicit_functions
[] = {
417 "min", "max", "ceild", "floord"
420 static bool is_implicit(const IdentifierInfo
*ident
)
422 const char *name
= ident
->getNameStart();
423 for (int i
= 0; i
< ARRAY_SIZE(implicit_functions
); ++i
)
424 if (!strcmp(name
, implicit_functions
[i
]))
429 /* Ignore implicit function declaration warnings on
430 * "min", "max", "ceild" and "floord" as we detect and handle these
433 struct MyDiagnosticPrinter
: public TextDiagnosticPrinter
{
434 const DiagnosticOptions
*DiagOpts
;
435 MyDiagnosticPrinter(const DiagnosticOptions
&DO
) :
436 DiagOpts(&DO
), TextDiagnosticPrinter(llvm::errs(), DO
) {}
437 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
438 return new MyDiagnosticPrinter(*DiagOpts
);
440 virtual void HandleDiagnostic(DiagnosticsEngine::Level level
,
441 const DiagnosticInfo
&info
) {
442 if (info
.getID() == diag::ext_implicit_function_decl
&&
443 info
.getNumArgs() == 1 &&
444 info
.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo
&&
445 is_implicit(info
.getArgIdentifier(0)))
446 /* ignore warning */;
448 TextDiagnosticPrinter::HandleDiagnostic(level
, info
);
452 static void update_arrays(struct pet_scop
*scop
,
453 map
<ValueDecl
*, isl_set
*> &value_bounds
,
454 set
<ValueDecl
*> &live_out
)
456 map
<ValueDecl
*, isl_set
*>::iterator vb_it
;
457 set
<ValueDecl
*>::iterator lo_it
;
462 for (int i
= 0; i
< scop
->n_array
; ++i
) {
465 pet_array
*array
= scop
->arrays
[i
];
467 id
= isl_set_get_tuple_id(array
->extent
);
468 decl
= (ValueDecl
*)isl_id_get_user(id
);
471 vb_it
= value_bounds
.find(decl
);
472 if (vb_it
!= value_bounds
.end())
473 array
->value_bounds
= isl_set_copy(vb_it
->second
);
475 lo_it
= live_out
.find(decl
);
476 if (lo_it
!= live_out
.end())
481 /* Extract a pet_scop from the C source file called "filename".
482 * If "function" is not NULL, extract the pet_scop from the function
484 * If "autodetect" is set, extract any pet_scop we can find.
485 * Otherwise, extract the pet_scop from the region delimited
486 * by "scop" and "endscop" pragmas.
488 * We first set up the clang parser and then try to extract the
489 * pet_scop from the appropriate function in PetASTConsumer.
490 * If we have found a pet_scop, we add the context and value_bounds
491 * constraints specified through pragmas.
493 struct pet_scop
*pet_scop_extract_from_C_source(isl_ctx
*ctx
,
494 const char *filename
, const char *function
, int autodetect
)
498 isl_set
*context_value
;
499 set
<ValueDecl
*> live_out
;
500 map
<ValueDecl
*, isl_set
*> value_bounds
;
501 map
<ValueDecl
*, isl_set
*>::iterator vb_it
;
503 CompilerInstance
*Clang
= new CompilerInstance();
504 DiagnosticOptions DO
;
505 Clang
->createDiagnostics(0, NULL
, new MyDiagnosticPrinter(DO
));
506 DiagnosticsEngine
&Diags
= Clang
->getDiagnostics();
507 Diags
.setSuppressSystemWarnings(true);
508 Clang
->createFileManager();
509 Clang
->createSourceManager(Clang
->getFileManager());
511 TO
.Triple
= llvm::sys::getHostTriple();
512 TargetInfo
*target
= TargetInfo::CreateTargetInfo(Diags
, TO
);
513 Clang
->setTarget(target
);
514 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
,
515 LangStandard::lang_unspecified
);
516 Clang
->getHeaderSearchOpts().ResourceDir
= ResourceDir
;
517 Clang
->createPreprocessor();
518 Preprocessor
&PP
= Clang
->getPreprocessor();
522 const FileEntry
*file
= Clang
->getFileManager().getFile(filename
);
524 isl_die(ctx
, isl_error_unknown
, "unable to open file",
526 Clang
->getSourceManager().createMainFileID(file
);
528 Clang
->createASTContext();
529 PetASTConsumer
consumer(ctx
, PP
, Clang
->getASTContext(),
530 loc
, function
, autodetect
);
531 Sema
*sema
= new Sema(PP
, Clang
->getASTContext(), consumer
);
534 PP
.AddPragmaHandler(new PragmaScopHandler(loc
));
535 PP
.AddPragmaHandler(new PragmaEndScopHandler(loc
));
536 PP
.AddPragmaHandler(new PragmaLiveOutHandler(*sema
, live_out
));
539 dim
= isl_space_params_alloc(ctx
, 0);
540 context
= isl_set_universe(isl_space_copy(dim
));
541 context_value
= isl_set_universe(dim
);
542 PP
.AddPragmaHandler(new PragmaParameterHandler(*sema
, context
,
544 PP
.AddPragmaHandler(new PragmaValueBoundsHandler(ctx
, *sema
, value_bounds
));
546 Diags
.getClient()->BeginSourceFile(Clang
->getLangOpts(), &PP
);
548 Diags
.getClient()->EndSourceFile();
552 llvm::llvm_shutdown();
555 consumer
.scop
->context
= isl_set_intersect(context
,
556 consumer
.scop
->context
);
557 consumer
.scop
->context_value
= isl_set_intersect(context_value
,
558 consumer
.scop
->context_value
);
560 isl_set_free(context
);
561 isl_set_free(context_value
);
564 update_arrays(consumer
.scop
, value_bounds
, live_out
);
566 for (vb_it
= value_bounds
.begin(); vb_it
!= value_bounds
.end(); vb_it
++)
567 isl_set_free(vb_it
->second
);
569 return consumer
.scop
;