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