2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 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
41 #ifdef HAVE_ADT_OWNINGPTR_H
42 #include <llvm/ADT/OwningPtr.h>
46 #ifdef HAVE_LLVM_OPTION_ARG_H
47 #include <llvm/Option/Arg.h>
49 #include <llvm/Support/raw_ostream.h>
50 #include <llvm/Support/ManagedStatic.h>
51 #include <llvm/Support/Host.h>
52 #include <clang/Basic/Version.h>
53 #include <clang/Basic/FileSystemOptions.h>
54 #include <clang/Basic/FileManager.h>
55 #include <clang/Basic/TargetOptions.h>
56 #include <clang/Basic/TargetInfo.h>
57 #include <clang/Driver/Compilation.h>
58 #include <clang/Driver/Driver.h>
59 #include <clang/Driver/Tool.h>
60 #include <clang/Frontend/CompilerInstance.h>
61 #include <clang/Frontend/CompilerInvocation.h>
62 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
63 #include <clang/Basic/DiagnosticOptions.h>
65 #include <clang/Frontend/DiagnosticOptions.h>
67 #include <clang/Frontend/TextDiagnosticPrinter.h>
68 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
69 #include <clang/Lex/HeaderSearchOptions.h>
71 #include <clang/Frontend/HeaderSearchOptions.h>
73 #ifdef HAVE_CLANG_BASIC_LANGSTANDARD_H
74 #include <clang/Basic/LangStandard.h>
76 #include <clang/Frontend/LangStandard.h>
78 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
79 #include <clang/Lex/PreprocessorOptions.h>
81 #include <clang/Frontend/PreprocessorOptions.h>
83 #include <clang/Frontend/FrontendOptions.h>
84 #include <clang/Frontend/Utils.h>
85 #include <clang/Lex/HeaderSearch.h>
86 #include <clang/Lex/Preprocessor.h>
87 #include <clang/Lex/Pragma.h>
88 #include <clang/AST/ASTContext.h>
89 #include <clang/AST/ASTConsumer.h>
90 #include <clang/Sema/Sema.h>
91 #include <clang/Sema/SemaDiagnostic.h>
92 #include <clang/Parse/Parser.h>
93 #include <clang/Parse/ParseAST.h>
96 #include <isl/constraint.h>
100 #include "clang_compatibility.h"
106 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
109 using namespace clang
;
110 using namespace clang::driver
;
111 #ifdef HAVE_LLVM_OPTION_ARG_H
112 using namespace llvm::opt
;
115 #ifdef HAVE_ADT_OWNINGPTR_H
116 #define unique_ptr llvm::OwningPtr
119 /* Called if we found something we didn't expect in one of the pragmas.
120 * We'll provide more informative warnings later.
122 static void unsupported(Preprocessor
&PP
, SourceLocation loc
)
124 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
125 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
127 DiagnosticBuilder B
= diag
.Report(loc
, id
);
130 static int get_int(const char *s
)
132 return s
[0] == '"' ? atoi(s
+ 1) : atoi(s
);
135 static ValueDecl
*get_value_decl(Sema
&sema
, Token
&token
)
137 IdentifierInfo
*name
;
140 if (token
.isNot(tok::identifier
))
143 name
= token
.getIdentifierInfo();
144 decl
= sema
.LookupSingleName(sema
.TUScope
, name
,
145 token
.getLocation(), Sema::LookupOrdinaryName
);
146 return decl
? cast_or_null
<ValueDecl
>(decl
) : NULL
;
149 /* Handle pragmas of the form
151 * #pragma value_bounds identifier lower_bound upper_bound
153 * For each such pragma, add a mapping
154 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
157 struct PragmaValueBoundsHandler
: public PragmaHandler
{
160 isl_union_map
*value_bounds
;
162 PragmaValueBoundsHandler(isl_ctx
*ctx
, Sema
&sema
) :
163 PragmaHandler("value_bounds"), sema(sema
), ctx(ctx
) {
164 isl_space
*space
= isl_space_params_alloc(ctx
, 0);
165 value_bounds
= isl_union_map_empty(space
);
168 ~PragmaValueBoundsHandler() {
169 isl_union_map_free(value_bounds
);
172 virtual void HandlePragma(Preprocessor
&PP
,
173 PragmaIntroducer Introducer
,
184 vd
= get_value_decl(sema
, token
);
186 unsupported(PP
, token
.getLocation());
191 if (!token
.isLiteral()) {
192 unsupported(PP
, token
.getLocation());
196 lb
= get_int(token
.getLiteralData());
199 if (!token
.isLiteral()) {
200 unsupported(PP
, token
.getLocation());
204 ub
= get_int(token
.getLiteralData());
206 dim
= isl_space_alloc(ctx
, 0, 0, 1);
207 map
= isl_map_universe(dim
);
208 map
= isl_map_lower_bound_si(map
, isl_dim_out
, 0, lb
);
209 map
= isl_map_upper_bound_si(map
, isl_dim_out
, 0, ub
);
210 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
211 map
= isl_map_set_tuple_id(map
, isl_dim_in
, id
);
213 value_bounds
= isl_union_map_add_map(value_bounds
, map
);
217 /* Given a variable declaration, check if it has an integer initializer
218 * and if so, add a parameter corresponding to the variable to "value"
219 * with its value fixed to the integer initializer and return the result.
221 static __isl_give isl_set
*extract_initialization(__isl_take isl_set
*value
,
233 vd
= cast
<VarDecl
>(decl
);
236 if (!vd
->getType()->isIntegerType())
238 expr
= vd
->getInit();
241 il
= cast
<IntegerLiteral
>(expr
);
245 ctx
= isl_set_get_ctx(value
);
246 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
247 space
= isl_space_params_alloc(ctx
, 1);
248 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0, id
);
249 set
= isl_set_universe(space
);
251 v
= PetScan::extract_int(ctx
, il
);
252 set
= isl_set_fix_val(set
, isl_dim_param
, 0, v
);
254 return isl_set_intersect(value
, set
);
257 /* Handle pragmas of the form
259 * #pragma parameter identifier lower_bound
261 * #pragma parameter identifier lower_bound upper_bound
263 * For each such pragma, intersect the context with the set
264 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
266 struct PragmaParameterHandler
: public PragmaHandler
{
269 isl_set
*&context_value
;
271 PragmaParameterHandler(Sema
&sema
, isl_set
*&context
,
272 isl_set
*&context_value
) :
273 PragmaHandler("parameter"), sema(sema
), context(context
),
274 context_value(context_value
) {}
276 virtual void HandlePragma(Preprocessor
&PP
,
277 PragmaIntroducer Introducer
,
280 isl_ctx
*ctx
= isl_set_get_ctx(context
);
290 vd
= get_value_decl(sema
, token
);
292 unsupported(PP
, token
.getLocation());
297 if (!token
.isLiteral()) {
298 unsupported(PP
, token
.getLocation());
302 lb
= get_int(token
.getLiteralData());
305 if (token
.isLiteral()) {
307 ub
= get_int(token
.getLiteralData());
308 } else if (token
.isNot(tok::eod
)) {
309 unsupported(PP
, token
.getLocation());
313 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
314 dim
= isl_space_params_alloc(ctx
, 1);
315 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
317 set
= isl_set_universe(dim
);
319 set
= isl_set_lower_bound_si(set
, isl_dim_param
, 0, lb
);
321 set
= isl_set_upper_bound_si(set
, isl_dim_param
, 0, ub
);
323 context
= isl_set_intersect(context
, set
);
325 context_value
= extract_initialization(context_value
, vd
);
329 /* Handle pragmas of the form
331 * #pragma pencil independent
333 * For each such pragma, add an entry to the "independent" vector.
335 struct PragmaPencilHandler
: public PragmaHandler
{
336 std::vector
<Independent
> &independent
;
338 PragmaPencilHandler(std::vector
<Independent
> &independent
) :
339 PragmaHandler("pencil"), independent(independent
) {}
341 virtual void HandlePragma(Preprocessor
&PP
,
342 PragmaIntroducer Introducer
,
345 IdentifierInfo
*info
;
348 if (token
.isNot(tok::identifier
))
351 info
= token
.getIdentifierInfo();
352 if (!info
->isStr("independent"))
356 if (token
.isNot(tok::eod
))
359 SourceManager
&SM
= PP
.getSourceManager();
360 SourceLocation sloc
= PencilTok
.getLocation();
361 unsigned line
= SM
.getExpansionLineNumber(sloc
);
362 independent
.push_back(Independent(line
));
366 #ifdef HAVE_TRANSLATELINECOL
368 /* Return a SourceLocation for line "line", column "col" of file "FID".
370 SourceLocation
translateLineCol(SourceManager
&SM
, FileID FID
, unsigned line
,
373 return SM
.translateLineCol(FID
, line
, col
);
378 /* Return a SourceLocation for line "line", column "col" of file "FID".
380 SourceLocation
translateLineCol(SourceManager
&SM
, FileID FID
, unsigned line
,
383 return SM
.getLocation(SM
.getFileEntryForID(FID
), line
, col
);
388 /* List of pairs of #pragma scop and #pragma endscop locations.
391 std::vector
<ScopLoc
> list
;
393 /* Add a new start (#pragma scop) location to the list.
394 * If the last #pragma scop did not have a matching
395 * #pragma endscop then overwrite it.
396 * "start" points to the location of the scop pragma.
398 void add_start(SourceManager
&SM
, SourceLocation start
) {
402 int line
= SM
.getExpansionLineNumber(start
);
403 start
= translateLineCol(SM
, SM
.getFileID(start
), line
, 1);
404 loc
.start_line
= line
;
405 loc
.start
= SM
.getFileOffset(start
);
406 if (list
.size() == 0 || list
[list
.size() - 1].end
!= 0)
409 list
[list
.size() - 1] = loc
;
412 /* Set the end location (#pragma endscop) of the last pair
414 * If there is no such pair of if the end of that pair
415 * is already set, then ignore the spurious #pragma endscop.
416 * "end" points to the location of the endscop pragma.
418 void add_end(SourceManager
&SM
, SourceLocation end
) {
419 if (list
.size() == 0 || list
[list
.size() - 1].end
!= 0)
421 list
[list
.size() - 1].endscop
= end
;
422 int line
= SM
.getExpansionLineNumber(end
);
423 end
= translateLineCol(SM
, SM
.getFileID(end
), line
+ 1, 1);
424 list
[list
.size() - 1].end
= SM
.getFileOffset(end
);
428 /* Handle pragmas of the form
432 * In particular, store the location of the line containing
433 * the pragma in the list "scops".
435 struct PragmaScopHandler
: public PragmaHandler
{
438 PragmaScopHandler(ScopLocList
&scops
) :
439 PragmaHandler("scop"), scops(scops
) {}
441 virtual void HandlePragma(Preprocessor
&PP
,
442 PragmaIntroducer Introducer
,
444 SourceManager
&SM
= PP
.getSourceManager();
445 SourceLocation sloc
= ScopTok
.getLocation();
446 scops
.add_start(SM
, sloc
);
450 /* Handle pragmas of the form
454 * In particular, store the location of the line following the one containing
455 * the pragma in the list "scops".
457 struct PragmaEndScopHandler
: public PragmaHandler
{
460 PragmaEndScopHandler(ScopLocList
&scops
) :
461 PragmaHandler("endscop"), scops(scops
) {}
463 virtual void HandlePragma(Preprocessor
&PP
,
464 PragmaIntroducer Introducer
,
466 SourceManager
&SM
= PP
.getSourceManager();
467 SourceLocation sloc
= EndScopTok
.getLocation();
468 scops
.add_end(SM
, sloc
);
472 /* Handle pragmas of the form
474 * #pragma live-out identifier, identifier, ...
476 * Each identifier on the line is stored in live_out.
478 struct PragmaLiveOutHandler
: public PragmaHandler
{
480 set
<ValueDecl
*> &live_out
;
482 PragmaLiveOutHandler(Sema
&sema
, set
<ValueDecl
*> &live_out
) :
483 PragmaHandler("live"), sema(sema
), live_out(live_out
) {}
485 virtual void HandlePragma(Preprocessor
&PP
,
486 PragmaIntroducer Introducer
,
491 if (token
.isNot(tok::minus
))
494 if (token
.isNot(tok::identifier
) ||
495 !token
.getIdentifierInfo()->isStr("out"))
499 while (token
.isNot(tok::eod
)) {
502 vd
= get_value_decl(sema
, token
);
504 unsupported(PP
, token
.getLocation());
509 if (token
.is(tok::comma
))
515 /* For each array in "scop", set its value_bounds property
516 * based on the information in "value_bounds" and
517 * mark it as live_out if it appears in "live_out".
519 static void update_arrays(struct pet_scop
*scop
,
520 __isl_take isl_union_map
*value_bounds
, set
<ValueDecl
*> &live_out
)
522 set
<ValueDecl
*>::iterator lo_it
;
523 isl_ctx
*ctx
= isl_union_map_get_ctx(value_bounds
);
526 isl_union_map_free(value_bounds
);
530 for (int i
= 0; i
< scop
->n_array
; ++i
) {
535 pet_array
*array
= scop
->arrays
[i
];
537 id
= isl_set_get_tuple_id(array
->extent
);
538 decl
= pet_id_get_decl(id
);
540 space
= isl_space_alloc(ctx
, 0, 0, 1);
541 space
= isl_space_set_tuple_id(space
, isl_dim_in
, id
);
543 bounds
= isl_union_map_extract_map(value_bounds
, space
);
544 if (!isl_map_plain_is_empty(bounds
))
545 array
->value_bounds
= isl_map_range(bounds
);
547 isl_map_free(bounds
);
549 lo_it
= live_out
.find(decl
);
550 if (lo_it
!= live_out
.end())
554 isl_union_map_free(value_bounds
);
557 /* Extract a pet_scop (if any) from each appropriate function.
558 * Each detected scop is passed to "fn".
559 * When autodetecting, at most one scop is extracted from each function.
560 * If "function" is not NULL, then we only extract a pet_scop if the
561 * name of the function matches.
562 * If "autodetect" is false, then we only extract if we have seen
563 * scop and endscop pragmas and if these are situated inside the function
566 struct PetASTConsumer
: public ASTConsumer
{
568 ASTContext
&ast_context
;
569 DiagnosticsEngine
&diags
;
571 std::vector
<Independent
> independent
;
572 const char *function
;
573 pet_options
*options
;
576 isl_set
*context_value
;
577 set
<ValueDecl
*> live_out
;
578 PragmaValueBoundsHandler
*vb_handler
;
579 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
);
583 PetASTConsumer(isl_ctx
*ctx
, Preprocessor
&PP
, ASTContext
&ast_context
,
584 DiagnosticsEngine
&diags
, ScopLocList
&scops
,
585 const char *function
, pet_options
*options
,
586 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
) :
587 PP(PP
), ast_context(ast_context
), diags(diags
),
588 scops(scops
), function(function
), options(options
),
590 vb_handler(NULL
), fn(fn
), user(user
), error(false)
593 space
= isl_space_params_alloc(ctx
, 0);
594 context
= isl_set_universe(isl_space_copy(space
));
595 context_value
= isl_set_universe(space
);
599 isl_set_free(context
);
600 isl_set_free(context_value
);
603 void handle_value_bounds(Sema
*sema
) {
604 vb_handler
= new PragmaValueBoundsHandler(ctx
, *sema
);
605 PP
.AddPragmaHandler(vb_handler
);
608 /* Add all pragma handlers to this->PP.
609 * The pencil pragmas are only handled if the pencil option is set.
611 void add_pragma_handlers(Sema
*sema
) {
612 PP
.AddPragmaHandler(new PragmaParameterHandler(*sema
, context
,
614 if (options
->pencil
) {
616 PH
= new PragmaPencilHandler(independent
);
617 PP
.AddPragmaHandler(PH
);
619 handle_value_bounds(sema
);
622 __isl_give isl_union_map
*get_value_bounds() {
623 return isl_union_map_copy(vb_handler
->value_bounds
);
626 /* Pass "scop" to "fn" after performing some postprocessing.
627 * In particular, add the context and value_bounds constraints
628 * speficied through pragmas, add reference identifiers and
629 * reset user pointers on parameters and tuple ids.
631 * If "scop" does not contain any statements and autodetect
632 * is turned on, then skip it.
634 void call_fn(pet_scop
*scop
) {
639 if (diags
.hasErrorOccurred()) {
644 if (options
->autodetect
&& scop
->n_stmt
== 0) {
648 scop
->context
= isl_set_intersect(scop
->context
,
649 isl_set_copy(context
));
650 scop
->context_value
= isl_set_intersect(scop
->context_value
,
651 isl_set_copy(context_value
));
653 update_arrays(scop
, get_value_bounds(), live_out
);
655 scop
= pet_scop_add_ref_ids(scop
);
656 scop
= pet_scop_anonymize(scop
);
658 if (fn(scop
, user
) < 0)
662 /* For each explicitly marked scop (using pragmas),
663 * extract the scop and call "fn" on it if it is inside "fd".
665 void scan_scops(FunctionDecl
*fd
) {
667 vector
<ScopLoc
>::iterator it
;
668 isl_union_map
*vb
= vb_handler
->value_bounds
;
669 SourceManager
&SM
= PP
.getSourceManager();
672 if (scops
.list
.size() == 0)
675 start
= SM
.getFileOffset(begin_loc(fd
));
676 end
= SM
.getFileOffset(end_loc(fd
));
678 for (it
= scops
.list
.begin(); it
!= scops
.list
.end(); ++it
) {
686 PetScan
ps(PP
, ast_context
, fd
, loc
, options
,
687 isl_union_map_copy(vb
), independent
);
693 virtual HandleTopLevelDeclReturn
HandleTopLevelDecl(DeclGroupRef dg
) {
694 DeclGroupRef::iterator it
;
697 return HandleTopLevelDeclContinue
;
699 for (it
= dg
.begin(); it
!= dg
.end(); ++it
) {
700 isl_union_map
*vb
= vb_handler
->value_bounds
;
701 FunctionDecl
*fd
= dyn_cast
<clang::FunctionDecl
>(*it
);
707 fd
->getNameInfo().getAsString() != function
)
709 if (options
->autodetect
) {
712 PetScan
ps(PP
, ast_context
, fd
, loc
, options
,
713 isl_union_map_copy(vb
),
724 return HandleTopLevelDeclContinue
;
728 static const char *ResourceDir
=
729 CLANG_PREFIX
"/lib/clang/" CLANG_VERSION_STRING
;
731 static const char *implicit_functions
[] = {
732 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
734 static const char *pencil_implicit_functions
[] = {
735 "imin", "umin", "imax", "umax", "__pencil_kill"
738 /* Should "ident" be treated as an implicit function?
739 * If "pencil" is set, then also allow pencil specific builtins.
741 static bool is_implicit(const IdentifierInfo
*ident
, int pencil
)
743 const char *name
= ident
->getNameStart();
744 for (size_t i
= 0; i
< ARRAY_SIZE(implicit_functions
); ++i
)
745 if (!strcmp(name
, implicit_functions
[i
]))
749 for (size_t i
= 0; i
< ARRAY_SIZE(pencil_implicit_functions
); ++i
)
750 if (!strcmp(name
, pencil_implicit_functions
[i
]))
755 /* Ignore implicit function declaration warnings on
756 * "min", "max", "ceild" and "floord" as we detect and handle these
758 * If "pencil" is set, then also ignore them on pencil specific
761 struct MyDiagnosticPrinter
: public TextDiagnosticPrinter
{
762 const DiagnosticOptions
*DiagOpts
;
764 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
765 MyDiagnosticPrinter(DiagnosticOptions
*DO
, int pencil
) :
766 TextDiagnosticPrinter(llvm::errs(), DO
), pencil(pencil
) {}
767 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
768 return new MyDiagnosticPrinter(&Diags
.getDiagnosticOptions(),
772 MyDiagnosticPrinter(const DiagnosticOptions
&DO
, int pencil
) :
773 DiagOpts(&DO
), TextDiagnosticPrinter(llvm::errs(), DO
),
775 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
776 return new MyDiagnosticPrinter(*DiagOpts
, pencil
);
779 virtual void HandleDiagnostic(DiagnosticsEngine::Level level
,
780 const DiagnosticInfo
&info
) {
781 if (info
.getID() == diag::ext_implicit_function_decl
&&
782 info
.getNumArgs() >= 1 &&
783 info
.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo
&&
784 is_implicit(info
.getArgIdentifier(0), pencil
))
785 /* ignore warning */;
787 TextDiagnosticPrinter::HandleDiagnostic(level
, info
);
793 #ifdef HAVE_CXXISPRODUCTION
794 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
796 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
797 "", false, false, Diags
);
799 #elif defined(HAVE_ISPRODUCTION)
800 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
802 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
805 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
806 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
808 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
812 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
814 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(), Diags
);
818 namespace clang
{ namespace driver
{ class Job
; } }
820 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
821 * We fix this with a simple overloaded function here.
824 static Job
*command(Job
*J
) { return J
; }
825 static Job
*command(Job
&J
) { return &J
; }
826 static Command
*command(Command
&C
) { return &C
; }
829 /* Create a CompilerInvocation object that stores the command line
830 * arguments constructed by the driver.
831 * The arguments are mainly useful for setting up the system include
832 * paths on newer clangs and on some platforms.
834 static CompilerInvocation
*construct_invocation(const char *filename
,
835 DiagnosticsEngine
&Diags
)
837 const char *binary
= CLANG_PREFIX
"/bin/clang";
838 const unique_ptr
<Driver
> driver(construct_driver(binary
, Diags
));
839 std::vector
<const char *> Argv
;
840 Argv
.push_back(binary
);
841 Argv
.push_back(filename
);
842 const unique_ptr
<Compilation
> compilation(
843 driver
->BuildCompilation(llvm::ArrayRef
<const char *>(Argv
)));
844 JobList
&Jobs
= compilation
->getJobs();
848 Command
*cmd
= cast
<Command
>(ClangAPI::command(*Jobs
.begin()));
849 if (strcmp(cmd
->getCreator().getName(), "clang"))
852 const ArgStringList
*args
= &cmd
->getArguments();
854 CompilerInvocation
*invocation
= new CompilerInvocation
;
855 CompilerInvocation::CreateFromArgs(*invocation
, args
->data() + 1,
856 args
->data() + args
->size(),
863 static CompilerInvocation
*construct_invocation(const char *filename
,
864 DiagnosticsEngine
&Diags
)
871 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
873 static MyDiagnosticPrinter
*construct_printer(CompilerInstance
*Clang
,
876 return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil
);
881 static MyDiagnosticPrinter
*construct_printer(CompilerInstance
*Clang
,
884 return new MyDiagnosticPrinter(Clang
->getDiagnosticOpts(), pencil
);
889 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
891 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
892 DiagnosticsEngine
&Diags
)
894 shared_ptr
<TargetOptions
> TO
= Clang
->getInvocation().TargetOpts
;
895 TO
->Triple
= llvm::sys::getDefaultTargetTriple();
896 return TargetInfo::CreateTargetInfo(Diags
, TO
);
899 #elif defined(CREATETARGETINFO_TAKES_POINTER)
901 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
902 DiagnosticsEngine
&Diags
)
904 TargetOptions
&TO
= Clang
->getTargetOpts();
905 TO
.Triple
= llvm::sys::getDefaultTargetTriple();
906 return TargetInfo::CreateTargetInfo(Diags
, &TO
);
911 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
912 DiagnosticsEngine
&Diags
)
914 TargetOptions
&TO
= Clang
->getTargetOpts();
915 TO
.Triple
= llvm::sys::getDefaultTargetTriple();
916 return TargetInfo::CreateTargetInfo(Diags
, TO
);
921 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
923 static void create_diagnostics(CompilerInstance
*Clang
)
925 Clang
->createDiagnostics(0, NULL
);
930 static void create_diagnostics(CompilerInstance
*Clang
)
932 Clang
->createDiagnostics();
937 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
939 static void create_preprocessor(CompilerInstance
*Clang
)
941 Clang
->createPreprocessor(TU_Complete
);
946 static void create_preprocessor(CompilerInstance
*Clang
)
948 Clang
->createPreprocessor();
953 #ifdef ADDPATH_TAKES_4_ARGUMENTS
955 void add_path(HeaderSearchOptions
&HSO
, string Path
)
957 HSO
.AddPath(Path
, frontend::Angled
, false, false);
962 void add_path(HeaderSearchOptions
&HSO
, string Path
)
964 HSO
.AddPath(Path
, frontend::Angled
, true, false, false);
969 #ifdef HAVE_SETMAINFILEID
971 static void create_main_file_id(SourceManager
&SM
, const FileEntry
*file
)
973 SM
.setMainFileID(SM
.createFileID(file
, SourceLocation(),
979 static void create_main_file_id(SourceManager
&SM
, const FileEntry
*file
)
981 SM
.createMainFileID(file
);
986 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
988 static void set_lang_defaults(CompilerInstance
*Clang
)
990 PreprocessorOptions
&PO
= Clang
->getPreprocessorOpts();
991 TargetOptions
&TO
= Clang
->getTargetOpts();
992 llvm::Triple
T(TO
.Triple
);
993 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
, T
, PO
,
994 LangStandard::lang_unspecified
);
999 static void set_lang_defaults(CompilerInstance
*Clang
)
1001 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
,
1002 LangStandard::lang_unspecified
);
1007 #ifdef SETINVOCATION_TAKES_SHARED_PTR
1009 static void set_invocation(CompilerInstance
*Clang
,
1010 CompilerInvocation
*invocation
)
1012 Clang
->setInvocation(std::shared_ptr
<CompilerInvocation
>(invocation
));
1017 static void set_invocation(CompilerInstance
*Clang
,
1018 CompilerInvocation
*invocation
)
1020 Clang
->setInvocation(invocation
);
1025 /* Add pet specific predefines to the preprocessor.
1026 * Currently, these are all pencil specific, so they are only
1027 * added if "pencil" is set.
1029 * We mimic the way <command line> is handled inside clang.
1031 void add_predefines(Preprocessor
&PP
, int pencil
)
1038 s
= PP
.getPredefines();
1039 s
+= "# 1 \"<pet>\" 1\n"
1040 "void __pencil_assume(int assumption);\n"
1041 "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n"
1042 "# 1 \"<built-in>\" 2\n";
1043 PP
.setPredefines(s
);
1046 /* Extract a pet_scop from each function in the C source file called "filename".
1047 * Each detected scop is passed to "fn".
1048 * If "function" is not NULL, only extract a pet_scop from the function
1050 * If "autodetect" is set, extract any pet_scop we can find.
1051 * Otherwise, extract the pet_scop from the region delimited
1052 * by "scop" and "endscop" pragmas.
1054 * We first set up the clang parser and then try to extract the
1055 * pet_scop from the appropriate function(s) in PetASTConsumer.
1057 static isl_stat
foreach_scop_in_C_source(isl_ctx
*ctx
,
1058 const char *filename
, const char *function
, pet_options
*options
,
1059 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
)
1061 CompilerInstance
*Clang
= new CompilerInstance();
1062 create_diagnostics(Clang
);
1063 DiagnosticsEngine
&Diags
= Clang
->getDiagnostics();
1064 Diags
.setSuppressSystemWarnings(true);
1065 CompilerInvocation
*invocation
= construct_invocation(filename
, Diags
);
1067 set_invocation(Clang
, invocation
);
1068 Diags
.setClient(construct_printer(Clang
, options
->pencil
));
1069 Clang
->createFileManager();
1070 Clang
->createSourceManager(Clang
->getFileManager());
1071 TargetInfo
*target
= create_target_info(Clang
, Diags
);
1072 Clang
->setTarget(target
);
1073 set_lang_defaults(Clang
);
1074 HeaderSearchOptions
&HSO
= Clang
->getHeaderSearchOpts();
1075 HSO
.ResourceDir
= ResourceDir
;
1076 for (int i
= 0; i
< options
->n_path
; ++i
)
1077 add_path(HSO
, options
->paths
[i
]);
1078 PreprocessorOptions
&PO
= Clang
->getPreprocessorOpts();
1079 for (int i
= 0; i
< options
->n_define
; ++i
)
1080 PO
.addMacroDef(options
->defines
[i
]);
1081 create_preprocessor(Clang
);
1082 Preprocessor
&PP
= Clang
->getPreprocessor();
1083 add_predefines(PP
, options
->pencil
);
1084 PP
.getBuiltinInfo().initializeBuiltins(PP
.getIdentifierTable(),
1089 const FileEntry
*file
= Clang
->getFileManager().getFile(filename
);
1091 isl_die(ctx
, isl_error_unknown
, "unable to open file",
1092 do { delete Clang
; return isl_stat_error
; } while (0));
1093 create_main_file_id(Clang
->getSourceManager(), file
);
1095 Clang
->createASTContext();
1096 PetASTConsumer
consumer(ctx
, PP
, Clang
->getASTContext(), Diags
,
1097 scops
, function
, options
, fn
, user
);
1098 Sema
*sema
= new Sema(PP
, Clang
->getASTContext(), consumer
);
1100 if (!options
->autodetect
) {
1101 PP
.AddPragmaHandler(new PragmaScopHandler(scops
));
1102 PP
.AddPragmaHandler(new PragmaEndScopHandler(scops
));
1103 PP
.AddPragmaHandler(new PragmaLiveOutHandler(*sema
,
1104 consumer
.live_out
));
1107 consumer
.add_pragma_handlers(sema
);
1109 Diags
.getClient()->BeginSourceFile(Clang
->getLangOpts(), &PP
);
1111 Diags
.getClient()->EndSourceFile();
1116 return consumer
.error
? isl_stat_error
: isl_stat_ok
;
1119 /* Extract a pet_scop from each function in the C source file called "filename".
1120 * Each detected scop is passed to "fn".
1122 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1123 * that all objects on the stack (of that function) are destroyed before we
1124 * call llvm_shutdown.
1126 static isl_stat
pet_foreach_scop_in_C_source(isl_ctx
*ctx
,
1127 const char *filename
, const char *function
,
1128 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
)
1131 pet_options
*options
;
1132 bool allocated
= false;
1134 options
= isl_ctx_peek_pet_options(ctx
);
1136 options
= pet_options_new_with_defaults();
1140 r
= foreach_scop_in_C_source(ctx
, filename
, function
, options
,
1142 llvm::llvm_shutdown();
1145 pet_options_free(options
);
1150 /* Store "scop" into the address pointed to by "user".
1151 * Return -1 to indicate that we are not interested in any further scops.
1152 * This function should therefore not be called a second call
1153 * so in principle there is no need to check if we have already set *user.
1155 static isl_stat
set_first_scop(pet_scop
*scop
, void *user
)
1157 pet_scop
**p
= (pet_scop
**) user
;
1162 pet_scop_free(scop
);
1164 return isl_stat_error
;
1167 /* Extract a pet_scop from the C source file called "filename".
1168 * If "function" is not NULL, extract the pet_scop from the function
1171 * We start extracting scops from every function and then abort
1172 * as soon as we have extracted one scop.
1174 struct pet_scop
*pet_scop_extract_from_C_source(isl_ctx
*ctx
,
1175 const char *filename
, const char *function
)
1177 pet_scop
*scop
= NULL
;
1179 pet_foreach_scop_in_C_source(ctx
, filename
, function
,
1180 &set_first_scop
, &scop
);
1185 /* Internal data structure for pet_transform_C_source
1187 * transform is the function that should be called to print a scop
1188 * in is the input source file
1189 * out is the output source file
1190 * end is the offset of the end of the previous scop (zero if we have not
1191 * found any scop yet)
1192 * p is a printer that prints to out.
1194 struct pet_transform_data
{
1195 __isl_give isl_printer
*(*transform
)(__isl_take isl_printer
*p
,
1196 struct pet_scop
*scop
, void *user
);
1205 /* This function is called each time a scop is detected.
1207 * We first copy the input text code from the end of the previous scop
1208 * until the start of "scop" and then print the scop itself through
1209 * a call to data->transform. We set up the printer to print
1210 * the transformed code with the same (initial) indentation as
1211 * the original code.
1212 * Finally, we keep track of the end of "scop" so that we can
1213 * continue copying when we find the next scop.
1215 * Before calling data->transform, we store a pointer to the original
1216 * input file in the extended scop in case the user wants to call
1217 * pet_scop_print_original from the callback.
1219 static isl_stat
pet_transform(struct pet_scop
*scop
, void *user
)
1221 struct pet_transform_data
*data
= (struct pet_transform_data
*) user
;
1225 return isl_stat_error
;
1226 start
= pet_loc_get_start(scop
->loc
);
1227 if (copy(data
->in
, data
->out
, data
->end
, start
) < 0)
1229 data
->end
= pet_loc_get_end(scop
->loc
);
1230 scop
= pet_scop_set_input_file(scop
, data
->in
);
1231 data
->p
= isl_printer_set_indent_prefix(data
->p
,
1232 pet_loc_get_indent(scop
->loc
));
1233 data
->p
= data
->transform(data
->p
, scop
, data
->user
);
1235 return isl_stat_error
;
1238 pet_scop_free(scop
);
1239 return isl_stat_error
;
1242 /* Transform the C source file "input" by rewriting each scop
1243 * through a call to "transform".
1244 * When autodetecting scops, at most one scop per function is rewritten.
1245 * The transformed C code is written to "output".
1247 * For each scop we find, we first copy the input text code
1248 * from the end of the previous scop (or the beginning of the file
1249 * in case of the first scop) until the start of the scop
1250 * and then print the scop itself through a call to "transform".
1251 * At the end we copy everything from the end of the final scop
1252 * until the end of the input file to "output".
1254 int pet_transform_C_source(isl_ctx
*ctx
, const char *input
, FILE *out
,
1255 __isl_give isl_printer
*(*transform
)(__isl_take isl_printer
*p
,
1256 struct pet_scop
*scop
, void *user
), void *user
)
1258 struct pet_transform_data data
;
1263 if (input
&& strcmp(input
, "-")) {
1264 data
.in
= fopen(input
, "r");
1266 isl_die(ctx
, isl_error_unknown
, "unable to open file",
1270 data
.p
= isl_printer_to_file(ctx
, data
.out
);
1271 data
.p
= isl_printer_set_output_format(data
.p
, ISL_FORMAT_C
);
1273 data
.transform
= transform
;
1276 r
= pet_foreach_scop_in_C_source(ctx
, input
, NULL
,
1277 &pet_transform
, &data
);
1279 isl_printer_free(data
.p
);
1282 if (r
== 0 && copy(data
.in
, data
.out
, data
.end
, -1) < 0)
1285 if (data
.in
!= stdin
)