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