aboutsummaryrefslogtreecommitdiff
path: root/lib/Sema/SemaExpr.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'lib/Sema/SemaExpr.cpp')
-rw-r--r--lib/Sema/SemaExpr.cpp2286
1 files changed, 2286 insertions, 0 deletions
diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp
new file mode 100644
index 0000000000..d756345c1a
--- /dev/null
+++ b/lib/Sema/SemaExpr.cpp
@@ -0,0 +1,2286 @@
+//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements semantic analysis for expressions.
+//
+//===----------------------------------------------------------------------===//
+
+#include "Sema.h"
+#include "SemaUtil.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/Parse/DeclSpec.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/LiteralSupport.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TargetInfo.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringExtras.h"
+using namespace clang;
+
+/// ActOnStringLiteral - The specified tokens were lexed as pasted string
+/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
+/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
+/// multiple tokens. However, the common case is that StringToks points to one
+/// string.
+///
+Action::ExprResult
+Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
+ assert(NumStringToks && "Must have at least one string!");
+
+ StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
+ if (Literal.hadError)
+ return ExprResult(true);
+
+ llvm::SmallVector<SourceLocation, 4> StringTokLocs;
+ for (unsigned i = 0; i != NumStringToks; ++i)
+ StringTokLocs.push_back(StringToks[i].getLocation());
+
+ // Verify that pascal strings aren't too large.
+ if (Literal.Pascal && Literal.GetStringLength() > 256)
+ return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
+ SourceRange(StringToks[0].getLocation(),
+ StringToks[NumStringToks-1].getLocation()));
+
+ QualType StrTy = Context.CharTy;
+ // FIXME: handle wchar_t
+ if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
+
+ // Get an array type for the string, according to C99 6.4.5. This includes
+ // the nul terminator character as well as the string length for pascal
+ // strings.
+ StrTy = Context.getConstantArrayType(StrTy,
+ llvm::APInt(32, Literal.GetStringLength()+1),
+ ArrayType::Normal, 0);
+
+ // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
+ return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
+ Literal.AnyWide, StrTy,
+ StringToks[0].getLocation(),
+ StringToks[NumStringToks-1].getLocation());
+}
+
+
+/// ActOnIdentifierExpr - The parser read an identifier in expression context,
+/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
+/// identifier is used in an function call context.
+Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
+ IdentifierInfo &II,
+ bool HasTrailingLParen) {
+ // Could be enum-constant or decl.
+ ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
+ if (D == 0) {
+ // Otherwise, this could be an implicitly declared function reference (legal
+ // in C90, extension in C99).
+ if (HasTrailingLParen &&
+ // Not in C++.
+ !getLangOptions().CPlusPlus)
+ D = ImplicitlyDefineFunction(Loc, II, S);
+ else {
+ if (CurMethodDecl) {
+ ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
+ ObjCInterfaceDecl *clsDeclared;
+ if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
+ IdentifierInfo &II = Context.Idents.get("self");
+ ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
+ return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
+ static_cast<Expr*>(SelfExpr.Val), true, true);
+ }
+ }
+ // If this name wasn't predeclared and if this is not a function call,
+ // diagnose the problem.
+ return Diag(Loc, diag::err_undeclared_var_use, II.getName());
+ }
+ }
+ if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
+ // check if referencing an identifier with __attribute__((deprecated)).
+ if (VD->getAttr<DeprecatedAttr>())
+ Diag(Loc, diag::warn_deprecated, VD->getName());
+
+ // Only create DeclRefExpr's for valid Decl's.
+ if (VD->isInvalidDecl())
+ return true;
+ return new DeclRefExpr(VD, VD->getType(), Loc);
+ }
+ if (isa<TypedefDecl>(D))
+ return Diag(Loc, diag::err_unexpected_typedef, II.getName());
+ if (isa<ObjCInterfaceDecl>(D))
+ return Diag(Loc, diag::err_unexpected_interface, II.getName());
+
+ assert(0 && "Invalid decl");
+ abort();
+}
+
+Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
+ tok::TokenKind Kind) {
+ PreDefinedExpr::IdentType IT;
+
+ switch (Kind) {
+ default: assert(0 && "Unknown simple primary expr!");
+ case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
+ case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
+ case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
+ }
+
+ // Verify that this is in a function context.
+ if (CurFunctionDecl == 0 && CurMethodDecl == 0)
+ return Diag(Loc, diag::err_predef_outside_function);
+
+ // Pre-defined identifiers are of type char[x], where x is the length of the
+ // string.
+ unsigned Length;
+ if (CurFunctionDecl)
+ Length = CurFunctionDecl->getIdentifier()->getLength();
+ else
+ Length = CurMethodDecl->getSynthesizedMethodSize();
+
+ llvm::APInt LengthI(32, Length + 1);
+ QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
+ ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
+ return new PreDefinedExpr(Loc, ResTy, IT);
+}
+
+Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
+ llvm::SmallString<16> CharBuffer;
+ CharBuffer.resize(Tok.getLength());
+ const char *ThisTokBegin = &CharBuffer[0];
+ unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
+
+ CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
+ Tok.getLocation(), PP);
+ if (Literal.hadError())
+ return ExprResult(true);
+
+ QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
+
+ return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
+}
+
+Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
+ // fast path for a single digit (which is quite common). A single digit
+ // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
+ if (Tok.getLength() == 1) {
+ const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
+
+ unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
+ return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
+ Context.IntTy,
+ Tok.getLocation()));
+ }
+ llvm::SmallString<512> IntegerBuffer;
+ IntegerBuffer.resize(Tok.getLength());
+ const char *ThisTokBegin = &IntegerBuffer[0];
+
+ // Get the spelling of the token, which eliminates trigraphs, etc.
+ unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
+ NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
+ Tok.getLocation(), PP);
+ if (Literal.hadError)
+ return ExprResult(true);
+
+ Expr *Res;
+
+ if (Literal.isFloatingLiteral()) {
+ QualType Ty;
+ const llvm::fltSemantics *Format;
+
+ if (Literal.isFloat) {
+ Ty = Context.FloatTy;
+ Format = Context.Target.getFloatFormat();
+ } else if (!Literal.isLong) {
+ Ty = Context.DoubleTy;
+ Format = Context.Target.getDoubleFormat();
+ } else {
+ Ty = Context.LongDoubleTy;
+ Format = Context.Target.getLongDoubleFormat();
+ }
+
+ // isExact will be set by GetFloatValue().
+ bool isExact = false;
+
+ Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
+ Ty, Tok.getLocation());
+
+ } else if (!Literal.isIntegerLiteral()) {
+ return ExprResult(true);
+ } else {
+ QualType t;
+
+ // long long is a C99 feature.
+ if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
+ Literal.isLongLong)
+ Diag(Tok.getLocation(), diag::ext_longlong);
+
+ // Get the value in the widest-possible width.
+ llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
+
+ if (Literal.GetIntegerValue(ResultVal)) {
+ // If this value didn't fit into uintmax_t, warn and force to ull.
+ Diag(Tok.getLocation(), diag::warn_integer_too_large);
+ t = Context.UnsignedLongLongTy;
+ assert(Context.getTypeSize(t) == ResultVal.getBitWidth() &&
+ "long long is not intmax_t?");
+ } else {
+ // If this value fits into a ULL, try to figure out what else it fits into
+ // according to the rules of C99 6.4.4.1p5.
+
+ // Octal, Hexadecimal, and integers with a U suffix are allowed to
+ // be an unsigned int.
+ bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
+
+ // Check from smallest to largest, picking the smallest type we can.
+ if (!Literal.isLong && !Literal.isLongLong) {
+ // Are int/unsigned possibilities?
+ unsigned IntSize =
+ static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
+ // Does it fit in a unsigned int?
+ if (ResultVal.isIntN(IntSize)) {
+ // Does it fit in a signed int?
+ if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
+ t = Context.IntTy;
+ else if (AllowUnsigned)
+ t = Context.UnsignedIntTy;
+ }
+
+ if (!t.isNull())
+ ResultVal.trunc(IntSize);
+ }
+
+ // Are long/unsigned long possibilities?
+ if (t.isNull() && !Literal.isLongLong) {
+ unsigned LongSize =
+ static_cast<unsigned>(Context.getTypeSize(Context.LongTy));
+
+ // Does it fit in a unsigned long?
+ if (ResultVal.isIntN(LongSize)) {
+ // Does it fit in a signed long?
+ if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
+ t = Context.LongTy;
+ else if (AllowUnsigned)
+ t = Context.UnsignedLongTy;
+ }
+ if (!t.isNull())
+ ResultVal.trunc(LongSize);
+ }
+
+ // Finally, check long long if needed.
+ if (t.isNull()) {
+ unsigned LongLongSize =
+ static_cast<unsigned>(Context.getTypeSize(Context.LongLongTy));
+
+ // Does it fit in a unsigned long long?
+ if (ResultVal.isIntN(LongLongSize)) {
+ // Does it fit in a signed long long?
+ if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
+ t = Context.LongLongTy;
+ else if (AllowUnsigned)
+ t = Context.UnsignedLongLongTy;
+ }
+ }
+
+ // If we still couldn't decide a type, we probably have something that
+ // does not fit in a signed long long, but has no U suffix.
+ if (t.isNull()) {
+ Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
+ t = Context.UnsignedLongLongTy;
+ }
+ }
+
+ Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
+ }
+
+ // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
+ if (Literal.isImaginary)
+ Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
+
+ return Res;
+}
+
+Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
+ ExprTy *Val) {
+ Expr *e = (Expr *)Val;
+ assert((e != 0) && "ActOnParenExpr() missing expr");
+ return new ParenExpr(L, R, e);
+}
+
+/// The UsualUnaryConversions() function is *not* called by this routine.
+/// See C99 6.3.2.1p[2-4] for more details.
+QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
+ SourceLocation OpLoc, bool isSizeof) {
+ // C99 6.5.3.4p1:
+ if (isa<FunctionType>(exprType) && isSizeof)
+ // alignof(function) is allowed.
+ Diag(OpLoc, diag::ext_sizeof_function_type);
+ else if (exprType->isVoidType())
+ Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
+ else if (exprType->isIncompleteType()) {
+ Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
+ diag::err_alignof_incomplete_type,
+ exprType.getAsString());
+ return QualType(); // error
+ }
+ // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
+ return Context.getSizeType();
+}
+
+Action::ExprResult Sema::
+ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
+ SourceLocation LPLoc, TypeTy *Ty,
+ SourceLocation RPLoc) {
+ // If error parsing type, ignore.
+ if (Ty == 0) return true;
+
+ // Verify that this is a valid expression.
+ QualType ArgTy = QualType::getFromOpaquePtr(Ty);
+
+ QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
+
+ if (resultType.isNull())
+ return true;
+ return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
+}
+
+QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
+ DefaultFunctionArrayConversion(V);
+
+ // These operators return the element type of a complex type.
+ if (const ComplexType *CT = V->getType()->getAsComplexType())
+ return CT->getElementType();
+
+ // Otherwise they pass through real integer and floating point types here.
+ if (V->getType()->isArithmeticType())
+ return V->getType();
+
+ // Reject anything else.
+ Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
+ return QualType();
+}
+
+
+
+Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
+ tok::TokenKind Kind,
+ ExprTy *Input) {
+ UnaryOperator::Opcode Opc;
+ switch (Kind) {
+ default: assert(0 && "Unknown unary op!");
+ case tok::plusplus: Opc = UnaryOperator::PostInc; break;
+ case tok::minusminus: Opc = UnaryOperator::PostDec; break;
+ }
+ QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
+ if (result.isNull())
+ return true;
+ return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
+}
+
+Action::ExprResult Sema::
+ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
+ ExprTy *Idx, SourceLocation RLoc) {
+ Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
+
+ // Perform default conversions.
+ DefaultFunctionArrayConversion(LHSExp);
+ DefaultFunctionArrayConversion(RHSExp);
+
+ QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
+
+ // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
+ // to the expression *((e1)+(e2)). This means the array "Base" may actually be
+ // in the subscript position. As a result, we need to derive the array base
+ // and index from the expression types.
+ Expr *BaseExpr, *IndexExpr;
+ QualType ResultType;
+ if (const PointerType *PTy = LHSTy->getAsPointerType()) {
+ BaseExpr = LHSExp;
+ IndexExpr = RHSExp;
+ // FIXME: need to deal with const...
+ ResultType = PTy->getPointeeType();
+ } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
+ // Handle the uncommon case of "123[Ptr]".
+ BaseExpr = RHSExp;
+ IndexExpr = LHSExp;
+ // FIXME: need to deal with const...
+ ResultType = PTy->getPointeeType();
+ } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
+ BaseExpr = LHSExp; // vectors: V[123]
+ IndexExpr = RHSExp;
+
+ // Component access limited to variables (reject vec4.rg[1]).
+ if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
+ return Diag(LLoc, diag::err_ocuvector_component_access,
+ SourceRange(LLoc, RLoc));
+ // FIXME: need to deal with const...
+ ResultType = VTy->getElementType();
+ } else {
+ return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
+ RHSExp->getSourceRange());
+ }
+ // C99 6.5.2.1p1
+ if (!IndexExpr->getType()->isIntegerType())
+ return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
+ IndexExpr->getSourceRange());
+
+ // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
+ // the following check catches trying to index a pointer to a function (e.g.
+ // void (*)(int)). Functions are not objects in C99.
+ if (!ResultType->isObjectType())
+ return Diag(BaseExpr->getLocStart(),
+ diag::err_typecheck_subscript_not_object,
+ BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
+
+ return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
+}
+
+QualType Sema::
+CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
+ IdentifierInfo &CompName, SourceLocation CompLoc) {
+ const OCUVectorType *vecType = baseType->getAsOCUVectorType();
+
+ // The vector accessor can't exceed the number of elements.
+ const char *compStr = CompName.getName();
+ if (strlen(compStr) > vecType->getNumElements()) {
+ Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
+ baseType.getAsString(), SourceRange(CompLoc));
+ return QualType();
+ }
+ // The component names must come from the same set.
+ if (vecType->getPointAccessorIdx(*compStr) != -1) {
+ do
+ compStr++;
+ while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
+ } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
+ do
+ compStr++;
+ while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
+ } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
+ do
+ compStr++;
+ while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
+ }
+
+ if (*compStr) {
+ // We didn't get to the end of the string. This means the component names
+ // didn't come from the same set *or* we encountered an illegal name.
+ Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
+ std::string(compStr,compStr+1), SourceRange(CompLoc));
+ return QualType();
+ }
+ // Each component accessor can't exceed the vector type.
+ compStr = CompName.getName();
+ while (*compStr) {
+ if (vecType->isAccessorWithinNumElements(*compStr))
+ compStr++;
+ else
+ break;
+ }
+ if (*compStr) {
+ // We didn't get to the end of the string. This means a component accessor
+ // exceeds the number of elements in the vector.
+ Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
+ baseType.getAsString(), SourceRange(CompLoc));
+ return QualType();
+ }
+ // The component accessor looks fine - now we need to compute the actual type.
+ // The vector type is implied by the component accessor. For example,
+ // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
+ unsigned CompSize = strlen(CompName.getName());
+ if (CompSize == 1)
+ return vecType->getElementType();
+
+ QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
+ // Now look up the TypeDefDecl from the vector type. Without this,
+ // diagostics look bad. We want OCU vector types to appear built-in.
+ for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
+ if (OCUVectorDecls[i]->getUnderlyingType() == VT)
+ return Context.getTypedefType(OCUVectorDecls[i]);
+ }
+ return VT; // should never get here (a typedef type should always be found).
+}
+
+Action::ExprResult Sema::
+ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
+ tok::TokenKind OpKind, SourceLocation MemberLoc,
+ IdentifierInfo &Member) {
+ Expr *BaseExpr = static_cast<Expr *>(Base);
+ assert(BaseExpr && "no record expression");
+
+ // Perform default conversions.
+ DefaultFunctionArrayConversion(BaseExpr);
+
+ QualType BaseType = BaseExpr->getType();
+ assert(!BaseType.isNull() && "no type for member expression");
+
+ if (OpKind == tok::arrow) {
+ if (const PointerType *PT = BaseType->getAsPointerType())
+ BaseType = PT->getPointeeType();
+ else
+ return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
+ SourceRange(MemberLoc));
+ }
+ // The base type is either a record or an OCUVectorType.
+ if (const RecordType *RTy = BaseType->getAsRecordType()) {
+ RecordDecl *RDecl = RTy->getDecl();
+ if (RTy->isIncompleteType())
+ return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
+ BaseExpr->getSourceRange());
+ // The record definition is complete, now make sure the member is valid.
+ FieldDecl *MemberDecl = RDecl->getMember(&Member);
+ if (!MemberDecl)
+ return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
+ SourceRange(MemberLoc));
+
+ // Figure out the type of the member; see C99 6.5.2.3p3
+ // FIXME: Handle address space modifiers
+ QualType MemberType = MemberDecl->getType();
+ unsigned combinedQualifiers =
+ MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
+ MemberType = MemberType.getQualifiedType(combinedQualifiers);
+
+ return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
+ MemberLoc, MemberType);
+ } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
+ // Component access limited to variables (reject vec4.rg.g).
+ if (!isa<DeclRefExpr>(BaseExpr))
+ return Diag(OpLoc, diag::err_ocuvector_component_access,
+ SourceRange(MemberLoc));
+ QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
+ if (ret.isNull())
+ return true;
+ return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
+ } else if (BaseType->isObjCInterfaceType()) {
+ ObjCInterfaceDecl *IFace;
+ if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
+ IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
+ else
+ IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
+ ObjCInterfaceDecl *clsDeclared;
+ if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
+ return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
+ OpKind==tok::arrow);
+ }
+ return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
+ SourceRange(MemberLoc));
+}
+
+/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
+/// This provides the location of the left/right parens and a list of comma
+/// locations.
+Action::ExprResult Sema::
+ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
+ ExprTy **args, unsigned NumArgs,
+ SourceLocation *CommaLocs, SourceLocation RParenLoc) {
+ Expr *Fn = static_cast<Expr *>(fn);
+ Expr **Args = reinterpret_cast<Expr**>(args);
+ assert(Fn && "no function call expression");
+
+ // Make the call expr early, before semantic checks. This guarantees cleanup
+ // of arguments and function on error.
+ llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
+ Context.BoolTy, RParenLoc));
+
+ // Promote the function operand.
+ TheCall->setCallee(UsualUnaryConversions(Fn));
+
+ // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
+ // type pointer to function".
+ const PointerType *PT = Fn->getType()->getAsPointerType();
+ if (PT == 0)
+ return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
+ SourceRange(Fn->getLocStart(), RParenLoc));
+ const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
+ if (FuncT == 0)
+ return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
+ SourceRange(Fn->getLocStart(), RParenLoc));
+
+ // We know the result type of the call, set it.
+ TheCall->setType(FuncT->getResultType());
+
+ if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
+ // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
+ // assignment, to the types of the corresponding parameter, ...
+ unsigned NumArgsInProto = Proto->getNumArgs();
+ unsigned NumArgsToCheck = NumArgs;
+
+ // If too few arguments are available, don't make the call.
+ if (NumArgs < NumArgsInProto)
+ return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
+ Fn->getSourceRange());
+
+ // If too many are passed and not variadic, error on the extras and drop
+ // them.
+ if (NumArgs > NumArgsInProto) {
+ if (!Proto->isVariadic()) {
+ Diag(Args[NumArgsInProto]->getLocStart(),
+ diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
+ SourceRange(Args[NumArgsInProto]->getLocStart(),
+ Args[NumArgs-1]->getLocEnd()));
+ // This deletes the extra arguments.
+ TheCall->setNumArgs(NumArgsInProto);
+ }
+ NumArgsToCheck = NumArgsInProto;
+ }
+
+ // Continue to check argument types (even if we have too few/many args).
+ for (unsigned i = 0; i != NumArgsToCheck; i++) {
+ Expr *Arg = Args[i];
+ QualType ProtoArgType = Proto->getArgType(i);
+ QualType ArgType = Arg->getType();
+
+ // Compute implicit casts from the operand to the formal argument type.
+ AssignConvertType ConvTy =
+ CheckSingleAssignmentConstraints(ProtoArgType, Arg);
+ TheCall->setArg(i, Arg);
+
+ if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
+ ArgType, Arg, "passing"))
+ return true;
+ }
+
+ // If this is a variadic call, handle args passed through "...".
+ if (Proto->isVariadic()) {
+ // Promote the arguments (C99 6.5.2.2p7).
+ for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
+ Expr *Arg = Args[i];
+ DefaultArgumentPromotion(Arg);
+ TheCall->setArg(i, Arg);
+ }
+ }
+ } else {
+ assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
+
+ // Promote the arguments (C99 6.5.2.2p6).
+ for (unsigned i = 0; i != NumArgs; i++) {
+ Expr *Arg = Args[i];
+ DefaultArgumentPromotion(Arg);
+ TheCall->setArg(i, Arg);
+ }
+ }
+
+ // Do special checking on direct calls to functions.
+ if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
+ if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
+ if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
+ if (CheckFunctionCall(FDecl, TheCall.get()))
+ return true;
+
+ return TheCall.take();
+}
+
+Action::ExprResult Sema::
+ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
+ SourceLocation RParenLoc, ExprTy *InitExpr) {
+ assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
+ QualType literalType = QualType::getFromOpaquePtr(Ty);
+ // FIXME: put back this assert when initializers are worked out.
+ //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
+ Expr *literalExpr = static_cast<Expr*>(InitExpr);
+
+ // FIXME: add more semantic analysis (C99 6.5.2.5).
+ if (CheckInitializerTypes(literalExpr, literalType))
+ return true;
+
+ bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
+ if (isFileScope) { // 6.5.2.5p3
+ if (CheckForConstantInitializer(literalExpr, literalType))
+ return true;
+ }
+ return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
+}
+
+Action::ExprResult Sema::
+ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
+ SourceLocation RBraceLoc) {
+ Expr **InitList = reinterpret_cast<Expr**>(initlist);
+
+ // Semantic analysis for initializers is done by ActOnDeclarator() and
+ // CheckInitializer() - it requires knowledge of the object being intialized.
+
+ InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
+ e->setType(Context.VoidTy); // FIXME: just a place holder for now.
+ return e;
+}
+
+bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
+ assert(VectorTy->isVectorType() && "Not a vector type!");
+
+ if (Ty->isVectorType() || Ty->isIntegerType()) {
+ if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
+ return Diag(R.getBegin(),
+ Ty->isVectorType() ?
+ diag::err_invalid_conversion_between_vectors :
+ diag::err_invalid_conversion_between_vector_and_integer,
+ VectorTy.getAsString().c_str(),
+ Ty.getAsString().c_str(), R);
+ } else
+ return Diag(R.getBegin(),
+ diag::err_invalid_conversion_between_vector_and_scalar,
+ VectorTy.getAsString().c_str(),
+ Ty.getAsString().c_str(), R);
+
+ return false;
+}
+
+Action::ExprResult Sema::
+ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
+ SourceLocation RParenLoc, ExprTy *Op) {
+ assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
+
+ Expr *castExpr = static_cast<Expr*>(Op);
+ QualType castType = QualType::getFromOpaquePtr(Ty);
+
+ UsualUnaryConversions(castExpr);
+
+ // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
+ // type needs to be scalar.
+ if (!castType->isVoidType()) { // Cast to void allows any expr type.
+ if (!castType->isScalarType() && !castType->isVectorType())
+ return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
+ castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
+ if (!castExpr->getType()->isScalarType() &&
+ !castExpr->getType()->isVectorType())
+ return Diag(castExpr->getLocStart(),
+ diag::err_typecheck_expect_scalar_operand,
+ castExpr->getType().getAsString(),castExpr->getSourceRange());
+
+ if (castExpr->getType()->isVectorType()) {
+ if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
+ castExpr->getType(), castType))
+ return true;
+ } else if (castType->isVectorType()) {
+ if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
+ castType, castExpr->getType()))
+ return true;
+ }
+ }
+ return new CastExpr(castType, castExpr, LParenLoc);
+}
+
+/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
+/// In that case, lex = cond.
+inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
+ Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
+ UsualUnaryConversions(cond);
+ UsualUnaryConversions(lex);
+ UsualUnaryConversions(rex);
+ QualType condT = cond->getType();
+ QualType lexT = lex->getType();
+ QualType rexT = rex->getType();
+
+ // first, check the condition.
+ if (!condT->isScalarType()) { // C99 6.5.15p2
+ Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
+ condT.getAsString());
+ return QualType();
+ }
+
+ // Now check the two expressions.
+
+ // If both operands have arithmetic type, do the usual arithmetic conversions
+ // to find a common type: C99 6.5.15p3,5.
+ if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
+ UsualArithmeticConversions(lex, rex);
+ return lex->getType();
+ }
+
+ // If both operands are the same structure or union type, the result is that
+ // type.
+ if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
+ if (const RecordType *RHSRT = rexT->getAsRecordType())
+ if (LHSRT->getDecl() == RHSRT->getDecl())
+ // "If both the operands have structure or union type, the result has
+ // that type." This implies that CV qualifiers are dropped.
+ return lexT.getUnqualifiedType();
+ }
+
+ // C99 6.5.15p5: "If both operands have void type, the result has void type."
+ if (lexT->isVoidType() && rexT->isVoidType())
+ return lexT.getUnqualifiedType();
+
+ // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
+ // the type of the other operand."
+ if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
+ ImpCastExprToType(rex, lexT); // promote the null to a pointer.
+ return lexT;
+ }
+ if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
+ ImpCastExprToType(lex, rexT); // promote the null to a pointer.
+ return rexT;
+ }
+ // Handle the case where both operands are pointers before we handle null
+ // pointer constants in case both operands are null pointer constants.
+ if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
+ if (const PointerType *RHSPT = rexT->getAsPointerType()) {
+ // get the "pointed to" types
+ QualType lhptee = LHSPT->getPointeeType();
+ QualType rhptee = RHSPT->getPointeeType();
+
+ // ignore qualifiers on void (C99 6.5.15p3, clause 6)
+ if (lhptee->isVoidType() &&
+ (rhptee->isObjectType() || rhptee->isIncompleteType())) {
+ // Figure out necessary qualifiers (C99 6.5.15p6)
+ QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
+ QualType destType = Context.getPointerType(destPointee);
+ ImpCastExprToType(lex, destType); // add qualifiers if necessary
+ ImpCastExprToType(rex, destType); // promote to void*
+ return destType;
+ }
+ if (rhptee->isVoidType() &&
+ (lhptee->isObjectType() || lhptee->isIncompleteType())) {
+ QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
+ QualType destType = Context.getPointerType(destPointee);
+ ImpCastExprToType(lex, destType); // add qualifiers if necessary
+ ImpCastExprToType(rex, destType); // promote to void*
+ return destType;
+ }
+
+ if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
+ rhptee.getUnqualifiedType())) {
+ Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
+ lexT.getAsString(), rexT.getAsString(),
+ lex->getSourceRange(), rex->getSourceRange());
+ // In this situation, we assume void* type. No especially good
+ // reason, but this is what gcc does, and we do have to pick
+ // to get a consistent AST.
+ QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
+ ImpCastExprToType(lex, voidPtrTy);
+ ImpCastExprToType(rex, voidPtrTy);
+ return voidPtrTy;
+ }
+ // The pointer types are compatible.
+ // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
+ // differently qualified versions of compatible types, the result type is
+ // a pointer to an appropriately qualified version of the *composite*
+ // type.
+ // FIXME: Need to return the composite type.
+ // FIXME: Need to add qualifiers
+ return lexT;
+ }
+ }
+
+ // Otherwise, the operands are not compatible.
+ Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
+ lexT.getAsString(), rexT.getAsString(),
+ lex->getSourceRange(), rex->getSourceRange());
+ return QualType();
+}
+
+/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
+/// in the case of a the GNU conditional expr extension.
+Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
+ SourceLocation ColonLoc,
+ ExprTy *Cond, ExprTy *LHS,
+ ExprTy *RHS) {
+ Expr *CondExpr = (Expr *) Cond;
+ Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
+
+ // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
+ // was the condition.
+ bool isLHSNull = LHSExpr == 0;
+ if (isLHSNull)
+ LHSExpr = CondExpr;
+
+ QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
+ RHSExpr, QuestionLoc);
+ if (result.isNull())
+ return true;
+ return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
+ RHSExpr, result);
+}
+
+/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
+/// do not have a prototype. Arguments that have type float are promoted to
+/// double. All other argument types are converted by UsualUnaryConversions().
+void Sema::DefaultArgumentPromotion(Expr *&Expr) {
+ QualType Ty = Expr->getType();
+ assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
+
+ if (Ty == Context.FloatTy)
+ ImpCastExprToType(Expr, Context.DoubleTy);
+ else
+ UsualUnaryConversions(Expr);
+}
+
+/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
+void Sema::DefaultFunctionArrayConversion(Expr *&e) {
+ QualType t = e->getType();
+ assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
+
+ if (const ReferenceType *ref = t->getAsReferenceType()) {
+ ImpCastExprToType(e, ref->getReferenceeType()); // C++ [expr]
+ t = e->getType();
+ }
+ if (t->isFunctionType())
+ ImpCastExprToType(e, Context.getPointerType(t));
+ else if (const ArrayType *ary = t->getAsArrayType()) {
+ // Make sure we don't lose qualifiers when dealing with typedefs. Example:
+ // typedef int arr[10];
+ // void test2() {
+ // const arr b;
+ // b[4] = 1;
+ // }
+ QualType ELT = ary->getElementType();
+ // FIXME: Handle ASQualType
+ ELT = ELT.getQualifiedType(t.getCVRQualifiers()|ELT.getCVRQualifiers());
+