source: src/InitTweak/GenInit.cpp @ 90e683b

Last change on this file since 90e683b was 90e683b, checked in by Andrew Beach <ajbeach@…>, 2 months ago

I set out to do a enum rework. It ended up being much the same and I unwound the core rework. But I hope the new names are a bit clearer and other minor fixes are helpful, so I am keeping those.

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