source: src/InitTweak/GenInit.cc @ 0e398ad

ADTast-experimental
Last change on this file since 0e398ad was 9feb34b, checked in by Andrew Beach <ajbeach@…>, 15 months ago

Moved toString and toCString to a new header. Updated includes. cassert was somehow getting instances of toString before but that stopped working so I embedded the new smaller include.

  • Property mode set to 100644
File size: 28.1 KB
RevLine 
[51587aa]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//
[11df881]7// GenInit.cc -- Generate initializers, and other stuff.
[51587aa]8//
[cf16f94]9// Author           : Rob Schluntz
[51587aa]10// Created On       : Mon May 18 07:44:20 2015
[a36eb2d]11// Last Modified By : Andrew Beach
[148ba7d]12// Last Modified On : Mon Oct 25 13:53:00 2021
13// Update Count     : 186
[51587aa]14//
[8ca3a72]15#include "GenInit.h"
16
[2bfc6b2]17#include <stddef.h>                    // for NULL
18#include <algorithm>                   // for any_of
19#include <cassert>                     // for assert, strict_dynamic_cast, assertf
[b8524ca]20#include <deque>
[2bfc6b2]21#include <iterator>                    // for back_inserter, inserter, back_inse...
22#include <list>                        // for _List_iterator, list
[8ca3a72]23
[b8524ca]24#include "AST/Decl.hpp"
25#include "AST/Init.hpp"
[a36eb2d]26#include "AST/Pass.hpp"
[b8524ca]27#include "AST/Node.hpp"
28#include "AST/Stmt.hpp"
[16ba4a6]29#include "CompilationState.h"
[8135d4c]30#include "CodeGen/OperatorTable.h"
[2bfc6b2]31#include "Common/PassVisitor.h"        // for PassVisitor, WithGuards, WithShort...
32#include "Common/SemanticError.h"      // for SemanticError
[9feb34b]33#include "Common/ToString.hpp"         // for toCString
[2bfc6b2]34#include "Common/UniqueName.h"         // for UniqueName
35#include "Common/utility.h"            // for ValueGuard, maybeClone
36#include "GenPoly/GenPoly.h"           // for getFunctionType, isPolyType
37#include "GenPoly/ScopedSet.h"         // for ScopedSet, ScopedSet<>::const_iter...
38#include "InitTweak.h"                 // for isConstExpr, InitExpander, checkIn...
[fdd0509]39#include "ResolvExpr/Resolver.h"
[2bfc6b2]40#include "SymTab/Autogen.h"            // for genImplicitCall
41#include "SymTab/Mangler.h"            // for Mangler
[07de76b]42#include "SynTree/LinkageSpec.h"       // for isOverridable, C
[2bfc6b2]43#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
44#include "SynTree/Expression.h"        // for VariableExpr, UntypedExpr, Address...
45#include "SynTree/Initializer.h"       // for ConstructorInit, SingleInit, Initi...
46#include "SynTree/Label.h"             // for Label
47#include "SynTree/Mutator.h"           // for mutateAll
48#include "SynTree/Statement.h"         // for CompoundStmt, ImplicitCtorDtorStmt
49#include "SynTree/Type.h"              // for Type, ArrayType, Type::Qualifiers
50#include "SynTree/Visitor.h"           // for acceptAll, maybeAccept
51#include "Tuples/Tuples.h"             // for maybeImpure
52#include "Validate/FindSpecialDecls.h" // for SizeType
[42e2ad7]53
54namespace InitTweak {
[a08ba92]55        namespace {
56                const std::list<Label> noLabels;
[5b40f30]57                const std::list<Expression *> noDesignators;
[a08ba92]58        }
[1e9d87b]59
[d24d4e1]60        struct ReturnFixer : public WithStmtsToAdd, public WithGuards {
[a0fdbd5]61                /// consistently allocates a temporary variable for the return value
62                /// of a function so that anything which the resolver decides can be constructed
[02c7d04]63                /// into the return type of a function can be returned.
[a0fdbd5]64                static void makeReturnTemp( std::list< Declaration * > &translationUnit );
[02c7d04]65
[7b6ca2e]66                void premutate( FunctionDecl *functionDecl );
67                void premutate( ReturnStmt * returnStmt );
[1e9d87b]68
69          protected:
[c6976ba]70                FunctionType * ftype = nullptr;
[cf16f94]71                std::string funcName;
72        };
[42e2ad7]73
[22bc276]74        struct CtorDtor : public WithGuards, public WithShortCircuiting, public WithVisitorRef<CtorDtor>  {
[02c7d04]75                /// create constructor and destructor statements for object declarations.
[5f98ce5]76                /// the actual call statements will be added in after the resolver has run
77                /// so that the initializer expression is only removed if a constructor is found
78                /// and the same destructor call is inserted in all of the appropriate locations.
[02c7d04]79                static void generateCtorDtor( std::list< Declaration * > &translationUnit );
[974906e2]80
[d24d4e1]81                void previsit( ObjectDecl * );
82                void previsit( FunctionDecl *functionDecl );
83
[5f98ce5]84                // should not traverse into any of these declarations to find objects
85                // that need to be constructed or destructed
[d24d4e1]86                void previsit( StructDecl *aggregateDecl );
[aec3e6b]87                void previsit( AggregateDecl * ) { visit_children = false; }
88                void previsit( NamedTypeDecl * ) { visit_children = false; }
[22bc276]89                void previsit( FunctionType * ) { visit_children = false; }
[db4ecc5]90
[d24d4e1]91                void previsit( CompoundStmt * compoundStmt );
[1ba88a0]92
93          private:
94                // set of mangled type names for which a constructor or destructor exists in the current scope.
95                // these types require a ConstructorInit node to be generated, anything else is a POD type and thus
96                // should not have a ConstructorInit generated.
97
[bfd4974]98                ManagedTypes managedTypes;
[1ba88a0]99                bool inFunction = false;
[974906e2]100        };
101
[fdd0509]102        struct HoistArrayDimension final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards, public WithIndexer {
[5f98ce5]103                /// hoist dimension from array types in object declaration so that it uses a single
104                /// const variable of type size_t, so that side effecting array dimensions are only
105                /// computed once.
106                static void hoistArrayDimension( std::list< Declaration * > & translationUnit );
107
[22bc276]108                void premutate( ObjectDecl * objectDecl );
109                DeclarationWithType * postmutate( ObjectDecl * objectDecl );
110                void premutate( FunctionDecl *functionDecl );
[5f98ce5]111                // should not traverse into any of these declarations to find objects
112                // that need to be constructed or destructed
[22bc276]113                void premutate( AggregateDecl * ) { visit_children = false; }
114                void premutate( NamedTypeDecl * ) { visit_children = false; }
115                void premutate( FunctionType * ) { visit_children = false; }
[5f98ce5]116
[fdd0509]117                // need this so that enumerators are added to the indexer, due to premutate(AggregateDecl *)
118                void premutate( EnumDecl * ) {}
119
[5f98ce5]120                void hoist( Type * type );
121
[68fe077a]122                Type::StorageClasses storageClasses;
[40e636a]123                bool inFunction = false;
[5f98ce5]124        };
125
[09867ec]126        struct HoistArrayDimension_NoResolve final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards {
127                /// hoist dimension from array types in object declaration so that it uses a single
128                /// const variable of type size_t, so that side effecting array dimensions are only
129                /// computed once.
130                static void hoistArrayDimension( std::list< Declaration * > & translationUnit );
131
132                void premutate( ObjectDecl * objectDecl );
133                DeclarationWithType * postmutate( ObjectDecl * objectDecl );
134                void premutate( FunctionDecl *functionDecl );
135                // should not traverse into any of these declarations to find objects
136                // that need to be constructed or destructed
137                void premutate( AggregateDecl * ) { visit_children = false; }
138                void premutate( NamedTypeDecl * ) { visit_children = false; }
139                void premutate( FunctionType * ) { visit_children = false; }
140
141                void hoist( Type * type );
142
143                Type::StorageClasses storageClasses;
144                bool inFunction = false;
145        };
146
[a0fdbd5]147        void genInit( std::list< Declaration * > & translationUnit ) {
[09867ec]148                if (!useNewAST) {
149                        HoistArrayDimension::hoistArrayDimension( translationUnit );
150                }
151                else {
152                        HoistArrayDimension_NoResolve::hoistArrayDimension( translationUnit );
153                }
[16ba4a6]154                fixReturnStatements( translationUnit );
155
156                if (!useNewAST) {
157                        CtorDtor::generateCtorDtor( translationUnit );
158                }
[02c7d04]159        }
160
[8b11840]161        void fixReturnStatements( std::list< Declaration * > & translationUnit ) {
[7b6ca2e]162                PassVisitor<ReturnFixer> fixer;
[a0fdbd5]163                mutateAll( translationUnit, fixer );
[a08ba92]164        }
[42e2ad7]165
[7b6ca2e]166        void ReturnFixer::premutate( ReturnStmt *returnStmt ) {
[65660bd]167                std::list< DeclarationWithType * > & returnVals = ftype->get_returnVals();
[cf16f94]168                assert( returnVals.size() == 0 || returnVals.size() == 1 );
[c6976ba]169                // hands off if the function returns a reference - we don't want to allocate a temporary if a variable's address
[cf16f94]170                // is being returned
[bd7e609]171                if ( returnStmt->expr && returnVals.size() == 1 && isConstructable( returnVals.front()->get_type() ) ) {
[cce9429]172                        // explicitly construct the return value using the return expression and the retVal object
[18ca28e]173                        assertf( returnVals.front()->name != "", "Function %s has unnamed return value\n", funcName.c_str() );
[c6976ba]174
[bd7e609]175                        ObjectDecl * retVal = strict_dynamic_cast< ObjectDecl * >( returnVals.front() );
176                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( returnStmt->expr ) ) {
177                                // return statement has already been mutated - don't need to do it again
178                                if ( varExpr->var == retVal ) return;
179                        }
[9fe33947]180                        Statement * stmt = genCtorDtor( "?{}", retVal, returnStmt->expr );
181                        assertf( stmt, "ReturnFixer: genCtorDtor returned nullptr: %s / %s", toString( retVal ).c_str(), toString( returnStmt->expr ).c_str() );
182                        stmtsToAddBefore.push_back( stmt );
[cf16f94]183
[cce9429]184                        // return the retVal object
[18ca28e]185                        returnStmt->expr = new VariableExpr( returnVals.front() );
[cf16f94]186                } // if
187        }
188
[7b6ca2e]189        void ReturnFixer::premutate( FunctionDecl *functionDecl ) {
[4eb31f2b]190                GuardValue( ftype );
191                GuardValue( funcName );
[1e9d87b]192
[22bc276]193                ftype = functionDecl->type;
194                funcName = functionDecl->name;
[cf16f94]195        }
[974906e2]196
[4d2434a]197        // precompute array dimension expression, because constructor generation may duplicate it,
198        // which would be incorrect if it is a side-effecting computation.
[5f98ce5]199        void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
[22bc276]200                PassVisitor<HoistArrayDimension> hoister;
201                mutateAll( translationUnit, hoister );
[5f98ce5]202        }
203
[22bc276]204        void HoistArrayDimension::premutate( ObjectDecl * objectDecl ) {
205                GuardValue( storageClasses );
[a7c90d4]206                storageClasses = objectDecl->get_storageClasses();
[22bc276]207        }
208
209        DeclarationWithType * HoistArrayDimension::postmutate( ObjectDecl * objectDecl ) {
[5f98ce5]210                hoist( objectDecl->get_type() );
[22bc276]211                return objectDecl;
[5f98ce5]212        }
213
214        void HoistArrayDimension::hoist( Type * type ) {
[40e636a]215                // if in function, generate const size_t var
[5f98ce5]216                static UniqueName dimensionName( "_array_dim" );
[40e636a]217
[a7c90d4]218                // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension.
[f9cebb5]219                if ( ! inFunction ) return;
[08d5507b]220                if ( storageClasses.is_static ) return;
[f9cebb5]221
222                if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
[5f98ce5]223                        if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?
224
[fdd0509]225                        // need to resolve array dimensions in order to accurately determine if constexpr
[09867ec]226                        ResolvExpr::findSingleExpression( arrayType->dimension, Validate::SizeType->clone(), indexer );
227                        // array is variable-length when the dimension is not constexpr
228                        arrayType->isVarLen = ! isConstExpr( arrayType->dimension );
[300d75b]229                        // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects.
[5465377c]230                        // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve
231                        // still try to detect constant expressions
232                        if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return;
[5f98ce5]233
[2bfc6b2]234                        ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
[615a096]235                        arrayDimension->get_type()->set_const( true );
[5f98ce5]236
237                        arrayType->set_dimension( new VariableExpr( arrayDimension ) );
[22bc276]238                        declsToAddBefore.push_back( arrayDimension );
[5f98ce5]239
240                        hoist( arrayType->get_base() );
241                        return;
242                }
243        }
[974906e2]244
[22bc276]245        void HoistArrayDimension::premutate( FunctionDecl * ) {
246                GuardValue( inFunction );
[fdd0509]247                inFunction = true;
[40e636a]248        }
249
[09867ec]250        // precompute array dimension expression, because constructor generation may duplicate it,
251        // which would be incorrect if it is a side-effecting computation.
252        void HoistArrayDimension_NoResolve::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
253                PassVisitor<HoistArrayDimension_NoResolve> hoister;
254                mutateAll( translationUnit, hoister );
255        }
256
257        void HoistArrayDimension_NoResolve::premutate( ObjectDecl * objectDecl ) {
258                GuardValue( storageClasses );
259                storageClasses = objectDecl->get_storageClasses();
260        }
261
262        DeclarationWithType * HoistArrayDimension_NoResolve::postmutate( ObjectDecl * objectDecl ) {
263                hoist( objectDecl->get_type() );
264                return objectDecl;
265        }
266
267        void HoistArrayDimension_NoResolve::hoist( Type * type ) {
268                // if in function, generate const size_t var
269                static UniqueName dimensionName( "_array_dim" );
270
271                // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension.
272                if ( ! inFunction ) return;
273                if ( storageClasses.is_static ) return;
274
275                if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
276                        if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?
277                        // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects.
278                        // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve
279                        // still try to detect constant expressions
280                        if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return;
281
282                        ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
283                        arrayDimension->get_type()->set_const( true );
284
285                        arrayType->set_dimension( new VariableExpr( arrayDimension ) );
286                        declsToAddBefore.push_back( arrayDimension );
287
288                        hoist( arrayType->get_base() );
289                        return;
290                }
291        }
292
293        void HoistArrayDimension_NoResolve::premutate( FunctionDecl * ) {
294                GuardValue( inFunction );
295                inFunction = true;
296        }
297
[a36eb2d]298namespace {
299
300#       warning Remove the _New suffix after the conversion is complete.
301        struct HoistArrayDimension_NoResolve_New final :
302                        public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting,
[c600df1]303                        public ast::WithGuards, public ast::WithConstTranslationUnit,
[a36eb2d]304                        public ast::WithVisitorRef<HoistArrayDimension_NoResolve_New> {
305                void previsit( const ast::ObjectDecl * decl );
306                const ast::DeclWithType * postvisit( const ast::ObjectDecl * decl );
307                // Do not look for objects inside there declarations (and type).
308                void previsit( const ast::AggregateDecl * ) { visit_children = false; }
309                void previsit( const ast::NamedTypeDecl * ) { visit_children = false; }
310                void previsit( const ast::FunctionType * ) { visit_children = false; }
311
312                const ast::Type * hoist( const ast::Type * type );
313
314                ast::Storage::Classes storageClasses;
315        };
316
317        void HoistArrayDimension_NoResolve_New::previsit(
318                        const ast::ObjectDecl * decl ) {
[148ba7d]319                GuardValue( storageClasses ) = decl->storage;
[a36eb2d]320        }
321
322        const ast::DeclWithType * HoistArrayDimension_NoResolve_New::postvisit(
323                        const ast::ObjectDecl * objectDecl ) {
324                return mutate_field( objectDecl, &ast::ObjectDecl::type,
325                                hoist( objectDecl->type ) );
326        }
327
328        const ast::Type * HoistArrayDimension_NoResolve_New::hoist(
329                        const ast::Type * type ) {
330                static UniqueName dimensionName( "_array_dim" );
331
332                if ( !isInFunction() || storageClasses.is_static ) {
333                        return type;
334                }
335
336                if ( auto arrayType = dynamic_cast< const ast::ArrayType * >( type ) ) {
337                        if ( nullptr == arrayType->dimension ) {
338                                return type;
339                        }
340
341                        if ( !Tuples::maybeImpure( arrayType->dimension ) ) {
342                                return type;
343                        }
344
[c600df1]345                        ast::ptr<ast::Type> dimType = transUnit().global.sizeType;
[a36eb2d]346                        assert( dimType );
347                        add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) );
348
349                        ast::ObjectDecl * arrayDimension = new ast::ObjectDecl(
350                                arrayType->dimension->location,
351                                dimensionName.newName(),
352                                dimType,
353                                new ast::SingleInit(
354                                        arrayType->dimension->location,
355                                        arrayType->dimension
356                                )
357                        );
358
359                        ast::ArrayType * mutType = ast::mutate( arrayType );
360                        mutType->dimension = new ast::VariableExpr(
361                                        arrayDimension->location, arrayDimension );
362                        declsToAddBefore.push_back( arrayDimension );
363
364                        mutType->base = hoist( mutType->base );
365                        return mutType;
366                }
367                return type;
368        }
369
370        struct ReturnFixer_New final :
[fc134a48]371                        public ast::WithStmtsToAdd<>, ast::WithGuards, ast::WithShortCircuiting {
[a36eb2d]372                void previsit( const ast::FunctionDecl * decl );
373                const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt );
374        private:
375                const ast::FunctionDecl * funcDecl = nullptr;
376        };
377
378        void ReturnFixer_New::previsit( const ast::FunctionDecl * decl ) {
[fc134a48]379                if (decl->linkage == ast::Linkage::Intrinsic) visit_children = false;
[148ba7d]380                GuardValue( funcDecl ) = decl;
[a36eb2d]381        }
382
383        const ast::ReturnStmt * ReturnFixer_New::previsit(
384                        const ast::ReturnStmt * stmt ) {
385                auto & returns = funcDecl->returns;
386                assert( returns.size() < 2 );
387                // Hands off if the function returns a reference.
388                // Don't allocate a temporary if the address is returned.
389                if ( stmt->expr && 1 == returns.size() ) {
390                        ast::ptr<ast::DeclWithType> retDecl = returns.front();
391                        if ( isConstructable( retDecl->get_type() ) ) {
392                                // Explicitly construct the return value using the return
393                                // expression and the retVal object.
394                                assertf( "" != retDecl->name,
395                                        "Function %s has unnamed return value.\n",
396                                        funcDecl->name.c_str() );
397
398                                auto retVal = retDecl.strict_as<ast::ObjectDecl>();
399                                if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) {
400                                        // Check if the return statement is already set up.
401                                        if ( varExpr->var == retVal ) return stmt;
402                                }
403                                ast::ptr<ast::Stmt> ctorStmt = genCtorDtor(
404                                        retVal->location, "?{}", retVal, stmt->expr );
405                                assertf( ctorStmt,
[4ec9513]406                                        "ReturnFixer: genCtorDtor returned nullptr: %s / %s",
[a36eb2d]407                                        toString( retVal ).c_str(),
408                                        toString( stmt->expr ).c_str() );
[4ec9513]409                                stmtsToAddBefore.push_back( ctorStmt );
[a36eb2d]410
411                                // Return the retVal object.
412                                ast::ReturnStmt * mutStmt = ast::mutate( stmt );
413                                mutStmt->expr = new ast::VariableExpr(
414                                        stmt->location, retDecl );
415                                return mutStmt;
416                        }
417                }
418                return stmt;
419        }
420
421} // namespace
422
423        void genInit( ast::TranslationUnit & transUnit ) {
424                ast::Pass<HoistArrayDimension_NoResolve_New>::run( transUnit );
425                ast::Pass<ReturnFixer_New>::run( transUnit );
426        }
427
[4ec9513]428        void fixReturnStatements( ast::TranslationUnit & transUnit ) {
429                ast::Pass<ReturnFixer_New>::run( transUnit );
430        }
431
[02c7d04]432        void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
[d24d4e1]433                PassVisitor<CtorDtor> ctordtor;
434                acceptAll( translationUnit, ctordtor );
[974906e2]435        }
436
[bfd4974]437        bool ManagedTypes::isManaged( Type * type ) const {
[22bc276]438                // references are never constructed
[c6976ba]439                if ( dynamic_cast< ReferenceType * >( type ) ) return false;
[0b465a5]440                // need to clear and reset qualifiers when determining if a type is managed
441                ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() );
442                type->get_qualifiers() = Type::Qualifiers();
[ac9ca96]443                if ( TupleType * tupleType = dynamic_cast< TupleType * > ( type ) ) {
444                        // tuple is also managed if any of its components are managed
[22bc276]445                        if ( std::any_of( tupleType->types.begin(), tupleType->types.end(), [&](Type * type) { return isManaged( type ); }) ) {
[ac9ca96]446                                return true;
447                        }
448                }
[30b65d8]449                // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable)
[e35f30a]450                return managedTypes.find( SymTab::Mangler::mangleConcrete( type ) ) != managedTypes.end() || GenPoly::isPolyType( type );
[65660bd]451        }
452
[bfd4974]453        bool ManagedTypes::isManaged( ObjectDecl * objDecl ) const {
[1ba88a0]454                Type * type = objDecl->get_type();
455                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
[be9aa0f]456                        // must always construct VLAs with an initializer, since this is an error in C
457                        if ( at->isVarLen && objDecl->init ) return true;
[1ba88a0]458                        type = at->get_base();
459                }
[65660bd]460                return isManaged( type );
[1ba88a0]461        }
462
[16ba4a6]463        // why is this not just on FunctionDecl?
[bfd4974]464        void ManagedTypes::handleDWT( DeclarationWithType * dwt ) {
[1ba88a0]465                // if this function is a user-defined constructor or destructor, mark down the type as "managed"
[bff227f]466                if ( ! LinkageSpec::isOverridable( dwt->get_linkage() ) && CodeGen::isCtorDtor( dwt->get_name() ) ) {
[1ba88a0]467                        std::list< DeclarationWithType * > & params = GenPoly::getFunctionType( dwt->get_type() )->get_parameters();
468                        assert( ! params.empty() );
[ce8c12f]469                        Type * type = InitTweak::getPointerBase( params.front()->get_type() );
470                        assert( type );
[e35f30a]471                        managedTypes.insert( SymTab::Mangler::mangleConcrete( type ) );
[1ba88a0]472                }
473        }
474
[bfd4974]475        void ManagedTypes::handleStruct( StructDecl * aggregateDecl ) {
476                // don't construct members, but need to take note if there is a managed member,
477                // because that means that this type is also managed
478                for ( Declaration * member : aggregateDecl->get_members() ) {
479                        if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
480                                if ( isManaged( field ) ) {
[e35f30a]481                                        // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
482                                        // polymorphic constructors make generic types managed types
[bfd4974]483                                        StructInstType inst( Type::Qualifiers(), aggregateDecl );
[e35f30a]484                                        managedTypes.insert( SymTab::Mangler::mangleConcrete( &inst ) );
[bfd4974]485                                        break;
486                                }
487                        }
488                }
489        }
490
491        void ManagedTypes::beginScope() { managedTypes.beginScope(); }
492        void ManagedTypes::endScope() { managedTypes.endScope(); }
493
[16ba4a6]494        bool ManagedTypes_new::isManaged( const ast::Type * type ) const {
495                // references are never constructed
496                if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false;
497                if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) {
498                        // tuple is also managed if any of its components are managed
499                        for (auto & component : tupleType->types) {
500                                if (isManaged(component)) return true;
501                        }
502                }
503                // need to clear and reset qualifiers when determining if a type is managed
504                // ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() );
505                auto tmp = shallowCopy(type);
506                tmp->qualifiers = {};
507                // delete tmp at return
508                ast::ptr<ast::Type> guard = tmp;
509                // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable)
510                return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp );
511        }
512
513        bool ManagedTypes_new::isManaged( const ast::ObjectDecl * objDecl ) const {
514                const ast::Type * type = objDecl->type;
515                while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) {
516                        // must always construct VLAs with an initializer, since this is an error in C
517                        if ( at->isVarLen && objDecl->init ) return true;
518                        type = at->base;
519                }
520                return isManaged( type );
521        }
522
523        void ManagedTypes_new::handleDWT( const ast::DeclWithType * dwt ) {
524                // if this function is a user-defined constructor or destructor, mark down the type as "managed"
525                if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) {
526                        auto & params = GenPoly::getFunctionType( dwt->get_type())->params;
527                        assert( ! params.empty() );
528                        // Type * type = InitTweak::getPointerBase( params.front() );
529                        // assert( type );
530                        managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
531                }
532        }
533
534        void ManagedTypes_new::handleStruct( const ast::StructDecl * aggregateDecl ) {
535                // don't construct members, but need to take note if there is a managed member,
536                // because that means that this type is also managed
537                for ( auto & member : aggregateDecl->members ) {
538                        if ( auto field = member.as<ast::ObjectDecl>() ) {
539                                if ( isManaged( field ) ) {
540                                        // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
541                                        // polymorphic constructors make generic types managed types
542                                        ast::StructInstType inst( aggregateDecl );
543                                        managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
544                                        break;
545                                }
546                        }
547                }
548        }
549
550        void ManagedTypes_new::beginScope() { managedTypes.beginScope(); }
551        void ManagedTypes_new::endScope() { managedTypes.endScope(); }
552
[092528b]553        ImplicitCtorDtorStmt * genCtorDtor( const std::string & fname, ObjectDecl * objDecl, Expression * arg ) {
554                // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor
555                assertf( objDecl, "genCtorDtor passed null objDecl" );
556                std::list< Statement * > stmts;
[b8524ca]557                InitExpander_old srcParam( maybeClone( arg ) );
[092528b]558                SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), fname, back_inserter( stmts ), objDecl );
559                assert( stmts.size() <= 1 );
[e3e16bc]560                return stmts.size() == 1 ? strict_dynamic_cast< ImplicitCtorDtorStmt * >( stmts.front() ) : nullptr;
[490fb92e]561
562        }
563
564        ast::ptr<ast::Stmt> genCtorDtor (const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg) {
565                assertf(objDecl, "genCtorDtor passed null objDecl");
566                InitExpander_new srcParam(arg);
567                return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl);
[092528b]568        }
569
[f0121d7]570        ConstructorInit * genCtorInit( ObjectDecl * objDecl ) {
571                // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor
572                // for each constructable object
573                std::list< Statement * > ctor;
574                std::list< Statement * > dtor;
575
[b8524ca]576                InitExpander_old srcParam( objDecl->get_init() );
577                InitExpander_old nullParam( (Initializer *)NULL );
[f0121d7]578                SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl );
579                SymTab::genImplicitCall( nullParam, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false );
580
581                // Currently genImplicitCall produces a single Statement - a CompoundStmt
582                // which  wraps everything that needs to happen. As such, it's technically
583                // possible to use a Statement ** in the above calls, but this is inherently
584                // unsafe, so instead we take the slightly less efficient route, but will be
585                // immediately informed if somehow the above assumption is broken. In this case,
586                // we could always wrap the list of statements at this point with a CompoundStmt,
587                // but it seems reasonable at the moment for this to be done by genImplicitCall
588                // itself. It is possible that genImplicitCall produces no statements (e.g. if
589                // an array type does not have a dimension). In this case, it's fine to ignore
590                // the object for the purposes of construction.
591                assert( ctor.size() == dtor.size() && ctor.size() <= 1 );
592                if ( ctor.size() == 1 ) {
593                        // need to remember init expression, in case no ctors exist
594                        // if ctor does exist, want to use ctor expression instead of init
595                        // push this decision to the resolver
596                        assert( dynamic_cast< ImplicitCtorDtorStmt * > ( ctor.front() ) && dynamic_cast< ImplicitCtorDtorStmt * > ( dtor.front() ) );
597                        return new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() );
598                }
599                return nullptr;
600        }
601
[d24d4e1]602        void CtorDtor::previsit( ObjectDecl * objDecl ) {
[bfd4974]603                managedTypes.handleDWT( objDecl );
[1ba88a0]604                // hands off if @=, extern, builtin, etc.
[a4dd728]605                // even if unmanaged, try to construct global or static if initializer is not constexpr, since this is not legal C
[bfd4974]606                if ( tryConstruct( objDecl ) && ( managedTypes.isManaged( objDecl ) || ((! inFunction || objDecl->get_storageClasses().is_static ) && ! isConstExpr( objDecl->get_init() ) ) ) ) {
[1ba88a0]607                        // constructed objects cannot be designated
[a16764a6]608                        if ( isDesignated( objDecl->get_init() ) ) SemanticError( objDecl, "Cannot include designations in the initializer for a managed Object. If this is really what you want, then initialize with @=.\n" );
[dcd73d1]609                        // constructed objects should not have initializers nested too deeply
[a16764a6]610                        if ( ! checkInitDepth( objDecl ) ) SemanticError( objDecl, "Managed object's initializer is too deep " );
[1ba88a0]611
[f0121d7]612                        objDecl->set_init( genCtorInit( objDecl ) );
[974906e2]613                }
614        }
615
[d24d4e1]616        void CtorDtor::previsit( FunctionDecl *functionDecl ) {
[22bc276]617                visit_children = false;  // do not try and construct parameters or forall parameters
[d24d4e1]618                GuardValue( inFunction );
[1ba88a0]619                inFunction = true;
620
[bfd4974]621                managedTypes.handleDWT( functionDecl );
[1ba88a0]622
[d24d4e1]623                GuardScope( managedTypes );
[1ba88a0]624                // go through assertions and recursively add seen ctor/dtors
[8c49c0e]625                for ( auto & tyDecl : functionDecl->get_functionType()->get_forall() ) {
[1ba88a0]626                        for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) {
[bfd4974]627                                managedTypes.handleDWT( assertion );
[1ba88a0]628                        }
629                }
630
[22bc276]631                maybeAccept( functionDecl->get_statements(), *visitor );
[02c7d04]632        }
[1ba88a0]633
[d24d4e1]634        void CtorDtor::previsit( StructDecl *aggregateDecl ) {
635                visit_children = false; // do not try to construct and destruct aggregate members
636
[bfd4974]637                managedTypes.handleStruct( aggregateDecl );
[1ba88a0]638        }
639
[22bc276]640        void CtorDtor::previsit( CompoundStmt * ) {
[d24d4e1]641                GuardScope( managedTypes );
[1ba88a0]642        }
[234b1cb]643
[b8524ca]644ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) {
[c19edd1]645        // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor for each
[b8524ca]646        // constructable object
647        InitExpander_new srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr };
[16ba4a6]648        ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl);
[c19edd1]649
650        ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall(
[16ba4a6]651                srcParam, dstParam, loc, "?{}", objDecl );
[c19edd1]652        ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall(
653                nullParam, dstParam, loc, "^?{}", objDecl,
[b8524ca]654                SymTab::LoopBackward );
[c19edd1]655
[b8524ca]656        // check that either both ctor and dtor are present, or neither
657        assert( (bool)ctor == (bool)dtor );
658
659        if ( ctor ) {
[c19edd1]660                // need to remember init expression, in case no ctors exist. If ctor does exist, want to
[b8524ca]661                // use ctor expression instead of init.
[c19edd1]662                ctor.strict_as< ast::ImplicitCtorDtorStmt >();
[b8524ca]663                dtor.strict_as< ast::ImplicitCtorDtorStmt >();
664
665                return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init };
666        }
667
[234b1cb]668        return nullptr;
669}
670
[42e2ad7]671} // namespace InitTweak
672
[51587aa]673// Local Variables: //
674// tab-width: 4 //
675// mode: c++ //
676// compile-command: "make install" //
677// End: //
Note: See TracBrowser for help on using the repository browser.