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