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