source: src/GenPoly/Box.cc@ d75038c

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor deferred_resn demangler enum forall-pointer-decay gc_noraii jacob/cs343-translation jenkins-sandbox memory new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new string with_gc
Last change on this file since d75038c was d75038c, checked in by Aaron Moss <a3moss@…>, 10 years ago

Fix segfault bug introduced in layout function code

  • Property mode set to 100644
File size: 101.2 KB
Line 
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// Box.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Feb 5 16:45:07 2016
13// Update Count : 286
14//
15
16#include <algorithm>
17#include <iterator>
18#include <list>
19#include <map>
20#include <set>
21#include <stack>
22#include <string>
23#include <utility>
24#include <vector>
25#include <cassert>
26
27#include "Box.h"
28#include "DeclMutator.h"
29#include "PolyMutator.h"
30#include "FindFunction.h"
31#include "ScopedMap.h"
32#include "ScopedSet.h"
33#include "ScrubTyVars.h"
34
35#include "Parser/ParseNode.h"
36
37#include "SynTree/Constant.h"
38#include "SynTree/Declaration.h"
39#include "SynTree/Expression.h"
40#include "SynTree/Initializer.h"
41#include "SynTree/Mutator.h"
42#include "SynTree/Statement.h"
43#include "SynTree/Type.h"
44#include "SynTree/TypeSubstitution.h"
45
46#include "ResolvExpr/TypeEnvironment.h"
47#include "ResolvExpr/TypeMap.h"
48#include "ResolvExpr/typeops.h"
49
50#include "SymTab/Indexer.h"
51#include "SymTab/Mangler.h"
52
53#include "Common/SemanticError.h"
54#include "Common/UniqueName.h"
55#include "Common/utility.h"
56
57#include <ext/functional> // temporary
58
59namespace GenPoly {
60 namespace {
61 const std::list<Label> noLabels;
62
63 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
64
65 /// Abstracts type equality for a list of parameter types
66 struct TypeList {
67 TypeList() : params() {}
68 TypeList( const std::list< Type* > &_params ) : params() { cloneAll(_params, params); }
69 TypeList( std::list< Type* > &&_params ) : params( _params ) {}
70
71 TypeList( const TypeList &that ) : params() { cloneAll(that.params, params); }
72 TypeList( TypeList &&that ) : params( std::move( that.params ) ) {}
73
74 /// Extracts types from a list of TypeExpr*
75 TypeList( const std::list< TypeExpr* >& _params ) : params() {
76 for ( std::list< TypeExpr* >::const_iterator param = _params.begin(); param != _params.end(); ++param ) {
77 params.push_back( (*param)->get_type()->clone() );
78 }
79 }
80
81 TypeList& operator= ( const TypeList &that ) {
82 deleteAll( params );
83
84 params.clear();
85 cloneAll( that.params, params );
86
87 return *this;
88 }
89
90 TypeList& operator= ( TypeList &&that ) {
91 deleteAll( params );
92
93 params = std::move( that.params );
94
95 return *this;
96 }
97
98 ~TypeList() { deleteAll( params ); }
99
100 bool operator== ( const TypeList& that ) const {
101 if ( params.size() != that.params.size() ) return false;
102
103 SymTab::Indexer dummy;
104 for ( std::list< Type* >::const_iterator it = params.begin(), jt = that.params.begin(); it != params.end(); ++it, ++jt ) {
105 if ( ! ResolvExpr::typesCompatible( *it, *jt, dummy ) ) return false;
106 }
107 return true;
108 }
109
110 std::list< Type* > params; ///< Instantiation parameters
111 };
112
113 /// Maps a key and a TypeList to the some value, accounting for scope
114 template< typename Key, typename Value >
115 class InstantiationMap {
116 /// Wraps value for a specific (Key, TypeList) combination
117 typedef std::pair< TypeList, Value* > Instantiation;
118 /// List of TypeLists paired with their appropriate values
119 typedef std::vector< Instantiation > ValueList;
120 /// Underlying map type; maps keys to a linear list of corresponding TypeLists and values
121 typedef ScopedMap< Key*, ValueList > InnerMap;
122
123 InnerMap instantiations; ///< instantiations
124
125 public:
126 /// Starts a new scope
127 void beginScope() { instantiations.beginScope(); }
128
129 /// Ends a scope
130 void endScope() { instantiations.endScope(); }
131
132 /// Gets the value for the (key, typeList) pair, returns NULL on none such.
133 Value *lookup( Key *key, const std::list< TypeExpr* >& params ) const {
134 TypeList typeList( params );
135
136 // scan scopes for matches to the key
137 for ( typename InnerMap::const_iterator insts = instantiations.find( key ); insts != instantiations.end(); insts = instantiations.findNext( insts, key ) ) {
138 for ( typename ValueList::const_reverse_iterator inst = insts->second.rbegin(); inst != insts->second.rend(); ++inst ) {
139 if ( inst->first == typeList ) return inst->second;
140 }
141 }
142 // no matching instantiations found
143 return 0;
144 }
145
146 /// Adds a value for a (key, typeList) pair to the current scope
147 void insert( Key *key, const std::list< TypeExpr* > &params, Value *value ) {
148 instantiations[ key ].push_back( Instantiation( TypeList( params ), value ) );
149 }
150 };
151
152 /// Adds layout-generation functions to polymorphic types
153 class LayoutFunctionBuilder : public DeclMutator {
154 unsigned int functionNesting; // current level of nested functions
155 public:
156 LayoutFunctionBuilder() : functionNesting( 0 ) {}
157
158 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
159 virtual Declaration *mutate( StructDecl *structDecl );
160 virtual Declaration *mutate( UnionDecl *unionDecl );
161 };
162
163 /// Replaces polymorphic return types with out-parameters, replaces calls to polymorphic functions with adapter calls as needed, and adds appropriate type variables to the function call
164 class Pass1 : public PolyMutator {
165 public:
166 Pass1();
167 virtual Expression *mutate( ApplicationExpr *appExpr );
168 virtual Expression *mutate( AddressExpr *addrExpr );
169 virtual Expression *mutate( UntypedExpr *expr );
170 virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
171 virtual TypeDecl *mutate( TypeDecl *typeDecl );
172 virtual Expression *mutate( CommaExpr *commaExpr );
173 virtual Expression *mutate( ConditionalExpr *condExpr );
174 virtual Statement * mutate( ReturnStmt *returnStmt );
175 virtual Type *mutate( PointerType *pointerType );
176 virtual Type * mutate( FunctionType *functionType );
177
178 virtual void doBeginScope();
179 virtual void doEndScope();
180 private:
181 /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
182 void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
183 /// passes extra type parameters into a polymorphic function application
184 void passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
185 /// wraps a function application with a new temporary for the out-parameter return value
186 Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
187 /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
188 void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
189 /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
190 /// If `doClone` is set to false, will not clone interior types
191 Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
192 /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
193 Expression *addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg );
194 Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
195 void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
196 void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
197 void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
198 /// Stores assignment operators from assertion list in local map of assignment operations
199 void findAssignOps( const std::list< TypeDecl *> &forall );
200 void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
201 FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
202 /// Replaces intrinsic operator functions with their arithmetic desugaring
203 Expression *handleIntrinsics( ApplicationExpr *appExpr );
204 /// Inserts a new temporary variable into the current scope with an auto-generated name
205 ObjectDecl *makeTemporary( Type *type );
206
207 std::map< std::string, DeclarationWithType *> assignOps; ///< Currently known type variable assignment operators
208 ResolvExpr::TypeMap< DeclarationWithType > scopedAssignOps; ///< Currently known assignment operators
209 ScopedMap< std::string, DeclarationWithType* > adapters; ///< Set of adapter functions in the current scope
210
211 DeclarationWithType *retval;
212 bool useRetval;
213 UniqueName tempNamer;
214 };
215
216 /// * Moves polymorphic returns in function types to pointer-type parameters
217 /// * adds type size and assertion parameters to parameter lists
218 /// * does dynamic calculation of type layouts
219 class Pass2 : public PolyMutator {
220 public:
221 template< typename DeclClass >
222 DeclClass *handleDecl( DeclClass *decl, Type *type );
223 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
224 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
225 virtual TypeDecl *mutate( TypeDecl *typeDecl );
226 virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
227 virtual Type *mutate( PointerType *pointerType );
228 virtual Type *mutate( FunctionType *funcType );
229 virtual Expression *mutate( SizeofExpr *sizeofExpr );
230 virtual Expression *mutate( AlignofExpr *alignofExpr );
231 virtual Expression *mutate( OffsetofExpr *offsetofExpr );
232 virtual Expression *mutate( OffsetPackExpr *offsetPackExpr );
233
234 virtual void doBeginScope();
235 virtual void doEndScope();
236 private:
237 void addAdapters( FunctionType *functionType );
238 /// Makes a new variable in the current scope with the given name, type & optional initializer
239 ObjectDecl *makeVar( const std::string &name, Type *type, Initializer *init = 0 );
240 /// returns true if the type has a dynamic layout; such a layout will be stored in appropriately-named local variables when the function returns
241 bool findGeneric( Type *ty );
242 /// adds type parameters to the layout call; will generate the appropriate parameters if needed
243 void addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams );
244
245 std::map< UniqueId, std::string > adapterName;
246 ScopedSet< std::string > knownLayouts; ///< Set of generic type layouts known in the current scope, indexed by sizeofName
247 ScopedSet< std::string > knownOffsets; ///< Set of non-generic types for which the offset array exists in the current scope, indexed by offsetofName
248 };
249
250 /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
251 class GenericInstantiator : public DeclMutator {
252 /// Map of (generic type, parameter list) pairs to concrete type instantiations
253 InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
254 /// Namer for concrete types
255 UniqueName typeNamer;
256
257 public:
258 GenericInstantiator() : DeclMutator(), instantiations(), typeNamer("_conc_") {}
259
260 virtual Type* mutate( StructInstType *inst );
261 virtual Type* mutate( UnionInstType *inst );
262
263 // virtual Expression* mutate( MemberExpr *memberExpr );
264
265 virtual void doBeginScope();
266 virtual void doEndScope();
267 private:
268 /// Wrap instantiation lookup for structs
269 StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
270 /// Wrap instantiation lookup for unions
271 UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
272 /// Wrap instantiation insertion for structs
273 void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
274 /// Wrap instantiation insertion for unions
275 void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
276 };
277
278 /// Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference;
279 /// also fixes offsetof expressions.
280 class MemberExprFixer : public PolyMutator {
281 public:
282 template< typename DeclClass >
283 DeclClass *handleDecl( DeclClass *decl, Type *type );
284 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
285 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
286 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
287 virtual TypeDecl *mutate( TypeDecl *objectDecl );
288 virtual Statement *mutate( DeclStmt *declStmt );
289 virtual Type *mutate( PointerType *pointerType );
290 virtual Type *mutate( FunctionType *funcType );
291 virtual Expression *mutate( MemberExpr *memberExpr );
292 virtual Expression *mutate( OffsetofExpr *offsetofExpr );
293 };
294
295 /// Replaces initialization of polymorphic values with alloca, declaration of dtype/ftype with appropriate void expression, and sizeof expressions of polymorphic types with the proper variable
296 class Pass3 : public PolyMutator {
297 public:
298 template< typename DeclClass >
299 DeclClass *handleDecl( DeclClass *decl, Type *type );
300 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
301 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
302 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
303 virtual TypeDecl *mutate( TypeDecl *objectDecl );
304 virtual Type *mutate( PointerType *pointerType );
305 virtual Type *mutate( FunctionType *funcType );
306 private:
307 };
308
309 } // anonymous namespace
310
311 /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
312 template< typename MutatorType >
313 inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
314 bool seenIntrinsic = false;
315 SemanticError errors;
316 for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
317 try {
318 if ( *i ) {
319 if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
320 seenIntrinsic = true;
321 } else if ( seenIntrinsic ) {
322 seenIntrinsic = false; // break on this line when debugging for end of prelude
323 }
324
325 *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
326 assert( *i );
327 } // if
328 } catch( SemanticError &e ) {
329 errors.append( e );
330 } // try
331 } // for
332 if ( ! errors.isEmpty() ) {
333 throw errors;
334 } // if
335 }
336
337 void box( std::list< Declaration *>& translationUnit ) {
338 LayoutFunctionBuilder layoutBuilder;
339 Pass1 pass1;
340 Pass2 pass2;
341 GenericInstantiator instantiator;
342 MemberExprFixer memberFixer;
343 Pass3 pass3;
344
345 layoutBuilder.mutateDeclarationList( translationUnit );
346 mutateTranslationUnit/*All*/( translationUnit, pass1 );
347 mutateTranslationUnit/*All*/( translationUnit, pass2 );
348 instantiator.mutateDeclarationList( translationUnit );
349 mutateTranslationUnit/*All*/( translationUnit, memberFixer );
350 mutateTranslationUnit/*All*/( translationUnit, pass3 );
351 }
352
353 ////////////////////////////////// LayoutFunctionBuilder ////////////////////////////////////////////
354
355 DeclarationWithType *LayoutFunctionBuilder::mutate( FunctionDecl *functionDecl ) {
356 functionDecl->set_functionType( maybeMutate( functionDecl->get_functionType(), *this ) );
357 mutateAll( functionDecl->get_oldDecls(), *this );
358 ++functionNesting;
359 functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
360 --functionNesting;
361 return functionDecl;
362 }
363
364 /// Get a list of type declarations that will affect a layout function
365 std::list< TypeDecl* > takeOtypeOnly( std::list< TypeDecl* > &decls ) {
366 std::list< TypeDecl * > otypeDecls;
367
368 for ( std::list< TypeDecl* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
369 if ( (*decl)->get_kind() == TypeDecl::Any ) {
370 otypeDecls.push_back( *decl );
371 }
372 }
373
374 return otypeDecls;
375 }
376
377 /// Adds parameters for otype layout to a function type
378 void addOtypeParams( FunctionType *layoutFnType, std::list< TypeDecl* > &otypeParams ) {
379 BasicType sizeAlignType( Type::Qualifiers(), BasicType::LongUnsignedInt );
380
381 for ( std::list< TypeDecl* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
382 TypeInstType paramType( Type::Qualifiers(), (*param)->get_name(), *param );
383 layoutFnType->get_parameters().push_back( new ObjectDecl( sizeofName( &paramType ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
384 layoutFnType->get_parameters().push_back( new ObjectDecl( alignofName( &paramType ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
385 }
386 }
387
388 /// Builds a layout function declaration
389 FunctionDecl *buildLayoutFunctionDecl( const std::string &typeName, unsigned int functionNesting, FunctionType *layoutFnType ) {
390 // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
391 // because each unit generates copies of the default routines for each aggregate.
392 FunctionDecl *layoutDecl = new FunctionDecl(
393 "__layoutof_" + typeName, functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, layoutFnType, new CompoundStmt( noLabels ), true, false );
394 layoutDecl->fixUniqueId();
395 return layoutDecl;
396 }
397
398 /// Makes a unary operation
399 Expression *makeOp( const std::string &name, Expression *arg ) {
400 UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
401 expr->get_args().push_back( arg );
402 return expr;
403 }
404
405 /// Makes a binary operation
406 Expression *makeOp( const std::string &name, Expression *lhs, Expression *rhs ) {
407 UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
408 expr->get_args().push_back( lhs );
409 expr->get_args().push_back( rhs );
410 return expr;
411 }
412
413 /// Returns the dereference of a local pointer variable
414 Expression *derefVar( ObjectDecl *var ) {
415 return makeOp( "*?", new VariableExpr( var ) );
416 }
417
418 /// makes an if-statement with a single-expression if-block and no then block
419 Statement *makeCond( Expression *cond, Expression *ifPart ) {
420 return new IfStmt( noLabels, cond, new ExprStmt( noLabels, ifPart ), 0 );
421 }
422
423 /// makes a statement that assigns rhs to lhs if lhs < rhs
424 Statement *makeAssignMax( Expression *lhs, Expression *rhs ) {
425 return makeCond( makeOp( "?<?", lhs, rhs ), makeOp( "?=?", lhs->clone(), rhs->clone() ) );
426 }
427
428 /// makes a statement that aligns lhs to rhs (rhs should be an integer power of two)
429 Statement *makeAlignTo( Expression *lhs, Expression *rhs ) {
430 // check that the lhs is zeroed out to the level of rhs
431 Expression *ifCond = makeOp( "?&?", lhs, makeOp( "?-?", rhs, new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), "1" ) ) ) );
432 // if not aligned, increment to alignment
433 Expression *ifExpr = makeOp( "?+=?", lhs->clone(), makeOp( "?-?", rhs->clone(), ifCond->clone() ) );
434 return makeCond( ifCond, ifExpr );
435 }
436
437 /// adds an expression to a compound statement
438 void addExpr( CompoundStmt *stmts, Expression *expr ) {
439 stmts->get_kids().push_back( new ExprStmt( noLabels, expr ) );
440 }
441
442 /// adds a statement to a compound statement
443 void addStmt( CompoundStmt *stmts, Statement *stmt ) {
444 stmts->get_kids().push_back( stmt );
445 }
446
447 Declaration *LayoutFunctionBuilder::mutate( StructDecl *structDecl ) {
448 // do not generate layout function for "empty" tag structs
449 if ( structDecl->get_members().empty() ) return structDecl;
450
451 // get parameters that can change layout, exiting early if none
452 std::list< TypeDecl* > otypeParams = takeOtypeOnly( structDecl->get_parameters() );
453 if ( otypeParams.empty() ) return structDecl;
454
455 // build layout function signature
456 FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
457 BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
458 PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
459
460 ObjectDecl *sizeParam = new ObjectDecl( "__sizeof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
461 layoutFnType->get_parameters().push_back( sizeParam );
462 ObjectDecl *alignParam = new ObjectDecl( "__alignof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
463 layoutFnType->get_parameters().push_back( alignParam );
464 ObjectDecl *offsetParam = new ObjectDecl( "__offsetof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
465 layoutFnType->get_parameters().push_back( offsetParam );
466 addOtypeParams( layoutFnType, otypeParams );
467
468 // build function decl
469 FunctionDecl *layoutDecl = buildLayoutFunctionDecl( structDecl->get_name(), functionNesting, layoutFnType );
470
471 // calculate struct layout in function body
472
473 // initialize size and alignment to 0 and 1 (will have at least one member to re-edit size
474 addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "0" ) ) ) );
475 addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
476 unsigned long n_members = 0;
477 bool firstMember = true;
478 for ( std::list< Declaration* >::const_iterator member = structDecl->get_members().begin(); member != structDecl->get_members().end(); ++member ) {
479 DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
480 assert( dwt );
481 Type *memberType = dwt->get_type();
482
483 if ( firstMember ) {
484 firstMember = false;
485 } else {
486 // make sure all members after the first (automatically aligned at 0) are properly padded for alignment
487 addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), new AlignofExpr( memberType->clone() ) ) );
488 }
489
490 // place current size in the current offset index
491 addExpr( layoutDecl->get_statements(), makeOp( "?=?", makeOp( "?[?]", new VariableExpr( offsetParam ), new ConstantExpr( Constant::from( n_members ) ) ),
492 derefVar( sizeParam ) ) );
493 ++n_members;
494
495 // add member size to current size
496 addExpr( layoutDecl->get_statements(), makeOp( "?+=?", derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
497
498 // take max of member alignment and global alignment
499 addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
500 }
501 // make sure the type is end-padded to a multiple of its alignment
502 addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
503
504 addDeclarationAfter( layoutDecl );
505 return structDecl;
506 }
507
508 Declaration *LayoutFunctionBuilder::mutate( UnionDecl *unionDecl ) {
509 // do not generate layout function for "empty" tag unions
510 if ( unionDecl->get_members().empty() ) return unionDecl;
511
512 // get parameters that can change layout, exiting early if none
513 std::list< TypeDecl* > otypeParams = takeOtypeOnly( unionDecl->get_parameters() );
514 if ( otypeParams.empty() ) return unionDecl;
515
516 // build layout function signature
517 FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
518 BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
519 PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
520
521 ObjectDecl *sizeParam = new ObjectDecl( "__sizeof_" + unionDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
522 layoutFnType->get_parameters().push_back( sizeParam );
523 ObjectDecl *alignParam = new ObjectDecl( "__alignof_" + unionDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
524 layoutFnType->get_parameters().push_back( alignParam );
525 addOtypeParams( layoutFnType, otypeParams );
526
527 // build function decl
528 FunctionDecl *layoutDecl = buildLayoutFunctionDecl( unionDecl->get_name(), functionNesting, layoutFnType );
529
530 // calculate union layout in function body
531 addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
532 addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
533 for ( std::list< Declaration* >::const_iterator member = unionDecl->get_members().begin(); member != unionDecl->get_members().end(); ++member ) {
534 DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
535 assert( dwt );
536 Type *memberType = dwt->get_type();
537
538 // take max member size and global size
539 addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
540
541 // take max of member alignment and global alignment
542 addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
543 }
544 // make sure the type is end-padded to a multiple of its alignment
545 addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
546
547 addDeclarationAfter( layoutDecl );
548 return unionDecl;
549 }
550
551 ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
552
553 namespace {
554 std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
555 std::stringstream name;
556
557 // NOTE: this function previously used isPolyObj, which failed to produce
558 // the correct thing in some situations. It's not clear to me why this wasn't working.
559
560 // if the return type or a parameter type involved polymorphic types, then the adapter will need
561 // to take those polymorphic types as pointers. Therefore, there can be two different functions
562 // with the same mangled name, so we need to further mangle the names.
563 for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
564 if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
565 name << "P";
566 } else {
567 name << "M";
568 }
569 }
570 name << "_";
571 std::list< DeclarationWithType *> &paramList = function->get_parameters();
572 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
573 if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
574 name << "P";
575 } else {
576 name << "M";
577 }
578 } // for
579 return name.str();
580 }
581
582 std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
583 return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
584 }
585
586 std::string makeAdapterName( const std::string &mangleName ) {
587 return "_adapter" + mangleName;
588 }
589
590 Pass1::Pass1() : useRetval( false ), tempNamer( "_temp" ) {}
591
592 /// Returns T if the given declaration is (*?=?)(T *, T) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
593 TypeInstType *isTypeInstAssignment( DeclarationWithType *decl ) {
594 if ( decl->get_name() == "?=?" ) {
595 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
596 if ( funType->get_parameters().size() == 2 ) {
597 if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
598 if ( TypeInstType *refType = dynamic_cast< TypeInstType *>( pointer->get_base() ) ) {
599 if ( TypeInstType *refType2 = dynamic_cast< TypeInstType *>( funType->get_parameters().back()->get_type() ) ) {
600 if ( refType->get_name() == refType2->get_name() ) {
601 return refType;
602 } // if
603 } // if
604 } // if
605 } // if
606 } // if
607 } // if
608 } // if
609 return 0;
610 }
611
612 /// returns T if the given declaration is: (*?=?)(T *, T) for some type T (return not checked, but maybe should be), NULL otherwise
613 /// Only picks assignments where neither parameter is cv-qualified
614 Type *isAssignment( DeclarationWithType *decl ) {
615 if ( decl->get_name() == "?=?" ) {
616 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
617 if ( funType->get_parameters().size() == 2 ) {
618 Type::Qualifiers defaultQualifiers;
619 Type *paramType1 = funType->get_parameters().front()->get_type();
620 if ( paramType1->get_qualifiers() != defaultQualifiers ) return 0;
621 Type *paramType2 = funType->get_parameters().back()->get_type();
622 if ( paramType2->get_qualifiers() != defaultQualifiers ) return 0;
623
624 if ( PointerType *pointerType = dynamic_cast< PointerType* >( paramType1 ) ) {
625 Type *baseType1 = pointerType->get_base();
626 if ( baseType1->get_qualifiers() != defaultQualifiers ) return 0;
627 SymTab::Indexer dummy;
628 if ( ResolvExpr::typesCompatible( baseType1, paramType2, dummy ) ) {
629 return baseType1;
630 } // if
631 } // if
632 } // if
633 } // if
634 } // if
635 return 0;
636 }
637
638 void Pass1::findAssignOps( const std::list< TypeDecl *> &forall ) {
639 // what if a nested function uses an assignment operator?
640 // assignOps.clear();
641 for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
642 for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
643 std::string typeName;
644 if ( TypeInstType *typeInst = isTypeInstAssignment( *assert ) ) {
645 assignOps[ typeInst->get_name() ] = *assert;
646 } // if
647 } // for
648 } // for
649 }
650
651 DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
652 // if this is a assignment function, put it in the map for this scope
653 if ( Type *assignedType = isAssignment( functionDecl ) ) {
654 if ( ! dynamic_cast< TypeInstType* >( assignedType ) ) {
655 scopedAssignOps.insert( assignedType, functionDecl );
656 }
657 }
658
659 if ( functionDecl->get_statements() ) { // empty routine body ?
660 doBeginScope();
661 TyVarMap oldtyVars = scopeTyVars;
662 std::map< std::string, DeclarationWithType *> oldassignOps = assignOps;
663 DeclarationWithType *oldRetval = retval;
664 bool oldUseRetval = useRetval;
665
666 // process polymorphic return value
667 retval = 0;
668 if ( isPolyRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
669 retval = functionDecl->get_functionType()->get_returnVals().front();
670
671 // give names to unnamed return values
672 if ( retval->get_name() == "" ) {
673 retval->set_name( "_retparm" );
674 retval->set_linkage( LinkageSpec::C );
675 } // if
676 } // if
677
678 FunctionType *functionType = functionDecl->get_functionType();
679 makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
680 findAssignOps( functionDecl->get_functionType()->get_forall() );
681
682 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
683 std::list< FunctionType *> functions;
684 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
685 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
686 findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
687 } // for
688 } // for
689 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
690 findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
691 } // for
692
693 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
694 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
695 if ( adapters.find( mangleName ) == adapters.end() ) {
696 std::string adapterName = makeAdapterName( mangleName );
697 adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
698 } // if
699 } // for
700
701 functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
702
703 scopeTyVars = oldtyVars;
704 assignOps = oldassignOps;
705 // std::cerr << "end FunctionDecl: ";
706 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
707 // std::cerr << i->first << " ";
708 // }
709 // std::cerr << "\n";
710 retval = oldRetval;
711 useRetval = oldUseRetval;
712 doEndScope();
713 } // if
714 return functionDecl;
715 }
716
717 TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
718 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
719 return Mutator::mutate( typeDecl );
720 }
721
722 Expression *Pass1::mutate( CommaExpr *commaExpr ) {
723 bool oldUseRetval = useRetval;
724 useRetval = false;
725 commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
726 useRetval = oldUseRetval;
727 commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
728 return commaExpr;
729 }
730
731 Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
732 bool oldUseRetval = useRetval;
733 useRetval = false;
734 condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
735 useRetval = oldUseRetval;
736 condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
737 condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
738 return condExpr;
739
740 }
741
742 void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
743 Type *polyBase = hasPolyBase( parmType, exprTyVars );
744 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
745 std::string sizeName = sizeofName( polyBase );
746 if ( seenTypes.count( sizeName ) ) return;
747
748 arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
749 arg++;
750 arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
751 arg++;
752 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
753 if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
754 // zero-length arrays are forbidden by C, so don't pass offset for empty struct
755 if ( ! argBaseStructType->get_baseStruct()->get_members().empty() ) {
756 arg = appExpr->get_args().insert( arg, new OffsetPackExpr( argBaseStructType->clone() ) );
757 arg++;
758 }
759 } else {
760 throw SemanticError( "Cannot pass non-struct type for generic struct" );
761 }
762 }
763
764 seenTypes.insert( sizeName );
765 }
766 }
767
768 void Pass1::passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
769 // pass size/align for type variables
770 for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
771 ResolvExpr::EqvClass eqvClass;
772 assert( env );
773 if ( tyParm->second == TypeDecl::Any ) {
774 Type *concrete = env->lookup( tyParm->first );
775 if ( concrete ) {
776 arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
777 arg++;
778 arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
779 arg++;
780 } else {
781 throw SemanticError( "unbound type variable in application ", appExpr );
782 } // if
783 } // if
784 } // for
785
786 // add size/align for generic types to parameter list
787 if ( appExpr->get_function()->get_results().empty() ) return;
788 FunctionType *funcType = getFunctionType( appExpr->get_function()->get_results().front() );
789 assert( funcType );
790
791 std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
792 std::list< Expression* >::const_iterator fnArg = arg;
793 std::set< std::string > seenTypes; //< names for generic types we've seen
794
795 // a polymorphic return type may need to be added to the argument list
796 if ( polyRetType ) {
797 Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
798 passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
799 }
800
801 // add type information args for presently unseen types in parameter list
802 for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
803 VariableExpr *fnArgBase = getBaseVar( *fnArg );
804 if ( ! fnArgBase || fnArgBase->get_results().empty() ) continue;
805 passArgTypeVars( appExpr, (*fnParm)->get_type(), fnArgBase->get_results().front(), arg, exprTyVars, seenTypes );
806 }
807 }
808
809 ObjectDecl *Pass1::makeTemporary( Type *type ) {
810 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
811 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
812 return newObj;
813 }
814
815 Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
816 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
817 // if ( useRetval ) {
818 // assert( retval );
819 // arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
820 // arg++;
821 // } else {
822
823 // Create temporary to hold return value of polymorphic function and produce that temporary as a result
824 // using a comma expression. Possibly change comma expression into statement expression "{}" for multiple
825 // return values.
826 ObjectDecl *newObj = makeTemporary( retType->clone() );
827 Expression *paramExpr = new VariableExpr( newObj );
828
829 // If the type of the temporary is not polymorphic, box temporary by taking its address;
830 // otherwise the temporary is already boxed and can be used directly.
831 if ( ! isPolyType( newObj->get_type(), scopeTyVars, env ) ) {
832 paramExpr = new AddressExpr( paramExpr );
833 } // if
834 arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
835 arg++;
836 // Build a comma expression to call the function and emulate a normal return.
837 CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
838 commaExpr->set_env( appExpr->get_env() );
839 appExpr->set_env( 0 );
840 return commaExpr;
841 // } // if
842 // return appExpr;
843 }
844
845 void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
846 for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
847 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
848 assert(paramType && "Aggregate parameters should be type expressions");
849 paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
850 }
851 }
852
853 Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
854 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
855 Type *concrete = env->lookup( typeInst->get_name() );
856 if ( concrete == 0 ) {
857 throw SemanticError( "Unbound type variable " + typeInst->get_name() + " in ", appExpr );
858 } // if
859 return concrete;
860 } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
861 if ( doClone ) {
862 structType = structType->clone();
863 }
864 replaceParametersWithConcrete( appExpr, structType->get_parameters() );
865 return structType;
866 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
867 if ( doClone ) {
868 unionType = unionType->clone();
869 }
870 replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
871 return unionType;
872 }
873 return type;
874 }
875
876 Expression *Pass1::addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg ) {
877 assert( env );
878 Type *concrete = replaceWithConcrete( appExpr, polyType );
879 // add out-parameter for return value
880 return addRetParam( appExpr, function, concrete, arg );
881 }
882
883 Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
884 Expression *ret = appExpr;
885 if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
886 ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
887 } // if
888 std::string mangleName = mangleAdapterName( function, tyVars );
889 std::string adapterName = makeAdapterName( mangleName );
890
891 // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
892 Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
893 appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
894 appExpr->set_function( new NameExpr( adapterName ) );
895
896 return ret;
897 }
898
899 void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
900 assert( ! arg->get_results().empty() );
901 if ( isPolyType( param, exprTyVars ) ) {
902 if ( isPolyType( arg->get_results().front() ) ) {
903 // if the argument's type is polymorphic, we don't need to box again!
904 return;
905 } else if ( arg->get_results().front()->get_isLvalue() ) {
906 // VariableExpr and MemberExpr are lvalues
907 arg = new AddressExpr( arg );
908 } else {
909 // use type computed in unification to declare boxed variables
910 Type * newType = param->clone();
911 if ( env ) env->apply( newType );
912 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, newType, 0 );
913 newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
914 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
915 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
916 assign->get_args().push_back( new VariableExpr( newObj ) );
917 assign->get_args().push_back( arg );
918 stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
919 arg = new AddressExpr( new VariableExpr( newObj ) );
920 } // if
921 } // if
922 }
923
924 /// cast parameters to polymorphic functions so that types are replaced with
925 /// void * if they are type parameters in the formal type.
926 /// this gets rid of warnings from gcc.
927 void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
928 Type * newType = formal->clone();
929 if ( getFunctionType( newType ) ) {
930 newType = ScrubTyVars::scrub( newType, tyVars );
931 actual = new CastExpr( actual, newType );
932 } // if
933 }
934
935 void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
936 for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
937 assert( arg != appExpr->get_args().end() );
938 addCast( *arg, (*param)->get_type(), exprTyVars );
939 boxParam( (*param)->get_type(), *arg, exprTyVars );
940 } // for
941 }
942
943 void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
944 std::list< Expression *>::iterator cur = arg;
945 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
946 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
947 InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
948 assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
949 Expression *newExpr = inferParam->second.expr->clone();
950 addCast( newExpr, (*assert)->get_type(), tyVars );
951 boxParam( (*assert)->get_type(), newExpr, tyVars );
952 appExpr->get_args().insert( cur, newExpr );
953 } // for
954 } // for
955 }
956
957 void makeRetParm( FunctionType *funcType ) {
958 DeclarationWithType *retParm = funcType->get_returnVals().front();
959
960 // make a new parameter that is a pointer to the type of the old return value
961 retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
962 funcType->get_parameters().push_front( retParm );
963
964 // we don't need the return value any more
965 funcType->get_returnVals().clear();
966 }
967
968 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
969 // actually make the adapter type
970 FunctionType *adapter = adaptee->clone();
971 if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
972 makeRetParm( adapter );
973 } // if
974 adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
975 return adapter;
976 }
977
978 Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
979 assert( param );
980 assert( arg );
981 if ( isPolyType( realParam->get_type(), tyVars ) ) {
982 if ( ! isPolyType( arg->get_type() ) ) {
983 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
984 deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
985 deref->get_results().push_back( arg->get_type()->clone() );
986 return deref;
987 } // if
988 } // if
989 return new VariableExpr( param );
990 }
991
992 void addAdapterParams( ApplicationExpr *adapteeApp, std::list< DeclarationWithType *>::iterator arg, std::list< DeclarationWithType *>::iterator param, std::list< DeclarationWithType *>::iterator paramEnd, std::list< DeclarationWithType *>::iterator realParam, const TyVarMap &tyVars ) {
993 UniqueName paramNamer( "_p" );
994 for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
995 if ( (*param)->get_name() == "" ) {
996 (*param)->set_name( paramNamer.newName() );
997 (*param)->set_linkage( LinkageSpec::C );
998 } // if
999 adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
1000 } // for
1001 }
1002
1003
1004
1005 FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
1006 FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
1007 adapterType = ScrubTyVars::scrub( adapterType, tyVars );
1008 DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
1009 adapteeDecl->set_name( "_adaptee" );
1010 ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
1011 Statement *bodyStmt;
1012
1013 std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
1014 std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
1015 std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
1016 for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
1017 assert( tyArg != realType->get_forall().end() );
1018 std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
1019 std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
1020 std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
1021 for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
1022 assert( assertArg != (*tyArg)->get_assertions().end() );
1023 adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
1024 } // for
1025 } // for
1026
1027 std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
1028 std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
1029 std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
1030 param++; // skip adaptee parameter
1031 if ( realType->get_returnVals().empty() ) {
1032 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1033 bodyStmt = new ExprStmt( noLabels, adapteeApp );
1034 } else if ( isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
1035 if ( (*param)->get_name() == "" ) {
1036 (*param)->set_name( "_ret" );
1037 (*param)->set_linkage( LinkageSpec::C );
1038 } // if
1039 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
1040 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
1041 deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
1042 assign->get_args().push_back( deref );
1043 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1044 assign->get_args().push_back( adapteeApp );
1045 bodyStmt = new ExprStmt( noLabels, assign );
1046 } else {
1047 // adapter for a function that returns a monomorphic value
1048 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1049 bodyStmt = new ReturnStmt( noLabels, adapteeApp );
1050 } // if
1051 CompoundStmt *adapterBody = new CompoundStmt( noLabels );
1052 adapterBody->get_kids().push_back( bodyStmt );
1053 std::string adapterName = makeAdapterName( mangleName );
1054 return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
1055 }
1056
1057 void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
1058 // collect a list of function types passed as parameters or implicit parameters (assertions)
1059 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1060 std::list< FunctionType *> functions;
1061 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
1062 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
1063 findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
1064 } // for
1065 } // for
1066 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1067 findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
1068 } // for
1069
1070 // parameter function types for which an appropriate adapter has been generated. we cannot use the types
1071 // after applying substitutions, since two different parameter types may be unified to the same type
1072 std::set< std::string > adaptersDone;
1073
1074 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1075 FunctionType *originalFunction = (*funType)->clone();
1076 FunctionType *realFunction = (*funType)->clone();
1077 std::string mangleName = SymTab::Mangler::mangle( realFunction );
1078
1079 // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
1080 // pre-substitution parameter function type.
1081 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1082 adaptersDone.insert( adaptersDone.begin(), mangleName );
1083
1084 // apply substitution to type variables to figure out what the adapter's type should look like
1085 assert( env );
1086 env->apply( realFunction );
1087 mangleName = SymTab::Mangler::mangle( realFunction );
1088 mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
1089
1090 typedef ScopedMap< std::string, DeclarationWithType* >::iterator AdapterIter;
1091 AdapterIter adapter = adapters.find( mangleName );
1092 if ( adapter == adapters.end() ) {
1093 // adapter has not been created yet in the current scope, so define it
1094 FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
1095 std::pair< AdapterIter, bool > answer = adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
1096 adapter = answer.first;
1097 stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
1098 } // if
1099 assert( adapter != adapters.end() );
1100
1101 // add the appropriate adapter as a parameter
1102 appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
1103 } // if
1104 } // for
1105 } // passAdapters
1106
1107 Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
1108 NameExpr *opExpr;
1109 if ( isIncr ) {
1110 opExpr = new NameExpr( "?+=?" );
1111 } else {
1112 opExpr = new NameExpr( "?-=?" );
1113 } // if
1114 UntypedExpr *addAssign = new UntypedExpr( opExpr );
1115 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1116 addAssign->get_args().push_back( address->get_arg() );
1117 } else {
1118 addAssign->get_args().push_back( appExpr->get_args().front() );
1119 } // if
1120 addAssign->get_args().push_back( new NameExpr( sizeofName( polyType ) ) );
1121 addAssign->get_results().front() = appExpr->get_results().front()->clone();
1122 if ( appExpr->get_env() ) {
1123 addAssign->set_env( appExpr->get_env() );
1124 appExpr->set_env( 0 );
1125 } // if
1126 appExpr->get_args().clear();
1127 delete appExpr;
1128 return addAssign;
1129 }
1130
1131 Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
1132 if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
1133 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
1134 if ( varExpr->get_var()->get_name() == "?[?]" ) {
1135 assert( ! appExpr->get_results().empty() );
1136 assert( appExpr->get_args().size() == 2 );
1137 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
1138 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
1139 assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
1140 UntypedExpr *ret = 0;
1141 if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
1142 ret = new UntypedExpr( new NameExpr( "?+?" ) );
1143 } // if
1144 if ( baseType1 ) {
1145 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1146 multiply->get_args().push_back( appExpr->get_args().back() );
1147 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1148 ret->get_args().push_back( appExpr->get_args().front() );
1149 ret->get_args().push_back( multiply );
1150 } else if ( baseType2 ) {
1151 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1152 multiply->get_args().push_back( appExpr->get_args().front() );
1153 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
1154 ret->get_args().push_back( multiply );
1155 ret->get_args().push_back( appExpr->get_args().back() );
1156 } // if
1157 if ( baseType1 || baseType2 ) {
1158 ret->get_results().push_front( appExpr->get_results().front()->clone() );
1159 if ( appExpr->get_env() ) {
1160 ret->set_env( appExpr->get_env() );
1161 appExpr->set_env( 0 );
1162 } // if
1163 appExpr->get_args().clear();
1164 delete appExpr;
1165 return ret;
1166 } // if
1167 } else if ( varExpr->get_var()->get_name() == "*?" ) {
1168 assert( ! appExpr->get_results().empty() );
1169 assert( ! appExpr->get_args().empty() );
1170 if ( isPolyType( appExpr->get_results().front(), scopeTyVars, env ) ) {
1171 Expression *ret = appExpr->get_args().front();
1172 delete ret->get_results().front();
1173 ret->get_results().front() = appExpr->get_results().front()->clone();
1174 if ( appExpr->get_env() ) {
1175 ret->set_env( appExpr->get_env() );
1176 appExpr->set_env( 0 );
1177 } // if
1178 appExpr->get_args().clear();
1179 delete appExpr;
1180 return ret;
1181 } // if
1182 } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
1183 assert( ! appExpr->get_results().empty() );
1184 assert( appExpr->get_args().size() == 1 );
1185 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
1186 Type *tempType = appExpr->get_results().front()->clone();
1187 if ( env ) {
1188 env->apply( tempType );
1189 } // if
1190 ObjectDecl *newObj = makeTemporary( tempType );
1191 VariableExpr *tempExpr = new VariableExpr( newObj );
1192 UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
1193 assignExpr->get_args().push_back( tempExpr->clone() );
1194 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1195 assignExpr->get_args().push_back( address->get_arg()->clone() );
1196 } else {
1197 assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
1198 } // if
1199 CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
1200 return new CommaExpr( firstComma, tempExpr );
1201 } // if
1202 } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
1203 assert( ! appExpr->get_results().empty() );
1204 assert( appExpr->get_args().size() == 1 );
1205 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
1206 return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
1207 } // if
1208 } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
1209 assert( ! appExpr->get_results().empty() );
1210 assert( appExpr->get_args().size() == 2 );
1211 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
1212 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
1213 if ( baseType1 && baseType2 ) {
1214 UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
1215 divide->get_args().push_back( appExpr );
1216 divide->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1217 divide->get_results().push_front( appExpr->get_results().front()->clone() );
1218 if ( appExpr->get_env() ) {
1219 divide->set_env( appExpr->get_env() );
1220 appExpr->set_env( 0 );
1221 } // if
1222 return divide;
1223 } else if ( baseType1 ) {
1224 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1225 multiply->get_args().push_back( appExpr->get_args().back() );
1226 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1227 appExpr->get_args().back() = multiply;
1228 } else if ( baseType2 ) {
1229 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1230 multiply->get_args().push_back( appExpr->get_args().front() );
1231 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
1232 appExpr->get_args().front() = multiply;
1233 } // if
1234 } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
1235 assert( ! appExpr->get_results().empty() );
1236 assert( appExpr->get_args().size() == 2 );
1237 Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env );
1238 if ( baseType ) {
1239 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1240 multiply->get_args().push_back( appExpr->get_args().back() );
1241 multiply->get_args().push_back( new NameExpr( sizeofName( baseType ) ) );
1242 appExpr->get_args().back() = multiply;
1243 } // if
1244 } // if
1245 return appExpr;
1246 } // if
1247 } // if
1248 return 0;
1249 }
1250
1251 Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
1252 // std::cerr << "mutate appExpr: ";
1253 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1254 // std::cerr << i->first << " ";
1255 // }
1256 // std::cerr << "\n";
1257 bool oldUseRetval = useRetval;
1258 useRetval = false;
1259 appExpr->get_function()->acceptMutator( *this );
1260 mutateAll( appExpr->get_args(), *this );
1261 useRetval = oldUseRetval;
1262
1263 assert( ! appExpr->get_function()->get_results().empty() );
1264 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1265 assert( pointer );
1266 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1267 assert( function );
1268
1269 if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
1270 return newExpr;
1271 } // if
1272
1273 Expression *ret = appExpr;
1274
1275 std::list< Expression *>::iterator arg = appExpr->get_args().begin();
1276 std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
1277
1278 TyVarMap exprTyVars;
1279 makeTyVarMap( function, exprTyVars );
1280 ReferenceToType *polyRetType = isPolyRet( function );
1281
1282 if ( polyRetType ) {
1283 ret = addPolyRetParam( appExpr, function, polyRetType, arg );
1284 } else if ( needsAdapter( function, scopeTyVars ) ) {
1285 // std::cerr << "needs adapter: ";
1286 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1287 // std::cerr << i->first << " ";
1288 // }
1289 // std::cerr << "\n";
1290 // change the application so it calls the adapter rather than the passed function
1291 ret = applyAdapter( appExpr, function, arg, scopeTyVars );
1292 } // if
1293 arg = appExpr->get_args().begin();
1294
1295 passTypeVars( appExpr, polyRetType, arg, exprTyVars );
1296 addInferredParams( appExpr, function, arg, exprTyVars );
1297
1298 arg = paramBegin;
1299
1300 boxParams( appExpr, function, arg, exprTyVars );
1301
1302 passAdapters( appExpr, function, exprTyVars );
1303
1304 return ret;
1305 }
1306
1307 Expression *Pass1::mutate( UntypedExpr *expr ) {
1308 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1309 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1310 if ( name->get_name() == "*?" ) {
1311 Expression *ret = expr->get_args().front();
1312 expr->get_args().clear();
1313 delete expr;
1314 return ret->acceptMutator( *this );
1315 } // if
1316 } // if
1317 } // if
1318 return PolyMutator::mutate( expr );
1319 }
1320
1321 Expression *Pass1::mutate( AddressExpr *addrExpr ) {
1322 assert( ! addrExpr->get_arg()->get_results().empty() );
1323
1324 bool needs = false;
1325 if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
1326 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1327 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1328 if ( name->get_name() == "*?" ) {
1329 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
1330 assert( ! appExpr->get_function()->get_results().empty() );
1331 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1332 assert( pointer );
1333 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1334 assert( function );
1335 needs = needsAdapter( function, scopeTyVars );
1336 } // if
1337 } // if
1338 } // if
1339 } // if
1340 } // if
1341 addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
1342 if ( isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env ) || needs ) {
1343 Expression *ret = addrExpr->get_arg();
1344 delete ret->get_results().front();
1345 ret->get_results().front() = addrExpr->get_results().front()->clone();
1346 addrExpr->set_arg( 0 );
1347 delete addrExpr;
1348 return ret;
1349 } else {
1350 return addrExpr;
1351 } // if
1352 }
1353
1354 /// Wraps a function declaration in a new pointer-to-function variable expression
1355 VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
1356 // line below cloned from FixFunction.cc
1357 ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
1358 new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
1359 functionObj->set_mangleName( functionDecl->get_mangleName() );
1360 return new VariableExpr( functionObj );
1361 }
1362
1363 Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1364 if ( retval && returnStmt->get_expr() ) {
1365 assert( ! returnStmt->get_expr()->get_results().empty() );
1366 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1367 // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
1368 // by this point, a cast expr on a polymorphic return value is redundant
1369 while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1370 returnStmt->set_expr( castExpr->get_arg() );
1371 returnStmt->get_expr()->set_env( castExpr->get_env() );
1372 castExpr->set_env( 0 );
1373 castExpr->set_arg( 0 );
1374 delete castExpr;
1375 } //while
1376
1377 // find assignment operator for (polymorphic) return type
1378 ApplicationExpr *assignExpr = 0;
1379 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
1380 // find assignment operator for type variable
1381 std::map< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1382 if ( assignIter == assignOps.end() ) {
1383 throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1384 } // if
1385 assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
1386 } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
1387 // find assignment operator for generic type
1388 DeclarationWithType *functionDecl = scopedAssignOps.find( refType );
1389 if ( ! functionDecl ) {
1390 throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1391 }
1392
1393 // wrap it up in an application expression
1394 assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1395 assignExpr->set_env( env->clone() );
1396
1397 // find each of its needed secondary assignment operators
1398 std::list< Expression* > &tyParams = refType->get_parameters();
1399 std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1400 std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1401 std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1402 for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1403 if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue; // skip types with no assign op (ftype/dtype)
1404
1405 std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1406 assert( ! asserts.empty() && "Type param needs assignment operator assertion" );
1407 DeclarationWithType *actualDecl = asserts.front();
1408 TypeInstType *actualType = isTypeInstAssignment( actualDecl );
1409 assert( actualType && "First assertion of type with assertions should be assignment operator" );
1410 TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1411 assert( formalTypeExpr && "type parameters must be type expressions" );
1412 Type *formalType = formalTypeExpr->get_type();
1413 assignExpr->get_env()->add( actualType->get_name(), formalType );
1414
1415 DeclarationWithType *assertAssign = 0;
1416 if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1417 std::map< std::string, DeclarationWithType *>::const_iterator assertAssignIt = assignOps.find( formalTypeInstType->get_name() );
1418 if ( assertAssignIt == assignOps.end() ) {
1419 throw SemanticError( "No assignment operation found for ", formalTypeInstType );
1420 }
1421 assertAssign = assertAssignIt->second;
1422 } else {
1423 assertAssign = scopedAssignOps.find( formalType );
1424 if ( ! assertAssign ) {
1425 throw SemanticError( "No assignment operation found for ", formalType );
1426 }
1427 }
1428
1429
1430 assignExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1431 = ParamEntry( assertAssign->get_uniqueId(), assertAssign->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertAssign ) );
1432 }
1433 }
1434 assert( assignExpr );
1435
1436 // replace return statement with appropriate assignment to out parameter
1437 Expression *retParm = new NameExpr( retval->get_name() );
1438 retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1439 assignExpr->get_args().push_back( retParm );
1440 assignExpr->get_args().push_back( returnStmt->get_expr() );
1441 stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1442 // } else {
1443 // useRetval = true;
1444 // stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1445 // useRetval = false;
1446 // } // if
1447 returnStmt->set_expr( 0 );
1448 } else {
1449 returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
1450 } // if
1451 return returnStmt;
1452 }
1453
1454 Type * Pass1::mutate( PointerType *pointerType ) {
1455 TyVarMap oldtyVars = scopeTyVars;
1456 makeTyVarMap( pointerType, scopeTyVars );
1457
1458 Type *ret = Mutator::mutate( pointerType );
1459
1460 scopeTyVars = oldtyVars;
1461 return ret;
1462 }
1463
1464 Type * Pass1::mutate( FunctionType *functionType ) {
1465 TyVarMap oldtyVars = scopeTyVars;
1466 makeTyVarMap( functionType, scopeTyVars );
1467
1468 Type *ret = Mutator::mutate( functionType );
1469
1470 scopeTyVars = oldtyVars;
1471 return ret;
1472 }
1473
1474 void Pass1::doBeginScope() {
1475 adapters.beginScope();
1476 scopedAssignOps.beginScope();
1477 }
1478
1479 void Pass1::doEndScope() {
1480 adapters.endScope();
1481 scopedAssignOps.endScope();
1482 }
1483
1484////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1485
1486 void Pass2::addAdapters( FunctionType *functionType ) {
1487 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1488 std::list< FunctionType *> functions;
1489 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1490 Type *orig = (*arg)->get_type();
1491 findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1492 (*arg)->set_type( orig );
1493 }
1494 std::set< std::string > adaptersDone;
1495 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1496 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
1497 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1498 std::string adapterName = makeAdapterName( mangleName );
1499 paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
1500 adaptersDone.insert( adaptersDone.begin(), mangleName );
1501 }
1502 }
1503// deleteAll( functions );
1504 }
1505
1506 template< typename DeclClass >
1507 DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1508 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1509
1510 return ret;
1511 }
1512
1513 DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1514 return handleDecl( functionDecl, functionDecl->get_functionType() );
1515 }
1516
1517 ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1518 return handleDecl( objectDecl, objectDecl->get_type() );
1519 }
1520
1521 TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1522 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1523 if ( typeDecl->get_base() ) {
1524 return handleDecl( typeDecl, typeDecl->get_base() );
1525 } else {
1526 return Mutator::mutate( typeDecl );
1527 }
1528 }
1529
1530 TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1531 return handleDecl( typedefDecl, typedefDecl->get_base() );
1532 }
1533
1534 Type * Pass2::mutate( PointerType *pointerType ) {
1535 TyVarMap oldtyVars = scopeTyVars;
1536 makeTyVarMap( pointerType, scopeTyVars );
1537
1538 Type *ret = Mutator::mutate( pointerType );
1539
1540 scopeTyVars = oldtyVars;
1541 return ret;
1542 }
1543
1544 Type *Pass2::mutate( FunctionType *funcType ) {
1545 TyVarMap oldtyVars = scopeTyVars;
1546 makeTyVarMap( funcType, scopeTyVars );
1547
1548 // move polymorphic return type to parameter list
1549 if ( isPolyRet( funcType ) ) {
1550 DeclarationWithType *ret = funcType->get_returnVals().front();
1551 ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1552 funcType->get_parameters().push_front( ret );
1553 funcType->get_returnVals().pop_front();
1554 }
1555
1556 // add size/align and assertions for type parameters to parameter list
1557 std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1558 std::list< DeclarationWithType *> inferredParams;
1559 ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
1560 ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1561 new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
1562 for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
1563 ObjectDecl *sizeParm, *alignParm;
1564 // add all size and alignment parameters to parameter list
1565 if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
1566 TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
1567
1568 sizeParm = newObj.clone();
1569 sizeParm->set_name( sizeofName( &parmType ) );
1570 last = funcType->get_parameters().insert( last, sizeParm );
1571 ++last;
1572
1573 alignParm = newObj.clone();
1574 alignParm->set_name( alignofName( &parmType ) );
1575 last = funcType->get_parameters().insert( last, alignParm );
1576 ++last;
1577 }
1578 // move all assertions into parameter list
1579 for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
1580// *assert = (*assert)->acceptMutator( *this );
1581 inferredParams.push_back( *assert );
1582 }
1583 (*tyParm)->get_assertions().clear();
1584 }
1585
1586 // add size/align for generic parameter types to parameter list
1587 std::set< std::string > seenTypes; // sizeofName for generic types we've seen
1588 for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
1589 Type *polyBase = hasPolyBase( (*fnParm)->get_type(), scopeTyVars );
1590 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
1591 std::string sizeName = sizeofName( polyBase );
1592 if ( seenTypes.count( sizeName ) ) continue;
1593
1594 ObjectDecl *sizeParm, *alignParm, *offsetParm;
1595 sizeParm = newObj.clone();
1596 sizeParm->set_name( sizeName );
1597 last = funcType->get_parameters().insert( last, sizeParm );
1598 ++last;
1599
1600 alignParm = newObj.clone();
1601 alignParm->set_name( alignofName( polyBase ) );
1602 last = funcType->get_parameters().insert( last, alignParm );
1603 ++last;
1604
1605 if ( StructInstType *polyBaseStruct = dynamic_cast< StructInstType* >( polyBase ) ) {
1606 // NOTE zero-length arrays are illegal in C, so empty structs have no offset array
1607 if ( ! polyBaseStruct->get_baseStruct()->get_members().empty() ) {
1608 offsetParm = newPtr.clone();
1609 offsetParm->set_name( offsetofName( polyBase ) );
1610 last = funcType->get_parameters().insert( last, offsetParm );
1611 ++last;
1612 }
1613 }
1614
1615 seenTypes.insert( sizeName );
1616 knownLayouts.insert( sizeName ); // make sure that any type information passed into the function is accounted for
1617 }
1618 }
1619
1620 // splice assertion parameters into parameter list
1621 funcType->get_parameters().splice( last, inferredParams );
1622 addAdapters( funcType );
1623 mutateAll( funcType->get_returnVals(), *this );
1624 mutateAll( funcType->get_parameters(), *this );
1625
1626 scopeTyVars = oldtyVars;
1627 return funcType;
1628 }
1629
1630 ObjectDecl *Pass2::makeVar( const std::string &name, Type *type, Initializer *init ) {
1631 ObjectDecl *newObj = new ObjectDecl( name, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, init );
1632 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
1633 return newObj;
1634 }
1635
1636 void Pass2::addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams ) {
1637 for ( std::list< Type* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
1638 if ( findGeneric( *param ) ) {
1639 // push size/align vars for a generic parameter back
1640 layoutCall->get_args().push_back( new NameExpr( sizeofName( *param ) ) );
1641 layoutCall->get_args().push_back( new NameExpr( alignofName( *param ) ) );
1642 } else {
1643 layoutCall->get_args().push_back( new SizeofExpr( (*param)->clone() ) );
1644 layoutCall->get_args().push_back( new AlignofExpr( (*param)->clone() ) );
1645 }
1646 }
1647 }
1648
1649 /// returns true if any of the otype parameters have a dynamic layout and puts all otype parameters in the output list
1650 bool findGenericParams( std::list< TypeDecl* > &baseParams, std::list< Expression* > &typeParams, std::list< Type* > &out ) {
1651 bool hasDynamicLayout = false;
1652
1653 std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1654 std::list< Expression* >::const_iterator typeParam = typeParams.begin();
1655 for ( ; baseParam != baseParams.end() && typeParam != typeParams.end(); ++baseParam, ++typeParam ) {
1656 // skip non-otype parameters
1657 if ( (*baseParam)->get_kind() != TypeDecl::Any ) continue;
1658 TypeExpr *typeExpr = dynamic_cast< TypeExpr* >( *typeParam );
1659 assert( typeExpr && "all otype parameters should be type expressions" );
1660
1661 Type *type = typeExpr->get_type();
1662 out.push_back( type );
1663 if ( isPolyType( type ) ) hasDynamicLayout = true;
1664 }
1665 assert( baseParam == baseParams.end() && typeParam == typeParams.end() );
1666
1667 return hasDynamicLayout;
1668 }
1669
1670 bool Pass2::findGeneric( Type *ty ) {
1671 if ( dynamic_cast< TypeInstType* >( ty ) ) {
1672 // NOTE this assumes that all type variables will be properly bound, and thus have their layouts in scope
1673 return true;
1674 } else if ( StructInstType *structTy = dynamic_cast< StructInstType* >( ty ) ) {
1675 // check if this type already has a layout generated for it
1676 std::string sizeName = sizeofName( ty );
1677 if ( knownLayouts.find( sizeName ) != knownLayouts.end() ) return true;
1678
1679 // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1680 std::list< Type* > otypeParams;
1681 if ( ! findGenericParams( *structTy->get_baseParameters(), structTy->get_parameters(), otypeParams ) ) return false;
1682
1683 // insert local variables for layout and generate call to layout function
1684 knownLayouts.insert( sizeName ); // done early so as not to interfere with the later addition of parameters to the layout call
1685 Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1686
1687 int n_members = structTy->get_baseStruct()->get_members().size();
1688 if ( n_members == 0 ) {
1689 // all empty structs have the same layout - size 1, align 1
1690 makeVar( sizeName, layoutType, new SingleInit( new ConstantExpr( Constant::from( (unsigned long)1 ) ) ) );
1691 makeVar( alignofName( ty ), layoutType->clone(), new SingleInit( new ConstantExpr( Constant::from( (unsigned long)1 ) ) ) );
1692 // NOTE zero-length arrays are forbidden in C, so empty structs have no offsetof array
1693 } else {
1694 ObjectDecl *sizeVar = makeVar( sizeName, layoutType );
1695 ObjectDecl *alignVar = makeVar( alignofName( ty ), layoutType->clone() );
1696 ObjectDecl *offsetVar = makeVar( offsetofName( ty ), new ArrayType( Type::Qualifiers(), layoutType->clone(), new ConstantExpr( Constant::from( n_members ) ), false, false ) );
1697
1698 // generate call to layout function
1699 UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( "__layoutof_" + structTy->get_baseStruct()->get_name() ) );
1700 layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1701 layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1702 layoutCall->get_args().push_back( new VariableExpr( offsetVar ) );
1703 addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1704
1705 stmtsToAdd.push_back( new ExprStmt( noLabels, layoutCall ) );
1706 }
1707
1708 return true;
1709 } else if ( UnionInstType *unionTy = dynamic_cast< UnionInstType* >( ty ) ) {
1710 // check if this type already has a layout generated for it
1711 std::string sizeName = sizeofName( ty );
1712 if ( knownLayouts.find( sizeName ) != knownLayouts.end() ) return true;
1713
1714 // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1715 std::list< Type* > otypeParams;
1716 if ( ! findGenericParams( *unionTy->get_baseParameters(), unionTy->get_parameters(), otypeParams ) ) return false;
1717
1718 // insert local variables for layout and generate call to layout function
1719 knownLayouts.insert( sizeName ); // done early so as not to interfere with the later addition of parameters to the layout call
1720 Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1721
1722 ObjectDecl *sizeVar = makeVar( sizeName, layoutType );
1723 ObjectDecl *alignVar = makeVar( alignofName( ty ), layoutType->clone() );
1724
1725 // generate call to layout function
1726 UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( "__layoutof_" + unionTy->get_baseUnion()->get_name() ) );
1727 layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1728 layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1729 addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1730
1731 stmtsToAdd.push_back( new ExprStmt( noLabels, layoutCall ) );
1732
1733 return true;
1734 }
1735
1736 return false;
1737 }
1738
1739 Expression *Pass2::mutate( SizeofExpr *sizeofExpr ) {
1740 Type *ty = sizeofExpr->get_type();
1741 if ( findGeneric( ty ) ) {
1742 Expression *ret = new NameExpr( sizeofName( ty ) );
1743 delete sizeofExpr;
1744 return ret;
1745 }
1746 return sizeofExpr;
1747 }
1748
1749 Expression *Pass2::mutate( AlignofExpr *alignofExpr ) {
1750 Type *ty = alignofExpr->get_type();
1751 if ( findGeneric( ty ) ) {
1752 Expression *ret = new NameExpr( alignofName( ty ) );
1753 delete alignofExpr;
1754 return ret;
1755 }
1756 return alignofExpr;
1757 }
1758
1759 Expression *Pass2::mutate( OffsetofExpr *offsetofExpr ) {
1760 findGeneric( offsetofExpr->get_type() );
1761 return offsetofExpr;
1762 }
1763
1764 Expression *Pass2::mutate( OffsetPackExpr *offsetPackExpr ) {
1765 StructInstType *ty = offsetPackExpr->get_type();
1766
1767 Expression *ret = 0;
1768 if ( findGeneric( ty ) ) {
1769 // pull offset back from generated type information
1770 ret = new NameExpr( offsetofName( ty ) );
1771 } else {
1772 std::string offsetName = offsetofName( ty );
1773 if ( knownOffsets.find( offsetName ) != knownOffsets.end() ) {
1774 // use the already-generated offsets for this type
1775 ret = new NameExpr( offsetName );
1776 } else {
1777 std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
1778 Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1779
1780 // build initializer list for offset array
1781 std::list< Initializer* > inits;
1782 for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
1783 DeclarationWithType *memberDecl;
1784 if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
1785 memberDecl = origMember->clone();
1786 } else {
1787 memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
1788 }
1789 inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
1790 }
1791
1792 // build the offset array and replace the pack with a reference to it
1793 ObjectDecl *offsetArray = makeVar( offsetName, new ArrayType( Type::Qualifiers(), offsetType, new ConstantExpr( Constant::from( baseMembers.size() ) ), false, false ),
1794 new ListInit( inits ) );
1795 ret = new VariableExpr( offsetArray );
1796 }
1797 }
1798
1799 delete offsetPackExpr;
1800 return ret;
1801 }
1802
1803 void Pass2::doBeginScope() {
1804 knownLayouts.beginScope();
1805 knownOffsets.beginScope();
1806 }
1807
1808 void Pass2::doEndScope() {
1809 knownLayouts.endScope();
1810 knownOffsets.beginScope();
1811 }
1812
1813//////////////////////////////////////// GenericInstantiator //////////////////////////////////////////////////
1814
1815 /// Makes substitutions of params into baseParams; returns true if all parameters substituted for a concrete type
1816 bool makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
1817 bool allConcrete = true; // will finish the substitution list even if they're not all concrete
1818
1819 // substitute concrete types for given parameters, and incomplete types for placeholders
1820 std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1821 std::list< Expression* >::const_iterator param = params.begin();
1822 for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
1823 // switch ( (*baseParam)->get_kind() ) {
1824 // case TypeDecl::Any: { // any type is a valid substitution here; complete types can be used to instantiate generics
1825 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
1826 assert(paramType && "Aggregate parameters should be type expressions");
1827 out.push_back( paramType->clone() );
1828 // check that the substituted type isn't a type variable itself
1829 if ( dynamic_cast< TypeInstType* >( paramType->get_type() ) ) {
1830 allConcrete = false;
1831 }
1832 // break;
1833 // }
1834 // case TypeDecl::Dtype: // dtype can be consistently replaced with void [only pointers, which become void*]
1835 // out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
1836 // break;
1837 // case TypeDecl::Ftype: // pointer-to-ftype can be consistently replaced with void (*)(void) [similar to dtype]
1838 // out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
1839 // break;
1840 // }
1841 }
1842
1843 // if any parameters left over, not done
1844 if ( baseParam != baseParams.end() ) return false;
1845 // // if not enough parameters given, substitute remaining incomplete types for placeholders
1846 // for ( ; baseParam != baseParams.end(); ++baseParam ) {
1847 // switch ( (*baseParam)->get_kind() ) {
1848 // case TypeDecl::Any: // no more substitutions here, fail early
1849 // return false;
1850 // case TypeDecl::Dtype: // dtype can be consistently replaced with void [only pointers, which become void*]
1851 // out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
1852 // break;
1853 // case TypeDecl::Ftype: // pointer-to-ftype can be consistently replaced with void (*)(void) [similar to dtype]
1854 // out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
1855 // break;
1856 // }
1857 // }
1858
1859 return allConcrete;
1860 }
1861
1862 /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
1863 void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
1864 std::list< Declaration* >& out ) {
1865 // substitute types into new members
1866 TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
1867 for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
1868 Declaration *newMember = (*member)->clone();
1869 subs.apply(newMember);
1870 out.push_back( newMember );
1871 }
1872 }
1873
1874 Type* GenericInstantiator::mutate( StructInstType *inst ) {
1875 // mutate subtypes
1876 Type *mutated = Mutator::mutate( inst );
1877 inst = dynamic_cast< StructInstType* >( mutated );
1878 if ( ! inst ) return mutated;
1879
1880 // exit early if no need for further mutation
1881 if ( inst->get_parameters().empty() ) return inst;
1882 assert( inst->get_baseParameters() && "Base struct has parameters" );
1883
1884 // check if type can be concretely instantiated; put substitutions into typeSubs
1885 std::list< TypeExpr* > typeSubs;
1886 if ( ! makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs ) ) {
1887 deleteAll( typeSubs );
1888 return inst;
1889 }
1890
1891 // make concrete instantiation of generic type
1892 StructDecl *concDecl = lookup( inst, typeSubs );
1893 if ( ! concDecl ) {
1894 // set concDecl to new type, insert type declaration into statements to add
1895 concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
1896 substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
1897 DeclMutator::addDeclaration( concDecl );
1898 insert( inst, typeSubs, concDecl );
1899 }
1900 StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
1901 newInst->set_baseStruct( concDecl );
1902
1903 deleteAll( typeSubs );
1904 delete inst;
1905 return newInst;
1906 }
1907
1908 Type* GenericInstantiator::mutate( UnionInstType *inst ) {
1909 // mutate subtypes
1910 Type *mutated = Mutator::mutate( inst );
1911 inst = dynamic_cast< UnionInstType* >( mutated );
1912 if ( ! inst ) return mutated;
1913
1914 // exit early if no need for further mutation
1915 if ( inst->get_parameters().empty() ) return inst;
1916 assert( inst->get_baseParameters() && "Base union has parameters" );
1917
1918 // check if type can be concretely instantiated; put substitutions into typeSubs
1919 std::list< TypeExpr* > typeSubs;
1920 if ( ! makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs ) ) {
1921 deleteAll( typeSubs );
1922 return inst;
1923 }
1924
1925 // make concrete instantiation of generic type
1926 UnionDecl *concDecl = lookup( inst, typeSubs );
1927 if ( ! concDecl ) {
1928 // set concDecl to new type, insert type declaration into statements to add
1929 concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
1930 substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
1931 DeclMutator::addDeclaration( concDecl );
1932 insert( inst, typeSubs, concDecl );
1933 }
1934 UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
1935 newInst->set_baseUnion( concDecl );
1936
1937 deleteAll( typeSubs );
1938 delete inst;
1939 return newInst;
1940 }
1941
1942 // /// Gets the base struct or union declaration for a member expression; NULL if not applicable
1943 // AggregateDecl* getMemberBaseDecl( MemberExpr *memberExpr ) {
1944 // // get variable for member aggregate
1945 // VariableExpr *varExpr = dynamic_cast< VariableExpr* >( memberExpr->get_aggregate() );
1946 // if ( ! varExpr ) return NULL;
1947 //
1948 // // get object for variable
1949 // ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1950 // if ( ! objectDecl ) return NULL;
1951 //
1952 // // get base declaration from object type
1953 // Type *objectType = objectDecl->get_type();
1954 // StructInstType *structType = dynamic_cast< StructInstType* >( objectType );
1955 // if ( structType ) return structType->get_baseStruct();
1956 // UnionInstType *unionType = dynamic_cast< UnionInstType* >( objectType );
1957 // if ( unionType ) return unionType->get_baseUnion();
1958 //
1959 // return NULL;
1960 // }
1961 //
1962 // /// Finds the declaration with the given name, returning decls.end() if none such
1963 // std::list< Declaration* >::const_iterator findDeclNamed( const std::list< Declaration* > &decls, const std::string &name ) {
1964 // for( std::list< Declaration* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
1965 // if ( (*decl)->get_name() == name ) return decl;
1966 // }
1967 // return decls.end();
1968 // }
1969 //
1970 // Expression* Instantiate::mutate( MemberExpr *memberExpr ) {
1971 // // mutate, exiting early if no longer MemberExpr
1972 // Expression *expr = Mutator::mutate( memberExpr );
1973 // memberExpr = dynamic_cast< MemberExpr* >( expr );
1974 // if ( ! memberExpr ) return expr;
1975 //
1976 // // get declaration of member and base declaration of member, exiting early if not found
1977 // AggregateDecl *memberBase = getMemberBaseDecl( memberExpr );
1978 // if ( ! memberBase ) return memberExpr;
1979 // DeclarationWithType *memberDecl = memberExpr->get_member();
1980 // std::list< Declaration* >::const_iterator baseIt = findDeclNamed( memberBase->get_members(), memberDecl->get_name() );
1981 // if ( baseIt == memberBase->get_members().end() ) return memberExpr;
1982 // DeclarationWithType *baseDecl = dynamic_cast< DeclarationWithType* >( *baseIt );
1983 // if ( ! baseDecl ) return memberExpr;
1984 //
1985 // // check if stated type of the member is not the type of the member's declaration; if so, need a cast
1986 // // this *SHOULD* be safe, I don't think anything but the void-replacements I put in for dtypes would make it past the typechecker
1987 // SymTab::Indexer dummy;
1988 // if ( ResolvExpr::typesCompatible( memberDecl->get_type(), baseDecl->get_type(), dummy ) ) return memberExpr;
1989 // else return new CastExpr( memberExpr, memberDecl->get_type() );
1990 // }
1991
1992 void GenericInstantiator::doBeginScope() {
1993 DeclMutator::doBeginScope();
1994 instantiations.beginScope();
1995 }
1996
1997 void GenericInstantiator::doEndScope() {
1998 DeclMutator::doEndScope();
1999 instantiations.endScope();
2000 }
2001
2002////////////////////////////////////////// MemberExprFixer ////////////////////////////////////////////////////
2003
2004 template< typename DeclClass >
2005 DeclClass * MemberExprFixer::handleDecl( DeclClass *decl, Type *type ) {
2006 TyVarMap oldtyVars = scopeTyVars;
2007 makeTyVarMap( type, scopeTyVars );
2008
2009 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
2010
2011 scopeTyVars = oldtyVars;
2012 return ret;
2013 }
2014
2015 ObjectDecl * MemberExprFixer::mutate( ObjectDecl *objectDecl ) {
2016 return handleDecl( objectDecl, objectDecl->get_type() );
2017 }
2018
2019 DeclarationWithType * MemberExprFixer::mutate( FunctionDecl *functionDecl ) {
2020 return handleDecl( functionDecl, functionDecl->get_functionType() );
2021 }
2022
2023 TypedefDecl * MemberExprFixer::mutate( TypedefDecl *typedefDecl ) {
2024 return handleDecl( typedefDecl, typedefDecl->get_base() );
2025 }
2026
2027 TypeDecl * MemberExprFixer::mutate( TypeDecl *typeDecl ) {
2028 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2029 return Mutator::mutate( typeDecl );
2030 }
2031
2032 Type * MemberExprFixer::mutate( PointerType *pointerType ) {
2033 TyVarMap oldtyVars = scopeTyVars;
2034 makeTyVarMap( pointerType, scopeTyVars );
2035
2036 Type *ret = Mutator::mutate( pointerType );
2037
2038 scopeTyVars = oldtyVars;
2039 return ret;
2040 }
2041
2042 Type * MemberExprFixer::mutate( FunctionType *functionType ) {
2043 TyVarMap oldtyVars = scopeTyVars;
2044 makeTyVarMap( functionType, scopeTyVars );
2045
2046 Type *ret = Mutator::mutate( functionType );
2047
2048 scopeTyVars = oldtyVars;
2049 return ret;
2050 }
2051
2052 Statement *MemberExprFixer::mutate( DeclStmt *declStmt ) {
2053 if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
2054 if ( isPolyType( objectDecl->get_type(), scopeTyVars ) ) {
2055 // change initialization of a polymorphic value object
2056 // to allocate storage with alloca
2057 Type *declType = objectDecl->get_type();
2058 UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
2059 alloc->get_args().push_back( new NameExpr( sizeofName( declType ) ) );
2060
2061 delete objectDecl->get_init();
2062
2063 std::list<Expression*> designators;
2064 objectDecl->set_init( new SingleInit( alloc, designators ) );
2065 }
2066 }
2067 return Mutator::mutate( declStmt );
2068 }
2069
2070 /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
2071 long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
2072 long i = 0;
2073 for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
2074 if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
2075
2076 if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
2077 if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
2078 || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
2079 else continue;
2080 } else return i;
2081 }
2082 return -1;
2083 }
2084
2085 /// Returns an index expression into the offset array for a type
2086 Expression *makeOffsetIndex( Type *objectType, long i ) {
2087 std::stringstream offset_namer;
2088 offset_namer << i;
2089 ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
2090 UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
2091 fieldOffset->get_args().push_back( new NameExpr( offsetofName( objectType ) ) );
2092 fieldOffset->get_args().push_back( fieldIndex );
2093 return fieldOffset;
2094 }
2095
2096 /// Returns an expression dereferenced n times
2097 Expression *makeDerefdVar( Expression *derefdVar, long n ) {
2098 for ( int i = 1; i < n; ++i ) {
2099 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
2100 derefExpr->get_args().push_back( derefdVar );
2101 derefdVar = derefExpr;
2102 }
2103 return derefdVar;
2104 }
2105
2106 Expression *MemberExprFixer::mutate( MemberExpr *memberExpr ) {
2107 // mutate, exiting early if no longer MemberExpr
2108 Expression *expr = Mutator::mutate( memberExpr );
2109 memberExpr = dynamic_cast< MemberExpr* >( expr );
2110 if ( ! memberExpr ) return expr;
2111
2112 // get declaration for base struct, exiting early if not found
2113 int varDepth;
2114 VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
2115 if ( ! varExpr ) return memberExpr;
2116 ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
2117 if ( ! objectDecl ) return memberExpr;
2118
2119 // only mutate member expressions for polymorphic types
2120 int tyDepth;
2121 Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
2122 if ( ! objectType ) return memberExpr;
2123
2124 Expression *newMemberExpr = 0;
2125 if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
2126 // look up offset index
2127 long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
2128 if ( i == -1 ) return memberExpr;
2129
2130 // replace member expression with pointer to base plus offset
2131 UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
2132 fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
2133 fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
2134 newMemberExpr = fieldLoc;
2135 } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
2136 // union members are all at offset zero, so build appropriately-dereferenced variable
2137 newMemberExpr = makeDerefdVar( varExpr->clone(), varDepth );
2138 } else return memberExpr;
2139 assert( newMemberExpr );
2140
2141 Type *memberType = memberExpr->get_member()->get_type();
2142 if ( ! isPolyType( memberType, scopeTyVars ) ) {
2143 // Not all members of a polymorphic type are themselves of polymorphic type; in this case the member expression should be wrapped and dereferenced to form an lvalue
2144 CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
2145 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
2146 derefExpr->get_args().push_back( ptrCastExpr );
2147 newMemberExpr = derefExpr;
2148 }
2149
2150 delete memberExpr;
2151 return newMemberExpr;
2152 }
2153
2154 Expression *MemberExprFixer::mutate( OffsetofExpr *offsetofExpr ) {
2155 // mutate, exiting early if no longer OffsetofExpr
2156 Expression *expr = Mutator::mutate( offsetofExpr );
2157 offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
2158 if ( ! offsetofExpr ) return expr;
2159
2160 // only mutate expressions for polymorphic structs/unions
2161 Type *ty = isPolyType( offsetofExpr->get_type(), scopeTyVars );
2162 if ( ! ty ) return offsetofExpr;
2163
2164 if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
2165 // replace offsetof expression by index into offset array
2166 long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
2167 if ( i == -1 ) return offsetofExpr;
2168
2169 Expression *offsetInd = makeOffsetIndex( ty, i );
2170 delete offsetofExpr;
2171 return offsetInd;
2172 } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
2173 // all union members are at offset zero
2174 delete offsetofExpr;
2175 return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), std::string("0") ) );
2176 } else return offsetofExpr;
2177 }
2178
2179////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
2180
2181 template< typename DeclClass >
2182 DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
2183 TyVarMap oldtyVars = scopeTyVars;
2184 makeTyVarMap( type, scopeTyVars );
2185
2186 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
2187 ScrubTyVars::scrub( decl, scopeTyVars );
2188
2189 scopeTyVars = oldtyVars;
2190 return ret;
2191 }
2192
2193 ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
2194 return handleDecl( objectDecl, objectDecl->get_type() );
2195 }
2196
2197 DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
2198 return handleDecl( functionDecl, functionDecl->get_functionType() );
2199 }
2200
2201 TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
2202 return handleDecl( typedefDecl, typedefDecl->get_base() );
2203 }
2204
2205 TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
2206// Initializer *init = 0;
2207// std::list< Expression *> designators;
2208// scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2209// if ( typeDecl->get_base() ) {
2210// init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
2211// }
2212// return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
2213
2214 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2215 return Mutator::mutate( typeDecl );
2216 }
2217
2218 Type * Pass3::mutate( PointerType *pointerType ) {
2219 TyVarMap oldtyVars = scopeTyVars;
2220 makeTyVarMap( pointerType, scopeTyVars );
2221
2222 Type *ret = Mutator::mutate( pointerType );
2223
2224 scopeTyVars = oldtyVars;
2225 return ret;
2226 }
2227
2228 Type * Pass3::mutate( FunctionType *functionType ) {
2229 TyVarMap oldtyVars = scopeTyVars;
2230 makeTyVarMap( functionType, scopeTyVars );
2231
2232 Type *ret = Mutator::mutate( functionType );
2233
2234 scopeTyVars = oldtyVars;
2235 return ret;
2236 }
2237 } // anonymous namespace
2238} // namespace GenPoly
2239
2240// Local Variables: //
2241// tab-width: 4 //
2242// mode: c++ //
2243// compile-command: "make install" //
2244// End: //
Note: See TracBrowser for help on using the repository browser.