[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> |
---|
[dc86541] | 20 | #include <unordered_map> |
---|
| 21 | #include <unordered_set> |
---|
[7b3f66b] | 22 | #include "InitTweak.h" |
---|
[6cf27a07] | 23 | #include "FixInit.h" |
---|
| 24 | #include "FixGlobalInit.h" |
---|
[db4ecc5] | 25 | #include "ResolvExpr/Resolver.h" |
---|
[845cedc] | 26 | #include "ResolvExpr/typeops.h" |
---|
[71f4e4f] | 27 | #include "SynTree/Declaration.h" |
---|
| 28 | #include "SynTree/Type.h" |
---|
| 29 | #include "SynTree/Expression.h" |
---|
[f9cebb5] | 30 | #include "SynTree/Attribute.h" |
---|
[71f4e4f] | 31 | #include "SynTree/Statement.h" |
---|
| 32 | #include "SynTree/Initializer.h" |
---|
| 33 | #include "SynTree/Mutator.h" |
---|
[db4ecc5] | 34 | #include "SymTab/Indexer.h" |
---|
[c8dfcd3] | 35 | #include "SymTab/Autogen.h" |
---|
[71f4e4f] | 36 | #include "GenPoly/PolyMutator.h" |
---|
[b6fe7e6] | 37 | #include "GenPoly/DeclMutator.h" |
---|
[c2931ea] | 38 | #include "SynTree/AddStmtVisitor.h" |
---|
[f0121d7] | 39 | #include "CodeGen/GenType.h" // for warning/error messages |
---|
[71f4e4f] | 40 | |
---|
[f0121d7] | 41 | bool ctordtorp = false; // print all debug |
---|
| 42 | bool ctorp = false; // print ctor debug |
---|
| 43 | bool cpctorp = false; // print copy ctor debug |
---|
| 44 | bool dtorp = false; // print dtor debug |
---|
[845cedc] | 45 | #define PRINT( text ) if ( ctordtorp ) { text } |
---|
[c2931ea] | 46 | #define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text } |
---|
| 47 | #define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text } |
---|
[845cedc] | 48 | |
---|
[71f4e4f] | 49 | namespace InitTweak { |
---|
| 50 | namespace { |
---|
[c2931ea] | 51 | class InsertImplicitCalls : public GenPoly::PolyMutator { |
---|
| 52 | public: |
---|
[adcc065] | 53 | /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which |
---|
| 54 | /// function calls need their parameters to be copy constructed |
---|
[c2931ea] | 55 | static void insert( std::list< Declaration * > & translationUnit ); |
---|
| 56 | |
---|
| 57 | virtual Expression * mutate( ApplicationExpr * appExpr ); |
---|
| 58 | }; |
---|
| 59 | |
---|
| 60 | class ResolveCopyCtors : public SymTab::Indexer { |
---|
| 61 | public: |
---|
[adcc065] | 62 | /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr, |
---|
| 63 | /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both |
---|
| 64 | /// arguments and return value temporaries |
---|
[c2931ea] | 65 | static void resolveImplicitCalls( std::list< Declaration * > & translationUnit ); |
---|
| 66 | |
---|
| 67 | virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
| 68 | |
---|
| 69 | /// create and resolve ctor/dtor expression: fname(var, [cpArg]) |
---|
[65660bd] | 70 | Expression * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL ); |
---|
| 71 | Expression * makeCtorDtor( const std::string & fname, Expression * thisArg, Expression * cpArg = NULL ); |
---|
[c2931ea] | 72 | /// true if type does not need to be copy constructed to ensure correctness |
---|
[1132b62] | 73 | bool skipCopyConstruct( Type * type ); |
---|
| 74 | void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
| 75 | void destructRet( Expression * ret, ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
[c2931ea] | 76 | private: |
---|
| 77 | TypeSubstitution * env; |
---|
| 78 | }; |
---|
| 79 | |
---|
| 80 | /// collects constructed object decls - used as a base class |
---|
| 81 | class ObjDeclCollector : public AddStmtVisitor { |
---|
| 82 | public: |
---|
| 83 | typedef AddStmtVisitor Parent; |
---|
| 84 | using Parent::visit; |
---|
| 85 | typedef std::set< ObjectDecl * > ObjectSet; |
---|
| 86 | virtual void visit( CompoundStmt *compoundStmt ); |
---|
| 87 | virtual void visit( DeclStmt *stmt ); |
---|
| 88 | protected: |
---|
| 89 | ObjectSet curVars; |
---|
| 90 | }; |
---|
| 91 | |
---|
[6cf27a07] | 92 | // debug |
---|
[c2931ea] | 93 | struct printSet { |
---|
| 94 | typedef ObjDeclCollector::ObjectSet ObjectSet; |
---|
| 95 | printSet( const ObjectSet & objs ) : objs( objs ) {} |
---|
| 96 | const ObjectSet & objs; |
---|
| 97 | }; |
---|
| 98 | std::ostream & operator<<( std::ostream & out, const printSet & set) { |
---|
| 99 | out << "{ "; |
---|
| 100 | for ( ObjectDecl * obj : set.objs ) { |
---|
| 101 | out << obj->get_name() << ", " ; |
---|
[adcc065] | 102 | } // for |
---|
[c2931ea] | 103 | out << " }"; |
---|
| 104 | return out; |
---|
| 105 | } |
---|
| 106 | |
---|
| 107 | class LabelFinder : public ObjDeclCollector { |
---|
| 108 | public: |
---|
| 109 | typedef ObjDeclCollector Parent; |
---|
| 110 | typedef std::map< Label, ObjectSet > LabelMap; |
---|
| 111 | // map of Label -> live variables at that label |
---|
| 112 | LabelMap vars; |
---|
| 113 | |
---|
| 114 | void handleStmt( Statement * stmt ); |
---|
| 115 | |
---|
| 116 | // xxx - This needs to be done better. |
---|
[adcc065] | 117 | // allow some generalization among different kinds of nodes with with similar parentage (e.g. all |
---|
| 118 | // expressions, all statements, etc.) important to have this to provide a single entry point so that as new |
---|
| 119 | // subclasses are added, there is only one place that the code has to be updated, rather than ensure that |
---|
| 120 | // every specialized class knows about every new kind of statement that might be added. |
---|
[c2931ea] | 121 | virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 122 | virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 123 | virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 124 | virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 125 | virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 126 | virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 127 | virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 128 | virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 129 | virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 130 | virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 131 | virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 132 | virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 133 | virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 134 | virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 135 | virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 136 | virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
| 137 | }; |
---|
| 138 | |
---|
| 139 | class InsertDtors : public ObjDeclCollector { |
---|
| 140 | public: |
---|
[adcc065] | 141 | /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed |
---|
| 142 | /// (currently by FixInit) |
---|
[c2931ea] | 143 | static void insert( std::list< Declaration * > & translationUnit ); |
---|
| 144 | |
---|
| 145 | typedef ObjDeclCollector Parent; |
---|
| 146 | typedef std::list< ObjectDecl * > OrderedDecls; |
---|
| 147 | typedef std::list< OrderedDecls > OrderedDeclsStack; |
---|
| 148 | |
---|
| 149 | InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {} |
---|
| 150 | |
---|
| 151 | virtual void visit( ObjectDecl * objDecl ); |
---|
| 152 | |
---|
| 153 | virtual void visit( CompoundStmt * compoundStmt ); |
---|
| 154 | virtual void visit( ReturnStmt * returnStmt ); |
---|
| 155 | virtual void visit( BranchStmt * stmt ); |
---|
| 156 | private: |
---|
| 157 | void handleGoto( BranchStmt * stmt ); |
---|
| 158 | |
---|
| 159 | LabelFinder::LabelMap & labelVars; |
---|
| 160 | OrderedDeclsStack reverseDeclOrder; |
---|
| 161 | }; |
---|
| 162 | |
---|
| 163 | class FixInit : public GenPoly::PolyMutator { |
---|
| 164 | public: |
---|
| 165 | /// expand each object declaration to use its constructor after it is declared. |
---|
| 166 | static void fixInitializers( std::list< Declaration * > &translationUnit ); |
---|
| 167 | |
---|
| 168 | virtual DeclarationWithType * mutate( ObjectDecl *objDecl ); |
---|
[72e9222] | 169 | |
---|
| 170 | std::list< Declaration * > staticDtorDecls; |
---|
[c2931ea] | 171 | }; |
---|
| 172 | |
---|
| 173 | class FixCopyCtors : public GenPoly::PolyMutator { |
---|
| 174 | public: |
---|
[adcc065] | 175 | /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression, |
---|
| 176 | /// and destructors |
---|
[c2931ea] | 177 | static void fixCopyCtors( std::list< Declaration * > &translationUnit ); |
---|
| 178 | |
---|
| 179 | virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
| 180 | }; |
---|
[79970ed] | 181 | |
---|
[c8dfcd3] | 182 | class GenStructMemberCalls : public SymTab::Indexer { |
---|
[79970ed] | 183 | public: |
---|
[c8dfcd3] | 184 | typedef Indexer Parent; |
---|
| 185 | /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors |
---|
| 186 | /// for any member that is missing a corresponding ctor/dtor call. |
---|
| 187 | /// error if a member is used before constructed |
---|
| 188 | static void generate( std::list< Declaration * > & translationUnit ); |
---|
[79970ed] | 189 | |
---|
| 190 | virtual void visit( FunctionDecl * funcDecl ); |
---|
| 191 | |
---|
| 192 | virtual void visit( MemberExpr * memberExpr ); |
---|
| 193 | virtual void visit( ApplicationExpr * appExpr ); |
---|
| 194 | |
---|
[3906301] | 195 | SemanticError errors; |
---|
[79970ed] | 196 | private: |
---|
| 197 | void handleFirstParam( Expression * firstParam ); |
---|
[3906301] | 198 | template< typename... Params > |
---|
| 199 | void emit( const Params &... params ); |
---|
[79970ed] | 200 | |
---|
| 201 | FunctionDecl * function = 0; |
---|
[c8dfcd3] | 202 | std::set< DeclarationWithType * > unhandled, usedUninit; |
---|
[79970ed] | 203 | ObjectDecl * thisParam = 0; |
---|
[c8dfcd3] | 204 | bool isCtor = false; // true if current function is a constructor |
---|
[44f6341] | 205 | StructDecl * structDecl = 0; |
---|
[c8dfcd3] | 206 | }; |
---|
| 207 | |
---|
| 208 | // very simple resolver-like mutator class - used to |
---|
| 209 | // resolve UntypedExprs that are found within newly |
---|
| 210 | // generated constructor/destructor calls |
---|
| 211 | class MutatingResolver : public Mutator { |
---|
| 212 | public: |
---|
| 213 | MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {} |
---|
| 214 | |
---|
| 215 | virtual DeclarationWithType* mutate( ObjectDecl *objectDecl ); |
---|
| 216 | |
---|
| 217 | virtual Expression* mutate( UntypedExpr *untypedExpr ); |
---|
| 218 | private: |
---|
| 219 | SymTab::Indexer & indexer; |
---|
[79970ed] | 220 | }; |
---|
[b6fe7e6] | 221 | |
---|
| 222 | class FixCtorExprs : public GenPoly::DeclMutator { |
---|
| 223 | public: |
---|
| 224 | /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument |
---|
| 225 | static void fix( std::list< Declaration * > & translationUnit ); |
---|
| 226 | |
---|
| 227 | virtual Expression * mutate( ConstructorExpr * ctorExpr ); |
---|
| 228 | }; |
---|
[c2931ea] | 229 | } // namespace |
---|
[db4ecc5] | 230 | |
---|
[6cf27a07] | 231 | void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) { |
---|
| 232 | // fixes ConstructorInit for global variables. should happen before fixInitializers. |
---|
| 233 | InitTweak::fixGlobalInit( translationUnit, filename, inLibrary ); |
---|
| 234 | |
---|
[b6fe7e6] | 235 | |
---|
[db4ecc5] | 236 | InsertImplicitCalls::insert( translationUnit ); |
---|
| 237 | ResolveCopyCtors::resolveImplicitCalls( translationUnit ); |
---|
[c2931ea] | 238 | InsertDtors::insert( translationUnit ); |
---|
[71f4e4f] | 239 | FixInit::fixInitializers( translationUnit ); |
---|
[c2931ea] | 240 | |
---|
[db4ecc5] | 241 | // FixCopyCtors must happen after FixInit, so that destructors are placed correctly |
---|
| 242 | FixCopyCtors::fixCopyCtors( translationUnit ); |
---|
[79970ed] | 243 | |
---|
[c8dfcd3] | 244 | GenStructMemberCalls::generate( translationUnit ); |
---|
[b6fe7e6] | 245 | // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a |
---|
| 246 | // hack in the way untyped assignments are generated, where the first argument cannot have |
---|
| 247 | // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr. |
---|
| 248 | // Thus such assignment exprs must never pushed through expression resolution (and thus should |
---|
| 249 | // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed. |
---|
| 250 | // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs |
---|
| 251 | // don't look right, and a member can be constructed more than once. |
---|
| 252 | FixCtorExprs::fix( translationUnit ); |
---|
[db4ecc5] | 253 | } |
---|
| 254 | |
---|
[c2931ea] | 255 | namespace { |
---|
| 256 | void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) { |
---|
| 257 | InsertImplicitCalls inserter; |
---|
| 258 | mutateAll( translationUnit, inserter ); |
---|
| 259 | } |
---|
[db4ecc5] | 260 | |
---|
[c2931ea] | 261 | void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) { |
---|
| 262 | ResolveCopyCtors resolver; |
---|
| 263 | acceptAll( translationUnit, resolver ); |
---|
| 264 | } |
---|
[71f4e4f] | 265 | |
---|
[c2931ea] | 266 | void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) { |
---|
| 267 | FixInit fixer; |
---|
[72e9222] | 268 | |
---|
| 269 | // can't use mutateAll, because need to insert declarations at top-level |
---|
| 270 | // can't use DeclMutator, because sometimes need to insert IfStmt, etc. |
---|
| 271 | SemanticError errors; |
---|
| 272 | for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) { |
---|
| 273 | try { |
---|
| 274 | *i = maybeMutate( *i, fixer ); |
---|
[f9cebb5] | 275 | translationUnit.splice( i, fixer.staticDtorDecls ); |
---|
[72e9222] | 276 | } catch( SemanticError &e ) { |
---|
| 277 | errors.append( e ); |
---|
| 278 | } // try |
---|
| 279 | } // for |
---|
| 280 | if ( ! errors.isEmpty() ) { |
---|
| 281 | throw errors; |
---|
| 282 | } // if |
---|
[c2931ea] | 283 | } |
---|
[71f4e4f] | 284 | |
---|
[c2931ea] | 285 | void InsertDtors::insert( std::list< Declaration * > & translationUnit ) { |
---|
| 286 | LabelFinder finder; |
---|
| 287 | InsertDtors inserter( finder ); |
---|
| 288 | acceptAll( translationUnit, finder ); |
---|
| 289 | acceptAll( translationUnit, inserter ); |
---|
| 290 | } |
---|
| 291 | |
---|
| 292 | void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) { |
---|
| 293 | FixCopyCtors fixer; |
---|
| 294 | mutateAll( translationUnit, fixer ); |
---|
| 295 | } |
---|
[db4ecc5] | 296 | |
---|
[c8dfcd3] | 297 | void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) { |
---|
| 298 | GenStructMemberCalls warner; |
---|
| 299 | acceptAll( translationUnit, warner ); |
---|
[3906301] | 300 | |
---|
[c8dfcd3] | 301 | // visitor doesn't throw so that it can collect all errors |
---|
| 302 | if ( ! warner.errors.isEmpty() ) { |
---|
| 303 | throw warner.errors; |
---|
[79970ed] | 304 | } |
---|
| 305 | } |
---|
| 306 | |
---|
[b6fe7e6] | 307 | void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) { |
---|
| 308 | FixCtorExprs fixer; |
---|
| 309 | fixer.mutateDeclarationList( translationUnit ); |
---|
| 310 | } |
---|
| 311 | |
---|
[c2931ea] | 312 | Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) { |
---|
| 313 | appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) ); |
---|
| 314 | assert( appExpr ); |
---|
| 315 | |
---|
| 316 | if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) { |
---|
| 317 | if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) { |
---|
| 318 | // optimization: don't need to copy construct in order to call intrinsic functions |
---|
| 319 | return appExpr; |
---|
| 320 | } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) { |
---|
| 321 | FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) ); |
---|
| 322 | assert( ftype ); |
---|
[79970ed] | 323 | if ( (isConstructor( funcDecl->get_name() ) || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) { |
---|
[c2931ea] | 324 | Type * t1 = ftype->get_parameters().front()->get_type(); |
---|
| 325 | Type * t2 = ftype->get_parameters().back()->get_type(); |
---|
| 326 | PointerType * ptrType = dynamic_cast< PointerType * > ( t1 ); |
---|
| 327 | assert( ptrType ); |
---|
| 328 | |
---|
| 329 | if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) { |
---|
| 330 | // optimization: don't need to copy construct in order to call a copy constructor or |
---|
| 331 | // assignment operator |
---|
| 332 | return appExpr; |
---|
[adcc065] | 333 | } // if |
---|
[79970ed] | 334 | } else if ( isDestructor( funcDecl->get_name() ) ) { |
---|
[c2931ea] | 335 | // correctness: never copy construct arguments to a destructor |
---|
[845cedc] | 336 | return appExpr; |
---|
[adcc065] | 337 | } // if |
---|
| 338 | } // if |
---|
| 339 | } // if |
---|
[c2931ea] | 340 | CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; ) |
---|
| 341 | |
---|
| 342 | // wrap each function call so that it is easy to identify nodes that have to be copy constructed |
---|
| 343 | ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr ); |
---|
| 344 | // save the type substitution onto the new node so that it is easy to find. |
---|
| 345 | // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion. |
---|
| 346 | // The substitution is needed to obtain the type of temporary variables so that copy constructor |
---|
| 347 | // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves |
---|
| 348 | // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which |
---|
| 349 | // saves the environment, or compute the types of temporaries here, but it's much simpler to |
---|
| 350 | // save the environment here, and more cohesive to compute temporary variables and resolve copy |
---|
| 351 | // constructor calls together. |
---|
| 352 | assert( env ); |
---|
| 353 | expr->set_env( env ); |
---|
| 354 | return expr; |
---|
[db4ecc5] | 355 | } |
---|
| 356 | |
---|
[c2931ea] | 357 | bool ResolveCopyCtors::skipCopyConstruct( Type * type ) { |
---|
| 358 | return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type ); |
---|
| 359 | } |
---|
| 360 | |
---|
[65660bd] | 361 | Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) { |
---|
[c2931ea] | 362 | assert( var ); |
---|
[1132b62] | 363 | return makeCtorDtor( fname, new AddressExpr( new VariableExpr( var ) ), cpArg ); |
---|
| 364 | } |
---|
| 365 | |
---|
[65660bd] | 366 | Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, Expression * thisArg, Expression * cpArg ) { |
---|
[1132b62] | 367 | assert( thisArg ); |
---|
[c2931ea] | 368 | UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) ); |
---|
[1132b62] | 369 | untyped->get_args().push_back( thisArg ); |
---|
[03b812d2] | 370 | if (cpArg) untyped->get_args().push_back( cpArg->clone() ); |
---|
[c2931ea] | 371 | |
---|
| 372 | // resolve copy constructor |
---|
[adcc065] | 373 | // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed |
---|
| 374 | // (VariableExpr and already resolved expression) |
---|
[c2931ea] | 375 | CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; ) |
---|
[65660bd] | 376 | Expression * resolved = ResolvExpr::findVoidExpression( untyped, *this ); |
---|
| 377 | assert( resolved ); |
---|
[c2931ea] | 378 | if ( resolved->get_env() ) { |
---|
| 379 | env->add( *resolved->get_env() ); |
---|
[adcc065] | 380 | } // if |
---|
[cf18eea] | 381 | |
---|
[c2931ea] | 382 | delete untyped; |
---|
| 383 | return resolved; |
---|
[540de412] | 384 | } |
---|
[db4ecc5] | 385 | |
---|
[1132b62] | 386 | void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ) { |
---|
[c2931ea] | 387 | static UniqueName tempNamer("_tmp_cp"); |
---|
[1132b62] | 388 | CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; ) |
---|
| 389 | assert( arg->has_result() ); |
---|
| 390 | Type * result = arg->get_result(); |
---|
| 391 | if ( skipCopyConstruct( result ) ) return; // skip certain non-copyable types |
---|
| 392 | |
---|
| 393 | // type may involve type variables, so apply type substitution to get temporary variable's actual type |
---|
| 394 | result = result->clone(); |
---|
| 395 | impCpCtorExpr->get_env()->apply( result ); |
---|
| 396 | ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 ); |
---|
| 397 | tmp->get_type()->set_isConst( false ); |
---|
| 398 | |
---|
| 399 | // create and resolve copy constructor |
---|
| 400 | CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; ) |
---|
[65660bd] | 401 | Expression * cpCtor = makeCtorDtor( "?{}", tmp, arg ); |
---|
| 402 | |
---|
| 403 | if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( cpCtor ) ) { |
---|
| 404 | // if the chosen constructor is intrinsic, the copy is unnecessary, so |
---|
| 405 | // don't create the temporary and don't call the copy constructor |
---|
| 406 | VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() ); |
---|
| 407 | assert( function ); |
---|
| 408 | if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) return; |
---|
| 409 | } |
---|
| 410 | |
---|
| 411 | // replace argument to function call with temporary |
---|
| 412 | arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) ); |
---|
| 413 | impCpCtorExpr->get_tempDecls().push_back( tmp ); |
---|
| 414 | impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) ); |
---|
[1132b62] | 415 | } |
---|
[c2931ea] | 416 | |
---|
[1132b62] | 417 | void ResolveCopyCtors::destructRet( Expression * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) { |
---|
| 418 | impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", new AddressExpr( ret ) ) ); |
---|
| 419 | } |
---|
| 420 | |
---|
| 421 | void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) { |
---|
[c2931ea] | 422 | CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; ) |
---|
| 423 | Visitor::visit( impCpCtorExpr ); |
---|
| 424 | env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer... |
---|
| 425 | |
---|
| 426 | ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr(); |
---|
| 427 | |
---|
| 428 | // take each argument and attempt to copy construct it. |
---|
| 429 | for ( Expression * & arg : appExpr->get_args() ) { |
---|
[1132b62] | 430 | copyConstructArg( arg, impCpCtorExpr ); |
---|
[adcc065] | 431 | } // for |
---|
[db4ecc5] | 432 | |
---|
[adcc065] | 433 | // each return value from the call needs to be connected with an ObjectDecl at the call site, which is |
---|
| 434 | // initialized with the return value and is destructed later |
---|
[c2931ea] | 435 | // xxx - handle multiple return values |
---|
| 436 | ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr(); |
---|
[adcc065] | 437 | // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher |
---|
| 438 | // level. Trying to pass that environment along. |
---|
[c2931ea] | 439 | callExpr->set_env( impCpCtorExpr->get_env()->clone() ); |
---|
[906e24d] | 440 | Type * result = appExpr->get_result(); |
---|
| 441 | if ( ! result->isVoid() ) { |
---|
[1132b62] | 442 | static UniqueName retNamer("_tmp_cp_ret"); |
---|
[c2931ea] | 443 | result = result->clone(); |
---|
| 444 | impCpCtorExpr->get_env()->apply( result ); |
---|
| 445 | ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 ); |
---|
| 446 | ret->get_type()->set_isConst( false ); |
---|
| 447 | impCpCtorExpr->get_returnDecls().push_back( ret ); |
---|
| 448 | CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; ) |
---|
[dc86541] | 449 | if ( ! result->get_isLvalue() ) { |
---|
| 450 | // destructing lvalue returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary |
---|
| 451 | destructRet( new VariableExpr( ret ), impCpCtorExpr ); |
---|
| 452 | } |
---|
[adcc065] | 453 | } // for |
---|
[c2931ea] | 454 | CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; ) |
---|
[db4ecc5] | 455 | } |
---|
| 456 | |
---|
| 457 | |
---|
[c2931ea] | 458 | Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) { |
---|
| 459 | CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; ) |
---|
| 460 | |
---|
| 461 | impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) ); |
---|
| 462 | assert( impCpCtorExpr ); |
---|
[db4ecc5] | 463 | |
---|
[c2931ea] | 464 | std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls(); |
---|
| 465 | std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls(); |
---|
| 466 | std::list< Expression * > & dtors = impCpCtorExpr->get_dtors(); |
---|
[845cedc] | 467 | |
---|
[c2931ea] | 468 | // add all temporary declarations and their constructors |
---|
| 469 | for ( ObjectDecl * obj : tempDecls ) { |
---|
| 470 | stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) ); |
---|
[adcc065] | 471 | } // for |
---|
[c2931ea] | 472 | for ( ObjectDecl * obj : returnDecls ) { |
---|
| 473 | stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) ); |
---|
[adcc065] | 474 | } // for |
---|
[db4ecc5] | 475 | |
---|
[c2931ea] | 476 | // add destructors after current statement |
---|
| 477 | for ( Expression * dtor : dtors ) { |
---|
| 478 | stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) ); |
---|
[adcc065] | 479 | } // for |
---|
[db4ecc5] | 480 | |
---|
[c2931ea] | 481 | // xxx - update to work with multiple return values |
---|
| 482 | ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front(); |
---|
| 483 | Expression * callExpr = impCpCtorExpr->get_callExpr(); |
---|
| 484 | |
---|
| 485 | CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; ) |
---|
| 486 | |
---|
| 487 | // detach fields from wrapper node so that it can be deleted without deleting too much |
---|
| 488 | dtors.clear(); |
---|
| 489 | tempDecls.clear(); |
---|
| 490 | returnDecls.clear(); |
---|
| 491 | impCpCtorExpr->set_callExpr( NULL ); |
---|
| 492 | impCpCtorExpr->set_env( NULL ); |
---|
| 493 | delete impCpCtorExpr; |
---|
| 494 | |
---|
| 495 | if ( returnDecl ) { |
---|
| 496 | UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
| 497 | assign->get_args().push_back( new VariableExpr( returnDecl ) ); |
---|
| 498 | assign->get_args().push_back( callExpr ); |
---|
| 499 | // know the result type of the assignment is the type of the LHS (minus the pointer), so |
---|
| 500 | // add that onto the assignment expression so that later steps have the necessary information |
---|
[906e24d] | 501 | assign->set_result( returnDecl->get_type()->clone() ); |
---|
[c2931ea] | 502 | |
---|
| 503 | Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) ); |
---|
[906e24d] | 504 | if ( callExpr->get_result()->get_isLvalue() ) { |
---|
[adcc065] | 505 | // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning |
---|
| 506 | // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the |
---|
| 507 | // type of the return temporary from T to T* to properly capture the return value. Then dereference |
---|
| 508 | // the result of the comma expression, since the lvalue returning call was originally wrapped with |
---|
| 509 | // an AddressExpr. Effectively, this turns |
---|
[c2931ea] | 510 | // lvalue T f(); |
---|
[b3b2077] | 511 | // &*f(); |
---|
[c2931ea] | 512 | // into |
---|
[b3b2077] | 513 | // T * f(); |
---|
[c2931ea] | 514 | // T * tmp_cp_retN; |
---|
[b3b2077] | 515 | // &*(tmp_cp_retN = &*f(), tmp_cp_retN); // the first * and second & are generated here |
---|
[c2931ea] | 516 | // which work out in terms of types, but is pretty messy. It would be nice to find a better way. |
---|
| 517 | assign->get_args().back() = new AddressExpr( assign->get_args().back() ); |
---|
| 518 | |
---|
| 519 | returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) ); |
---|
[b3b2077] | 520 | retExpr->set_result( new PointerType( Type::Qualifiers(), retExpr->get_result() ) ); |
---|
| 521 | retExpr = UntypedExpr::createDeref( retExpr ); |
---|
[adcc065] | 522 | } // if |
---|
[b6fe7e6] | 523 | retExpr->set_env( env->clone() ); |
---|
[c2931ea] | 524 | return retExpr; |
---|
| 525 | } else { |
---|
| 526 | return callExpr; |
---|
[adcc065] | 527 | } // if |
---|
[4ffdd63] | 528 | } |
---|
[c2931ea] | 529 | |
---|
| 530 | DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) { |
---|
[adcc065] | 531 | // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init |
---|
| 532 | // is removed from the ObjectDecl |
---|
[c2931ea] | 533 | objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) ); |
---|
| 534 | |
---|
| 535 | if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) { |
---|
| 536 | // a decision should have been made by the resolver, so ctor and init are not both non-NULL |
---|
| 537 | assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() ); |
---|
| 538 | if ( Statement * ctor = ctorInit->get_ctor() ) { |
---|
| 539 | if ( objDecl->get_storageClass() == DeclarationNode::Static ) { |
---|
[72e9222] | 540 | // originally wanted to take advantage of gcc nested functions, but |
---|
[f9cebb5] | 541 | // we get memory errors with this approach. To remedy this, the static |
---|
| 542 | // variable is hoisted when the destructor needs to be called. |
---|
[72e9222] | 543 | // |
---|
[c2931ea] | 544 | // generate: |
---|
[f9cebb5] | 545 | // static T __objName_static_varN; |
---|
[72e9222] | 546 | // void __objName_dtor_atexitN() { |
---|
[f9cebb5] | 547 | // __dtor__...; |
---|
[72e9222] | 548 | // } |
---|
| 549 | // int f(...) { |
---|
| 550 | // ... |
---|
| 551 | // static bool __objName_uninitialized = true; |
---|
| 552 | // if (__objName_uninitialized) { |
---|
| 553 | // __ctor(__objName); |
---|
| 554 | // __objName_uninitialized = false; |
---|
[f9cebb5] | 555 | // atexit(__objName_dtor_atexitN); |
---|
[c2931ea] | 556 | // } |
---|
[72e9222] | 557 | // ... |
---|
[c2931ea] | 558 | // } |
---|
| 559 | |
---|
[72e9222] | 560 | static UniqueName dtorCallerNamer( "_dtor_atexit" ); |
---|
| 561 | |
---|
| 562 | // static bool __objName_uninitialized = true |
---|
[c2931ea] | 563 | BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool ); |
---|
| 564 | SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators ); |
---|
| 565 | ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr ); |
---|
| 566 | isUninitializedVar->fixUniqueId(); |
---|
| 567 | |
---|
| 568 | // __objName_uninitialized = false; |
---|
| 569 | UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
| 570 | setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) ); |
---|
| 571 | setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) ); |
---|
| 572 | |
---|
| 573 | // generate body of if |
---|
| 574 | CompoundStmt * initStmts = new CompoundStmt( noLabels ); |
---|
| 575 | std::list< Statement * > & body = initStmts->get_kids(); |
---|
| 576 | body.push_back( ctor ); |
---|
| 577 | body.push_back( new ExprStmt( noLabels, setTrue ) ); |
---|
| 578 | |
---|
| 579 | // put it all together |
---|
| 580 | IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 ); |
---|
| 581 | stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) ); |
---|
| 582 | stmtsToAddAfter.push_back( ifStmt ); |
---|
[72e9222] | 583 | |
---|
[f9cebb5] | 584 | if ( ctorInit->get_dtor() ) { |
---|
| 585 | // if the object has a non-trivial destructor, have to |
---|
| 586 | // hoist it and the object into the global space and |
---|
| 587 | // call the destructor function with atexit. |
---|
| 588 | |
---|
| 589 | Statement * dtorStmt = ctorInit->get_dtor()->clone(); |
---|
| 590 | |
---|
| 591 | // void __objName_dtor_atexitN(...) {...} |
---|
| 592 | FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false ); |
---|
| 593 | dtorCaller->fixUniqueId(); |
---|
[c8dfcd3] | 594 | dtorCaller->get_statements()->push_back( dtorStmt ); |
---|
[f9cebb5] | 595 | |
---|
| 596 | // atexit(dtor_atexit); |
---|
| 597 | UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) ); |
---|
| 598 | callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) ); |
---|
| 599 | |
---|
| 600 | body.push_back( new ExprStmt( noLabels, callAtexit ) ); |
---|
| 601 | |
---|
| 602 | // hoist variable and dtor caller decls to list of decls that will be added into global scope |
---|
| 603 | staticDtorDecls.push_back( objDecl ); |
---|
| 604 | staticDtorDecls.push_back( dtorCaller ); |
---|
| 605 | |
---|
| 606 | // need to rename object uniquely since it now appears |
---|
| 607 | // at global scope and there could be multiple function-scoped |
---|
| 608 | // static variables with the same name in different functions. |
---|
[c8dfcd3] | 609 | // Note: it isn't sufficient to modify only the mangleName, because |
---|
| 610 | // then subsequent Indexer passes can choke on seeing the object's name |
---|
| 611 | // if another object has the same name and type. An unfortunate side-effect |
---|
| 612 | // of renaming the object is that subsequent NameExprs may fail to resolve, |
---|
| 613 | // but there shouldn't be any remaining past this point. |
---|
[f9cebb5] | 614 | static UniqueName staticNamer( "_static_var" ); |
---|
[c8dfcd3] | 615 | objDecl->set_name( objDecl->get_name() + staticNamer.newName() ); |
---|
| 616 | objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) ); |
---|
[f9cebb5] | 617 | |
---|
| 618 | objDecl->set_init( NULL ); |
---|
| 619 | ctorInit->set_ctor( NULL ); |
---|
| 620 | delete ctorInit; |
---|
| 621 | |
---|
| 622 | // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope |
---|
| 623 | // create a new object which is never used |
---|
| 624 | static UniqueName dummyNamer( "_dummy" ); |
---|
| 625 | 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") } ); |
---|
| 626 | return dummy; |
---|
| 627 | } |
---|
[c2931ea] | 628 | } else { |
---|
| 629 | stmtsToAddAfter.push_back( ctor ); |
---|
[adcc065] | 630 | } // if |
---|
[c2931ea] | 631 | objDecl->set_init( NULL ); |
---|
| 632 | ctorInit->set_ctor( NULL ); |
---|
| 633 | } else if ( Initializer * init = ctorInit->get_init() ) { |
---|
| 634 | objDecl->set_init( init ); |
---|
| 635 | ctorInit->set_init( NULL ); |
---|
| 636 | } else { |
---|
| 637 | // no constructor and no initializer, which is okay |
---|
| 638 | objDecl->set_init( NULL ); |
---|
[adcc065] | 639 | } // if |
---|
[c2931ea] | 640 | delete ctorInit; |
---|
[adcc065] | 641 | } // if |
---|
[c2931ea] | 642 | return objDecl; |
---|
[db4ecc5] | 643 | } |
---|
| 644 | |
---|
[c2931ea] | 645 | void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) { |
---|
| 646 | std::set< ObjectDecl * > prevVars = curVars; |
---|
| 647 | Parent::visit( compoundStmt ); |
---|
| 648 | curVars = prevVars; |
---|
[db4ecc5] | 649 | } |
---|
| 650 | |
---|
[c2931ea] | 651 | void ObjDeclCollector::visit( DeclStmt *stmt ) { |
---|
[4b2589a] | 652 | // keep track of all variables currently in scope |
---|
[c2931ea] | 653 | if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) { |
---|
| 654 | curVars.insert( objDecl ); |
---|
[adcc065] | 655 | } // if |
---|
[e39aa0f] | 656 | Parent::visit( stmt ); |
---|
[db4ecc5] | 657 | } |
---|
| 658 | |
---|
[c2931ea] | 659 | void LabelFinder::handleStmt( Statement * stmt ) { |
---|
[4b2589a] | 660 | // for each label, remember the variables in scope at that label. |
---|
[c2931ea] | 661 | for ( Label l : stmt->get_labels() ) { |
---|
| 662 | vars[l] = curVars; |
---|
[adcc065] | 663 | } // for |
---|
[71f4e4f] | 664 | } |
---|
[f1e012b] | 665 | |
---|
[ec79847] | 666 | template<typename Iterator, typename OutputIterator> |
---|
| 667 | void insertDtors( Iterator begin, Iterator end, OutputIterator out ) { |
---|
| 668 | for ( Iterator it = begin ; it != end ; ++it ) { |
---|
[adcc065] | 669 | // extract destructor statement from the object decl and insert it into the output. Note that this is |
---|
| 670 | // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually |
---|
| 671 | // calls an intrinsic dtor then the call must (and will) still be generated since the argument may |
---|
| 672 | // contain side effects. |
---|
[c2931ea] | 673 | ObjectDecl * objDecl = *it; |
---|
| 674 | ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ); |
---|
| 675 | assert( ctorInit && ctorInit->get_dtor() ); |
---|
| 676 | *out++ = ctorInit->get_dtor()->clone(); |
---|
[adcc065] | 677 | } // for |
---|
[f1e012b] | 678 | } |
---|
[39786813] | 679 | |
---|
[c2931ea] | 680 | void InsertDtors::visit( ObjectDecl * objDecl ) { |
---|
| 681 | // remember non-static destructed objects so that their destructors can be inserted later |
---|
| 682 | if ( objDecl->get_storageClass() != DeclarationNode::Static ) { |
---|
| 683 | if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) { |
---|
| 684 | // a decision should have been made by the resolver, so ctor and init are not both non-NULL |
---|
| 685 | assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() ); |
---|
| 686 | Statement * dtor = ctorInit->get_dtor(); |
---|
[f9cebb5] | 687 | if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) { |
---|
[c2931ea] | 688 | // don't need to call intrinsic dtor, because it does nothing, but |
---|
| 689 | // non-intrinsic dtors must be called |
---|
| 690 | reverseDeclOrder.front().push_front( objDecl ); |
---|
[adcc065] | 691 | } // if |
---|
| 692 | } // if |
---|
| 693 | } // if |
---|
[c2931ea] | 694 | Parent::visit( objDecl ); |
---|
| 695 | } |
---|
[39786813] | 696 | |
---|
[c2931ea] | 697 | void InsertDtors::visit( CompoundStmt * compoundStmt ) { |
---|
[adcc065] | 698 | // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors |
---|
| 699 | // when block is left, just the destructors associated with variables defined in this block, so push a new |
---|
| 700 | // list to the top of the stack so that we can differentiate scopes |
---|
[c2931ea] | 701 | reverseDeclOrder.push_front( OrderedDecls() ); |
---|
| 702 | Parent::visit( compoundStmt ); |
---|
[39786813] | 703 | |
---|
[4b2589a] | 704 | // add destructors for the current scope that we're exiting |
---|
[c2931ea] | 705 | std::list< Statement * > & statements = compoundStmt->get_kids(); |
---|
| 706 | insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) ); |
---|
| 707 | reverseDeclOrder.pop_front(); |
---|
[39786813] | 708 | } |
---|
| 709 | |
---|
[c2931ea] | 710 | void InsertDtors::visit( ReturnStmt * returnStmt ) { |
---|
[4b2589a] | 711 | // return exits all scopes, so dump destructors for all scopes |
---|
[c2931ea] | 712 | for ( OrderedDecls & od : reverseDeclOrder ) { |
---|
| 713 | insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) ); |
---|
[adcc065] | 714 | } // for |
---|
[39786813] | 715 | } |
---|
[f1e012b] | 716 | |
---|
[adcc065] | 717 | // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the |
---|
| 718 | // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope |
---|
| 719 | // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user |
---|
| 720 | // of the error. See C++ Reference 6.6 Jump Statements for details. |
---|
[c2931ea] | 721 | void InsertDtors::handleGoto( BranchStmt * stmt ) { |
---|
[e39aa0f] | 722 | assert( stmt->get_target() != "" && "BranchStmt missing a label" ); |
---|
[c2931ea] | 723 | // S_L = lvars = set of objects in scope at label definition |
---|
| 724 | // S_G = curVars = set of objects in scope at goto statement |
---|
| 725 | ObjectSet & lvars = labelVars[ stmt->get_target() ]; |
---|
| 726 | |
---|
| 727 | DTOR_PRINT( |
---|
| 728 | std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl; |
---|
| 729 | std::cerr << "S_G = " << printSet( curVars ) << std::endl; |
---|
| 730 | std::cerr << "S_L = " << printSet( lvars ) << std::endl; |
---|
| 731 | ) |
---|
| 732 | |
---|
| 733 | ObjectSet diff; |
---|
| 734 | // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty |
---|
| 735 | std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) ); |
---|
| 736 | DTOR_PRINT( |
---|
| 737 | std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl; |
---|
| 738 | ) |
---|
| 739 | if ( ! diff.empty() ) { |
---|
| 740 | throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt ); |
---|
[adcc065] | 741 | } // if |
---|
[c2931ea] | 742 | // S_G-S_L results in set of objects that must be destructed |
---|
| 743 | diff.clear(); |
---|
| 744 | std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) ); |
---|
| 745 | DTOR_PRINT( |
---|
| 746 | std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl; |
---|
| 747 | ) |
---|
| 748 | if ( ! diff.empty() ) { |
---|
| 749 | // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor |
---|
| 750 | OrderedDecls ordered; |
---|
| 751 | for ( OrderedDecls & rdo : reverseDeclOrder ) { |
---|
| 752 | // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order. |
---|
| 753 | copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } ); |
---|
[adcc065] | 754 | } // for |
---|
[c2931ea] | 755 | insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) ); |
---|
[adcc065] | 756 | } // if |
---|
[c2931ea] | 757 | } |
---|
[39786813] | 758 | |
---|
[c2931ea] | 759 | void InsertDtors::visit( BranchStmt * stmt ) { |
---|
| 760 | switch( stmt->get_type() ) { |
---|
[adcc065] | 761 | case BranchStmt::Continue: |
---|
| 762 | case BranchStmt::Break: |
---|
| 763 | // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should |
---|
| 764 | // always be empty), but it serves as a small sanity check. |
---|
| 765 | case BranchStmt::Goto: |
---|
| 766 | handleGoto( stmt ); |
---|
| 767 | break; |
---|
| 768 | default: |
---|
| 769 | assert( false ); |
---|
| 770 | } // switch |
---|
[c2931ea] | 771 | } |
---|
[79970ed] | 772 | |
---|
| 773 | bool checkWarnings( FunctionDecl * funcDecl ) { |
---|
| 774 | // only check for warnings if the current function is a user-defined |
---|
| 775 | // constructor or destructor |
---|
| 776 | if ( ! funcDecl ) return false; |
---|
| 777 | if ( ! funcDecl->get_statements() ) return false; |
---|
| 778 | return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() ); |
---|
| 779 | } |
---|
| 780 | |
---|
[c8dfcd3] | 781 | void GenStructMemberCalls::visit( FunctionDecl * funcDecl ) { |
---|
| 782 | ValueGuard< FunctionDecl * > oldFunction( funcDecl ); |
---|
| 783 | ValueGuard< std::set< DeclarationWithType * > > oldUnhandled( unhandled ); |
---|
| 784 | ValueGuard< std::set< DeclarationWithType * > > oldUsedUninit( usedUninit ); |
---|
| 785 | ValueGuard< ObjectDecl * > oldThisParam( thisParam ); |
---|
| 786 | ValueGuard< bool > oldIsCtor( isCtor ); |
---|
[44f6341] | 787 | ValueGuard< StructDecl * > oldStructDecl( structDecl ); |
---|
[c8dfcd3] | 788 | |
---|
| 789 | // need to start with fresh sets |
---|
| 790 | unhandled.clear(); |
---|
| 791 | usedUninit.clear(); |
---|
[79970ed] | 792 | |
---|
| 793 | function = funcDecl; |
---|
[c8dfcd3] | 794 | isCtor = isConstructor( function->get_name() ); |
---|
| 795 | if ( checkWarnings( function ) ) { |
---|
| 796 | FunctionType * type = function->get_functionType(); |
---|
[79970ed] | 797 | assert( ! type->get_parameters().empty() ); |
---|
| 798 | thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() ); |
---|
| 799 | PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() ); |
---|
| 800 | StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() ); |
---|
| 801 | if ( structType ) { |
---|
[44f6341] | 802 | structDecl = structType->get_baseStruct(); |
---|
[79970ed] | 803 | for ( Declaration * member : structDecl->get_members() ) { |
---|
| 804 | if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) { |
---|
| 805 | // record all of the struct type's members that need to be constructed or |
---|
| 806 | // destructed by the end of the function |
---|
| 807 | unhandled.insert( field ); |
---|
| 808 | } |
---|
| 809 | } |
---|
| 810 | } |
---|
| 811 | } |
---|
[c8dfcd3] | 812 | Parent::visit( function ); |
---|
| 813 | |
---|
| 814 | // remove the unhandled objects from usedUninit, because a call is inserted |
---|
| 815 | // to handle them - only objects that are later constructed are used uninitialized. |
---|
| 816 | std::set< DeclarationWithType * > diff; |
---|
| 817 | std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ) ); |
---|
| 818 | for ( DeclarationWithType * member : diff ) { |
---|
[44f6341] | 819 | emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", member->get_name(), " used before being constructed" ); |
---|
[79970ed] | 820 | } |
---|
| 821 | |
---|
[c8dfcd3] | 822 | if ( ! unhandled.empty() ) { |
---|
| 823 | // need to explicitly re-add function parameters in order to resolve copy constructors |
---|
| 824 | enterScope(); |
---|
[b16898e] | 825 | maybeAccept( function->get_functionType(), *this ); |
---|
[44f6341] | 826 | |
---|
| 827 | // need to iterate through members in reverse in order for |
---|
| 828 | // ctor/dtor statements to come out in the right order |
---|
[1ba88a0] | 829 | for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) { |
---|
[44f6341] | 830 | DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member ); |
---|
| 831 | // skip non-DWT members |
---|
| 832 | if ( ! field ) continue; |
---|
| 833 | // skip handled members |
---|
| 834 | if ( ! unhandled.count( field ) ) continue; |
---|
| 835 | |
---|
| 836 | // insert and resolve default/copy constructor call for each field that's unhandled |
---|
[c8dfcd3] | 837 | std::list< Statement * > stmt; |
---|
| 838 | UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) ); |
---|
| 839 | deref->get_args().push_back( new VariableExpr( thisParam ) ); |
---|
[4d4882a] | 840 | |
---|
| 841 | Expression * arg2 = 0; |
---|
| 842 | if ( isCopyConstructor( function ) ) { |
---|
[44f6341] | 843 | // if copy ctor, need to pass second-param-of-this-function.field |
---|
[4d4882a] | 844 | std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters(); |
---|
| 845 | assert( params.size() == 2 ); |
---|
[44f6341] | 846 | arg2 = new MemberExpr( field, new VariableExpr( params.back() ) ); |
---|
[4d4882a] | 847 | } |
---|
| 848 | InitExpander srcParam( arg2 ); |
---|
[44f6341] | 849 | SymTab::genImplicitCall( srcParam, new MemberExpr( field, deref ), function->get_name(), back_inserter( stmt ), field, isCtor ); |
---|
[c8dfcd3] | 850 | |
---|
| 851 | assert( stmt.size() <= 1 ); |
---|
| 852 | if ( stmt.size() == 1 ) { |
---|
| 853 | Statement * callStmt = stmt.front(); |
---|
| 854 | |
---|
| 855 | MutatingResolver resolver( *this ); |
---|
| 856 | try { |
---|
| 857 | callStmt->acceptMutator( resolver ); |
---|
| 858 | if ( isCtor ) { |
---|
| 859 | function->get_statements()->push_front( callStmt ); |
---|
| 860 | } else { |
---|
| 861 | // destructor statements should be added at the end |
---|
| 862 | function->get_statements()->push_back( callStmt ); |
---|
| 863 | } |
---|
| 864 | } catch ( SemanticError & error ) { |
---|
[44f6341] | 865 | emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed", " and no ", isCtor ? "default constructor" : "destructor", " found" ); |
---|
[c8dfcd3] | 866 | } |
---|
| 867 | } |
---|
| 868 | } |
---|
| 869 | leaveScope(); |
---|
| 870 | } |
---|
[79970ed] | 871 | } |
---|
| 872 | |
---|
[c8dfcd3] | 873 | void GenStructMemberCalls::visit( ApplicationExpr * appExpr ) { |
---|
[79970ed] | 874 | if ( ! checkWarnings( function ) ) return; |
---|
| 875 | |
---|
| 876 | std::string fname = getFunctionName( appExpr ); |
---|
| 877 | if ( fname == function->get_name() ) { |
---|
| 878 | // call to same kind of function |
---|
| 879 | Expression * firstParam = appExpr->get_args().front(); |
---|
| 880 | |
---|
| 881 | if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) { |
---|
| 882 | // if calling another constructor on thisParam, assume that function handles |
---|
| 883 | // all members - if it doesn't a warning will appear in that function. |
---|
| 884 | if ( varExpr->get_var() == thisParam ) { |
---|
| 885 | unhandled.clear(); |
---|
| 886 | } |
---|
| 887 | } else { |
---|
| 888 | // if first parameter is a member expression then |
---|
| 889 | // remove the member from unhandled set. |
---|
| 890 | handleFirstParam( firstParam ); |
---|
| 891 | } |
---|
| 892 | } |
---|
| 893 | |
---|
| 894 | Parent::visit( appExpr ); |
---|
| 895 | } |
---|
| 896 | |
---|
[c8dfcd3] | 897 | void GenStructMemberCalls::handleFirstParam( Expression * firstParam ) { |
---|
[79970ed] | 898 | using namespace std; |
---|
| 899 | if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) { |
---|
| 900 | if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) { |
---|
| 901 | if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) { |
---|
| 902 | if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) { |
---|
| 903 | if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) { |
---|
| 904 | if ( varExpr->get_var() == thisParam ) { |
---|
| 905 | unhandled.erase( memberExpr->get_member() ); |
---|
| 906 | } |
---|
| 907 | } |
---|
| 908 | } |
---|
| 909 | } |
---|
| 910 | } |
---|
| 911 | } |
---|
| 912 | } |
---|
| 913 | |
---|
[c8dfcd3] | 914 | void GenStructMemberCalls::visit( MemberExpr * memberExpr ) { |
---|
[79970ed] | 915 | if ( ! checkWarnings( function ) ) return; |
---|
[c8dfcd3] | 916 | if ( ! isCtor ) return; |
---|
[79970ed] | 917 | |
---|
| 918 | if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) { |
---|
| 919 | if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) { |
---|
| 920 | if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) { |
---|
| 921 | if ( varExpr->get_var() == thisParam ) { |
---|
| 922 | if ( unhandled.count( memberExpr->get_member() ) ) { |
---|
| 923 | // emit a warning because a member was used before it was constructed |
---|
[c8dfcd3] | 924 | usedUninit.insert( memberExpr->get_member() ); |
---|
[79970ed] | 925 | } |
---|
| 926 | } |
---|
| 927 | } |
---|
| 928 | } |
---|
| 929 | } |
---|
| 930 | Parent::visit( memberExpr ); |
---|
| 931 | } |
---|
[3906301] | 932 | |
---|
| 933 | template< typename Visitor, typename... Params > |
---|
| 934 | void error( Visitor & v, const Params &... params ) { |
---|
| 935 | v.errors.append( toString( params... ) ); |
---|
| 936 | } |
---|
| 937 | |
---|
| 938 | template< typename... Params > |
---|
[c8dfcd3] | 939 | void GenStructMemberCalls::emit( const Params &... params ) { |
---|
[3906301] | 940 | // toggle warnings vs. errors here. |
---|
| 941 | // warn( params... ); |
---|
| 942 | error( *this, params... ); |
---|
| 943 | } |
---|
[c8dfcd3] | 944 | |
---|
| 945 | DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) { |
---|
| 946 | // add object to the indexer assumes that there will be no name collisions |
---|
| 947 | // in generated code. If this changes, add mutate methods for entities with |
---|
| 948 | // scope and call {enter,leave}Scope explicitly. |
---|
| 949 | objectDecl->accept( indexer ); |
---|
| 950 | return objectDecl; |
---|
| 951 | } |
---|
| 952 | |
---|
| 953 | Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) { |
---|
| 954 | return safe_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) ); |
---|
| 955 | } |
---|
[b6fe7e6] | 956 | |
---|
| 957 | Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) { |
---|
| 958 | static UniqueName tempNamer( "_tmp_ctor_expr" ); |
---|
[f0121d7] | 959 | // xxx - is the size check necessary? |
---|
[906e24d] | 960 | assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 ); |
---|
| 961 | ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, ctorExpr->get_result()->clone(), nullptr ); |
---|
[b6fe7e6] | 962 | addDeclaration( tmp ); |
---|
| 963 | |
---|
| 964 | ApplicationExpr * callExpr = safe_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() ); |
---|
| 965 | TypeSubstitution * env = ctorExpr->get_env(); |
---|
| 966 | ctorExpr->set_callExpr( nullptr ); |
---|
| 967 | ctorExpr->set_env( nullptr ); |
---|
| 968 | |
---|
| 969 | Expression *& firstArg = callExpr->get_args().front(); |
---|
| 970 | UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
| 971 | assign->get_args().push_back( new VariableExpr( tmp ) ); |
---|
| 972 | assign->get_args().push_back( firstArg ); |
---|
[906e24d] | 973 | assign->set_result( ctorExpr->get_result()->clone() ); |
---|
[b6fe7e6] | 974 | firstArg = assign; |
---|
| 975 | |
---|
| 976 | CommaExpr * commaExpr = new CommaExpr( callExpr, new VariableExpr( tmp ) ); |
---|
| 977 | commaExpr->set_env( env ); |
---|
| 978 | delete ctorExpr; |
---|
| 979 | return commaExpr; |
---|
| 980 | } |
---|
[c2931ea] | 981 | } // namespace |
---|
[71f4e4f] | 982 | } // namespace InitTweak |
---|
| 983 | |
---|
| 984 | // Local Variables: // |
---|
| 985 | // tab-width: 4 // |
---|
| 986 | // mode: c++ // |
---|
| 987 | // compile-command: "make install" // |
---|
| 988 | // End: // |
---|