// // Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo // // The contents of this file are covered under the licence agreement in the // file "LICENCE" distributed with Cforall. // // Expr.cpp -- // // Author : Aaron B. Moss // Created On : Wed May 15 17:00:00 2019 // Last Modified By : Peter A. Buhr // Created On : Thr Jun 13 13:38:00 2019 // Update Count : 6 // #include "Expr.hpp" #include // for strict_dynamic_cast #include // for to_string #include #include "Copy.hpp" // for shallowCopy #include "Eval.hpp" // for call #include "GenericSubstitution.hpp" #include "LinkageSpec.hpp" #include "Stmt.hpp" #include "Type.hpp" #include "TypeSubstitution.hpp" #include "Common/utility.h" #include "Common/SemanticError.h" #include "GenPoly/Lvalue.h" // for referencesPermissable #include "InitTweak/InitTweak.h" // for getFunction, getPointerBase #include "ResolvExpr/typeops.h" // for extractResultType #include "Tuples/Tuples.h" // for makeTupleType namespace ast { namespace { std::set const lvalueFunctionNames = {"*?", "?[?]"}; } // --- Expr bool Expr::get_lvalue() const { return false; } // --- ApplicationExpr ApplicationExpr::ApplicationExpr( const CodeLocation & loc, const Expr * f, std::vector> && as ) : Expr( loc ), func( f ), args( std::move(as) ) { // ensure that `ApplicationExpr` result type is `FuncExpr` const PointerType * pt = strict_dynamic_cast< const PointerType * >( f->result.get() ); const FunctionType * fn = strict_dynamic_cast< const FunctionType * >( pt->base.get() ); result = ResolvExpr::extractResultType( fn ); assert( result ); } bool ApplicationExpr::get_lvalue() const { if ( const DeclWithType * func = InitTweak::getFunction( this ) ) { return func->linkage == Linkage::Intrinsic && lvalueFunctionNames.count( func->name ); } return false; } // --- UntypedExpr UntypedExpr * UntypedExpr::createDeref( const CodeLocation & loc, const Expr * arg ) { assert( arg ); UntypedExpr * ret = call( loc, "*?", arg ); if ( const Type * ty = arg->result ) { const Type * base = InitTweak::getPointerBase( ty ); assertf( base, "expected pointer type in dereference (type was %s)", toString( ty ).c_str() ); if ( GenPoly::referencesPermissable() ) { // if references are still allowed in the AST, dereference returns a reference ret->result = new ReferenceType{ base }; } else { // references have been removed, in which case dereference returns an lvalue of the // base type ret->result = base; } } return ret; } bool UntypedExpr::get_lvalue() const { std::string fname = InitTweak::getFunctionName( this ); return lvalueFunctionNames.count( fname ); } UntypedExpr * UntypedExpr::createAssign( const CodeLocation & loc, const Expr * lhs, const Expr * rhs ) { assert( lhs && rhs ); UntypedExpr * ret = call( loc, "?=?", lhs, rhs ); if ( lhs->result && rhs->result ) { // if both expressions are typed, assumes that this assignment is a C bitwise assignment, // so the result is the type of the RHS ret->result = rhs->result; } return ret; } // --- AddressExpr // Address expressions are typed based on the following inference rules: // E : lvalue T &..& (n references) // &E : T *&..& (n references) // // E : T &..& (m references) // &E : T *&..& (m-1 references) namespace { /// The type of the address of a type. /// Caller is responsible for managing returned memory Type * addrType( const Type * type ) { if ( const ReferenceType * refType = dynamic_cast< const ReferenceType * >( type ) ) { return new ReferenceType{ addrType( refType->base ), refType->qualifiers }; } else { return new PointerType{ type }; } } } AddressExpr::AddressExpr( const CodeLocation & loc, const Expr * a ) : Expr( loc ), arg( a ) { if ( arg->result ) { if ( arg->get_lvalue() ) { // lvalue, retains all levels of reference, and gains a pointer inside the references Type * res = addrType( arg->result ); result = res; } else { // taking address of non-lvalue, must be a reference, loses one layer of reference if ( const ReferenceType * refType = dynamic_cast< const ReferenceType * >( arg->result.get() ) ) { Type * res = addrType( refType->base ); result = res; } else { SemanticError( loc, arg->result.get(), "Attempt to take address of non-lvalue expression: " ); } } } } // --- LabelAddressExpr // label address always has type `void*` LabelAddressExpr::LabelAddressExpr( const CodeLocation & loc, Label && a ) : Expr( loc, new PointerType{ new VoidType{} } ), arg( a ) {} // --- CastExpr CastExpr::CastExpr( const CodeLocation & loc, const Expr * a, GeneratedFlag g ) : Expr( loc, new VoidType{} ), arg( a ), isGenerated( g ) {} bool CastExpr::get_lvalue() const { // This is actually wrong by C, but it works with our current set-up. return arg->get_lvalue(); } // --- KeywordCastExpr const char * KeywordCastExpr::targetString() const { return AggregateDecl::aggrString( target ); } // --- UntypedMemberExpr bool UntypedMemberExpr::get_lvalue() const { return aggregate->get_lvalue(); } // --- MemberExpr MemberExpr::MemberExpr( const CodeLocation & loc, const DeclWithType * mem, const Expr * agg ) : Expr( loc ), member( mem ), aggregate( agg ) { assert( member ); assert( aggregate ); assert( aggregate->result ); // Deep copy on result type avoids mutation on transitively multiply referenced object. // // Example, adapted from parts of builtins and bootloader: // // forall(dtype T) // struct __Destructor { // T * object; // void (*dtor)(T *); // }; // // forall(dtype S) // void foo(__Destructor(S) &d) { // if (d.dtor) { // here // } // } // // Let e be the "d.dtor" guard espression, which is MemberExpr after resolve. Let d be the // declaration of member __Destructor.dtor (an ObjectDecl), as accessed via the top-level // declaration of __Destructor. Consider the types e.result and d.type. In the old AST, one // is a clone of the other. Ordinary new-AST use would set them up as a multiply-referenced // object. // // e.result: PointerType // .base: FunctionType // .params.front(): ObjectDecl, the anonymous parameter of type T* // .type: PointerType // .base: TypeInstType // let x = that // let y = similar, except start from d.type // // Consider two code lines down, genericSubstitution(...).apply(result). // // Applying this chosen-candidate's type substitution means modifying x, substituting // S for T. This mutation should affect x and not y. result = deepCopy(mem->get_type()); // substitute aggregate generic parameters into member type genericSubstitution( aggregate->result ).apply( result ); // ensure appropriate restrictions from aggregate type add_qualifiers( result, aggregate->result->qualifiers ); } MemberExpr::MemberExpr( const CodeLocation & loc, const DeclWithType * mem, const Expr * agg, MemberExpr::NoOpConstruction overloadSelector ) : Expr( loc ), member( mem ), aggregate( agg ) { assert( member ); assert( aggregate ); assert( aggregate->result ); (void) overloadSelector; } bool MemberExpr::get_lvalue() const { // This is actually wrong by C, but it works with our current set-up. return true; } // --- VariableExpr VariableExpr::VariableExpr( const CodeLocation & loc ) : Expr( loc ), var( nullptr ) {} VariableExpr::VariableExpr( const CodeLocation & loc, const DeclWithType * v ) : Expr( loc ), var( v ) { assert( var ); assert( var->get_type() ); result = shallowCopy( var->get_type() ); } bool VariableExpr::get_lvalue() const { // It isn't always an lvalue, but it is never an rvalue. return true; } VariableExpr * VariableExpr::functionPointer( const CodeLocation & loc, const FunctionDecl * decl ) { // wrap usually-determined result type in a pointer VariableExpr * funcExpr = new VariableExpr{ loc, decl }; funcExpr->result = new PointerType{ funcExpr->result }; return funcExpr; } // --- ConstantExpr long long int ConstantExpr::intValue() const { if ( const BasicType * bty = result.as< BasicType >() ) { if ( bty->isInteger() ) { assert(ival); return ival.value(); } } else if ( result.as< ZeroType >() ) { return 0; } else if ( result.as< OneType >() ) { return 1; } SemanticError( this, "Constant expression of non-integral type " ); } ConstantExpr * ConstantExpr::from_bool( const CodeLocation & loc, bool b ) { return new ConstantExpr{ loc, new BasicType{ BasicType::Bool }, b ? "1" : "0", (unsigned long long)b }; } ConstantExpr * ConstantExpr::from_int( const CodeLocation & loc, int i ) { return new ConstantExpr{ loc, new BasicType{ BasicType::SignedInt }, std::to_string( i ), (unsigned long long)i }; } ConstantExpr * ConstantExpr::from_ulong( const CodeLocation & loc, unsigned long i ) { return new ConstantExpr{ loc, new BasicType{ BasicType::LongUnsignedInt }, std::to_string( i ), (unsigned long long)i }; } ConstantExpr * ConstantExpr::null( const CodeLocation & loc, const Type * ptrType ) { return new ConstantExpr{ loc, ptrType ? ptrType : new PointerType{ new VoidType{} }, "0", (unsigned long long)0 }; } // --- SizeofExpr SizeofExpr::SizeofExpr( const CodeLocation & loc, const Expr * e ) : Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {} SizeofExpr::SizeofExpr( const CodeLocation & loc, const Type * t ) : Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {} // --- AlignofExpr AlignofExpr::AlignofExpr( const CodeLocation & loc, const Expr * e ) : Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {} AlignofExpr::AlignofExpr( const CodeLocation & loc, const Type * t ) : Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {} // --- OffsetofExpr OffsetofExpr::OffsetofExpr( const CodeLocation & loc, const Type * ty, const DeclWithType * mem ) : Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), type( ty ), member( mem ) { assert( type ); assert( member ); } // --- OffsetPackExpr OffsetPackExpr::OffsetPackExpr( const CodeLocation & loc, const StructInstType * ty ) : Expr( loc, new ArrayType{ new BasicType{ BasicType::LongUnsignedInt }, nullptr, FixedLen, DynamicDim } ), type( ty ) { assert( type ); } // --- LogicalExpr LogicalExpr::LogicalExpr( const CodeLocation & loc, const Expr * a1, const Expr * a2, LogicalFlag ia ) : Expr( loc, new BasicType{ BasicType::SignedInt } ), arg1( a1 ), arg2( a2 ), isAnd( ia ) {} // --- CommaExpr bool CommaExpr::get_lvalue() const { // This is wrong by C, but the current implementation uses it. // (ex: Specialize, Lvalue and Box) return arg2->get_lvalue(); } // --- ConstructorExpr ConstructorExpr::ConstructorExpr( const CodeLocation & loc, const Expr * call ) : Expr( loc ), callExpr( call ) { // allow resolver to type a constructor used as an expression if it has the same type as its // first argument assert( callExpr ); const Expr * arg = InitTweak::getCallArg( callExpr, 0 ); assert( arg ); result = arg->result; } // --- CompoundLiteralExpr CompoundLiteralExpr::CompoundLiteralExpr( const CodeLocation & loc, const Type * t, const Init * i ) : Expr( loc ), init( i ) { assert( t && i ); result = t; } bool CompoundLiteralExpr::get_lvalue() const { return true; } // --- TupleExpr TupleExpr::TupleExpr( const CodeLocation & loc, std::vector> && xs ) : Expr( loc, Tuples::makeTupleType( xs ) ), exprs( xs ) {} // --- TupleIndexExpr TupleIndexExpr::TupleIndexExpr( const CodeLocation & loc, const Expr * t, unsigned i ) : Expr( loc ), tuple( t ), index( i ) { const TupleType * type = strict_dynamic_cast< const TupleType * >( tuple->result.get() ); assertf( type->size() > index, "TupleIndexExpr index out of bounds: tuple size %d, requested " "index %d in expr %s", type->size(), index, toString( tuple ).c_str() ); // like MemberExpr, TupleIndexExpr is always an lvalue result = type->types[ index ]; } bool TupleIndexExpr::get_lvalue() const { return tuple->get_lvalue(); } // --- TupleAssignExpr TupleAssignExpr::TupleAssignExpr( const CodeLocation & loc, std::vector> && assigns, std::vector> && tempDecls ) : Expr( loc, Tuples::makeTupleType( assigns ) ), stmtExpr() { // convert internally into a StmtExpr which contains the declarations and produces the tuple of // the assignments std::list> stmts; for ( const ObjectDecl * obj : tempDecls ) { stmts.emplace_back( new DeclStmt{ loc, obj } ); } TupleExpr * tupleExpr = new TupleExpr{ loc, std::move(assigns) }; assert( tupleExpr->result ); stmts.emplace_back( new ExprStmt{ loc, tupleExpr } ); stmtExpr = new StmtExpr{ loc, new CompoundStmt{ loc, std::move(stmts) } }; } TupleAssignExpr::TupleAssignExpr( const CodeLocation & loc, const Type * result, const StmtExpr * s ) : Expr( loc, result ), stmtExpr() { stmtExpr = s; } // --- StmtExpr StmtExpr::StmtExpr( const CodeLocation & loc, const CompoundStmt * ss ) : Expr( loc ), stmts( ss ), returnDecls(), dtors() { computeResult(); } void StmtExpr::computeResult() { assert( stmts ); const std::list> & body = stmts->kids; if ( ! returnDecls.empty() ) { // prioritize return decl for result type, since if a return decl exists, then the StmtExpr // is currently in an intermediate state where the body will always give a void result type result = returnDecls.front()->get_type(); } else if ( ! body.empty() ) { if ( const ExprStmt * exprStmt = body.back().as< ExprStmt >() ) { result = exprStmt->expr->result; } } // ensure a result type exists if ( ! result ) { result = new VoidType{}; } } // --- UniqueExpr unsigned long long UniqueExpr::nextId = 0; UniqueExpr::UniqueExpr( const CodeLocation & loc, const Expr * e, unsigned long long i ) : Expr( loc, e->result ), expr( e ), id( i ) { assert( expr ); if ( id == -1ull ) { assert( nextId != -1ull ); id = nextId++; } } } // Local Variables: // // tab-width: 4 // // mode: c++ // // compile-command: "make install" // // End: //