source: src/InitTweak/InitTweak.cc @ 5a73f0f

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 5a73f0f was caab997, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Recognize enumerators as constexpr

  • Property mode set to 100644
File size: 24.2 KB
RevLine 
[d180746]1#include <algorithm>               // for find, all_of
[e3e16bc]2#include <cassert>                 // for assertf, assert, strict_dynamic_cast
[d180746]3#include <iostream>                // for ostream, cerr, endl
4#include <iterator>                // for back_insert_iterator, back_inserter
5#include <memory>                  // for __shared_ptr
6
[fd236ed]7#include "Common/PassVisitor.h"
[d180746]8#include "Common/SemanticError.h"  // for SemanticError
9#include "Common/UniqueName.h"     // for UniqueName
10#include "Common/utility.h"        // for toString, deleteAll, maybeClone
11#include "GenPoly/GenPoly.h"       // for getFunctionType
[2b46a13]12#include "InitTweak.h"
[d180746]13#include "Parser/LinkageSpec.h"    // for Spec, isBuiltin, Intrinsic
14#include "ResolvExpr/typeops.h"    // for typesCompatibleIgnoreQualifiers
[f5c3b6c]15#include "SymTab/Autogen.h"
[d180746]16#include "SymTab/Indexer.h"        // for Indexer
17#include "SynTree/Attribute.h"     // for Attribute
18#include "SynTree/Constant.h"      // for Constant
19#include "SynTree/Declaration.h"   // for ObjectDecl, DeclarationWithType
20#include "SynTree/Expression.h"    // for Expression, UntypedExpr, Applicati...
21#include "SynTree/Initializer.h"   // for Initializer, ListInit, Designation
[ba3706f]22#include "SynTree/Label.h"         // for Label
[d180746]23#include "SynTree/Statement.h"     // for CompoundStmt, ExprStmt, BranchStmt
24#include "SynTree/Type.h"          // for FunctionType, ArrayType, PointerType
25#include "SynTree/Visitor.h"       // for Visitor, maybeAccept
[29bc63e]26#include "Tuples/Tuples.h"         // for Tuples::isTtype
[d180746]27
28class UntypedValofExpr;
[2b46a13]29
30namespace InitTweak {
[64071c2]31        namespace {
[1fbeebd]32                struct HasDesignations : public WithShortCircuiting {
[64071c2]33                        bool hasDesignations = false;
[fd236ed]34
35                        void previsit( BaseSyntaxNode * ) {
36                                // short circuit if we already know there are designations
37                                if ( hasDesignations ) visit_children = false;
38                        }
39
40                        void previsit( Designation * des ) {
41                                // short circuit if we already know there are designations
42                                if ( hasDesignations ) visit_children = false;
43                                else if ( ! des->get_designators().empty() ) {
44                                        hasDesignations = true;
45                                        visit_children = false;
46                                }
[64071c2]47                        }
48                };
[2b46a13]49
[ef3d798]50                struct InitDepthChecker : public WithGuards {
[dcd73d1]51                        bool depthOkay = true;
52                        Type * type;
53                        int curDepth = 0, maxDepth = 0;
54                        InitDepthChecker( Type * type ) : type( type ) {
55                                Type * t = type;
56                                while ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
57                                        maxDepth++;
58                                        t = at->get_base();
59                                }
60                                maxDepth++;
61                        }
[ef3d798]62                        void previsit( ListInit * ) {
[dcd73d1]63                                curDepth++;
[ef3d798]64                                GuardAction( [this]() { curDepth--; } );
[dcd73d1]65                                if ( curDepth > maxDepth ) depthOkay = false;
66                        }
67                };
68
[c3f551b]69                struct InitFlattener : public WithShortCircuiting {
70                        void previsit( SingleInit * singleInit ) {
71                                visit_children = false;
72                                argList.push_back( singleInit->value->clone() );
73                        }
[64071c2]74                        std::list< Expression * > argList;
75                };
[2b46a13]76
[64071c2]77        }
[2b46a13]78
[64071c2]79        std::list< Expression * > makeInitList( Initializer * init ) {
[c3f551b]80                PassVisitor<InitFlattener> flattener;
[4d2434a]81                maybeAccept( init, flattener );
[c3f551b]82                return flattener.pass.argList;
[64071c2]83        }
[2b46a13]84
[64071c2]85        bool isDesignated( Initializer * init ) {
[fd236ed]86                PassVisitor<HasDesignations> finder;
[64071c2]87                maybeAccept( init, finder );
[fd236ed]88                return finder.pass.hasDesignations;
[dcd73d1]89        }
90
91        bool checkInitDepth( ObjectDecl * objDecl ) {
[ef3d798]92                PassVisitor<InitDepthChecker> checker( objDecl->type );
93                maybeAccept( objDecl->init, checker );
94                return checker.pass.depthOkay;
[64071c2]95        }
[2b46a13]96
[39f84a4]97        class InitExpander::ExpanderImpl {
98        public:
[3351cc0]99                virtual ~ExpanderImpl() = default;
[39f84a4]100                virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
[4d2434a]101                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
[39f84a4]102        };
103
104        class InitImpl : public InitExpander::ExpanderImpl {
105        public:
[4d2434a]106                InitImpl( Initializer * init ) : init( init ) {}
[bd41764]107                virtual ~InitImpl() = default;
[39f84a4]108
[7e003011]109                virtual std::list< Expression * > next( __attribute((unused)) std::list< Expression * > & indices ) {
[39f84a4]110                        // this is wrong, but just a placeholder for now
[4d2434a]111                        // if ( ! flattened ) flatten( indices );
112                        // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
113                        return makeInitList( init );
[39f84a4]114                }
[4d2434a]115
116                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]117        private:
[4d2434a]118                Initializer * init;
[39f84a4]119        };
120
121        class ExprImpl : public InitExpander::ExpanderImpl {
122        public:
123                ExprImpl( Expression * expr ) : arg( expr ) {}
[bd41764]124                virtual ~ExprImpl() { delete arg; }
[9b4c936]125
[39f84a4]126                virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
127                        std::list< Expression * > ret;
128                        Expression * expr = maybeClone( arg );
129                        if ( expr ) {
130                                for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
131                                        // go through indices and layer on subscript exprs ?[?]
132                                        ++it;
133                                        UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
134                                        subscriptExpr->get_args().push_back( expr );
135                                        subscriptExpr->get_args().push_back( (*it)->clone() );
136                                        expr = subscriptExpr;
137                                }
138                                ret.push_back( expr );
139                        }
140                        return ret;
141                }
[4d2434a]142
143                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]144        private:
145                Expression * arg;
146        };
147
148        InitExpander::InitExpander( Initializer * init ) : expander( new InitImpl( init ) ) {}
149
150        InitExpander::InitExpander( Expression * expr ) : expander( new ExprImpl( expr ) ) {}
151
152        std::list< Expression * > InitExpander::operator*() {
153                return cur;
154        }
155
156        InitExpander & InitExpander::operator++() {
157                cur = expander->next( indices );
158                return *this;
159        }
160
161        // use array indices list to build switch statement
162        void InitExpander::addArrayIndex( Expression * index, Expression * dimension ) {
163                indices.push_back( index );
164                indices.push_back( dimension );
165        }
166
[4d2434a]167        void InitExpander::clearArrayIndices() {
[9b4c936]168                deleteAll( indices );
[4d2434a]169                indices.clear();
[1a5ad8c]170        }
171
172        bool InitExpander::addReference() {
173                bool added = false;
174                for ( Expression *& expr : cur ) {
175                        expr = new AddressExpr( expr );
176                        added = true;
177                }
178                return added;
[4d2434a]179        }
180
181        namespace {
[f9cebb5]182                /// given index i, dimension d, initializer init, and callExpr f, generates
183                ///   if (i < d) f(..., init)
184                ///   ++i;
185                /// so that only elements within the range of the array are constructed
[4d2434a]186                template< typename OutIterator >
[f9cebb5]187                void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
[4d2434a]188                        UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
189                        cond->get_args().push_back( index->clone() );
190                        cond->get_args().push_back( dimension->clone() );
191
192                        std::list< Expression * > args = makeInitList( init );
193                        callExpr->get_args().splice( callExpr->get_args().end(), args );
194
[ba3706f]195                        *out++ = new IfStmt( cond, new ExprStmt( callExpr ), nullptr );
[4d2434a]196
197                        UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
[175ad32]198                        increment->get_args().push_back( index->clone() );
[ba3706f]199                        *out++ = new ExprStmt( increment );
[4d2434a]200                }
201
202                template< typename OutIterator >
203                void build( UntypedExpr * callExpr, InitExpander::IndexList::iterator idx, InitExpander::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
204                        if ( idx == idxEnd ) return;
205                        Expression * index = *idx++;
206                        assert( idx != idxEnd );
207                        Expression * dimension = *idx++;
208
[f9cebb5]209                        // xxx - may want to eventually issue a warning here if we can detect
210                        // that the number of elements exceeds to dimension of the array
[4d2434a]211                        if ( idx == idxEnd ) {
212                                if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
213                                        for ( Initializer * init : *listInit ) {
[f9cebb5]214                                                buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]215                                        }
216                                } else {
[f9cebb5]217                                        buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]218                                }
219                        } else {
220                                std::list< Statement * > branches;
221
222                                unsigned long cond = 0;
223                                ListInit * listInit = dynamic_cast< ListInit * >( init );
224                                if ( ! listInit ) {
225                                        // xxx - this shouldn't be an error, but need a way to
226                                        // terminate without creating output, so should catch this error
227                                        throw SemanticError( "unbalanced list initializers" );
228                                }
[f9cebb5]229
230                                static UniqueName targetLabel( "L__autogen__" );
231                                Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
[4d2434a]232                                for ( Initializer * init : *listInit ) {
233                                        Expression * condition;
234                                        // check for designations
235                                        // if ( init-> ) {
236                                                condition = new ConstantExpr( Constant::from_ulong( cond ) );
237                                                ++cond;
238                                        // } else {
239                                        //      condition = // ... take designation
240                                        //      cond = // ... take designation+1
241                                        // }
242                                        std::list< Statement * > stmts;
243                                        build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
[ba3706f]244                                        stmts.push_back( new BranchStmt( switchLabel, BranchStmt::Break ) );
245                                        CaseStmt * caseStmt = new CaseStmt( condition, stmts );
[4d2434a]246                                        branches.push_back( caseStmt );
247                                }
[ba3706f]248                                *out++ = new SwitchStmt( index->clone(), branches );
249                                *out++ = new NullStmt( { switchLabel } );
[4d2434a]250                        }
251                }
252        }
253
254        // if array came with an initializer list: initialize each element
255        // may have more initializers than elements in the array - need to check at each index that
256        // we haven't exceeded size.
257        // may have fewer initializers than elements in the array - need to default construct
258        // remaining elements.
259        // To accomplish this, generate switch statement, consuming all of expander's elements
260        Statement * InitImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
[22bc276]261                if ( ! init ) return nullptr;
[ba3706f]262                CompoundStmt * block = new CompoundStmt();
[f9cebb5]263                build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
264                if ( block->get_kids().empty() ) {
265                        delete block;
[22bc276]266                        return nullptr;
[4d2434a]267                } else {
[22bc276]268                        init = nullptr; // init was consumed in creating the list init
[f9cebb5]269                        return block;
[4d2434a]270                }
[39f84a4]271        }
272
[22bc276]273        Statement * ExprImpl::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
274                return nullptr;
[4d2434a]275        }
276
277        Statement * InitExpander::buildListInit( UntypedExpr * dst ) {
278                return expander->buildListInit( dst, indices );
279        }
280
[549c006]281        Type * getTypeofThis( FunctionType * ftype ) {
282                assertf( ftype, "getTypeofThis: nullptr ftype" );
283                ObjectDecl * thisParam = getParamThis( ftype );
[7fc7cdb]284                ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
285                return refType->base;
286        }
287
[549c006]288        ObjectDecl * getParamThis( FunctionType * ftype ) {
289                assertf( ftype, "getParamThis: nullptr ftype" );
[7fc7cdb]290                auto & params = ftype->parameters;
[549c006]291                assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
[7fc7cdb]292                return strict_dynamic_cast< ObjectDecl * >( params.front() );
293        }
294
[22bc276]295        bool tryConstruct( DeclarationWithType * dwt ) {
296                ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
297                if ( ! objDecl ) return false;
[64071c2]298                return ! LinkageSpec::isBuiltin( objDecl->get_linkage() ) &&
[22bc276]299                        (objDecl->get_init() == nullptr ||
300                                ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
301                        && ! objDecl->get_storageClasses().is_extern
[29bc63e]302                        && isConstructable( objDecl->type );
303        }
304
305        bool isConstructable( Type * type ) {
306                return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
[64071c2]307        }
[2b46a13]308
[0a6aad4]309        struct CallFinder {
[4d2434a]310                CallFinder( const std::list< std::string > & names ) : names( names ) {}
311
[0a6aad4]312                void postvisit( ApplicationExpr * appExpr ) {
[4d2434a]313                        handleCallExpr( appExpr );
314                }
315
[0a6aad4]316                void postvisit( UntypedExpr * untypedExpr ) {
[4d2434a]317                        handleCallExpr( untypedExpr );
318                }
319
320                std::list< Expression * > * matches;
321        private:
322                const std::list< std::string > names;
323
324                template< typename CallExpr >
325                void handleCallExpr( CallExpr * expr ) {
326                        std::string fname = getFunctionName( expr );
327                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
328                                matches->push_back( expr );
[cad355a]329                        }
[64071c2]330                }
[4d2434a]331        };
332
333        void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
[0a6aad4]334                static PassVisitor<CallFinder> finder( std::list< std::string >{ "?{}", "^?{}" } );
335                finder.pass.matches = &matches;
[4d2434a]336                maybeAccept( stmt, finder );
[64071c2]337        }
[4d2434a]338
339        Expression * getCtorDtorCall( Statement * stmt ) {
340                std::list< Expression * > matches;
341                collectCtorDtorCalls( stmt, matches );
342                assert( matches.size() <= 1 );
[22bc276]343                return matches.size() == 1 ? matches.front() : nullptr;
[4d2434a]344        }
345
[aedfd91]346        namespace {
[599b386]347                DeclarationWithType * getCalledFunction( Expression * expr );
348
349                template<typename CallExpr>
350                DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
351                        // (*f)(x) => should get "f"
352                        std::string name = getFunctionName( expr );
353                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
[b128d3e]354                        assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
[599b386]355                        return getCalledFunction( expr->get_args().front() );
356                }
357
[ee1635c8]358                DeclarationWithType * getCalledFunction( Expression * expr ) {
359                        assert( expr );
360                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
[6fc5c14]361                                return varExpr->var;
[ee1635c8]362                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
[6fc5c14]363                                return memberExpr->member;
[ee1635c8]364                        } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
[6fc5c14]365                                return getCalledFunction( castExpr->arg );
[599b386]366                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
367                                return handleDerefCalledFunction( untypedExpr );
368                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
369                                return handleDerefCalledFunction( appExpr );
[f3b0a07]370                        } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
[6fc5c14]371                                return getCalledFunction( addrExpr->arg );
372                        } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
373                                return getCalledFunction( commaExpr->arg2 );
[ee1635c8]374                        }
375                        return nullptr;
[aedfd91]376                }
377        }
[70f89d00]378
[b7b8674]379        DeclarationWithType * getFunction( Expression * expr ) {
380                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
381                        return getCalledFunction( appExpr->get_function() );
382                } else if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * > ( expr ) ) {
383                        return getCalledFunction( untyped->get_function() );
384                }
385                assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
386        }
387
[aedfd91]388        ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
389                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
[22bc276]390                if ( ! appExpr ) return nullptr;
[ee1635c8]391                DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
[f3b0a07]392                assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
[64071c2]393                // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
394                // will call all member dtors, and some members may have a user defined dtor.
[22bc276]395                return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
[aedfd91]396        }
397
[a465caf]398        namespace {
399                template <typename Predicate>
400                bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
401                        std::list< Expression * > callExprs;
402                        collectCtorDtorCalls( stmt, callExprs );
403                        // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
404                        return std::all_of( callExprs.begin(), callExprs.end(), pred);
405                }
406        }
407
[f9cebb5]408        bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
[a465caf]409                return allofCtorDtor( stmt, []( Expression * callExpr ){
[4d2434a]410                        if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
[906e24d]411                                FunctionType *funcType = GenPoly::getFunctionType( appExpr->get_function()->get_result() );
[4d2434a]412                                assert( funcType );
413                                return funcType->get_parameters().size() == 1;
414                        }
415                        return false;
416                });
[64071c2]417        }
[f1b1e4c]418
[a465caf]419        bool isIntrinsicCallStmt( Statement * stmt ) {
420                return allofCtorDtor( stmt, []( Expression * callExpr ) {
421                        return isIntrinsicCallExpr( callExpr );
422                });
423        }
424
[64071c2]425        namespace {
426                template<typename CallExpr>
427                Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
[a61ad31]428                        if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
[64071c2]429                        for ( Expression *& arg : callExpr->get_args() ) {
430                                if ( pos == 0 ) return arg;
431                                pos--;
432                        }
433                        assert( false );
434                }
435        }
[f1b1e4c]436
[64071c2]437        Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
438                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
439                        return callArg( appExpr, pos );
440                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
441                        return callArg( untypedExpr, pos );
[f3b0a07]442                } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
443                        std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
444                        assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
[e3e16bc]445                        ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
446                        TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
[f3b0a07]447                        assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
448                        return getCallArg( tuple->get_exprs().front(), pos );
[62a05d1]449                } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
450                        return getCallArg( copyCtor->callExpr, pos );
[64071c2]451                } else {
[f3b0a07]452                        assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
[64071c2]453                }
454        }
[f1b1e4c]455
[64071c2]456        namespace {
[599b386]457                std::string funcName( Expression * func );
458
459                template<typename CallExpr>
460                std::string handleDerefName( CallExpr * expr ) {
461                        // (*f)(x) => should get name "f"
462                        std::string name = getFunctionName( expr );
463                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
[b128d3e]464                        assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
[599b386]465                        return funcName( expr->get_args().front() );
466                }
467
[c738ca4]468                std::string funcName( Expression * func ) {
[64071c2]469                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
470                                return nameExpr->get_name();
471                        } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
472                                return varExpr->get_var()->get_name();
[c738ca4]473                        }       else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
474                                return funcName( castExpr->get_arg() );
[ee1635c8]475                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
476                                return memberExpr->get_member()->get_name();
[96a10cd]477                        } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
[fd782b2]478                                return funcName( memberExpr->get_member() );
[599b386]479                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
480                                return handleDerefName( untypedExpr );
481                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
482                                return handleDerefName( appExpr );
[19a9822]483                        } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
484                                return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
[64071c2]485                        } else {
[19a9822]486                                assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
[64071c2]487                        }
488                }
489        }
[70f89d00]490
[64071c2]491        std::string getFunctionName( Expression * expr ) {
[599b386]492                // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
493                // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
494                // can't possibly do anything reasonable.
[64071c2]495                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
[c738ca4]496                        return funcName( appExpr->get_function() );
[64071c2]497                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
[c738ca4]498                        return funcName( untypedExpr->get_function() );
[64071c2]499                } else {
[c738ca4]500                        std::cerr << expr << std::endl;
[d1969a6]501                        assertf( false, "Unexpected expression type passed to getFunctionName" );
[64071c2]502                }
503        }
[10a7775]504
[64071c2]505        Type * getPointerBase( Type * type ) {
506                if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
507                        return ptrType->get_base();
508                } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
509                        return arrayType->get_base();
[ce8c12f]510                } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
511                        return refType->get_base();
[64071c2]512                } else {
[22bc276]513                        return nullptr;
[64071c2]514                }
515        }
[10a7775]516
[64071c2]517        Type * isPointerType( Type * type ) {
518                if ( getPointerBase( type ) ) return type;
[22bc276]519                else return nullptr;
[64071c2]520        }
[40e636a]521
[f5c3b6c]522        ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src ) {
523                static FunctionDecl * assign = nullptr;
524                if ( ! assign ) {
525                        // temporary? Generate a fake assignment operator to represent bitwise assignments.
526                        // This operator could easily exist as a real function, but it's tricky because nothing should resolve to this function.
527                        TypeDecl * td = new TypeDecl( "T", noStorageClasses, nullptr, TypeDecl::Dtype, true );
528                        assign = new FunctionDecl( "?=?", noStorageClasses, LinkageSpec::Intrinsic, SymTab::genAssignType( new TypeInstType( noQualifiers, td->name, td ) ), nullptr );
529                }
530                if ( dynamic_cast< ReferenceType * >( dst->result ) ) {
531                        dst = new AddressExpr( dst );
532                } else {
533                        dst = new CastExpr( dst, new ReferenceType( noQualifiers, dst->result->clone() ) );
534                }
535                if ( dynamic_cast< ReferenceType * >( src->result ) ) {
536                        src = new CastExpr( src, new ReferenceType( noQualifiers, src->result->stripReferences()->clone() ) );
537                }
538                return new ApplicationExpr( VariableExpr::functionPointer( assign ), { dst, src } );
539        }
540
[c5f3c68]541        struct ConstExprChecker : public WithShortCircuiting {
542                // most expressions are not const expr
543                void previsit( Expression * ) { isConstExpr = false; visit_children = false; }
[40e636a]544
[c5f3c68]545                void previsit( AddressExpr *addressExpr ) {
546                        visit_children = false;
[65dc863]547
[1ba88a0]548                        // address of a variable or member expression is constexpr
549                        Expression * arg = addressExpr->get_arg();
550                        if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
551                }
[c5f3c68]552
553                // these expressions may be const expr, depending on their children
554                void previsit( SizeofExpr * ) {}
555                void previsit( AlignofExpr * ) {}
556                void previsit( UntypedOffsetofExpr * ) {}
557                void previsit( OffsetofExpr * ) {}
558                void previsit( OffsetPackExpr * ) {}
559                void previsit( AttrExpr * ) {}
560                void previsit( CommaExpr * ) {}
561                void previsit( LogicalExpr * ) {}
562                void previsit( ConditionalExpr * ) {}
563                void previsit( CastExpr * ) {}
564                void previsit( ConstantExpr * ) {}
565
[caab997]566                void previsit( VariableExpr * varExpr ) {
567                        visit_children = false;
568
569                        if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( varExpr->result ) ) {
570                                long long int value;
571                                if ( inst->baseEnum->valueOf( varExpr->var, value ) ) {
572                                        // enumerators are const expr
573                                        return;
574                                }
575                        }
576                        isConstExpr = false;
577                }
578
[c5f3c68]579                bool isConstExpr = true;
[40e636a]580        };
581
582        bool isConstExpr( Expression * expr ) {
583                if ( expr ) {
[c5f3c68]584                        PassVisitor<ConstExprChecker> checker;
[40e636a]585                        expr->accept( checker );
[c5f3c68]586                        return checker.pass.isConstExpr;
[40e636a]587                }
588                return true;
589        }
590
591        bool isConstExpr( Initializer * init ) {
592                if ( init ) {
[c5f3c68]593                        PassVisitor<ConstExprChecker> checker;
[40e636a]594                        init->accept( checker );
[c5f3c68]595                        return checker.pass.isConstExpr;
[40e636a]596                } // if
597                // for all intents and purposes, no initializer means const expr
598                return true;
599        }
600
[79970ed]601        bool isConstructor( const std::string & str ) { return str == "?{}"; }
602        bool isDestructor( const std::string & str ) { return str == "^?{}"; }
[ee1635c8]603        bool isAssignment( const std::string & str ) { return str == "?=?"; }
[79970ed]604        bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
[ee1635c8]605        bool isCtorDtorAssign( const std::string & str ) { return isCtorDtor( str ) || isAssignment( str ); }
[4d4882a]606
[ee1635c8]607        FunctionDecl * isCopyFunction( Declaration * decl, const std::string & fname ) {
[4d4882a]608                FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl );
[0a267c1]609                if ( ! function ) return nullptr;
610                if ( function->name != fname ) return nullptr;
611                FunctionType * ftype = function->type;
612                if ( ftype->parameters.size() != 2 ) return nullptr;
[4d4882a]613
[ce8c12f]614                Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
[0a267c1]615                Type * t2 = ftype->parameters.back()->get_type();
[ce8c12f]616                assert( t1 );
[4d4882a]617
[ce8c12f]618                if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
[4d4882a]619                        return function;
620                } else {
[ee1635c8]621                        return nullptr;
[4d4882a]622                }
623        }
[ee1635c8]624
[207c7e1d]625        FunctionDecl * isAssignment( Declaration * decl ) {
626                return isCopyFunction( decl, "?=?" );
627        }
628        FunctionDecl * isDestructor( Declaration * decl ) {
629                if ( isDestructor( decl->get_name() ) ) {
630                        return dynamic_cast< FunctionDecl * >( decl );
631                }
632                return nullptr;
633        }
634        FunctionDecl * isDefaultConstructor( Declaration * decl ) {
[0a267c1]635                if ( isConstructor( decl->name ) ) {
[207c7e1d]636                        if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
[0a267c1]637                                if ( func->type->parameters.size() == 1 ) {
[207c7e1d]638                                        return func;
639                                }
640                        }
641                }
642                return nullptr;
643        }
[ee1635c8]644        FunctionDecl * isCopyConstructor( Declaration * decl ) {
645                return isCopyFunction( decl, "?{}" );
646        }
[2b46a13]647}
Note: See TracBrowser for help on using the repository browser.