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 #include <llvm/Support/raw_ostream.h>
47 #include <llvm/Support/ManagedStatic.h>
48 #include <llvm/Support/Host.h>
49 #include <clang/Basic/Version.h>
50 #include <clang/Basic/FileSystemOptions.h>
51 #include <clang/Basic/FileManager.h>
52 #include <clang/Basic/TargetOptions.h>
53 #include <clang/Basic/TargetInfo.h>
54 #include <clang/Driver/Compilation.h>
55 #include <clang/Driver/Driver.h>
56 #include <clang/Driver/Tool.h>
57 #include <clang/Frontend/CompilerInstance.h>
58 #include <clang/Frontend/CompilerInvocation.h>
59 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
60 #include <clang/Basic/DiagnosticOptions.h>
62 #include <clang/Frontend/DiagnosticOptions.h>
64 #include <clang/Frontend/TextDiagnosticPrinter.h>
65 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
66 #include <clang/Lex/HeaderSearchOptions.h>
68 #include <clang/Frontend/HeaderSearchOptions.h>
70 #include <clang/Frontend/LangStandard.h>
71 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
72 #include <clang/Lex/PreprocessorOptions.h>
74 #include <clang/Frontend/PreprocessorOptions.h>
76 #include <clang/Frontend/FrontendOptions.h>
77 #include <clang/Frontend/Utils.h>
78 #include <clang/Lex/HeaderSearch.h>
79 #include <clang/Lex/Preprocessor.h>
80 #include <clang/Lex/Pragma.h>
81 #include <clang/AST/ASTContext.h>
82 #include <clang/AST/ASTConsumer.h>
83 #include <clang/Sema/Sema.h>
84 #include <clang/Sema/SemaDiagnostic.h>
85 #include <clang/Parse/Parser.h>
86 #include <clang/Parse/ParseAST.h>
89 #include <isl/constraint.h>
93 #include "clang_compatibility.h"
99 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
102 using namespace clang
;
103 using namespace clang::driver
;
105 #ifdef HAVE_ADT_OWNINGPTR_H
106 #define unique_ptr llvm::OwningPtr
109 /* Called if we found something we didn't expect in one of the pragmas.
110 * We'll provide more informative warnings later.
112 static void unsupported(Preprocessor
&PP
, SourceLocation loc
)
114 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
115 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
117 DiagnosticBuilder B
= diag
.Report(loc
, id
);
120 static int get_int(const char *s
)
122 return s
[0] == '"' ? atoi(s
+ 1) : atoi(s
);
125 static ValueDecl
*get_value_decl(Sema
&sema
, Token
&token
)
127 IdentifierInfo
*name
;
130 if (token
.isNot(tok::identifier
))
133 name
= token
.getIdentifierInfo();
134 decl
= sema
.LookupSingleName(sema
.TUScope
, name
,
135 token
.getLocation(), Sema::LookupOrdinaryName
);
136 return decl
? cast_or_null
<ValueDecl
>(decl
) : NULL
;
139 /* Handle pragmas of the form
141 * #pragma value_bounds identifier lower_bound upper_bound
143 * For each such pragma, add a mapping
144 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
147 struct PragmaValueBoundsHandler
: public PragmaHandler
{
150 isl_union_map
*value_bounds
;
152 PragmaValueBoundsHandler(isl_ctx
*ctx
, Sema
&sema
) :
153 PragmaHandler("value_bounds"), sema(sema
), ctx(ctx
) {
154 isl_space
*space
= isl_space_params_alloc(ctx
, 0);
155 value_bounds
= isl_union_map_empty(space
);
158 ~PragmaValueBoundsHandler() {
159 isl_union_map_free(value_bounds
);
162 virtual void HandlePragma(Preprocessor
&PP
,
163 PragmaIntroducerKind Introducer
,
174 vd
= get_value_decl(sema
, token
);
176 unsupported(PP
, token
.getLocation());
181 if (!token
.isLiteral()) {
182 unsupported(PP
, token
.getLocation());
186 lb
= get_int(token
.getLiteralData());
189 if (!token
.isLiteral()) {
190 unsupported(PP
, token
.getLocation());
194 ub
= get_int(token
.getLiteralData());
196 dim
= isl_space_alloc(ctx
, 0, 0, 1);
197 map
= isl_map_universe(dim
);
198 map
= isl_map_lower_bound_si(map
, isl_dim_out
, 0, lb
);
199 map
= isl_map_upper_bound_si(map
, isl_dim_out
, 0, ub
);
200 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
201 map
= isl_map_set_tuple_id(map
, isl_dim_in
, id
);
203 value_bounds
= isl_union_map_add_map(value_bounds
, map
);
207 /* Given a variable declaration, check if it has an integer initializer
208 * and if so, add a parameter corresponding to the variable to "value"
209 * with its value fixed to the integer initializer and return the result.
211 static __isl_give isl_set
*extract_initialization(__isl_take isl_set
*value
,
223 vd
= cast
<VarDecl
>(decl
);
226 if (!vd
->getType()->isIntegerType())
228 expr
= vd
->getInit();
231 il
= cast
<IntegerLiteral
>(expr
);
235 ctx
= isl_set_get_ctx(value
);
236 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
237 space
= isl_space_params_alloc(ctx
, 1);
238 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0, id
);
239 set
= isl_set_universe(space
);
241 v
= PetScan::extract_int(ctx
, il
);
242 set
= isl_set_fix_val(set
, isl_dim_param
, 0, v
);
244 return isl_set_intersect(value
, set
);
247 /* Handle pragmas of the form
249 * #pragma parameter identifier lower_bound
251 * #pragma parameter identifier lower_bound upper_bound
253 * For each such pragma, intersect the context with the set
254 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
256 struct PragmaParameterHandler
: public PragmaHandler
{
259 isl_set
*&context_value
;
261 PragmaParameterHandler(Sema
&sema
, isl_set
*&context
,
262 isl_set
*&context_value
) :
263 PragmaHandler("parameter"), sema(sema
), context(context
),
264 context_value(context_value
) {}
266 virtual void HandlePragma(Preprocessor
&PP
,
267 PragmaIntroducerKind Introducer
,
270 isl_ctx
*ctx
= isl_set_get_ctx(context
);
280 vd
= get_value_decl(sema
, token
);
282 unsupported(PP
, token
.getLocation());
287 if (!token
.isLiteral()) {
288 unsupported(PP
, token
.getLocation());
292 lb
= get_int(token
.getLiteralData());
295 if (token
.isLiteral()) {
297 ub
= get_int(token
.getLiteralData());
298 } else if (token
.isNot(tok::eod
)) {
299 unsupported(PP
, token
.getLocation());
303 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
304 dim
= isl_space_params_alloc(ctx
, 1);
305 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
307 set
= isl_set_universe(dim
);
309 set
= isl_set_lower_bound_si(set
, isl_dim_param
, 0, lb
);
311 set
= isl_set_upper_bound_si(set
, isl_dim_param
, 0, ub
);
313 context
= isl_set_intersect(context
, set
);
315 context_value
= extract_initialization(context_value
, vd
);
319 /* Handle pragmas of the form
321 * #pragma pencil independent
323 * For each such pragma, add an entry to the "independent" vector.
325 struct PragmaPencilHandler
: public PragmaHandler
{
326 std::vector
<Independent
> &independent
;
328 PragmaPencilHandler(std::vector
<Independent
> &independent
) :
329 PragmaHandler("pencil"), independent(independent
) {}
331 virtual void HandlePragma(Preprocessor
&PP
,
332 PragmaIntroducerKind Introducer
,
335 IdentifierInfo
*info
;
338 if (token
.isNot(tok::identifier
))
341 info
= token
.getIdentifierInfo();
342 if (!info
->isStr("independent"))
346 if (token
.isNot(tok::eod
))
349 SourceManager
&SM
= PP
.getSourceManager();
350 SourceLocation sloc
= PencilTok
.getLocation();
351 unsigned line
= SM
.getExpansionLineNumber(sloc
);
352 independent
.push_back(Independent(line
));
356 #ifdef HAVE_TRANSLATELINECOL
358 /* Return a SourceLocation for line "line", column "col" of file "FID".
360 SourceLocation
translateLineCol(SourceManager
&SM
, FileID FID
, unsigned line
,
363 return SM
.translateLineCol(FID
, line
, col
);
368 /* Return a SourceLocation for line "line", column "col" of file "FID".
370 SourceLocation
translateLineCol(SourceManager
&SM
, FileID FID
, unsigned line
,
373 return SM
.getLocation(SM
.getFileEntryForID(FID
), line
, col
);
378 /* List of pairs of #pragma scop and #pragma endscop locations.
381 std::vector
<ScopLoc
> list
;
383 /* Add a new start (#pragma scop) location to the list.
384 * If the last #pragma scop did not have a matching
385 * #pragma endscop then overwrite it.
386 * "start" points to the location of the scop pragma.
388 void add_start(SourceManager
&SM
, SourceLocation start
) {
392 int line
= SM
.getExpansionLineNumber(start
);
393 start
= translateLineCol(SM
, SM
.getFileID(start
), line
, 1);
394 loc
.start_line
= line
;
395 loc
.start
= SM
.getFileOffset(start
);
396 if (list
.size() == 0 || list
[list
.size() - 1].end
!= 0)
399 list
[list
.size() - 1] = loc
;
402 /* Set the end location (#pragma endscop) of the last pair
404 * If there is no such pair of if the end of that pair
405 * is already set, then ignore the spurious #pragma endscop.
406 * "end" points to the location of the endscop pragma.
408 void add_end(SourceManager
&SM
, SourceLocation end
) {
409 if (list
.size() == 0 || list
[list
.size() - 1].end
!= 0)
411 list
[list
.size() - 1].endscop
= end
;
412 int line
= SM
.getExpansionLineNumber(end
);
413 end
= translateLineCol(SM
, SM
.getFileID(end
), line
+ 1, 1);
414 list
[list
.size() - 1].end
= SM
.getFileOffset(end
);
418 /* Handle pragmas of the form
422 * In particular, store the location of the line containing
423 * the pragma in the list "scops".
425 struct PragmaScopHandler
: public PragmaHandler
{
428 PragmaScopHandler(ScopLocList
&scops
) :
429 PragmaHandler("scop"), scops(scops
) {}
431 virtual void HandlePragma(Preprocessor
&PP
,
432 PragmaIntroducerKind Introducer
,
434 SourceManager
&SM
= PP
.getSourceManager();
435 SourceLocation sloc
= ScopTok
.getLocation();
436 scops
.add_start(SM
, sloc
);
440 /* Handle pragmas of the form
444 * In particular, store the location of the line following the one containing
445 * the pragma in the list "scops".
447 struct PragmaEndScopHandler
: public PragmaHandler
{
450 PragmaEndScopHandler(ScopLocList
&scops
) :
451 PragmaHandler("endscop"), scops(scops
) {}
453 virtual void HandlePragma(Preprocessor
&PP
,
454 PragmaIntroducerKind Introducer
,
456 SourceManager
&SM
= PP
.getSourceManager();
457 SourceLocation sloc
= EndScopTok
.getLocation();
458 scops
.add_end(SM
, sloc
);
462 /* Handle pragmas of the form
464 * #pragma live-out identifier, identifier, ...
466 * Each identifier on the line is stored in live_out.
468 struct PragmaLiveOutHandler
: public PragmaHandler
{
470 set
<ValueDecl
*> &live_out
;
472 PragmaLiveOutHandler(Sema
&sema
, set
<ValueDecl
*> &live_out
) :
473 PragmaHandler("live"), sema(sema
), live_out(live_out
) {}
475 virtual void HandlePragma(Preprocessor
&PP
,
476 PragmaIntroducerKind Introducer
,
481 if (token
.isNot(tok::minus
))
484 if (token
.isNot(tok::identifier
) ||
485 !token
.getIdentifierInfo()->isStr("out"))
489 while (token
.isNot(tok::eod
)) {
492 vd
= get_value_decl(sema
, token
);
494 unsupported(PP
, token
.getLocation());
499 if (token
.is(tok::comma
))
505 /* For each array in "scop", set its value_bounds property
506 * based on the information in "value_bounds" and
507 * mark it as live_out if it appears in "live_out".
509 static void update_arrays(struct pet_scop
*scop
,
510 __isl_take isl_union_map
*value_bounds
, set
<ValueDecl
*> &live_out
)
512 set
<ValueDecl
*>::iterator lo_it
;
513 isl_ctx
*ctx
= isl_union_map_get_ctx(value_bounds
);
516 isl_union_map_free(value_bounds
);
520 for (int i
= 0; i
< scop
->n_array
; ++i
) {
525 pet_array
*array
= scop
->arrays
[i
];
527 id
= isl_set_get_tuple_id(array
->extent
);
528 decl
= pet_id_get_decl(id
);
530 space
= isl_space_alloc(ctx
, 0, 0, 1);
531 space
= isl_space_set_tuple_id(space
, isl_dim_in
, id
);
533 bounds
= isl_union_map_extract_map(value_bounds
, space
);
534 if (!isl_map_plain_is_empty(bounds
))
535 array
->value_bounds
= isl_map_range(bounds
);
537 isl_map_free(bounds
);
539 lo_it
= live_out
.find(decl
);
540 if (lo_it
!= live_out
.end())
544 isl_union_map_free(value_bounds
);
547 /* Extract a pet_scop (if any) from each appropriate function.
548 * Each detected scop is passed to "fn".
549 * When autodetecting, at most one scop is extracted from each function.
550 * If "function" is not NULL, then we only extract a pet_scop if the
551 * name of the function matches.
552 * If "autodetect" is false, then we only extract if we have seen
553 * scop and endscop pragmas and if these are situated inside the function
556 struct PetASTConsumer
: public ASTConsumer
{
558 ASTContext
&ast_context
;
559 DiagnosticsEngine
&diags
;
561 std::vector
<Independent
> independent
;
562 const char *function
;
563 pet_options
*options
;
566 isl_set
*context_value
;
567 set
<ValueDecl
*> live_out
;
568 PragmaValueBoundsHandler
*vb_handler
;
569 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
);
573 PetASTConsumer(isl_ctx
*ctx
, Preprocessor
&PP
, ASTContext
&ast_context
,
574 DiagnosticsEngine
&diags
, ScopLocList
&scops
,
575 const char *function
, pet_options
*options
,
576 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
) :
577 PP(PP
), ast_context(ast_context
), diags(diags
),
578 scops(scops
), function(function
), options(options
),
580 vb_handler(NULL
), fn(fn
), user(user
), error(false)
583 space
= isl_space_params_alloc(ctx
, 0);
584 context
= isl_set_universe(isl_space_copy(space
));
585 context_value
= isl_set_universe(space
);
589 isl_set_free(context
);
590 isl_set_free(context_value
);
593 void handle_value_bounds(Sema
*sema
) {
594 vb_handler
= new PragmaValueBoundsHandler(ctx
, *sema
);
595 PP
.AddPragmaHandler(vb_handler
);
598 /* Add all pragma handlers to this->PP.
599 * The pencil pragmas are only handled if the pencil option is set.
601 void add_pragma_handlers(Sema
*sema
) {
602 PP
.AddPragmaHandler(new PragmaParameterHandler(*sema
, context
,
604 if (options
->pencil
) {
606 PH
= new PragmaPencilHandler(independent
);
607 PP
.AddPragmaHandler(PH
);
609 handle_value_bounds(sema
);
612 __isl_give isl_union_map
*get_value_bounds() {
613 return isl_union_map_copy(vb_handler
->value_bounds
);
616 /* Pass "scop" to "fn" after performing some postprocessing.
617 * In particular, add the context and value_bounds constraints
618 * speficied through pragmas, add reference identifiers and
619 * reset user pointers on parameters and tuple ids.
621 * If "scop" does not contain any statements and autodetect
622 * is turned on, then skip it.
624 void call_fn(pet_scop
*scop
) {
629 if (diags
.hasErrorOccurred()) {
634 if (options
->autodetect
&& scop
->n_stmt
== 0) {
638 scop
->context
= isl_set_intersect(scop
->context
,
639 isl_set_copy(context
));
640 scop
->context_value
= isl_set_intersect(scop
->context_value
,
641 isl_set_copy(context_value
));
643 update_arrays(scop
, get_value_bounds(), live_out
);
645 scop
= pet_scop_add_ref_ids(scop
);
646 scop
= pet_scop_anonymize(scop
);
648 if (fn(scop
, user
) < 0)
652 /* For each explicitly marked scop (using pragmas),
653 * extract the scop and call "fn" on it if it is inside "fd".
655 void scan_scops(FunctionDecl
*fd
) {
657 vector
<ScopLoc
>::iterator it
;
658 isl_union_map
*vb
= vb_handler
->value_bounds
;
659 SourceManager
&SM
= PP
.getSourceManager();
662 if (scops
.list
.size() == 0)
665 start
= SM
.getFileOffset(begin_loc(fd
));
666 end
= SM
.getFileOffset(end_loc(fd
));
668 for (it
= scops
.list
.begin(); it
!= scops
.list
.end(); ++it
) {
676 PetScan
ps(PP
, ast_context
, fd
, loc
, options
,
677 isl_union_map_copy(vb
), independent
);
683 virtual HandleTopLevelDeclReturn
HandleTopLevelDecl(DeclGroupRef dg
) {
684 DeclGroupRef::iterator it
;
687 return HandleTopLevelDeclContinue
;
689 for (it
= dg
.begin(); it
!= dg
.end(); ++it
) {
690 isl_union_map
*vb
= vb_handler
->value_bounds
;
691 FunctionDecl
*fd
= dyn_cast
<clang::FunctionDecl
>(*it
);
697 fd
->getNameInfo().getAsString() != function
)
699 if (options
->autodetect
) {
702 PetScan
ps(PP
, ast_context
, fd
, loc
, options
,
703 isl_union_map_copy(vb
),
712 return HandleTopLevelDeclContinue
;
716 static const char *ResourceDir
=
717 CLANG_PREFIX
"/lib/clang/" CLANG_VERSION_STRING
;
719 static const char *implicit_functions
[] = {
720 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
722 static const char *pencil_implicit_functions
[] = {
723 "imin", "umin", "imax", "umax", "__pencil_kill"
726 /* Should "ident" be treated as an implicit function?
727 * If "pencil" is set, then also allow pencil specific builtins.
729 static bool is_implicit(const IdentifierInfo
*ident
, int pencil
)
731 const char *name
= ident
->getNameStart();
732 for (size_t i
= 0; i
< ARRAY_SIZE(implicit_functions
); ++i
)
733 if (!strcmp(name
, implicit_functions
[i
]))
737 for (size_t i
= 0; i
< ARRAY_SIZE(pencil_implicit_functions
); ++i
)
738 if (!strcmp(name
, pencil_implicit_functions
[i
]))
743 /* Ignore implicit function declaration warnings on
744 * "min", "max", "ceild" and "floord" as we detect and handle these
746 * If "pencil" is set, then also ignore them on pencil specific
749 struct MyDiagnosticPrinter
: public TextDiagnosticPrinter
{
750 const DiagnosticOptions
*DiagOpts
;
752 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
753 MyDiagnosticPrinter(DiagnosticOptions
*DO
, int pencil
) :
754 TextDiagnosticPrinter(llvm::errs(), DO
), pencil(pencil
) {}
755 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
756 return new MyDiagnosticPrinter(&Diags
.getDiagnosticOptions(),
760 MyDiagnosticPrinter(const DiagnosticOptions
&DO
, int pencil
) :
761 DiagOpts(&DO
), TextDiagnosticPrinter(llvm::errs(), DO
),
763 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
764 return new MyDiagnosticPrinter(*DiagOpts
, pencil
);
767 virtual void HandleDiagnostic(DiagnosticsEngine::Level level
,
768 const DiagnosticInfo
&info
) {
769 if (info
.getID() == diag::ext_implicit_function_decl
&&
770 info
.getNumArgs() >= 1 &&
771 info
.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo
&&
772 is_implicit(info
.getArgIdentifier(0), pencil
))
773 /* ignore warning */;
775 TextDiagnosticPrinter::HandleDiagnostic(level
, info
);
781 #ifdef HAVE_CXXISPRODUCTION
782 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
784 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
785 "", false, false, Diags
);
787 #elif defined(HAVE_ISPRODUCTION)
788 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
790 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
793 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
794 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
796 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
800 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
802 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(), Diags
);
806 namespace clang
{ namespace driver
{ class Job
; } }
808 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
809 * We fix this with a simple overloaded function here.
812 static Job
*command(Job
*J
) { return J
; }
813 static Job
*command(Job
&J
) { return &J
; }
814 static Command
*command(Command
&C
) { return &C
; }
817 /* Create a CompilerInvocation object that stores the command line
818 * arguments constructed by the driver.
819 * The arguments are mainly useful for setting up the system include
820 * paths on newer clangs and on some platforms.
822 static CompilerInvocation
*construct_invocation(const char *filename
,
823 DiagnosticsEngine
&Diags
)
825 const char *binary
= CLANG_PREFIX
"/bin/clang";
826 const unique_ptr
<Driver
> driver(construct_driver(binary
, Diags
));
827 std::vector
<const char *> Argv
;
828 Argv
.push_back(binary
);
829 Argv
.push_back(filename
);
830 const unique_ptr
<Compilation
> compilation(
831 driver
->BuildCompilation(llvm::ArrayRef
<const char *>(Argv
)));
832 JobList
&Jobs
= compilation
->getJobs();
836 Command
*cmd
= cast
<Command
>(ClangAPI::command(*Jobs
.begin()));
837 if (strcmp(cmd
->getCreator().getName(), "clang"))
840 const ArgStringList
*args
= &cmd
->getArguments();
842 CompilerInvocation
*invocation
= new CompilerInvocation
;
843 CompilerInvocation::CreateFromArgs(*invocation
, args
->data() + 1,
844 args
->data() + args
->size(),
851 static CompilerInvocation
*construct_invocation(const char *filename
,
852 DiagnosticsEngine
&Diags
)
859 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
861 static MyDiagnosticPrinter
*construct_printer(CompilerInstance
*Clang
,
864 return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil
);
869 static MyDiagnosticPrinter
*construct_printer(CompilerInstance
*Clang
,
872 return new MyDiagnosticPrinter(Clang
->getDiagnosticOpts(), pencil
);
877 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
879 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
880 DiagnosticsEngine
&Diags
)
882 shared_ptr
<TargetOptions
> TO
= Clang
->getInvocation().TargetOpts
;
883 TO
->Triple
= llvm::sys::getDefaultTargetTriple();
884 return TargetInfo::CreateTargetInfo(Diags
, TO
);
887 #elif defined(CREATETARGETINFO_TAKES_POINTER)
889 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
890 DiagnosticsEngine
&Diags
)
892 TargetOptions
&TO
= Clang
->getTargetOpts();
893 TO
.Triple
= llvm::sys::getDefaultTargetTriple();
894 return TargetInfo::CreateTargetInfo(Diags
, &TO
);
899 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
900 DiagnosticsEngine
&Diags
)
902 TargetOptions
&TO
= Clang
->getTargetOpts();
903 TO
.Triple
= llvm::sys::getDefaultTargetTriple();
904 return TargetInfo::CreateTargetInfo(Diags
, TO
);
909 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
911 static void create_diagnostics(CompilerInstance
*Clang
)
913 Clang
->createDiagnostics(0, NULL
);
918 static void create_diagnostics(CompilerInstance
*Clang
)
920 Clang
->createDiagnostics();
925 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
927 static void create_preprocessor(CompilerInstance
*Clang
)
929 Clang
->createPreprocessor(TU_Complete
);
934 static void create_preprocessor(CompilerInstance
*Clang
)
936 Clang
->createPreprocessor();
941 #ifdef ADDPATH_TAKES_4_ARGUMENTS
943 void add_path(HeaderSearchOptions
&HSO
, string Path
)
945 HSO
.AddPath(Path
, frontend::Angled
, false, false);
950 void add_path(HeaderSearchOptions
&HSO
, string Path
)
952 HSO
.AddPath(Path
, frontend::Angled
, true, false, false);
957 #ifdef HAVE_SETMAINFILEID
959 static void create_main_file_id(SourceManager
&SM
, const FileEntry
*file
)
961 SM
.setMainFileID(SM
.createFileID(file
, SourceLocation(),
967 static void create_main_file_id(SourceManager
&SM
, const FileEntry
*file
)
969 SM
.createMainFileID(file
);
974 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
976 static void set_lang_defaults(CompilerInstance
*Clang
)
978 PreprocessorOptions
&PO
= Clang
->getPreprocessorOpts();
979 TargetOptions
&TO
= Clang
->getTargetOpts();
980 llvm::Triple
T(TO
.Triple
);
981 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
, T
, PO
,
982 LangStandard::lang_unspecified
);
987 static void set_lang_defaults(CompilerInstance
*Clang
)
989 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
,
990 LangStandard::lang_unspecified
);
995 #ifdef SETINVOCATION_TAKES_SHARED_PTR
997 static void set_invocation(CompilerInstance
*Clang
,
998 CompilerInvocation
*invocation
)
1000 Clang
->setInvocation(std::shared_ptr
<CompilerInvocation
>(invocation
));
1005 static void set_invocation(CompilerInstance
*Clang
,
1006 CompilerInvocation
*invocation
)
1008 Clang
->setInvocation(invocation
);
1013 /* Add pet specific predefines to the preprocessor.
1014 * Currently, these are all pencil specific, so they are only
1015 * added if "pencil" is set.
1017 * We mimic the way <command line> is handled inside clang.
1019 void add_predefines(Preprocessor
&PP
, int pencil
)
1026 s
= PP
.getPredefines();
1027 s
+= "# 1 \"<pet>\" 1\n"
1028 "void __pencil_assume(int assumption);\n"
1029 "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n"
1030 "# 1 \"<built-in>\" 2\n";
1031 PP
.setPredefines(s
);
1034 /* Extract a pet_scop from each function in the C source file called "filename".
1035 * Each detected scop is passed to "fn".
1036 * If "function" is not NULL, only extract a pet_scop from the function
1038 * If "autodetect" is set, extract any pet_scop we can find.
1039 * Otherwise, extract the pet_scop from the region delimited
1040 * by "scop" and "endscop" pragmas.
1042 * We first set up the clang parser and then try to extract the
1043 * pet_scop from the appropriate function(s) in PetASTConsumer.
1045 static isl_stat
foreach_scop_in_C_source(isl_ctx
*ctx
,
1046 const char *filename
, const char *function
, pet_options
*options
,
1047 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
)
1049 CompilerInstance
*Clang
= new CompilerInstance();
1050 create_diagnostics(Clang
);
1051 DiagnosticsEngine
&Diags
= Clang
->getDiagnostics();
1052 Diags
.setSuppressSystemWarnings(true);
1053 CompilerInvocation
*invocation
= construct_invocation(filename
, Diags
);
1055 set_invocation(Clang
, invocation
);
1056 Diags
.setClient(construct_printer(Clang
, options
->pencil
));
1057 Clang
->createFileManager();
1058 Clang
->createSourceManager(Clang
->getFileManager());
1059 TargetInfo
*target
= create_target_info(Clang
, Diags
);
1060 Clang
->setTarget(target
);
1061 set_lang_defaults(Clang
);
1062 HeaderSearchOptions
&HSO
= Clang
->getHeaderSearchOpts();
1063 HSO
.ResourceDir
= ResourceDir
;
1064 for (int i
= 0; i
< options
->n_path
; ++i
)
1065 add_path(HSO
, options
->paths
[i
]);
1066 PreprocessorOptions
&PO
= Clang
->getPreprocessorOpts();
1067 for (int i
= 0; i
< options
->n_define
; ++i
)
1068 PO
.addMacroDef(options
->defines
[i
]);
1069 create_preprocessor(Clang
);
1070 Preprocessor
&PP
= Clang
->getPreprocessor();
1071 add_predefines(PP
, options
->pencil
);
1072 PP
.getBuiltinInfo().initializeBuiltins(PP
.getIdentifierTable(),
1077 const FileEntry
*file
= Clang
->getFileManager().getFile(filename
);
1079 isl_die(ctx
, isl_error_unknown
, "unable to open file",
1080 do { delete Clang
; return isl_stat_error
; } while (0));
1081 create_main_file_id(Clang
->getSourceManager(), file
);
1083 Clang
->createASTContext();
1084 PetASTConsumer
consumer(ctx
, PP
, Clang
->getASTContext(), Diags
,
1085 scops
, function
, options
, fn
, user
);
1086 Sema
*sema
= new Sema(PP
, Clang
->getASTContext(), consumer
);
1088 if (!options
->autodetect
) {
1089 PP
.AddPragmaHandler(new PragmaScopHandler(scops
));
1090 PP
.AddPragmaHandler(new PragmaEndScopHandler(scops
));
1091 PP
.AddPragmaHandler(new PragmaLiveOutHandler(*sema
,
1092 consumer
.live_out
));
1095 consumer
.add_pragma_handlers(sema
);
1097 Diags
.getClient()->BeginSourceFile(Clang
->getLangOpts(), &PP
);
1099 Diags
.getClient()->EndSourceFile();
1104 return consumer
.error
? isl_stat_error
: isl_stat_ok
;
1107 /* Extract a pet_scop from each function in the C source file called "filename".
1108 * Each detected scop is passed to "fn".
1110 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1111 * that all objects on the stack (of that function) are destroyed before we
1112 * call llvm_shutdown.
1114 static isl_stat
pet_foreach_scop_in_C_source(isl_ctx
*ctx
,
1115 const char *filename
, const char *function
,
1116 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
)
1119 pet_options
*options
;
1120 bool allocated
= false;
1122 options
= isl_ctx_peek_pet_options(ctx
);
1124 options
= pet_options_new_with_defaults();
1128 r
= foreach_scop_in_C_source(ctx
, filename
, function
, options
,
1130 llvm::llvm_shutdown();
1133 pet_options_free(options
);
1138 /* Store "scop" into the address pointed to by "user".
1139 * Return -1 to indicate that we are not interested in any further scops.
1140 * This function should therefore not be called a second call
1141 * so in principle there is no need to check if we have already set *user.
1143 static isl_stat
set_first_scop(pet_scop
*scop
, void *user
)
1145 pet_scop
**p
= (pet_scop
**) user
;
1150 pet_scop_free(scop
);
1152 return isl_stat_error
;
1155 /* Extract a pet_scop from the C source file called "filename".
1156 * If "function" is not NULL, extract the pet_scop from the function
1159 * We start extracting scops from every function and then abort
1160 * as soon as we have extracted one scop.
1162 struct pet_scop
*pet_scop_extract_from_C_source(isl_ctx
*ctx
,
1163 const char *filename
, const char *function
)
1165 pet_scop
*scop
= NULL
;
1167 pet_foreach_scop_in_C_source(ctx
, filename
, function
,
1168 &set_first_scop
, &scop
);
1173 /* Internal data structure for pet_transform_C_source
1175 * transform is the function that should be called to print a scop
1176 * in is the input source file
1177 * out is the output source file
1178 * end is the offset of the end of the previous scop (zero if we have not
1179 * found any scop yet)
1180 * p is a printer that prints to out.
1182 struct pet_transform_data
{
1183 __isl_give isl_printer
*(*transform
)(__isl_take isl_printer
*p
,
1184 struct pet_scop
*scop
, void *user
);
1193 /* This function is called each time a scop is detected.
1195 * We first copy the input text code from the end of the previous scop
1196 * until the start of "scop" and then print the scop itself through
1197 * a call to data->transform. We set up the printer to print
1198 * the transformed code with the same (initial) indentation as
1199 * the original code.
1200 * Finally, we keep track of the end of "scop" so that we can
1201 * continue copying when we find the next scop.
1203 * Before calling data->transform, we store a pointer to the original
1204 * input file in the extended scop in case the user wants to call
1205 * pet_scop_print_original from the callback.
1207 static isl_stat
pet_transform(struct pet_scop
*scop
, void *user
)
1209 struct pet_transform_data
*data
= (struct pet_transform_data
*) user
;
1213 return isl_stat_error
;
1214 start
= pet_loc_get_start(scop
->loc
);
1215 if (copy(data
->in
, data
->out
, data
->end
, start
) < 0)
1217 data
->end
= pet_loc_get_end(scop
->loc
);
1218 scop
= pet_scop_set_input_file(scop
, data
->in
);
1219 data
->p
= isl_printer_set_indent_prefix(data
->p
,
1220 pet_loc_get_indent(scop
->loc
));
1221 data
->p
= data
->transform(data
->p
, scop
, data
->user
);
1223 return isl_stat_error
;
1226 pet_scop_free(scop
);
1227 return isl_stat_error
;
1230 /* Transform the C source file "input" by rewriting each scop
1231 * through a call to "transform".
1232 * When autodetecting scops, at most one scop per function is rewritten.
1233 * The transformed C code is written to "output".
1235 * For each scop we find, we first copy the input text code
1236 * from the end of the previous scop (or the beginning of the file
1237 * in case of the first scop) until the start of the scop
1238 * and then print the scop itself through a call to "transform".
1239 * At the end we copy everything from the end of the final scop
1240 * until the end of the input file to "output".
1242 int pet_transform_C_source(isl_ctx
*ctx
, const char *input
, FILE *out
,
1243 __isl_give isl_printer
*(*transform
)(__isl_take isl_printer
*p
,
1244 struct pet_scop
*scop
, void *user
), void *user
)
1246 struct pet_transform_data data
;
1251 if (input
&& strcmp(input
, "-")) {
1252 data
.in
= fopen(input
, "r");
1254 isl_die(ctx
, isl_error_unknown
, "unable to open file",
1258 data
.p
= isl_printer_to_file(ctx
, data
.out
);
1259 data
.p
= isl_printer_set_output_format(data
.p
, ISL_FORMAT_C
);
1261 data
.transform
= transform
;
1264 r
= pet_foreach_scop_in_C_source(ctx
, input
, NULL
,
1265 &pet_transform
, &data
);
1267 isl_printer_free(data
.p
);
1270 if (r
== 0 && copy(data
.in
, data
.out
, data
.end
, -1) < 0)
1273 if (data
.in
!= stdin
)