source: src/InitTweak/InitTweak.cc @ b9dae14c

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since b9dae14c was 16ba4a6, checked in by Fangren Yu <f37yu@…>, 3 years ago

factor out resolver calls in pre-resolution stage

  • Property mode set to 100644
File size: 46.3 KB
RevLine 
[2d11663]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
[033ff37]11// Last Modified By : Peter A. Buhr
[07de76b]12// Last Modified On : Fri Dec 13 23:15:52 2019
13// Update Count     : 8
[2d11663]14//
15
[d180746]16#include <algorithm>               // for find, all_of
[e3e16bc]17#include <cassert>                 // for assertf, assert, strict_dynamic_cast
[d180746]18#include <iostream>                // for ostream, cerr, endl
19#include <iterator>                // for back_insert_iterator, back_inserter
20#include <memory>                  // for __shared_ptr
[2d11663]21#include <vector>
[d180746]22
[9b4f329]23#include "AST/Expr.hpp"
[c1ed2ee]24#include "AST/Init.hpp"
[b8524ca]25#include "AST/Node.hpp"
[c1ed2ee]26#include "AST/Pass.hpp"
[9b4f329]27#include "AST/Stmt.hpp"
[9e1d485]28#include "AST/Type.hpp"
[fd236ed]29#include "Common/PassVisitor.h"
[d180746]30#include "Common/SemanticError.h"  // for SemanticError
31#include "Common/UniqueName.h"     // for UniqueName
32#include "Common/utility.h"        // for toString, deleteAll, maybeClone
33#include "GenPoly/GenPoly.h"       // for getFunctionType
[2b46a13]34#include "InitTweak.h"
[d180746]35#include "ResolvExpr/typeops.h"    // for typesCompatibleIgnoreQualifiers
[f5c3b6c]36#include "SymTab/Autogen.h"
[d180746]37#include "SymTab/Indexer.h"        // for Indexer
[07de76b]38#include "SynTree/LinkageSpec.h"   // for Spec, isBuiltin, Intrinsic
[d180746]39#include "SynTree/Attribute.h"     // for Attribute
40#include "SynTree/Constant.h"      // for Constant
41#include "SynTree/Declaration.h"   // for ObjectDecl, DeclarationWithType
42#include "SynTree/Expression.h"    // for Expression, UntypedExpr, Applicati...
43#include "SynTree/Initializer.h"   // for Initializer, ListInit, Designation
[ba3706f]44#include "SynTree/Label.h"         // for Label
[d180746]45#include "SynTree/Statement.h"     // for CompoundStmt, ExprStmt, BranchStmt
46#include "SynTree/Type.h"          // for FunctionType, ArrayType, PointerType
47#include "SynTree/Visitor.h"       // for Visitor, maybeAccept
[29bc63e]48#include "Tuples/Tuples.h"         // for Tuples::isTtype
[d180746]49
[2b46a13]50namespace InitTweak {
[64071c2]51        namespace {
[1fbeebd]52                struct HasDesignations : public WithShortCircuiting {
[64071c2]53                        bool hasDesignations = false;
[fd236ed]54
55                        void previsit( BaseSyntaxNode * ) {
56                                // short circuit if we already know there are designations
57                                if ( hasDesignations ) visit_children = false;
58                        }
59
60                        void previsit( Designation * des ) {
61                                // short circuit if we already know there are designations
62                                if ( hasDesignations ) visit_children = false;
63                                else if ( ! des->get_designators().empty() ) {
64                                        hasDesignations = true;
65                                        visit_children = false;
66                                }
[64071c2]67                        }
68                };
[2b46a13]69
[ef3d798]70                struct InitDepthChecker : public WithGuards {
[dcd73d1]71                        bool depthOkay = true;
72                        Type * type;
73                        int curDepth = 0, maxDepth = 0;
74                        InitDepthChecker( Type * type ) : type( type ) {
75                                Type * t = type;
76                                while ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
77                                        maxDepth++;
78                                        t = at->get_base();
79                                }
80                                maxDepth++;
81                        }
[ef3d798]82                        void previsit( ListInit * ) {
[dcd73d1]83                                curDepth++;
[ef3d798]84                                GuardAction( [this]() { curDepth--; } );
[dcd73d1]85                                if ( curDepth > maxDepth ) depthOkay = false;
86                        }
87                };
88
[16ba4a6]89                struct HasDesignations_new : public ast::WithShortCircuiting {
90                        bool result = false;
91
92                        void previsit( const ast::Node * ) {
93                                // short circuit if we already know there are designations
94                                if ( result ) visit_children = false;
95                        }
96
97                        void previsit( const ast::Designation * des ) {
98                                // short circuit if we already know there are designations
99                                if ( result ) visit_children = false;
100                                else if ( ! des->designators.empty() ) {
101                                        result = true;
102                                        visit_children = false;
103                                }
104                        }
105                };
106
107                struct InitDepthChecker_new : public ast::WithGuards {
108                        bool result = true;
109                        const ast::Type * type;
110                        int curDepth = 0, maxDepth = 0;
111                        InitDepthChecker_new( const ast::Type * type ) : type( type ) {
112                                const ast::Type * t = type;
113                                while ( auto at = dynamic_cast< const ast::ArrayType * >( t ) ) {
114                                        maxDepth++;
115                                        t = at->base;
116                                }
117                                maxDepth++;
118                        }
119                        void previsit( ListInit * ) {
120                                curDepth++;
121                                GuardAction( [this]() { curDepth--; } );
122                                if ( curDepth > maxDepth ) result = false;
123                        }
124                };
125
[c1ed2ee]126                struct InitFlattener_old : public WithShortCircuiting {
[c3f551b]127                        void previsit( SingleInit * singleInit ) {
128                                visit_children = false;
129                                argList.push_back( singleInit->value->clone() );
130                        }
[64071c2]131                        std::list< Expression * > argList;
132                };
[2b46a13]133
[c1ed2ee]134                struct InitFlattener_new : public ast::WithShortCircuiting {
135                        std::vector< ast::ptr< ast::Expr > > argList;
136
137                        void previsit( const ast::SingleInit * singleInit ) {
138                                visit_children = false;
139                                argList.emplace_back( singleInit->value );
140                        }
141                };
142
143        } // anonymous namespace
[2b46a13]144
[64071c2]145        std::list< Expression * > makeInitList( Initializer * init ) {
[c1ed2ee]146                PassVisitor<InitFlattener_old> flattener;
[4d2434a]147                maybeAccept( init, flattener );
[c3f551b]148                return flattener.pass.argList;
[64071c2]149        }
[2b46a13]150
[64071c2]151        bool isDesignated( Initializer * init ) {
[fd236ed]152                PassVisitor<HasDesignations> finder;
[64071c2]153                maybeAccept( init, finder );
[fd236ed]154                return finder.pass.hasDesignations;
[dcd73d1]155        }
156
157        bool checkInitDepth( ObjectDecl * objDecl ) {
[ef3d798]158                PassVisitor<InitDepthChecker> checker( objDecl->type );
159                maybeAccept( objDecl->init, checker );
160                return checker.pass.depthOkay;
[64071c2]161        }
[2b46a13]162
[16ba4a6]163        bool isDesignated( const ast::Init * init ) {
164                ast::Pass<HasDesignations_new> finder;
165                maybe_accept( init, finder );
166                return finder.core.result;
167        }
168
169        bool checkInitDepth( const ast::ObjectDecl * objDecl ) {
170                ast::Pass<InitDepthChecker_new> checker( objDecl->type );
171                maybe_accept( objDecl->init.get(), checker );
172                return checker.core.result;
173        }
174
[b8524ca]175std::vector< ast::ptr< ast::Expr > > makeInitList( const ast::Init * init ) {
[c1ed2ee]176        ast::Pass< InitFlattener_new > flattener;
177        maybe_accept( init, flattener );
[7ff3e522]178        return std::move( flattener.core.argList );
[b8524ca]179}
180
181        class InitExpander_old::ExpanderImpl {
[39f84a4]182        public:
[3351cc0]183                virtual ~ExpanderImpl() = default;
[39f84a4]184                virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
[4d2434a]185                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
[39f84a4]186        };
187
[b8524ca]188        class InitImpl_old : public InitExpander_old::ExpanderImpl {
[39f84a4]189        public:
[b8524ca]190                InitImpl_old( Initializer * init ) : init( init ) {}
191                virtual ~InitImpl_old() = default;
[39f84a4]192
[7e003011]193                virtual std::list< Expression * > next( __attribute((unused)) std::list< Expression * > & indices ) {
[39f84a4]194                        // this is wrong, but just a placeholder for now
[4d2434a]195                        // if ( ! flattened ) flatten( indices );
196                        // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
197                        return makeInitList( init );
[39f84a4]198                }
[4d2434a]199
200                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]201        private:
[4d2434a]202                Initializer * init;
[39f84a4]203        };
204
[b8524ca]205        class ExprImpl_old : public InitExpander_old::ExpanderImpl {
[39f84a4]206        public:
[b8524ca]207                ExprImpl_old( Expression * expr ) : arg( expr ) {}
208                virtual ~ExprImpl_old() { delete arg; }
[9b4c936]209
[39f84a4]210                virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
211                        std::list< Expression * > ret;
212                        Expression * expr = maybeClone( arg );
213                        if ( expr ) {
214                                for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
215                                        // go through indices and layer on subscript exprs ?[?]
216                                        ++it;
217                                        UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
218                                        subscriptExpr->get_args().push_back( expr );
219                                        subscriptExpr->get_args().push_back( (*it)->clone() );
220                                        expr = subscriptExpr;
221                                }
222                                ret.push_back( expr );
223                        }
224                        return ret;
225                }
[4d2434a]226
227                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]228        private:
229                Expression * arg;
230        };
231
[b8524ca]232        InitExpander_old::InitExpander_old( Initializer * init ) : expander( new InitImpl_old( init ) ) {}
[39f84a4]233
[b8524ca]234        InitExpander_old::InitExpander_old( Expression * expr ) : expander( new ExprImpl_old( expr ) ) {}
[39f84a4]235
[b8524ca]236        std::list< Expression * > InitExpander_old::operator*() {
[39f84a4]237                return cur;
238        }
239
[b8524ca]240        InitExpander_old & InitExpander_old::operator++() {
[39f84a4]241                cur = expander->next( indices );
242                return *this;
243        }
244
245        // use array indices list to build switch statement
[b8524ca]246        void InitExpander_old::addArrayIndex( Expression * index, Expression * dimension ) {
[39f84a4]247                indices.push_back( index );
248                indices.push_back( dimension );
249        }
250
[b8524ca]251        void InitExpander_old::clearArrayIndices() {
[9b4c936]252                deleteAll( indices );
[4d2434a]253                indices.clear();
[1a5ad8c]254        }
255
[b8524ca]256        bool InitExpander_old::addReference() {
[1a5ad8c]257                bool added = false;
258                for ( Expression *& expr : cur ) {
259                        expr = new AddressExpr( expr );
260                        added = true;
261                }
262                return added;
[4d2434a]263        }
264
265        namespace {
[f9cebb5]266                /// given index i, dimension d, initializer init, and callExpr f, generates
267                ///   if (i < d) f(..., init)
268                ///   ++i;
269                /// so that only elements within the range of the array are constructed
[4d2434a]270                template< typename OutIterator >
[f9cebb5]271                void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
[4d2434a]272                        UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
273                        cond->get_args().push_back( index->clone() );
274                        cond->get_args().push_back( dimension->clone() );
275
276                        std::list< Expression * > args = makeInitList( init );
277                        callExpr->get_args().splice( callExpr->get_args().end(), args );
278
[ba3706f]279                        *out++ = new IfStmt( cond, new ExprStmt( callExpr ), nullptr );
[4d2434a]280
281                        UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
[175ad32]282                        increment->get_args().push_back( index->clone() );
[ba3706f]283                        *out++ = new ExprStmt( increment );
[4d2434a]284                }
285
286                template< typename OutIterator >
[b8524ca]287                void build( UntypedExpr * callExpr, InitExpander_old::IndexList::iterator idx, InitExpander_old::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
[4d2434a]288                        if ( idx == idxEnd ) return;
289                        Expression * index = *idx++;
290                        assert( idx != idxEnd );
291                        Expression * dimension = *idx++;
292
[f9cebb5]293                        // xxx - may want to eventually issue a warning here if we can detect
294                        // that the number of elements exceeds to dimension of the array
[4d2434a]295                        if ( idx == idxEnd ) {
296                                if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
297                                        for ( Initializer * init : *listInit ) {
[f9cebb5]298                                                buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]299                                        }
300                                } else {
[f9cebb5]301                                        buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]302                                }
303                        } else {
304                                std::list< Statement * > branches;
305
306                                unsigned long cond = 0;
307                                ListInit * listInit = dynamic_cast< ListInit * >( init );
308                                if ( ! listInit ) {
309                                        // xxx - this shouldn't be an error, but need a way to
310                                        // terminate without creating output, so should catch this error
[a16764a6]311                                        SemanticError( init->location, "unbalanced list initializers" );
[4d2434a]312                                }
[f9cebb5]313
314                                static UniqueName targetLabel( "L__autogen__" );
315                                Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
[4d2434a]316                                for ( Initializer * init : *listInit ) {
317                                        Expression * condition;
318                                        // check for designations
319                                        // if ( init-> ) {
320                                                condition = new ConstantExpr( Constant::from_ulong( cond ) );
321                                                ++cond;
322                                        // } else {
323                                        //      condition = // ... take designation
324                                        //      cond = // ... take designation+1
325                                        // }
326                                        std::list< Statement * > stmts;
327                                        build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
[ba3706f]328                                        stmts.push_back( new BranchStmt( switchLabel, BranchStmt::Break ) );
329                                        CaseStmt * caseStmt = new CaseStmt( condition, stmts );
[4d2434a]330                                        branches.push_back( caseStmt );
331                                }
[ba3706f]332                                *out++ = new SwitchStmt( index->clone(), branches );
333                                *out++ = new NullStmt( { switchLabel } );
[4d2434a]334                        }
335                }
336        }
337
338        // if array came with an initializer list: initialize each element
339        // may have more initializers than elements in the array - need to check at each index that
340        // we haven't exceeded size.
341        // may have fewer initializers than elements in the array - need to default construct
342        // remaining elements.
343        // To accomplish this, generate switch statement, consuming all of expander's elements
[b8524ca]344        Statement * InitImpl_old::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
[22bc276]345                if ( ! init ) return nullptr;
[ba3706f]346                CompoundStmt * block = new CompoundStmt();
[f9cebb5]347                build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
348                if ( block->get_kids().empty() ) {
349                        delete block;
[22bc276]350                        return nullptr;
[4d2434a]351                } else {
[22bc276]352                        init = nullptr; // init was consumed in creating the list init
[f9cebb5]353                        return block;
[4d2434a]354                }
[39f84a4]355        }
356
[b8524ca]357        Statement * ExprImpl_old::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
[22bc276]358                return nullptr;
[4d2434a]359        }
360
[b8524ca]361        Statement * InitExpander_old::buildListInit( UntypedExpr * dst ) {
[4d2434a]362                return expander->buildListInit( dst, indices );
363        }
364
[b8524ca]365class InitExpander_new::ExpanderImpl {
366public:
367        virtual ~ExpanderImpl() = default;
368        virtual std::vector< ast::ptr< ast::Expr > > next( IndexList & indices ) = 0;
[6f096d2]369        virtual ast::ptr< ast::Stmt > buildListInit(
[c1ed2ee]370                ast::UntypedExpr * callExpr, IndexList & indices ) = 0;
[b8524ca]371};
372
373namespace {
[c1ed2ee]374        template< typename Out >
[6f096d2]375        void buildCallExpr(
376                ast::UntypedExpr * callExpr, const ast::Expr * index, const ast::Expr * dimension,
[c1ed2ee]377                const ast::Init * init, Out & out
378        ) {
379                const CodeLocation & loc = init->location;
380
[6f096d2]381                auto cond = new ast::UntypedExpr{
[c1ed2ee]382                        loc, new ast::NameExpr{ loc, "?<?" }, { index, dimension } };
[6f096d2]383
[c1ed2ee]384                std::vector< ast::ptr< ast::Expr > > args = makeInitList( init );
385                splice( callExpr->args, args );
386
387                out.emplace_back( new ast::IfStmt{ loc, cond, new ast::ExprStmt{ loc, callExpr } } );
388
[6f096d2]389                out.emplace_back( new ast::ExprStmt{
[c1ed2ee]390                        loc, new ast::UntypedExpr{ loc, new ast::NameExpr{ loc, "++?" }, { index } } } );
391        }
392
393        template< typename Out >
394        void build(
[6f096d2]395                ast::UntypedExpr * callExpr, const InitExpander_new::IndexList & indices,
[c1ed2ee]396                const ast::Init * init, Out & out
397        ) {
398                if ( indices.empty() ) return;
399
400                unsigned idx = 0;
401
402                const ast::Expr * index = indices[idx++];
403                assert( idx != indices.size() );
404                const ast::Expr * dimension = indices[idx++];
405
406                if ( idx == indices.size() ) {
407                        if ( auto listInit = dynamic_cast< const ast::ListInit * >( init ) ) {
408                                for ( const ast::Init * init : *listInit ) {
[16ba4a6]409                                        buildCallExpr( shallowCopy(callExpr), index, dimension, init, out );
[c1ed2ee]410                                }
411                        } else {
[16ba4a6]412                                buildCallExpr( shallowCopy(callExpr), index, dimension, init, out );
[c1ed2ee]413                        }
414                } else {
415                        const CodeLocation & loc = init->location;
416
417                        unsigned long cond = 0;
418                        auto listInit = dynamic_cast< const ast::ListInit * >( init );
419                        if ( ! listInit ) { SemanticError( loc, "unbalanced list initializers" ); }
420
421                        static UniqueName targetLabel( "L__autogen__" );
[6f096d2]422                        ast::Label switchLabel{
[c1ed2ee]423                                loc, targetLabel.newName(), { new ast::Attribute{ "unused" } } };
[6f096d2]424
[c1ed2ee]425                        std::vector< ast::ptr< ast::Stmt > > branches;
426                        for ( const ast::Init * init : *listInit ) {
427                                auto condition = ast::ConstantExpr::from_ulong( loc, cond );
428                                ++cond;
429
430                                std::vector< ast::ptr< ast::Stmt > > stmts;
431                                build( callExpr, indices, init, stmts );
[6f096d2]432                                stmts.emplace_back(
[c1ed2ee]433                                        new ast::BranchStmt{ loc, ast::BranchStmt::Break, switchLabel } );
434                                branches.emplace_back( new ast::CaseStmt{ loc, condition, std::move( stmts ) } );
435                        }
436                        out.emplace_back( new ast::SwitchStmt{ loc, index, std::move( branches ) } );
437                        out.emplace_back( new ast::NullStmt{ loc, { switchLabel } } );
438                }
439        }
440
[b8524ca]441        class InitImpl_new final : public InitExpander_new::ExpanderImpl {
442                ast::ptr< ast::Init > init;
443        public:
444                InitImpl_new( const ast::Init * i ) : init( i ) {}
445
446                std::vector< ast::ptr< ast::Expr > > next( InitExpander_new::IndexList & ) override {
447                        return makeInitList( init );
448                }
[6f096d2]449
450                ast::ptr< ast::Stmt > buildListInit(
451                        ast::UntypedExpr * callExpr, InitExpander_new::IndexList & indices
[b8524ca]452                ) override {
[6f096d2]453                        // If array came with an initializer list, initialize each element. We may have more
454                        // initializers than elements of the array; need to check at each index that we have
455                        // not exceeded size. We may have fewer initializers than elements in the array; need
456                        // to default-construct remaining elements. To accomplish this, generate switch
[c1ed2ee]457                        // statement consuming all of expander's elements
458
459                        if ( ! init ) return {};
460
461                        std::list< ast::ptr< ast::Stmt > > stmts;
462                        build( callExpr, indices, init, stmts );
463                        if ( stmts.empty() ) {
464                                return {};
465                        } else {
466                                auto block = new ast::CompoundStmt{ init->location, std::move( stmts ) };
467                                init = nullptr;  // consumed in creating the list init
468                                return block;
469                        }
[b8524ca]470                }
471        };
472
473        class ExprImpl_new final : public InitExpander_new::ExpanderImpl {
474                ast::ptr< ast::Expr > arg;
475        public:
476                ExprImpl_new( const ast::Expr * a ) : arg( a ) {}
477
[6f096d2]478                std::vector< ast::ptr< ast::Expr > > next(
479                        InitExpander_new::IndexList & indices
[b8524ca]480                ) override {
[c1ed2ee]481                        if ( ! arg ) return {};
482
483                        const CodeLocation & loc = arg->location;
484                        const ast::Expr * expr = arg;
485                        for ( auto it = indices.rbegin(); it != indices.rend(); ++it ) {
486                                // go through indices and layer on subscript exprs ?[?]
487                                ++it;
[6f096d2]488                                expr = new ast::UntypedExpr{
[c1ed2ee]489                                        loc, new ast::NameExpr{ loc, "?[?]" }, { expr, *it } };
490                        }
491                        return { expr };
[b8524ca]492                }
[6f096d2]493
494                ast::ptr< ast::Stmt > buildListInit(
495                        ast::UntypedExpr *, InitExpander_new::IndexList &
496                ) override {
[b8524ca]497                        return {};
498                }
499        };
500} // anonymous namespace
501
502InitExpander_new::InitExpander_new( const ast::Init * init )
503: expander( new InitImpl_new{ init } ), crnt(), indices() {}
504
505InitExpander_new::InitExpander_new( const ast::Expr * expr )
506: expander( new ExprImpl_new{ expr } ), crnt(), indices() {}
507
508std::vector< ast::ptr< ast::Expr > > InitExpander_new::operator* () { return crnt; }
509
510InitExpander_new & InitExpander_new::operator++ () {
511        crnt = expander->next( indices );
512        return *this;
513}
514
[6f096d2]515/// builds statement which has the same semantics as a C-style list initializer (for array
[b8524ca]516/// initializers) using callExpr as the base expression to perform initialization
[c1ed2ee]517ast::ptr< ast::Stmt > InitExpander_new::buildListInit( ast::UntypedExpr * callExpr ) {
[b8524ca]518        return expander->buildListInit( callExpr, indices );
519}
520
521void InitExpander_new::addArrayIndex( const ast::Expr * index, const ast::Expr * dimension ) {
522        indices.emplace_back( index );
523        indices.emplace_back( dimension );
524}
525
526void InitExpander_new::clearArrayIndices() { indices.clear(); }
527
528bool InitExpander_new::addReference() {
529        for ( ast::ptr< ast::Expr > & expr : crnt ) {
530                expr = new ast::AddressExpr{ expr };
531        }
532        return ! crnt.empty();
533}
534
[549c006]535        Type * getTypeofThis( FunctionType * ftype ) {
536                assertf( ftype, "getTypeofThis: nullptr ftype" );
537                ObjectDecl * thisParam = getParamThis( ftype );
[7fc7cdb]538                ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
539                return refType->base;
540        }
541
[549c006]542        ObjectDecl * getParamThis( FunctionType * ftype ) {
543                assertf( ftype, "getParamThis: nullptr ftype" );
[7fc7cdb]544                auto & params = ftype->parameters;
[549c006]545                assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
[7fc7cdb]546                return strict_dynamic_cast< ObjectDecl * >( params.front() );
547        }
548
[490fb92e]549        const ast::ObjectDecl * getParamThis(const ast::FunctionDecl * func) {
550                assertf( func, "getParamThis: nullptr ftype" );
551                auto & params = func->params;
552                assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( func ).c_str());
553                return params.front().strict_as<ast::ObjectDecl>();
554        }
555
[22bc276]556        bool tryConstruct( DeclarationWithType * dwt ) {
557                ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
558                if ( ! objDecl ) return false;
[df7a162]559                return (objDecl->get_init() == nullptr ||
[22bc276]560                                ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
561                        && ! objDecl->get_storageClasses().is_extern
[29bc63e]562                        && isConstructable( objDecl->type );
563        }
564
565        bool isConstructable( Type * type ) {
566                return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
[64071c2]567        }
[2b46a13]568
[490fb92e]569        bool tryConstruct( const ast::DeclWithType * dwt ) {
570                auto objDecl = dynamic_cast< const ast::ObjectDecl * >( dwt );
571                if ( ! objDecl ) return false;
572                return (objDecl->init == nullptr ||
573                                ( objDecl->init != nullptr && objDecl->init->maybeConstructed ))
574                        && ! objDecl->storage.is_extern
575                        && isConstructable( objDecl->type );
576        }
577
578        bool isConstructable( const ast::Type * type ) {
579                return ! dynamic_cast< const ast::VarArgsType * >( type ) && ! dynamic_cast< const ast::ReferenceType * >( type ) 
580                && ! dynamic_cast< const ast::FunctionType * >( type ) && ! Tuples::isTtype( type );
581        }
582
[2d11663]583        struct CallFinder_old {
584                CallFinder_old( const std::list< std::string > & names ) : names( names ) {}
[4d2434a]585
[0a6aad4]586                void postvisit( ApplicationExpr * appExpr ) {
[4d2434a]587                        handleCallExpr( appExpr );
588                }
589
[0a6aad4]590                void postvisit( UntypedExpr * untypedExpr ) {
[4d2434a]591                        handleCallExpr( untypedExpr );
592                }
593
594                std::list< Expression * > * matches;
595        private:
596                const std::list< std::string > names;
597
598                template< typename CallExpr >
599                void handleCallExpr( CallExpr * expr ) {
600                        std::string fname = getFunctionName( expr );
601                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
602                                matches->push_back( expr );
[cad355a]603                        }
[64071c2]604                }
[4d2434a]605        };
606
[2d11663]607        struct CallFinder_new final {
[490fb92e]608                std::vector< const ast::Expr * > matches;
[2d11663]609                const std::vector< std::string > names;
610
611                CallFinder_new( std::vector< std::string > && ns ) : matches(), names( std::move(ns) ) {}
612
613                void handleCallExpr( const ast::Expr * expr ) {
614                        std::string fname = getFunctionName( expr );
615                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
616                                matches.emplace_back( expr );
617                        }
618                }
619
620                void postvisit( const ast::ApplicationExpr * expr ) { handleCallExpr( expr ); }
621                void postvisit( const ast::UntypedExpr *     expr ) { handleCallExpr( expr ); }
622        };
623
[4d2434a]624        void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
[2d11663]625                static PassVisitor<CallFinder_old> finder( std::list< std::string >{ "?{}", "^?{}" } );
[0a6aad4]626                finder.pass.matches = &matches;
[4d2434a]627                maybeAccept( stmt, finder );
[64071c2]628        }
[4d2434a]629
[490fb92e]630        std::vector< const ast::Expr * > collectCtorDtorCalls( const ast::Stmt * stmt ) {
[2d11663]631                ast::Pass< CallFinder_new > finder{ std::vector< std::string >{ "?{}", "^?{}" } };
632                maybe_accept( stmt, finder );
[7ff3e522]633                return std::move( finder.core.matches );
[2d11663]634        }
635
[4d2434a]636        Expression * getCtorDtorCall( Statement * stmt ) {
637                std::list< Expression * > matches;
638                collectCtorDtorCalls( stmt, matches );
[20eacb7]639                assertf( matches.size() <= 1, "%zd constructor/destructors found in %s", matches.size(), toString( stmt ).c_str() );
[22bc276]640                return matches.size() == 1 ? matches.front() : nullptr;
[4d2434a]641        }
642
[aedfd91]643        namespace {
[599b386]644                DeclarationWithType * getCalledFunction( Expression * expr );
[d7aa12c]645                const ast::DeclWithType * getCalledFunction( const ast::Expr * expr );
[599b386]646
647                template<typename CallExpr>
648                DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
649                        // (*f)(x) => should get "f"
650                        std::string name = getFunctionName( expr );
651                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
[b128d3e]652                        assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
[599b386]653                        return getCalledFunction( expr->get_args().front() );
654                }
655
[d7aa12c]656                template<typename CallExpr>
657                const ast::DeclWithType * handleDerefCalledFunction( const CallExpr * expr ) {
658                        // (*f)(x) => should get "f"
659                        std::string name = getFunctionName( expr );
660                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
661                        assertf( ! expr->args.empty(), "Cannot get called function from dereference with no arguments" );
662                        return getCalledFunction( expr->args.front() );
663                }
664
665
[ee1635c8]666                DeclarationWithType * getCalledFunction( Expression * expr ) {
667                        assert( expr );
668                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
[6fc5c14]669                                return varExpr->var;
[ee1635c8]670                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
[6fc5c14]671                                return memberExpr->member;
[ee1635c8]672                        } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
[6fc5c14]673                                return getCalledFunction( castExpr->arg );
[599b386]674                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
675                                return handleDerefCalledFunction( untypedExpr );
676                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
677                                return handleDerefCalledFunction( appExpr );
[f3b0a07]678                        } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
[6fc5c14]679                                return getCalledFunction( addrExpr->arg );
680                        } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
681                                return getCalledFunction( commaExpr->arg2 );
[ee1635c8]682                        }
683                        return nullptr;
[aedfd91]684                }
[d7aa12c]685
686                const ast::DeclWithType * getCalledFunction( const ast::Expr * expr ) {
687                        assert( expr );
688                        if ( const ast::VariableExpr * varExpr = dynamic_cast< const ast::VariableExpr * >( expr ) ) {
689                                return varExpr->var;
690                        } else if ( const ast::MemberExpr * memberExpr = dynamic_cast< const ast::MemberExpr * >( expr ) ) {
691                                return memberExpr->member;
692                        } else if ( const ast::CastExpr * castExpr = dynamic_cast< const ast::CastExpr * >( expr ) ) {
693                                return getCalledFunction( castExpr->arg );
694                        } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * >( expr ) ) {
695                                return handleDerefCalledFunction( untypedExpr );
696                        } else if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * > ( expr ) ) {
697                                return handleDerefCalledFunction( appExpr );
698                        } else if ( const ast::AddressExpr * addrExpr = dynamic_cast< const ast::AddressExpr * >( expr ) ) {
699                                return getCalledFunction( addrExpr->arg );
700                        } else if ( const ast::CommaExpr * commaExpr = dynamic_cast< const ast::CommaExpr * >( expr ) ) {
701                                return getCalledFunction( commaExpr->arg2 );
702                        }
703                        return nullptr;
704                }
[335d81f]705
706                DeclarationWithType * getFunctionCore( const Expression * expr ) {
707                        if ( const auto * appExpr = dynamic_cast< const ApplicationExpr * >( expr ) ) {
708                                return getCalledFunction( appExpr->function );
709                        } else if ( const auto * untyped = dynamic_cast< const UntypedExpr * >( expr ) ) {
710                                return getCalledFunction( untyped->function );
711                        }
712                        assertf( false, "getFunction with unknown expression: %s", toString( expr ).c_str() );
713                }
[aedfd91]714        }
[70f89d00]715
[b7b8674]716        DeclarationWithType * getFunction( Expression * expr ) {
[335d81f]717                return getFunctionCore( expr );
718        }
719
720        const DeclarationWithType * getFunction( const Expression * expr ) {
721                return getFunctionCore( expr );
[b7b8674]722        }
723
[d7aa12c]724        const ast::DeclWithType * getFunction( const ast::Expr * expr ) {
725                if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr ) ) {
726                        return getCalledFunction( appExpr->func );
727                } else if ( const ast::UntypedExpr * untyped = dynamic_cast< const ast::UntypedExpr * > ( expr ) ) {
728                        return getCalledFunction( untyped->func );
729                }
730                assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
731        }
732
[aedfd91]733        ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
734                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
[22bc276]735                if ( ! appExpr ) return nullptr;
[ee1635c8]736                DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
[f3b0a07]737                assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
[64071c2]738                // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
739                // will call all member dtors, and some members may have a user defined dtor.
[22bc276]740                return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
[aedfd91]741        }
742
[2d11663]743        const ast::ApplicationExpr * isIntrinsicCallExpr( const ast::Expr * expr ) {
744                auto appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr );
745                if ( ! appExpr ) return nullptr;
746
747                const ast::DeclWithType * func = getCalledFunction( appExpr->func );
[6f096d2]748                assertf( func,
[2d11663]749                        "getCalledFunction returned nullptr: %s", toString( appExpr->func ).c_str() );
[6f096d2]750
751                // check for Intrinsic only -- don't want to remove all overridable ctor/dtor because
752                // autogenerated ctor/dtor will call all member dtors, and some members may have a
[2d11663]753                // user-defined dtor
754                return func->linkage == ast::Linkage::Intrinsic ? appExpr : nullptr;
755        }
756
[a465caf]757        namespace {
758                template <typename Predicate>
759                bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
760                        std::list< Expression * > callExprs;
761                        collectCtorDtorCalls( stmt, callExprs );
762                        // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
763                        return std::all_of( callExprs.begin(), callExprs.end(), pred);
764                }
[2d11663]765
766                template <typename Predicate>
767                bool allofCtorDtor( const ast::Stmt * stmt, const Predicate & pred ) {
[490fb92e]768                        std::vector< const ast::Expr * > callExprs = collectCtorDtorCalls( stmt );
[2d11663]769                        return std::all_of( callExprs.begin(), callExprs.end(), pred );
770                }
[a465caf]771        }
772
[f9cebb5]773        bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
[a465caf]774                return allofCtorDtor( stmt, []( Expression * callExpr ){
[4d2434a]775                        if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
[f072892]776                                FunctionType *funcType = GenPoly::getFunctionType( appExpr->function->result );
[4d2434a]777                                assert( funcType );
778                                return funcType->get_parameters().size() == 1;
779                        }
780                        return false;
[2d11663]781                });
782        }
783
784        bool isIntrinsicSingleArgCallStmt( const ast::Stmt * stmt ) {
785                return allofCtorDtor( stmt, []( const ast::Expr * callExpr ){
786                        if ( const ast::ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
[6f096d2]787                                const ast::FunctionType * funcType =
[2d11663]788                                        GenPoly::getFunctionType( appExpr->func->result );
789                                assert( funcType );
790                                return funcType->params.size() == 1;
791                        }
792                        return false;
[4d2434a]793                });
[64071c2]794        }
[f1b1e4c]795
[a465caf]796        bool isIntrinsicCallStmt( Statement * stmt ) {
797                return allofCtorDtor( stmt, []( Expression * callExpr ) {
798                        return isIntrinsicCallExpr( callExpr );
799                });
800        }
801
[64071c2]802        namespace {
803                template<typename CallExpr>
804                Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
[a61ad31]805                        if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
[64071c2]806                        for ( Expression *& arg : callExpr->get_args() ) {
807                                if ( pos == 0 ) return arg;
808                                pos--;
809                        }
810                        assert( false );
811                }
[9b4f329]812
[b5fed34]813                template<typename CallExpr>
814                const ast::Expr * callArg( const CallExpr * call, unsigned int pos ) {
815                        if( pos >= call->args.size() ) {
816                                assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.",
817                                        pos, toString( call ).c_str() );
818                        }
819                        for ( const ast::Expr * arg : call->args ) {
820                                if ( pos == 0 ) return arg;
821                                --pos;
822                        }
823                        assert( false );
824                }
[64071c2]825        }
[f1b1e4c]826
[64071c2]827        Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
828                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
829                        return callArg( appExpr, pos );
830                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
831                        return callArg( untypedExpr, pos );
[f3b0a07]832                } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
833                        std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
834                        assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
[e3e16bc]835                        ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
836                        TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
[f3b0a07]837                        assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
838                        return getCallArg( tuple->get_exprs().front(), pos );
[62a05d1]839                } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
840                        return getCallArg( copyCtor->callExpr, pos );
[64071c2]841                } else {
[f3b0a07]842                        assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
[64071c2]843                }
844        }
[b5fed34]845
[9b4f329]846        const ast::Expr * getCallArg( const ast::Expr * call, unsigned pos ) {
[b5fed34]847                if ( auto app = dynamic_cast< const ast::ApplicationExpr * >( call ) ) {
848                        return callArg( app, pos );
849                } else if ( auto untyped = dynamic_cast< const ast::UntypedExpr * >( call ) ) {
850                        return callArg( untyped, pos );
851                } else if ( auto tupleAssn = dynamic_cast< const ast::TupleAssignExpr * >( call ) ) {
852                        const std::list<ast::ptr<ast::Stmt>>& stmts = tupleAssn->stmtExpr->stmts->kids;
853                        assertf( ! stmts.empty(), "TupleAssignExpr missing statements." );
854                        auto stmt  = strict_dynamic_cast< const ast::ExprStmt * >( stmts.back().get() );
855                        auto tuple = strict_dynamic_cast< const ast::TupleExpr * >( stmt->expr.get() );
856                        assertf( ! tuple->exprs.empty(), "TupleAssignExpr has empty tuple expr.");
857                        return getCallArg( tuple->exprs.front(), pos );
858                } else if ( auto ctor = dynamic_cast< const ast::ImplicitCopyCtorExpr * >( call ) ) {
859                        return getCallArg( ctor->callExpr, pos );
860                } else {
861                        assertf( false, "Unexpected expression type passed to getCallArg: %s",
862                                toString( call ).c_str() );
863                }
[9b4f329]864        }
[f1b1e4c]865
[64071c2]866        namespace {
[599b386]867                std::string funcName( Expression * func );
[d7aa12c]868                std::string funcName( const ast::Expr * func );
[599b386]869
870                template<typename CallExpr>
871                std::string handleDerefName( CallExpr * expr ) {
872                        // (*f)(x) => should get name "f"
873                        std::string name = getFunctionName( expr );
874                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
[b128d3e]875                        assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
[599b386]876                        return funcName( expr->get_args().front() );
877                }
878
[d7aa12c]879                template<typename CallExpr>
880                std::string handleDerefName( const CallExpr * expr ) {
881                        // (*f)(x) => should get name "f"
882                        std::string name = getFunctionName( expr );
883                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
884                        assertf( ! expr->args.empty(), "Cannot get function name from dereference with no arguments" );
885                        return funcName( expr->args.front() );
886                }
887
[c738ca4]888                std::string funcName( Expression * func ) {
[64071c2]889                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
890                                return nameExpr->get_name();
891                        } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
892                                return varExpr->get_var()->get_name();
[c738ca4]893                        }       else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
894                                return funcName( castExpr->get_arg() );
[ee1635c8]895                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
896                                return memberExpr->get_member()->get_name();
[96a10cd]897                        } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
[fd782b2]898                                return funcName( memberExpr->get_member() );
[599b386]899                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
900                                return handleDerefName( untypedExpr );
901                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
902                                return handleDerefName( appExpr );
[19a9822]903                        } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
904                                return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
[64071c2]905                        } else {
[19a9822]906                                assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
[64071c2]907                        }
908                }
[d7aa12c]909
910                std::string funcName( const ast::Expr * func ) {
911                        if ( const ast::NameExpr * nameExpr = dynamic_cast< const ast::NameExpr * >( func ) ) {
912                                return nameExpr->name;
913                        } else if ( const ast::VariableExpr * varExpr = dynamic_cast< const ast::VariableExpr * >( func ) ) {
914                                return varExpr->var->name;
915                        }       else if ( const ast::CastExpr * castExpr = dynamic_cast< const ast::CastExpr * >( func ) ) {
916                                return funcName( castExpr->arg );
917                        } else if ( const ast::MemberExpr * memberExpr = dynamic_cast< const ast::MemberExpr * >( func ) ) {
918                                return memberExpr->member->name;
919                        } else if ( const ast::UntypedMemberExpr * memberExpr = dynamic_cast< const ast::UntypedMemberExpr * > ( func ) ) {
920                                return funcName( memberExpr->member );
921                        } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * >( func ) ) {
922                                return handleDerefName( untypedExpr );
923                        } else if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( func ) ) {
924                                return handleDerefName( appExpr );
925                        } else if ( const ast::ConstructorExpr * ctorExpr = dynamic_cast< const ast::ConstructorExpr * >( func ) ) {
926                                return funcName( getCallArg( ctorExpr->callExpr, 0 ) );
927                        } else {
928                                assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
929                        }
930                }
[64071c2]931        }
[70f89d00]932
[64071c2]933        std::string getFunctionName( Expression * expr ) {
[599b386]934                // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
935                // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
936                // can't possibly do anything reasonable.
[64071c2]937                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
[c738ca4]938                        return funcName( appExpr->get_function() );
[64071c2]939                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
[c738ca4]940                        return funcName( untypedExpr->get_function() );
[64071c2]941                } else {
[c738ca4]942                        std::cerr << expr << std::endl;
[d1969a6]943                        assertf( false, "Unexpected expression type passed to getFunctionName" );
[64071c2]944                }
945        }
[10a7775]946
[d7aa12c]947        std::string getFunctionName( const ast::Expr * expr ) {
948                // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
949                // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
950                // can't possibly do anything reasonable.
951                if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr ) ) {
952                        return funcName( appExpr->func );
953                } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * > ( expr ) ) {
954                        return funcName( untypedExpr->func );
955                } else {
956                        std::cerr << expr << std::endl;
957                        assertf( false, "Unexpected expression type passed to getFunctionName" );
958                }
959        }
960
[64071c2]961        Type * getPointerBase( Type * type ) {
962                if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
963                        return ptrType->get_base();
964                } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
965                        return arrayType->get_base();
[ce8c12f]966                } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
967                        return refType->get_base();
[64071c2]968                } else {
[22bc276]969                        return nullptr;
[64071c2]970                }
971        }
[9e1d485]972        const ast::Type* getPointerBase( const ast::Type* t ) {
[b5fed34]973                if ( const auto * p = dynamic_cast< const ast::PointerType * >( t ) ) {
974                        return p->base;
975                } else if ( const auto * a = dynamic_cast< const ast::ArrayType * >( t ) ) {
976                        return a->base;
977                } else if ( const auto * r = dynamic_cast< const ast::ReferenceType * >( t ) ) {
978                        return r->base;
979                } else return nullptr;
[9e1d485]980        }
[10a7775]981
[64071c2]982        Type * isPointerType( Type * type ) {
983                if ( getPointerBase( type ) ) return type;
[22bc276]984                else return nullptr;
[64071c2]985        }
[40e636a]986
[f5c3b6c]987        ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src ) {
988                static FunctionDecl * assign = nullptr;
989                if ( ! assign ) {
990                        // temporary? Generate a fake assignment operator to represent bitwise assignments.
991                        // This operator could easily exist as a real function, but it's tricky because nothing should resolve to this function.
992                        TypeDecl * td = new TypeDecl( "T", noStorageClasses, nullptr, TypeDecl::Dtype, true );
993                        assign = new FunctionDecl( "?=?", noStorageClasses, LinkageSpec::Intrinsic, SymTab::genAssignType( new TypeInstType( noQualifiers, td->name, td ) ), nullptr );
994                }
995                if ( dynamic_cast< ReferenceType * >( dst->result ) ) {
[5002738]996                        for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
997                                dst = new AddressExpr( dst );
998                        }
[f5c3b6c]999                } else {
1000                        dst = new CastExpr( dst, new ReferenceType( noQualifiers, dst->result->clone() ) );
1001                }
1002                if ( dynamic_cast< ReferenceType * >( src->result ) ) {
[5002738]1003                        for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
1004                                src = new AddressExpr( src );
1005                        }
[ba89e9b7]1006                        // src = new CastExpr( src, new ReferenceType( noQualifiers, src->result->stripReferences()->clone() ) );
[f5c3b6c]1007                }
1008                return new ApplicationExpr( VariableExpr::functionPointer( assign ), { dst, src } );
1009        }
1010
[490fb92e]1011        // looks like some other such codegen uses UntypedExpr and does not create fake function. should revisit afterwards
1012        // following passes may accidentally resolve this expression if returned as untyped...
1013        ast::Expr * createBitwiseAssignment (const ast::Expr * dst, const ast::Expr * src) {
1014                static ast::ptr<ast::FunctionDecl> assign = nullptr;
1015                if (!assign) {
1016                        auto td = new ast::TypeDecl({}, "T", {}, nullptr, ast::TypeDecl::Dtype, true);
1017                        assign = new ast::FunctionDecl({}, "?=?", {}, 
1018                        { new ast::ObjectDecl({}, "_dst", new ast::ReferenceType(new ast::TypeInstType("T", td))),
1019                          new ast::ObjectDecl({}, "_src", new ast::TypeInstType("T", td))},
1020                        { new ast::ObjectDecl({}, "_ret", new ast::TypeInstType("T", td))}, nullptr, {}, ast::Linkage::Intrinsic);
1021                }
1022                if (dst->result.as<ast::ReferenceType>()) {
1023                        for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
1024                                dst = new ast::AddressExpr(dst);
1025                        }
1026                }
1027                else {
1028                        dst = new ast::CastExpr(dst, new ast::ReferenceType(dst->result, {}));
1029                }
1030                if (src->result.as<ast::ReferenceType>()) {
1031                        for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
1032                                src = new ast::AddressExpr(src);
1033                        }
1034                }
1035                return new ast::ApplicationExpr(dst->location, ast::VariableExpr::functionPointer(dst->location, assign), {dst, src});
1036        }
1037
[c5f3c68]1038        struct ConstExprChecker : public WithShortCircuiting {
1039                // most expressions are not const expr
1040                void previsit( Expression * ) { isConstExpr = false; visit_children = false; }
[40e636a]1041
[c5f3c68]1042                void previsit( AddressExpr *addressExpr ) {
1043                        visit_children = false;
[65dc863]1044
[1ba88a0]1045                        // address of a variable or member expression is constexpr
1046                        Expression * arg = addressExpr->get_arg();
1047                        if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
1048                }
[c5f3c68]1049
1050                // these expressions may be const expr, depending on their children
1051                void previsit( SizeofExpr * ) {}
1052                void previsit( AlignofExpr * ) {}
1053                void previsit( UntypedOffsetofExpr * ) {}
1054                void previsit( OffsetofExpr * ) {}
1055                void previsit( OffsetPackExpr * ) {}
1056                void previsit( CommaExpr * ) {}
1057                void previsit( LogicalExpr * ) {}
1058                void previsit( ConditionalExpr * ) {}
1059                void previsit( CastExpr * ) {}
1060                void previsit( ConstantExpr * ) {}
1061
[caab997]1062                void previsit( VariableExpr * varExpr ) {
1063                        visit_children = false;
1064
1065                        if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( varExpr->result ) ) {
1066                                long long int value;
1067                                if ( inst->baseEnum->valueOf( varExpr->var, value ) ) {
1068                                        // enumerators are const expr
1069                                        return;
1070                                }
1071                        }
1072                        isConstExpr = false;
1073                }
1074
[c5f3c68]1075                bool isConstExpr = true;
[40e636a]1076        };
1077
[16ba4a6]1078        struct ConstExprChecker_new : public ast::WithShortCircuiting {
1079                // most expressions are not const expr
1080                void previsit( const ast::Expr * ) { result = false; visit_children = false; }
1081
1082                void previsit( const ast::AddressExpr *addressExpr ) {
1083                        visit_children = false;
1084                        const ast::Expr * arg = addressExpr->arg;
1085
1086                        // address of a variable or member expression is constexpr
1087                        if ( ! dynamic_cast< const ast::NameExpr * >( arg ) 
1088                        && ! dynamic_cast< const ast::VariableExpr * >( arg ) 
1089                        && ! dynamic_cast< const ast::MemberExpr * >( arg ) 
1090                        && ! dynamic_cast< const ast::UntypedMemberExpr * >( arg ) ) result = false;
1091                }
1092
1093                // these expressions may be const expr, depending on their children
1094                void previsit( const ast::SizeofExpr * ) {}
1095                void previsit( const ast::AlignofExpr * ) {}
1096                void previsit( const ast::UntypedOffsetofExpr * ) {}
1097                void previsit( const ast::OffsetofExpr * ) {}
1098                void previsit( const ast::OffsetPackExpr * ) {}
1099                void previsit( const ast::CommaExpr * ) {}
1100                void previsit( const ast::LogicalExpr * ) {}
1101                void previsit( const ast::ConditionalExpr * ) {}
1102                void previsit( const ast::CastExpr * ) {}
1103                void previsit( const ast::ConstantExpr * ) {}
1104
1105                void previsit( const ast::VariableExpr * varExpr ) {
1106                        visit_children = false;
1107
1108                        if ( auto inst = varExpr->result.as<ast::EnumInstType>() ) {
1109                                long long int value;
1110                                if ( inst->base->valueOf( varExpr->var, value ) ) {
1111                                        // enumerators are const expr
1112                                        return;
1113                                }
1114                        }
1115                        result = false;
1116                }
1117
1118                bool result = true;
1119        };
1120
[40e636a]1121        bool isConstExpr( Expression * expr ) {
1122                if ( expr ) {
[c5f3c68]1123                        PassVisitor<ConstExprChecker> checker;
[40e636a]1124                        expr->accept( checker );
[c5f3c68]1125                        return checker.pass.isConstExpr;
[40e636a]1126                }
1127                return true;
1128        }
1129
1130        bool isConstExpr( Initializer * init ) {
1131                if ( init ) {
[c5f3c68]1132                        PassVisitor<ConstExprChecker> checker;
[40e636a]1133                        init->accept( checker );
[c5f3c68]1134                        return checker.pass.isConstExpr;
[40e636a]1135                } // if
1136                // for all intents and purposes, no initializer means const expr
1137                return true;
1138        }
1139
[16ba4a6]1140        bool isConstExpr( const ast::Expr * expr ) {
1141                if ( expr ) {
1142                        ast::Pass<ConstExprChecker_new> checker;
1143                        expr->accept( checker );
1144                        return checker.core.result;
1145                }
1146                return true;
1147        }
1148
1149        bool isConstExpr( const ast::Init * init ) {
1150                if ( init ) {
1151                        ast::Pass<ConstExprChecker_new> checker;
1152                        init->accept( checker );
1153                        return checker.core.result;
1154                } // if
1155                // for all intents and purposes, no initializer means const expr
1156                return true;
1157        }
1158
[79970ed]1159        bool isConstructor( const std::string & str ) { return str == "?{}"; }
1160        bool isDestructor( const std::string & str ) { return str == "^?{}"; }
[ee1635c8]1161        bool isAssignment( const std::string & str ) { return str == "?=?"; }
[79970ed]1162        bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
[ee1635c8]1163        bool isCtorDtorAssign( const std::string & str ) { return isCtorDtor( str ) || isAssignment( str ); }
[4d4882a]1164
[6f096d2]1165        const FunctionDecl * isCopyFunction( const Declaration * decl, const std::string & fname ) {
1166                const FunctionDecl * function = dynamic_cast< const FunctionDecl * >( decl );
[0a267c1]1167                if ( ! function ) return nullptr;
1168                if ( function->name != fname ) return nullptr;
1169                FunctionType * ftype = function->type;
1170                if ( ftype->parameters.size() != 2 ) return nullptr;
[4d4882a]1171
[ce8c12f]1172                Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
[0a267c1]1173                Type * t2 = ftype->parameters.back()->get_type();
[ce8c12f]1174                assert( t1 );
[4d4882a]1175
[ce8c12f]1176                if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
[4d4882a]1177                        return function;
1178                } else {
[ee1635c8]1179                        return nullptr;
[4d4882a]1180                }
1181        }
[ee1635c8]1182
[d76c588]1183        bool isCopyFunction( const ast::FunctionDecl * decl ) {
1184                const ast::FunctionType * ftype = decl->type;
1185                if ( ftype->params.size() != 2 ) return false;
1186
[954c954]1187                const ast::Type * t1 = getPointerBase( ftype->params.front() );
[d76c588]1188                if ( ! t1 ) return false;
[954c954]1189                const ast::Type * t2 = ftype->params.back();
[6f096d2]1190
[d76c588]1191                return ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, ast::SymbolTable{} );
1192        }
1193
[6f096d2]1194        const FunctionDecl * isAssignment( const Declaration * decl ) {
[207c7e1d]1195                return isCopyFunction( decl, "?=?" );
1196        }
[6f096d2]1197        const FunctionDecl * isDestructor( const Declaration * decl ) {
1198                if ( isDestructor( decl->name ) ) {
1199                        return dynamic_cast< const FunctionDecl * >( decl );
[207c7e1d]1200                }
1201                return nullptr;
1202        }
[6f096d2]1203        const FunctionDecl * isDefaultConstructor( const Declaration * decl ) {
[0a267c1]1204                if ( isConstructor( decl->name ) ) {
[6f096d2]1205                        if ( const FunctionDecl * func = dynamic_cast< const FunctionDecl * >( decl ) ) {
[0a267c1]1206                                if ( func->type->parameters.size() == 1 ) {
[207c7e1d]1207                                        return func;
1208                                }
1209                        }
1210                }
1211                return nullptr;
1212        }
[6f096d2]1213        const FunctionDecl * isCopyConstructor( const Declaration * decl ) {
[ee1635c8]1214                return isCopyFunction( decl, "?{}" );
1215        }
[f1791a4]1216
1217        void addDataSectonAttribute( ObjectDecl * objDecl ) {
1218                Type *strLitT = new PointerType( Type::Qualifiers( ),
1219                        new BasicType( Type::Qualifiers( ), BasicType::Char ) );
1220                std::list< Expression * > attr_params;
1221                attr_params.push_back( 
1222                        new ConstantExpr( Constant( strLitT, "\".data#\"", std::nullopt ) ) );
1223                objDecl->attributes.push_back(new Attribute("section", attr_params));
1224        }
1225
[7d651a6]1226        void addDataSectionAttribute( ast::ObjectDecl * objDecl ) {
1227                auto strLitT = new ast::PointerType(new ast::BasicType(ast::BasicType::Char));
1228                objDecl->attributes.push_back(new ast::Attribute("section", {new ast::ConstantExpr(objDecl->location, strLitT, "\".data#\"", std::nullopt)}));
1229        }
1230
[2b46a13]1231}
Note: See TracBrowser for help on using the repository browser.