source: src/GenPoly/Box.cc@ 33e6a2cc

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 33e6a2cc was 4067aa8, checked in by Aaron Moss <a3moss@…>, 10 years ago

Fix non-polymorphic members of polymorphic types (general case of Thierry's pointer bug)

  • Property mode set to 100644
File size: 69.0 KB
RevLine 
[51587aa]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//
[ae63a18]7// Box.cc --
[51587aa]8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
[bd85400]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Feb 5 16:45:07 2016
13// Update Count : 286
[51587aa]14//
[51b73452]15
16#include <set>
[b1a6d6b]17#include <stack>
[51b73452]18#include <string>
19#include <iterator>
20#include <algorithm>
21#include <cassert>
22
23#include "Box.h"
[05d47278]24#include "InstantiateGeneric.h"
[51b73452]25#include "PolyMutator.h"
26#include "FindFunction.h"
27#include "ScrubTyVars.h"
28
[68cd1ce]29#include "Parser/ParseNode.h"
30
[cdec5af]31#include "SynTree/Constant.h"
[51b73452]32#include "SynTree/Type.h"
33#include "SynTree/Expression.h"
34#include "SynTree/Initializer.h"
35#include "SynTree/Statement.h"
36#include "SynTree/Mutator.h"
[68cd1ce]37
[51b73452]38#include "ResolvExpr/TypeEnvironment.h"
[dc12481]39#include "ResolvExpr/TypeMap.h"
40#include "ResolvExpr/typeops.h"
[68cd1ce]41
[51b73452]42#include "SymTab/Mangler.h"
43
[d3b7937]44#include "Common/SemanticError.h"
45#include "Common/UniqueName.h"
46#include "Common/utility.h"
[51b73452]47
48#include <ext/functional> // temporary
49
50namespace GenPoly {
[01aeade]51 namespace {
52 const std::list<Label> noLabels;
53
[e56cfdb0]54 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
55
[f8b961b]56 /// 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
[01aeade]57 class Pass1 : public PolyMutator {
58 public:
59 Pass1();
60 virtual Expression *mutate( ApplicationExpr *appExpr );
61 virtual Expression *mutate( AddressExpr *addrExpr );
62 virtual Expression *mutate( UntypedExpr *expr );
63 virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
64 virtual TypeDecl *mutate( TypeDecl *typeDecl );
65 virtual Expression *mutate( CommaExpr *commaExpr );
66 virtual Expression *mutate( ConditionalExpr *condExpr );
[cf16f94]67 virtual Statement * mutate( ReturnStmt *returnStmt );
[01aeade]68 virtual Type *mutate( PointerType *pointerType );
[cf16f94]69 virtual Type * mutate( FunctionType *functionType );
[ae63a18]70
[01aeade]71 virtual void doBeginScope();
72 virtual void doEndScope();
73 private:
[05d47278]74 /// Makes a new temporary array holding the offsets of the fields of `type`, and returns a new variable expression referencing it
75 Expression *makeOffsetArray( StructInstType *type );
[5c52b06]76 /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
77 void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
[05d47278]78 /// passes extra type parameters into a polymorphic function application
[5c52b06]79 void passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
[48ca586]80 /// wraps a function application with a new temporary for the out-parameter return value
[01aeade]81 Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
[48ca586]82 /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
83 void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
84 /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
85 /// If `doClone` is set to false, will not clone interior types
86 Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
87 /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
88 Expression *addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg );
[01aeade]89 Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
90 void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
91 void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
92 void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
[1194734]93 /// Stores assignment operators from assertion list in local map of assignment operations
[01aeade]94 void findAssignOps( const std::list< TypeDecl *> &forall );
95 void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
96 FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
[05d47278]97 /// Replaces intrinsic operator functions with their arithmetic desugaring
[01aeade]98 Expression *handleIntrinsics( ApplicationExpr *appExpr );
[05d47278]99 /// Inserts a new temporary variable into the current scope with an auto-generated name
[01aeade]100 ObjectDecl *makeTemporary( Type *type );
[c29d9ce]101
[e56cfdb0]102 typedef std::map< std::string, DeclarationWithType *> AdapterMap;
[c29d9ce]103 std::map< std::string, DeclarationWithType *> assignOps;
[dc12481]104 ResolvExpr::TypeMap< DeclarationWithType > scopedAssignOps;
[01aeade]105 std::stack< AdapterMap > adapters;
106 DeclarationWithType *retval;
107 bool useRetval;
108 UniqueName tempNamer;
109 };
110
[f8b961b]111 /// Moves polymorphic returns in function types to pointer-type parameters, adds type size and assertion parameters to parameter lists as well
[01aeade]112 class Pass2 : public PolyMutator {
113 public:
114 template< typename DeclClass >
115 DeclClass *handleDecl( DeclClass *decl, Type *type );
116 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
117 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
118 virtual TypeDecl *mutate( TypeDecl *typeDecl );
119 virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
120 virtual Type *mutate( PointerType *pointerType );
121 virtual Type *mutate( FunctionType *funcType );
122 private:
123 void addAdapters( FunctionType *functionType );
[ae63a18]124
[01aeade]125 std::map< UniqueId, std::string > adapterName;
126 };
127
[2a4b088]128 /// Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference;
129 /// also fixes offsetof expressions.
[05d47278]130 class MemberExprFixer : public PolyMutator {
131 public:
132 template< typename DeclClass >
133 DeclClass *handleDecl( DeclClass *decl, Type *type );
134 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
135 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
136 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
137 virtual TypeDecl *mutate( TypeDecl *objectDecl );
138 virtual Statement *mutate( DeclStmt *declStmt );
139 virtual Type *mutate( PointerType *pointerType );
140 virtual Type *mutate( FunctionType *funcType );
141 virtual Expression *mutate( MemberExpr *memberExpr );
[2a4b088]142 virtual Expression *mutate( OffsetofExpr *offsetofExpr );
[05d47278]143 };
[b4cd03b7]144
[f8b961b]145 /// 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
[01aeade]146 class Pass3 : public PolyMutator {
147 public:
148 template< typename DeclClass >
149 DeclClass *handleDecl( DeclClass *decl, Type *type );
150 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
151 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
152 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
153 virtual TypeDecl *mutate( TypeDecl *objectDecl );
154 virtual Type *mutate( PointerType *pointerType );
155 virtual Type *mutate( FunctionType *funcType );
156 private:
157 };
158
159 } // anonymous namespace
160
161 void printAllNotBuiltin( const std::list< Declaration *>& translationUnit, std::ostream &os ) {
162 for ( std::list< Declaration *>::const_iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
163 if ( ! LinkageSpec::isBuiltin( (*i)->get_linkage() ) ) {
164 (*i)->print( os );
165 os << std::endl;
[6c3744e]166 } // if
[01aeade]167 } // for
[6c3744e]168 }
169
[05d47278]170 /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
171 template< typename MutatorType >
172 inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
173 bool seenIntrinsic = false;
174 SemanticError errors;
175 for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
176 try {
177 if ( *i ) {
178 if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
179 seenIntrinsic = true;
180 } else if ( seenIntrinsic ) {
181 seenIntrinsic = false; // break on this line when debugging for end of prelude
182 }
[b4cd03b7]183
[05d47278]184 *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
185 assert( *i );
186 } // if
187 } catch( SemanticError &e ) {
188 errors.append( e );
189 } // try
190 } // for
191 if ( ! errors.isEmpty() ) {
192 throw errors;
193 } // if
194 }
195
[01aeade]196 void box( std::list< Declaration *>& translationUnit ) {
197 Pass1 pass1;
198 Pass2 pass2;
[05d47278]199 MemberExprFixer memberFixer;
[01aeade]200 Pass3 pass3;
[05d47278]201 mutateTranslationUnit/*All*/( translationUnit, pass1 );
202 mutateTranslationUnit/*All*/( translationUnit, pass2 );
203 instantiateGeneric( translationUnit );
204 mutateTranslationUnit/*All*/( translationUnit, memberFixer );
205 mutateTranslationUnit/*All*/( translationUnit, pass3 );
[6c3744e]206 }
207
[01aeade]208 ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
209
210 namespace {
[bdf1954]211 std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
212 std::stringstream name;
213
[ed1065c]214 // NOTE: this function previously used isPolyObj, which failed to produce
215 // the correct thing in some situations. It's not clear to me why this wasn't working.
216
[ae63a18]217 // if the return type or a parameter type involved polymorphic types, then the adapter will need
218 // to take those polymorphic types as pointers. Therefore, there can be two different functions
[bdf1954]219 // with the same mangled name, so we need to further mangle the names.
[ed1065c]220 for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
[ffad73a]221 if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
[ed1065c]222 name << "P";
223 } else {
224 name << "M";
225 }
[bdf1954]226 }
227 name << "_";
228 std::list< DeclarationWithType *> &paramList = function->get_parameters();
229 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
[ffad73a]230 if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
[bdf1954]231 name << "P";
232 } else {
[ae63a18]233 name << "M";
[bdf1954]234 }
235 } // for
236 return name.str();
237 }
238
239 std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
240 return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
241 }
242
[01aeade]243 std::string makeAdapterName( const std::string &mangleName ) {
244 return "_adapter" + mangleName;
245 }
[6c3744e]246
[56fcd77]247 Pass1::Pass1() : useRetval( false ), tempNamer( "_temp" ) {
[e56cfdb0]248 adapters.push(AdapterMap());
[01aeade]249 }
250
[dc12481]251 /// Returns T if the given declaration is (*?=?)(T *, T) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
252 TypeInstType *isTypeInstAssignment( DeclarationWithType *decl ) {
[01aeade]253 if ( decl->get_name() == "?=?" ) {
[1194734]254 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
255 if ( funType->get_parameters().size() == 2 ) {
256 if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
[dc12481]257 if ( TypeInstType *refType = dynamic_cast< TypeInstType *>( pointer->get_base() ) ) {
258 if ( TypeInstType *refType2 = dynamic_cast< TypeInstType *>( funType->get_parameters().back()->get_type() ) ) {
[1194734]259 if ( refType->get_name() == refType2->get_name() ) {
260 return refType;
[cf16f94]261 } // if
[01aeade]262 } // if
263 } // if
264 } // if
265 } // if
266 } // if
267 } // if
[1194734]268 return 0;
[01aeade]269 }
[dc12481]270
271 /// returns T if the given declaration is: (*?=?)(T *, T) for some type T (return not checked, but maybe should be), NULL otherwise
272 /// Only picks assignments where neither parameter is cv-qualified
273 Type *isAssignment( DeclarationWithType *decl ) {
274 if ( decl->get_name() == "?=?" ) {
275 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
276 if ( funType->get_parameters().size() == 2 ) {
277 Type::Qualifiers defaultQualifiers;
278 Type *paramType1 = funType->get_parameters().front()->get_type();
279 if ( paramType1->get_qualifiers() != defaultQualifiers ) return 0;
280 Type *paramType2 = funType->get_parameters().back()->get_type();
281 if ( paramType2->get_qualifiers() != defaultQualifiers ) return 0;
282
283 if ( PointerType *pointerType = dynamic_cast< PointerType* >( paramType1 ) ) {
284 Type *baseType1 = pointerType->get_base();
285 if ( baseType1->get_qualifiers() != defaultQualifiers ) return 0;
286 SymTab::Indexer dummy;
287 if ( ResolvExpr::typesCompatible( baseType1, paramType2, dummy ) ) {
288 return baseType1;
289 } // if
290 } // if
291 } // if
292 } // if
293 } // if
294 return 0;
295 }
[01aeade]296
297 void Pass1::findAssignOps( const std::list< TypeDecl *> &forall ) {
[ed1065c]298 // what if a nested function uses an assignment operator?
299 // assignOps.clear();
[01aeade]300 for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
301 for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
302 std::string typeName;
[dc12481]303 if ( TypeInstType *typeInst = isTypeInstAssignment( *assert ) ) {
[1194734]304 assignOps[ typeInst->get_name() ] = *assert;
[01aeade]305 } // if
306 } // for
307 } // for
308 }
309
[82dd287]310 DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
[1194734]311 // if this is a polymorphic assignment function, put it in the map for this scope
[dc12481]312 if ( Type *assignedType = isAssignment( functionDecl ) ) {
313 if ( ! dynamic_cast< TypeInstType* >( assignedType ) ) {
314 scopedAssignOps.insert( assignedType, functionDecl );
[1194734]315 }
316 }
[b4cd03b7]317
[e56cfdb0]318 if ( functionDecl->get_statements() ) { // empty routine body ?
319 doBeginScope();
[01aeade]320 TyVarMap oldtyVars = scopeTyVars;
[ed1065c]321 std::map< std::string, DeclarationWithType *> oldassignOps = assignOps;
[01aeade]322 DeclarationWithType *oldRetval = retval;
323 bool oldUseRetval = useRetval;
[e56cfdb0]324
325 // process polymorphic return value
[01aeade]326 retval = 0;
[aadc9a4]327 if ( isPolyRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
[01aeade]328 retval = functionDecl->get_functionType()->get_returnVals().front();
[ae63a18]329
[01aeade]330 // give names to unnamed return values
331 if ( retval->get_name() == "" ) {
332 retval->set_name( "_retparm" );
333 retval->set_linkage( LinkageSpec::C );
334 } // if
335 } // if
[ae63a18]336
[e56cfdb0]337 FunctionType *functionType = functionDecl->get_functionType();
[01aeade]338 makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
339 findAssignOps( functionDecl->get_functionType()->get_forall() );
[e56cfdb0]340
341 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
342 std::list< FunctionType *> functions;
343 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
344 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
345 findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
346 } // for
347 } // for
348 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
349 findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
350 } // for
[b4cd03b7]351
[e56cfdb0]352 AdapterMap & adapters = Pass1::adapters.top();
353 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[bdf1954]354 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
[e56cfdb0]355 if ( adapters.find( mangleName ) == adapters.end() ) {
356 std::string adapterName = makeAdapterName( mangleName );
357 adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
358 } // if
359 } // for
360
[01aeade]361 functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
[ae63a18]362
[01aeade]363 scopeTyVars = oldtyVars;
[ed1065c]364 assignOps = oldassignOps;
[e56cfdb0]365 // std::cerr << "end FunctionDecl: ";
366 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
367 // std::cerr << i->first << " ";
368 // }
369 // std::cerr << "\n";
[01aeade]370 retval = oldRetval;
371 useRetval = oldUseRetval;
[e56cfdb0]372 doEndScope();
[01aeade]373 } // if
374 return functionDecl;
375 }
[6c3744e]376
[01aeade]377 TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
378 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
379 return Mutator::mutate( typeDecl );
380 }
[6c3744e]381
[01aeade]382 Expression *Pass1::mutate( CommaExpr *commaExpr ) {
383 bool oldUseRetval = useRetval;
384 useRetval = false;
385 commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
386 useRetval = oldUseRetval;
387 commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
388 return commaExpr;
389 }
[6c3744e]390
[01aeade]391 Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
392 bool oldUseRetval = useRetval;
393 useRetval = false;
394 condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
395 useRetval = oldUseRetval;
396 condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
397 condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
398 return condExpr;
[6c3744e]399
[01aeade]400 }
[6c3744e]401
[05d47278]402 Expression *Pass1::makeOffsetArray( StructInstType *ty ) {
[4a79e3c9]403 std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
[b4cd03b7]404
[05d47278]405 // make a new temporary array
406 Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[4a79e3c9]407 std::stringstream lenGen;
408 lenGen << baseMembers.size();
409 ConstantExpr *lenExpr = new ConstantExpr( Constant( offsetType->clone(), lenGen.str() ) );
410 ObjectDecl *arrayTemp = makeTemporary( new ArrayType( Type::Qualifiers(), offsetType, lenExpr, false, false ) );
[05d47278]411
412 // build initializer list for temporary
413 std::list< Initializer* > inits;
[4a79e3c9]414 for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
[05d47278]415 DeclarationWithType *memberDecl;
416 if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
417 memberDecl = origMember->clone();
418 } else {
419 memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
420 }
421 inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
422 }
423 arrayTemp->set_init( new ListInit( inits ) );
424
425 // return variable pointing to temporary
426 return new VariableExpr( arrayTemp );
427 }
[b4cd03b7]428
[5c52b06]429 void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
430 Type *polyBase = hasPolyBase( parmType, exprTyVars );
431 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
432 std::string sizeName = sizeofName( polyBase );
433 if ( seenTypes.count( sizeName ) ) return;
434
435 arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
436 arg++;
437 arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
438 arg++;
439 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
440 if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
441 arg = appExpr->get_args().insert( arg, makeOffsetArray( argBaseStructType ) );
442 arg++;
443 } else {
444 throw SemanticError( "Cannot pass non-struct type for generic struct" );
445 }
446 }
447
448 seenTypes.insert( sizeName );
449 }
450 }
451
452 void Pass1::passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
[7754cde]453 // pass size/align for type variables
[01aeade]454 for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
455 ResolvExpr::EqvClass eqvClass;
456 assert( env );
457 if ( tyParm->second == TypeDecl::Any ) {
458 Type *concrete = env->lookup( tyParm->first );
459 if ( concrete ) {
460 arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
461 arg++;
[db0b3ce]462 arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
463 arg++;
[01aeade]464 } else {
465 throw SemanticError( "unbound type variable in application ", appExpr );
466 } // if
467 } // if
468 } // for
[7754cde]469
470 // add size/align for generic types to parameter list
471 if ( appExpr->get_function()->get_results().empty() ) return;
472 FunctionType *funcType = getFunctionType( appExpr->get_function()->get_results().front() );
473 assert( funcType );
[ae63a18]474
[7754cde]475 std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
476 std::list< Expression* >::const_iterator fnArg = arg;
[69911c11]477 std::set< std::string > seenTypes; //< names for generic types we've seen
[7754cde]478
[5c52b06]479 // a polymorphic return type may need to be added to the argument list
480 if ( polyRetType ) {
481 Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
482 passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
483 }
484
485 // add type information args for presently unseen types in parameter list
486 for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
487 VariableExpr *fnArgBase = getBaseVar( *fnArg );
488 if ( ! fnArgBase || fnArgBase->get_results().empty() ) continue;
489 passArgTypeVars( appExpr, (*fnParm)->get_type(), fnArgBase->get_results().front(), arg, exprTyVars, seenTypes );
[7754cde]490 }
[01aeade]491 }
[6c3744e]492
[01aeade]493 ObjectDecl *Pass1::makeTemporary( Type *type ) {
[68cd1ce]494 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
[01aeade]495 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
496 return newObj;
497 }
[6c3744e]498
[01aeade]499 Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
[cf16f94]500 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
501 // if ( useRetval ) {
502 // assert( retval );
503 // arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
504 // arg++;
505 // } else {
506
507 // Create temporary to hold return value of polymorphic function and produce that temporary as a result
508 // using a comma expression. Possibly change comma expression into statement expression "{}" for multiple
509 // return values.
510 ObjectDecl *newObj = makeTemporary( retType->clone() );
511 Expression *paramExpr = new VariableExpr( newObj );
[5c52b06]512
513 // If the type of the temporary is not polymorphic, box temporary by taking its address;
514 // otherwise the temporary is already boxed and can be used directly.
[5f6c42c]515 if ( ! isPolyType( newObj->get_type(), scopeTyVars, env ) ) {
[cf16f94]516 paramExpr = new AddressExpr( paramExpr );
[01aeade]517 } // if
[cf16f94]518 arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
519 arg++;
520 // Build a comma expression to call the function and emulate a normal return.
521 CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
522 commaExpr->set_env( appExpr->get_env() );
523 appExpr->set_env( 0 );
524 return commaExpr;
525 // } // if
526 // return appExpr;
[01aeade]527 }
[6c3744e]528
[48ca586]529 void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
530 for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
531 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
532 assert(paramType && "Aggregate parameters should be type expressions");
533 paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
534 }
535 }
[b4cd03b7]536
[48ca586]537 Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
538 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
539 Type *concrete = env->lookup( typeInst->get_name() );
540 if ( concrete == 0 ) {
541 throw SemanticError( "Unbound type variable " + typeInst->get_name() + " in ", appExpr );
542 } // if
543 return concrete;
544 } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
545 if ( doClone ) {
546 structType = structType->clone();
547 }
548 replaceParametersWithConcrete( appExpr, structType->get_parameters() );
549 return structType;
550 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
551 if ( doClone ) {
552 unionType = unionType->clone();
553 }
554 replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
555 return unionType;
556 }
557 return type;
558 }
559
560 Expression *Pass1::addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg ) {
[01aeade]561 assert( env );
[48ca586]562 Type *concrete = replaceWithConcrete( appExpr, polyType );
[5c52b06]563 // add out-parameter for return value
[01aeade]564 return addRetParam( appExpr, function, concrete, arg );
565 }
[6c3744e]566
[01aeade]567 Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
568 Expression *ret = appExpr;
[ffad73a]569 if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]570 ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
571 } // if
[bdf1954]572 std::string mangleName = mangleAdapterName( function, tyVars );
[01aeade]573 std::string adapterName = makeAdapterName( mangleName );
[b1a6d6b]574
[b4cd03b7]575 // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
576 Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
577 appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
[01aeade]578 appExpr->set_function( new NameExpr( adapterName ) );
[ae63a18]579
[01aeade]580 return ret;
581 }
[6c3744e]582
[01aeade]583 void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
584 assert( ! arg->get_results().empty() );
[1cced28]585 if ( isPolyType( param, exprTyVars ) ) {
[9407ed8]586 if ( isPolyType( arg->get_results().front() ) ) {
587 // if the argument's type is polymorphic, we don't need to box again!
[01aeade]588 return;
589 } else if ( arg->get_results().front()->get_isLvalue() ) {
590 // VariableExpr and MemberExpr are lvalues
591 arg = new AddressExpr( arg );
592 } else {
[bd85400]593 // use type computed in unification to declare boxed variables
594 Type * newType = param->clone();
595 if ( env ) env->apply( newType );
596 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, newType, 0 );
[f6d7e0f]597 newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
[01aeade]598 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
599 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
600 assign->get_args().push_back( new VariableExpr( newObj ) );
601 assign->get_args().push_back( arg );
602 stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
603 arg = new AddressExpr( new VariableExpr( newObj ) );
604 } // if
605 } // if
606 }
[6c3744e]607
[b4cd03b7]608 /// cast parameters to polymorphic functions so that types are replaced with
609 /// void * if they are type parameters in the formal type.
610 /// this gets rid of warnings from gcc.
[01aeade]611 void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
[b4cd03b7]612 Type * newType = formal->clone();
613 if ( getFunctionType( newType ) ) {
614 newType = ScrubTyVars::scrub( newType, tyVars );
[01aeade]615 actual = new CastExpr( actual, newType );
616 } // if
617 }
[6c3744e]618
[01aeade]619 void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
620 for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
621 assert( arg != appExpr->get_args().end() );
622 addCast( *arg, (*param)->get_type(), exprTyVars );
623 boxParam( (*param)->get_type(), *arg, exprTyVars );
624 } // for
625 }
[6c3744e]626
[01aeade]627 void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
628 std::list< Expression *>::iterator cur = arg;
629 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
630 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
631 InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
[698664b3]632 assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
[01aeade]633 Expression *newExpr = inferParam->second.expr->clone();
634 addCast( newExpr, (*assert)->get_type(), tyVars );
635 boxParam( (*assert)->get_type(), newExpr, tyVars );
636 appExpr->get_args().insert( cur, newExpr );
637 } // for
638 } // for
639 }
[6c3744e]640
[01aeade]641 void makeRetParm( FunctionType *funcType ) {
642 DeclarationWithType *retParm = funcType->get_returnVals().front();
[6c3744e]643
[01aeade]644 // make a new parameter that is a pointer to the type of the old return value
645 retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
646 funcType->get_parameters().push_front( retParm );
[6c3744e]647
[01aeade]648 // we don't need the return value any more
649 funcType->get_returnVals().clear();
650 }
[6c3744e]651
[01aeade]652 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
653 // actually make the adapter type
654 FunctionType *adapter = adaptee->clone();
[ffad73a]655 if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]656 makeRetParm( adapter );
657 } // if
[68cd1ce]658 adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
[01aeade]659 return adapter;
660 }
[6c3744e]661
[01aeade]662 Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
663 assert( param );
664 assert( arg );
[ffad73a]665 if ( isPolyType( realParam->get_type(), tyVars ) ) {
[30aeb27]666 if ( ! isPolyType( arg->get_type() ) ) {
[e56cfdb0]667 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
668 deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
669 deref->get_results().push_back( arg->get_type()->clone() );
670 return deref;
671 } // if
[01aeade]672 } // if
673 return new VariableExpr( param );
674 }
[6c3744e]675
[01aeade]676 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 ) {
677 UniqueName paramNamer( "_p" );
678 for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
679 if ( (*param)->get_name() == "" ) {
680 (*param)->set_name( paramNamer.newName() );
681 (*param)->set_linkage( LinkageSpec::C );
682 } // if
683 adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
684 } // for
685 }
[6c3744e]686
[b1a6d6b]687
688
[01aeade]689 FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
690 FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
691 adapterType = ScrubTyVars::scrub( adapterType, tyVars );
692 DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
693 adapteeDecl->set_name( "_adaptee" );
694 ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
695 Statement *bodyStmt;
[ae63a18]696
[01aeade]697 std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
698 std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
699 std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
700 for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
701 assert( tyArg != realType->get_forall().end() );
702 std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
703 std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
704 std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
705 for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
706 assert( assertArg != (*tyArg)->get_assertions().end() );
707 adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
708 } // for
709 } // for
[ae63a18]710
[01aeade]711 std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
712 std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
713 std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
714 param++; // skip adaptee parameter
715 if ( realType->get_returnVals().empty() ) {
716 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
717 bodyStmt = new ExprStmt( noLabels, adapteeApp );
[ffad73a]718 } else if ( isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]719 if ( (*param)->get_name() == "" ) {
720 (*param)->set_name( "_ret" );
721 (*param)->set_linkage( LinkageSpec::C );
722 } // if
723 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
724 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
725 deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
726 assign->get_args().push_back( deref );
727 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
728 assign->get_args().push_back( adapteeApp );
729 bodyStmt = new ExprStmt( noLabels, assign );
730 } else {
731 // adapter for a function that returns a monomorphic value
732 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
733 bodyStmt = new ReturnStmt( noLabels, adapteeApp );
734 } // if
735 CompoundStmt *adapterBody = new CompoundStmt( noLabels );
736 adapterBody->get_kids().push_back( bodyStmt );
737 std::string adapterName = makeAdapterName( mangleName );
[de62360d]738 return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
[01aeade]739 }
[6c3744e]740
[c29d9ce]741 void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
[e497c1d]742 // collect a list of function types passed as parameters or implicit parameters (assertions)
[01aeade]743 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
744 std::list< FunctionType *> functions;
745 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
746 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
747 findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
748 } // for
749 } // for
750 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
751 findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
752 } // for
[e497c1d]753
[e56cfdb0]754 // parameter function types for which an appropriate adapter has been generated. we cannot use the types
755 // after applying substitutions, since two different parameter types may be unified to the same type
[01aeade]756 std::set< std::string > adaptersDone;
[e497c1d]757
[01aeade]758 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[c29d9ce]759 FunctionType *originalFunction = (*funType)->clone();
[01aeade]760 FunctionType *realFunction = (*funType)->clone();
761 std::string mangleName = SymTab::Mangler::mangle( realFunction );
[e497c1d]762
[e56cfdb0]763 // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
764 // pre-substitution parameter function type.
[01aeade]765 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
[e497c1d]766 adaptersDone.insert( adaptersDone.begin(), mangleName );
[ae63a18]767
[e56cfdb0]768 // apply substitution to type variables to figure out what the adapter's type should look like
[e497c1d]769 assert( env );
770 env->apply( realFunction );
[ae63a18]771 mangleName = SymTab::Mangler::mangle( realFunction );
[bdf1954]772 mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
[e497c1d]773
[e56cfdb0]774 AdapterMap & adapters = Pass1::adapters.top();
775 AdapterMap::iterator adapter = adapters.find( mangleName );
776 if ( adapter == adapters.end() ) {
777 // adapter has not been created yet in the current scope, so define it
778 FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
779 adapter = adapters.insert( adapters.begin(), std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
780 stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
[c29d9ce]781 } // if
[e56cfdb0]782 assert( adapter != adapters.end() );
783
784 // add the appropriate adapter as a parameter
785 appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
[01aeade]786 } // if
787 } // for
[e56cfdb0]788 } // passAdapters
[6c3744e]789
[78dd0da]790 Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
[01aeade]791 NameExpr *opExpr;
792 if ( isIncr ) {
793 opExpr = new NameExpr( "?+=?" );
794 } else {
795 opExpr = new NameExpr( "?-=?" );
[6c3744e]796 } // if
[01aeade]797 UntypedExpr *addAssign = new UntypedExpr( opExpr );
798 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
799 addAssign->get_args().push_back( address->get_arg() );
800 } else {
801 addAssign->get_args().push_back( appExpr->get_args().front() );
[6c3744e]802 } // if
[78dd0da]803 addAssign->get_args().push_back( new NameExpr( sizeofName( polyType ) ) );
[01aeade]804 addAssign->get_results().front() = appExpr->get_results().front()->clone();
805 if ( appExpr->get_env() ) {
806 addAssign->set_env( appExpr->get_env() );
[6c3744e]807 appExpr->set_env( 0 );
808 } // if
[01aeade]809 appExpr->get_args().clear();
810 delete appExpr;
811 return addAssign;
812 }
813
814 Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
815 if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
816 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
817 if ( varExpr->get_var()->get_name() == "?[?]" ) {
818 assert( ! appExpr->get_results().empty() );
819 assert( appExpr->get_args().size() == 2 );
[ffad73a]820 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
821 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
[ae63a18]822 assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
[01aeade]823 UntypedExpr *ret = 0;
[ae63a18]824 if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
[01aeade]825 ret = new UntypedExpr( new NameExpr( "?+?" ) );
826 } // if
[ffad73a]827 if ( baseType1 ) {
[01aeade]828 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
829 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]830 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]831 ret->get_args().push_back( appExpr->get_args().front() );
832 ret->get_args().push_back( multiply );
[ffad73a]833 } else if ( baseType2 ) {
[01aeade]834 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
835 multiply->get_args().push_back( appExpr->get_args().front() );
[ffad73a]836 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
[01aeade]837 ret->get_args().push_back( multiply );
838 ret->get_args().push_back( appExpr->get_args().back() );
839 } // if
[ffad73a]840 if ( baseType1 || baseType2 ) {
[01aeade]841 ret->get_results().push_front( appExpr->get_results().front()->clone() );
842 if ( appExpr->get_env() ) {
843 ret->set_env( appExpr->get_env() );
844 appExpr->set_env( 0 );
845 } // if
846 appExpr->get_args().clear();
847 delete appExpr;
848 return ret;
849 } // if
850 } else if ( varExpr->get_var()->get_name() == "*?" ) {
851 assert( ! appExpr->get_results().empty() );
852 assert( ! appExpr->get_args().empty() );
[ffad73a]853 if ( isPolyType( appExpr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]854 Expression *ret = appExpr->get_args().front();
855 delete ret->get_results().front();
856 ret->get_results().front() = appExpr->get_results().front()->clone();
857 if ( appExpr->get_env() ) {
858 ret->set_env( appExpr->get_env() );
859 appExpr->set_env( 0 );
860 } // if
861 appExpr->get_args().clear();
862 delete appExpr;
863 return ret;
864 } // if
865 } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
866 assert( ! appExpr->get_results().empty() );
867 assert( appExpr->get_args().size() == 1 );
[ffad73a]868 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]869 Type *tempType = appExpr->get_results().front()->clone();
870 if ( env ) {
871 env->apply( tempType );
872 } // if
873 ObjectDecl *newObj = makeTemporary( tempType );
874 VariableExpr *tempExpr = new VariableExpr( newObj );
875 UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
876 assignExpr->get_args().push_back( tempExpr->clone() );
877 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
878 assignExpr->get_args().push_back( address->get_arg()->clone() );
879 } else {
880 assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
881 } // if
[ffad73a]882 CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
[01aeade]883 return new CommaExpr( firstComma, tempExpr );
884 } // if
885 } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
886 assert( ! appExpr->get_results().empty() );
887 assert( appExpr->get_args().size() == 1 );
[ffad73a]888 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
889 return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
[01aeade]890 } // if
891 } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
892 assert( ! appExpr->get_results().empty() );
893 assert( appExpr->get_args().size() == 2 );
[ffad73a]894 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
895 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
896 if ( baseType1 && baseType2 ) {
[01aeade]897 UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
898 divide->get_args().push_back( appExpr );
[ffad73a]899 divide->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]900 divide->get_results().push_front( appExpr->get_results().front()->clone() );
901 if ( appExpr->get_env() ) {
902 divide->set_env( appExpr->get_env() );
903 appExpr->set_env( 0 );
904 } // if
905 return divide;
[ffad73a]906 } else if ( baseType1 ) {
[01aeade]907 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
908 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]909 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]910 appExpr->get_args().back() = multiply;
[ffad73a]911 } else if ( baseType2 ) {
[01aeade]912 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
913 multiply->get_args().push_back( appExpr->get_args().front() );
[ffad73a]914 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
[01aeade]915 appExpr->get_args().front() = multiply;
916 } // if
917 } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
918 assert( ! appExpr->get_results().empty() );
919 assert( appExpr->get_args().size() == 2 );
[ffad73a]920 Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env );
921 if ( baseType ) {
[01aeade]922 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
923 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]924 multiply->get_args().push_back( new NameExpr( sizeofName( baseType ) ) );
[01aeade]925 appExpr->get_args().back() = multiply;
926 } // if
927 } // if
928 return appExpr;
929 } // if
[6c3744e]930 } // if
[01aeade]931 return 0;
932 }
[6c3744e]933
[01aeade]934 Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
[e56cfdb0]935 // std::cerr << "mutate appExpr: ";
936 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
937 // std::cerr << i->first << " ";
938 // }
939 // std::cerr << "\n";
[01aeade]940 bool oldUseRetval = useRetval;
941 useRetval = false;
942 appExpr->get_function()->acceptMutator( *this );
943 mutateAll( appExpr->get_args(), *this );
944 useRetval = oldUseRetval;
[ae63a18]945
[01aeade]946 assert( ! appExpr->get_function()->get_results().empty() );
947 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
948 assert( pointer );
949 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
950 assert( function );
[ae63a18]951
[01aeade]952 if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
953 return newExpr;
954 } // if
[ae63a18]955
[01aeade]956 Expression *ret = appExpr;
[ae63a18]957
[01aeade]958 std::list< Expression *>::iterator arg = appExpr->get_args().begin();
959 std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
[ae63a18]960
[5c52b06]961 TyVarMap exprTyVars;
962 makeTyVarMap( function, exprTyVars );
[dc12481]963 ReferenceToType *polyRetType = isPolyRet( function );
[5c52b06]964
[dc12481]965 if ( polyRetType ) {
[5c52b06]966 ret = addPolyRetParam( appExpr, function, polyRetType, arg );
[01aeade]967 } else if ( needsAdapter( function, scopeTyVars ) ) {
[e56cfdb0]968 // std::cerr << "needs adapter: ";
969 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
970 // std::cerr << i->first << " ";
971 // }
972 // std::cerr << "\n";
[01aeade]973 // change the application so it calls the adapter rather than the passed function
974 ret = applyAdapter( appExpr, function, arg, scopeTyVars );
975 } // if
976 arg = appExpr->get_args().begin();
[ae63a18]977
[5c52b06]978 passTypeVars( appExpr, polyRetType, arg, exprTyVars );
[01aeade]979 addInferredParams( appExpr, function, arg, exprTyVars );
[51b73452]980
[01aeade]981 arg = paramBegin;
[ae63a18]982
[01aeade]983 boxParams( appExpr, function, arg, exprTyVars );
[6c3744e]984
[01aeade]985 passAdapters( appExpr, function, exprTyVars );
[6c3744e]986
[01aeade]987 return ret;
988 }
[6c3744e]989
[01aeade]990 Expression *Pass1::mutate( UntypedExpr *expr ) {
[ffad73a]991 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]992 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
993 if ( name->get_name() == "*?" ) {
994 Expression *ret = expr->get_args().front();
995 expr->get_args().clear();
996 delete expr;
997 return ret->acceptMutator( *this );
998 } // if
999 } // if
1000 } // if
1001 return PolyMutator::mutate( expr );
1002 }
[6c3744e]1003
[01aeade]1004 Expression *Pass1::mutate( AddressExpr *addrExpr ) {
1005 assert( ! addrExpr->get_arg()->get_results().empty() );
[cf16f94]1006
1007 bool needs = false;
1008 if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
[5f6c42c]1009 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
[cf16f94]1010 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1011 if ( name->get_name() == "*?" ) {
1012 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
1013 assert( ! appExpr->get_function()->get_results().empty() );
1014 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1015 assert( pointer );
1016 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1017 assert( function );
1018 needs = needsAdapter( function, scopeTyVars );
1019 } // if
1020 } // if
1021 } // if
1022 } // if
1023 } // if
[01aeade]1024 addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
[5f6c42c]1025 if ( isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env ) || needs ) {
[01aeade]1026 Expression *ret = addrExpr->get_arg();
1027 delete ret->get_results().front();
1028 ret->get_results().front() = addrExpr->get_results().front()->clone();
1029 addrExpr->set_arg( 0 );
1030 delete addrExpr;
1031 return ret;
1032 } else {
1033 return addrExpr;
1034 } // if
1035 }
[6c3744e]1036
[b10c9959]1037 /// Wraps a function declaration in a new pointer-to-function variable expression
1038 VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
1039 // line below cloned from FixFunction.cc
1040 ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
1041 new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
1042 functionObj->set_mangleName( functionDecl->get_mangleName() );
1043 return new VariableExpr( functionObj );
1044 }
1045
[cf16f94]1046 Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1047 if ( retval && returnStmt->get_expr() ) {
1048 assert( ! returnStmt->get_expr()->get_results().empty() );
1049 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1050 // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
[ae63a18]1051 // by this point, a cast expr on a polymorphic return value is redundant
[cf16f94]1052 while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1053 returnStmt->set_expr( castExpr->get_arg() );
1054 returnStmt->get_expr()->set_env( castExpr->get_env() );
1055 castExpr->set_env( 0 );
1056 castExpr->set_arg( 0 );
1057 delete castExpr;
[5f6c42c]1058 } //while
[1194734]1059
1060 // find assignment operator for (polymorphic) return type
[b10c9959]1061 ApplicationExpr *assignExpr = 0;
[1194734]1062 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
[b10c9959]1063 // find assignment operator for type variable
[1194734]1064 std::map< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1065 if ( assignIter == assignOps.end() ) {
1066 throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1067 } // if
[b10c9959]1068 assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
[1194734]1069 } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
[b10c9959]1070 // find assignment operator for generic type
[dc12481]1071 DeclarationWithType *functionDecl = scopedAssignOps.find( refType );
1072 if ( ! functionDecl ) {
[1194734]1073 throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1074 }
[b10c9959]1075
1076 // wrap it up in an application expression
1077 assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1078 assignExpr->set_env( env->clone() );
1079
1080 // find each of its needed secondary assignment operators
1081 std::list< Expression* > &tyParams = refType->get_parameters();
1082 std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1083 std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1084 std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1085 for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1086 if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue; // skip types with no assign op (ftype/dtype)
1087
1088 std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1089 assert( ! asserts.empty() && "Type param needs assignment operator assertion" );
1090 DeclarationWithType *actualDecl = asserts.front();
[dc12481]1091 TypeInstType *actualType = isTypeInstAssignment( actualDecl );
[b10c9959]1092 assert( actualType && "First assertion of type with assertions should be assignment operator" );
1093 TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1094 assert( formalTypeExpr && "type parameters must be type expressions" );
1095 Type *formalType = formalTypeExpr->get_type();
1096 assignExpr->get_env()->add( actualType->get_name(), formalType );
1097
1098 DeclarationWithType *assertAssign = 0;
1099 if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1100 std::map< std::string, DeclarationWithType *>::const_iterator assertAssignIt = assignOps.find( formalTypeInstType->get_name() );
1101 if ( assertAssignIt == assignOps.end() ) {
1102 throw SemanticError( "No assignment operation found for ", formalTypeInstType );
1103 }
1104 assertAssign = assertAssignIt->second;
[dc12481]1105 } else {
1106 assertAssign = scopedAssignOps.find( formalType );
1107 if ( ! assertAssign ) {
1108 throw SemanticError( "No assignment operation found for ", formalType );
[b10c9959]1109 }
[dc12481]1110 }
[b10c9959]1111
1112
1113 assignExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1114 = ParamEntry( assertAssign->get_uniqueId(), assertAssign->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertAssign ) );
1115 }
[1194734]1116 }
[b10c9959]1117 assert( assignExpr );
[1194734]1118
1119 // replace return statement with appropriate assignment to out parameter
[cf16f94]1120 Expression *retParm = new NameExpr( retval->get_name() );
1121 retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1122 assignExpr->get_args().push_back( retParm );
1123 assignExpr->get_args().push_back( returnStmt->get_expr() );
1124 stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1125 // } else {
1126 // useRetval = true;
1127 // stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1128 // useRetval = false;
1129 // } // if
1130 returnStmt->set_expr( 0 );
[01aeade]1131 } else {
[cf16f94]1132 returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
[01aeade]1133 } // if
[cf16f94]1134 return returnStmt;
[01aeade]1135 }
[6c3744e]1136
[01aeade]1137 Type * Pass1::mutate( PointerType *pointerType ) {
1138 TyVarMap oldtyVars = scopeTyVars;
1139 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1140
[01aeade]1141 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1142
[01aeade]1143 scopeTyVars = oldtyVars;
1144 return ret;
1145 }
[6c3744e]1146
[01aeade]1147 Type * Pass1::mutate( FunctionType *functionType ) {
1148 TyVarMap oldtyVars = scopeTyVars;
1149 makeTyVarMap( functionType, scopeTyVars );
[ae63a18]1150
[01aeade]1151 Type *ret = Mutator::mutate( functionType );
[ae63a18]1152
[01aeade]1153 scopeTyVars = oldtyVars;
1154 return ret;
1155 }
[51b73452]1156
[01aeade]1157 void Pass1::doBeginScope() {
[bdf1954]1158 // push a copy of the current map
[e56cfdb0]1159 adapters.push(adapters.top());
[1194734]1160 scopedAssignOps.beginScope();
[01aeade]1161 }
[b1a6d6b]1162
[01aeade]1163 void Pass1::doEndScope() {
1164 adapters.pop();
[1194734]1165 scopedAssignOps.endScope();
[01aeade]1166 }
[51b73452]1167
1168////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1169
[01aeade]1170 void Pass2::addAdapters( FunctionType *functionType ) {
1171 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1172 std::list< FunctionType *> functions;
1173 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1174 Type *orig = (*arg)->get_type();
1175 findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1176 (*arg)->set_type( orig );
1177 }
1178 std::set< std::string > adaptersDone;
1179 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[bdf1954]1180 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
[01aeade]1181 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1182 std::string adapterName = makeAdapterName( mangleName );
[68cd1ce]1183 paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
[01aeade]1184 adaptersDone.insert( adaptersDone.begin(), mangleName );
1185 }
1186 }
[5f6c42c]1187// deleteAll( functions );
[01aeade]1188 }
[6c3744e]1189
[01aeade]1190 template< typename DeclClass >
1191 DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1192 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
[6c3744e]1193
[01aeade]1194 return ret;
1195 }
[6c3744e]1196
[01aeade]1197 DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1198 return handleDecl( functionDecl, functionDecl->get_functionType() );
1199 }
[6c3744e]1200
[01aeade]1201 ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1202 return handleDecl( objectDecl, objectDecl->get_type() );
1203 }
[6c3744e]1204
[01aeade]1205 TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1206 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1207 if ( typeDecl->get_base() ) {
1208 return handleDecl( typeDecl, typeDecl->get_base() );
1209 } else {
1210 return Mutator::mutate( typeDecl );
1211 }
1212 }
[6c3744e]1213
[01aeade]1214 TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1215 return handleDecl( typedefDecl, typedefDecl->get_base() );
1216 }
[6c3744e]1217
[01aeade]1218 Type * Pass2::mutate( PointerType *pointerType ) {
1219 TyVarMap oldtyVars = scopeTyVars;
1220 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1221
[01aeade]1222 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1223
[01aeade]1224 scopeTyVars = oldtyVars;
1225 return ret;
1226 }
[6c3744e]1227
[01aeade]1228 Type *Pass2::mutate( FunctionType *funcType ) {
1229 TyVarMap oldtyVars = scopeTyVars;
1230 makeTyVarMap( funcType, scopeTyVars );
[7754cde]1231
1232 // move polymorphic return type to parameter list
[aadc9a4]1233 if ( isPolyRet( funcType ) ) {
[01aeade]1234 DeclarationWithType *ret = funcType->get_returnVals().front();
1235 ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1236 funcType->get_parameters().push_front( ret );
1237 funcType->get_returnVals().pop_front();
1238 }
[7754cde]1239
1240 // add size/align and assertions for type parameters to parameter list
[01aeade]1241 std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1242 std::list< DeclarationWithType *> inferredParams;
[78dd0da]1243 ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
[05d47278]1244 ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1245 new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
[f8b961b]1246// ObjectDecl *newFunPtr = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 );
[01aeade]1247 for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
[db0b3ce]1248 ObjectDecl *sizeParm, *alignParm;
1249 // add all size and alignment parameters to parameter list
[01aeade]1250 if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
[78dd0da]1251 TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
[ae63a18]1252
[78dd0da]1253 sizeParm = newObj.clone();
1254 sizeParm->set_name( sizeofName( &parmType ) );
[db0b3ce]1255 last = funcType->get_parameters().insert( last, sizeParm );
1256 ++last;
[78dd0da]1257
1258 alignParm = newObj.clone();
1259 alignParm->set_name( alignofName( &parmType ) );
[db0b3ce]1260 last = funcType->get_parameters().insert( last, alignParm );
[01aeade]1261 ++last;
1262 }
[e56cfdb0]1263 // move all assertions into parameter list
[01aeade]1264 for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
[f8b961b]1265// *assert = (*assert)->acceptMutator( *this );
[01aeade]1266 inferredParams.push_back( *assert );
1267 }
1268 (*tyParm)->get_assertions().clear();
1269 }
[7754cde]1270
[5c52b06]1271 // add size/align for generic parameter types to parameter list
[b18b0b5]1272 std::set< std::string > seenTypes; // sizeofName for generic types we've seen
[7754cde]1273 for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
[32805db]1274 Type *polyBase = hasPolyBase( (*fnParm)->get_type(), scopeTyVars );
1275 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
1276 std::string sizeName = sizeofName( polyBase );
[7754cde]1277 if ( seenTypes.count( sizeName ) ) continue;
[ae63a18]1278
[05d47278]1279 ObjectDecl *sizeParm, *alignParm, *offsetParm;
[7754cde]1280 sizeParm = newObj.clone();
1281 sizeParm->set_name( sizeName );
1282 last = funcType->get_parameters().insert( last, sizeParm );
1283 ++last;
1284
1285 alignParm = newObj.clone();
[32805db]1286 alignParm->set_name( alignofName( polyBase ) );
[7754cde]1287 last = funcType->get_parameters().insert( last, alignParm );
1288 ++last;
1289
[32805db]1290 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
[05d47278]1291 offsetParm = newPtr.clone();
[32805db]1292 offsetParm->set_name( offsetofName( polyBase ) );
[05d47278]1293 last = funcType->get_parameters().insert( last, offsetParm );
1294 ++last;
1295 }
1296
[7754cde]1297 seenTypes.insert( sizeName );
1298 }
1299 }
1300
1301 // splice assertion parameters into parameter list
[01aeade]1302 funcType->get_parameters().splice( last, inferredParams );
1303 addAdapters( funcType );
1304 mutateAll( funcType->get_returnVals(), *this );
1305 mutateAll( funcType->get_parameters(), *this );
[ae63a18]1306
[01aeade]1307 scopeTyVars = oldtyVars;
1308 return funcType;
1309 }
[51b73452]1310
[05d47278]1311////////////////////////////////////////// MemberExprFixer ////////////////////////////////////////////////////
[51b73452]1312
[01aeade]1313 template< typename DeclClass >
[05d47278]1314 DeclClass * MemberExprFixer::handleDecl( DeclClass *decl, Type *type ) {
[01aeade]1315 TyVarMap oldtyVars = scopeTyVars;
1316 makeTyVarMap( type, scopeTyVars );
[ae63a18]1317
[01aeade]1318 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
[6c3744e]1319
[01aeade]1320 scopeTyVars = oldtyVars;
1321 return ret;
1322 }
[6c3744e]1323
[05d47278]1324 ObjectDecl * MemberExprFixer::mutate( ObjectDecl *objectDecl ) {
[01aeade]1325 return handleDecl( objectDecl, objectDecl->get_type() );
1326 }
[6c3744e]1327
[05d47278]1328 DeclarationWithType * MemberExprFixer::mutate( FunctionDecl *functionDecl ) {
[01aeade]1329 return handleDecl( functionDecl, functionDecl->get_functionType() );
1330 }
[6c3744e]1331
[05d47278]1332 TypedefDecl * MemberExprFixer::mutate( TypedefDecl *typedefDecl ) {
[01aeade]1333 return handleDecl( typedefDecl, typedefDecl->get_base() );
1334 }
[6c3744e]1335
[05d47278]1336 TypeDecl * MemberExprFixer::mutate( TypeDecl *typeDecl ) {
[01aeade]1337 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1338 return Mutator::mutate( typeDecl );
1339 }
[51b73452]1340
[05d47278]1341 Type * MemberExprFixer::mutate( PointerType *pointerType ) {
[01aeade]1342 TyVarMap oldtyVars = scopeTyVars;
1343 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1344
[01aeade]1345 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1346
[01aeade]1347 scopeTyVars = oldtyVars;
1348 return ret;
1349 }
[6c3744e]1350
[05d47278]1351 Type * MemberExprFixer::mutate( FunctionType *functionType ) {
[01aeade]1352 TyVarMap oldtyVars = scopeTyVars;
1353 makeTyVarMap( functionType, scopeTyVars );
[ae63a18]1354
[01aeade]1355 Type *ret = Mutator::mutate( functionType );
[ae63a18]1356
[01aeade]1357 scopeTyVars = oldtyVars;
1358 return ret;
[6c3744e]1359 }
[51b73452]1360
[05d47278]1361 Statement *MemberExprFixer::mutate( DeclStmt *declStmt ) {
[01aeade]1362 if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
[ffad73a]1363 if ( isPolyType( objectDecl->get_type(), scopeTyVars ) ) {
[e01559c]1364 // change initialization of a polymorphic value object
1365 // to allocate storage with alloca
[ffad73a]1366 Type *declType = objectDecl->get_type();
[01aeade]1367 UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
[ffad73a]1368 alloc->get_args().push_back( new NameExpr( sizeofName( declType ) ) );
[e01559c]1369
1370 delete objectDecl->get_init();
1371
1372 std::list<Expression*> designators;
1373 objectDecl->set_init( new SingleInit( alloc, designators ) );
[01aeade]1374 }
1375 }
1376 return Mutator::mutate( declStmt );
1377 }
[05d47278]1378
[2a4b088]1379 /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1380 long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1381 long i = 0;
1382 for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1383 if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1384
1385 if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
[bed4d37c]1386 if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1387 || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
[2a4b088]1388 else continue;
1389 } else return i;
1390 }
1391 return -1;
1392 }
1393
1394 /// Returns an index expression into the offset array for a type
1395 Expression *makeOffsetIndex( Type *objectType, long i ) {
1396 std::stringstream offset_namer;
1397 offset_namer << i;
1398 ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
1399 UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1400 fieldOffset->get_args().push_back( new NameExpr( offsetofName( objectType ) ) );
1401 fieldOffset->get_args().push_back( fieldIndex );
1402 return fieldOffset;
1403 }
1404
1405 /// Returns an expression dereferenced n times
1406 Expression *makeDerefdVar( Expression *derefdVar, long n ) {
1407 for ( int i = 1; i < n; ++i ) {
1408 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1409 derefExpr->get_args().push_back( derefdVar );
1410 derefdVar = derefExpr;
1411 }
1412 return derefdVar;
1413 }
1414
[05d47278]1415 Expression *MemberExprFixer::mutate( MemberExpr *memberExpr ) {
1416 // mutate, exiting early if no longer MemberExpr
1417 Expression *expr = Mutator::mutate( memberExpr );
1418 memberExpr = dynamic_cast< MemberExpr* >( expr );
1419 if ( ! memberExpr ) return expr;
1420
1421 // get declaration for base struct, exiting early if not found
[8488c715]1422 int varDepth;
1423 VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
[05d47278]1424 if ( ! varExpr ) return memberExpr;
1425 ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1426 if ( ! objectDecl ) return memberExpr;
1427
1428 // only mutate member expressions for polymorphic types
[8488c715]1429 int tyDepth;
1430 Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
[05d47278]1431 if ( ! objectType ) return memberExpr;
1432
[4318107]1433 Expression *newMemberExpr = 0;
[05d47278]1434 if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
[2a4b088]1435 // look up offset index
1436 long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
1437 if ( i == -1 ) return memberExpr;
[05d47278]1438
[2a4b088]1439 // replace member expression with pointer to base plus offset
1440 UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1441 fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
1442 fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
[4318107]1443 newMemberExpr = fieldLoc;
[98735ef]1444 } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
[2a4b088]1445 // union members are all at offset zero, so build appropriately-dereferenced variable
[4318107]1446 newMemberExpr = makeDerefdVar( varExpr->clone(), varDepth );
[2a4b088]1447 } else return memberExpr;
[4318107]1448 assert( newMemberExpr );
1449
[4067aa8]1450 Type *memberType = memberExpr->get_member()->get_type();
1451 if ( ! isPolyType( memberType, scopeTyVars ) ) {
1452 // 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
1453 CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
[4318107]1454 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1455 derefExpr->get_args().push_back( ptrCastExpr );
1456 newMemberExpr = derefExpr;
1457 }
1458
1459 delete memberExpr;
1460 return newMemberExpr;
[2a4b088]1461 }
[05d47278]1462
[2a4b088]1463 Expression *MemberExprFixer::mutate( OffsetofExpr *offsetofExpr ) {
1464 // mutate, exiting early if no longer OffsetofExpr
1465 Expression *expr = Mutator::mutate( offsetofExpr );
1466 offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
1467 if ( ! offsetofExpr ) return expr;
1468
1469 // only mutate expressions for polymorphic structs/unions
1470 Type *ty = isPolyType( offsetofExpr->get_type(), scopeTyVars );
1471 if ( ! ty ) return offsetofExpr;
1472
1473 if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
1474 // replace offsetof expression by index into offset array
1475 long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
1476 if ( i == -1 ) return offsetofExpr;
1477
1478 Expression *offsetInd = makeOffsetIndex( ty, i );
1479 delete offsetofExpr;
1480 return offsetInd;
[5c52b06]1481 } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
[2a4b088]1482 // all union members are at offset zero
1483 delete offsetofExpr;
1484 return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), std::string("0") ) );
1485 } else return offsetofExpr;
[05d47278]1486 }
1487
1488////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
1489
1490 template< typename DeclClass >
1491 DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
1492 TyVarMap oldtyVars = scopeTyVars;
1493 makeTyVarMap( type, scopeTyVars );
1494
1495 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1496 ScrubTyVars::scrub( decl, scopeTyVars );
1497
1498 scopeTyVars = oldtyVars;
1499 return ret;
1500 }
1501
1502 ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
1503 return handleDecl( objectDecl, objectDecl->get_type() );
1504 }
1505
1506 DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
1507 return handleDecl( functionDecl, functionDecl->get_functionType() );
1508 }
1509
1510 TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
1511 return handleDecl( typedefDecl, typedefDecl->get_base() );
1512 }
1513
1514 TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
1515// Initializer *init = 0;
1516// std::list< Expression *> designators;
1517// scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1518// if ( typeDecl->get_base() ) {
1519// init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
1520// }
1521// return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
1522
1523 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1524 return Mutator::mutate( typeDecl );
1525 }
1526
1527 Type * Pass3::mutate( PointerType *pointerType ) {
1528 TyVarMap oldtyVars = scopeTyVars;
1529 makeTyVarMap( pointerType, scopeTyVars );
1530
1531 Type *ret = Mutator::mutate( pointerType );
1532
1533 scopeTyVars = oldtyVars;
1534 return ret;
1535 }
1536
1537 Type * Pass3::mutate( FunctionType *functionType ) {
1538 TyVarMap oldtyVars = scopeTyVars;
1539 makeTyVarMap( functionType, scopeTyVars );
1540
1541 Type *ret = Mutator::mutate( functionType );
1542
1543 scopeTyVars = oldtyVars;
1544 return ret;
1545 }
[01aeade]1546 } // anonymous namespace
[51b73452]1547} // namespace GenPoly
[01aeade]1548
[51587aa]1549// Local Variables: //
1550// tab-width: 4 //
1551// mode: c++ //
1552// compile-command: "make install" //
1553// End: //
Note: See TracBrowser for help on using the repository browser.