source: src/InitTweak/GenInit.cpp @ e6491ca

Last change on this file since e6491ca was e6491ca, checked in by JiadaL <j82liang@…>, 6 weeks ago

resolve enum dimension as size of enum

  • 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                                const ast::TypeExpr * ty = dynamic_cast< const ast::TypeExpr * >( arrayType->dimension.get() );
167                                if ( ty ) {
168                                        auto inst = ty->type.as<ast::EnumInstType>();
169                                        if ( inst ) {
170                                                if ( inst->base->isCfa ) {
171                                                        arrayDimension = new ast::ObjectDecl(
172                                                                arrayType->dimension->location,
173                                                                dimensionName.newName(),
174                                                                new ast::BasicType( ast::BasicKind::UnsignedChar ),
175                                                                new ast::SingleInit(
176                                                                        arrayType->dimension->location,
177                                                                        ast::ConstantExpr::from_int( arrayType->dimension->location, inst->base->members.size() )
178                                                                )
179                                                        );
180                                                        // return arrayType;
181                                                }
182                                        }
183                                }
184                                if ( arrayDimension == nullptr ) {
185                                        arrayDimension = new ast::ObjectDecl(
186                                                arrayType->dimension->location,
187                                                dimensionName.newName(),
188                                                dimType,
189                                                new ast::SingleInit(
190                                                        arrayType->dimension->location,
191                                                        arrayType->dimension
192                                                )
193                                        );
194                                }
195
196                                ast::ArrayType * mutType = ast::mutate( arrayType );
197                                mutType->dimension = new ast::VariableExpr(
198                                                arrayDimension->location, arrayDimension );
199                                outer->declsToAddBefore.push_back( arrayDimension );
200
201                                return mutType;
202                        }  // postvisit( const ast::ArrayType * )
203                }; // struct HoistDimsFromTypes
204
205                ast::Storage::Classes storageClasses;
206                void previsit(
207                                const ast::ObjectDecl * decl ) {
208                        GuardValue( storageClasses ) = decl->storage;
209                }
210
211                const ast::DeclWithType * postvisit(
212                                const ast::ObjectDecl * objectDecl ) {
213
214                        if ( !isInFunction() || storageClasses.is_static ) {
215                                return objectDecl;
216                        }
217
218                        const ast::Type * mid = objectDecl->type;
219
220                        ast::Pass<HoistDimsFromTypes> hoist{this};
221                        const ast::Type * result = mid->accept( hoist );
222
223                        return mutate_field( objectDecl, &ast::ObjectDecl::type, result );
224                }
225        };
226
227        struct ReturnFixer final :
228                        public ast::WithStmtsToAdd, ast::WithGuards, ast::WithShortCircuiting {
229                void previsit( const ast::FunctionDecl * decl );
230                const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt );
231        private:
232                const ast::FunctionDecl * funcDecl = nullptr;
233        };
234
235        void ReturnFixer::previsit( const ast::FunctionDecl * decl ) {
236                if (decl->linkage == ast::Linkage::Intrinsic) visit_children = false;
237                GuardValue( funcDecl ) = decl;
238        }
239
240        const ast::ReturnStmt * ReturnFixer::previsit(
241                        const ast::ReturnStmt * stmt ) {
242                auto & returns = funcDecl->returns;
243                assert( returns.size() < 2 );
244                // Hands off if the function returns a reference.
245                // Don't allocate a temporary if the address is returned.
246                if ( stmt->expr && 1 == returns.size() ) {
247                        ast::ptr<ast::DeclWithType> retDecl = returns.front();
248                        if ( isConstructable( retDecl->get_type() ) ) {
249                                // Explicitly construct the return value using the return
250                                // expression and the retVal object.
251                                assertf( "" != retDecl->name,
252                                        "Function %s has unnamed return value.\n",
253                                        funcDecl->name.c_str() );
254
255                                auto retVal = retDecl.strict_as<ast::ObjectDecl>();
256                                if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) {
257                                        // Check if the return statement is already set up.
258                                        if ( varExpr->var == retVal ) return stmt;
259                                }
260                                const ast::Stmt * ctorStmt = genCtorDtor(
261                                        retVal->location, "?{}", retVal, stmt->expr );
262                                assertf( ctorStmt,
263                                        "ReturnFixer: genCtorDtor returned nullptr: %s / %s",
264                                        toString( retVal ).c_str(),
265                                        toString( stmt->expr ).c_str() );
266                                stmtsToAddBefore.push_back( ctorStmt );
267
268                                // Return the retVal object.
269                                ast::ReturnStmt * mutStmt = ast::mutate( stmt );
270                                mutStmt->expr = new ast::VariableExpr(
271                                        stmt->location, retDecl );
272                                return mutStmt;
273                        }
274                }
275                return stmt;
276        }
277
278} // namespace
279
280void genInit( ast::TranslationUnit & transUnit ) {
281        ast::Pass<HoistArrayDimension_NoResolve>::run( transUnit );
282        ast::Pass<ReturnFixer>::run( transUnit );
283}
284
285void fixReturnStatements( ast::TranslationUnit & transUnit ) {
286        ast::Pass<ReturnFixer>::run( transUnit );
287}
288
289bool ManagedTypes::isManaged( const ast::Type * type ) const {
290        // references are never constructed
291        if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false;
292        if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) {
293                // tuple is also managed if any of its components are managed
294                for (auto & component : tupleType->types) {
295                        if (isManaged(component)) return true;
296                }
297        }
298        // need to clear and reset qualifiers when determining if a type is managed
299        auto tmp = shallowCopy(type);
300        tmp->qualifiers = {};
301        // delete tmp at return
302        ast::ptr<ast::Type> guard = tmp;
303        // 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)
304        return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp );
305}
306
307bool ManagedTypes::isManaged( const ast::ObjectDecl * objDecl ) const {
308        const ast::Type * type = objDecl->type;
309        while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) {
310                // must always construct VLAs with an initializer, since this is an error in C
311                if ( at->isVarLen && objDecl->init ) return true;
312                type = at->base;
313        }
314        return isManaged( type );
315}
316
317void ManagedTypes::handleDWT( const ast::DeclWithType * dwt ) {
318        // if this function is a user-defined constructor or destructor, mark down the type as "managed"
319        if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) {
320                auto & params = GenPoly::getFunctionType( dwt->get_type())->params;
321                assert( ! params.empty() );
322                // Type * type = InitTweak::getPointerBase( params.front() );
323                // assert( type );
324                managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
325        }
326}
327
328void ManagedTypes::handleStruct( const ast::StructDecl * aggregateDecl ) {
329        // don't construct members, but need to take note if there is a managed member,
330        // because that means that this type is also managed
331        for ( auto & member : aggregateDecl->members ) {
332                if ( auto field = member.as<ast::ObjectDecl>() ) {
333                        if ( isManaged( field ) ) {
334                                // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
335                                // polymorphic constructors make generic types managed types
336                                ast::StructInstType inst( aggregateDecl );
337                                managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
338                                break;
339                        }
340                }
341        }
342}
343
344void ManagedTypes::beginScope() { managedTypes.beginScope(); }
345void ManagedTypes::endScope() { managedTypes.endScope(); }
346
347const ast::Stmt * genCtorDtor( const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg ) {
348        assertf(objDecl, "genCtorDtor passed null objDecl");
349        InitExpander srcParam(arg);
350        return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl);
351}
352
353ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) {
354        // Call genImplicitCall to generate calls to ctor/dtor for each constructable object.
355        InitExpander srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr };
356        ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl);
357
358        ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall(
359                srcParam, dstParam, loc, "?{}", objDecl );
360        ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall(
361                nullParam, dstParam, loc, "^?{}", objDecl,
362                SymTab::LoopBackward );
363
364        // check that either both ctor and dtor are present, or neither
365        assert( (bool)ctor == (bool)dtor );
366
367        if ( ctor ) {
368                // need to remember init expression, in case no ctors exist. If ctor does exist, want to
369                // use ctor expression instead of init.
370                ctor.strict_as< ast::ImplicitCtorDtorStmt >();
371                dtor.strict_as< ast::ImplicitCtorDtorStmt >();
372
373                return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init };
374        }
375
376        return nullptr;
377}
378
379} // namespace InitTweak
380
381// Local Variables: //
382// tab-width: 4 //
383// mode: c++ //
384// compile-command: "make install" //
385// End: //
Note: See TracBrowser for help on using the repository browser.