source: src/InitTweak/GenInit.cc @ cdacb73

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

factor out resolver calls in pre-resolution stage

  • Property mode set to 100644
File size: 20.7 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 --
8//
9// Author           : Rob Schluntz
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Dec 13 23:15:10 2019
13// Update Count     : 184
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/Node.hpp"
27#include "AST/Stmt.hpp"
28#include "CompilationState.h"
29#include "CodeGen/OperatorTable.h"
30#include "Common/PassVisitor.h"        // for PassVisitor, WithGuards, WithShort...
31#include "Common/SemanticError.h"      // for SemanticError
32#include "Common/UniqueName.h"         // for UniqueName
33#include "Common/utility.h"            // for ValueGuard, maybeClone
34#include "GenPoly/GenPoly.h"           // for getFunctionType, isPolyType
35#include "GenPoly/ScopedSet.h"         // for ScopedSet, ScopedSet<>::const_iter...
36#include "InitTweak.h"                 // for isConstExpr, InitExpander, checkIn...
37#include "ResolvExpr/Resolver.h"
38#include "SymTab/Autogen.h"            // for genImplicitCall
39#include "SymTab/Mangler.h"            // for Mangler
40#include "SynTree/LinkageSpec.h"       // for isOverridable, C
41#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
42#include "SynTree/Expression.h"        // for VariableExpr, UntypedExpr, Address...
43#include "SynTree/Initializer.h"       // for ConstructorInit, SingleInit, Initi...
44#include "SynTree/Label.h"             // for Label
45#include "SynTree/Mutator.h"           // for mutateAll
46#include "SynTree/Statement.h"         // for CompoundStmt, ImplicitCtorDtorStmt
47#include "SynTree/Type.h"              // for Type, ArrayType, Type::Qualifiers
48#include "SynTree/Visitor.h"           // for acceptAll, maybeAccept
49#include "Tuples/Tuples.h"             // for maybeImpure
50#include "Validate/FindSpecialDecls.h" // for SizeType
51
52namespace InitTweak {
53        namespace {
54                const std::list<Label> noLabels;
55                const std::list<Expression *> noDesignators;
56        }
57
58        struct ReturnFixer : public WithStmtsToAdd, public WithGuards {
59                /// consistently allocates a temporary variable for the return value
60                /// of a function so that anything which the resolver decides can be constructed
61                /// into the return type of a function can be returned.
62                static void makeReturnTemp( std::list< Declaration * > &translationUnit );
63
64                void premutate( FunctionDecl *functionDecl );
65                void premutate( ReturnStmt * returnStmt );
66
67          protected:
68                FunctionType * ftype = nullptr;
69                std::string funcName;
70        };
71
72        struct CtorDtor : public WithGuards, public WithShortCircuiting, public WithVisitorRef<CtorDtor>  {
73                /// create constructor and destructor statements for object declarations.
74                /// the actual call statements will be added in after the resolver has run
75                /// so that the initializer expression is only removed if a constructor is found
76                /// and the same destructor call is inserted in all of the appropriate locations.
77                static void generateCtorDtor( std::list< Declaration * > &translationUnit );
78
79                void previsit( ObjectDecl * );
80                void previsit( FunctionDecl *functionDecl );
81
82                // should not traverse into any of these declarations to find objects
83                // that need to be constructed or destructed
84                void previsit( StructDecl *aggregateDecl );
85                void previsit( AggregateDecl * ) { visit_children = false; }
86                void previsit( NamedTypeDecl * ) { visit_children = false; }
87                void previsit( FunctionType * ) { visit_children = false; }
88
89                void previsit( CompoundStmt * compoundStmt );
90
91          private:
92                // set of mangled type names for which a constructor or destructor exists in the current scope.
93                // these types require a ConstructorInit node to be generated, anything else is a POD type and thus
94                // should not have a ConstructorInit generated.
95
96                ManagedTypes managedTypes;
97                bool inFunction = false;
98        };
99
100        struct HoistArrayDimension final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards, public WithIndexer {
101                /// hoist dimension from array types in object declaration so that it uses a single
102                /// const variable of type size_t, so that side effecting array dimensions are only
103                /// computed once.
104                static void hoistArrayDimension( std::list< Declaration * > & translationUnit );
105
106                void premutate( ObjectDecl * objectDecl );
107                DeclarationWithType * postmutate( ObjectDecl * objectDecl );
108                void premutate( FunctionDecl *functionDecl );
109                // should not traverse into any of these declarations to find objects
110                // that need to be constructed or destructed
111                void premutate( AggregateDecl * ) { visit_children = false; }
112                void premutate( NamedTypeDecl * ) { visit_children = false; }
113                void premutate( FunctionType * ) { visit_children = false; }
114
115                // need this so that enumerators are added to the indexer, due to premutate(AggregateDecl *)
116                void premutate( EnumDecl * ) {}
117
118                void hoist( Type * type );
119
120                Type::StorageClasses storageClasses;
121                bool inFunction = false;
122        };
123
124        void genInit( std::list< Declaration * > & translationUnit ) {
125                HoistArrayDimension::hoistArrayDimension( translationUnit );
126                fixReturnStatements( translationUnit );
127
128                if (!useNewAST) {
129                        CtorDtor::generateCtorDtor( translationUnit );
130                }
131        }
132
133        void fixReturnStatements( std::list< Declaration * > & translationUnit ) {
134                PassVisitor<ReturnFixer> fixer;
135                mutateAll( translationUnit, fixer );
136        }
137
138        void ReturnFixer::premutate( ReturnStmt *returnStmt ) {
139                std::list< DeclarationWithType * > & returnVals = ftype->get_returnVals();
140                assert( returnVals.size() == 0 || returnVals.size() == 1 );
141                // hands off if the function returns a reference - we don't want to allocate a temporary if a variable's address
142                // is being returned
143                if ( returnStmt->expr && returnVals.size() == 1 && isConstructable( returnVals.front()->get_type() ) ) {
144                        // explicitly construct the return value using the return expression and the retVal object
145                        assertf( returnVals.front()->name != "", "Function %s has unnamed return value\n", funcName.c_str() );
146
147                        ObjectDecl * retVal = strict_dynamic_cast< ObjectDecl * >( returnVals.front() );
148                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( returnStmt->expr ) ) {
149                                // return statement has already been mutated - don't need to do it again
150                                if ( varExpr->var == retVal ) return;
151                        }
152                        Statement * stmt = genCtorDtor( "?{}", retVal, returnStmt->expr );
153                        assertf( stmt, "ReturnFixer: genCtorDtor returned nullptr: %s / %s", toString( retVal ).c_str(), toString( returnStmt->expr ).c_str() );
154                        stmtsToAddBefore.push_back( stmt );
155
156                        // return the retVal object
157                        returnStmt->expr = new VariableExpr( returnVals.front() );
158                } // if
159        }
160
161        void ReturnFixer::premutate( FunctionDecl *functionDecl ) {
162                GuardValue( ftype );
163                GuardValue( funcName );
164
165                ftype = functionDecl->type;
166                funcName = functionDecl->name;
167        }
168
169        // precompute array dimension expression, because constructor generation may duplicate it,
170        // which would be incorrect if it is a side-effecting computation.
171        void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
172                PassVisitor<HoistArrayDimension> hoister;
173                mutateAll( translationUnit, hoister );
174        }
175
176        void HoistArrayDimension::premutate( ObjectDecl * objectDecl ) {
177                GuardValue( storageClasses );
178                storageClasses = objectDecl->get_storageClasses();
179        }
180
181        DeclarationWithType * HoistArrayDimension::postmutate( ObjectDecl * objectDecl ) {
182                hoist( objectDecl->get_type() );
183                return objectDecl;
184        }
185
186        void HoistArrayDimension::hoist( Type * type ) {
187                // if in function, generate const size_t var
188                static UniqueName dimensionName( "_array_dim" );
189
190                // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension.
191                if ( ! inFunction ) return;
192                if ( storageClasses.is_static ) return;
193
194                if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
195                        if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?
196
197                        // need to resolve array dimensions in order to accurately determine if constexpr
198                        if (!useNewAST) {
199                                ResolvExpr::findSingleExpression( arrayType->dimension, Validate::SizeType->clone(), indexer );
200                                // array is variable-length when the dimension is not constexpr
201                                arrayType->isVarLen = ! isConstExpr( arrayType->dimension );
202                        }
203                        // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects.
204                        // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve     
205                        // only skip in the most trivial case, which does not require resolve
206                        if (dynamic_cast<ConstantExpr *>(arrayType->dimension)) return;
207                        // if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return;
208
209                        ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
210                        arrayDimension->get_type()->set_const( true );
211
212                        arrayType->set_dimension( new VariableExpr( arrayDimension ) );
213                        declsToAddBefore.push_back( arrayDimension );
214
215                        hoist( arrayType->get_base() );
216                        return;
217                }
218        }
219
220        void HoistArrayDimension::premutate( FunctionDecl * ) {
221                GuardValue( inFunction );
222                inFunction = true;
223        }
224
225        void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
226                PassVisitor<CtorDtor> ctordtor;
227                acceptAll( translationUnit, ctordtor );
228        }
229
230        bool ManagedTypes::isManaged( Type * type ) const {
231                // references are never constructed
232                if ( dynamic_cast< ReferenceType * >( type ) ) return false;
233                // need to clear and reset qualifiers when determining if a type is managed
234                ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() );
235                type->get_qualifiers() = Type::Qualifiers();
236                if ( TupleType * tupleType = dynamic_cast< TupleType * > ( type ) ) {
237                        // tuple is also managed if any of its components are managed
238                        if ( std::any_of( tupleType->types.begin(), tupleType->types.end(), [&](Type * type) { return isManaged( type ); }) ) {
239                                return true;
240                        }
241                }
242                // 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)
243                return managedTypes.find( SymTab::Mangler::mangleConcrete( type ) ) != managedTypes.end() || GenPoly::isPolyType( type );
244        }
245
246        bool ManagedTypes::isManaged( ObjectDecl * objDecl ) const {
247                Type * type = objDecl->get_type();
248                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
249                        // must always construct VLAs with an initializer, since this is an error in C
250                        if ( at->isVarLen && objDecl->init ) return true;
251                        type = at->get_base();
252                }
253                return isManaged( type );
254        }
255
256        // why is this not just on FunctionDecl?
257        void ManagedTypes::handleDWT( DeclarationWithType * dwt ) {
258                // if this function is a user-defined constructor or destructor, mark down the type as "managed"
259                if ( ! LinkageSpec::isOverridable( dwt->get_linkage() ) && CodeGen::isCtorDtor( dwt->get_name() ) ) {
260                        std::list< DeclarationWithType * > & params = GenPoly::getFunctionType( dwt->get_type() )->get_parameters();
261                        assert( ! params.empty() );
262                        Type * type = InitTweak::getPointerBase( params.front()->get_type() );
263                        assert( type );
264                        managedTypes.insert( SymTab::Mangler::mangleConcrete( type ) );
265                }
266        }
267
268        void ManagedTypes::handleStruct( StructDecl * aggregateDecl ) {
269                // don't construct members, but need to take note if there is a managed member,
270                // because that means that this type is also managed
271                for ( Declaration * member : aggregateDecl->get_members() ) {
272                        if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
273                                if ( isManaged( field ) ) {
274                                        // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
275                                        // polymorphic constructors make generic types managed types
276                                        StructInstType inst( Type::Qualifiers(), aggregateDecl );
277                                        managedTypes.insert( SymTab::Mangler::mangleConcrete( &inst ) );
278                                        break;
279                                }
280                        }
281                }
282        }
283
284        void ManagedTypes::beginScope() { managedTypes.beginScope(); }
285        void ManagedTypes::endScope() { managedTypes.endScope(); }
286
287        bool ManagedTypes_new::isManaged( const ast::Type * type ) const {
288                // references are never constructed
289                if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false;
290                if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) {
291                        // tuple is also managed if any of its components are managed
292                        for (auto & component : tupleType->types) {
293                                if (isManaged(component)) return true;
294                        }
295                }
296                // need to clear and reset qualifiers when determining if a type is managed
297                // ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() );
298                auto tmp = shallowCopy(type);
299                tmp->qualifiers = {};
300                // delete tmp at return
301                ast::ptr<ast::Type> guard = tmp;
302                // 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)
303                return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp );
304        }
305
306        bool ManagedTypes_new::isManaged( const ast::ObjectDecl * objDecl ) const {
307                const ast::Type * type = objDecl->type;
308                while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) {
309                        // must always construct VLAs with an initializer, since this is an error in C
310                        if ( at->isVarLen && objDecl->init ) return true;
311                        type = at->base;
312                }
313                return isManaged( type );
314        }
315
316        void ManagedTypes_new::handleDWT( const ast::DeclWithType * dwt ) {
317                // if this function is a user-defined constructor or destructor, mark down the type as "managed"
318                if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) {
319                        auto & params = GenPoly::getFunctionType( dwt->get_type())->params;
320                        assert( ! params.empty() );
321                        // Type * type = InitTweak::getPointerBase( params.front() );
322                        // assert( type );
323                        managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
324                }
325        }
326
327        void ManagedTypes_new::handleStruct( const ast::StructDecl * aggregateDecl ) {
328                // don't construct members, but need to take note if there is a managed member,
329                // because that means that this type is also managed
330                for ( auto & member : aggregateDecl->members ) {
331                        if ( auto field = member.as<ast::ObjectDecl>() ) {
332                                if ( isManaged( field ) ) {
333                                        // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
334                                        // polymorphic constructors make generic types managed types
335                                        ast::StructInstType inst( aggregateDecl );
336                                        managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
337                                        break;
338                                }
339                        }
340                }
341        }
342
343        void ManagedTypes_new::beginScope() { managedTypes.beginScope(); }
344        void ManagedTypes_new::endScope() { managedTypes.endScope(); }
345
346        ImplicitCtorDtorStmt * genCtorDtor( const std::string & fname, ObjectDecl * objDecl, Expression * arg ) {
347                // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor
348                assertf( objDecl, "genCtorDtor passed null objDecl" );
349                std::list< Statement * > stmts;
350                InitExpander_old srcParam( maybeClone( arg ) );
351                SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), fname, back_inserter( stmts ), objDecl );
352                assert( stmts.size() <= 1 );
353                return stmts.size() == 1 ? strict_dynamic_cast< ImplicitCtorDtorStmt * >( stmts.front() ) : nullptr;
354
355        }
356
357        ast::ptr<ast::Stmt> genCtorDtor (const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg) {
358                assertf(objDecl, "genCtorDtor passed null objDecl");
359                InitExpander_new srcParam(arg);
360                return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl);
361        }
362
363        ConstructorInit * genCtorInit( ObjectDecl * objDecl ) {
364                // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor
365                // for each constructable object
366                std::list< Statement * > ctor;
367                std::list< Statement * > dtor;
368
369                InitExpander_old srcParam( objDecl->get_init() );
370                InitExpander_old nullParam( (Initializer *)NULL );
371                SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl );
372                SymTab::genImplicitCall( nullParam, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false );
373
374                // Currently genImplicitCall produces a single Statement - a CompoundStmt
375                // which  wraps everything that needs to happen. As such, it's technically
376                // possible to use a Statement ** in the above calls, but this is inherently
377                // unsafe, so instead we take the slightly less efficient route, but will be
378                // immediately informed if somehow the above assumption is broken. In this case,
379                // we could always wrap the list of statements at this point with a CompoundStmt,
380                // but it seems reasonable at the moment for this to be done by genImplicitCall
381                // itself. It is possible that genImplicitCall produces no statements (e.g. if
382                // an array type does not have a dimension). In this case, it's fine to ignore
383                // the object for the purposes of construction.
384                assert( ctor.size() == dtor.size() && ctor.size() <= 1 );
385                if ( ctor.size() == 1 ) {
386                        // need to remember init expression, in case no ctors exist
387                        // if ctor does exist, want to use ctor expression instead of init
388                        // push this decision to the resolver
389                        assert( dynamic_cast< ImplicitCtorDtorStmt * > ( ctor.front() ) && dynamic_cast< ImplicitCtorDtorStmt * > ( dtor.front() ) );
390                        return new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() );
391                }
392                return nullptr;
393        }
394
395        void CtorDtor::previsit( ObjectDecl * objDecl ) {
396                managedTypes.handleDWT( objDecl );
397                // hands off if @=, extern, builtin, etc.
398                // even if unmanaged, try to construct global or static if initializer is not constexpr, since this is not legal C
399                if ( tryConstruct( objDecl ) && ( managedTypes.isManaged( objDecl ) || ((! inFunction || objDecl->get_storageClasses().is_static ) && ! isConstExpr( objDecl->get_init() ) ) ) ) {
400                        // constructed objects cannot be designated
401                        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" );
402                        // constructed objects should not have initializers nested too deeply
403                        if ( ! checkInitDepth( objDecl ) ) SemanticError( objDecl, "Managed object's initializer is too deep " );
404
405                        objDecl->set_init( genCtorInit( objDecl ) );
406                }
407        }
408
409        void CtorDtor::previsit( FunctionDecl *functionDecl ) {
410                visit_children = false;  // do not try and construct parameters or forall parameters
411                GuardValue( inFunction );
412                inFunction = true;
413
414                managedTypes.handleDWT( functionDecl );
415
416                GuardScope( managedTypes );
417                // go through assertions and recursively add seen ctor/dtors
418                for ( auto & tyDecl : functionDecl->get_functionType()->get_forall() ) {
419                        for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) {
420                                managedTypes.handleDWT( assertion );
421                        }
422                }
423
424                maybeAccept( functionDecl->get_statements(), *visitor );
425        }
426
427        void CtorDtor::previsit( StructDecl *aggregateDecl ) {
428                visit_children = false; // do not try to construct and destruct aggregate members
429
430                managedTypes.handleStruct( aggregateDecl );
431        }
432
433        void CtorDtor::previsit( CompoundStmt * ) {
434                GuardScope( managedTypes );
435        }
436
437ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) {
438        // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor for each
439        // constructable object
440        InitExpander_new srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr };
441        ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl);
442       
443        ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall( 
444                srcParam, dstParam, loc, "?{}", objDecl );
445        ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall( 
446                nullParam, dstParam, loc, "^?{}", objDecl, 
447                SymTab::LoopBackward );
448       
449        // check that either both ctor and dtor are present, or neither
450        assert( (bool)ctor == (bool)dtor );
451
452        if ( ctor ) {
453                // need to remember init expression, in case no ctors exist. If ctor does exist, want to
454                // use ctor expression instead of init.
455                ctor.strict_as< ast::ImplicitCtorDtorStmt >(); 
456                dtor.strict_as< ast::ImplicitCtorDtorStmt >();
457
458                return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init };
459        }
460
461        return nullptr;
462}
463
464} // namespace InitTweak
465
466// Local Variables: //
467// tab-width: 4 //
468// mode: c++ //
469// compile-command: "make install" //
470// End: //
Note: See TracBrowser for help on using the repository browser.