source: src/InitTweak/InitTweak.cc@ 4dba1da

ADT ast-experimental pthread-emulation
Last change on this file since 4dba1da was ed9a1ae, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Cfa now distinguishes between thread and _Thread_local.

  • Property mode set to 100644
File size: 47.0 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// InitTweak.cc --
8//
9// Author : Rob Schluntz
10// Created On : Fri May 13 11:26:36 2016
11// Last Modified By : Andrew Beach
12// Last Modified On : Mon Dec 6 13:21:00 2021
13// Update Count : 20
14//
15
16#include <algorithm> // for find, all_of
17#include <cassert> // for assertf, assert, strict_dynamic_cast
18#include <iostream> // for ostream, cerr, endl
19#include <iterator> // for back_insert_iterator, back_inserter
20#include <memory> // for __shared_ptr
21#include <vector>
22
23#include "AST/Expr.hpp"
24#include "AST/Init.hpp"
25#include "AST/Node.hpp"
26#include "AST/Pass.hpp"
27#include "AST/Stmt.hpp"
28#include "AST/Type.hpp"
29#include "CodeGen/OperatorTable.h" // for isConstructor, isDestructor, isCto...
30#include "Common/PassVisitor.h"
31#include "Common/SemanticError.h" // for SemanticError
32#include "Common/UniqueName.h" // for UniqueName
33#include "Common/utility.h" // for toString, deleteAll, maybeClone
34#include "GenPoly/GenPoly.h" // for getFunctionType
35#include "InitTweak.h"
36#include "ResolvExpr/typeops.h" // for typesCompatibleIgnoreQualifiers
37#include "SymTab/Autogen.h"
38#include "SymTab/Indexer.h" // for Indexer
39#include "SynTree/LinkageSpec.h" // for Spec, isBuiltin, Intrinsic
40#include "SynTree/Attribute.h" // for Attribute
41#include "SynTree/Constant.h" // for Constant
42#include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType
43#include "SynTree/Expression.h" // for Expression, UntypedExpr, Applicati...
44#include "SynTree/Initializer.h" // for Initializer, ListInit, Designation
45#include "SynTree/Label.h" // for Label
46#include "SynTree/Statement.h" // for CompoundStmt, ExprStmt, BranchStmt
47#include "SynTree/Type.h" // for FunctionType, ArrayType, PointerType
48#include "SynTree/Visitor.h" // for Visitor, maybeAccept
49#include "Tuples/Tuples.h" // for Tuples::isTtype
50
51namespace InitTweak {
52 namespace {
53 struct HasDesignations : public WithShortCircuiting {
54 bool hasDesignations = false;
55
56 void previsit( BaseSyntaxNode * ) {
57 // short circuit if we already know there are designations
58 if ( hasDesignations ) visit_children = false;
59 }
60
61 void previsit( Designation * des ) {
62 // short circuit if we already know there are designations
63 if ( hasDesignations ) visit_children = false;
64 else if ( ! des->get_designators().empty() ) {
65 hasDesignations = true;
66 visit_children = false;
67 }
68 }
69 };
70
71 struct InitDepthChecker : public WithGuards {
72 bool depthOkay = true;
73 Type * type;
74 int curDepth = 0, maxDepth = 0;
75 InitDepthChecker( Type * type ) : type( type ) {
76 Type * t = type;
77 while ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
78 maxDepth++;
79 t = at->get_base();
80 }
81 maxDepth++;
82 }
83 void previsit( ListInit * ) {
84 curDepth++;
85 GuardAction( [this]() { curDepth--; } );
86 if ( curDepth > maxDepth ) depthOkay = false;
87 }
88 };
89
90 struct HasDesignations_new : public ast::WithShortCircuiting {
91 bool result = false;
92
93 void previsit( const ast::Node * ) {
94 // short circuit if we already know there are designations
95 if ( result ) visit_children = false;
96 }
97
98 void previsit( const ast::Designation * des ) {
99 // short circuit if we already know there are designations
100 if ( result ) visit_children = false;
101 else if ( ! des->designators.empty() ) {
102 result = true;
103 visit_children = false;
104 }
105 }
106 };
107
108 struct InitDepthChecker_new : public ast::WithGuards {
109 bool result = true;
110 const ast::Type * type;
111 int curDepth = 0, maxDepth = 0;
112 InitDepthChecker_new( const ast::Type * type ) : type( type ) {
113 const ast::Type * t = type;
114 while ( auto at = dynamic_cast< const ast::ArrayType * >( t ) ) {
115 maxDepth++;
116 t = at->base;
117 }
118 maxDepth++;
119 }
120 void previsit( ListInit * ) {
121 curDepth++;
122 GuardAction( [this]() { curDepth--; } );
123 if ( curDepth > maxDepth ) result = false;
124 }
125 };
126
127 struct InitFlattener_old : public WithShortCircuiting {
128 void previsit( SingleInit * singleInit ) {
129 visit_children = false;
130 argList.push_back( singleInit->value->clone() );
131 }
132 std::list< Expression * > argList;
133 };
134
135 struct InitFlattener_new : public ast::WithShortCircuiting {
136 std::vector< ast::ptr< ast::Expr > > argList;
137
138 void previsit( const ast::SingleInit * singleInit ) {
139 visit_children = false;
140 argList.emplace_back( singleInit->value );
141 }
142 };
143
144 } // anonymous namespace
145
146 std::list< Expression * > makeInitList( Initializer * init ) {
147 PassVisitor<InitFlattener_old> flattener;
148 maybeAccept( init, flattener );
149 return flattener.pass.argList;
150 }
151
152 bool isDesignated( Initializer * init ) {
153 PassVisitor<HasDesignations> finder;
154 maybeAccept( init, finder );
155 return finder.pass.hasDesignations;
156 }
157
158 bool checkInitDepth( ObjectDecl * objDecl ) {
159 PassVisitor<InitDepthChecker> checker( objDecl->type );
160 maybeAccept( objDecl->init, checker );
161 return checker.pass.depthOkay;
162 }
163
164 bool isDesignated( const ast::Init * init ) {
165 ast::Pass<HasDesignations_new> finder;
166 maybe_accept( init, finder );
167 return finder.core.result;
168 }
169
170 bool checkInitDepth( const ast::ObjectDecl * objDecl ) {
171 ast::Pass<InitDepthChecker_new> checker( objDecl->type );
172 maybe_accept( objDecl->init.get(), checker );
173 return checker.core.result;
174 }
175
176std::vector< ast::ptr< ast::Expr > > makeInitList( const ast::Init * init ) {
177 ast::Pass< InitFlattener_new > flattener;
178 maybe_accept( init, flattener );
179 return std::move( flattener.core.argList );
180}
181
182 class InitExpander_old::ExpanderImpl {
183 public:
184 virtual ~ExpanderImpl() = default;
185 virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
186 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
187 };
188
189 class InitImpl_old : public InitExpander_old::ExpanderImpl {
190 public:
191 InitImpl_old( Initializer * init ) : init( init ) {}
192 virtual ~InitImpl_old() = default;
193
194 virtual std::list< Expression * > next( __attribute((unused)) std::list< Expression * > & indices ) {
195 // this is wrong, but just a placeholder for now
196 // if ( ! flattened ) flatten( indices );
197 // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
198 return makeInitList( init );
199 }
200
201 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
202 private:
203 Initializer * init;
204 };
205
206 class ExprImpl_old : public InitExpander_old::ExpanderImpl {
207 public:
208 ExprImpl_old( Expression * expr ) : arg( expr ) {}
209 virtual ~ExprImpl_old() { delete arg; }
210
211 virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
212 std::list< Expression * > ret;
213 Expression * expr = maybeClone( arg );
214 if ( expr ) {
215 for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
216 // go through indices and layer on subscript exprs ?[?]
217 ++it;
218 UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
219 subscriptExpr->get_args().push_back( expr );
220 subscriptExpr->get_args().push_back( (*it)->clone() );
221 expr = subscriptExpr;
222 }
223 ret.push_back( expr );
224 }
225 return ret;
226 }
227
228 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
229 private:
230 Expression * arg;
231 };
232
233 InitExpander_old::InitExpander_old( Initializer * init ) : expander( new InitImpl_old( init ) ) {}
234
235 InitExpander_old::InitExpander_old( Expression * expr ) : expander( new ExprImpl_old( expr ) ) {}
236
237 std::list< Expression * > InitExpander_old::operator*() {
238 return cur;
239 }
240
241 InitExpander_old & InitExpander_old::operator++() {
242 cur = expander->next( indices );
243 return *this;
244 }
245
246 // use array indices list to build switch statement
247 void InitExpander_old::addArrayIndex( Expression * index, Expression * dimension ) {
248 indices.push_back( index );
249 indices.push_back( dimension );
250 }
251
252 void InitExpander_old::clearArrayIndices() {
253 deleteAll( indices );
254 indices.clear();
255 }
256
257 bool InitExpander_old::addReference() {
258 bool added = false;
259 for ( Expression *& expr : cur ) {
260 expr = new AddressExpr( expr );
261 added = true;
262 }
263 return added;
264 }
265
266 namespace {
267 /// given index i, dimension d, initializer init, and callExpr f, generates
268 /// if (i < d) f(..., init)
269 /// ++i;
270 /// so that only elements within the range of the array are constructed
271 template< typename OutIterator >
272 void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
273 UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
274 cond->get_args().push_back( index->clone() );
275 cond->get_args().push_back( dimension->clone() );
276
277 std::list< Expression * > args = makeInitList( init );
278 callExpr->get_args().splice( callExpr->get_args().end(), args );
279
280 *out++ = new IfStmt( cond, new ExprStmt( callExpr ), nullptr );
281
282 UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
283 increment->get_args().push_back( index->clone() );
284 *out++ = new ExprStmt( increment );
285 }
286
287 template< typename OutIterator >
288 void build( UntypedExpr * callExpr, InitExpander_old::IndexList::iterator idx, InitExpander_old::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
289 if ( idx == idxEnd ) return;
290 Expression * index = *idx++;
291 assert( idx != idxEnd );
292 Expression * dimension = *idx++;
293
294 // xxx - may want to eventually issue a warning here if we can detect
295 // that the number of elements exceeds to dimension of the array
296 if ( idx == idxEnd ) {
297 if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
298 for ( Initializer * init : *listInit ) {
299 buildCallExpr( callExpr->clone(), index, dimension, init, out );
300 }
301 } else {
302 buildCallExpr( callExpr->clone(), index, dimension, init, out );
303 }
304 } else {
305 std::list< Statement * > branches;
306
307 unsigned long cond = 0;
308 ListInit * listInit = dynamic_cast< ListInit * >( init );
309 if ( ! listInit ) {
310 // xxx - this shouldn't be an error, but need a way to
311 // terminate without creating output, so should catch this error
312 SemanticError( init->location, "unbalanced list initializers" );
313 }
314
315 static UniqueName targetLabel( "L__autogen__" );
316 Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
317 for ( Initializer * init : *listInit ) {
318 Expression * condition;
319 // check for designations
320 // if ( init-> ) {
321 condition = new ConstantExpr( Constant::from_ulong( cond ) );
322 ++cond;
323 // } else {
324 // condition = // ... take designation
325 // cond = // ... take designation+1
326 // }
327 std::list< Statement * > stmts;
328 build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
329 stmts.push_back( new BranchStmt( switchLabel, BranchStmt::Break ) );
330 CaseStmt * caseStmt = new CaseStmt( condition, stmts );
331 branches.push_back( caseStmt );
332 }
333 *out++ = new SwitchStmt( index->clone(), branches );
334 *out++ = new NullStmt( { switchLabel } );
335 }
336 }
337 }
338
339 // if array came with an initializer list: initialize each element
340 // may have more initializers than elements in the array - need to check at each index that
341 // we haven't exceeded size.
342 // may have fewer initializers than elements in the array - need to default construct
343 // remaining elements.
344 // To accomplish this, generate switch statement, consuming all of expander's elements
345 Statement * InitImpl_old::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
346 if ( ! init ) return nullptr;
347 CompoundStmt * block = new CompoundStmt();
348 build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
349 if ( block->get_kids().empty() ) {
350 delete block;
351 return nullptr;
352 } else {
353 init = nullptr; // init was consumed in creating the list init
354 return block;
355 }
356 }
357
358 Statement * ExprImpl_old::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
359 return nullptr;
360 }
361
362 Statement * InitExpander_old::buildListInit( UntypedExpr * dst ) {
363 return expander->buildListInit( dst, indices );
364 }
365
366class InitExpander_new::ExpanderImpl {
367public:
368 virtual ~ExpanderImpl() = default;
369 virtual std::vector< ast::ptr< ast::Expr > > next( IndexList & indices ) = 0;
370 virtual ast::ptr< ast::Stmt > buildListInit(
371 ast::UntypedExpr * callExpr, IndexList & indices ) = 0;
372};
373
374namespace {
375 template< typename Out >
376 void buildCallExpr(
377 ast::UntypedExpr * callExpr, const ast::Expr * index, const ast::Expr * dimension,
378 const ast::Init * init, Out & out
379 ) {
380 const CodeLocation & loc = init->location;
381
382 auto cond = new ast::UntypedExpr{
383 loc, new ast::NameExpr{ loc, "?<?" }, { index, dimension } };
384
385 std::vector< ast::ptr< ast::Expr > > args = makeInitList( init );
386 splice( callExpr->args, args );
387
388 out.emplace_back( new ast::IfStmt{ loc, cond, new ast::ExprStmt{ loc, callExpr } } );
389
390 out.emplace_back( new ast::ExprStmt{
391 loc, new ast::UntypedExpr{ loc, new ast::NameExpr{ loc, "++?" }, { index } } } );
392 }
393
394 template< typename Out >
395 void build(
396 ast::UntypedExpr * callExpr, const InitExpander_new::IndexList & indices,
397 const ast::Init * init, Out & out
398 ) {
399 if ( indices.empty() ) return;
400
401 unsigned idx = 0;
402
403 const ast::Expr * index = indices[idx++];
404 assert( idx != indices.size() );
405 const ast::Expr * dimension = indices[idx++];
406
407 if ( idx == indices.size() ) {
408 if ( auto listInit = dynamic_cast< const ast::ListInit * >( init ) ) {
409 for ( const ast::Init * init : *listInit ) {
410 buildCallExpr( shallowCopy(callExpr), index, dimension, init, out );
411 }
412 } else {
413 buildCallExpr( shallowCopy(callExpr), index, dimension, init, out );
414 }
415 } else {
416 const CodeLocation & loc = init->location;
417
418 unsigned long cond = 0;
419 auto listInit = dynamic_cast< const ast::ListInit * >( init );
420 if ( ! listInit ) { SemanticError( loc, "unbalanced list initializers" ); }
421
422 static UniqueName targetLabel( "L__autogen__" );
423 ast::Label switchLabel{
424 loc, targetLabel.newName(), { new ast::Attribute{ "unused" } } };
425
426 std::vector< ast::ptr< ast::CaseClause > > branches;
427 for ( const ast::Init * init : *listInit ) {
428 auto condition = ast::ConstantExpr::from_ulong( loc, cond );
429 ++cond;
430
431 std::vector< ast::ptr< ast::Stmt > > stmts;
432 build( callExpr, indices, init, stmts );
433 stmts.emplace_back(
434 new ast::BranchStmt{ loc, ast::BranchStmt::Break, switchLabel } );
435 branches.emplace_back( new ast::CaseClause{ loc, condition, std::move( stmts ) } );
436 }
437 out.emplace_back( new ast::SwitchStmt{ loc, index, std::move( branches ) } );
438 out.emplace_back( new ast::NullStmt{ loc, { switchLabel } } );
439 }
440 }
441
442 class InitImpl_new final : public InitExpander_new::ExpanderImpl {
443 ast::ptr< ast::Init > init;
444 public:
445 InitImpl_new( const ast::Init * i ) : init( i ) {}
446
447 std::vector< ast::ptr< ast::Expr > > next( InitExpander_new::IndexList & ) override {
448 return makeInitList( init );
449 }
450
451 ast::ptr< ast::Stmt > buildListInit(
452 ast::UntypedExpr * callExpr, InitExpander_new::IndexList & indices
453 ) override {
454 // If array came with an initializer list, initialize each element. We may have more
455 // initializers than elements of the array; need to check at each index that we have
456 // not exceeded size. We may have fewer initializers than elements in the array; need
457 // to default-construct remaining elements. To accomplish this, generate switch
458 // statement consuming all of expander's elements
459
460 if ( ! init ) return {};
461
462 std::list< ast::ptr< ast::Stmt > > stmts;
463 build( callExpr, indices, init, stmts );
464 if ( stmts.empty() ) {
465 return {};
466 } else {
467 auto block = new ast::CompoundStmt{ init->location, std::move( stmts ) };
468 init = nullptr; // consumed in creating the list init
469 return block;
470 }
471 }
472 };
473
474 class ExprImpl_new final : public InitExpander_new::ExpanderImpl {
475 ast::ptr< ast::Expr > arg;
476 public:
477 ExprImpl_new( const ast::Expr * a ) : arg( a ) {}
478
479 std::vector< ast::ptr< ast::Expr > > next(
480 InitExpander_new::IndexList & indices
481 ) override {
482 if ( ! arg ) return {};
483
484 const CodeLocation & loc = arg->location;
485 const ast::Expr * expr = arg;
486 for ( auto it = indices.rbegin(); it != indices.rend(); ++it ) {
487 // go through indices and layer on subscript exprs ?[?]
488 ++it;
489 expr = new ast::UntypedExpr{
490 loc, new ast::NameExpr{ loc, "?[?]" }, { expr, *it } };
491 }
492 return { expr };
493 }
494
495 ast::ptr< ast::Stmt > buildListInit(
496 ast::UntypedExpr *, InitExpander_new::IndexList &
497 ) override {
498 return {};
499 }
500 };
501} // anonymous namespace
502
503InitExpander_new::InitExpander_new( const ast::Init * init )
504: expander( new InitImpl_new{ init } ), crnt(), indices() {}
505
506InitExpander_new::InitExpander_new( const ast::Expr * expr )
507: expander( new ExprImpl_new{ expr } ), crnt(), indices() {}
508
509std::vector< ast::ptr< ast::Expr > > InitExpander_new::operator* () { return crnt; }
510
511InitExpander_new & InitExpander_new::operator++ () {
512 crnt = expander->next( indices );
513 return *this;
514}
515
516/// builds statement which has the same semantics as a C-style list initializer (for array
517/// initializers) using callExpr as the base expression to perform initialization
518ast::ptr< ast::Stmt > InitExpander_new::buildListInit( ast::UntypedExpr * callExpr ) {
519 return expander->buildListInit( callExpr, indices );
520}
521
522void InitExpander_new::addArrayIndex( const ast::Expr * index, const ast::Expr * dimension ) {
523 indices.emplace_back( index );
524 indices.emplace_back( dimension );
525}
526
527void InitExpander_new::clearArrayIndices() { indices.clear(); }
528
529bool InitExpander_new::addReference() {
530 for ( ast::ptr< ast::Expr > & expr : crnt ) {
531 expr = new ast::AddressExpr{ expr };
532 }
533 return ! crnt.empty();
534}
535
536 Type * getTypeofThis( FunctionType * ftype ) {
537 assertf( ftype, "getTypeofThis: nullptr ftype" );
538 ObjectDecl * thisParam = getParamThis( ftype );
539 ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
540 return refType->base;
541 }
542
543 const ast::Type * getTypeofThis( const ast::FunctionType * ftype ) {
544 assertf( ftype, "getTypeofThis: nullptr ftype" );
545 const std::vector<ast::ptr<ast::Type>> & params = ftype->params;
546 assertf( !params.empty(), "getTypeofThis: ftype with 0 parameters: %s",
547 toString( ftype ).c_str() );
548 const ast::ReferenceType * refType =
549 params.front().strict_as<ast::ReferenceType>();
550 return refType->base;
551 }
552
553 ObjectDecl * getParamThis( FunctionType * ftype ) {
554 assertf( ftype, "getParamThis: nullptr ftype" );
555 auto & params = ftype->parameters;
556 assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
557 return strict_dynamic_cast< ObjectDecl * >( params.front() );
558 }
559
560 const ast::ObjectDecl * getParamThis(const ast::FunctionDecl * func) {
561 assertf( func, "getParamThis: nullptr ftype" );
562 auto & params = func->params;
563 assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( func ).c_str());
564 return params.front().strict_as<ast::ObjectDecl>();
565 }
566
567 bool tryConstruct( DeclarationWithType * dwt ) {
568 ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
569 if ( ! objDecl ) return false;
570 return (objDecl->get_init() == nullptr ||
571 ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
572 && ! objDecl->get_storageClasses().is_extern
573 && isConstructable( objDecl->type );
574 }
575
576 bool isConstructable( Type * type ) {
577 return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
578 }
579
580 bool tryConstruct( const ast::DeclWithType * dwt ) {
581 auto objDecl = dynamic_cast< const ast::ObjectDecl * >( dwt );
582 if ( ! objDecl ) return false;
583 return (objDecl->init == nullptr ||
584 ( objDecl->init != nullptr && objDecl->init->maybeConstructed ))
585 && ! objDecl->storage.is_extern
586 && isConstructable( objDecl->type );
587 }
588
589 bool isConstructable( const ast::Type * type ) {
590 return ! dynamic_cast< const ast::VarArgsType * >( type ) && ! dynamic_cast< const ast::ReferenceType * >( type )
591 && ! dynamic_cast< const ast::FunctionType * >( type ) && ! Tuples::isTtype( type );
592 }
593
594 struct CallFinder_old {
595 CallFinder_old( const std::list< std::string > & names ) : names( names ) {}
596
597 void postvisit( ApplicationExpr * appExpr ) {
598 handleCallExpr( appExpr );
599 }
600
601 void postvisit( UntypedExpr * untypedExpr ) {
602 handleCallExpr( untypedExpr );
603 }
604
605 std::list< Expression * > * matches;
606 private:
607 const std::list< std::string > names;
608
609 template< typename CallExpr >
610 void handleCallExpr( CallExpr * expr ) {
611 std::string fname = getFunctionName( expr );
612 if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
613 matches->push_back( expr );
614 }
615 }
616 };
617
618 struct CallFinder_new final {
619 std::vector< const ast::Expr * > matches;
620 const std::vector< std::string > names;
621
622 CallFinder_new( std::vector< std::string > && ns ) : matches(), names( std::move(ns) ) {}
623
624 void handleCallExpr( const ast::Expr * expr ) {
625 std::string fname = getFunctionName( expr );
626 if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
627 matches.emplace_back( expr );
628 }
629 }
630
631 void postvisit( const ast::ApplicationExpr * expr ) { handleCallExpr( expr ); }
632 void postvisit( const ast::UntypedExpr * expr ) { handleCallExpr( expr ); }
633 };
634
635 void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
636 static PassVisitor<CallFinder_old> finder( std::list< std::string >{ "?{}", "^?{}" } );
637 finder.pass.matches = &matches;
638 maybeAccept( stmt, finder );
639 }
640
641 std::vector< const ast::Expr * > collectCtorDtorCalls( const ast::Stmt * stmt ) {
642 ast::Pass< CallFinder_new > finder{ std::vector< std::string >{ "?{}", "^?{}" } };
643 maybe_accept( stmt, finder );
644 return std::move( finder.core.matches );
645 }
646
647 Expression * getCtorDtorCall( Statement * stmt ) {
648 std::list< Expression * > matches;
649 collectCtorDtorCalls( stmt, matches );
650 assertf( matches.size() <= 1, "%zd constructor/destructors found in %s", matches.size(), toString( stmt ).c_str() );
651 return matches.size() == 1 ? matches.front() : nullptr;
652 }
653
654 namespace {
655 DeclarationWithType * getCalledFunction( Expression * expr );
656 const ast::DeclWithType * getCalledFunction( const ast::Expr * expr );
657
658 template<typename CallExpr>
659 DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
660 // (*f)(x) => should get "f"
661 std::string name = getFunctionName( expr );
662 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
663 assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
664 return getCalledFunction( expr->get_args().front() );
665 }
666
667 template<typename CallExpr>
668 const ast::DeclWithType * handleDerefCalledFunction( const CallExpr * expr ) {
669 // (*f)(x) => should get "f"
670 std::string name = getFunctionName( expr );
671 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
672 assertf( ! expr->args.empty(), "Cannot get called function from dereference with no arguments" );
673 return getCalledFunction( expr->args.front() );
674 }
675
676
677 DeclarationWithType * getCalledFunction( Expression * expr ) {
678 assert( expr );
679 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
680 return varExpr->var;
681 } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
682 return memberExpr->member;
683 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
684 return getCalledFunction( castExpr->arg );
685 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
686 return handleDerefCalledFunction( untypedExpr );
687 } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
688 return handleDerefCalledFunction( appExpr );
689 } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
690 return getCalledFunction( addrExpr->arg );
691 } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
692 return getCalledFunction( commaExpr->arg2 );
693 }
694 return nullptr;
695 }
696
697 const ast::DeclWithType * getCalledFunction( const ast::Expr * expr ) {
698 assert( expr );
699 if ( const ast::VariableExpr * varExpr = dynamic_cast< const ast::VariableExpr * >( expr ) ) {
700 return varExpr->var;
701 } else if ( const ast::MemberExpr * memberExpr = dynamic_cast< const ast::MemberExpr * >( expr ) ) {
702 return memberExpr->member;
703 } else if ( const ast::CastExpr * castExpr = dynamic_cast< const ast::CastExpr * >( expr ) ) {
704 return getCalledFunction( castExpr->arg );
705 } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * >( expr ) ) {
706 return handleDerefCalledFunction( untypedExpr );
707 } else if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * > ( expr ) ) {
708 return handleDerefCalledFunction( appExpr );
709 } else if ( const ast::AddressExpr * addrExpr = dynamic_cast< const ast::AddressExpr * >( expr ) ) {
710 return getCalledFunction( addrExpr->arg );
711 } else if ( const ast::CommaExpr * commaExpr = dynamic_cast< const ast::CommaExpr * >( expr ) ) {
712 return getCalledFunction( commaExpr->arg2 );
713 }
714 return nullptr;
715 }
716
717 DeclarationWithType * getFunctionCore( const Expression * expr ) {
718 if ( const auto * appExpr = dynamic_cast< const ApplicationExpr * >( expr ) ) {
719 return getCalledFunction( appExpr->function );
720 } else if ( const auto * untyped = dynamic_cast< const UntypedExpr * >( expr ) ) {
721 return getCalledFunction( untyped->function );
722 }
723 assertf( false, "getFunction with unknown expression: %s", toString( expr ).c_str() );
724 }
725 }
726
727 DeclarationWithType * getFunction( Expression * expr ) {
728 return getFunctionCore( expr );
729 }
730
731 const DeclarationWithType * getFunction( const Expression * expr ) {
732 return getFunctionCore( expr );
733 }
734
735 const ast::DeclWithType * getFunction( const ast::Expr * expr ) {
736 if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr ) ) {
737 return getCalledFunction( appExpr->func );
738 } else if ( const ast::UntypedExpr * untyped = dynamic_cast< const ast::UntypedExpr * > ( expr ) ) {
739 return getCalledFunction( untyped->func );
740 }
741 assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
742 }
743
744 ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
745 ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
746 if ( ! appExpr ) return nullptr;
747 DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
748 assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
749 // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
750 // will call all member dtors, and some members may have a user defined dtor.
751 return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
752 }
753
754 const ast::ApplicationExpr * isIntrinsicCallExpr( const ast::Expr * expr ) {
755 auto appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr );
756 if ( ! appExpr ) return nullptr;
757
758 const ast::DeclWithType * func = getCalledFunction( appExpr->func );
759 assertf( func,
760 "getCalledFunction returned nullptr: %s", toString( appExpr->func ).c_str() );
761
762 // check for Intrinsic only -- don't want to remove all overridable ctor/dtor because
763 // autogenerated ctor/dtor will call all member dtors, and some members may have a
764 // user-defined dtor
765 return func->linkage == ast::Linkage::Intrinsic ? appExpr : nullptr;
766 }
767
768 namespace {
769 template <typename Predicate>
770 bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
771 std::list< Expression * > callExprs;
772 collectCtorDtorCalls( stmt, callExprs );
773 return std::all_of( callExprs.begin(), callExprs.end(), pred);
774 }
775
776 template <typename Predicate>
777 bool allofCtorDtor( const ast::Stmt * stmt, const Predicate & pred ) {
778 std::vector< const ast::Expr * > callExprs = collectCtorDtorCalls( stmt );
779 return std::all_of( callExprs.begin(), callExprs.end(), pred );
780 }
781 }
782
783 bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
784 return allofCtorDtor( stmt, []( Expression * callExpr ){
785 if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
786 FunctionType *funcType = GenPoly::getFunctionType( appExpr->function->result );
787 assert( funcType );
788 return funcType->get_parameters().size() == 1;
789 }
790 return false;
791 });
792 }
793
794 bool isIntrinsicSingleArgCallStmt( const ast::Stmt * stmt ) {
795 return allofCtorDtor( stmt, []( const ast::Expr * callExpr ){
796 if ( const ast::ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
797 const ast::FunctionType * funcType =
798 GenPoly::getFunctionType( appExpr->func->result );
799 assert( funcType );
800 return funcType->params.size() == 1;
801 }
802 return false;
803 });
804 }
805
806 bool isIntrinsicCallStmt( Statement * stmt ) {
807 return allofCtorDtor( stmt, []( Expression * callExpr ) {
808 return isIntrinsicCallExpr( callExpr );
809 });
810 }
811
812 namespace {
813 template<typename CallExpr>
814 Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
815 if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
816 for ( Expression *& arg : callExpr->get_args() ) {
817 if ( pos == 0 ) return arg;
818 pos--;
819 }
820 assert( false );
821 }
822
823 template<typename CallExpr>
824 const ast::Expr * callArg( const CallExpr * call, unsigned int pos ) {
825 if( pos >= call->args.size() ) {
826 assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.",
827 pos, toString( call ).c_str() );
828 }
829 for ( const ast::Expr * arg : call->args ) {
830 if ( pos == 0 ) return arg;
831 --pos;
832 }
833 assert( false );
834 }
835 }
836
837 Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
838 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
839 return callArg( appExpr, pos );
840 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
841 return callArg( untypedExpr, pos );
842 } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
843 std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
844 assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
845 ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
846 TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
847 assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
848 return getCallArg( tuple->get_exprs().front(), pos );
849 } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
850 return getCallArg( copyCtor->callExpr, pos );
851 } else {
852 assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
853 }
854 }
855
856 const ast::Expr * getCallArg( const ast::Expr * call, unsigned pos ) {
857 if ( auto app = dynamic_cast< const ast::ApplicationExpr * >( call ) ) {
858 return callArg( app, pos );
859 } else if ( auto untyped = dynamic_cast< const ast::UntypedExpr * >( call ) ) {
860 return callArg( untyped, pos );
861 } else if ( auto tupleAssn = dynamic_cast< const ast::TupleAssignExpr * >( call ) ) {
862 const std::list<ast::ptr<ast::Stmt>>& stmts = tupleAssn->stmtExpr->stmts->kids;
863 assertf( ! stmts.empty(), "TupleAssignExpr missing statements." );
864 auto stmt = strict_dynamic_cast< const ast::ExprStmt * >( stmts.back().get() );
865 auto tuple = strict_dynamic_cast< const ast::TupleExpr * >( stmt->expr.get() );
866 assertf( ! tuple->exprs.empty(), "TupleAssignExpr has empty tuple expr.");
867 return getCallArg( tuple->exprs.front(), pos );
868 } else if ( auto ctor = dynamic_cast< const ast::ImplicitCopyCtorExpr * >( call ) ) {
869 return getCallArg( ctor->callExpr, pos );
870 } else {
871 assertf( false, "Unexpected expression type passed to getCallArg: %s",
872 toString( call ).c_str() );
873 }
874 }
875
876 namespace {
877 std::string funcName( Expression * func );
878 std::string funcName( const ast::Expr * func );
879
880 template<typename CallExpr>
881 std::string handleDerefName( CallExpr * expr ) {
882 // (*f)(x) => should get name "f"
883 std::string name = getFunctionName( expr );
884 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
885 assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
886 return funcName( expr->get_args().front() );
887 }
888
889 template<typename CallExpr>
890 std::string handleDerefName( const CallExpr * expr ) {
891 // (*f)(x) => should get name "f"
892 std::string name = getFunctionName( expr );
893 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
894 assertf( ! expr->args.empty(), "Cannot get function name from dereference with no arguments" );
895 return funcName( expr->args.front() );
896 }
897
898 std::string funcName( Expression * func ) {
899 if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
900 return nameExpr->get_name();
901 } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
902 return varExpr->get_var()->get_name();
903 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
904 return funcName( castExpr->get_arg() );
905 } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
906 return memberExpr->get_member()->get_name();
907 } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
908 return funcName( memberExpr->get_member() );
909 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
910 return handleDerefName( untypedExpr );
911 } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
912 return handleDerefName( appExpr );
913 } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
914 return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
915 } else {
916 assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
917 }
918 }
919
920 std::string funcName( const ast::Expr * func ) {
921 if ( const ast::NameExpr * nameExpr = dynamic_cast< const ast::NameExpr * >( func ) ) {
922 return nameExpr->name;
923 } else if ( const ast::VariableExpr * varExpr = dynamic_cast< const ast::VariableExpr * >( func ) ) {
924 return varExpr->var->name;
925 } else if ( const ast::CastExpr * castExpr = dynamic_cast< const ast::CastExpr * >( func ) ) {
926 return funcName( castExpr->arg );
927 } else if ( const ast::MemberExpr * memberExpr = dynamic_cast< const ast::MemberExpr * >( func ) ) {
928 return memberExpr->member->name;
929 } else if ( const ast::UntypedMemberExpr * memberExpr = dynamic_cast< const ast::UntypedMemberExpr * > ( func ) ) {
930 return funcName( memberExpr->member );
931 } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * >( func ) ) {
932 return handleDerefName( untypedExpr );
933 } else if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( func ) ) {
934 return handleDerefName( appExpr );
935 } else if ( const ast::ConstructorExpr * ctorExpr = dynamic_cast< const ast::ConstructorExpr * >( func ) ) {
936 return funcName( getCallArg( ctorExpr->callExpr, 0 ) );
937 } else {
938 assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
939 }
940 }
941 }
942
943 std::string getFunctionName( Expression * expr ) {
944 // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
945 // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
946 // can't possibly do anything reasonable.
947 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
948 return funcName( appExpr->get_function() );
949 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
950 return funcName( untypedExpr->get_function() );
951 } else {
952 std::cerr << expr << std::endl;
953 assertf( false, "Unexpected expression type passed to getFunctionName" );
954 }
955 }
956
957 std::string getFunctionName( const ast::Expr * expr ) {
958 // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
959 // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
960 // can't possibly do anything reasonable.
961 if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr ) ) {
962 return funcName( appExpr->func );
963 } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * > ( expr ) ) {
964 return funcName( untypedExpr->func );
965 } else {
966 std::cerr << expr << std::endl;
967 assertf( false, "Unexpected expression type passed to getFunctionName" );
968 }
969 }
970
971 Type * getPointerBase( Type * type ) {
972 if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
973 return ptrType->get_base();
974 } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
975 return arrayType->get_base();
976 } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
977 return refType->get_base();
978 } else {
979 return nullptr;
980 }
981 }
982 const ast::Type* getPointerBase( const ast::Type* t ) {
983 if ( const auto * p = dynamic_cast< const ast::PointerType * >( t ) ) {
984 return p->base;
985 } else if ( const auto * a = dynamic_cast< const ast::ArrayType * >( t ) ) {
986 return a->base;
987 } else if ( const auto * r = dynamic_cast< const ast::ReferenceType * >( t ) ) {
988 return r->base;
989 } else return nullptr;
990 }
991
992 Type * isPointerType( Type * type ) {
993 return getPointerBase( type ) ? type : nullptr;
994 }
995
996 ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src ) {
997 static FunctionDecl * assign = nullptr;
998 if ( ! assign ) {
999 // temporary? Generate a fake assignment operator to represent bitwise assignments.
1000 // This operator could easily exist as a real function, but it's tricky because nothing should resolve to this function.
1001 TypeDecl * td = new TypeDecl( "T", noStorageClasses, nullptr, TypeDecl::Dtype, true );
1002 assign = new FunctionDecl( "?=?", noStorageClasses, LinkageSpec::Intrinsic, SymTab::genAssignType( new TypeInstType( noQualifiers, td->name, td ) ), nullptr );
1003 }
1004 if ( dynamic_cast< ReferenceType * >( dst->result ) ) {
1005 for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
1006 dst = new AddressExpr( dst );
1007 }
1008 } else {
1009 dst = new CastExpr( dst, new ReferenceType( noQualifiers, dst->result->clone() ) );
1010 }
1011 if ( dynamic_cast< ReferenceType * >( src->result ) ) {
1012 for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
1013 src = new AddressExpr( src );
1014 }
1015 }
1016 return new ApplicationExpr( VariableExpr::functionPointer( assign ), { dst, src } );
1017 }
1018
1019 // looks like some other such codegen uses UntypedExpr and does not create fake function. should revisit afterwards
1020 // following passes may accidentally resolve this expression if returned as untyped...
1021 ast::Expr * createBitwiseAssignment (const ast::Expr * dst, const ast::Expr * src) {
1022 static ast::ptr<ast::FunctionDecl> assign = nullptr;
1023 if (!assign) {
1024 auto td = new ast::TypeDecl({}, "T", {}, nullptr, ast::TypeDecl::Dtype, true);
1025 assign = new ast::FunctionDecl({}, "?=?", {},
1026 { new ast::ObjectDecl({}, "_dst", new ast::ReferenceType(new ast::TypeInstType("T", td))),
1027 new ast::ObjectDecl({}, "_src", new ast::TypeInstType("T", td))},
1028 { new ast::ObjectDecl({}, "_ret", new ast::TypeInstType("T", td))}, nullptr, {}, ast::Linkage::Intrinsic);
1029 }
1030 if (dst->result.as<ast::ReferenceType>()) {
1031 for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
1032 dst = new ast::AddressExpr(dst);
1033 }
1034 }
1035 else {
1036 dst = new ast::CastExpr(dst, new ast::ReferenceType(dst->result, {}));
1037 }
1038 if (src->result.as<ast::ReferenceType>()) {
1039 for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
1040 src = new ast::AddressExpr(src);
1041 }
1042 }
1043 return new ast::ApplicationExpr(dst->location, ast::VariableExpr::functionPointer(dst->location, assign), {dst, src});
1044 }
1045
1046 struct ConstExprChecker : public WithShortCircuiting {
1047 // most expressions are not const expr
1048 void previsit( Expression * ) { isConstExpr = false; visit_children = false; }
1049
1050 void previsit( AddressExpr *addressExpr ) {
1051 visit_children = false;
1052
1053 // address of a variable or member expression is constexpr
1054 Expression * arg = addressExpr->get_arg();
1055 if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
1056 }
1057
1058 // these expressions may be const expr, depending on their children
1059 void previsit( SizeofExpr * ) {}
1060 void previsit( AlignofExpr * ) {}
1061 void previsit( UntypedOffsetofExpr * ) {}
1062 void previsit( OffsetofExpr * ) {}
1063 void previsit( OffsetPackExpr * ) {}
1064 void previsit( CommaExpr * ) {}
1065 void previsit( LogicalExpr * ) {}
1066 void previsit( ConditionalExpr * ) {}
1067 void previsit( CastExpr * ) {}
1068 void previsit( ConstantExpr * ) {}
1069
1070 void previsit( VariableExpr * varExpr ) {
1071 visit_children = false;
1072
1073 if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( varExpr->result ) ) {
1074 long long int value;
1075 if ( inst->baseEnum->valueOf( varExpr->var, value ) ) {
1076 // enumerators are const expr
1077 return;
1078 }
1079 }
1080 isConstExpr = false;
1081 }
1082
1083 bool isConstExpr = true;
1084 };
1085
1086 struct ConstExprChecker_new : public ast::WithShortCircuiting {
1087 // most expressions are not const expr
1088 void previsit( const ast::Expr * ) { result = false; visit_children = false; }
1089
1090 void previsit( const ast::AddressExpr *addressExpr ) {
1091 visit_children = false;
1092 const ast::Expr * arg = addressExpr->arg;
1093
1094 // address of a variable or member expression is constexpr
1095 if ( ! dynamic_cast< const ast::NameExpr * >( arg )
1096 && ! dynamic_cast< const ast::VariableExpr * >( arg )
1097 && ! dynamic_cast< const ast::MemberExpr * >( arg )
1098 && ! dynamic_cast< const ast::UntypedMemberExpr * >( arg ) ) result = false;
1099 }
1100
1101 // these expressions may be const expr, depending on their children
1102 void previsit( const ast::SizeofExpr * ) {}
1103 void previsit( const ast::AlignofExpr * ) {}
1104 void previsit( const ast::UntypedOffsetofExpr * ) {}
1105 void previsit( const ast::OffsetofExpr * ) {}
1106 void previsit( const ast::OffsetPackExpr * ) {}
1107 void previsit( const ast::CommaExpr * ) {}
1108 void previsit( const ast::LogicalExpr * ) {}
1109 void previsit( const ast::ConditionalExpr * ) {}
1110 void previsit( const ast::CastExpr * ) {}
1111 void previsit( const ast::ConstantExpr * ) {}
1112
1113 void previsit( const ast::VariableExpr * varExpr ) {
1114 visit_children = false;
1115
1116 if ( auto inst = varExpr->result.as<ast::EnumInstType>() ) {
1117 long long int value;
1118 if ( inst->base->valueOf( varExpr->var, value ) ) {
1119 // enumerators are const expr
1120 return;
1121 }
1122 }
1123 result = false;
1124 }
1125
1126 bool result = true;
1127 };
1128
1129 bool isConstExpr( Expression * expr ) {
1130 if ( expr ) {
1131 PassVisitor<ConstExprChecker> checker;
1132 expr->accept( checker );
1133 return checker.pass.isConstExpr;
1134 }
1135 return true;
1136 }
1137
1138 bool isConstExpr( Initializer * init ) {
1139 if ( init ) {
1140 PassVisitor<ConstExprChecker> checker;
1141 init->accept( checker );
1142 return checker.pass.isConstExpr;
1143 } // if
1144 // for all intents and purposes, no initializer means const expr
1145 return true;
1146 }
1147
1148 bool isConstExpr( const ast::Expr * expr ) {
1149 if ( expr ) {
1150 ast::Pass<ConstExprChecker_new> checker;
1151 expr->accept( checker );
1152 return checker.core.result;
1153 }
1154 return true;
1155 }
1156
1157 bool isConstExpr( const ast::Init * init ) {
1158 if ( init ) {
1159 ast::Pass<ConstExprChecker_new> checker;
1160 init->accept( checker );
1161 return checker.core.result;
1162 } // if
1163 // for all intents and purposes, no initializer means const expr
1164 return true;
1165 }
1166
1167 const FunctionDecl * isCopyFunction( const Declaration * decl, const std::string & fname ) {
1168 const FunctionDecl * function = dynamic_cast< const FunctionDecl * >( decl );
1169 if ( ! function ) return nullptr;
1170 if ( function->name != fname ) return nullptr;
1171 FunctionType * ftype = function->type;
1172 if ( ftype->parameters.size() != 2 ) return nullptr;
1173
1174 Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
1175 Type * t2 = ftype->parameters.back()->get_type();
1176 assert( t1 );
1177
1178 if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
1179 return function;
1180 } else {
1181 return nullptr;
1182 }
1183 }
1184
1185bool isAssignment( const ast::FunctionDecl * decl ) {
1186 return CodeGen::isAssignment( decl->name ) && isCopyFunction( decl );
1187}
1188
1189bool isDestructor( const ast::FunctionDecl * decl ) {
1190 return CodeGen::isDestructor( decl->name );
1191}
1192
1193bool isDefaultConstructor( const ast::FunctionDecl * decl ) {
1194 return CodeGen::isConstructor( decl->name ) && 1 == decl->params.size();
1195}
1196
1197bool isCopyConstructor( const ast::FunctionDecl * decl ) {
1198 return CodeGen::isConstructor( decl->name ) && 2 == decl->params.size();
1199}
1200
1201bool isCopyFunction( const ast::FunctionDecl * decl ) {
1202 const ast::FunctionType * ftype = decl->type;
1203 if ( ftype->params.size() != 2 ) return false;
1204
1205 const ast::Type * t1 = getPointerBase( ftype->params.front() );
1206 if ( ! t1 ) return false;
1207 const ast::Type * t2 = ftype->params.back();
1208
1209 return ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, ast::SymbolTable{} );
1210}
1211
1212 const FunctionDecl * isAssignment( const Declaration * decl ) {
1213 return isCopyFunction( decl, "?=?" );
1214 }
1215 const FunctionDecl * isDestructor( const Declaration * decl ) {
1216 if ( CodeGen::isDestructor( decl->name ) ) {
1217 return dynamic_cast< const FunctionDecl * >( decl );
1218 }
1219 return nullptr;
1220 }
1221 const FunctionDecl * isDefaultConstructor( const Declaration * decl ) {
1222 if ( CodeGen::isConstructor( decl->name ) ) {
1223 if ( const FunctionDecl * func = dynamic_cast< const FunctionDecl * >( decl ) ) {
1224 if ( func->type->parameters.size() == 1 ) {
1225 return func;
1226 }
1227 }
1228 }
1229 return nullptr;
1230 }
1231 const FunctionDecl * isCopyConstructor( const Declaration * decl ) {
1232 return isCopyFunction( decl, "?{}" );
1233 }
1234
1235 #if defined( __x86_64 ) || defined( __i386 ) // assembler comment to prevent assembler warning message
1236 #define ASM_COMMENT "#"
1237 #else // defined( __ARM_ARCH )
1238 #define ASM_COMMENT "//"
1239 #endif
1240 static const char * const data_section = ".data" ASM_COMMENT;
1241 static const char * const tlsd_section = ".tdata" ASM_COMMENT;
1242 void addDataSectionAttribute( ObjectDecl * objDecl ) {
1243 const bool is_tls = objDecl->get_storageClasses().is_threadlocal_any();
1244 const char * section = is_tls ? tlsd_section : data_section;
1245 objDecl->attributes.push_back(new Attribute("section", {
1246 new ConstantExpr( Constant::from_string( section ) )
1247 }));
1248 }
1249
1250 void addDataSectionAttribute( ast::ObjectDecl * objDecl ) {
1251 const bool is_tls = objDecl->storage.is_threadlocal_any();
1252 const char * section = is_tls ? tlsd_section : data_section;
1253 objDecl->attributes.push_back(new ast::Attribute("section", {
1254 ast::ConstantExpr::from_string(objDecl->location, section)
1255 }));
1256 }
1257
1258}
Note: See TracBrowser for help on using the repository browser.