From d8e39bbb847b35d8912db2d13096d588651a72f1 Mon Sep 17 00:00:00 2001 From: Anders Carlsson Date: Sat, 11 Apr 2009 01:08:03 +0000 Subject: [PATCH] Add support for generating reference initialization code. llvm-svn: 68852 --- clang/lib/CodeGen/CGExprConstant.cpp | 23 +++++++++++++++++++++-- clang/test/CodeGenCXX/const-init.cpp | 11 +++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 clang/test/CodeGenCXX/const-init.cpp diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp index a3fca20f4fb1..2373ad64e923 100644 --- a/clang/lib/CodeGen/CGExprConstant.cpp +++ b/clang/lib/CodeGen/CGExprConstant.cpp @@ -474,7 +474,26 @@ llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, CodeGenFunction *CGF) { Expr::EvalResult Result; - if (E->Evaluate(Result, Context)) { + bool Success = false; + + if (DestType->isReferenceType()) { + // If the destination type is a reference type, we need to evaluate it + // as an lvalue. + if (E->EvaluateAsLValue(Result, Context)) { + if (const Expr *LVBase = Result.Val.getLValueBase()) { + if (const DeclRefExpr *DRE = dyn_cast(LVBase)) { + const ValueDecl *VD = cast(DRE->getDecl()); + + // We can only initialize a reference with an lvalue if the lvalue + // is not a reference itself. + Success = !VD->getType()->isReferenceType(); + } + } + } + } else + Success = E->Evaluate(Result, Context); + + if (Success) { assert(!Result.HasSideEffects && "Constant expr should not have any side effects!"); switch (Result.Val.getKind()) { @@ -482,7 +501,7 @@ llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, assert(0 && "Constant expressions should be initialized."); return 0; case APValue::LValue: { - const llvm::Type *DestTy = getTypes().ConvertTypeForMem(E->getType()); + const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType); llvm::Constant *Offset = llvm::ConstantInt::get(llvm::Type::Int64Ty, Result.Val.getLValueOffset()); diff --git a/clang/test/CodeGenCXX/const-init.cpp b/clang/test/CodeGenCXX/const-init.cpp new file mode 100644 index 000000000000..427ba5372992 --- /dev/null +++ b/clang/test/CodeGenCXX/const-init.cpp @@ -0,0 +1,11 @@ +// RUN: clang-cc -verify -emit-llvm -o %t %s + +int a = 10; +int &ar = a; + +void f(); +void (&fr)() = f; + +struct S { int& a; }; +S s = { a }; +