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