[71f4e4f] | 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 | // FixInit.h -- |
---|
| 8 | // |
---|
| 9 | // Author : Rob Schluntz |
---|
| 10 | // Created On : Wed Jan 13 16:29:30 2016 |
---|
[adcc065] | 11 | // Last Modified By : Peter A. Buhr |
---|
[4e06c1e] | 12 | // Last Modified On : Tue Jul 12 17:41:15 2016 |
---|
| 13 | // Update Count : 34 |
---|
[71f4e4f] | 14 | // |
---|
| 15 | |
---|
| 16 | #include <stack> |
---|
| 17 | #include <list> |
---|
[c2931ea] | 18 | #include <iterator> |
---|
| 19 | #include <algorithm> |
---|
[7b3f66b] | 20 | #include "InitTweak.h" |
---|
[6cf27a07] | 21 | #include "FixInit.h" |
---|
| 22 | #include "FixGlobalInit.h" |
---|
[db4ecc5] | 23 | #include "ResolvExpr/Resolver.h" |
---|
[845cedc] | 24 | #include "ResolvExpr/typeops.h" |
---|
[71f4e4f] | 25 | #include "SynTree/Declaration.h" |
---|
| 26 | #include "SynTree/Type.h" |
---|
| 27 | #include "SynTree/Expression.h" |
---|
[f9cebb5] | 28 | #include "SynTree/Attribute.h" |
---|
[71f4e4f] | 29 | #include "SynTree/Statement.h" |
---|
| 30 | #include "SynTree/Initializer.h" |
---|
| 31 | #include "SynTree/Mutator.h" |
---|
[db4ecc5] | 32 | #include "SymTab/Indexer.h" |
---|
[71f4e4f] | 33 | #include "GenPoly/PolyMutator.h" |
---|
[c2931ea] | 34 | #include "SynTree/AddStmtVisitor.h" |
---|
[71f4e4f] | 35 | |
---|
[845cedc] | 36 | bool ctordtorp = false; |
---|
[c2931ea] | 37 | bool ctorp = false; |
---|
| 38 | bool cpctorp = false; |
---|
[e39aa0f] | 39 | bool dtorp = false; |
---|
[845cedc] | 40 | #define PRINT( text ) if ( ctordtorp ) { text } |
---|
[c2931ea] | 41 | #define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text } |
---|
| 42 | #define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text } |
---|
[845cedc] | 43 | |
---|
[71f4e4f] | 44 | namespace InitTweak { |
---|
| 45 | namespace { |
---|
| 46 | const std::list<Label> noLabels; |
---|
[e0323a2] | 47 | const std::list<Expression*> noDesignators; |
---|
[71f4e4f] | 48 | |
---|
[c2931ea] | 49 | class InsertImplicitCalls : public GenPoly::PolyMutator { |
---|
| 50 | public: |
---|
[adcc065] | 51 | /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which |
---|
| 52 | /// function calls need their parameters to be copy constructed |
---|
[c2931ea] | 53 | static void insert( std::list< Declaration * > & translationUnit ); |
---|
| 54 | |
---|
| 55 | virtual Expression * mutate( ApplicationExpr * appExpr ); |
---|
| 56 | }; |
---|
| 57 | |
---|
| 58 | class ResolveCopyCtors : public SymTab::Indexer { |
---|
| 59 | public: |
---|
[adcc065] | 60 | /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr, |
---|
| 61 | /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both |
---|
| 62 | /// arguments and return value temporaries |
---|
[c2931ea] | 63 | static void resolveImplicitCalls( std::list< Declaration * > & translationUnit ); |
---|
| 64 | |
---|
| 65 | virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
| 66 | |
---|
| 67 | /// create and resolve ctor/dtor expression: fname(var, [cpArg]) |
---|
| 68 | ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL ); |
---|
| 69 | /// true if type does not need to be copy constructed to ensure correctness |
---|
| 70 | bool skipCopyConstruct( Type * ); |
---|
| 71 | private: |
---|
| 72 | TypeSubstitution * env; |
---|
| 73 | }; |
---|
| 74 | |
---|
| 75 | /// collects constructed object decls - used as a base class |
---|
| 76 | class ObjDeclCollector : public AddStmtVisitor { |
---|
| 77 | public: |
---|
| 78 | typedef AddStmtVisitor Parent; |
---|
| 79 | using Parent::visit; |
---|
| 80 | typedef std::set< ObjectDecl * > ObjectSet; |
---|
| 81 | virtual void visit( CompoundStmt *compoundStmt ); |
---|
| 82 | virtual void visit( DeclStmt *stmt ); |
---|
| 83 | protected: |
---|
| 84 | ObjectSet curVars; |
---|
| 85 | }; |
---|
| 86 | |
---|
[6cf27a07] | 87 | // debug |
---|
[c2931ea] | 88 | struct printSet { |
---|
| 89 | typedef ObjDeclCollector::ObjectSet ObjectSet; |
---|
| 90 | printSet( const ObjectSet & objs ) : objs( objs ) {} |
---|
| 91 | const ObjectSet & objs; |
---|
| 92 | }; |
---|
| 93 | std::ostream & operator<<( std::ostream & out, const printSet & set) { |
---|
| 94 | out << "{ "; |
---|
| 95 | for ( ObjectDecl * obj : set.objs ) { |
---|
| 96 | out << obj->get_name() << ", " ; |
---|
[adcc065] | 97 | } // for |
---|
[c2931ea] | 98 | out << " }"; |
---|
| 99 | return out; |
---|
| 100 | } |
---|
| 101 | |
---|
| 102 | class LabelFinder : public ObjDeclCollector { |
---|
| 103 | public: |
---|
| 104 | typedef ObjDeclCollector Parent; |
---|
| 105 | typedef std::map< Label, ObjectSet > LabelMap; |
---|
| 106 | // map of Label -> live variables at that label |
---|
| 107 | LabelMap vars; |
---|
| 108 | |
---|
| 109 | void handleStmt( Statement * stmt ); |
---|
| 110 | |
---|
| 111 | // xxx - This needs to be done better. |
---|
[adcc065] | 112 | // allow some generalization among different kinds of nodes with with similar parentage (e.g. all |
---|
| 113 | // expressions, all statements, etc.) important to have this to provide a single entry point so that as new |
---|
| 114 | // subclasses are added, there is only one place that the code has to be updated, rather than ensure that |
---|
| 115 | // every specialized class knows about every new kind of statement that might be added. |
---|
[c2931ea] | 116 | virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 117 | virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 118 | virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 119 | virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 120 | virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 121 | virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 122 | virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 123 | virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 124 | virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 125 | virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 126 | virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 127 | virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 128 | virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 129 | virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 130 | virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 131 | virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 132 | }; |
---|
| 133 | |
---|
| 134 | class InsertDtors : public ObjDeclCollector { |
---|
| 135 | public: |
---|
[adcc065] | 136 | /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed |
---|
| 137 | /// (currently by FixInit) |
---|
[c2931ea] | 138 | static void insert( std::list< Declaration * > & translationUnit ); |
---|
| 139 | |
---|
| 140 | typedef ObjDeclCollector Parent; |
---|
| 141 | typedef std::list< ObjectDecl * > OrderedDecls; |
---|
| 142 | typedef std::list< OrderedDecls > OrderedDeclsStack; |
---|
| 143 | |
---|
| 144 | InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {} |
---|
| 145 | |
---|
| 146 | virtual void visit( ObjectDecl * objDecl ); |
---|
| 147 | |
---|
| 148 | virtual void visit( CompoundStmt * compoundStmt ); |
---|
| 149 | virtual void visit( ReturnStmt * returnStmt ); |
---|
| 150 | virtual void visit( BranchStmt * stmt ); |
---|
| 151 | private: |
---|
| 152 | void handleGoto( BranchStmt * stmt ); |
---|
| 153 | |
---|
| 154 | LabelFinder::LabelMap & labelVars; |
---|
| 155 | OrderedDeclsStack reverseDeclOrder; |
---|
| 156 | }; |
---|
| 157 | |
---|
| 158 | class FixInit : public GenPoly::PolyMutator { |
---|
| 159 | public: |
---|
| 160 | /// expand each object declaration to use its constructor after it is declared. |
---|
| 161 | static void fixInitializers( std::list< Declaration * > &translationUnit ); |
---|
| 162 | |
---|
| 163 | virtual DeclarationWithType * mutate( ObjectDecl *objDecl ); |
---|
[72e9222] | 164 | |
---|
| 165 | std::list< Declaration * > staticDtorDecls; |
---|
[c2931ea] | 166 | }; |
---|
| 167 | |
---|
| 168 | class FixCopyCtors : public GenPoly::PolyMutator { |
---|
| 169 | public: |
---|
[adcc065] | 170 | /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression, |
---|
| 171 | /// and destructors |
---|
[c2931ea] | 172 | static void fixCopyCtors( std::list< Declaration * > &translationUnit ); |
---|
| 173 | |
---|
| 174 | virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
| 175 | }; |
---|
| 176 | } // namespace |
---|
[db4ecc5] | 177 | |
---|
[6cf27a07] | 178 | void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) { |
---|
| 179 | // fixes ConstructorInit for global variables. should happen before fixInitializers. |
---|
| 180 | InitTweak::fixGlobalInit( translationUnit, filename, inLibrary ); |
---|
| 181 | |
---|
[db4ecc5] | 182 | InsertImplicitCalls::insert( translationUnit ); |
---|
| 183 | ResolveCopyCtors::resolveImplicitCalls( translationUnit ); |
---|
[c2931ea] | 184 | InsertDtors::insert( translationUnit ); |
---|
[71f4e4f] | 185 | FixInit::fixInitializers( translationUnit ); |
---|
[c2931ea] | 186 | |
---|
[db4ecc5] | 187 | // FixCopyCtors must happen after FixInit, so that destructors are placed correctly |
---|
| 188 | FixCopyCtors::fixCopyCtors( translationUnit ); |
---|
| 189 | } |
---|
| 190 | |
---|
[c2931ea] | 191 | namespace { |
---|
| 192 | void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) { |
---|
| 193 | InsertImplicitCalls inserter; |
---|
| 194 | mutateAll( translationUnit, inserter ); |
---|
| 195 | } |
---|
[db4ecc5] | 196 | |
---|
[c2931ea] | 197 | void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) { |
---|
| 198 | ResolveCopyCtors resolver; |
---|
| 199 | acceptAll( translationUnit, resolver ); |
---|
| 200 | } |
---|
[71f4e4f] | 201 | |
---|
[c2931ea] | 202 | void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) { |
---|
| 203 | FixInit fixer; |
---|
[72e9222] | 204 | |
---|
| 205 | // can't use mutateAll, because need to insert declarations at top-level |
---|
| 206 | // can't use DeclMutator, because sometimes need to insert IfStmt, etc. |
---|
| 207 | SemanticError errors; |
---|
| 208 | for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) { |
---|
| 209 | try { |
---|
| 210 | *i = maybeMutate( *i, fixer ); |
---|
[f9cebb5] | 211 | translationUnit.splice( i, fixer.staticDtorDecls ); |
---|
[72e9222] | 212 | } catch( SemanticError &e ) { |
---|
| 213 | errors.append( e ); |
---|
| 214 | } // try |
---|
| 215 | } // for |
---|
| 216 | if ( ! errors.isEmpty() ) { |
---|
| 217 | throw errors; |
---|
| 218 | } // if |
---|
[c2931ea] | 219 | } |
---|
[71f4e4f] | 220 | |
---|
[c2931ea] | 221 | void InsertDtors::insert( std::list< Declaration * > & translationUnit ) { |
---|
| 222 | LabelFinder finder; |
---|
| 223 | InsertDtors inserter( finder ); |
---|
| 224 | acceptAll( translationUnit, finder ); |
---|
| 225 | acceptAll( translationUnit, inserter ); |
---|
| 226 | } |
---|
| 227 | |
---|
| 228 | void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) { |
---|
| 229 | FixCopyCtors fixer; |
---|
| 230 | mutateAll( translationUnit, fixer ); |
---|
| 231 | } |
---|
[db4ecc5] | 232 | |
---|
[c2931ea] | 233 | Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) { |
---|
| 234 | appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) ); |
---|
| 235 | assert( appExpr ); |
---|
| 236 | |
---|
| 237 | if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) { |
---|
| 238 | if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) { |
---|
| 239 | // optimization: don't need to copy construct in order to call intrinsic functions |
---|
| 240 | return appExpr; |
---|
| 241 | } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) { |
---|
| 242 | FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) ); |
---|
| 243 | assert( ftype ); |
---|
| 244 | if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) { |
---|
| 245 | Type * t1 = ftype->get_parameters().front()->get_type(); |
---|
| 246 | Type * t2 = ftype->get_parameters().back()->get_type(); |
---|
| 247 | PointerType * ptrType = dynamic_cast< PointerType * > ( t1 ); |
---|
| 248 | assert( ptrType ); |
---|
| 249 | |
---|
| 250 | if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) { |
---|
| 251 | // optimization: don't need to copy construct in order to call a copy constructor or |
---|
| 252 | // assignment operator |
---|
| 253 | return appExpr; |
---|
[adcc065] | 254 | } // if |
---|
[c2931ea] | 255 | } else if ( funcDecl->get_name() == "^?{}" ) { |
---|
| 256 | // correctness: never copy construct arguments to a destructor |
---|
[845cedc] | 257 | return appExpr; |
---|
[adcc065] | 258 | } // if |
---|
| 259 | } // if |
---|
| 260 | } // if |
---|
[c2931ea] | 261 | CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; ) |
---|
| 262 | |
---|
| 263 | // wrap each function call so that it is easy to identify nodes that have to be copy constructed |
---|
| 264 | ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr ); |
---|
| 265 | // save the type substitution onto the new node so that it is easy to find. |
---|
| 266 | // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion. |
---|
| 267 | // The substitution is needed to obtain the type of temporary variables so that copy constructor |
---|
| 268 | // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves |
---|
| 269 | // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which |
---|
| 270 | // saves the environment, or compute the types of temporaries here, but it's much simpler to |
---|
| 271 | // save the environment here, and more cohesive to compute temporary variables and resolve copy |
---|
| 272 | // constructor calls together. |
---|
| 273 | assert( env ); |
---|
| 274 | expr->set_env( env ); |
---|
| 275 | return expr; |
---|
[db4ecc5] | 276 | } |
---|
| 277 | |
---|
[c2931ea] | 278 | bool ResolveCopyCtors::skipCopyConstruct( Type * type ) { |
---|
| 279 | return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type ); |
---|
| 280 | } |
---|
| 281 | |
---|
| 282 | ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) { |
---|
| 283 | assert( var ); |
---|
| 284 | UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) ); |
---|
| 285 | untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) ); |
---|
| 286 | if (cpArg) untyped->get_args().push_back( cpArg ); |
---|
| 287 | |
---|
| 288 | // resolve copy constructor |
---|
[adcc065] | 289 | // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed |
---|
| 290 | // (VariableExpr and already resolved expression) |
---|
[c2931ea] | 291 | CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; ) |
---|
| 292 | ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) ); |
---|
| 293 | if ( resolved->get_env() ) { |
---|
| 294 | env->add( *resolved->get_env() ); |
---|
[adcc065] | 295 | } // if |
---|
[cf18eea] | 296 | |
---|
[c2931ea] | 297 | assert( resolved ); |
---|
| 298 | delete untyped; |
---|
| 299 | return resolved; |
---|
[540de412] | 300 | } |
---|
[db4ecc5] | 301 | |
---|
[c2931ea] | 302 | void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) { |
---|
| 303 | static UniqueName tempNamer("_tmp_cp"); |
---|
| 304 | static UniqueName retNamer("_tmp_cp_ret"); |
---|
| 305 | |
---|
| 306 | CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; ) |
---|
| 307 | Visitor::visit( impCpCtorExpr ); |
---|
| 308 | env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer... |
---|
| 309 | |
---|
| 310 | ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr(); |
---|
| 311 | |
---|
| 312 | // take each argument and attempt to copy construct it. |
---|
| 313 | for ( Expression * & arg : appExpr->get_args() ) { |
---|
| 314 | CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; ) |
---|
| 315 | // xxx - need to handle tuple arguments |
---|
| 316 | assert( ! arg->get_results().empty() ); |
---|
| 317 | Type * result = arg->get_results().front(); |
---|
| 318 | if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types |
---|
| 319 | // type may involve type variables, so apply type substitution to get temporary variable's actual type |
---|
| 320 | result = result->clone(); |
---|
| 321 | impCpCtorExpr->get_env()->apply( result ); |
---|
| 322 | ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 ); |
---|
| 323 | tmp->get_type()->set_isConst( false ); |
---|
| 324 | |
---|
| 325 | // create and resolve copy constructor |
---|
| 326 | CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; ) |
---|
| 327 | ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg ); |
---|
| 328 | |
---|
| 329 | // if the chosen constructor is intrinsic, the copy is unnecessary, so |
---|
| 330 | // don't create the temporary and don't call the copy constructor |
---|
| 331 | VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() ); |
---|
| 332 | assert( function ); |
---|
| 333 | if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) { |
---|
| 334 | // replace argument to function call with temporary |
---|
| 335 | arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) ); |
---|
| 336 | impCpCtorExpr->get_tempDecls().push_back( tmp ); |
---|
| 337 | impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) ); |
---|
[adcc065] | 338 | } // if |
---|
| 339 | } // for |
---|
[db4ecc5] | 340 | |
---|
[adcc065] | 341 | // each return value from the call needs to be connected with an ObjectDecl at the call site, which is |
---|
| 342 | // initialized with the return value and is destructed later |
---|
[c2931ea] | 343 | // xxx - handle multiple return values |
---|
| 344 | ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr(); |
---|
[adcc065] | 345 | // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher |
---|
| 346 | // level. Trying to pass that environment along. |
---|
[c2931ea] | 347 | callExpr->set_env( impCpCtorExpr->get_env()->clone() ); |
---|
| 348 | for ( Type * result : appExpr->get_results() ) { |
---|
| 349 | result = result->clone(); |
---|
| 350 | impCpCtorExpr->get_env()->apply( result ); |
---|
| 351 | ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 ); |
---|
| 352 | ret->get_type()->set_isConst( false ); |
---|
| 353 | impCpCtorExpr->get_returnDecls().push_back( ret ); |
---|
| 354 | CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; ) |
---|
| 355 | impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) ); |
---|
[adcc065] | 356 | } // for |
---|
[c2931ea] | 357 | CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; ) |
---|
[db4ecc5] | 358 | } |
---|
| 359 | |
---|
| 360 | |
---|
[c2931ea] | 361 | Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) { |
---|
| 362 | CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; ) |
---|
| 363 | |
---|
| 364 | impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) ); |
---|
| 365 | assert( impCpCtorExpr ); |
---|
[db4ecc5] | 366 | |
---|
[c2931ea] | 367 | std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls(); |
---|
| 368 | std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls(); |
---|
| 369 | std::list< Expression * > & dtors = impCpCtorExpr->get_dtors(); |
---|
[845cedc] | 370 | |
---|
[c2931ea] | 371 | // add all temporary declarations and their constructors |
---|
| 372 | for ( ObjectDecl * obj : tempDecls ) { |
---|
| 373 | stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) ); |
---|
[adcc065] | 374 | } // for |
---|
[c2931ea] | 375 | for ( ObjectDecl * obj : returnDecls ) { |
---|
| 376 | stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) ); |
---|
[adcc065] | 377 | } // for |
---|
[db4ecc5] | 378 | |
---|
[c2931ea] | 379 | // add destructors after current statement |
---|
| 380 | for ( Expression * dtor : dtors ) { |
---|
| 381 | stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) ); |
---|
[adcc065] | 382 | } // for |
---|
[db4ecc5] | 383 | |
---|
[c2931ea] | 384 | // xxx - update to work with multiple return values |
---|
| 385 | ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front(); |
---|
| 386 | Expression * callExpr = impCpCtorExpr->get_callExpr(); |
---|
| 387 | |
---|
| 388 | CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; ) |
---|
| 389 | |
---|
| 390 | // detach fields from wrapper node so that it can be deleted without deleting too much |
---|
| 391 | dtors.clear(); |
---|
| 392 | tempDecls.clear(); |
---|
| 393 | returnDecls.clear(); |
---|
| 394 | impCpCtorExpr->set_callExpr( NULL ); |
---|
| 395 | impCpCtorExpr->set_env( NULL ); |
---|
| 396 | delete impCpCtorExpr; |
---|
| 397 | |
---|
| 398 | if ( returnDecl ) { |
---|
| 399 | UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
| 400 | assign->get_args().push_back( new VariableExpr( returnDecl ) ); |
---|
| 401 | assign->get_args().push_back( callExpr ); |
---|
| 402 | // know the result type of the assignment is the type of the LHS (minus the pointer), so |
---|
| 403 | // add that onto the assignment expression so that later steps have the necessary information |
---|
| 404 | assign->add_result( returnDecl->get_type()->clone() ); |
---|
| 405 | |
---|
| 406 | Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) ); |
---|
| 407 | if ( callExpr->get_results().front()->get_isLvalue() ) { |
---|
[adcc065] | 408 | // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning |
---|
| 409 | // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the |
---|
| 410 | // type of the return temporary from T to T* to properly capture the return value. Then dereference |
---|
| 411 | // the result of the comma expression, since the lvalue returning call was originally wrapped with |
---|
| 412 | // an AddressExpr. Effectively, this turns |
---|
[c2931ea] | 413 | // lvalue T f(); |
---|
| 414 | // &*f() |
---|
| 415 | // into |
---|
| 416 | // T * tmp_cp_retN; |
---|
| 417 | // tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret); |
---|
| 418 | // which work out in terms of types, but is pretty messy. It would be nice to find a better way. |
---|
| 419 | assign->get_args().back() = new AddressExpr( assign->get_args().back() ); |
---|
| 420 | |
---|
| 421 | Type * resultType = returnDecl->get_type()->clone(); |
---|
| 422 | returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) ); |
---|
| 423 | UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) ); |
---|
| 424 | deref->get_args().push_back( retExpr ); |
---|
| 425 | deref->add_result( resultType ); |
---|
| 426 | retExpr = deref; |
---|
[adcc065] | 427 | } // if |
---|
[c2931ea] | 428 | // xxx - might need to set env on retExpr... |
---|
| 429 | // retExpr->set_env( env->clone() ); |
---|
| 430 | return retExpr; |
---|
| 431 | } else { |
---|
| 432 | return callExpr; |
---|
[adcc065] | 433 | } // if |
---|
[4ffdd63] | 434 | } |
---|
[c2931ea] | 435 | |
---|
| 436 | DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) { |
---|
[adcc065] | 437 | // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init |
---|
| 438 | // is removed from the ObjectDecl |
---|
[c2931ea] | 439 | objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) ); |
---|
| 440 | |
---|
| 441 | if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) { |
---|
| 442 | // a decision should have been made by the resolver, so ctor and init are not both non-NULL |
---|
| 443 | assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() ); |
---|
| 444 | if ( Statement * ctor = ctorInit->get_ctor() ) { |
---|
| 445 | if ( objDecl->get_storageClass() == DeclarationNode::Static ) { |
---|
[72e9222] | 446 | // originally wanted to take advantage of gcc nested functions, but |
---|
[f9cebb5] | 447 | // we get memory errors with this approach. To remedy this, the static |
---|
| 448 | // variable is hoisted when the destructor needs to be called. |
---|
[72e9222] | 449 | // |
---|
[c2931ea] | 450 | // generate: |
---|
[f9cebb5] | 451 | // static T __objName_static_varN; |
---|
[72e9222] | 452 | // void __objName_dtor_atexitN() { |
---|
[f9cebb5] | 453 | // __dtor__...; |
---|
[72e9222] | 454 | // } |
---|
| 455 | // int f(...) { |
---|
| 456 | // ... |
---|
| 457 | // static bool __objName_uninitialized = true; |
---|
| 458 | // if (__objName_uninitialized) { |
---|
| 459 | // __ctor(__objName); |
---|
| 460 | // __objName_uninitialized = false; |
---|
[f9cebb5] | 461 | // atexit(__objName_dtor_atexitN); |
---|
[c2931ea] | 462 | // } |
---|
[72e9222] | 463 | // ... |
---|
[c2931ea] | 464 | // } |
---|
| 465 | |
---|
[72e9222] | 466 | static UniqueName dtorCallerNamer( "_dtor_atexit" ); |
---|
| 467 | |
---|
| 468 | // static bool __objName_uninitialized = true |
---|
[c2931ea] | 469 | BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool ); |
---|
| 470 | SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators ); |
---|
| 471 | ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr ); |
---|
| 472 | isUninitializedVar->fixUniqueId(); |
---|
| 473 | |
---|
| 474 | // __objName_uninitialized = false; |
---|
| 475 | UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
| 476 | setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) ); |
---|
| 477 | setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) ); |
---|
| 478 | |
---|
| 479 | // generate body of if |
---|
| 480 | CompoundStmt * initStmts = new CompoundStmt( noLabels ); |
---|
| 481 | std::list< Statement * > & body = initStmts->get_kids(); |
---|
| 482 | body.push_back( ctor ); |
---|
| 483 | body.push_back( new ExprStmt( noLabels, setTrue ) ); |
---|
| 484 | |
---|
| 485 | // put it all together |
---|
| 486 | IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 ); |
---|
| 487 | stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) ); |
---|
| 488 | stmtsToAddAfter.push_back( ifStmt ); |
---|
[72e9222] | 489 | |
---|
[f9cebb5] | 490 | if ( ctorInit->get_dtor() ) { |
---|
| 491 | // if the object has a non-trivial destructor, have to |
---|
| 492 | // hoist it and the object into the global space and |
---|
| 493 | // call the destructor function with atexit. |
---|
| 494 | |
---|
| 495 | Statement * dtorStmt = ctorInit->get_dtor()->clone(); |
---|
| 496 | |
---|
| 497 | // void __objName_dtor_atexitN(...) {...} |
---|
| 498 | FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false ); |
---|
| 499 | dtorCaller->fixUniqueId(); |
---|
| 500 | dtorCaller->get_statements()->get_kids().push_back( dtorStmt ); |
---|
| 501 | |
---|
| 502 | // atexit(dtor_atexit); |
---|
| 503 | UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) ); |
---|
| 504 | callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) ); |
---|
| 505 | |
---|
| 506 | body.push_back( new ExprStmt( noLabels, callAtexit ) ); |
---|
| 507 | |
---|
| 508 | // hoist variable and dtor caller decls to list of decls that will be added into global scope |
---|
| 509 | staticDtorDecls.push_back( objDecl ); |
---|
| 510 | staticDtorDecls.push_back( dtorCaller ); |
---|
| 511 | |
---|
| 512 | // need to rename object uniquely since it now appears |
---|
| 513 | // at global scope and there could be multiple function-scoped |
---|
| 514 | // static variables with the same name in different functions. |
---|
| 515 | static UniqueName staticNamer( "_static_var" ); |
---|
| 516 | objDecl->set_mangleName( objDecl->get_mangleName() + staticNamer.newName() ); |
---|
| 517 | |
---|
| 518 | objDecl->set_init( NULL ); |
---|
| 519 | ctorInit->set_ctor( NULL ); |
---|
| 520 | delete ctorInit; |
---|
| 521 | |
---|
| 522 | // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope |
---|
| 523 | // create a new object which is never used |
---|
| 524 | static UniqueName dummyNamer( "_dummy" ); |
---|
| 525 | ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), DeclarationNode::Static, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } ); |
---|
| 526 | return dummy; |
---|
| 527 | } |
---|
[c2931ea] | 528 | } else { |
---|
| 529 | stmtsToAddAfter.push_back( ctor ); |
---|
[adcc065] | 530 | } // if |
---|
[c2931ea] | 531 | objDecl->set_init( NULL ); |
---|
| 532 | ctorInit->set_ctor( NULL ); |
---|
| 533 | } else if ( Initializer * init = ctorInit->get_init() ) { |
---|
| 534 | objDecl->set_init( init ); |
---|
| 535 | ctorInit->set_init( NULL ); |
---|
| 536 | } else { |
---|
| 537 | // no constructor and no initializer, which is okay |
---|
| 538 | objDecl->set_init( NULL ); |
---|
[adcc065] | 539 | } // if |
---|
[c2931ea] | 540 | delete ctorInit; |
---|
[adcc065] | 541 | } // if |
---|
[c2931ea] | 542 | return objDecl; |
---|
[db4ecc5] | 543 | } |
---|
| 544 | |
---|
[c2931ea] | 545 | void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) { |
---|
| 546 | std::set< ObjectDecl * > prevVars = curVars; |
---|
| 547 | Parent::visit( compoundStmt ); |
---|
| 548 | curVars = prevVars; |
---|
[db4ecc5] | 549 | } |
---|
| 550 | |
---|
[c2931ea] | 551 | void ObjDeclCollector::visit( DeclStmt *stmt ) { |
---|
[4b2589a] | 552 | // keep track of all variables currently in scope |
---|
[c2931ea] | 553 | if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) { |
---|
| 554 | curVars.insert( objDecl ); |
---|
[adcc065] | 555 | } // if |
---|
[e39aa0f] | 556 | Parent::visit( stmt ); |
---|
[db4ecc5] | 557 | } |
---|
| 558 | |
---|
[c2931ea] | 559 | void LabelFinder::handleStmt( Statement * stmt ) { |
---|
[4b2589a] | 560 | // for each label, remember the variables in scope at that label. |
---|
[c2931ea] | 561 | for ( Label l : stmt->get_labels() ) { |
---|
| 562 | vars[l] = curVars; |
---|
[adcc065] | 563 | } // for |
---|
[71f4e4f] | 564 | } |
---|
[f1e012b] | 565 | |
---|
[ec79847] | 566 | template<typename Iterator, typename OutputIterator> |
---|
| 567 | void insertDtors( Iterator begin, Iterator end, OutputIterator out ) { |
---|
| 568 | for ( Iterator it = begin ; it != end ; ++it ) { |
---|
[adcc065] | 569 | // extract destructor statement from the object decl and insert it into the output. Note that this is |
---|
| 570 | // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually |
---|
| 571 | // calls an intrinsic dtor then the call must (and will) still be generated since the argument may |
---|
| 572 | // contain side effects. |
---|
[c2931ea] | 573 | ObjectDecl * objDecl = *it; |
---|
| 574 | ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ); |
---|
| 575 | assert( ctorInit && ctorInit->get_dtor() ); |
---|
| 576 | *out++ = ctorInit->get_dtor()->clone(); |
---|
[adcc065] | 577 | } // for |
---|
[f1e012b] | 578 | } |
---|
[39786813] | 579 | |
---|
[c2931ea] | 580 | void InsertDtors::visit( ObjectDecl * objDecl ) { |
---|
| 581 | // remember non-static destructed objects so that their destructors can be inserted later |
---|
| 582 | if ( objDecl->get_storageClass() != DeclarationNode::Static ) { |
---|
| 583 | if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) { |
---|
| 584 | // a decision should have been made by the resolver, so ctor and init are not both non-NULL |
---|
| 585 | assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() ); |
---|
| 586 | Statement * dtor = ctorInit->get_dtor(); |
---|
[f9cebb5] | 587 | if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) { |
---|
[c2931ea] | 588 | // don't need to call intrinsic dtor, because it does nothing, but |
---|
| 589 | // non-intrinsic dtors must be called |
---|
| 590 | reverseDeclOrder.front().push_front( objDecl ); |
---|
[adcc065] | 591 | } // if |
---|
| 592 | } // if |
---|
| 593 | } // if |
---|
[c2931ea] | 594 | Parent::visit( objDecl ); |
---|
| 595 | } |
---|
[39786813] | 596 | |
---|
[c2931ea] | 597 | void InsertDtors::visit( CompoundStmt * compoundStmt ) { |
---|
[adcc065] | 598 | // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors |
---|
| 599 | // when block is left, just the destructors associated with variables defined in this block, so push a new |
---|
| 600 | // list to the top of the stack so that we can differentiate scopes |
---|
[c2931ea] | 601 | reverseDeclOrder.push_front( OrderedDecls() ); |
---|
| 602 | Parent::visit( compoundStmt ); |
---|
[39786813] | 603 | |
---|
[4b2589a] | 604 | // add destructors for the current scope that we're exiting |
---|
[c2931ea] | 605 | std::list< Statement * > & statements = compoundStmt->get_kids(); |
---|
| 606 | insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) ); |
---|
| 607 | reverseDeclOrder.pop_front(); |
---|
[39786813] | 608 | } |
---|
| 609 | |
---|
[c2931ea] | 610 | void InsertDtors::visit( ReturnStmt * returnStmt ) { |
---|
[4b2589a] | 611 | // return exits all scopes, so dump destructors for all scopes |
---|
[c2931ea] | 612 | for ( OrderedDecls & od : reverseDeclOrder ) { |
---|
| 613 | insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) ); |
---|
[adcc065] | 614 | } // for |
---|
[39786813] | 615 | } |
---|
[f1e012b] | 616 | |
---|
[adcc065] | 617 | // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the |
---|
| 618 | // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope |
---|
| 619 | // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user |
---|
| 620 | // of the error. See C++ Reference 6.6 Jump Statements for details. |
---|
[c2931ea] | 621 | void InsertDtors::handleGoto( BranchStmt * stmt ) { |
---|
[e39aa0f] | 622 | assert( stmt->get_target() != "" && "BranchStmt missing a label" ); |
---|
[c2931ea] | 623 | // S_L = lvars = set of objects in scope at label definition |
---|
| 624 | // S_G = curVars = set of objects in scope at goto statement |
---|
| 625 | ObjectSet & lvars = labelVars[ stmt->get_target() ]; |
---|
| 626 | |
---|
| 627 | DTOR_PRINT( |
---|
| 628 | std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl; |
---|
| 629 | std::cerr << "S_G = " << printSet( curVars ) << std::endl; |
---|
| 630 | std::cerr << "S_L = " << printSet( lvars ) << std::endl; |
---|
| 631 | ) |
---|
| 632 | |
---|
| 633 | ObjectSet diff; |
---|
| 634 | // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty |
---|
| 635 | std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) ); |
---|
| 636 | DTOR_PRINT( |
---|
| 637 | std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl; |
---|
| 638 | ) |
---|
| 639 | if ( ! diff.empty() ) { |
---|
| 640 | throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt ); |
---|
[adcc065] | 641 | } // if |
---|
[c2931ea] | 642 | // S_G-S_L results in set of objects that must be destructed |
---|
| 643 | diff.clear(); |
---|
| 644 | std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) ); |
---|
| 645 | DTOR_PRINT( |
---|
| 646 | std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl; |
---|
| 647 | ) |
---|
| 648 | if ( ! diff.empty() ) { |
---|
| 649 | // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor |
---|
| 650 | OrderedDecls ordered; |
---|
| 651 | for ( OrderedDecls & rdo : reverseDeclOrder ) { |
---|
| 652 | // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order. |
---|
| 653 | copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } ); |
---|
[adcc065] | 654 | } // for |
---|
[c2931ea] | 655 | insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) ); |
---|
[adcc065] | 656 | } // if |
---|
[c2931ea] | 657 | } |
---|
[39786813] | 658 | |
---|
[c2931ea] | 659 | void InsertDtors::visit( BranchStmt * stmt ) { |
---|
| 660 | switch( stmt->get_type() ) { |
---|
[adcc065] | 661 | case BranchStmt::Continue: |
---|
| 662 | case BranchStmt::Break: |
---|
| 663 | // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should |
---|
| 664 | // always be empty), but it serves as a small sanity check. |
---|
| 665 | case BranchStmt::Goto: |
---|
| 666 | handleGoto( stmt ); |
---|
| 667 | break; |
---|
| 668 | default: |
---|
| 669 | assert( false ); |
---|
| 670 | } // switch |
---|
[c2931ea] | 671 | } |
---|
| 672 | } // namespace |
---|
[71f4e4f] | 673 | } // namespace InitTweak |
---|
| 674 | |
---|
| 675 | // Local Variables: // |
---|
| 676 | // tab-width: 4 // |
---|
| 677 | // mode: c++ // |
---|
| 678 | // compile-command: "make install" // |
---|
| 679 | // End: // |
---|