source: src/InitTweak/InitTweak.cc @ ef3d798

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 ef3d798 was ef3d798, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Convert InitDepthChecker? to PassVisitor?

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