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 | // Validate.cc --
|
---|
8 | //
|
---|
9 | // Author : Richard C. Bilson
|
---|
10 | // Created On : Sun May 17 21:50:04 2015
|
---|
11 | // Last Modified By : Peter A. Buhr
|
---|
12 | // Last Modified On : Mon Aug 28 13:47:23 2017
|
---|
13 | // Update Count : 359
|
---|
14 | //
|
---|
15 |
|
---|
16 | // The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
|
---|
17 | // as regular in structure as possible. Some assumptions can be made regarding the state of the tree after this pass is
|
---|
18 | // complete, including:
|
---|
19 | //
|
---|
20 | // - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
|
---|
21 | // union.
|
---|
22 | //
|
---|
23 | // - All enumeration constants have type EnumInstType.
|
---|
24 | //
|
---|
25 | // - The type "void" never occurs in lists of function parameter or return types. A function
|
---|
26 | // taking no arguments has no argument types.
|
---|
27 | //
|
---|
28 | // - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
|
---|
29 | // by the particular set of type arguments.
|
---|
30 | //
|
---|
31 | // - Every declaration is assigned a unique id.
|
---|
32 | //
|
---|
33 | // - No typedef declarations or instances exist; the actual type is substituted for each instance.
|
---|
34 | //
|
---|
35 | // - Each type, struct, and union definition is followed by an appropriate assignment operator.
|
---|
36 | //
|
---|
37 | // - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
|
---|
38 | // definition occurs later in the input.
|
---|
39 |
|
---|
40 | #include "Validate.h"
|
---|
41 |
|
---|
42 | #include <cassert> // for assertf, assert
|
---|
43 | #include <cstddef> // for size_t
|
---|
44 | #include <list> // for list
|
---|
45 | #include <string> // for string
|
---|
46 | #include <utility> // for pair
|
---|
47 |
|
---|
48 | #include "CodeGen/CodeGenerator.h" // for genName
|
---|
49 | #include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
|
---|
50 | #include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd
|
---|
51 | #include "Common/ScopedMap.h" // for ScopedMap
|
---|
52 | #include "Common/SemanticError.h" // for SemanticError
|
---|
53 | #include "Common/UniqueName.h" // for UniqueName
|
---|
54 | #include "Common/utility.h" // for operator+, cloneAll, deleteAll
|
---|
55 | #include "Concurrency/Keywords.h" // for applyKeywords
|
---|
56 | #include "FixFunction.h" // for FixFunction
|
---|
57 | #include "Indexer.h" // for Indexer
|
---|
58 | #include "InitTweak/GenInit.h" // for fixReturnStatements
|
---|
59 | #include "InitTweak/InitTweak.h" // for isCtorDtorAssign
|
---|
60 | #include "Parser/LinkageSpec.h" // for C
|
---|
61 | #include "ResolvExpr/typeops.h" // for typesCompatible
|
---|
62 | #include "SymTab/AddVisit.h" // for addVisit
|
---|
63 | #include "SymTab/Autogen.h" // for SizeType
|
---|
64 | #include "SynTree/Attribute.h" // for noAttributes, Attribute
|
---|
65 | #include "SynTree/Constant.h" // for Constant
|
---|
66 | #include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType
|
---|
67 | #include "SynTree/Expression.h" // for CompoundLiteralExpr, Expressio...
|
---|
68 | #include "SynTree/Initializer.h" // for ListInit, Initializer
|
---|
69 | #include "SynTree/Label.h" // for operator==, Label
|
---|
70 | #include "SynTree/Mutator.h" // for Mutator
|
---|
71 | #include "SynTree/Type.h" // for Type, TypeInstType, EnumInstType
|
---|
72 | #include "SynTree/TypeSubstitution.h" // for TypeSubstitution
|
---|
73 | #include "SynTree/Visitor.h" // for Visitor
|
---|
74 |
|
---|
75 | class CompoundStmt;
|
---|
76 | class ReturnStmt;
|
---|
77 | class SwitchStmt;
|
---|
78 |
|
---|
79 |
|
---|
80 | #define debugPrint( x ) if ( doDebug ) { std::cout << x; }
|
---|
81 |
|
---|
82 | namespace SymTab {
|
---|
83 | struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
|
---|
84 | /// Flattens nested struct types
|
---|
85 | static void hoistStruct( std::list< Declaration * > &translationUnit );
|
---|
86 |
|
---|
87 | void previsit( EnumInstType * enumInstType );
|
---|
88 | void previsit( StructInstType * structInstType );
|
---|
89 | void previsit( UnionInstType * unionInstType );
|
---|
90 | void previsit( StructDecl * aggregateDecl );
|
---|
91 | void previsit( UnionDecl * aggregateDecl );
|
---|
92 |
|
---|
93 | private:
|
---|
94 | template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
|
---|
95 |
|
---|
96 | AggregateDecl * parentAggr = nullptr;
|
---|
97 | };
|
---|
98 |
|
---|
99 | /// Fix return types so that every function returns exactly one value
|
---|
100 | struct ReturnTypeFixer {
|
---|
101 | static void fix( std::list< Declaration * > &translationUnit );
|
---|
102 |
|
---|
103 | void postvisit( FunctionDecl * functionDecl );
|
---|
104 | void postvisit( FunctionType * ftype );
|
---|
105 | };
|
---|
106 |
|
---|
107 | /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
|
---|
108 | struct EnumAndPointerDecay {
|
---|
109 | void previsit( EnumDecl *aggregateDecl );
|
---|
110 | void previsit( FunctionType *func );
|
---|
111 | };
|
---|
112 |
|
---|
113 | /// Associates forward declarations of aggregates with their definitions
|
---|
114 | struct LinkReferenceToTypes final : public WithIndexer, public WithGuards {
|
---|
115 | LinkReferenceToTypes( const Indexer *indexer );
|
---|
116 | void postvisit( TypeInstType *typeInst );
|
---|
117 |
|
---|
118 | void postvisit( EnumInstType *enumInst );
|
---|
119 | void postvisit( StructInstType *structInst );
|
---|
120 | void postvisit( UnionInstType *unionInst );
|
---|
121 | void postvisit( TraitInstType *traitInst );
|
---|
122 |
|
---|
123 | void postvisit( EnumDecl *enumDecl );
|
---|
124 | void postvisit( StructDecl *structDecl );
|
---|
125 | void postvisit( UnionDecl *unionDecl );
|
---|
126 | void postvisit( TraitDecl * traitDecl );
|
---|
127 |
|
---|
128 | void previsit( StructDecl *structDecl );
|
---|
129 | void previsit( UnionDecl *unionDecl );
|
---|
130 |
|
---|
131 | void renameGenericParams( std::list< TypeDecl * > & params );
|
---|
132 |
|
---|
133 | private:
|
---|
134 | const Indexer *local_indexer;
|
---|
135 |
|
---|
136 | typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
|
---|
137 | typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
|
---|
138 | typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
|
---|
139 | ForwardEnumsType forwardEnums;
|
---|
140 | ForwardStructsType forwardStructs;
|
---|
141 | ForwardUnionsType forwardUnions;
|
---|
142 | /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
|
---|
143 | bool inGeneric = false;
|
---|
144 | };
|
---|
145 |
|
---|
146 | /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
|
---|
147 | struct ForallPointerDecay final {
|
---|
148 | void previsit( ObjectDecl * object );
|
---|
149 | void previsit( FunctionDecl * func );
|
---|
150 | void previsit( StructDecl * aggrDecl );
|
---|
151 | void previsit( UnionDecl * aggrDecl );
|
---|
152 | };
|
---|
153 |
|
---|
154 | struct ReturnChecker : public WithGuards {
|
---|
155 | /// Checks that return statements return nothing if their return type is void
|
---|
156 | /// and return something if the return type is non-void.
|
---|
157 | static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
|
---|
158 |
|
---|
159 | void previsit( FunctionDecl * functionDecl );
|
---|
160 | void previsit( ReturnStmt * returnStmt );
|
---|
161 |
|
---|
162 | typedef std::list< DeclarationWithType * > ReturnVals;
|
---|
163 | ReturnVals returnVals;
|
---|
164 | };
|
---|
165 |
|
---|
166 | struct EliminateTypedef final : public WithVisitorRef<EliminateTypedef>, public WithGuards {
|
---|
167 | EliminateTypedef() : scopeLevel( 0 ) {}
|
---|
168 | /// Replaces typedefs by forward declarations
|
---|
169 | static void eliminateTypedef( std::list< Declaration * > &translationUnit );
|
---|
170 |
|
---|
171 | Type * postmutate( TypeInstType * aggregateUseType );
|
---|
172 | Declaration * postmutate( TypedefDecl * typeDecl );
|
---|
173 | void premutate( TypeDecl * typeDecl );
|
---|
174 | void premutate( FunctionDecl * funcDecl );
|
---|
175 | void premutate( ObjectDecl * objDecl );
|
---|
176 | DeclarationWithType * postmutate( ObjectDecl * objDecl );
|
---|
177 |
|
---|
178 | void premutate( CastExpr * castExpr );
|
---|
179 |
|
---|
180 | void premutate( CompoundStmt * compoundStmt );
|
---|
181 | CompoundStmt * postmutate( CompoundStmt * compoundStmt );
|
---|
182 |
|
---|
183 | void premutate( StructDecl * structDecl );
|
---|
184 | Declaration * postmutate( StructDecl * structDecl );
|
---|
185 | void premutate( UnionDecl * unionDecl );
|
---|
186 | Declaration * postmutate( UnionDecl * unionDecl );
|
---|
187 | void premutate( EnumDecl * enumDecl );
|
---|
188 | Declaration * postmutate( EnumDecl * enumDecl );
|
---|
189 | Declaration * postmutate( TraitDecl * contextDecl );
|
---|
190 |
|
---|
191 | void premutate( FunctionType * ftype );
|
---|
192 |
|
---|
193 | private:
|
---|
194 | template<typename AggDecl>
|
---|
195 | AggDecl *handleAggregate( AggDecl * aggDecl );
|
---|
196 |
|
---|
197 | template<typename AggDecl>
|
---|
198 | void addImplicitTypedef( AggDecl * aggDecl );
|
---|
199 |
|
---|
200 | typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
|
---|
201 | typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
|
---|
202 | typedef std::map< std::string, TypeDecl * > TypeDeclMap;
|
---|
203 | TypedefMap typedefNames;
|
---|
204 | TypeDeclMap typedeclNames;
|
---|
205 | int scopeLevel;
|
---|
206 | bool inFunctionType = false;
|
---|
207 | };
|
---|
208 |
|
---|
209 | struct VerifyCtorDtorAssign {
|
---|
210 | /// ensure that constructors, destructors, and assignment have at least one
|
---|
211 | /// parameter, the first of which must be a pointer, and that ctor/dtors have no
|
---|
212 | /// return values.
|
---|
213 | static void verify( std::list< Declaration * > &translationUnit );
|
---|
214 |
|
---|
215 | void previsit( FunctionDecl *funcDecl );
|
---|
216 | };
|
---|
217 |
|
---|
218 | /// ensure that generic types have the correct number of type arguments
|
---|
219 | struct ValidateGenericParameters {
|
---|
220 | void previsit( StructInstType * inst );
|
---|
221 | void previsit( UnionInstType * inst );
|
---|
222 | };
|
---|
223 |
|
---|
224 | struct ArrayLength {
|
---|
225 | /// for array types without an explicit length, compute the length and store it so that it
|
---|
226 | /// is known to the rest of the phases. For example,
|
---|
227 | /// int x[] = { 1, 2, 3 };
|
---|
228 | /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
|
---|
229 | /// here x and y are known at compile-time to have length 3, so change this into
|
---|
230 | /// int x[3] = { 1, 2, 3 };
|
---|
231 | /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
|
---|
232 | static void computeLength( std::list< Declaration * > & translationUnit );
|
---|
233 |
|
---|
234 | void previsit( ObjectDecl * objDecl );
|
---|
235 | };
|
---|
236 |
|
---|
237 | struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
|
---|
238 | Type::StorageClasses storageClasses;
|
---|
239 |
|
---|
240 | void premutate( ObjectDecl *objectDecl );
|
---|
241 | Expression * postmutate( CompoundLiteralExpr *compLitExpr );
|
---|
242 | };
|
---|
243 |
|
---|
244 | struct LabelAddressFixer final : public WithGuards {
|
---|
245 | std::set< Label > labels;
|
---|
246 |
|
---|
247 | void premutate( FunctionDecl * funcDecl );
|
---|
248 | Expression * postmutate( AddressExpr * addrExpr );
|
---|
249 | };
|
---|
250 |
|
---|
251 | FunctionDecl * dereferenceOperator = nullptr;
|
---|
252 | struct FindSpecialDeclarations final {
|
---|
253 | void previsit( FunctionDecl * funcDecl );
|
---|
254 | };
|
---|
255 |
|
---|
256 | void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
|
---|
257 | PassVisitor<EnumAndPointerDecay> epc;
|
---|
258 | PassVisitor<LinkReferenceToTypes> lrt( nullptr );
|
---|
259 | PassVisitor<ForallPointerDecay> fpd;
|
---|
260 | PassVisitor<CompoundLiteral> compoundliteral;
|
---|
261 | PassVisitor<ValidateGenericParameters> genericParams;
|
---|
262 | PassVisitor<FindSpecialDeclarations> finder;
|
---|
263 | PassVisitor<LabelAddressFixer> labelAddrFixer;
|
---|
264 |
|
---|
265 | EliminateTypedef::eliminateTypedef( translationUnit );
|
---|
266 | HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
|
---|
267 | ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
|
---|
268 | acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling
|
---|
269 | acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
|
---|
270 | acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes
|
---|
271 | VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors
|
---|
272 | ReturnChecker::checkFunctionReturns( translationUnit );
|
---|
273 | InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
|
---|
274 | Concurrency::applyKeywords( translationUnit );
|
---|
275 | acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
|
---|
276 | autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
|
---|
277 | Concurrency::implementMutexFuncs( translationUnit );
|
---|
278 | Concurrency::implementThreadStarter( translationUnit );
|
---|
279 | mutateAll( translationUnit, compoundliteral );
|
---|
280 | ArrayLength::computeLength( translationUnit );
|
---|
281 | acceptAll( translationUnit, finder ); // xxx - remove this pass soon
|
---|
282 | mutateAll( translationUnit, labelAddrFixer );
|
---|
283 | }
|
---|
284 |
|
---|
285 | void validateType( Type *type, const Indexer *indexer ) {
|
---|
286 | PassVisitor<EnumAndPointerDecay> epc;
|
---|
287 | PassVisitor<LinkReferenceToTypes> lrt( indexer );
|
---|
288 | PassVisitor<ForallPointerDecay> fpd;
|
---|
289 | type->accept( epc );
|
---|
290 | type->accept( lrt );
|
---|
291 | type->accept( fpd );
|
---|
292 | }
|
---|
293 |
|
---|
294 | void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
|
---|
295 | PassVisitor<HoistStruct> hoister;
|
---|
296 | acceptAll( translationUnit, hoister );
|
---|
297 | }
|
---|
298 |
|
---|
299 | bool isStructOrUnion( Declaration *decl ) {
|
---|
300 | return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
|
---|
301 | }
|
---|
302 |
|
---|
303 | template< typename AggDecl >
|
---|
304 | void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
|
---|
305 | if ( parentAggr ) {
|
---|
306 | // Add elements in stack order corresponding to nesting structure.
|
---|
307 | declsToAddBefore.push_front( aggregateDecl );
|
---|
308 | } else {
|
---|
309 | GuardValue( parentAggr );
|
---|
310 | parentAggr = aggregateDecl;
|
---|
311 | } // if
|
---|
312 | // Always remove the hoisted aggregate from the inner structure.
|
---|
313 | GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, isStructOrUnion, false ); } );
|
---|
314 | }
|
---|
315 |
|
---|
316 | void HoistStruct::previsit( EnumInstType * inst ) {
|
---|
317 | if ( inst->baseEnum ) {
|
---|
318 | declsToAddBefore.push_front( inst->baseEnum );
|
---|
319 | }
|
---|
320 | }
|
---|
321 |
|
---|
322 | void HoistStruct::previsit( StructInstType * inst ) {
|
---|
323 | if ( inst->baseStruct ) {
|
---|
324 | declsToAddBefore.push_front( inst->baseStruct );
|
---|
325 | }
|
---|
326 | }
|
---|
327 |
|
---|
328 | void HoistStruct::previsit( UnionInstType * inst ) {
|
---|
329 | if ( inst->baseUnion ) {
|
---|
330 | declsToAddBefore.push_front( inst->baseUnion );
|
---|
331 | }
|
---|
332 | }
|
---|
333 |
|
---|
334 | void HoistStruct::previsit( StructDecl * aggregateDecl ) {
|
---|
335 | handleAggregate( aggregateDecl );
|
---|
336 | }
|
---|
337 |
|
---|
338 | void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
|
---|
339 | handleAggregate( aggregateDecl );
|
---|
340 | }
|
---|
341 |
|
---|
342 | void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
|
---|
343 | // Set the type of each member of the enumeration to be EnumConstant
|
---|
344 | for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
|
---|
345 | ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
|
---|
346 | assert( obj );
|
---|
347 | obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->get_name() ) );
|
---|
348 | } // for
|
---|
349 | }
|
---|
350 |
|
---|
351 | namespace {
|
---|
352 | template< typename DWTList >
|
---|
353 | void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
|
---|
354 | auto nvals = dwts.size();
|
---|
355 | bool containsVoid = false;
|
---|
356 | for ( auto & dwt : dwts ) {
|
---|
357 | // fix each DWT and record whether a void was found
|
---|
358 | containsVoid |= fixFunction( dwt );
|
---|
359 | }
|
---|
360 |
|
---|
361 | // the only case in which "void" is valid is where it is the only one in the list
|
---|
362 | if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
|
---|
363 | throw SemanticError( func, "invalid type void in function type " );
|
---|
364 | }
|
---|
365 |
|
---|
366 | // one void is the only thing in the list; remove it.
|
---|
367 | if ( containsVoid ) {
|
---|
368 | delete dwts.front();
|
---|
369 | dwts.clear();
|
---|
370 | }
|
---|
371 | }
|
---|
372 | }
|
---|
373 |
|
---|
374 | void EnumAndPointerDecay::previsit( FunctionType *func ) {
|
---|
375 | // Fix up parameters and return types
|
---|
376 | fixFunctionList( func->parameters, func->isVarArgs, func );
|
---|
377 | fixFunctionList( func->returnVals, false, func );
|
---|
378 | }
|
---|
379 |
|
---|
380 | LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
|
---|
381 | if ( other_indexer ) {
|
---|
382 | local_indexer = other_indexer;
|
---|
383 | } else {
|
---|
384 | local_indexer = &indexer;
|
---|
385 | } // if
|
---|
386 | }
|
---|
387 |
|
---|
388 | void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
|
---|
389 | EnumDecl *st = local_indexer->lookupEnum( enumInst->get_name() );
|
---|
390 | // it's not a semantic error if the enum is not found, just an implicit forward declaration
|
---|
391 | if ( st ) {
|
---|
392 | //assert( ! enumInst->get_baseEnum() || enumInst->get_baseEnum()->get_members().empty() || ! st->get_members().empty() );
|
---|
393 | enumInst->set_baseEnum( st );
|
---|
394 | } // if
|
---|
395 | if ( ! st || st->get_members().empty() ) {
|
---|
396 | // use of forward declaration
|
---|
397 | forwardEnums[ enumInst->get_name() ].push_back( enumInst );
|
---|
398 | } // if
|
---|
399 | }
|
---|
400 |
|
---|
401 | void checkGenericParameters( ReferenceToType * inst ) {
|
---|
402 | for ( Expression * param : inst->parameters ) {
|
---|
403 | if ( ! dynamic_cast< TypeExpr * >( param ) ) {
|
---|
404 | throw SemanticError( inst, "Expression parameters for generic types are currently unsupported: " );
|
---|
405 | }
|
---|
406 | }
|
---|
407 | }
|
---|
408 |
|
---|
409 | void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
|
---|
410 | StructDecl *st = local_indexer->lookupStruct( structInst->get_name() );
|
---|
411 | // it's not a semantic error if the struct is not found, just an implicit forward declaration
|
---|
412 | if ( st ) {
|
---|
413 | //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
|
---|
414 | structInst->set_baseStruct( st );
|
---|
415 | } // if
|
---|
416 | if ( ! st || st->get_members().empty() ) {
|
---|
417 | // use of forward declaration
|
---|
418 | forwardStructs[ structInst->get_name() ].push_back( structInst );
|
---|
419 | } // if
|
---|
420 | checkGenericParameters( structInst );
|
---|
421 | }
|
---|
422 |
|
---|
423 | void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
|
---|
424 | UnionDecl *un = local_indexer->lookupUnion( unionInst->get_name() );
|
---|
425 | // it's not a semantic error if the union is not found, just an implicit forward declaration
|
---|
426 | if ( un ) {
|
---|
427 | unionInst->set_baseUnion( un );
|
---|
428 | } // if
|
---|
429 | if ( ! un || un->get_members().empty() ) {
|
---|
430 | // use of forward declaration
|
---|
431 | forwardUnions[ unionInst->get_name() ].push_back( unionInst );
|
---|
432 | } // if
|
---|
433 | checkGenericParameters( unionInst );
|
---|
434 | }
|
---|
435 |
|
---|
436 | template< typename Decl >
|
---|
437 | void normalizeAssertions( std::list< Decl * > & assertions ) {
|
---|
438 | // ensure no duplicate trait members after the clone
|
---|
439 | auto pred = [](Decl * d1, Decl * d2) {
|
---|
440 | // only care if they're equal
|
---|
441 | DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
|
---|
442 | DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
|
---|
443 | if ( dwt1 && dwt2 ) {
|
---|
444 | if ( dwt1->get_name() == dwt2->get_name() && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
|
---|
445 | // std::cerr << "=========== equal:" << std::endl;
|
---|
446 | // std::cerr << "d1: " << d1 << std::endl;
|
---|
447 | // std::cerr << "d2: " << d2 << std::endl;
|
---|
448 | return false;
|
---|
449 | }
|
---|
450 | }
|
---|
451 | return d1 < d2;
|
---|
452 | };
|
---|
453 | std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
|
---|
454 | // if ( unique_members.size() != assertions.size() ) {
|
---|
455 | // std::cerr << "============different" << std::endl;
|
---|
456 | // std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
|
---|
457 | // }
|
---|
458 |
|
---|
459 | std::list< Decl * > order;
|
---|
460 | order.splice( order.end(), assertions );
|
---|
461 | std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
|
---|
462 | return unique_members.count( decl );
|
---|
463 | });
|
---|
464 | }
|
---|
465 |
|
---|
466 | // expand assertions from trait instance, performing the appropriate type variable substitutions
|
---|
467 | template< typename Iterator >
|
---|
468 | void expandAssertions( TraitInstType * inst, Iterator out ) {
|
---|
469 | assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toString( inst ).c_str() );
|
---|
470 | std::list< DeclarationWithType * > asserts;
|
---|
471 | for ( Declaration * decl : inst->baseTrait->members ) {
|
---|
472 | asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
|
---|
473 | }
|
---|
474 | // substitute trait decl parameters for instance parameters
|
---|
475 | applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
|
---|
476 | }
|
---|
477 |
|
---|
478 | void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
|
---|
479 | if ( traitDecl->name == "sized" ) {
|
---|
480 | // "sized" is a special trait - flick the sized status on for the type variable
|
---|
481 | assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
|
---|
482 | TypeDecl * td = traitDecl->parameters.front();
|
---|
483 | td->set_sized( true );
|
---|
484 | }
|
---|
485 |
|
---|
486 | // move assertions from type parameters into the body of the trait
|
---|
487 | for ( TypeDecl * td : traitDecl->parameters ) {
|
---|
488 | for ( DeclarationWithType * assert : td->assertions ) {
|
---|
489 | if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
|
---|
490 | expandAssertions( inst, back_inserter( traitDecl->members ) );
|
---|
491 | } else {
|
---|
492 | traitDecl->members.push_back( assert->clone() );
|
---|
493 | }
|
---|
494 | }
|
---|
495 | deleteAll( td->assertions );
|
---|
496 | td->assertions.clear();
|
---|
497 | } // for
|
---|
498 | }
|
---|
499 |
|
---|
500 | void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
|
---|
501 | // handle other traits
|
---|
502 | TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
|
---|
503 | if ( ! traitDecl ) {
|
---|
504 | throw SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
|
---|
505 | } // if
|
---|
506 | if ( traitDecl->get_parameters().size() != traitInst->get_parameters().size() ) {
|
---|
507 | throw SemanticError( traitInst, "incorrect number of trait parameters: " );
|
---|
508 | } // if
|
---|
509 | traitInst->baseTrait = traitDecl;
|
---|
510 |
|
---|
511 | // need to carry over the 'sized' status of each decl in the instance
|
---|
512 | for ( auto p : group_iterate( traitDecl->get_parameters(), traitInst->get_parameters() ) ) {
|
---|
513 | TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
|
---|
514 | if ( ! expr ) {
|
---|
515 | throw SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
|
---|
516 | }
|
---|
517 | if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
|
---|
518 | TypeDecl * formalDecl = std::get<0>(p);
|
---|
519 | TypeDecl * instDecl = inst->get_baseType();
|
---|
520 | if ( formalDecl->get_sized() ) instDecl->set_sized( true );
|
---|
521 | }
|
---|
522 | }
|
---|
523 | // normalizeAssertions( traitInst->members );
|
---|
524 | }
|
---|
525 |
|
---|
526 | void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
|
---|
527 | // visit enum members first so that the types of self-referencing members are updated properly
|
---|
528 | if ( ! enumDecl->get_members().empty() ) {
|
---|
529 | ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->get_name() );
|
---|
530 | if ( fwds != forwardEnums.end() ) {
|
---|
531 | for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
|
---|
532 | (*inst )->set_baseEnum( enumDecl );
|
---|
533 | } // for
|
---|
534 | forwardEnums.erase( fwds );
|
---|
535 | } // if
|
---|
536 | } // if
|
---|
537 | }
|
---|
538 |
|
---|
539 | void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) {
|
---|
540 | // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
|
---|
541 | // forall(otype T)
|
---|
542 | // struct Box {
|
---|
543 | // T x;
|
---|
544 | // };
|
---|
545 | // forall(otype T)
|
---|
546 | // void f(Box(T) b) {
|
---|
547 | // ...
|
---|
548 | // }
|
---|
549 | // The T in Box and the T in f are different, so internally the naming must reflect that.
|
---|
550 | GuardValue( inGeneric );
|
---|
551 | inGeneric = ! params.empty();
|
---|
552 | for ( TypeDecl * td : params ) {
|
---|
553 | td->name = "__" + td->name + "_generic_";
|
---|
554 | }
|
---|
555 | }
|
---|
556 |
|
---|
557 | void LinkReferenceToTypes::previsit( StructDecl * structDecl ) {
|
---|
558 | renameGenericParams( structDecl->parameters );
|
---|
559 | }
|
---|
560 |
|
---|
561 | void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) {
|
---|
562 | renameGenericParams( unionDecl->parameters );
|
---|
563 | }
|
---|
564 |
|
---|
565 | void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
|
---|
566 | // visit struct members first so that the types of self-referencing members are updated properly
|
---|
567 | // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
|
---|
568 | if ( ! structDecl->get_members().empty() ) {
|
---|
569 | ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
|
---|
570 | if ( fwds != forwardStructs.end() ) {
|
---|
571 | for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
|
---|
572 | (*inst )->set_baseStruct( structDecl );
|
---|
573 | } // for
|
---|
574 | forwardStructs.erase( fwds );
|
---|
575 | } // if
|
---|
576 | } // if
|
---|
577 | }
|
---|
578 |
|
---|
579 | void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
|
---|
580 | if ( ! unionDecl->get_members().empty() ) {
|
---|
581 | ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
|
---|
582 | if ( fwds != forwardUnions.end() ) {
|
---|
583 | for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
|
---|
584 | (*inst )->set_baseUnion( unionDecl );
|
---|
585 | } // for
|
---|
586 | forwardUnions.erase( fwds );
|
---|
587 | } // if
|
---|
588 | } // if
|
---|
589 | }
|
---|
590 |
|
---|
591 | void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
|
---|
592 | // ensure generic parameter instances are renamed like the base type
|
---|
593 | if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
|
---|
594 | if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->get_name() ) ) {
|
---|
595 | if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
|
---|
596 | typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
|
---|
597 | } // if
|
---|
598 | } // if
|
---|
599 | }
|
---|
600 |
|
---|
601 | /// Fix up assertions - flattens assertion lists, removing all trait instances
|
---|
602 | void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
|
---|
603 | for ( TypeDecl * type : forall ) {
|
---|
604 | std::list< DeclarationWithType * > asserts;
|
---|
605 | asserts.splice( asserts.end(), type->assertions );
|
---|
606 | // expand trait instances into their members
|
---|
607 | for ( DeclarationWithType * assertion : asserts ) {
|
---|
608 | if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
|
---|
609 | // expand trait instance into all of its members
|
---|
610 | expandAssertions( traitInst, back_inserter( type->assertions ) );
|
---|
611 | delete traitInst;
|
---|
612 | } else {
|
---|
613 | // pass other assertions through
|
---|
614 | type->assertions.push_back( assertion );
|
---|
615 | } // if
|
---|
616 | } // for
|
---|
617 | // apply FixFunction to every assertion to check for invalid void type
|
---|
618 | for ( DeclarationWithType *& assertion : type->assertions ) {
|
---|
619 | bool isVoid = fixFunction( assertion );
|
---|
620 | if ( isVoid ) {
|
---|
621 | throw SemanticError( node, "invalid type void in assertion of function " );
|
---|
622 | } // if
|
---|
623 | } // for
|
---|
624 | // normalizeAssertions( type->assertions );
|
---|
625 | } // for
|
---|
626 | }
|
---|
627 |
|
---|
628 | void ForallPointerDecay::previsit( ObjectDecl *object ) {
|
---|
629 | forallFixer( object->type->forall, object );
|
---|
630 | if ( PointerType *pointer = dynamic_cast< PointerType * >( object->type ) ) {
|
---|
631 | forallFixer( pointer->base->forall, object );
|
---|
632 | } // if
|
---|
633 | object->fixUniqueId();
|
---|
634 | }
|
---|
635 |
|
---|
636 | void ForallPointerDecay::previsit( FunctionDecl *func ) {
|
---|
637 | forallFixer( func->type->forall, func );
|
---|
638 | func->fixUniqueId();
|
---|
639 | }
|
---|
640 |
|
---|
641 | void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
|
---|
642 | forallFixer( aggrDecl->parameters, aggrDecl );
|
---|
643 | }
|
---|
644 |
|
---|
645 | void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
|
---|
646 | forallFixer( aggrDecl->parameters, aggrDecl );
|
---|
647 | }
|
---|
648 |
|
---|
649 | void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
|
---|
650 | PassVisitor<ReturnChecker> checker;
|
---|
651 | acceptAll( translationUnit, checker );
|
---|
652 | }
|
---|
653 |
|
---|
654 | void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
|
---|
655 | GuardValue( returnVals );
|
---|
656 | returnVals = functionDecl->get_functionType()->get_returnVals();
|
---|
657 | }
|
---|
658 |
|
---|
659 | void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
|
---|
660 | // Previously this also checked for the existence of an expr paired with no return values on
|
---|
661 | // the function return type. This is incorrect, since you can have an expression attached to
|
---|
662 | // a return statement in a void-returning function in C. The expression is treated as if it
|
---|
663 | // were cast to void.
|
---|
664 | if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
|
---|
665 | throw SemanticError( returnStmt, "Non-void function returns no values: " );
|
---|
666 | }
|
---|
667 | }
|
---|
668 |
|
---|
669 |
|
---|
670 | bool isTypedef( Declaration *decl ) {
|
---|
671 | return dynamic_cast< TypedefDecl * >( decl );
|
---|
672 | }
|
---|
673 |
|
---|
674 | void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
|
---|
675 | PassVisitor<EliminateTypedef> eliminator;
|
---|
676 | mutateAll( translationUnit, eliminator );
|
---|
677 | if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
|
---|
678 | // grab and remember declaration of size_t
|
---|
679 | SizeType = eliminator.pass.typedefNames["size_t"].first->get_base()->clone();
|
---|
680 | } else {
|
---|
681 | // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
|
---|
682 | // eventually should have a warning for this case.
|
---|
683 | SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
|
---|
684 | }
|
---|
685 | filter( translationUnit, isTypedef, true );
|
---|
686 | }
|
---|
687 |
|
---|
688 | Type * EliminateTypedef::postmutate( TypeInstType * typeInst ) {
|
---|
689 | // instances of typedef types will come here. If it is an instance
|
---|
690 | // of a typdef type, link the instance to its actual type.
|
---|
691 | TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
|
---|
692 | if ( def != typedefNames.end() ) {
|
---|
693 | Type *ret = def->second.first->base->clone();
|
---|
694 | ret->get_qualifiers() |= typeInst->get_qualifiers();
|
---|
695 | // attributes are not carried over from typedef to function parameters/return values
|
---|
696 | if ( ! inFunctionType ) {
|
---|
697 | ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
|
---|
698 | } else {
|
---|
699 | deleteAll( ret->attributes );
|
---|
700 | ret->attributes.clear();
|
---|
701 | }
|
---|
702 | // place instance parameters on the typedef'd type
|
---|
703 | if ( ! typeInst->parameters.empty() ) {
|
---|
704 | ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
|
---|
705 | if ( ! rtt ) {
|
---|
706 | throw SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
|
---|
707 | }
|
---|
708 | rtt->get_parameters().clear();
|
---|
709 | cloneAll( typeInst->parameters, rtt->parameters );
|
---|
710 | mutateAll( rtt->parameters, *visitor ); // recursively fix typedefs on parameters
|
---|
711 | } // if
|
---|
712 | delete typeInst;
|
---|
713 | return ret;
|
---|
714 | } else {
|
---|
715 | TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
|
---|
716 | assertf( base != typedeclNames.end(), "Cannot find typedecl name %s", typeInst->name.c_str() );
|
---|
717 | typeInst->set_baseType( base->second );
|
---|
718 | } // if
|
---|
719 | return typeInst;
|
---|
720 | }
|
---|
721 |
|
---|
722 | struct VarLenChecker : WithShortCircuiting {
|
---|
723 | void previsit( FunctionType * ) { visit_children = false; }
|
---|
724 | void previsit( ArrayType * at ) {
|
---|
725 | isVarLen |= at->isVarLen;
|
---|
726 | }
|
---|
727 | bool isVarLen = false;
|
---|
728 | };
|
---|
729 |
|
---|
730 | bool isVariableLength( Type * t ) {
|
---|
731 | PassVisitor<VarLenChecker> varLenChecker;
|
---|
732 | maybeAccept( t, varLenChecker );
|
---|
733 | return varLenChecker.pass.isVarLen;
|
---|
734 | }
|
---|
735 |
|
---|
736 | Declaration *EliminateTypedef::postmutate( TypedefDecl * tyDecl ) {
|
---|
737 | if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
|
---|
738 | // typedef to the same name from the same scope
|
---|
739 | // must be from the same type
|
---|
740 |
|
---|
741 | Type * t1 = tyDecl->get_base();
|
---|
742 | Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
|
---|
743 | if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
|
---|
744 | throw SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
|
---|
745 | }
|
---|
746 | // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
|
---|
747 | // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
|
---|
748 | // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
|
---|
749 | // to fix this corner case likely outweighs the utility of allowing it.
|
---|
750 | if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
|
---|
751 | throw SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
|
---|
752 | }
|
---|
753 | } else {
|
---|
754 | typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
|
---|
755 | } // if
|
---|
756 |
|
---|
757 | // When a typedef is a forward declaration:
|
---|
758 | // typedef struct screen SCREEN;
|
---|
759 | // the declaration portion must be retained:
|
---|
760 | // struct screen;
|
---|
761 | // because the expansion of the typedef is:
|
---|
762 | // void rtn( SCREEN *p ) => void rtn( struct screen *p )
|
---|
763 | // hence the type-name "screen" must be defined.
|
---|
764 | // Note, qualifiers on the typedef are superfluous for the forward declaration.
|
---|
765 |
|
---|
766 | Type *designatorType = tyDecl->get_base()->stripDeclarator();
|
---|
767 | if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
|
---|
768 | return new StructDecl( aggDecl->get_name(), DeclarationNode::Struct, noAttributes, tyDecl->get_linkage() );
|
---|
769 | } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
|
---|
770 | return new UnionDecl( aggDecl->get_name(), noAttributes, tyDecl->get_linkage() );
|
---|
771 | } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
|
---|
772 | return new EnumDecl( enumDecl->get_name(), noAttributes, tyDecl->get_linkage() );
|
---|
773 | } else {
|
---|
774 | return tyDecl->clone();
|
---|
775 | } // if
|
---|
776 | }
|
---|
777 |
|
---|
778 | void EliminateTypedef::premutate( TypeDecl * typeDecl ) {
|
---|
779 | TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
|
---|
780 | if ( i != typedefNames.end() ) {
|
---|
781 | typedefNames.erase( i ) ;
|
---|
782 | } // if
|
---|
783 |
|
---|
784 | typedeclNames[ typeDecl->get_name() ] = typeDecl;
|
---|
785 | }
|
---|
786 |
|
---|
787 | void EliminateTypedef::premutate( FunctionDecl * ) {
|
---|
788 | GuardScope( typedefNames );
|
---|
789 | }
|
---|
790 |
|
---|
791 | void EliminateTypedef::premutate( ObjectDecl * ) {
|
---|
792 | GuardScope( typedefNames );
|
---|
793 | }
|
---|
794 |
|
---|
795 | DeclarationWithType *EliminateTypedef::postmutate( ObjectDecl * objDecl ) {
|
---|
796 | if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->get_type() ) ) { // function type?
|
---|
797 | // replace the current object declaration with a function declaration
|
---|
798 | FunctionDecl * newDecl = new FunctionDecl( objDecl->get_name(), objDecl->get_storageClasses(), objDecl->get_linkage(), funtype, 0, objDecl->get_attributes(), objDecl->get_funcSpec() );
|
---|
799 | objDecl->get_attributes().clear();
|
---|
800 | objDecl->set_type( nullptr );
|
---|
801 | delete objDecl;
|
---|
802 | return newDecl;
|
---|
803 | } // if
|
---|
804 | return objDecl;
|
---|
805 | }
|
---|
806 |
|
---|
807 | void EliminateTypedef::premutate( CastExpr * ) {
|
---|
808 | GuardScope( typedefNames );
|
---|
809 | }
|
---|
810 |
|
---|
811 | void EliminateTypedef::premutate( CompoundStmt * ) {
|
---|
812 | GuardScope( typedefNames );
|
---|
813 | scopeLevel += 1;
|
---|
814 | GuardAction( [this](){ scopeLevel -= 1; } );
|
---|
815 | }
|
---|
816 |
|
---|
817 | CompoundStmt *EliminateTypedef::postmutate( CompoundStmt * compoundStmt ) {
|
---|
818 | // remove and delete decl stmts
|
---|
819 | filter( compoundStmt->kids, [](Statement * stmt) {
|
---|
820 | if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
|
---|
821 | if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
|
---|
822 | return true;
|
---|
823 | } // if
|
---|
824 | } // if
|
---|
825 | return false;
|
---|
826 | }, true);
|
---|
827 | return compoundStmt;
|
---|
828 | }
|
---|
829 |
|
---|
830 | // there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed
|
---|
831 | // as well
|
---|
832 | template<typename AggDecl>
|
---|
833 | AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
|
---|
834 | filter( aggDecl->members, isTypedef, true );
|
---|
835 | return aggDecl;
|
---|
836 | }
|
---|
837 |
|
---|
838 | template<typename AggDecl>
|
---|
839 | void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
|
---|
840 | if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
|
---|
841 | Type *type = nullptr;
|
---|
842 | if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
|
---|
843 | type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
|
---|
844 | } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
|
---|
845 | type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
|
---|
846 | } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) {
|
---|
847 | type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
|
---|
848 | } // if
|
---|
849 | TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
|
---|
850 | typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
|
---|
851 | } // if
|
---|
852 | }
|
---|
853 |
|
---|
854 | void EliminateTypedef::premutate( StructDecl * structDecl ) {
|
---|
855 | addImplicitTypedef( structDecl );
|
---|
856 | }
|
---|
857 |
|
---|
858 |
|
---|
859 | Declaration *EliminateTypedef::postmutate( StructDecl * structDecl ) {
|
---|
860 | return handleAggregate( structDecl );
|
---|
861 | }
|
---|
862 |
|
---|
863 | void EliminateTypedef::premutate( UnionDecl * unionDecl ) {
|
---|
864 | addImplicitTypedef( unionDecl );
|
---|
865 | }
|
---|
866 |
|
---|
867 | Declaration *EliminateTypedef::postmutate( UnionDecl * unionDecl ) {
|
---|
868 | return handleAggregate( unionDecl );
|
---|
869 | }
|
---|
870 |
|
---|
871 | void EliminateTypedef::premutate( EnumDecl * enumDecl ) {
|
---|
872 | addImplicitTypedef( enumDecl );
|
---|
873 | }
|
---|
874 |
|
---|
875 | Declaration *EliminateTypedef::postmutate( EnumDecl * enumDecl ) {
|
---|
876 | return handleAggregate( enumDecl );
|
---|
877 | }
|
---|
878 |
|
---|
879 | Declaration *EliminateTypedef::postmutate( TraitDecl * traitDecl ) {
|
---|
880 | return handleAggregate( traitDecl );
|
---|
881 | }
|
---|
882 |
|
---|
883 | void EliminateTypedef::premutate( FunctionType * ) {
|
---|
884 | GuardValue( inFunctionType );
|
---|
885 | inFunctionType = true;
|
---|
886 | }
|
---|
887 |
|
---|
888 | void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
|
---|
889 | PassVisitor<VerifyCtorDtorAssign> verifier;
|
---|
890 | acceptAll( translationUnit, verifier );
|
---|
891 | }
|
---|
892 |
|
---|
893 | void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
|
---|
894 | FunctionType * funcType = funcDecl->get_functionType();
|
---|
895 | std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
|
---|
896 | std::list< DeclarationWithType * > ¶ms = funcType->get_parameters();
|
---|
897 |
|
---|
898 | if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
|
---|
899 | if ( params.size() == 0 ) {
|
---|
900 | throw SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " );
|
---|
901 | }
|
---|
902 | ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
|
---|
903 | if ( ! refType ) {
|
---|
904 | throw SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " );
|
---|
905 | }
|
---|
906 | if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
|
---|
907 | throw SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " );
|
---|
908 | }
|
---|
909 | }
|
---|
910 | }
|
---|
911 |
|
---|
912 | template< typename Aggr >
|
---|
913 | void validateGeneric( Aggr * inst ) {
|
---|
914 | std::list< TypeDecl * > * params = inst->get_baseParameters();
|
---|
915 | if ( params ) {
|
---|
916 | std::list< Expression * > & args = inst->get_parameters();
|
---|
917 |
|
---|
918 | // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
|
---|
919 | // A substitution is used to ensure that defaults are replaced correctly, e.g.,
|
---|
920 | // forall(otype T, otype alloc = heap_allocator(T)) struct vector;
|
---|
921 | // vector(int) v;
|
---|
922 | // after insertion of default values becomes
|
---|
923 | // vector(int, heap_allocator(T))
|
---|
924 | // and the substitution is built with T=int so that after substitution, the result is
|
---|
925 | // vector(int, heap_allocator(int))
|
---|
926 | TypeSubstitution sub;
|
---|
927 | auto paramIter = params->begin();
|
---|
928 | for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
|
---|
929 | if ( i < args.size() ) {
|
---|
930 | TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
|
---|
931 | sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
|
---|
932 | } else if ( i == args.size() ) {
|
---|
933 | Type * defaultType = (*paramIter)->get_init();
|
---|
934 | if ( defaultType ) {
|
---|
935 | args.push_back( new TypeExpr( defaultType->clone() ) );
|
---|
936 | sub.add( (*paramIter)->get_name(), defaultType->clone() );
|
---|
937 | }
|
---|
938 | }
|
---|
939 | }
|
---|
940 |
|
---|
941 | sub.apply( inst );
|
---|
942 | if ( args.size() < params->size() ) throw SemanticError( inst, "Too few type arguments in generic type " );
|
---|
943 | if ( args.size() > params->size() ) throw SemanticError( inst, "Too many type arguments in generic type " );
|
---|
944 | }
|
---|
945 | }
|
---|
946 |
|
---|
947 | void ValidateGenericParameters::previsit( StructInstType * inst ) {
|
---|
948 | validateGeneric( inst );
|
---|
949 | }
|
---|
950 |
|
---|
951 | void ValidateGenericParameters::previsit( UnionInstType * inst ) {
|
---|
952 | validateGeneric( inst );
|
---|
953 | }
|
---|
954 |
|
---|
955 | void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
|
---|
956 | storageClasses = objectDecl->get_storageClasses();
|
---|
957 | }
|
---|
958 |
|
---|
959 | Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
|
---|
960 | // transform [storage_class] ... (struct S){ 3, ... };
|
---|
961 | // into [storage_class] struct S temp = { 3, ... };
|
---|
962 | static UniqueName indexName( "_compLit" );
|
---|
963 |
|
---|
964 | ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
|
---|
965 | compLitExpr->set_result( nullptr );
|
---|
966 | compLitExpr->set_initializer( nullptr );
|
---|
967 | delete compLitExpr;
|
---|
968 | declsToAddBefore.push_back( tempvar ); // add modified temporary to current block
|
---|
969 | return new VariableExpr( tempvar );
|
---|
970 | }
|
---|
971 |
|
---|
972 | void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
|
---|
973 | PassVisitor<ReturnTypeFixer> fixer;
|
---|
974 | acceptAll( translationUnit, fixer );
|
---|
975 | }
|
---|
976 |
|
---|
977 | void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
|
---|
978 | FunctionType * ftype = functionDecl->get_functionType();
|
---|
979 | std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
|
---|
980 | assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
|
---|
981 | if ( retVals.size() == 1 ) {
|
---|
982 | // ensure all function return values have a name - use the name of the function to disambiguate (this also provides a nice bit of help for debugging).
|
---|
983 | // ensure other return values have a name.
|
---|
984 | DeclarationWithType * ret = retVals.front();
|
---|
985 | if ( ret->get_name() == "" ) {
|
---|
986 | ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
|
---|
987 | }
|
---|
988 | ret->get_attributes().push_back( new Attribute( "unused" ) );
|
---|
989 | }
|
---|
990 | }
|
---|
991 |
|
---|
992 | void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
|
---|
993 | // xxx - need to handle named return values - this information needs to be saved somehow
|
---|
994 | // so that resolution has access to the names.
|
---|
995 | // Note that this pass needs to happen early so that other passes which look for tuple types
|
---|
996 | // find them in all of the right places, including function return types.
|
---|
997 | std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
|
---|
998 | if ( retVals.size() > 1 ) {
|
---|
999 | // generate a single return parameter which is the tuple of all of the return values
|
---|
1000 | TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
|
---|
1001 | // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
|
---|
1002 | ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
|
---|
1003 | deleteAll( retVals );
|
---|
1004 | retVals.clear();
|
---|
1005 | retVals.push_back( newRet );
|
---|
1006 | }
|
---|
1007 | }
|
---|
1008 |
|
---|
1009 | void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
|
---|
1010 | PassVisitor<ArrayLength> len;
|
---|
1011 | acceptAll( translationUnit, len );
|
---|
1012 | }
|
---|
1013 |
|
---|
1014 | void ArrayLength::previsit( ObjectDecl * objDecl ) {
|
---|
1015 | if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
|
---|
1016 | if ( at->get_dimension() ) return;
|
---|
1017 | if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->get_init() ) ) {
|
---|
1018 | at->set_dimension( new ConstantExpr( Constant::from_ulong( init->get_initializers().size() ) ) );
|
---|
1019 | }
|
---|
1020 | }
|
---|
1021 | }
|
---|
1022 |
|
---|
1023 | struct LabelFinder {
|
---|
1024 | std::set< Label > & labels;
|
---|
1025 | LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
|
---|
1026 | void previsit( Statement * stmt ) {
|
---|
1027 | for ( Label & l : stmt->labels ) {
|
---|
1028 | labels.insert( l );
|
---|
1029 | }
|
---|
1030 | }
|
---|
1031 | };
|
---|
1032 |
|
---|
1033 | void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
|
---|
1034 | GuardValue( labels );
|
---|
1035 | PassVisitor<LabelFinder> finder( labels );
|
---|
1036 | funcDecl->accept( finder );
|
---|
1037 | }
|
---|
1038 |
|
---|
1039 | Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
|
---|
1040 | // convert &&label into label address
|
---|
1041 | if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
|
---|
1042 | if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
|
---|
1043 | if ( labels.count( nameExpr->name ) ) {
|
---|
1044 | Label name = nameExpr->name;
|
---|
1045 | delete addrExpr;
|
---|
1046 | return new LabelAddressExpr( name );
|
---|
1047 | }
|
---|
1048 | }
|
---|
1049 | }
|
---|
1050 | return addrExpr;
|
---|
1051 | }
|
---|
1052 |
|
---|
1053 | void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
|
---|
1054 | if ( ! dereferenceOperator ) {
|
---|
1055 | if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
|
---|
1056 | FunctionType * ftype = funcDecl->get_functionType();
|
---|
1057 | if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
|
---|
1058 | dereferenceOperator = funcDecl;
|
---|
1059 | }
|
---|
1060 | }
|
---|
1061 | }
|
---|
1062 | }
|
---|
1063 | } // namespace SymTab
|
---|
1064 |
|
---|
1065 | // Local Variables: //
|
---|
1066 | // tab-width: 4 //
|
---|
1067 | // mode: c++ //
|
---|
1068 | // compile-command: "make install" //
|
---|
1069 | // End: //
|
---|