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
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// GenInit.cc -- Generate initializers, and other stuff.
8//
9// Author           : Rob Schluntz
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Mon Oct 25 13:53:00 2021
13// Update Count     : 186
14//
15#include "GenInit.h"
16
17#include <stddef.h>                    // for NULL
18#include <algorithm>                   // for any_of
19#include <cassert>                     // for assert, strict_dynamic_cast, assertf
20#include <deque>
21#include <iterator>                    // for back_inserter, inserter, back_inse...
22#include <list>                        // for _List_iterator, list
23
24#include "AST/Decl.hpp"
25#include "AST/Init.hpp"
26#include "AST/Pass.hpp"
27#include "AST/Node.hpp"
28#include "AST/Stmt.hpp"
29#include "CompilationState.h"
30#include "CodeGen/OperatorTable.h"
31#include "Common/PassVisitor.h"        // for PassVisitor, WithGuards, WithShort...
32#include "Common/SemanticError.h"      // for SemanticError
33#include "Common/ToString.hpp"         // for toCString
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...
39#include "ResolvExpr/Resolver.h"
40#include "SymTab/Autogen.h"            // for genImplicitCall
41#include "SymTab/Mangler.h"            // for Mangler
42#include "SynTree/LinkageSpec.h"       // for isOverridable, C
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
53
54namespace InitTweak {
55        namespace {
56                const std::list<Label> noLabels;
57                const std::list<Expression *> noDesignators;
58        }
59
60        struct ReturnFixer : public WithStmtsToAdd, public WithGuards {
61                /// consistently allocates a temporary variable for the return value
62                /// of a function so that anything which the resolver decides can be constructed
63                /// into the return type of a function can be returned.
64                static void makeReturnTemp( std::list< Declaration * > &translationUnit );
65
66                void premutate( FunctionDecl *functionDecl );
67                void premutate( ReturnStmt * returnStmt );
68
69          protected:
70                FunctionType * ftype = nullptr;
71                std::string funcName;
72        };
73
74        struct CtorDtor : public WithGuards, public WithShortCircuiting, public WithVisitorRef<CtorDtor>  {
75                /// create constructor and destructor statements for object declarations.
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.
79                static void generateCtorDtor( std::list< Declaration * > &translationUnit );
80
81                void previsit( ObjectDecl * );
82                void previsit( FunctionDecl *functionDecl );
83
84                // should not traverse into any of these declarations to find objects
85                // that need to be constructed or destructed
86                void previsit( StructDecl *aggregateDecl );
87                void previsit( AggregateDecl * ) { visit_children = false; }
88                void previsit( NamedTypeDecl * ) { visit_children = false; }
89                void previsit( FunctionType * ) { visit_children = false; }
90
91                void previsit( CompoundStmt * compoundStmt );
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
98                ManagedTypes managedTypes;
99                bool inFunction = false;
100        };
101
102        struct HoistArrayDimension final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards, public WithIndexer {
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
108                void premutate( ObjectDecl * objectDecl );
109                DeclarationWithType * postmutate( ObjectDecl * objectDecl );
110                void premutate( FunctionDecl *functionDecl );
111                // should not traverse into any of these declarations to find objects
112                // that need to be constructed or destructed
113                void premutate( AggregateDecl * ) { visit_children = false; }
114                void premutate( NamedTypeDecl * ) { visit_children = false; }
115                void premutate( FunctionType * ) { visit_children = false; }
116
117                // need this so that enumerators are added to the indexer, due to premutate(AggregateDecl *)
118                void premutate( EnumDecl * ) {}
119
120                void hoist( Type * type );
121
122                Type::StorageClasses storageClasses;
123                bool inFunction = false;
124        };
125
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
147        void genInit( std::list< Declaration * > & translationUnit ) {
148                if (!useNewAST) {
149                        HoistArrayDimension::hoistArrayDimension( translationUnit );
150                }
151                else {
152                        HoistArrayDimension_NoResolve::hoistArrayDimension( translationUnit );
153                }
154                fixReturnStatements( translationUnit );
155
156                if (!useNewAST) {
157                        CtorDtor::generateCtorDtor( translationUnit );
158                }
159        }
160
161        void fixReturnStatements( std::list< Declaration * > & translationUnit ) {
162                PassVisitor<ReturnFixer> fixer;
163                mutateAll( translationUnit, fixer );
164        }
165
166        void ReturnFixer::premutate( ReturnStmt *returnStmt ) {
167                std::list< DeclarationWithType * > & returnVals = ftype->get_returnVals();
168                assert( returnVals.size() == 0 || returnVals.size() == 1 );
169                // hands off if the function returns a reference - we don't want to allocate a temporary if a variable's address
170                // is being returned
171                if ( returnStmt->expr && returnVals.size() == 1 && isConstructable( returnVals.front()->get_type() ) ) {
172                        // explicitly construct the return value using the return expression and the retVal object
173                        assertf( returnVals.front()->name != "", "Function %s has unnamed return value\n", funcName.c_str() );
174
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                        }
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 );
183
184                        // return the retVal object
185                        returnStmt->expr = new VariableExpr( returnVals.front() );
186                } // if
187        }
188
189        void ReturnFixer::premutate( FunctionDecl *functionDecl ) {
190                GuardValue( ftype );
191                GuardValue( funcName );
192
193                ftype = functionDecl->type;
194                funcName = functionDecl->name;
195        }
196
197        // precompute array dimension expression, because constructor generation may duplicate it,
198        // which would be incorrect if it is a side-effecting computation.
199        void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
200                PassVisitor<HoistArrayDimension> hoister;
201                mutateAll( translationUnit, hoister );
202        }
203
204        void HoistArrayDimension::premutate( ObjectDecl * objectDecl ) {
205                GuardValue( storageClasses );
206                storageClasses = objectDecl->get_storageClasses();
207        }
208
209        DeclarationWithType * HoistArrayDimension::postmutate( ObjectDecl * objectDecl ) {
210                hoist( objectDecl->get_type() );
211                return objectDecl;
212        }
213
214        void HoistArrayDimension::hoist( Type * type ) {
215                // if in function, generate const size_t var
216                static UniqueName dimensionName( "_array_dim" );
217
218                // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension.
219                if ( ! inFunction ) return;
220                if ( storageClasses.is_static ) return;
221
222                if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
223                        if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?
224
225                        // need to resolve array dimensions in order to accurately determine if constexpr
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 );
229                        // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects.
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;
233
234                        ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
235                        arrayDimension->get_type()->set_const( true );
236
237                        arrayType->set_dimension( new VariableExpr( arrayDimension ) );
238                        declsToAddBefore.push_back( arrayDimension );
239
240                        hoist( arrayType->get_base() );
241                        return;
242                }
243        }
244
245        void HoistArrayDimension::premutate( FunctionDecl * ) {
246                GuardValue( inFunction );
247                inFunction = true;
248        }
249
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
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,
303                        public ast::WithGuards, public ast::WithConstTranslationUnit,
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 ) {
319                GuardValue( storageClasses ) = decl->storage;
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
345                        ast::ptr<ast::Type> dimType = transUnit().global.sizeType;
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 :
371                        public ast::WithStmtsToAdd<>, ast::WithGuards, ast::WithShortCircuiting {
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 ) {
379                if (decl->linkage == ast::Linkage::Intrinsic) visit_children = false;
380                GuardValue( funcDecl ) = decl;
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,
406                                        "ReturnFixer: genCtorDtor returned nullptr: %s / %s",
407                                        toString( retVal ).c_str(),
408                                        toString( stmt->expr ).c_str() );
409                                stmtsToAddBefore.push_back( ctorStmt );
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
428        void fixReturnStatements( ast::TranslationUnit & transUnit ) {
429                ast::Pass<ReturnFixer_New>::run( transUnit );
430        }
431
432        void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
433                PassVisitor<CtorDtor> ctordtor;
434                acceptAll( translationUnit, ctordtor );
435        }
436
437        bool ManagedTypes::isManaged( Type * type ) const {
438                // references are never constructed
439                if ( dynamic_cast< ReferenceType * >( type ) ) return false;
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();
443                if ( TupleType * tupleType = dynamic_cast< TupleType * > ( type ) ) {
444                        // tuple is also managed if any of its components are managed
445                        if ( std::any_of( tupleType->types.begin(), tupleType->types.end(), [&](Type * type) { return isManaged( type ); }) ) {
446                                return true;
447                        }
448                }
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)
450                return managedTypes.find( SymTab::Mangler::mangleConcrete( type ) ) != managedTypes.end() || GenPoly::isPolyType( type );
451        }
452
453        bool ManagedTypes::isManaged( ObjectDecl * objDecl ) const {
454                Type * type = objDecl->get_type();
455                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
456                        // must always construct VLAs with an initializer, since this is an error in C
457                        if ( at->isVarLen && objDecl->init ) return true;
458                        type = at->get_base();
459                }
460                return isManaged( type );
461        }
462
463        // why is this not just on FunctionDecl?
464        void ManagedTypes::handleDWT( DeclarationWithType * dwt ) {
465                // if this function is a user-defined constructor or destructor, mark down the type as "managed"
466                if ( ! LinkageSpec::isOverridable( dwt->get_linkage() ) && CodeGen::isCtorDtor( dwt->get_name() ) ) {
467                        std::list< DeclarationWithType * > & params = GenPoly::getFunctionType( dwt->get_type() )->get_parameters();
468                        assert( ! params.empty() );
469                        Type * type = InitTweak::getPointerBase( params.front()->get_type() );
470                        assert( type );
471                        managedTypes.insert( SymTab::Mangler::mangleConcrete( type ) );
472                }
473        }
474
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 ) ) {
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
483                                        StructInstType inst( Type::Qualifiers(), aggregateDecl );
484                                        managedTypes.insert( SymTab::Mangler::mangleConcrete( &inst ) );
485                                        break;
486                                }
487                        }
488                }
489        }
490
491        void ManagedTypes::beginScope() { managedTypes.beginScope(); }
492        void ManagedTypes::endScope() { managedTypes.endScope(); }
493
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
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;
557                InitExpander_old srcParam( maybeClone( arg ) );
558                SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), fname, back_inserter( stmts ), objDecl );
559                assert( stmts.size() <= 1 );
560                return stmts.size() == 1 ? strict_dynamic_cast< ImplicitCtorDtorStmt * >( stmts.front() ) : nullptr;
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);
568        }
569
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
576                InitExpander_old srcParam( objDecl->get_init() );
577                InitExpander_old nullParam( (Initializer *)NULL );
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
602        void CtorDtor::previsit( ObjectDecl * objDecl ) {
603                managedTypes.handleDWT( objDecl );
604                // hands off if @=, extern, builtin, etc.
605                // even if unmanaged, try to construct global or static if initializer is not constexpr, since this is not legal C
606                if ( tryConstruct( objDecl ) && ( managedTypes.isManaged( objDecl ) || ((! inFunction || objDecl->get_storageClasses().is_static ) && ! isConstExpr( objDecl->get_init() ) ) ) ) {
607                        // constructed objects cannot be designated
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" );
609                        // constructed objects should not have initializers nested too deeply
610                        if ( ! checkInitDepth( objDecl ) ) SemanticError( objDecl, "Managed object's initializer is too deep " );
611
612                        objDecl->set_init( genCtorInit( objDecl ) );
613                }
614        }
615
616        void CtorDtor::previsit( FunctionDecl *functionDecl ) {
617                visit_children = false;  // do not try and construct parameters or forall parameters
618                GuardValue( inFunction );
619                inFunction = true;
620
621                managedTypes.handleDWT( functionDecl );
622
623                GuardScope( managedTypes );
624                // go through assertions and recursively add seen ctor/dtors
625                for ( auto & tyDecl : functionDecl->get_functionType()->get_forall() ) {
626                        for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) {
627                                managedTypes.handleDWT( assertion );
628                        }
629                }
630
631                maybeAccept( functionDecl->get_statements(), *visitor );
632        }
633
634        void CtorDtor::previsit( StructDecl *aggregateDecl ) {
635                visit_children = false; // do not try to construct and destruct aggregate members
636
637                managedTypes.handleStruct( aggregateDecl );
638        }
639
640        void CtorDtor::previsit( CompoundStmt * ) {
641                GuardScope( managedTypes );
642        }
643
644ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) {
645        // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor for each
646        // constructable object
647        InitExpander_new srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr };
648        ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl);
649
650        ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall(
651                srcParam, dstParam, loc, "?{}", objDecl );
652        ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall(
653                nullParam, dstParam, loc, "^?{}", objDecl,
654                SymTab::LoopBackward );
655
656        // check that either both ctor and dtor are present, or neither
657        assert( (bool)ctor == (bool)dtor );
658
659        if ( ctor ) {
660                // need to remember init expression, in case no ctors exist. If ctor does exist, want to
661                // use ctor expression instead of init.
662                ctor.strict_as< ast::ImplicitCtorDtorStmt >();
663                dtor.strict_as< ast::ImplicitCtorDtorStmt >();
664
665                return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init };
666        }
667
668        return nullptr;
669}
670
671} // namespace InitTweak
672
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.