source: src/InitTweak/InitTweak.cc @ a2a85658

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since a2a85658 was 2d11663, checked in by Aaron Moss <a3moss@…>, 5 years ago

resolver porting; finish top level of initialization

  • Property mode set to 100644
File size: 33.8 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 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// InitTweak.cc --
8//
9// Author           : Rob Schluntz
10// Created On       : Fri May 13 11:26:36 2016
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Mon Jun 10 13:30:00 2019
13// Update Count     : 5
14//
15
16#include <algorithm>               // for find, all_of
17#include <cassert>                 // for assertf, assert, strict_dynamic_cast
18#include <iostream>                // for ostream, cerr, endl
19#include <iterator>                // for back_insert_iterator, back_inserter
20#include <memory>                  // for __shared_ptr
21#include <vector>
22
23#include "AST/Expr.hpp"
24#include "AST/Stmt.hpp"
25#include "AST/Type.hpp"
26#include "Common/PassVisitor.h"
27#include "Common/SemanticError.h"  // for SemanticError
28#include "Common/UniqueName.h"     // for UniqueName
29#include "Common/utility.h"        // for toString, deleteAll, maybeClone
30#include "GenPoly/GenPoly.h"       // for getFunctionType
31#include "InitTweak.h"
32#include "Parser/LinkageSpec.h"    // for Spec, isBuiltin, Intrinsic
33#include "ResolvExpr/typeops.h"    // for typesCompatibleIgnoreQualifiers
34#include "SymTab/Autogen.h"
35#include "SymTab/Indexer.h"        // for Indexer
36#include "SynTree/Attribute.h"     // for Attribute
37#include "SynTree/Constant.h"      // for Constant
38#include "SynTree/Declaration.h"   // for ObjectDecl, DeclarationWithType
39#include "SynTree/Expression.h"    // for Expression, UntypedExpr, Applicati...
40#include "SynTree/Initializer.h"   // for Initializer, ListInit, Designation
41#include "SynTree/Label.h"         // for Label
42#include "SynTree/Statement.h"     // for CompoundStmt, ExprStmt, BranchStmt
43#include "SynTree/Type.h"          // for FunctionType, ArrayType, PointerType
44#include "SynTree/Visitor.h"       // for Visitor, maybeAccept
45#include "Tuples/Tuples.h"         // for Tuples::isTtype
46
47namespace InitTweak {
48        namespace {
49                struct HasDesignations : public WithShortCircuiting {
50                        bool hasDesignations = false;
51
52                        void previsit( BaseSyntaxNode * ) {
53                                // short circuit if we already know there are designations
54                                if ( hasDesignations ) visit_children = false;
55                        }
56
57                        void previsit( Designation * des ) {
58                                // short circuit if we already know there are designations
59                                if ( hasDesignations ) visit_children = false;
60                                else if ( ! des->get_designators().empty() ) {
61                                        hasDesignations = true;
62                                        visit_children = false;
63                                }
64                        }
65                };
66
67                struct InitDepthChecker : public WithGuards {
68                        bool depthOkay = true;
69                        Type * type;
70                        int curDepth = 0, maxDepth = 0;
71                        InitDepthChecker( Type * type ) : type( type ) {
72                                Type * t = type;
73                                while ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
74                                        maxDepth++;
75                                        t = at->get_base();
76                                }
77                                maxDepth++;
78                        }
79                        void previsit( ListInit * ) {
80                                curDepth++;
81                                GuardAction( [this]() { curDepth--; } );
82                                if ( curDepth > maxDepth ) depthOkay = false;
83                        }
84                };
85
86                struct InitFlattener : public WithShortCircuiting {
87                        void previsit( SingleInit * singleInit ) {
88                                visit_children = false;
89                                argList.push_back( singleInit->value->clone() );
90                        }
91                        std::list< Expression * > argList;
92                };
93
94        }
95
96        std::list< Expression * > makeInitList( Initializer * init ) {
97                PassVisitor<InitFlattener> flattener;
98                maybeAccept( init, flattener );
99                return flattener.pass.argList;
100        }
101
102        bool isDesignated( Initializer * init ) {
103                PassVisitor<HasDesignations> finder;
104                maybeAccept( init, finder );
105                return finder.pass.hasDesignations;
106        }
107
108        bool checkInitDepth( ObjectDecl * objDecl ) {
109                PassVisitor<InitDepthChecker> checker( objDecl->type );
110                maybeAccept( objDecl->init, checker );
111                return checker.pass.depthOkay;
112        }
113
114        class InitExpander::ExpanderImpl {
115        public:
116                virtual ~ExpanderImpl() = default;
117                virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
118                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
119        };
120
121        class InitImpl : public InitExpander::ExpanderImpl {
122        public:
123                InitImpl( Initializer * init ) : init( init ) {}
124                virtual ~InitImpl() = default;
125
126                virtual std::list< Expression * > next( __attribute((unused)) std::list< Expression * > & indices ) {
127                        // this is wrong, but just a placeholder for now
128                        // if ( ! flattened ) flatten( indices );
129                        // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
130                        return makeInitList( init );
131                }
132
133                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
134        private:
135                Initializer * init;
136        };
137
138        class ExprImpl : public InitExpander::ExpanderImpl {
139        public:
140                ExprImpl( Expression * expr ) : arg( expr ) {}
141                virtual ~ExprImpl() { delete arg; }
142
143                virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
144                        std::list< Expression * > ret;
145                        Expression * expr = maybeClone( arg );
146                        if ( expr ) {
147                                for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
148                                        // go through indices and layer on subscript exprs ?[?]
149                                        ++it;
150                                        UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
151                                        subscriptExpr->get_args().push_back( expr );
152                                        subscriptExpr->get_args().push_back( (*it)->clone() );
153                                        expr = subscriptExpr;
154                                }
155                                ret.push_back( expr );
156                        }
157                        return ret;
158                }
159
160                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
161        private:
162                Expression * arg;
163        };
164
165        InitExpander::InitExpander( Initializer * init ) : expander( new InitImpl( init ) ) {}
166
167        InitExpander::InitExpander( Expression * expr ) : expander( new ExprImpl( expr ) ) {}
168
169        std::list< Expression * > InitExpander::operator*() {
170                return cur;
171        }
172
173        InitExpander & InitExpander::operator++() {
174                cur = expander->next( indices );
175                return *this;
176        }
177
178        // use array indices list to build switch statement
179        void InitExpander::addArrayIndex( Expression * index, Expression * dimension ) {
180                indices.push_back( index );
181                indices.push_back( dimension );
182        }
183
184        void InitExpander::clearArrayIndices() {
185                deleteAll( indices );
186                indices.clear();
187        }
188
189        bool InitExpander::addReference() {
190                bool added = false;
191                for ( Expression *& expr : cur ) {
192                        expr = new AddressExpr( expr );
193                        added = true;
194                }
195                return added;
196        }
197
198        namespace {
199                /// given index i, dimension d, initializer init, and callExpr f, generates
200                ///   if (i < d) f(..., init)
201                ///   ++i;
202                /// so that only elements within the range of the array are constructed
203                template< typename OutIterator >
204                void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
205                        UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
206                        cond->get_args().push_back( index->clone() );
207                        cond->get_args().push_back( dimension->clone() );
208
209                        std::list< Expression * > args = makeInitList( init );
210                        callExpr->get_args().splice( callExpr->get_args().end(), args );
211
212                        *out++ = new IfStmt( cond, new ExprStmt( callExpr ), nullptr );
213
214                        UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
215                        increment->get_args().push_back( index->clone() );
216                        *out++ = new ExprStmt( increment );
217                }
218
219                template< typename OutIterator >
220                void build( UntypedExpr * callExpr, InitExpander::IndexList::iterator idx, InitExpander::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
221                        if ( idx == idxEnd ) return;
222                        Expression * index = *idx++;
223                        assert( idx != idxEnd );
224                        Expression * dimension = *idx++;
225
226                        // xxx - may want to eventually issue a warning here if we can detect
227                        // that the number of elements exceeds to dimension of the array
228                        if ( idx == idxEnd ) {
229                                if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
230                                        for ( Initializer * init : *listInit ) {
231                                                buildCallExpr( callExpr->clone(), index, dimension, init, out );
232                                        }
233                                } else {
234                                        buildCallExpr( callExpr->clone(), index, dimension, init, out );
235                                }
236                        } else {
237                                std::list< Statement * > branches;
238
239                                unsigned long cond = 0;
240                                ListInit * listInit = dynamic_cast< ListInit * >( init );
241                                if ( ! listInit ) {
242                                        // xxx - this shouldn't be an error, but need a way to
243                                        // terminate without creating output, so should catch this error
244                                        SemanticError( init->location, "unbalanced list initializers" );
245                                }
246
247                                static UniqueName targetLabel( "L__autogen__" );
248                                Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
249                                for ( Initializer * init : *listInit ) {
250                                        Expression * condition;
251                                        // check for designations
252                                        // if ( init-> ) {
253                                                condition = new ConstantExpr( Constant::from_ulong( cond ) );
254                                                ++cond;
255                                        // } else {
256                                        //      condition = // ... take designation
257                                        //      cond = // ... take designation+1
258                                        // }
259                                        std::list< Statement * > stmts;
260                                        build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
261                                        stmts.push_back( new BranchStmt( switchLabel, BranchStmt::Break ) );
262                                        CaseStmt * caseStmt = new CaseStmt( condition, stmts );
263                                        branches.push_back( caseStmt );
264                                }
265                                *out++ = new SwitchStmt( index->clone(), branches );
266                                *out++ = new NullStmt( { switchLabel } );
267                        }
268                }
269        }
270
271        // if array came with an initializer list: initialize each element
272        // may have more initializers than elements in the array - need to check at each index that
273        // we haven't exceeded size.
274        // may have fewer initializers than elements in the array - need to default construct
275        // remaining elements.
276        // To accomplish this, generate switch statement, consuming all of expander's elements
277        Statement * InitImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
278                if ( ! init ) return nullptr;
279                CompoundStmt * block = new CompoundStmt();
280                build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
281                if ( block->get_kids().empty() ) {
282                        delete block;
283                        return nullptr;
284                } else {
285                        init = nullptr; // init was consumed in creating the list init
286                        return block;
287                }
288        }
289
290        Statement * ExprImpl::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
291                return nullptr;
292        }
293
294        Statement * InitExpander::buildListInit( UntypedExpr * dst ) {
295                return expander->buildListInit( dst, indices );
296        }
297
298        Type * getTypeofThis( FunctionType * ftype ) {
299                assertf( ftype, "getTypeofThis: nullptr ftype" );
300                ObjectDecl * thisParam = getParamThis( ftype );
301                ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
302                return refType->base;
303        }
304
305        ObjectDecl * getParamThis( FunctionType * ftype ) {
306                assertf( ftype, "getParamThis: nullptr ftype" );
307                auto & params = ftype->parameters;
308                assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
309                return strict_dynamic_cast< ObjectDecl * >( params.front() );
310        }
311
312        bool tryConstruct( DeclarationWithType * dwt ) {
313                ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
314                if ( ! objDecl ) return false;
315                return (objDecl->get_init() == nullptr ||
316                                ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
317                        && ! objDecl->get_storageClasses().is_extern
318                        && isConstructable( objDecl->type );
319        }
320
321        bool isConstructable( Type * type ) {
322                return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
323        }
324
325        struct CallFinder_old {
326                CallFinder_old( const std::list< std::string > & names ) : names( names ) {}
327
328                void postvisit( ApplicationExpr * appExpr ) {
329                        handleCallExpr( appExpr );
330                }
331
332                void postvisit( UntypedExpr * untypedExpr ) {
333                        handleCallExpr( untypedExpr );
334                }
335
336                std::list< Expression * > * matches;
337        private:
338                const std::list< std::string > names;
339
340                template< typename CallExpr >
341                void handleCallExpr( CallExpr * expr ) {
342                        std::string fname = getFunctionName( expr );
343                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
344                                matches->push_back( expr );
345                        }
346                }
347        };
348
349        struct CallFinder_new final {
350                std::vector< ast::ptr< ast::Expr > > matches;
351                const std::vector< std::string > names;
352
353                CallFinder_new( std::vector< std::string > && ns ) : matches(), names( std::move(ns) ) {}
354
355                void handleCallExpr( const ast::Expr * expr ) {
356                        std::string fname = getFunctionName( expr );
357                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
358                                matches.emplace_back( expr );
359                        }
360                }
361
362                void postvisit( const ast::ApplicationExpr * expr ) { handleCallExpr( expr ); }
363                void postvisit( const ast::UntypedExpr *     expr ) { handleCallExpr( expr ); }
364        };
365
366        void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
367                static PassVisitor<CallFinder_old> finder( std::list< std::string >{ "?{}", "^?{}" } );
368                finder.pass.matches = &matches;
369                maybeAccept( stmt, finder );
370        }
371
372        std::vector< ast::ptr< ast::Expr > > collectCtorDtorCalls( const ast::Stmt * stmt ) {
373                ast::Pass< CallFinder_new > finder{ std::vector< std::string >{ "?{}", "^?{}" } };
374                maybe_accept( stmt, finder );
375                return std::move( finder.pass.matches );
376        }
377
378        Expression * getCtorDtorCall( Statement * stmt ) {
379                std::list< Expression * > matches;
380                collectCtorDtorCalls( stmt, matches );
381                assertf( matches.size() <= 1, "%zd constructor/destructors found in %s", matches.size(), toString( stmt ).c_str() );
382                return matches.size() == 1 ? matches.front() : nullptr;
383        }
384
385        namespace {
386                DeclarationWithType * getCalledFunction( Expression * expr );
387                const ast::DeclWithType * getCalledFunction( const ast::Expr * expr );
388
389                template<typename CallExpr>
390                DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
391                        // (*f)(x) => should get "f"
392                        std::string name = getFunctionName( expr );
393                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
394                        assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
395                        return getCalledFunction( expr->get_args().front() );
396                }
397
398                template<typename CallExpr>
399                const ast::DeclWithType * handleDerefCalledFunction( const CallExpr * expr ) {
400                        // (*f)(x) => should get "f"
401                        std::string name = getFunctionName( expr );
402                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
403                        assertf( ! expr->args.empty(), "Cannot get called function from dereference with no arguments" );
404                        return getCalledFunction( expr->args.front() );
405                }
406
407
408                DeclarationWithType * getCalledFunction( Expression * expr ) {
409                        assert( expr );
410                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
411                                return varExpr->var;
412                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
413                                return memberExpr->member;
414                        } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
415                                return getCalledFunction( castExpr->arg );
416                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
417                                return handleDerefCalledFunction( untypedExpr );
418                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
419                                return handleDerefCalledFunction( appExpr );
420                        } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
421                                return getCalledFunction( addrExpr->arg );
422                        } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
423                                return getCalledFunction( commaExpr->arg2 );
424                        }
425                        return nullptr;
426                }
427
428                const ast::DeclWithType * getCalledFunction( const ast::Expr * expr ) {
429                        assert( expr );
430                        if ( const ast::VariableExpr * varExpr = dynamic_cast< const ast::VariableExpr * >( expr ) ) {
431                                return varExpr->var;
432                        } else if ( const ast::MemberExpr * memberExpr = dynamic_cast< const ast::MemberExpr * >( expr ) ) {
433                                return memberExpr->member;
434                        } else if ( const ast::CastExpr * castExpr = dynamic_cast< const ast::CastExpr * >( expr ) ) {
435                                return getCalledFunction( castExpr->arg );
436                        } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * >( expr ) ) {
437                                return handleDerefCalledFunction( untypedExpr );
438                        } else if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * > ( expr ) ) {
439                                return handleDerefCalledFunction( appExpr );
440                        } else if ( const ast::AddressExpr * addrExpr = dynamic_cast< const ast::AddressExpr * >( expr ) ) {
441                                return getCalledFunction( addrExpr->arg );
442                        } else if ( const ast::CommaExpr * commaExpr = dynamic_cast< const ast::CommaExpr * >( expr ) ) {
443                                return getCalledFunction( commaExpr->arg2 );
444                        }
445                        return nullptr;
446                }
447        }
448
449        DeclarationWithType * getFunction( Expression * expr ) {
450                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
451                        return getCalledFunction( appExpr->get_function() );
452                } else if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * > ( expr ) ) {
453                        return getCalledFunction( untyped->get_function() );
454                }
455                assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
456        }
457
458        const ast::DeclWithType * getFunction( const ast::Expr * expr ) {
459                if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr ) ) {
460                        return getCalledFunction( appExpr->func );
461                } else if ( const ast::UntypedExpr * untyped = dynamic_cast< const ast::UntypedExpr * > ( expr ) ) {
462                        return getCalledFunction( untyped->func );
463                }
464                assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
465        }
466
467        ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
468                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
469                if ( ! appExpr ) return nullptr;
470                DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
471                assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
472                // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
473                // will call all member dtors, and some members may have a user defined dtor.
474                return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
475        }
476
477        const ast::ApplicationExpr * isIntrinsicCallExpr( const ast::Expr * expr ) {
478                auto appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr );
479                if ( ! appExpr ) return nullptr;
480
481                const ast::DeclWithType * func = getCalledFunction( appExpr->func );
482                assertf( func, 
483                        "getCalledFunction returned nullptr: %s", toString( appExpr->func ).c_str() );
484               
485                // check for Intrinsic only -- don't want to remove all overridable ctor/dtor because
486                // autogenerated ctor/dtor will call all member dtors, and some members may have a
487                // user-defined dtor
488                return func->linkage == ast::Linkage::Intrinsic ? appExpr : nullptr;
489        }
490
491        namespace {
492                template <typename Predicate>
493                bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
494                        std::list< Expression * > callExprs;
495                        collectCtorDtorCalls( stmt, callExprs );
496                        // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
497                        return std::all_of( callExprs.begin(), callExprs.end(), pred);
498                }
499
500                template <typename Predicate>
501                bool allofCtorDtor( const ast::Stmt * stmt, const Predicate & pred ) {
502                        std::vector< ast::ptr< ast::Expr > > callExprs = collectCtorDtorCalls( stmt );
503                        return std::all_of( callExprs.begin(), callExprs.end(), pred );
504                }
505        }
506
507        bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
508                return allofCtorDtor( stmt, []( Expression * callExpr ){
509                        if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
510                                FunctionType *funcType = GenPoly::getFunctionType( appExpr->function->result );
511                                assert( funcType );
512                                return funcType->get_parameters().size() == 1;
513                        }
514                        return false;
515                });
516        }
517
518        bool isIntrinsicSingleArgCallStmt( const ast::Stmt * stmt ) {
519                return allofCtorDtor( stmt, []( const ast::Expr * callExpr ){
520                        if ( const ast::ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
521                                const ast::FunctionType * funcType = 
522                                        GenPoly::getFunctionType( appExpr->func->result );
523                                assert( funcType );
524                                return funcType->params.size() == 1;
525                        }
526                        return false;
527                });
528        }
529
530        bool isIntrinsicCallStmt( Statement * stmt ) {
531                return allofCtorDtor( stmt, []( Expression * callExpr ) {
532                        return isIntrinsicCallExpr( callExpr );
533                });
534        }
535
536        namespace {
537                template<typename CallExpr>
538                Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
539                        if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
540                        for ( Expression *& arg : callExpr->get_args() ) {
541                                if ( pos == 0 ) return arg;
542                                pos--;
543                        }
544                        assert( false );
545                }
546
547                template<typename CallExpr>
548                const ast::Expr * callArg( const CallExpr * call, unsigned int pos ) {
549                        if( pos >= call->args.size() ) {
550                                assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.",
551                                        pos, toString( call ).c_str() );
552                        }
553                        for ( const ast::Expr * arg : call->args ) {
554                                if ( pos == 0 ) return arg;
555                                --pos;
556                        }
557                        assert( false );
558                }
559        }
560
561        Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
562                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
563                        return callArg( appExpr, pos );
564                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
565                        return callArg( untypedExpr, pos );
566                } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
567                        std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
568                        assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
569                        ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
570                        TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
571                        assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
572                        return getCallArg( tuple->get_exprs().front(), pos );
573                } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
574                        return getCallArg( copyCtor->callExpr, pos );
575                } else {
576                        assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
577                }
578        }
579
580        const ast::Expr * getCallArg( const ast::Expr * call, unsigned pos ) {
581                if ( auto app = dynamic_cast< const ast::ApplicationExpr * >( call ) ) {
582                        return callArg( app, pos );
583                } else if ( auto untyped = dynamic_cast< const ast::UntypedExpr * >( call ) ) {
584                        return callArg( untyped, pos );
585                } else if ( auto tupleAssn = dynamic_cast< const ast::TupleAssignExpr * >( call ) ) {
586                        const std::list<ast::ptr<ast::Stmt>>& stmts = tupleAssn->stmtExpr->stmts->kids;
587                        assertf( ! stmts.empty(), "TupleAssignExpr missing statements." );
588                        auto stmt  = strict_dynamic_cast< const ast::ExprStmt * >( stmts.back().get() );
589                        auto tuple = strict_dynamic_cast< const ast::TupleExpr * >( stmt->expr.get() );
590                        assertf( ! tuple->exprs.empty(), "TupleAssignExpr has empty tuple expr.");
591                        return getCallArg( tuple->exprs.front(), pos );
592                } else if ( auto ctor = dynamic_cast< const ast::ImplicitCopyCtorExpr * >( call ) ) {
593                        return getCallArg( ctor->callExpr, pos );
594                } else {
595                        assertf( false, "Unexpected expression type passed to getCallArg: %s",
596                                toString( call ).c_str() );
597                }
598        }
599
600        namespace {
601                std::string funcName( Expression * func );
602                std::string funcName( const ast::Expr * func );
603
604                template<typename CallExpr>
605                std::string handleDerefName( CallExpr * expr ) {
606                        // (*f)(x) => should get name "f"
607                        std::string name = getFunctionName( expr );
608                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
609                        assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
610                        return funcName( expr->get_args().front() );
611                }
612
613                template<typename CallExpr>
614                std::string handleDerefName( const CallExpr * expr ) {
615                        // (*f)(x) => should get name "f"
616                        std::string name = getFunctionName( expr );
617                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
618                        assertf( ! expr->args.empty(), "Cannot get function name from dereference with no arguments" );
619                        return funcName( expr->args.front() );
620                }
621
622                std::string funcName( Expression * func ) {
623                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
624                                return nameExpr->get_name();
625                        } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
626                                return varExpr->get_var()->get_name();
627                        }       else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
628                                return funcName( castExpr->get_arg() );
629                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
630                                return memberExpr->get_member()->get_name();
631                        } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
632                                return funcName( memberExpr->get_member() );
633                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
634                                return handleDerefName( untypedExpr );
635                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
636                                return handleDerefName( appExpr );
637                        } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
638                                return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
639                        } else {
640                                assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
641                        }
642                }
643
644                std::string funcName( const ast::Expr * func ) {
645                        if ( const ast::NameExpr * nameExpr = dynamic_cast< const ast::NameExpr * >( func ) ) {
646                                return nameExpr->name;
647                        } else if ( const ast::VariableExpr * varExpr = dynamic_cast< const ast::VariableExpr * >( func ) ) {
648                                return varExpr->var->name;
649                        }       else if ( const ast::CastExpr * castExpr = dynamic_cast< const ast::CastExpr * >( func ) ) {
650                                return funcName( castExpr->arg );
651                        } else if ( const ast::MemberExpr * memberExpr = dynamic_cast< const ast::MemberExpr * >( func ) ) {
652                                return memberExpr->member->name;
653                        } else if ( const ast::UntypedMemberExpr * memberExpr = dynamic_cast< const ast::UntypedMemberExpr * > ( func ) ) {
654                                return funcName( memberExpr->member );
655                        } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * >( func ) ) {
656                                return handleDerefName( untypedExpr );
657                        } else if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( func ) ) {
658                                return handleDerefName( appExpr );
659                        } else if ( const ast::ConstructorExpr * ctorExpr = dynamic_cast< const ast::ConstructorExpr * >( func ) ) {
660                                return funcName( getCallArg( ctorExpr->callExpr, 0 ) );
661                        } else {
662                                assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
663                        }
664                }
665        }
666
667        std::string getFunctionName( Expression * expr ) {
668                // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
669                // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
670                // can't possibly do anything reasonable.
671                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
672                        return funcName( appExpr->get_function() );
673                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
674                        return funcName( untypedExpr->get_function() );
675                } else {
676                        std::cerr << expr << std::endl;
677                        assertf( false, "Unexpected expression type passed to getFunctionName" );
678                }
679        }
680
681        std::string getFunctionName( const ast::Expr * expr ) {
682                // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
683                // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
684                // can't possibly do anything reasonable.
685                if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr ) ) {
686                        return funcName( appExpr->func );
687                } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * > ( expr ) ) {
688                        return funcName( untypedExpr->func );
689                } else {
690                        std::cerr << expr << std::endl;
691                        assertf( false, "Unexpected expression type passed to getFunctionName" );
692                }
693        }
694
695        Type * getPointerBase( Type * type ) {
696                if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
697                        return ptrType->get_base();
698                } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
699                        return arrayType->get_base();
700                } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
701                        return refType->get_base();
702                } else {
703                        return nullptr;
704                }
705        }
706        const ast::Type* getPointerBase( const ast::Type* t ) {
707                if ( const auto * p = dynamic_cast< const ast::PointerType * >( t ) ) {
708                        return p->base;
709                } else if ( const auto * a = dynamic_cast< const ast::ArrayType * >( t ) ) {
710                        return a->base;
711                } else if ( const auto * r = dynamic_cast< const ast::ReferenceType * >( t ) ) {
712                        return r->base;
713                } else return nullptr;
714        }
715
716        Type * isPointerType( Type * type ) {
717                if ( getPointerBase( type ) ) return type;
718                else return nullptr;
719        }
720
721        ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src ) {
722                static FunctionDecl * assign = nullptr;
723                if ( ! assign ) {
724                        // temporary? Generate a fake assignment operator to represent bitwise assignments.
725                        // This operator could easily exist as a real function, but it's tricky because nothing should resolve to this function.
726                        TypeDecl * td = new TypeDecl( "T", noStorageClasses, nullptr, TypeDecl::Dtype, true );
727                        assign = new FunctionDecl( "?=?", noStorageClasses, LinkageSpec::Intrinsic, SymTab::genAssignType( new TypeInstType( noQualifiers, td->name, td ) ), nullptr );
728                }
729                if ( dynamic_cast< ReferenceType * >( dst->result ) ) {
730                        for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
731                                dst = new AddressExpr( dst );
732                        }
733                } else {
734                        dst = new CastExpr( dst, new ReferenceType( noQualifiers, dst->result->clone() ) );
735                }
736                if ( dynamic_cast< ReferenceType * >( src->result ) ) {
737                        for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
738                                src = new AddressExpr( src );
739                        }
740                        // src = new CastExpr( src, new ReferenceType( noQualifiers, src->result->stripReferences()->clone() ) );
741                }
742                return new ApplicationExpr( VariableExpr::functionPointer( assign ), { dst, src } );
743        }
744
745        struct ConstExprChecker : public WithShortCircuiting {
746                // most expressions are not const expr
747                void previsit( Expression * ) { isConstExpr = false; visit_children = false; }
748
749                void previsit( AddressExpr *addressExpr ) {
750                        visit_children = false;
751
752                        // address of a variable or member expression is constexpr
753                        Expression * arg = addressExpr->get_arg();
754                        if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
755                }
756
757                // these expressions may be const expr, depending on their children
758                void previsit( SizeofExpr * ) {}
759                void previsit( AlignofExpr * ) {}
760                void previsit( UntypedOffsetofExpr * ) {}
761                void previsit( OffsetofExpr * ) {}
762                void previsit( OffsetPackExpr * ) {}
763                void previsit( AttrExpr * ) {}
764                void previsit( CommaExpr * ) {}
765                void previsit( LogicalExpr * ) {}
766                void previsit( ConditionalExpr * ) {}
767                void previsit( CastExpr * ) {}
768                void previsit( ConstantExpr * ) {}
769
770                void previsit( VariableExpr * varExpr ) {
771                        visit_children = false;
772
773                        if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( varExpr->result ) ) {
774                                long long int value;
775                                if ( inst->baseEnum->valueOf( varExpr->var, value ) ) {
776                                        // enumerators are const expr
777                                        return;
778                                }
779                        }
780                        isConstExpr = false;
781                }
782
783                bool isConstExpr = true;
784        };
785
786        bool isConstExpr( Expression * expr ) {
787                if ( expr ) {
788                        PassVisitor<ConstExprChecker> checker;
789                        expr->accept( checker );
790                        return checker.pass.isConstExpr;
791                }
792                return true;
793        }
794
795        bool isConstExpr( Initializer * init ) {
796                if ( init ) {
797                        PassVisitor<ConstExprChecker> checker;
798                        init->accept( checker );
799                        return checker.pass.isConstExpr;
800                } // if
801                // for all intents and purposes, no initializer means const expr
802                return true;
803        }
804
805        bool isConstructor( const std::string & str ) { return str == "?{}"; }
806        bool isDestructor( const std::string & str ) { return str == "^?{}"; }
807        bool isAssignment( const std::string & str ) { return str == "?=?"; }
808        bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
809        bool isCtorDtorAssign( const std::string & str ) { return isCtorDtor( str ) || isAssignment( str ); }
810
811        FunctionDecl * isCopyFunction( Declaration * decl, const std::string & fname ) {
812                FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl );
813                if ( ! function ) return nullptr;
814                if ( function->name != fname ) return nullptr;
815                FunctionType * ftype = function->type;
816                if ( ftype->parameters.size() != 2 ) return nullptr;
817
818                Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
819                Type * t2 = ftype->parameters.back()->get_type();
820                assert( t1 );
821
822                if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
823                        return function;
824                } else {
825                        return nullptr;
826                }
827        }
828
829        bool isCopyFunction( const ast::FunctionDecl * decl ) {
830                const ast::FunctionType * ftype = decl->type;
831                if ( ftype->params.size() != 2 ) return false;
832
833                const ast::Type * t1 = getPointerBase( ftype->params.front()->get_type() );
834                if ( ! t1 ) return false;
835                const ast::Type * t2 = ftype->params.back()->get_type();
836               
837                return ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, ast::SymbolTable{} );
838        }
839
840        FunctionDecl * isAssignment( Declaration * decl ) {
841                return isCopyFunction( decl, "?=?" );
842        }
843        FunctionDecl * isDestructor( Declaration * decl ) {
844                if ( isDestructor( decl->get_name() ) ) {
845                        return dynamic_cast< FunctionDecl * >( decl );
846                }
847                return nullptr;
848        }
849        FunctionDecl * isDefaultConstructor( Declaration * decl ) {
850                if ( isConstructor( decl->name ) ) {
851                        if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
852                                if ( func->type->parameters.size() == 1 ) {
853                                        return func;
854                                }
855                        }
856                }
857                return nullptr;
858        }
859        FunctionDecl * isCopyConstructor( Declaration * decl ) {
860                return isCopyFunction( decl, "?{}" );
861        }
862}
Note: See TracBrowser for help on using the repository browser.