2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
40 #include <llvm/Support/raw_ostream.h>
41 #include <llvm/Support/ManagedStatic.h>
42 #include <llvm/Support/Host.h>
43 #include <clang/Basic/Version.h>
44 #include <clang/Basic/FileSystemOptions.h>
45 #include <clang/Basic/FileManager.h>
46 #include <clang/Basic/TargetOptions.h>
47 #include <clang/Basic/TargetInfo.h>
48 #include <clang/Driver/Compilation.h>
49 #include <clang/Driver/Driver.h>
50 #include <clang/Driver/Tool.h>
51 #include <clang/Frontend/CompilerInstance.h>
52 #include <clang/Frontend/CompilerInvocation.h>
53 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
54 #include <clang/Basic/DiagnosticOptions.h>
56 #include <clang/Frontend/DiagnosticOptions.h>
58 #include <clang/Frontend/TextDiagnosticPrinter.h>
59 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
60 #include <clang/Lex/HeaderSearchOptions.h>
62 #include <clang/Frontend/HeaderSearchOptions.h>
64 #include <clang/Frontend/LangStandard.h>
65 #include <clang/Frontend/PreprocessorOptions.h>
66 #include <clang/Frontend/FrontendOptions.h>
67 #include <clang/Frontend/Utils.h>
68 #include <clang/Lex/HeaderSearch.h>
69 #include <clang/Lex/Preprocessor.h>
70 #include <clang/Lex/Pragma.h>
71 #include <clang/AST/ASTContext.h>
72 #include <clang/AST/ASTConsumer.h>
73 #include <clang/Sema/Sema.h>
74 #include <clang/Sema/SemaDiagnostic.h>
75 #include <clang/Parse/Parser.h>
76 #include <clang/Parse/ParseAST.h>
79 #include <isl/constraint.h>
84 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
87 using namespace clang
;
88 using namespace clang::driver
;
90 /* Called if we found something we didn't expect in one of the pragmas.
91 * We'll provide more informative warnings later.
93 static void unsupported(Preprocessor
&PP
, SourceLocation loc
)
95 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
96 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
98 DiagnosticBuilder B
= diag
.Report(loc
, id
);
101 static int get_int(const char *s
)
103 return s
[0] == '"' ? atoi(s
+ 1) : atoi(s
);
106 static ValueDecl
*get_value_decl(Sema
&sema
, Token
&token
)
108 IdentifierInfo
*name
;
111 if (token
.isNot(tok::identifier
))
114 name
= token
.getIdentifierInfo();
115 decl
= sema
.LookupSingleName(sema
.TUScope
, name
,
116 token
.getLocation(), Sema::LookupOrdinaryName
);
117 return decl
? cast_or_null
<ValueDecl
>(decl
) : NULL
;
120 /* Handle pragmas of the form
122 * #pragma value_bounds identifier lower_bound upper_bound
124 * For each such pragma, add a mapping
125 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
128 struct PragmaValueBoundsHandler
: public PragmaHandler
{
131 isl_union_map
*value_bounds
;
133 PragmaValueBoundsHandler(isl_ctx
*ctx
, Sema
&sema
) :
134 PragmaHandler("value_bounds"), ctx(ctx
), sema(sema
) {
135 isl_space
*space
= isl_space_params_alloc(ctx
, 0);
136 value_bounds
= isl_union_map_empty(space
);
139 ~PragmaValueBoundsHandler() {
140 isl_union_map_free(value_bounds
);
143 virtual void HandlePragma(Preprocessor
&PP
,
144 PragmaIntroducerKind Introducer
,
155 vd
= get_value_decl(sema
, token
);
157 unsupported(PP
, token
.getLocation());
162 if (!token
.isLiteral()) {
163 unsupported(PP
, token
.getLocation());
167 lb
= get_int(token
.getLiteralData());
170 if (!token
.isLiteral()) {
171 unsupported(PP
, token
.getLocation());
175 ub
= get_int(token
.getLiteralData());
177 dim
= isl_space_alloc(ctx
, 0, 0, 1);
178 map
= isl_map_universe(dim
);
179 map
= isl_map_lower_bound_si(map
, isl_dim_out
, 0, lb
);
180 map
= isl_map_upper_bound_si(map
, isl_dim_out
, 0, ub
);
181 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
182 map
= isl_map_set_tuple_id(map
, isl_dim_in
, id
);
184 value_bounds
= isl_union_map_add_map(value_bounds
, map
);
188 /* Given a variable declaration, check if it has an integer initializer
189 * and if so, add a parameter corresponding to the variable to "value"
190 * with its value fixed to the integer initializer and return the result.
192 static __isl_give isl_set
*extract_initialization(__isl_take isl_set
*value
,
204 vd
= cast
<VarDecl
>(decl
);
207 if (!vd
->getType()->isIntegerType())
209 expr
= vd
->getInit();
212 il
= cast
<IntegerLiteral
>(expr
);
216 ctx
= isl_set_get_ctx(value
);
217 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
218 space
= isl_space_params_alloc(ctx
, 1);
219 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0, id
);
220 set
= isl_set_universe(space
);
223 PetScan::extract_int(il
, &v
);
224 set
= isl_set_fix(set
, isl_dim_param
, 0, v
);
227 return isl_set_intersect(value
, set
);
230 /* Handle pragmas of the form
232 * #pragma parameter identifier lower_bound
234 * #pragma parameter identifier lower_bound upper_bound
236 * For each such pragma, intersect the context with the set
237 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
239 struct PragmaParameterHandler
: public PragmaHandler
{
242 isl_set
*&context_value
;
244 PragmaParameterHandler(Sema
&sema
, isl_set
*&context
,
245 isl_set
*&context_value
) :
246 PragmaHandler("parameter"), sema(sema
), context(context
),
247 context_value(context_value
) {}
249 virtual void HandlePragma(Preprocessor
&PP
,
250 PragmaIntroducerKind Introducer
,
253 isl_ctx
*ctx
= isl_set_get_ctx(context
);
263 vd
= get_value_decl(sema
, token
);
265 unsupported(PP
, token
.getLocation());
270 if (!token
.isLiteral()) {
271 unsupported(PP
, token
.getLocation());
275 lb
= get_int(token
.getLiteralData());
278 if (token
.isLiteral()) {
280 ub
= get_int(token
.getLiteralData());
281 } else if (token
.isNot(tok::eod
)) {
282 unsupported(PP
, token
.getLocation());
286 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
287 dim
= isl_space_params_alloc(ctx
, 1);
288 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
290 set
= isl_set_universe(dim
);
292 set
= isl_set_lower_bound_si(set
, isl_dim_param
, 0, lb
);
294 set
= isl_set_upper_bound_si(set
, isl_dim_param
, 0, ub
);
296 context
= isl_set_intersect(context
, set
);
298 context_value
= extract_initialization(context_value
, vd
);
302 /* Handle pragmas of the form
306 * In particular, store the current location in loc.start.
308 struct PragmaScopHandler
: public PragmaHandler
{
311 PragmaScopHandler(ScopLoc
&loc
) : PragmaHandler("scop"), loc(loc
) {}
313 virtual void HandlePragma(Preprocessor
&PP
,
314 PragmaIntroducerKind Introducer
,
316 SourceManager
&SM
= PP
.getSourceManager();
317 loc
.start
= SM
.getFileOffset(ScopTok
.getLocation());
321 /* Handle pragmas of the form
325 * In particular, store the current location in loc.end.
327 struct PragmaEndScopHandler
: public PragmaHandler
{
330 PragmaEndScopHandler(ScopLoc
&loc
) :
331 PragmaHandler("endscop"), loc(loc
) {}
333 virtual void HandlePragma(Preprocessor
&PP
,
334 PragmaIntroducerKind Introducer
,
336 SourceManager
&SM
= PP
.getSourceManager();
337 loc
.end
= SM
.getFileOffset(EndScopTok
.getLocation());
341 /* Handle pragmas of the form
343 * #pragma live-out identifier, identifier, ...
345 * Each identifier on the line is stored in live_out.
347 struct PragmaLiveOutHandler
: public PragmaHandler
{
349 set
<ValueDecl
*> &live_out
;
351 PragmaLiveOutHandler(Sema
&sema
, set
<ValueDecl
*> &live_out
) :
352 PragmaHandler("live"), sema(sema
), live_out(live_out
) {}
354 virtual void HandlePragma(Preprocessor
&PP
,
355 PragmaIntroducerKind Introducer
,
360 if (token
.isNot(tok::minus
))
363 if (token
.isNot(tok::identifier
) ||
364 !token
.getIdentifierInfo()->isStr("out"))
368 while (token
.isNot(tok::eod
)) {
371 vd
= get_value_decl(sema
, token
);
373 unsupported(PP
, token
.getLocation());
378 if (token
.is(tok::comma
))
384 /* Extract a pet_scop from the appropriate function.
385 * If "function" is not NULL, then we only extract a pet_scop if the
386 * name of the function matches.
387 * If "autodetect" is false, then we only extract if we have seen
388 * scop and endscop pragmas and if these are situated inside the function
391 struct PetASTConsumer
: public ASTConsumer
{
393 ASTContext
&ast_context
;
395 const char *function
;
396 pet_options
*options
;
398 struct pet_scop
*scop
;
399 PragmaValueBoundsHandler
*vb_handler
;
401 PetASTConsumer(isl_ctx
*ctx
, Preprocessor
&PP
, ASTContext
&ast_context
,
402 ScopLoc
&loc
, const char *function
, pet_options
*options
) :
403 ctx(ctx
), PP(PP
), ast_context(ast_context
), loc(loc
),
404 scop(NULL
), function(function
), options(options
),
407 void handle_value_bounds(Sema
*sema
) {
408 vb_handler
= new PragmaValueBoundsHandler(ctx
, *sema
);
409 PP
.AddPragmaHandler(vb_handler
);
412 __isl_give isl_union_map
*get_value_bounds() {
413 return isl_union_map_copy(vb_handler
->value_bounds
);
416 virtual HandleTopLevelDeclReturn
HandleTopLevelDecl(DeclGroupRef dg
) {
417 DeclGroupRef::iterator it
;
420 return HandleTopLevelDeclContinue
;
421 for (it
= dg
.begin(); it
!= dg
.end(); ++it
) {
422 isl_union_map
*vb
= vb_handler
->value_bounds
;
423 FunctionDecl
*fd
= dyn_cast
<clang::FunctionDecl
>(*it
);
429 fd
->getNameInfo().getAsString() != function
)
431 if (options
->autodetect
) {
432 PetScan
ps(PP
, ast_context
, loc
, options
,
433 isl_union_map_copy(vb
));
442 SourceManager
&SM
= PP
.getSourceManager();
443 if (SM
.getFileOffset(fd
->getLocStart()) > loc
.end
)
445 if (SM
.getFileOffset(fd
->getLocEnd()) < loc
.start
)
447 PetScan
ps(PP
, ast_context
, loc
, options
,
448 isl_union_map_copy(vb
));
453 return HandleTopLevelDeclContinue
;
457 static const char *ResourceDir
= CLANG_PREFIX
"/lib/clang/"CLANG_VERSION_STRING
;
459 static const char *implicit_functions
[] = {
460 "min", "max", "ceild", "floord"
463 static bool is_implicit(const IdentifierInfo
*ident
)
465 const char *name
= ident
->getNameStart();
466 for (int i
= 0; i
< ARRAY_SIZE(implicit_functions
); ++i
)
467 if (!strcmp(name
, implicit_functions
[i
]))
472 /* Ignore implicit function declaration warnings on
473 * "min", "max", "ceild" and "floord" as we detect and handle these
476 * The cloned field keeps track of whether the clone method
477 * has ever been called. Newer clangs (by default) clone
478 * the DiagnosticConsumer passed to createDiagnostics and
479 * then take ownership of the clone, which means that
480 * the original has to be deleted by the calling code.
482 struct MyDiagnosticPrinter
: public TextDiagnosticPrinter
{
483 const DiagnosticOptions
*DiagOpts
;
485 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
486 MyDiagnosticPrinter(DiagnosticOptions
*DO
) :
487 TextDiagnosticPrinter(llvm::errs(), DO
) {}
488 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
490 return new MyDiagnosticPrinter(&Diags
.getDiagnosticOptions());
493 MyDiagnosticPrinter(const DiagnosticOptions
&DO
) :
494 DiagOpts(&DO
), TextDiagnosticPrinter(llvm::errs(), DO
) {}
495 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
497 return new MyDiagnosticPrinter(*DiagOpts
);
500 virtual void HandleDiagnostic(DiagnosticsEngine::Level level
,
501 const DiagnosticInfo
&info
) {
502 if (info
.getID() == diag::ext_implicit_function_decl
&&
503 info
.getNumArgs() == 1 &&
504 info
.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo
&&
505 is_implicit(info
.getArgIdentifier(0)))
506 /* ignore warning */;
508 TextDiagnosticPrinter::HandleDiagnostic(level
, info
);
512 bool MyDiagnosticPrinter::cloned
= false;
514 /* For each array in "scop", set its value_bounds property
515 * based on the infofrmation in "value_bounds" and
516 * mark it as live_out if it appears in "live_out".
518 static void update_arrays(struct pet_scop
*scop
,
519 __isl_take isl_union_map
*value_bounds
, set
<ValueDecl
*> &live_out
)
521 set
<ValueDecl
*>::iterator lo_it
;
522 isl_ctx
*ctx
= isl_union_map_get_ctx(value_bounds
);
525 isl_union_map_free(value_bounds
);
529 for (int i
= 0; i
< scop
->n_array
; ++i
) {
534 pet_array
*array
= scop
->arrays
[i
];
536 id
= isl_set_get_tuple_id(array
->extent
);
537 decl
= (ValueDecl
*)isl_id_get_user(id
);
539 space
= isl_space_alloc(ctx
, 0, 0, 1);
540 space
= isl_space_set_tuple_id(space
, isl_dim_in
, id
);
542 bounds
= isl_union_map_extract_map(value_bounds
, space
);
543 if (!isl_map_plain_is_empty(bounds
))
544 array
->value_bounds
= isl_map_range(bounds
);
546 isl_map_free(bounds
);
548 lo_it
= live_out
.find(decl
);
549 if (lo_it
!= live_out
.end())
553 isl_union_map_free(value_bounds
);
558 #ifdef HAVE_CXXISPRODUCTION
559 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
561 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
562 "", false, false, Diags
);
565 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
567 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
572 /* Create a CompilerInvocation object that stores the command line
573 * arguments constructed by the driver.
574 * The arguments are mainly useful for setting up the system include
575 * paths on newer clangs and on some platforms.
577 static CompilerInvocation
*construct_invocation(const char *filename
,
578 DiagnosticsEngine
&Diags
)
580 const char *binary
= CLANG_PREFIX
"/bin/clang";
581 const llvm::OwningPtr
<Driver
> driver(construct_driver(binary
, Diags
));
582 std::vector
<const char *> Argv
;
583 Argv
.push_back(binary
);
584 Argv
.push_back(filename
);
585 const llvm::OwningPtr
<Compilation
> compilation(
586 driver
->BuildCompilation(llvm::ArrayRef
<const char *>(Argv
)));
587 JobList
&Jobs
= compilation
->getJobs();
591 Command
*cmd
= cast
<Command
>(*Jobs
.begin());
592 if (strcmp(cmd
->getCreator().getName(), "clang"))
595 const ArgStringList
*args
= &cmd
->getArguments();
597 CompilerInvocation
*invocation
= new CompilerInvocation
;
598 CompilerInvocation::CreateFromArgs(*invocation
, args
->data() + 1,
599 args
->data() + args
->size(),
606 static CompilerInvocation
*construct_invocation(const char *filename
,
607 DiagnosticsEngine
&Diags
)
614 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
616 static MyDiagnosticPrinter
*construct_printer(void)
618 return new MyDiagnosticPrinter(new DiagnosticOptions());
623 static MyDiagnosticPrinter
*construct_printer(void)
625 DiagnosticOptions DO
;
626 return new MyDiagnosticPrinter(DO
);
631 /* Extract a pet_scop from the C source file called "filename".
632 * If "function" is not NULL, extract the pet_scop from the function
634 * If "autodetect" is set, extract any pet_scop we can find.
635 * Otherwise, extract the pet_scop from the region delimited
636 * by "scop" and "endscop" pragmas.
638 * We first set up the clang parser and then try to extract the
639 * pet_scop from the appropriate function in PetASTConsumer.
640 * If we have found a pet_scop, we add the context and value_bounds
641 * constraints specified through pragmas.
643 static struct pet_scop
*scop_extract_from_C_source(isl_ctx
*ctx
,
644 const char *filename
, const char *function
, pet_options
*options
)
648 isl_set
*context_value
;
650 set
<ValueDecl
*> live_out
;
651 isl_union_map
*value_bounds
;
653 CompilerInstance
*Clang
= new CompilerInstance();
654 MyDiagnosticPrinter
*printer
= construct_printer();
655 Clang
->createDiagnostics(0, NULL
, printer
);
658 DiagnosticsEngine
&Diags
= Clang
->getDiagnostics();
659 Diags
.setSuppressSystemWarnings(true);
660 CompilerInvocation
*invocation
= construct_invocation(filename
, Diags
);
662 Clang
->setInvocation(invocation
);
663 Clang
->createFileManager();
664 Clang
->createSourceManager(Clang
->getFileManager());
665 TargetOptions
&TO
= Clang
->getTargetOpts();
666 TO
.Triple
= llvm::sys::getDefaultTargetTriple();
667 TargetInfo
*target
= TargetInfo::CreateTargetInfo(Diags
, TO
);
668 Clang
->setTarget(target
);
669 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
,
670 LangStandard::lang_unspecified
);
671 HeaderSearchOptions
&HSO
= Clang
->getHeaderSearchOpts();
672 HSO
.ResourceDir
= ResourceDir
;
673 for (int i
= 0; i
< options
->n_path
; ++i
)
674 HSO
.AddPath(options
->paths
[i
],
675 frontend::Angled
, true, false, false);
676 PreprocessorOptions
&PO
= Clang
->getPreprocessorOpts();
677 for (int i
= 0; i
< options
->n_define
; ++i
)
678 PO
.addMacroDef(options
->defines
[i
]);
679 Clang
->createPreprocessor();
680 Preprocessor
&PP
= Clang
->getPreprocessor();
684 const FileEntry
*file
= Clang
->getFileManager().getFile(filename
);
686 isl_die(ctx
, isl_error_unknown
, "unable to open file",
687 do { delete Clang
; return NULL
; } while (0));
688 Clang
->getSourceManager().createMainFileID(file
);
690 Clang
->createASTContext();
691 PetASTConsumer
consumer(ctx
, PP
, Clang
->getASTContext(),
692 loc
, function
, options
);
693 Sema
*sema
= new Sema(PP
, Clang
->getASTContext(), consumer
);
695 if (!options
->autodetect
) {
696 PP
.AddPragmaHandler(new PragmaScopHandler(loc
));
697 PP
.AddPragmaHandler(new PragmaEndScopHandler(loc
));
698 PP
.AddPragmaHandler(new PragmaLiveOutHandler(*sema
, live_out
));
701 dim
= isl_space_params_alloc(ctx
, 0);
702 context
= isl_set_universe(isl_space_copy(dim
));
703 context_value
= isl_set_universe(dim
);
704 PP
.AddPragmaHandler(new PragmaParameterHandler(*sema
, context
,
706 consumer
.handle_value_bounds(sema
);
708 Diags
.getClient()->BeginSourceFile(Clang
->getLangOpts(), &PP
);
710 Diags
.getClient()->EndSourceFile();
712 scop
= consumer
.scop
;
713 if (Diags
.hasErrorOccurred()) {
719 scop
->context
= isl_set_intersect(context
, scop
->context
);
720 scop
->context_value
= isl_set_intersect(context_value
,
721 scop
->context_value
);
723 isl_set_free(context
);
724 isl_set_free(context_value
);
727 scop
= pet_scop_anonymize(scop
);
729 update_arrays(scop
, consumer
.get_value_bounds(), live_out
);
737 struct pet_scop
*pet_scop_extract_from_C_source(isl_ctx
*ctx
,
738 const char *filename
, const char *function
)
741 pet_options
*options
;
742 bool allocated
= false;
744 options
= isl_ctx_peek_pet_options(ctx
);
746 options
= pet_options_new_with_defaults();
750 scop
= scop_extract_from_C_source(ctx
, filename
, function
, options
);
751 llvm::llvm_shutdown();
754 pet_options_free(options
);