source: src/InitTweak/GenInit.cpp @ c92bdcc

Last change on this file since c92bdcc was c92bdcc, checked in by Andrew Beach <ajbeach@…>, 8 weeks ago

Updated the rest of the names in src/ (except for the generated files).

  • Property mode set to 100644
File size: 14.2 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.cpp -- 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.hpp"
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.hpp"
30#include "CodeGen/OperatorTable.hpp"
31#include "Common/SemanticError.hpp"    // for SemanticError
32#include "Common/ToString.hpp"         // for toCString
33#include "Common/UniqueName.hpp"       // for UniqueName
34#include "Common/Utility.hpp"          // for ValueGuard, maybeClone
35#include "GenPoly/GenPoly.hpp"         // for getFunctionType, isPolyType
36#include "GenPoly/ScopedSet.hpp"       // for ScopedSet, ScopedSet<>::const_iter...
37#include "InitTweak.hpp"               // for isConstExpr, InitExpander, checkIn...
38#include "ResolvExpr/Resolver.hpp"
39#include "SymTab/GenImplicitCall.hpp"  // for genImplicitCall
40#include "SymTab/Mangler.hpp"          // for Mangler
41#include "Tuples/Tuples.hpp"           // for maybeImpure
42
43namespace InitTweak {
44
45namespace {
46
47        // Outer pass finds declarations, for their type could wrap a type that needs hoisting
48        struct HoistArrayDimension_NoResolve final :
49                        public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting,
50                        public ast::WithGuards, public ast::WithConstTranslationUnit,
51                        public ast::WithVisitorRef<HoistArrayDimension_NoResolve>,
52                        public ast::WithSymbolTableX<ast::SymbolTable::ErrorDetection::IgnoreErrors> {
53
54                // Inner pass looks within a type, for a part that depends on an expression
55                struct HoistDimsFromTypes final :
56                                public ast::WithShortCircuiting, public ast::WithGuards {
57
58                        HoistArrayDimension_NoResolve * outer;
59                        HoistDimsFromTypes( HoistArrayDimension_NoResolve * outer ) : outer(outer) {}
60
61                        // Only intended for visiting through types.
62                        // Tolerate, and short-circuit at, the dimension expression of an array type.
63                        //    (We'll operate on the dimension expression of an array type directly
64                        //    from the parent type, not by visiting through it)
65                        // Look inside type exprs.
66                        void previsit( const ast::Node * ) {
67                                assert( false && "unsupported node type" );
68                        };
69                        const ast::Expr * allowedExpr = nullptr;
70                        void previsit( const ast::Type * ) {
71                                GuardValue( allowedExpr ) = nullptr;
72                        }
73                        void previsit( const ast::ArrayType * t ) {
74                                GuardValue( allowedExpr ) = t->dimension.get();
75                        }
76                        void previsit( const ast::PointerType * t ) {
77                                GuardValue( allowedExpr ) = t->dimension.get();
78                        }
79                        void previsit( const ast::TypeofType * t ) {
80                                GuardValue( allowedExpr ) = t->expr.get();
81                        }
82                        void previsit( const ast::Expr * e ) {
83                                assert( e == allowedExpr &&
84                                    "only expecting to visit exprs that are dimension exprs or typeof(-) inner exprs" );
85
86                                // Skip the tolerated expressions
87                                visit_children = false;
88                        }
89                        void previsit( const ast::TypeExpr * ) {}
90
91                        const ast::Type * postvisit(
92                                        const ast::ArrayType * arrayType ) {
93                                static UniqueName dimensionName( "_array_dim" );
94
95                                if ( nullptr == arrayType->dimension ) {  // if no dimension is given, don't presume to invent one
96                                        return arrayType;
97                                }
98
99                                // find size_t; use it as the type for a dim expr
100                                ast::ptr<ast::Type> dimType = outer->transUnit().global.sizeType;
101                                assert( dimType );
102                                add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) );
103
104                                // Special-case handling: leave the user's dimension expression alone
105                                // - requires the user to have followed a careful convention
106                                // - may apply to extremely simple applications, but only as windfall
107                                // - users of advanced applications will be following the convention on purpose
108                                // - CFA maintainers must protect the criteria against leaving too much alone
109
110                                // Actual leave-alone cases following are conservative approximations of "cannot vary"
111
112                                // Leave alone: literals and enum constants
113                                if ( dynamic_cast< const ast::ConstantExpr * >( arrayType->dimension.get() ) ) {
114                                        return arrayType;
115                                }
116
117                                // Leave alone: direct use of an object declared to be const
118                                const ast::NameExpr * dimn = dynamic_cast< const ast::NameExpr * >( arrayType->dimension.get() );
119                                if ( dimn ) {
120                                        std::vector<ast::SymbolTable::IdData> dimnDefs = outer->symtab.lookupId( dimn->name );
121                                        if ( dimnDefs.size() == 1 ) {
122                                                const ast::DeclWithType * dimnDef = dimnDefs[0].id.get();
123                                                assert( dimnDef && "symbol table binds a name to nothing" );
124                                                const ast::ObjectDecl * dimOb = dynamic_cast< const ast::ObjectDecl * >( dimnDef );
125                                                if( dimOb ) {
126                                                        const ast::Type * dimTy = dimOb->type.get();
127                                                        assert( dimTy && "object declaration bearing no type" );
128                                                        // must not hoist some: size_t
129                                                        // must hoist all: pointers and references
130                                                        // the analysis is conservative; BasicType is a simple approximation
131                                                        if ( dynamic_cast< const ast::BasicType * >( dimTy ) ||
132                                                             dynamic_cast< const ast::SueInstType<ast::EnumDecl> * >( dimTy ) ) {
133                                                                if ( dimTy->is_const() ) {
134                                                                        // The dimension is certainly re-evaluable, giving the same answer each time.
135                                                                        // Our user might be hoping to write the array type in multiple places, having them unify.
136                                                                        // Leave the type alone.
137
138                                                                        // We believe the new criterion leaves less alone than the old criterion.
139                                                                        // Thus, the old criterion should have left the current case alone.
140                                                                        // Catch cases that weren't thought through.
141                                                                        assert( !Tuples::maybeImpure( arrayType->dimension ) );
142
143                                                                        return arrayType;
144                                                                }
145                                                        };
146                                                }
147                                        }
148                                }
149
150                                // Leave alone: any sizeof expression (answer cannot vary during current lexical scope)
151                                const ast::SizeofExpr * sz = dynamic_cast< const ast::SizeofExpr * >( arrayType->dimension.get() );
152                                if ( sz ) {
153                                        return arrayType;
154                                }
155
156                                // General-case handling: change the array-type's dim expr (hoist the user-given content out of the type)
157                                // - always safe
158                                // - user-unnoticeable in common applications (benign noise in -CFA output)
159                                // - may annoy a responsible user of advanced applications (but they can work around)
160                                // - protects against misusing advanced features
161                                //
162                                // The hoist, by example, is:
163                                // FROM USER:  float a[ rand() ];
164                                // TO GCC:     const size_t __len_of_a = rand(); float a[ __len_of_a ];
165
166                                ast::ObjectDecl * arrayDimension = new ast::ObjectDecl(
167                                        arrayType->dimension->location,
168                                        dimensionName.newName(),
169                                        dimType,
170                                        new ast::SingleInit(
171                                                arrayType->dimension->location,
172                                                arrayType->dimension
173                                        )
174                                );
175
176                                ast::ArrayType * mutType = ast::mutate( arrayType );
177                                mutType->dimension = new ast::VariableExpr(
178                                                arrayDimension->location, arrayDimension );
179                                outer->declsToAddBefore.push_back( arrayDimension );
180
181                                return mutType;
182                        }  // postvisit( const ast::ArrayType * )
183                }; // struct HoistDimsFromTypes
184
185                ast::Storage::Classes storageClasses;
186                void previsit(
187                                const ast::ObjectDecl * decl ) {
188                        GuardValue( storageClasses ) = decl->storage;
189                }
190
191                const ast::DeclWithType * postvisit(
192                                const ast::ObjectDecl * objectDecl ) {
193
194                        if ( !isInFunction() || storageClasses.is_static ) {
195                                return objectDecl;
196                        }
197
198                        const ast::Type * mid = objectDecl->type;
199
200                        ast::Pass<HoistDimsFromTypes> hoist{this};
201                        const ast::Type * result = mid->accept( hoist );
202
203                        return mutate_field( objectDecl, &ast::ObjectDecl::type, result );
204                }
205        };
206
207        struct ReturnFixer final :
208                        public ast::WithStmtsToAdd<>, ast::WithGuards, ast::WithShortCircuiting {
209                void previsit( const ast::FunctionDecl * decl );
210                const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt );
211        private:
212                const ast::FunctionDecl * funcDecl = nullptr;
213        };
214
215        void ReturnFixer::previsit( const ast::FunctionDecl * decl ) {
216                if (decl->linkage == ast::Linkage::Intrinsic) visit_children = false;
217                GuardValue( funcDecl ) = decl;
218        }
219
220        const ast::ReturnStmt * ReturnFixer::previsit(
221                        const ast::ReturnStmt * stmt ) {
222                auto & returns = funcDecl->returns;
223                assert( returns.size() < 2 );
224                // Hands off if the function returns a reference.
225                // Don't allocate a temporary if the address is returned.
226                if ( stmt->expr && 1 == returns.size() ) {
227                        ast::ptr<ast::DeclWithType> retDecl = returns.front();
228                        if ( isConstructable( retDecl->get_type() ) ) {
229                                // Explicitly construct the return value using the return
230                                // expression and the retVal object.
231                                assertf( "" != retDecl->name,
232                                        "Function %s has unnamed return value.\n",
233                                        funcDecl->name.c_str() );
234
235                                auto retVal = retDecl.strict_as<ast::ObjectDecl>();
236                                if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) {
237                                        // Check if the return statement is already set up.
238                                        if ( varExpr->var == retVal ) return stmt;
239                                }
240                                const ast::Stmt * ctorStmt = genCtorDtor(
241                                        retVal->location, "?{}", retVal, stmt->expr );
242                                assertf( ctorStmt,
243                                        "ReturnFixer: genCtorDtor returned nullptr: %s / %s",
244                                        toString( retVal ).c_str(),
245                                        toString( stmt->expr ).c_str() );
246                                stmtsToAddBefore.push_back( ctorStmt );
247
248                                // Return the retVal object.
249                                ast::ReturnStmt * mutStmt = ast::mutate( stmt );
250                                mutStmt->expr = new ast::VariableExpr(
251                                        stmt->location, retDecl );
252                                return mutStmt;
253                        }
254                }
255                return stmt;
256        }
257
258} // namespace
259
260void genInit( ast::TranslationUnit & transUnit ) {
261        ast::Pass<HoistArrayDimension_NoResolve>::run( transUnit );
262        ast::Pass<ReturnFixer>::run( transUnit );
263}
264
265void fixReturnStatements( ast::TranslationUnit & transUnit ) {
266        ast::Pass<ReturnFixer>::run( transUnit );
267}
268
269bool ManagedTypes::isManaged( const ast::Type * type ) const {
270        // references are never constructed
271        if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false;
272        if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) {
273                // tuple is also managed if any of its components are managed
274                for (auto & component : tupleType->types) {
275                        if (isManaged(component)) return true;
276                }
277        }
278        // need to clear and reset qualifiers when determining if a type is managed
279        // ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() );
280        auto tmp = shallowCopy(type);
281        tmp->qualifiers = {};
282        // delete tmp at return
283        ast::ptr<ast::Type> guard = tmp;
284        // 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)
285        return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp );
286}
287
288bool ManagedTypes::isManaged( const ast::ObjectDecl * objDecl ) const {
289        const ast::Type * type = objDecl->type;
290        while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) {
291                // must always construct VLAs with an initializer, since this is an error in C
292                if ( at->isVarLen && objDecl->init ) return true;
293                type = at->base;
294        }
295        return isManaged( type );
296}
297
298void ManagedTypes::handleDWT( const ast::DeclWithType * dwt ) {
299        // if this function is a user-defined constructor or destructor, mark down the type as "managed"
300        if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) {
301                auto & params = GenPoly::getFunctionType( dwt->get_type())->params;
302                assert( ! params.empty() );
303                // Type * type = InitTweak::getPointerBase( params.front() );
304                // assert( type );
305                managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
306        }
307}
308
309void ManagedTypes::handleStruct( const ast::StructDecl * aggregateDecl ) {
310        // don't construct members, but need to take note if there is a managed member,
311        // because that means that this type is also managed
312        for ( auto & member : aggregateDecl->members ) {
313                if ( auto field = member.as<ast::ObjectDecl>() ) {
314                        if ( isManaged( field ) ) {
315                                // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
316                                // polymorphic constructors make generic types managed types
317                                ast::StructInstType inst( aggregateDecl );
318                                managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
319                                break;
320                        }
321                }
322        }
323}
324
325void ManagedTypes::beginScope() { managedTypes.beginScope(); }
326void ManagedTypes::endScope() { managedTypes.endScope(); }
327
328const ast::Stmt * genCtorDtor( const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg ) {
329        assertf(objDecl, "genCtorDtor passed null objDecl");
330        InitExpander srcParam(arg);
331        return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl);
332}
333
334ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) {
335        // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor for each
336        // constructable object
337        InitExpander srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr };
338        ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl);
339
340        ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall(
341                srcParam, dstParam, loc, "?{}", objDecl );
342        ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall(
343                nullParam, dstParam, loc, "^?{}", objDecl,
344                SymTab::LoopBackward );
345
346        // check that either both ctor and dtor are present, or neither
347        assert( (bool)ctor == (bool)dtor );
348
349        if ( ctor ) {
350                // need to remember init expression, in case no ctors exist. If ctor does exist, want to
351                // use ctor expression instead of init.
352                ctor.strict_as< ast::ImplicitCtorDtorStmt >();
353                dtor.strict_as< ast::ImplicitCtorDtorStmt >();
354
355                return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init };
356        }
357
358        return nullptr;
359}
360
361} // namespace InitTweak
362
363// Local Variables: //
364// tab-width: 4 //
365// mode: c++ //
366// compile-command: "make install" //
367// End: //
Note: See TracBrowser for help on using the repository browser.