source: src/AST/Pass.proto.hpp @ 0522ebe

Last change on this file since 0522ebe was 5bf685f, checked in by Andrew Beach <ajbeach@…>, 6 months ago

Replayed maybeClone with maybeCopy, removed unused helppers in utility.h and pushed some includes out of headers.

  • Property mode set to 100644
File size: 19.1 KB
RevLine 
[04124c4]1//
2// Cforall Version 1.0.0 Copyright (C) 2019 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Pass.impl.hpp --
8//
9// Author           : Thierry Delisle
10// Created On       : Thu May 09 15::37::05 2019
11// Last Modified By :
12// Last Modified On :
13// Update Count     :
14//
15
[f47f887]16#pragma once
17// IWYU pragma: private, include "Pass.hpp"
18
[2d0f918]19#include "Common/Iterate.hpp"
[c15085d]20#include "Common/Stats/Heap.h"
[5bf685f]21#include "Common/utility.h"
[f47f887]22namespace ast {
[26e6d88]23        template<typename core_t> class Pass;
24        class TranslationUnit;
25        struct PureVisitor;
26        template<typename node_t> node_t * deepCopy( const node_t * );
[cad9edb]27}
[d3aa64f1]28
[2d0f918]29#ifdef PEDANTIC_PASS_ASSERT
[efe89894]30#define __pedantic_pass_assert(...) assert(__VA_ARGS__)
[2d0f918]31#define __pedantic_pass_assertf(...) assertf(__VA_ARGS__)
32#else
33#define __pedantic_pass_assert(...)
34#define __pedantic_pass_assertf(...)
35#endif
36
[cad9edb]37namespace ast::__pass {
[4ec9513]38
[26e6d88]39typedef std::function<void( void * )> cleanup_func_t;
40typedef std::function<void( cleanup_func_t, void * )> at_cleanup_t;
[f47f887]41
[26e6d88]42// boolean reference that may be null
43// either refers to a boolean value or is null and returns true
44class bool_ref {
45public:
46        bool_ref() = default;
47        ~bool_ref() = default;
[f47f887]48
[26e6d88]49        operator bool() { return m_ref ? *m_ref : true; }
50        bool operator=( bool val ) { assert(m_ref); return *m_ref = val; }
[f47f887]51
[26e6d88]52private:
[f47f887]53
[26e6d88]54        friend class visit_children_guard;
[f47f887]55
[26e6d88]56        bool * set( bool * val ) {
57                bool * prev = m_ref;
58                m_ref = val;
59                return prev;
60        }
[f47f887]61
[26e6d88]62        bool * m_ref = nullptr;
63};
64
65// Implementation of the guard value
66// Created inside the visit scope
67class guard_value {
68public:
69        /// Push onto the cleanup
70        guard_value( at_cleanup_t * at_cleanup ) {
71                if( at_cleanup ) {
72                        *at_cleanup = [this]( cleanup_func_t && func, void* val ) {
73                                push( std::move( func ), val );
74                        };
[04124c4]75                }
[26e6d88]76        }
[f47f887]77
[26e6d88]78        ~guard_value() {
79                while( !cleanups.empty() ) {
80                        auto& cleanup = cleanups.top();
81                        cleanup.func( cleanup.val );
82                        cleanups.pop();
[04124c4]83                }
[26e6d88]84        }
[f47f887]85
[26e6d88]86        void push( cleanup_func_t && func, void* val ) {
87                cleanups.emplace( std::move(func), val );
88        }
[f47f887]89
[26e6d88]90private:
91        struct cleanup_t {
92                cleanup_func_t func;
93                void * val;
[f47f887]94
[26e6d88]95                cleanup_t( cleanup_func_t&& func, void * val ) : func(func), val(val) {}
[04124c4]96        };
[f47f887]97
[26e6d88]98        std::stack< cleanup_t, std::vector<cleanup_t> > cleanups;
99};
[04124c4]100
[26e6d88]101// Guard structure implementation for whether or not children should be visited
102class visit_children_guard {
103public:
[dff6452]104
[26e6d88]105        visit_children_guard( bool_ref * ref )
106                : m_val ( true )
107                , m_prev( ref ? ref->set( &m_val ) : nullptr )
108                , m_ref ( ref )
109        {}
[dff6452]110
[26e6d88]111        ~visit_children_guard() {
112                if( m_ref ) {
113                        m_ref->set( m_prev );
114                }
115        }
[eb211bf]116
[26e6d88]117        operator bool() { return m_val; }
118
119private:
120        bool       m_val;
121        bool     * m_prev;
122        bool_ref * m_ref;
123};
124
125/// "Short hand" to check if this is a valid previsit function
126/// Mostly used to make the static_assert look (and print) prettier
127template<typename core_t, typename node_t>
128struct is_valid_previsit {
129        using ret_t = decltype( std::declval<core_t*>()->previsit( std::declval<const node_t *>() ) );
130
131        static constexpr bool value = std::is_void< ret_t >::value ||
132                std::is_base_of<const node_t, typename std::remove_pointer<ret_t>::type >::value;
133};
134
135/// The result is a single node.
136template< typename node_t >
137struct result1 {
138        bool differs = false;
139        const node_t * value = nullptr;
140
141        template< typename object_t, typename super_t, typename field_t >
[2d0f918]142        void apply( object_t * object, field_t super_t::* field ) {
143                object->*field = value;
144        }
[26e6d88]145};
146
147/// The result is a container of statements.
148template< template<class...> class container_t >
149struct resultNstmt {
150        /// The delta/change on a single node.
151        struct delta {
152                ptr<Stmt> new_val;
153                ssize_t old_idx;
154                bool is_old;
155
156                delta(const Stmt * s, ssize_t i, bool old) :
157                        new_val(s), old_idx(i), is_old(old) {}
[eb211bf]158        };
159
[26e6d88]160        bool differs = false;
161        container_t< delta > values;
[eb211bf]162
[26e6d88]163        template< typename object_t, typename super_t, typename field_t >
[2d0f918]164        void apply( object_t * object, field_t super_t::* field ) {
165                field_t & container = object->*field;
166                __pedantic_pass_assert( container.size() <= values.size() );
167
168                auto cit = enumerate(container).begin();
169
170                container_t<ptr<Stmt>> nvals;
171                for ( delta & d : values ) {
172                        if ( d.is_old ) {
173                                __pedantic_pass_assert( cit.idx <= d.old_idx );
174                                std::advance( cit, d.old_idx - cit.idx );
175                                nvals.push_back( std::move( (*cit).val ) );
176                        } else {
177                                nvals.push_back( std::move( d.new_val ) );
178                        }
179                }
180
181                container = std::move(nvals);
182        }
[eb211bf]183
[26e6d88]184        template< template<class...> class incontainer_t >
[2d0f918]185        void take_all( incontainer_t<ptr<Stmt>> * stmts ) {
186                if ( !stmts || stmts->empty() ) return;
187
188                std::transform( stmts->begin(), stmts->end(), std::back_inserter( values ),
189                        [](ast::ptr<ast::Stmt>& stmt) -> delta {
190                                return delta( stmt.release(), -1, false );
191                        });
192                stmts->clear();
193                differs = true;
194        }
[eb211bf]195
[26e6d88]196        template< template<class...> class incontainer_t >
[2d0f918]197        void take_all( incontainer_t<ptr<Decl>> * decls ) {
198                if ( !decls || decls->empty() ) return;
199
200                std::transform( decls->begin(), decls->end(), std::back_inserter( values ),
201                        [](ast::ptr<ast::Decl>& decl) -> delta {
202                                ast::Decl const * d = decl.release();
203                                return delta( new DeclStmt( d->location, d ), -1, false );
204                        });
205                decls->clear();
206                differs = true;
207        }
[26e6d88]208};
[eb211bf]209
[26e6d88]210/// The result is a container of nodes.
211template< template<class...> class container_t, typename node_t >
212struct resultN {
213        bool differs = false;
214        container_t<ptr<node_t>> values;
[0b8bf27]215
[26e6d88]216        template< typename object_t, typename super_t, typename field_t >
[2d0f918]217        void apply( object_t * object, field_t super_t::* field ) {
218                field_t & container = object->*field;
219                __pedantic_pass_assert( container.size() == values.size() );
220
221                for ( size_t i = 0; i < container.size(); ++i ) {
222                        // Take all the elements that are different in 'values'
223                        // and swap them into 'container'
224                        if ( values[i] != nullptr ) swap(container[i], values[i]);
225                }
226                // Now the original containers should still have the unchanged values
227                // but also contain the new values.
228        }
[26e6d88]229};
[e4b6cf78]230
[26e6d88]231/// Used by previsit implementation
232/// We need to reassign the result to 'node', unless the function
233/// returns void, then we just leave 'node' unchanged
234template<bool is_void>
235struct __assign;
[e4b6cf78]236
[26e6d88]237template<>
238struct __assign<true> {
[7ff3e522]239        template<typename core_t, typename node_t>
[26e6d88]240        static inline void result( core_t & core, const node_t * & node ) {
241                core.previsit( node );
[04124c4]242        }
[26e6d88]243};
[04124c4]244
[26e6d88]245template<>
246struct __assign<false> {
[7ff3e522]247        template<typename core_t, typename node_t>
[26e6d88]248        static inline void result( core_t & core, const node_t * & node ) {
249                node = core.previsit( node );
250                assertf(node, "Previsit must not return NULL");
251        }
252};
[04124c4]253
[26e6d88]254/// Used by postvisit implementation
255/// We need to return the result unless the function
256/// returns void, then we just return the original node
257template<bool is_void>
258struct __return;
259
260template<>
261struct __return<true> {
[7ff3e522]262        template<typename core_t, typename node_t>
[26e6d88]263        static inline const node_t * result( core_t & core, const node_t * & node ) {
264                core.postvisit( node );
265                return node;
[04124c4]266        }
[26e6d88]267};
[04124c4]268
[26e6d88]269template<>
270struct __return<false> {
[7ff3e522]271        template<typename core_t, typename node_t>
[26e6d88]272        static inline auto result( core_t & core, const node_t * & node ) {
273                return core.postvisit( node );
[c15085d]274        }
[26e6d88]275};
276
277//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
278// Deep magic (a.k.a template meta programming) to make the templated visitor work
279// Basically the goal is to make 2 previsit
280// 1 - Use when a pass implements a valid previsit. This uses overloading which means the any overload of
281//     'pass.previsit( node )' that compiles will be used for that node for that type
282//     This requires that this option only compile for passes that actually define an appropriate visit.
283//     SFINAE will make sure the compilation errors in this function don't halt the build.
284//     See http://en.cppreference.com/w/cpp/language/sfinae for details on SFINAE
285// 2 - Since the first implementation might not be specilizable, the second implementation exists and does nothing.
286//     This is needed only to eliminate the need for passes to specify any kind of handlers.
287//     The second implementation only works because it has a lower priority. This is due to the bogus last parameter.
288//     The second implementation takes a long while the first takes an int. Since the caller always passes an literal 0
289//     the first implementation takes priority in regards to overloading.
290//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
291// PreVisit : may mutate the pointer passed in if the node is mutated in the previsit call
292template<typename core_t, typename node_t>
293static inline auto previsit( core_t & core, const node_t * & node, int ) -> decltype( core.previsit( node ), void() ) {
294        static_assert(
295                is_valid_previsit<core_t, node_t>::value,
296                "Previsit may not change the type of the node. It must return its paremeter or void."
297        );
298
299        __assign<
300                std::is_void<
301                        decltype( core.previsit( node ) )
302                >::value
303        >::result( core, node );
304}
[c15085d]305
[26e6d88]306template<typename core_t, typename node_t>
307static inline auto previsit( core_t &, const node_t *, long ) {}
308
309// PostVisit : never mutates the passed pointer but may return a different node
310template<typename core_t, typename node_t>
311static inline auto postvisit( core_t & core, const node_t * node, int ) ->
312        decltype( core.postvisit( node ), node->accept( *(Visitor*)nullptr ) )
313{
314        return __return<
315                std::is_void<
316                        decltype( core.postvisit( node ) )
317                >::value
318        >::result( core, node );
319}
[c15085d]320
[26e6d88]321template<typename core_t, typename node_t>
322static inline const node_t * postvisit( core_t &, const node_t * node, long ) { return node; }
323
324//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
325// Deep magic (a.k.a template meta programming) continued
326// To make the templated visitor be more expressive, we allow 'accessories' : classes/structs the implementation can inherit
327// from in order to get extra functionallity for example
328// class ErrorChecker : WithShortCircuiting { ... };
329// Pass<ErrorChecker> checker;
330// this would define a pass that uses the templated visitor with the additionnal feature that it has short circuiting
331// Note that in all cases the accessories are not required but guarantee the requirements of the feature is matched
332//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
333// For several accessories, the feature is enabled by detecting that a specific field is present
334// Use a macro the encapsulate the logic of detecting a particular field
335// The type is not strictly enforced but does match the accessory
336#define FIELD_PTR( name, default_type ) \
337template< typename core_t > \
338static inline auto name( core_t & core, int ) -> decltype( &core.name ) { return &core.name; } \
339\
340template< typename core_t > \
341static inline default_type * name( core_t &, long ) { return nullptr; }
342
343// List of fields and their expected types
344FIELD_PTR( typeSubs, const ast::TypeSubstitution * )
345FIELD_PTR( stmtsToAddBefore, std::list< ast::ptr< ast::Stmt > > )
346FIELD_PTR( stmtsToAddAfter , std::list< ast::ptr< ast::Stmt > > )
347FIELD_PTR( declsToAddBefore, std::list< ast::ptr< ast::Decl > > )
348FIELD_PTR( declsToAddAfter , std::list< ast::ptr< ast::Decl > > )
349FIELD_PTR( visit_children, __pass::bool_ref )
350FIELD_PTR( at_cleanup, __pass::at_cleanup_t )
351FIELD_PTR( visitor, ast::Pass<core_t> * const )
352
353// Remove the macro to make sure we don't clash
354#undef FIELD_PTR
355
356template< typename core_t >
357static inline auto beginTrace(core_t &, int) -> decltype( core_t::traceId, void() ) {
358        // Stats::Heap::stacktrace_push(core_t::traceId);
359}
[c15085d]360
[26e6d88]361template< typename core_t >
362static inline auto endTrace(core_t &, int) -> decltype( core_t::traceId, void() ) {
363        // Stats::Heap::stacktrace_pop();
364}
[c15085d]365
[26e6d88]366template< typename core_t >
367static void beginTrace(core_t &, long) {}
[0dd9a5e]368
[26e6d88]369template< typename core_t >
370static void endTrace(core_t &, long) {}
[0dd9a5e]371
[26e6d88]372// Allows visitor to handle an error on top-level declarations, and possibly suppress the error.
373// If on_error() returns false, the error will be ignored. By default, it returns true.
[0dd9a5e]374
[26e6d88]375template< typename core_t >
376static bool on_error (core_t &, ptr<Decl> &, long) { return true; }
[95e5018]377
[26e6d88]378template< typename core_t >
379static auto on_error (core_t & core, ptr<Decl> & decl, int) -> decltype(core.on_error(decl)) {
380        return core.on_error(decl);
381}
[a9762dc]382
[26e6d88]383template< typename core_t, typename node_t >
384static auto make_location_guard( core_t & core, node_t * node, int )
385                -> decltype( node->location, ValueGuardPtr<const CodeLocation *>( &core.location ) ) {
386        ValueGuardPtr<const CodeLocation *> guard( &core.location );
387        core.location = &node->location;
388        return guard;
389}
[f47f887]390
[26e6d88]391template< typename core_t, typename node_t >
392static auto make_location_guard( core_t &, node_t *, long ) -> int {
393        return 0;
394}
[f47f887]395
[26e6d88]396// Another feature of the templated visitor is that it calls beginScope()/endScope() for compound statement.
397// All passes which have such functions are assumed desire this behaviour
398// detect it using the same strategy
399namespace scope {
400        template<typename core_t>
401        static inline auto enter( core_t & core, int ) -> decltype( core.beginScope(), void() ) {
402                core.beginScope();
403        }
[f47f887]404
[26e6d88]405        template<typename core_t>
406        static inline void enter( core_t &, long ) {}
[f47f887]407
[26e6d88]408        template<typename core_t>
409        static inline auto leave( core_t & core, int ) -> decltype( core.endScope(), void() ) {
410                core.endScope();
411        }
[f47f887]412
[26e6d88]413        template<typename core_t>
414        static inline void leave( core_t &, long ) {}
415} // namespace scope
416
417// Certain passes desire an up to date symbol table automatically
418// detect the presence of a member name `symtab` and call all the members appropriately
419namespace symtab {
420        // Some simple scoping rules
421        template<typename core_t>
422        static inline auto enter( core_t & core, int ) -> decltype( core.symtab, void() ) {
423                core.symtab.enterScope();
424        }
[f47f887]425
[26e6d88]426        template<typename core_t>
427        static inline auto enter( core_t &, long ) {}
428
429        template<typename core_t>
430        static inline auto leave( core_t & core, int ) -> decltype( core.symtab, void() ) {
431                core.symtab.leaveScope();
432        }
[6d51bd7]433
[26e6d88]434        template<typename core_t>
435        static inline auto leave( core_t &, long ) {}
[6d51bd7]436
[26e6d88]437        // The symbol table has 2 kind of functions mostly, 1 argument and 2 arguments
438        // Create macro to condense these common patterns
439        #define SYMTAB_FUNC1( func, type ) \
440        template<typename core_t> \
441        static inline auto func( core_t & core, int, type arg ) -> decltype( core.symtab.func( arg ), void() ) {\
442                core.symtab.func( arg ); \
443        } \
444        \
445        template<typename core_t> \
446        static inline void func( core_t &, long, type ) {}
447
448        #define SYMTAB_FUNC2( func, type1, type2 ) \
449        template<typename core_t> \
450        static inline auto func( core_t & core, int, type1 arg1, type2 arg2 ) -> decltype( core.symtab.func( arg1, arg2 ), void () ) {\
451                core.symtab.func( arg1, arg2 ); \
452        } \
453        \
454        template<typename core_t> \
455        static inline void func( core_t &, long, type1, type2 ) {}
456
457        SYMTAB_FUNC1( addId     , const DeclWithType *  );
458        SYMTAB_FUNC1( addType   , const NamedTypeDecl * );
459        SYMTAB_FUNC1( addStruct , const StructDecl *    );
460        SYMTAB_FUNC1( addEnum   , const EnumDecl *      );
461        SYMTAB_FUNC1( addUnion  , const UnionDecl *     );
462        SYMTAB_FUNC1( addTrait  , const TraitDecl *     );
463        SYMTAB_FUNC2( addWith   , const std::vector< ptr<Expr> > &, const Decl * );
464
465        // A few extra functions have more complicated behaviour, they are hand written
466        template<typename core_t>
467        static inline auto addStructFwd( core_t & core, int, const ast::StructDecl * decl ) -> decltype( core.symtab.addStruct( decl ), void() ) {
468                ast::StructDecl * fwd = new ast::StructDecl( decl->location, decl->name );
469                for ( const auto & param : decl->params ) {
470                        fwd->params.push_back( deepCopy( param.get() ) );
[6d51bd7]471                }
[26e6d88]472                core.symtab.addStruct( fwd );
473        }
[6d51bd7]474
[26e6d88]475        template<typename core_t>
476        static inline void addStructFwd( core_t &, long, const ast::StructDecl * ) {}
[6d51bd7]477
[26e6d88]478        template<typename core_t>
479        static inline auto addUnionFwd( core_t & core, int, const ast::UnionDecl * decl ) -> decltype( core.symtab.addUnion( decl ), void() ) {
480                ast::UnionDecl * fwd = new ast::UnionDecl( decl->location, decl->name );
481                for ( const auto & param : decl->params ) {
482                        fwd->params.push_back( deepCopy( param.get() ) );
[6d51bd7]483                }
[26e6d88]484                core.symtab.addUnion( fwd );
485        }
[6d51bd7]486
[26e6d88]487        template<typename core_t>
488        static inline void addUnionFwd( core_t &, long, const ast::UnionDecl * ) {}
[6d51bd7]489
[26e6d88]490        template<typename core_t>
[e0069bd]491        static inline auto addStructId( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addStructId( str ), void() ) {
[26e6d88]492                if ( ! core.symtab.lookupStruct( str ) ) {
[e0069bd]493                        core.symtab.addStructId( str );
[6d51bd7]494                }
[26e6d88]495        }
[6d51bd7]496
[26e6d88]497        template<typename core_t>
[e0069bd]498        static inline void addStructId( core_t &, long, const std::string & ) {}
[26e6d88]499
500        template<typename core_t>
[e0069bd]501        static inline auto addUnionId( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addUnionId( str ), void() ) {
[26e6d88]502                if ( ! core.symtab.lookupUnion( str ) ) {
[e0069bd]503                        core.symtab.addUnionId( str );
[e0e9a0b]504                }
[26e6d88]505        }
[e0e9a0b]506
[26e6d88]507        template<typename core_t>
[e0069bd]508        static inline void addUnionId( core_t &, long, const std::string & ) {}
[26e6d88]509
510        #undef SYMTAB_FUNC1
511        #undef SYMTAB_FUNC2
512} // namespace symtab
513
514// Some passes need to mutate TypeDecl and properly update their pointing TypeInstType.
515// Detect the presence of a member name `subs` and call all members appropriately
516namespace forall {
517        // Some simple scoping rules
518        template<typename core_t>
519        static inline auto enter( core_t & core, int, const ast::FunctionType * type )
520                        -> decltype( core.subs, void() ) {
521                if ( ! type->forall.empty() ) core.subs.beginScope();
522        }
[e0e9a0b]523
[26e6d88]524        template<typename core_t>
525        static inline auto enter( core_t &, long, const ast::FunctionType * ) {}
[e0e9a0b]526
[26e6d88]527        template<typename core_t>
528        static inline auto leave( core_t & core, int, const ast::FunctionType * type )
529                        -> decltype( core.subs, void() ) {
530                if ( ! type->forall.empty() ) { core.subs.endScope(); }
531        }
[e0e9a0b]532
[26e6d88]533        template<typename core_t>
534        static inline auto leave( core_t &, long, const ast::FunctionType * ) {}
[e0e9a0b]535
[26e6d88]536        // Replaces a TypeInstType's base TypeDecl according to the table
537        template<typename core_t>
538        static inline auto replace( core_t & core, int, const ast::TypeInstType *& inst )
539                        -> decltype( core.subs, void() ) {
540                inst = ast::mutate_field(
541                        inst, &ast::TypeInstType::base, core.subs.replace( inst->base ) );
542        }
[e6b42e7]543
[26e6d88]544        template<typename core_t>
545        static inline auto replace( core_t &, long, const ast::TypeInstType *& ) {}
546} // namespace forall
[c600df1]547
[26e6d88]548// For passes that need access to the global context. Searches `translationUnit`
549namespace translation_unit {
550        template<typename core_t>
551        static inline auto get_cptr( core_t & core, int )
552                        -> decltype( &core.translationUnit ) {
553                return &core.translationUnit;
[c600df1]554        }
555
[26e6d88]556        template<typename core_t>
557        static inline const TranslationUnit ** get_cptr( core_t &, long ) {
558                return nullptr;
559        }
560}
[e6b42e7]561
[26e6d88]562// For passes, usually utility passes, that have a result.
563namespace result {
564        template<typename core_t>
565        static inline auto get( core_t & core, char ) -> decltype( core.result() ) {
566                return core.result();
567        }
[e6b42e7]568
[26e6d88]569        template<typename core_t>
570        static inline auto get( core_t & core, int ) -> decltype( core.result ) {
571                return core.result;
[66a89e7]572        }
[cad9edb]573
[26e6d88]574        template<typename core_t>
575        static inline void get( core_t &, long ) {}
576}
577
[cad9edb]578} // namespace ast::__pass
[2d0f918]579
580#undef __pedantic_pass_assertf
581#undef __pedantic_pass_assert
Note: See TracBrowser for help on using the repository browser.