source: src/GenPoly/Box.cc@ 39786813

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 with_gc
Last change on this file since 39786813 was c14cff1, checked in by Rob Schluntz <rschlunt@…>, 10 years ago

Merge branch 'master' into ctor

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