1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for expressions.
12 //===----------------------------------------------------------------------===//
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/Parse/DeclSpec.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 using namespace clang;
28 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
29 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31 /// multiple tokens. However, the common case is that StringToks points to one
35 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
36 assert(NumStringToks && "Must have at least one string!");
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
40 return ExprResult(true);
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
46 // Verify that pascal strings aren't too large.
47 if (Literal.Pascal && Literal.GetStringLength() > 256)
48 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
49 SourceRange(StringToks[0].getLocation(),
50 StringToks[NumStringToks-1].getLocation()));
52 QualType StrTy = Context.CharTy;
53 // FIXME: handle wchar_t
54 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
56 // Get an array type for the string, according to C99 6.4.5. This includes
57 // the nul terminator character as well as the string length for pascal
59 StrTy = Context.getConstantArrayType(StrTy,
60 llvm::APInt(32, Literal.GetStringLength()+1),
61 ArrayType::Normal, 0);
63 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
64 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
65 Literal.AnyWide, StrTy,
66 StringToks[0].getLocation(),
67 StringToks[NumStringToks-1].getLocation());
71 /// ActOnIdentifierExpr - The parser read an identifier in expression context,
72 /// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
73 /// identifier is used in an function call context.
74 Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
76 bool HasTrailingLParen) {
77 // Could be enum-constant or decl.
78 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
80 // Otherwise, this could be an implicitly declared function reference (legal
81 // in C90, extension in C99).
82 if (HasTrailingLParen &&
84 !getLangOptions().CPlusPlus)
85 D = ImplicitlyDefineFunction(Loc, II, S);
88 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
89 ObjCInterfaceDecl *clsDeclared;
90 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
91 IdentifierInfo &II = Context.Idents.get("self");
92 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
93 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
94 static_cast<Expr*>(SelfExpr.Val), true, true);
97 // If this name wasn't predeclared and if this is not a function call,
98 // diagnose the problem.
99 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
102 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
103 // check if referencing an identifier with __attribute__((deprecated)).
104 if (VD->getAttr<DeprecatedAttr>())
105 Diag(Loc, diag::warn_deprecated, VD->getName());
107 // Only create DeclRefExpr's for valid Decl's.
108 if (VD->isInvalidDecl())
110 return new DeclRefExpr(VD, VD->getType(), Loc);
112 if (isa<TypedefDecl>(D))
113 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
114 if (isa<ObjCInterfaceDecl>(D))
115 return Diag(Loc, diag::err_unexpected_interface, II.getName());
117 assert(0 && "Invalid decl");
121 Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
122 tok::TokenKind Kind) {
123 PreDefinedExpr::IdentType IT;
126 default: assert(0 && "Unknown simple primary expr!");
127 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
128 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
129 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
132 // Verify that this is in a function context.
133 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
134 return Diag(Loc, diag::err_predef_outside_function);
136 // Pre-defined identifiers are of type char[x], where x is the length of the
140 Length = CurFunctionDecl->getIdentifier()->getLength();
142 Length = CurMethodDecl->getSynthesizedMethodSize();
144 llvm::APInt LengthI(32, Length + 1);
145 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
146 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
147 return new PreDefinedExpr(Loc, ResTy, IT);
150 Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
151 llvm::SmallString<16> CharBuffer;
152 CharBuffer.resize(Tok.getLength());
153 const char *ThisTokBegin = &CharBuffer[0];
154 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
156 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
157 Tok.getLocation(), PP);
158 if (Literal.hadError())
159 return ExprResult(true);
160 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
164 Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
165 // fast path for a single digit (which is quite common). A single digit
166 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
167 if (Tok.getLength() == 1) {
168 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
170 unsigned IntSize = static_cast<unsigned>(
171 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
172 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
176 llvm::SmallString<512> IntegerBuffer;
177 IntegerBuffer.resize(Tok.getLength());
178 const char *ThisTokBegin = &IntegerBuffer[0];
180 // Get the spelling of the token, which eliminates trigraphs, etc.
181 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
182 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
183 Tok.getLocation(), PP);
184 if (Literal.hadError)
185 return ExprResult(true);
189 if (Literal.isFloatingLiteral()) {
191 const llvm::fltSemantics *Format;
192 uint64_t Size; unsigned Align;
194 if (Literal.isFloat) {
195 Ty = Context.FloatTy;
196 Context.Target.getFloatInfo(Size, Align, Format,
197 Context.getFullLoc(Tok.getLocation()));
199 } else if (Literal.isLong) {
200 Ty = Context.LongDoubleTy;
201 Context.Target.getLongDoubleInfo(Size, Align, Format,
202 Context.getFullLoc(Tok.getLocation()));
204 Ty = Context.DoubleTy;
205 Context.Target.getDoubleInfo(Size, Align, Format,
206 Context.getFullLoc(Tok.getLocation()));
209 // isExact will be set by GetFloatValue().
210 bool isExact = false;
212 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
213 Ty, Tok.getLocation());
215 } else if (!Literal.isIntegerLiteral()) {
216 return ExprResult(true);
220 // long long is a C99 feature.
221 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
223 Diag(Tok.getLocation(), diag::ext_longlong);
225 // Get the value in the widest-possible width.
226 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
227 Context.getFullLoc(Tok.getLocation())), 0);
229 if (Literal.GetIntegerValue(ResultVal)) {
230 // If this value didn't fit into uintmax_t, warn and force to ull.
231 Diag(Tok.getLocation(), diag::warn_integer_too_large);
232 t = Context.UnsignedLongLongTy;
233 assert(Context.getTypeSize(t, Tok.getLocation()) ==
234 ResultVal.getBitWidth() && "long long is not intmax_t?");
236 // If this value fits into a ULL, try to figure out what else it fits into
237 // according to the rules of C99 6.4.4.1p5.
239 // Octal, Hexadecimal, and integers with a U suffix are allowed to
240 // be an unsigned int.
241 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
243 // Check from smallest to largest, picking the smallest type we can.
244 if (!Literal.isLong && !Literal.isLongLong) {
245 // Are int/unsigned possibilities?
246 unsigned IntSize = static_cast<unsigned>(
247 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
248 // Does it fit in a unsigned int?
249 if (ResultVal.isIntN(IntSize)) {
250 // Does it fit in a signed int?
251 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
253 else if (AllowUnsigned)
254 t = Context.UnsignedIntTy;
258 ResultVal.trunc(IntSize);
261 // Are long/unsigned long possibilities?
262 if (t.isNull() && !Literal.isLongLong) {
263 unsigned LongSize = static_cast<unsigned>(
264 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
266 // Does it fit in a unsigned long?
267 if (ResultVal.isIntN(LongSize)) {
268 // Does it fit in a signed long?
269 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
271 else if (AllowUnsigned)
272 t = Context.UnsignedLongTy;
275 ResultVal.trunc(LongSize);
278 // Finally, check long long if needed.
280 unsigned LongLongSize = static_cast<unsigned>(
281 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
283 // Does it fit in a unsigned long long?
284 if (ResultVal.isIntN(LongLongSize)) {
285 // Does it fit in a signed long long?
286 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
287 t = Context.LongLongTy;
288 else if (AllowUnsigned)
289 t = Context.UnsignedLongLongTy;
293 // If we still couldn't decide a type, we probably have something that
294 // does not fit in a signed long long, but has no U suffix.
296 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
297 t = Context.UnsignedLongLongTy;
301 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
304 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
305 if (Literal.isImaginary)
306 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
311 Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
313 Expr *e = (Expr *)Val;
314 assert((e != 0) && "ActOnParenExpr() missing expr");
315 return new ParenExpr(L, R, e);
318 /// The UsualUnaryConversions() function is *not* called by this routine.
319 /// See C99 6.3.2.1p[2-4] for more details.
320 QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
321 SourceLocation OpLoc, bool isSizeof) {
323 if (isa<FunctionType>(exprType) && isSizeof)
324 // alignof(function) is allowed.
325 Diag(OpLoc, diag::ext_sizeof_function_type);
326 else if (exprType->isVoidType())
327 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
328 else if (exprType->isIncompleteType()) {
329 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
330 diag::err_alignof_incomplete_type,
331 exprType.getAsString());
332 return QualType(); // error
334 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
335 return Context.getSizeType();
338 Action::ExprResult Sema::
339 ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
340 SourceLocation LPLoc, TypeTy *Ty,
341 SourceLocation RPLoc) {
342 // If error parsing type, ignore.
343 if (Ty == 0) return true;
345 // Verify that this is a valid expression.
346 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
348 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
350 if (resultType.isNull())
352 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
355 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
356 DefaultFunctionArrayConversion(V);
358 // These operators return the element type of a complex type.
359 if (const ComplexType *CT = V->getType()->getAsComplexType())
360 return CT->getElementType();
362 // Otherwise they pass through real integer and floating point types here.
363 if (V->getType()->isArithmeticType())
366 // Reject anything else.
367 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
373 Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
376 UnaryOperator::Opcode Opc;
378 default: assert(0 && "Unknown unary op!");
379 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
380 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
382 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
385 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
388 Action::ExprResult Sema::
389 ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
390 ExprTy *Idx, SourceLocation RLoc) {
391 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
393 // Perform default conversions.
394 DefaultFunctionArrayConversion(LHSExp);
395 DefaultFunctionArrayConversion(RHSExp);
397 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
399 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
400 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
401 // in the subscript position. As a result, we need to derive the array base
402 // and index from the expression types.
403 Expr *BaseExpr, *IndexExpr;
405 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
408 // FIXME: need to deal with const...
409 ResultType = PTy->getPointeeType();
410 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
411 // Handle the uncommon case of "123[Ptr]".
414 // FIXME: need to deal with const...
415 ResultType = PTy->getPointeeType();
416 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
417 BaseExpr = LHSExp; // vectors: V[123]
420 // Component access limited to variables (reject vec4.rg[1]).
421 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
422 return Diag(LLoc, diag::err_ocuvector_component_access,
423 SourceRange(LLoc, RLoc));
424 // FIXME: need to deal with const...
425 ResultType = VTy->getElementType();
427 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
428 RHSExp->getSourceRange());
431 if (!IndexExpr->getType()->isIntegerType())
432 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
433 IndexExpr->getSourceRange());
435 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
436 // the following check catches trying to index a pointer to a function (e.g.
437 // void (*)(int)). Functions are not objects in C99.
438 if (!ResultType->isObjectType())
439 return Diag(BaseExpr->getLocStart(),
440 diag::err_typecheck_subscript_not_object,
441 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
443 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
447 CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
448 IdentifierInfo &CompName, SourceLocation CompLoc) {
449 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
451 // The vector accessor can't exceed the number of elements.
452 const char *compStr = CompName.getName();
453 if (strlen(compStr) > vecType->getNumElements()) {
454 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
455 baseType.getAsString(), SourceRange(CompLoc));
458 // The component names must come from the same set.
459 if (vecType->getPointAccessorIdx(*compStr) != -1) {
462 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
463 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
466 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
467 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
470 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
474 // We didn't get to the end of the string. This means the component names
475 // didn't come from the same set *or* we encountered an illegal name.
476 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
477 std::string(compStr,compStr+1), SourceRange(CompLoc));
480 // Each component accessor can't exceed the vector type.
481 compStr = CompName.getName();
483 if (vecType->isAccessorWithinNumElements(*compStr))
489 // We didn't get to the end of the string. This means a component accessor
490 // exceeds the number of elements in the vector.
491 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
492 baseType.getAsString(), SourceRange(CompLoc));
495 // The component accessor looks fine - now we need to compute the actual type.
496 // The vector type is implied by the component accessor. For example,
497 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
498 unsigned CompSize = strlen(CompName.getName());
500 return vecType->getElementType();
502 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
503 // Now look up the TypeDefDecl from the vector type. Without this,
504 // diagostics look bad. We want OCU vector types to appear built-in.
505 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
506 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
507 return Context.getTypedefType(OCUVectorDecls[i]);
509 return VT; // should never get here (a typedef type should always be found).
512 Action::ExprResult Sema::
513 ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
514 tok::TokenKind OpKind, SourceLocation MemberLoc,
515 IdentifierInfo &Member) {
516 Expr *BaseExpr = static_cast<Expr *>(Base);
517 assert(BaseExpr && "no record expression");
519 // Perform default conversions.
520 DefaultFunctionArrayConversion(BaseExpr);
522 QualType BaseType = BaseExpr->getType();
523 assert(!BaseType.isNull() && "no type for member expression");
525 if (OpKind == tok::arrow) {
526 if (const PointerType *PT = BaseType->getAsPointerType())
527 BaseType = PT->getPointeeType();
529 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
530 SourceRange(MemberLoc));
532 // The base type is either a record or an OCUVectorType.
533 if (const RecordType *RTy = BaseType->getAsRecordType()) {
534 RecordDecl *RDecl = RTy->getDecl();
535 if (RTy->isIncompleteType())
536 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
537 BaseExpr->getSourceRange());
538 // The record definition is complete, now make sure the member is valid.
539 FieldDecl *MemberDecl = RDecl->getMember(&Member);
541 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
542 SourceRange(MemberLoc));
544 // Figure out the type of the member; see C99 6.5.2.3p3
545 // FIXME: Handle address space modifiers
546 QualType MemberType = MemberDecl->getType();
547 unsigned combinedQualifiers =
548 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
549 MemberType = MemberType.getQualifiedType(combinedQualifiers);
551 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
552 MemberLoc, MemberType);
553 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
554 // Component access limited to variables (reject vec4.rg.g).
555 if (!isa<DeclRefExpr>(BaseExpr))
556 return Diag(OpLoc, diag::err_ocuvector_component_access,
557 SourceRange(MemberLoc));
558 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
561 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
562 } else if (BaseType->isObjCInterfaceType()) {
563 ObjCInterfaceDecl *IFace;
564 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
565 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
567 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
568 ObjCInterfaceDecl *clsDeclared;
569 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
570 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
573 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
574 SourceRange(MemberLoc));
577 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
578 /// This provides the location of the left/right parens and a list of comma
580 Action::ExprResult Sema::
581 ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
582 ExprTy **args, unsigned NumArgs,
583 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
584 Expr *Fn = static_cast<Expr *>(fn);
585 Expr **Args = reinterpret_cast<Expr**>(args);
586 assert(Fn && "no function call expression");
588 // Make the call expr early, before semantic checks. This guarantees cleanup
589 // of arguments and function on error.
590 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
591 Context.BoolTy, RParenLoc));
593 // Promote the function operand.
594 TheCall->setCallee(UsualUnaryConversions(Fn));
596 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
597 // type pointer to function".
598 const PointerType *PT = Fn->getType()->getAsPointerType();
600 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
601 SourceRange(Fn->getLocStart(), RParenLoc));
602 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
604 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
605 SourceRange(Fn->getLocStart(), RParenLoc));
607 // We know the result type of the call, set it.
608 TheCall->setType(FuncT->getResultType());
610 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
611 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
612 // assignment, to the types of the corresponding parameter, ...
613 unsigned NumArgsInProto = Proto->getNumArgs();
614 unsigned NumArgsToCheck = NumArgs;
616 // If too few arguments are available, don't make the call.
617 if (NumArgs < NumArgsInProto)
618 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
619 Fn->getSourceRange());
621 // If too many are passed and not variadic, error on the extras and drop
623 if (NumArgs > NumArgsInProto) {
624 if (!Proto->isVariadic()) {
625 Diag(Args[NumArgsInProto]->getLocStart(),
626 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
627 SourceRange(Args[NumArgsInProto]->getLocStart(),
628 Args[NumArgs-1]->getLocEnd()));
629 // This deletes the extra arguments.
630 TheCall->setNumArgs(NumArgsInProto);
632 NumArgsToCheck = NumArgsInProto;
635 // Continue to check argument types (even if we have too few/many args).
636 for (unsigned i = 0; i != NumArgsToCheck; i++) {
638 QualType ProtoArgType = Proto->getArgType(i);
639 QualType ArgType = Arg->getType();
641 // Compute implicit casts from the operand to the formal argument type.
642 AssignConvertType ConvTy =
643 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
644 TheCall->setArg(i, Arg);
646 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
647 ArgType, Arg, "passing"))
651 // If this is a variadic call, handle args passed through "...".
652 if (Proto->isVariadic()) {
653 // Promote the arguments (C99 6.5.2.2p7).
654 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
656 DefaultArgumentPromotion(Arg);
657 TheCall->setArg(i, Arg);
661 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
663 // Promote the arguments (C99 6.5.2.2p6).
664 for (unsigned i = 0; i != NumArgs; i++) {
666 DefaultArgumentPromotion(Arg);
667 TheCall->setArg(i, Arg);
671 // Do special checking on direct calls to functions.
672 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
673 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
674 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
675 if (CheckFunctionCall(FDecl, TheCall.get()))
678 return TheCall.take();
681 Action::ExprResult Sema::
682 ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
683 SourceLocation RParenLoc, ExprTy *InitExpr) {
684 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
685 QualType literalType = QualType::getFromOpaquePtr(Ty);
686 // FIXME: put back this assert when initializers are worked out.
687 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
688 Expr *literalExpr = static_cast<Expr*>(InitExpr);
690 // FIXME: add more semantic analysis (C99 6.5.2.5).
691 if (CheckInitializerTypes(literalExpr, literalType))
694 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
695 if (isFileScope) { // 6.5.2.5p3
696 if (CheckForConstantInitializer(literalExpr, literalType))
699 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
702 Action::ExprResult Sema::
703 ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
704 SourceLocation RBraceLoc) {
705 Expr **InitList = reinterpret_cast<Expr**>(initlist);
707 // Semantic analysis for initializers is done by ActOnDeclarator() and
708 // CheckInitializer() - it requires knowledge of the object being intialized.
710 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
711 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
715 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
716 assert(VectorTy->isVectorType() && "Not a vector type!");
718 if (Ty->isVectorType() || Ty->isIntegerType()) {
719 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
720 Context.getTypeSize(Ty, SourceLocation()))
721 return Diag(R.getBegin(),
723 diag::err_invalid_conversion_between_vectors :
724 diag::err_invalid_conversion_between_vector_and_integer,
725 VectorTy.getAsString().c_str(),
726 Ty.getAsString().c_str(), R);
728 return Diag(R.getBegin(),
729 diag::err_invalid_conversion_between_vector_and_scalar,
730 VectorTy.getAsString().c_str(),
731 Ty.getAsString().c_str(), R);
736 Action::ExprResult Sema::
737 ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
738 SourceLocation RParenLoc, ExprTy *Op) {
739 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
741 Expr *castExpr = static_cast<Expr*>(Op);
742 QualType castType = QualType::getFromOpaquePtr(Ty);
744 UsualUnaryConversions(castExpr);
746 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
747 // type needs to be scalar.
748 if (!castType->isVoidType()) { // Cast to void allows any expr type.
749 if (!castType->isScalarType() && !castType->isVectorType())
750 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
751 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
752 if (!castExpr->getType()->isScalarType() &&
753 !castExpr->getType()->isVectorType())
754 return Diag(castExpr->getLocStart(),
755 diag::err_typecheck_expect_scalar_operand,
756 castExpr->getType().getAsString(),castExpr->getSourceRange());
758 if (castExpr->getType()->isVectorType()) {
759 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
760 castExpr->getType(), castType))
762 } else if (castType->isVectorType()) {
763 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
764 castType, castExpr->getType()))
768 return new CastExpr(castType, castExpr, LParenLoc);
771 /// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
772 /// In that case, lex = cond.
773 inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
774 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
775 UsualUnaryConversions(cond);
776 UsualUnaryConversions(lex);
777 UsualUnaryConversions(rex);
778 QualType condT = cond->getType();
779 QualType lexT = lex->getType();
780 QualType rexT = rex->getType();
782 // first, check the condition.
783 if (!condT->isScalarType()) { // C99 6.5.15p2
784 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
785 condT.getAsString());
789 // Now check the two expressions.
791 // If both operands have arithmetic type, do the usual arithmetic conversions
792 // to find a common type: C99 6.5.15p3,5.
793 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
794 UsualArithmeticConversions(lex, rex);
795 return lex->getType();
798 // If both operands are the same structure or union type, the result is that
800 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
801 if (const RecordType *RHSRT = rexT->getAsRecordType())
802 if (LHSRT->getDecl() == RHSRT->getDecl())
803 // "If both the operands have structure or union type, the result has
804 // that type." This implies that CV qualifiers are dropped.
805 return lexT.getUnqualifiedType();
808 // C99 6.5.15p5: "If both operands have void type, the result has void type."
809 if (lexT->isVoidType() && rexT->isVoidType())
810 return lexT.getUnqualifiedType();
812 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
813 // the type of the other operand."
814 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
815 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
818 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
819 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
822 // Handle the case where both operands are pointers before we handle null
823 // pointer constants in case both operands are null pointer constants.
824 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
825 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
826 // get the "pointed to" types
827 QualType lhptee = LHSPT->getPointeeType();
828 QualType rhptee = RHSPT->getPointeeType();
830 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
831 if (lhptee->isVoidType() &&
832 (rhptee->isObjectType() || rhptee->isIncompleteType())) {
833 // Figure out necessary qualifiers (C99 6.5.15p6)
834 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
835 QualType destType = Context.getPointerType(destPointee);
836 ImpCastExprToType(lex, destType); // add qualifiers if necessary
837 ImpCastExprToType(rex, destType); // promote to void*
840 if (rhptee->isVoidType() &&
841 (lhptee->isObjectType() || lhptee->isIncompleteType())) {
842 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
843 QualType destType = Context.getPointerType(destPointee);
844 ImpCastExprToType(lex, destType); // add qualifiers if necessary
845 ImpCastExprToType(rex, destType); // promote to void*
849 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
850 rhptee.getUnqualifiedType())) {
851 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
852 lexT.getAsString(), rexT.getAsString(),
853 lex->getSourceRange(), rex->getSourceRange());
854 // In this situation, we assume void* type. No especially good
855 // reason, but this is what gcc does, and we do have to pick
856 // to get a consistent AST.
857 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
858 ImpCastExprToType(lex, voidPtrTy);
859 ImpCastExprToType(rex, voidPtrTy);
862 // The pointer types are compatible.
863 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
864 // differently qualified versions of compatible types, the result type is
865 // a pointer to an appropriately qualified version of the *composite*
867 // FIXME: Need to return the composite type.
868 // FIXME: Need to add qualifiers
873 // Otherwise, the operands are not compatible.
874 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
875 lexT.getAsString(), rexT.getAsString(),
876 lex->getSourceRange(), rex->getSourceRange());
880 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
881 /// in the case of a the GNU conditional expr extension.
882 Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
883 SourceLocation ColonLoc,
884 ExprTy *Cond, ExprTy *LHS,
886 Expr *CondExpr = (Expr *) Cond;
887 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
889 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
890 // was the condition.
891 bool isLHSNull = LHSExpr == 0;
895 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
896 RHSExpr, QuestionLoc);
899 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
903 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
904 /// do not have a prototype. Arguments that have type float are promoted to
905 /// double. All other argument types are converted by UsualUnaryConversions().
906 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
907 QualType Ty = Expr->getType();
908 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
910 if (Ty == Context.FloatTy)
911 ImpCastExprToType(Expr, Context.DoubleTy);
913 UsualUnaryConversions(Expr);
916 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
917 void Sema::DefaultFunctionArrayConversion(Expr *&e) {
918 QualType t = e->getType();
919 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
921 if (const ReferenceType *ref = t->getAsReferenceType()) {
922 ImpCastExprToType(e, ref->getReferenceeType()); // C++ [expr]
925 if (t->isFunctionType())
926 ImpCastExprToType(e, Context.getPointerType(t));
927 else if (const ArrayType *ary = t->getAsArrayType()) {
928 // Make sure we don't lose qualifiers when dealing with typedefs. Example:
929 // typedef int arr[10];
934 QualType ELT = ary->getElementType();
935 // FIXME: Handle ASQualType
936 ELT = ELT.getQualifiedType(t.getCVRQualifiers()|ELT.getCVRQualifiers());
937 ImpCastExprToType(e, Context.getPointerType(ELT));
941 /// UsualUnaryConversions - Performs various conversions that are common to most
942 /// operators (C99 6.3). The conversions of array and function types are
943 /// sometimes surpressed. For example, the array->pointer conversion doesn't
944 /// apply if the array is an argument to the sizeof or address (&) operators.
945 /// In these instances, this routine should *not* be called.
946 Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
947 QualType Ty = Expr->getType();
948 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
950 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
951 ImpCastExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
952 Ty = Expr->getType();
954 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
955 ImpCastExprToType(Expr, Context.IntTy);
957 DefaultFunctionArrayConversion(Expr);
962 /// UsualArithmeticConversions - Performs various conversions that are common to
963 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
964 /// routine returns the first non-arithmetic type found. The client is
965 /// responsible for emitting appropriate error diagnostics.
966 /// FIXME: verify the conversion rules for "complex int" are consistent with GCC.
967 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
970 UsualUnaryConversions(lhsExpr);
971 UsualUnaryConversions(rhsExpr);
973 // For conversion purposes, we ignore any qualifiers.
974 // For example, "const float" and "float" are equivalent.
975 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
976 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
978 // If both types are identical, no conversion is needed.
982 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
983 // The caller can deal with this (e.g. pointer + int).
984 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
987 // At this point, we have two different arithmetic types.
989 // Handle complex types first (C99 6.3.1.8p1).
990 if (lhs->isComplexType() || rhs->isComplexType()) {
991 // if we have an integer operand, the result is the complex type.
992 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
993 // convert the rhs to the lhs complex type.
994 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
997 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
998 // convert the lhs to the rhs complex type.
999 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1002 // This handles complex/complex, complex/float, or float/complex.
1003 // When both operands are complex, the shorter operand is converted to the
1004 // type of the longer, and that is the type of the result. This corresponds
1005 // to what is done when combining two real floating-point operands.
1006 // The fun begins when size promotion occur across type domains.
1007 // From H&S 6.3.4: When one operand is complex and the other is a real
1008 // floating-point type, the less precise type is converted, within it's
1009 // real or complex domain, to the precision of the other type. For example,
1010 // when combining a "long double" with a "double _Complex", the
1011 // "double _Complex" is promoted to "long double _Complex".
1012 int result = Context.compareFloatingType(lhs, rhs);
1014 if (result > 0) { // The left side is bigger, convert rhs.
1015 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1017 ImpCastExprToType(rhsExpr, rhs);
1018 } else if (result < 0) { // The right side is bigger, convert lhs.
1019 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1021 ImpCastExprToType(lhsExpr, lhs);
1023 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1024 // domains match. This is a requirement for our implementation, C99
1025 // does not require this promotion.
1026 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1027 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
1029 ImpCastExprToType(lhsExpr, rhs);
1031 } else { // handle "_Complex double, double".
1033 ImpCastExprToType(rhsExpr, lhs);
1037 return lhs; // The domain/size match exactly.
1039 // Now handle "real" floating types (i.e. float, double, long double).
1040 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1041 // if we have an integer operand, the result is the real floating type.
1042 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
1043 // convert rhs to the lhs floating point type.
1044 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1047 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
1048 // convert lhs to the rhs floating point type.
1049 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1052 // We have two real floating types, float/complex combos were handled above.
1053 // Convert the smaller operand to the bigger result.
1054 int result = Context.compareFloatingType(lhs, rhs);
1056 if (result > 0) { // convert the rhs
1057 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1060 if (result < 0) { // convert the lhs
1061 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1064 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
1066 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1067 // Handle GCC complex int extension.
1068 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
1069 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
1071 if (lhsComplexInt && rhsComplexInt) {
1072 if (Context.maxIntegerType(lhsComplexInt->getElementType(),
1073 rhsComplexInt->getElementType()) == lhs) {
1075 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1079 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1081 } else if (lhsComplexInt && rhs->isIntegerType()) {
1082 // convert the rhs to the lhs complex type.
1083 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1085 } else if (rhsComplexInt && lhs->isIntegerType()) {
1086 // convert the lhs to the rhs complex type.
1087 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1091 // Finally, we have two differing integer types.
1092 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
1093 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1096 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1100 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
1101 // being closely modeled after the C99 spec:-). The odd characteristic of this
1102 // routine is it effectively iqnores the qualifiers on the top level pointee.
1103 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1104 // FIXME: add a couple examples in this comment.
1105 Sema::AssignConvertType
1106 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1107 QualType lhptee, rhptee;
1109 // get the "pointed to" type (ignoring qualifiers at the top level)
1110 lhptee = lhsType->getAsPointerType()->getPointeeType();
1111 rhptee = rhsType->getAsPointerType()->getPointeeType();
1113 // make sure we operate on the canonical type
1114 lhptee = lhptee.getCanonicalType();
1115 rhptee = rhptee.getCanonicalType();
1117 AssignConvertType ConvTy = Compatible;
1119 // C99 6.5.16.1p1: This following citation is common to constraints
1120 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1121 // qualifiers of the type *pointed to* by the right;
1122 // FIXME: Handle ASQualType
1123 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1124 rhptee.getCVRQualifiers())
1125 ConvTy = CompatiblePointerDiscardsQualifiers;
1127 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1128 // incomplete type and the other is a pointer to a qualified or unqualified
1129 // version of void...
1130 if (lhptee->isVoidType()) {
1131 if (rhptee->isObjectType() || rhptee->isIncompleteType())
1134 // As an extension, we allow cast to/from void* to function pointer.
1135 if (rhptee->isFunctionType())
1136 return FunctionVoidPointer;
1139 if (rhptee->isVoidType()) {
1140 if (lhptee->isObjectType() || lhptee->isIncompleteType())
1143 // As an extension, we allow cast to/from void* to function pointer.
1144 if (lhptee->isFunctionType())
1145 return FunctionVoidPointer;
1148 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1149 // unqualified versions of compatible types, ...
1150 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1151 rhptee.getUnqualifiedType()))
1152 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1156 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1157 /// has code to accommodate several GCC extensions when type checking
1158 /// pointers. Here are some objectionable examples that GCC considers warnings:
1162 /// struct foo *pfoo;
1164 /// pint = pshort; // warning: assignment from incompatible pointer type
1165 /// a = pint; // warning: assignment makes integer from pointer without a cast
1166 /// pint = a; // warning: assignment makes pointer from integer without a cast
1167 /// pint = pfoo; // warning: assignment from incompatible pointer type
1169 /// As a result, the code for dealing with pointers is more complex than the
1170 /// C99 spec dictates.
1171 /// Note: the warning above turn into errors when -pedantic-errors is enabled.
1173 Sema::AssignConvertType
1174 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
1175 // Get canonical types. We're not formatting these types, just comparing
1177 lhsType = lhsType.getCanonicalType();
1178 rhsType = rhsType.getCanonicalType();
1180 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
1181 return Compatible; // Common case: fast path an exact match.
1183 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1184 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
1186 return Incompatible;
1189 if (lhsType->isObjCQualifiedIdType()
1190 || rhsType->isObjCQualifiedIdType()) {
1191 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
1193 return Incompatible;
1196 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1197 // For OCUVector, allow vector splats; float -> <n x float>
1198 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1199 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1203 // If LHS and RHS are both vectors of integer or both vectors of floating
1204 // point types, and the total vector length is the same, allow the
1205 // conversion. This is a bitcast; no bits are changed but the result type
1207 if (getLangOptions().LaxVectorConversions &&
1208 lhsType->isVectorType() && rhsType->isVectorType()) {
1209 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1210 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1211 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1212 Context.getTypeSize(rhsType, SourceLocation()))
1216 return Incompatible;
1219 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
1222 if (lhsType->isPointerType()) {
1223 if (rhsType->isIntegerType())
1224 return IntToPointer;
1226 if (rhsType->isPointerType())
1227 return CheckPointerTypesForAssignment(lhsType, rhsType);
1228 return Incompatible;
1231 if (rhsType->isPointerType()) {
1232 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1233 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1234 return PointerToInt;
1236 if (lhsType->isPointerType())
1237 return CheckPointerTypesForAssignment(lhsType, rhsType);
1238 return Incompatible;
1241 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1242 if (Context.tagTypesAreCompatible(lhsType, rhsType))
1245 return Incompatible;
1248 Sema::AssignConvertType
1249 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1250 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1251 // a null pointer constant.
1252 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
1253 && rExpr->isNullPointerConstant(Context)) {
1254 ImpCastExprToType(rExpr, lhsType);
1257 // This check seems unnatural, however it is necessary to ensure the proper
1258 // conversion of functions/arrays. If the conversion were done for all
1259 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
1260 // expressions that surpress this implicit conversion (&, sizeof).
1262 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1263 // are better understood.
1264 if (!lhsType->isReferenceType())
1265 DefaultFunctionArrayConversion(rExpr);
1267 Sema::AssignConvertType result =
1268 CheckAssignmentConstraints(lhsType, rExpr->getType());
1270 // C99 6.5.16.1p2: The value of the right operand is converted to the
1271 // type of the assignment expression.
1272 if (rExpr->getType() != lhsType)
1273 ImpCastExprToType(rExpr, lhsType);
1277 Sema::AssignConvertType
1278 Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1279 return CheckAssignmentConstraints(lhsType, rhsType);
1282 QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1283 Diag(loc, diag::err_typecheck_invalid_operands,
1284 lex->getType().getAsString(), rex->getType().getAsString(),
1285 lex->getSourceRange(), rex->getSourceRange());
1289 inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1291 QualType lhsType = lex->getType(), rhsType = rex->getType();
1293 // make sure the vector types are identical.
1294 if (lhsType == rhsType)
1297 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1298 // promote the rhs to the vector type.
1299 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1300 if (V->getElementType().getCanonicalType().getTypePtr()
1301 == rhsType.getCanonicalType().getTypePtr()) {
1302 ImpCastExprToType(rex, lhsType);
1307 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1308 // promote the lhs to the vector type.
1309 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1310 if (V->getElementType().getCanonicalType().getTypePtr()
1311 == lhsType.getCanonicalType().getTypePtr()) {
1312 ImpCastExprToType(lex, rhsType);
1317 // You cannot convert between vector values of different size.
1318 Diag(loc, diag::err_typecheck_vector_not_convertable,
1319 lex->getType().getAsString(), rex->getType().getAsString(),
1320 lex->getSourceRange(), rex->getSourceRange());
1324 inline QualType Sema::CheckMultiplyDivideOperands(
1325 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1327 QualType lhsType = lex->getType(), rhsType = rex->getType();
1329 if (lhsType->isVectorType() || rhsType->isVectorType())
1330 return CheckVectorOperands(loc, lex, rex);
1332 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1334 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1336 return InvalidOperands(loc, lex, rex);
1339 inline QualType Sema::CheckRemainderOperands(
1340 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1342 QualType lhsType = lex->getType(), rhsType = rex->getType();
1344 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1346 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1348 return InvalidOperands(loc, lex, rex);
1351 inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
1352 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1354 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1355 return CheckVectorOperands(loc, lex, rex);
1357 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1359 // handle the common case first (both operands are arithmetic).
1360 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1363 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1364 return lex->getType();
1365 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1366 return rex->getType();
1367 return InvalidOperands(loc, lex, rex);
1370 inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
1371 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1373 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1374 return CheckVectorOperands(loc, lex, rex);
1376 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1378 // Enforce type constraints: C99 6.5.6p3.
1380 // Handle the common case first (both operands are arithmetic).
1381 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1384 // Either ptr - int or ptr - ptr.
1385 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1386 QualType lpointee = LHSPTy->getPointeeType();
1388 // The LHS must be an object type, not incomplete, function, etc.
1389 if (!lpointee->isObjectType()) {
1390 // Handle the GNU void* extension.
1391 if (lpointee->isVoidType()) {
1392 Diag(loc, diag::ext_gnu_void_ptr,
1393 lex->getSourceRange(), rex->getSourceRange());
1395 Diag(loc, diag::err_typecheck_sub_ptr_object,
1396 lex->getType().getAsString(), lex->getSourceRange());
1401 // The result type of a pointer-int computation is the pointer type.
1402 if (rex->getType()->isIntegerType())
1403 return lex->getType();
1405 // Handle pointer-pointer subtractions.
1406 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1407 QualType rpointee = RHSPTy->getPointeeType();
1409 // RHS must be an object type, unless void (GNU).
1410 if (!rpointee->isObjectType()) {
1411 // Handle the GNU void* extension.
1412 if (rpointee->isVoidType()) {
1413 if (!lpointee->isVoidType())
1414 Diag(loc, diag::ext_gnu_void_ptr,
1415 lex->getSourceRange(), rex->getSourceRange());
1417 Diag(loc, diag::err_typecheck_sub_ptr_object,
1418 rex->getType().getAsString(), rex->getSourceRange());
1423 // Pointee types must be compatible.
1424 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1425 rpointee.getUnqualifiedType())) {
1426 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1427 lex->getType().getAsString(), rex->getType().getAsString(),
1428 lex->getSourceRange(), rex->getSourceRange());
1432 return Context.getPointerDiffType();
1436 return InvalidOperands(loc, lex, rex);
1439 inline QualType Sema::CheckShiftOperands( // C99 6.5.7
1440 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1441 // C99 6.5.7p2: Each of the operands shall have integer type.
1442 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1443 return InvalidOperands(loc, lex, rex);
1445 // Shifts don't perform usual arithmetic conversions, they just do integer
1446 // promotions on each operand. C99 6.5.7p3
1448 UsualUnaryConversions(lex);
1449 UsualUnaryConversions(rex);
1451 // "The type of the result is that of the promoted left operand."
1452 return lex->getType();
1455 inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1456 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
1458 // C99 6.5.8p3 / C99 6.5.9p4
1459 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1460 UsualArithmeticConversions(lex, rex);
1462 UsualUnaryConversions(lex);
1463 UsualUnaryConversions(rex);
1465 QualType lType = lex->getType();
1466 QualType rType = rex->getType();
1468 // For non-floating point types, check for self-comparisons of the form
1469 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1470 // often indicate logic errors in the program.
1471 if (!lType->isFloatingType()) {
1472 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1473 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1474 if (DRL->getDecl() == DRR->getDecl())
1475 Diag(loc, diag::warn_selfcomparison);
1479 if (lType->isRealType() && rType->isRealType())
1480 return Context.IntTy;
1482 // Check for comparisons of floating point operands using != and ==.
1483 if (lType->isFloatingType()) {
1484 assert (rType->isFloatingType());
1485 CheckFloatComparison(loc,lex,rex);
1488 if (lType->isArithmeticType() && rType->isArithmeticType())
1489 return Context.IntTy;
1492 bool LHSIsNull = lex->isNullPointerConstant(Context);
1493 bool RHSIsNull = rex->isNullPointerConstant(Context);
1495 // All of the following pointer related warnings are GCC extensions, except
1496 // when handling null pointer constants. One day, we can consider making them
1497 // errors (when -pedantic-errors is enabled).
1498 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
1499 QualType lpointee = lType->getAsPointerType()->getPointeeType();
1500 QualType rpointee = rType->getAsPointerType()->getPointeeType();
1502 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1503 !lpointee->isVoidType() && !lpointee->isVoidType() &&
1504 !Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1505 rpointee.getUnqualifiedType())) {
1506 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1507 lType.getAsString(), rType.getAsString(),
1508 lex->getSourceRange(), rex->getSourceRange());
1510 ImpCastExprToType(rex, lType); // promote the pointer to pointer
1511 return Context.IntTy;
1513 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1514 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1515 ImpCastExprToType(rex, lType);
1516 return Context.IntTy;
1518 if (lType->isPointerType() && rType->isIntegerType()) {
1520 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1521 lType.getAsString(), rType.getAsString(),
1522 lex->getSourceRange(), rex->getSourceRange());
1523 ImpCastExprToType(rex, lType); // promote the integer to pointer
1524 return Context.IntTy;
1526 if (lType->isIntegerType() && rType->isPointerType()) {
1528 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1529 lType.getAsString(), rType.getAsString(),
1530 lex->getSourceRange(), rex->getSourceRange());
1531 ImpCastExprToType(lex, rType); // promote the integer to pointer
1532 return Context.IntTy;
1534 return InvalidOperands(loc, lex, rex);
1537 inline QualType Sema::CheckBitwiseOperands(
1538 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1540 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1541 return CheckVectorOperands(loc, lex, rex);
1543 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1545 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1547 return InvalidOperands(loc, lex, rex);
1550 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1551 Expr *&lex, Expr *&rex, SourceLocation loc)
1553 UsualUnaryConversions(lex);
1554 UsualUnaryConversions(rex);
1556 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1557 return Context.IntTy;
1558 return InvalidOperands(loc, lex, rex);
1561 inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1562 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
1564 QualType lhsType = lex->getType();
1565 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1566 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1568 switch (mlval) { // C99 6.5.16p2
1569 case Expr::MLV_Valid:
1571 case Expr::MLV_ConstQualified:
1572 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1574 case Expr::MLV_ArrayType:
1575 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1576 lhsType.getAsString(), lex->getSourceRange());
1578 case Expr::MLV_NotObjectType:
1579 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1580 lhsType.getAsString(), lex->getSourceRange());
1582 case Expr::MLV_InvalidExpression:
1583 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1584 lex->getSourceRange());
1586 case Expr::MLV_IncompleteType:
1587 case Expr::MLV_IncompleteVoidType:
1588 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1589 lhsType.getAsString(), lex->getSourceRange());
1591 case Expr::MLV_DuplicateVectorComponents:
1592 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1593 lex->getSourceRange());
1597 AssignConvertType ConvTy;
1598 if (compoundType.isNull())
1599 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1601 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1603 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1607 // C99 6.5.16p3: The type of an assignment expression is the type of the
1608 // left operand unless the left operand has qualified type, in which case
1609 // it is the unqualified version of the type of the left operand.
1610 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1611 // is converted to the type of the assignment expression (above).
1612 // C++ 5.17p1: the type of the assignment expression is that of its left
1614 return lhsType.getUnqualifiedType();
1617 inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1618 Expr *&lex, Expr *&rex, SourceLocation loc) {
1619 UsualUnaryConversions(rex);
1620 return rex->getType();
1623 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1624 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1625 QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1626 QualType resType = op->getType();
1627 assert(!resType.isNull() && "no type for increment/decrement expression");
1629 // C99 6.5.2.4p1: We allow complex as a GCC extension.
1630 if (const PointerType *pt = resType->getAsPointerType()) {
1631 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1632 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1633 resType.getAsString(), op->getSourceRange());
1636 } else if (!resType->isRealType()) {
1637 if (resType->isComplexType())
1638 // C99 does not support ++/-- on complex types.
1639 Diag(OpLoc, diag::ext_integer_increment_complex,
1640 resType.getAsString(), op->getSourceRange());
1642 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1643 resType.getAsString(), op->getSourceRange());
1647 // At this point, we know we have a real, complex or pointer type.
1648 // Now make sure the operand is a modifiable lvalue.
1649 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1650 if (mlval != Expr::MLV_Valid) {
1651 // FIXME: emit a more precise diagnostic...
1652 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1653 op->getSourceRange());
1659 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
1660 /// This routine allows us to typecheck complex/recursive expressions
1661 /// where the declaration is needed for type checking. Here are some
1662 /// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1663 static ValueDecl *getPrimaryDecl(Expr *e) {
1664 switch (e->getStmtClass()) {
1665 case Stmt::DeclRefExprClass:
1666 return cast<DeclRefExpr>(e)->getDecl();
1667 case Stmt::MemberExprClass:
1668 // Fields cannot be declared with a 'register' storage class.
1669 // &X->f is always ok, even if X is declared register.
1670 if (cast<MemberExpr>(e)->isArrow())
1672 return getPrimaryDecl(cast<MemberExpr>(e)->getBase());
1673 case Stmt::ArraySubscriptExprClass: {
1674 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1676 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(e)->getBase());
1677 if (!VD || VD->getType()->isPointerType())
1682 case Stmt::UnaryOperatorClass:
1683 return getPrimaryDecl(cast<UnaryOperator>(e)->getSubExpr());
1684 case Stmt::ParenExprClass:
1685 return getPrimaryDecl(cast<ParenExpr>(e)->getSubExpr());
1686 case Stmt::ImplicitCastExprClass:
1687 // &X[4] when X is an array, has an implicit cast from array to pointer.
1688 return getPrimaryDecl(cast<ImplicitCastExpr>(e)->getSubExpr());
1694 /// CheckAddressOfOperand - The operand of & must be either a function
1695 /// designator or an lvalue designating an object. If it is an lvalue, the
1696 /// object cannot be declared with storage class register or be a bit field.
1697 /// Note: The usual conversions are *not* applied to the operand of the &
1698 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1699 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1700 if (getLangOptions().C99) {
1701 // Implement C99-only parts of addressof rules.
1702 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1703 if (uOp->getOpcode() == UnaryOperator::Deref)
1704 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1705 // (assuming the deref expression is valid).
1706 return uOp->getSubExpr()->getType();
1708 // Technically, there should be a check for array subscript
1709 // expressions here, but the result of one is always an lvalue anyway.
1711 ValueDecl *dcl = getPrimaryDecl(op);
1712 Expr::isLvalueResult lval = op->isLvalue();
1714 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1715 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1716 // FIXME: emit more specific diag...
1717 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1718 op->getSourceRange());
1721 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1722 if (MemExpr->getMemberDecl()->isBitField()) {
1723 Diag(OpLoc, diag::err_typecheck_address_of,
1724 std::string("bit-field"), op->getSourceRange());
1727 // Check for Apple extension for accessing vector components.
1728 } else if (isa<ArraySubscriptExpr>(op) &&
1729 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1730 Diag(OpLoc, diag::err_typecheck_address_of,
1731 std::string("vector"), op->getSourceRange());
1733 } else if (dcl) { // C99 6.5.3.2p1
1734 // We have an lvalue with a decl. Make sure the decl is not declared
1735 // with the register storage-class specifier.
1736 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1737 if (vd->getStorageClass() == VarDecl::Register) {
1738 Diag(OpLoc, diag::err_typecheck_address_of,
1739 std::string("register variable"), op->getSourceRange());
1743 assert(0 && "Unknown/unexpected decl type");
1745 // If the operand has type "type", the result has type "pointer to type".
1746 return Context.getPointerType(op->getType());
1749 QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1750 UsualUnaryConversions(op);
1751 QualType qType = op->getType();
1753 if (const PointerType *PT = qType->getAsPointerType()) {
1754 // Note that per both C89 and C99, this is always legal, even
1755 // if ptype is an incomplete type or void.
1756 // It would be possible to warn about dereferencing a
1757 // void pointer, but it's completely well-defined,
1758 // and such a warning is unlikely to catch any mistakes.
1759 return PT->getPointeeType();
1761 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1762 qType.getAsString(), op->getSourceRange());
1766 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1767 tok::TokenKind Kind) {
1768 BinaryOperator::Opcode Opc;
1770 default: assert(0 && "Unknown binop!");
1771 case tok::star: Opc = BinaryOperator::Mul; break;
1772 case tok::slash: Opc = BinaryOperator::Div; break;
1773 case tok::percent: Opc = BinaryOperator::Rem; break;
1774 case tok::plus: Opc = BinaryOperator::Add; break;
1775 case tok::minus: Opc = BinaryOperator::Sub; break;
1776 case tok::lessless: Opc = BinaryOperator::Shl; break;
1777 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1778 case tok::lessequal: Opc = BinaryOperator::LE; break;
1779 case tok::less: Opc = BinaryOperator::LT; break;
1780 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1781 case tok::greater: Opc = BinaryOperator::GT; break;
1782 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1783 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1784 case tok::amp: Opc = BinaryOperator::And; break;
1785 case tok::caret: Opc = BinaryOperator::Xor; break;
1786 case tok::pipe: Opc = BinaryOperator::Or; break;
1787 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1788 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1789 case tok::equal: Opc = BinaryOperator::Assign; break;
1790 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1791 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1792 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1793 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1794 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1795 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1796 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1797 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1798 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1799 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1800 case tok::comma: Opc = BinaryOperator::Comma; break;
1805 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1806 tok::TokenKind Kind) {
1807 UnaryOperator::Opcode Opc;
1809 default: assert(0 && "Unknown unary op!");
1810 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1811 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1812 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1813 case tok::star: Opc = UnaryOperator::Deref; break;
1814 case tok::plus: Opc = UnaryOperator::Plus; break;
1815 case tok::minus: Opc = UnaryOperator::Minus; break;
1816 case tok::tilde: Opc = UnaryOperator::Not; break;
1817 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1818 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1819 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1820 case tok::kw___real: Opc = UnaryOperator::Real; break;
1821 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1822 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1827 // Binary Operators. 'Tok' is the token for the operator.
1828 Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1829 ExprTy *LHS, ExprTy *RHS) {
1830 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1831 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1833 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1834 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
1836 QualType ResultTy; // Result type of the binary operator.
1837 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1841 assert(0 && "Unknown binary expr!");
1842 case BinaryOperator::Assign:
1843 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1845 case BinaryOperator::Mul:
1846 case BinaryOperator::Div:
1847 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1849 case BinaryOperator::Rem:
1850 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1852 case BinaryOperator::Add:
1853 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1855 case BinaryOperator::Sub:
1856 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1858 case BinaryOperator::Shl:
1859 case BinaryOperator::Shr:
1860 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1862 case BinaryOperator::LE:
1863 case BinaryOperator::LT:
1864 case BinaryOperator::GE:
1865 case BinaryOperator::GT:
1866 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
1868 case BinaryOperator::EQ:
1869 case BinaryOperator::NE:
1870 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
1872 case BinaryOperator::And:
1873 case BinaryOperator::Xor:
1874 case BinaryOperator::Or:
1875 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1877 case BinaryOperator::LAnd:
1878 case BinaryOperator::LOr:
1879 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1881 case BinaryOperator::MulAssign:
1882 case BinaryOperator::DivAssign:
1883 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
1884 if (!CompTy.isNull())
1885 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1887 case BinaryOperator::RemAssign:
1888 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
1889 if (!CompTy.isNull())
1890 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1892 case BinaryOperator::AddAssign:
1893 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
1894 if (!CompTy.isNull())
1895 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1897 case BinaryOperator::SubAssign:
1898 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
1899 if (!CompTy.isNull())
1900 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1902 case BinaryOperator::ShlAssign:
1903 case BinaryOperator::ShrAssign:
1904 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
1905 if (!CompTy.isNull())
1906 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1908 case BinaryOperator::AndAssign:
1909 case BinaryOperator::XorAssign:
1910 case BinaryOperator::OrAssign:
1911 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
1912 if (!CompTy.isNull())
1913 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1915 case BinaryOperator::Comma:
1916 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1919 if (ResultTy.isNull())
1921 if (CompTy.isNull())
1922 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
1924 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
1927 // Unary Operators. 'Tok' is the token for the operator.
1928 Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1930 Expr *Input = (Expr*)input;
1931 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1932 QualType resultType;
1935 assert(0 && "Unimplemented unary expr!");
1936 case UnaryOperator::PreInc:
1937 case UnaryOperator::PreDec:
1938 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1940 case UnaryOperator::AddrOf:
1941 resultType = CheckAddressOfOperand(Input, OpLoc);
1943 case UnaryOperator::Deref:
1944 DefaultFunctionArrayConversion(Input);
1945 resultType = CheckIndirectionOperand(Input, OpLoc);
1947 case UnaryOperator::Plus:
1948 case UnaryOperator::Minus:
1949 UsualUnaryConversions(Input);
1950 resultType = Input->getType();
1951 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1952 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1953 resultType.getAsString());
1955 case UnaryOperator::Not: // bitwise complement
1956 UsualUnaryConversions(Input);
1957 resultType = Input->getType();
1958 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1959 if (!resultType->isIntegerType()) {
1960 if (resultType->isComplexType())
1961 // C99 does not support '~' for complex conjugation.
1962 Diag(OpLoc, diag::ext_integer_complement_complex,
1963 resultType.getAsString());
1965 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1966 resultType.getAsString());
1969 case UnaryOperator::LNot: // logical negation
1970 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1971 DefaultFunctionArrayConversion(Input);
1972 resultType = Input->getType();
1973 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1974 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1975 resultType.getAsString());
1976 // LNot always has type int. C99 6.5.3.3p5.
1977 resultType = Context.IntTy;
1979 case UnaryOperator::SizeOf:
1980 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1982 case UnaryOperator::AlignOf:
1983 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1985 case UnaryOperator::Real:
1986 case UnaryOperator::Imag:
1987 resultType = CheckRealImagOperand(Input, OpLoc);
1989 case UnaryOperator::Extension:
1990 resultType = Input->getType();
1993 if (resultType.isNull())
1995 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1998 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1999 Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
2000 SourceLocation LabLoc,
2001 IdentifierInfo *LabelII) {
2002 // Look up the record for this label identifier.
2003 LabelStmt *&LabelDecl = LabelMap[LabelII];
2005 // If we haven't seen this label yet, create a forward reference.
2007 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2009 // Create the AST node. The address of a label always has type 'void*'.
2010 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2011 Context.getPointerType(Context.VoidTy));
2014 Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
2015 SourceLocation RPLoc) { // "({..})"
2016 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2017 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2018 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2020 // FIXME: there are a variety of strange constraints to enforce here, for
2021 // example, it is not possible to goto into a stmt expression apparently.
2022 // More semantic analysis is needed.
2024 // FIXME: the last statement in the compount stmt has its value used. We
2025 // should not warn about it being unused.
2027 // If there are sub stmts in the compound stmt, take the type of the last one
2028 // as the type of the stmtexpr.
2029 QualType Ty = Context.VoidTy;
2031 if (!Compound->body_empty())
2032 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2033 Ty = LastExpr->getType();
2035 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2038 Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
2039 SourceLocation TypeLoc,
2041 OffsetOfComponent *CompPtr,
2042 unsigned NumComponents,
2043 SourceLocation RPLoc) {
2044 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2045 assert(!ArgTy.isNull() && "Missing type argument!");
2047 // We must have at least one component that refers to the type, and the first
2048 // one is known to be a field designator. Verify that the ArgTy represents
2049 // a struct/union/class.
2050 if (!ArgTy->isRecordType())
2051 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2053 // Otherwise, create a compound literal expression as the base, and
2054 // iteratively process the offsetof designators.
2055 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
2057 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2058 // GCC extension, diagnose them.
2059 if (NumComponents != 1)
2060 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2061 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2063 for (unsigned i = 0; i != NumComponents; ++i) {
2064 const OffsetOfComponent &OC = CompPtr[i];
2065 if (OC.isBrackets) {
2066 // Offset of an array sub-field. TODO: Should we allow vector elements?
2067 const ArrayType *AT = Res->getType()->getAsArrayType();
2070 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2071 Res->getType().getAsString());
2074 // FIXME: C++: Verify that operator[] isn't overloaded.
2077 Expr *Idx = static_cast<Expr*>(OC.U.E);
2078 if (!Idx->getType()->isIntegerType())
2079 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2080 Idx->getSourceRange());
2082 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2086 const RecordType *RC = Res->getType()->getAsRecordType();
2089 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2090 Res->getType().getAsString());
2093 // Get the decl corresponding to this.
2094 RecordDecl *RD = RC->getDecl();
2095 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2097 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2098 OC.U.IdentInfo->getName(),
2099 SourceRange(OC.LocStart, OC.LocEnd));
2101 // FIXME: C++: Verify that MemberDecl isn't a static field.
2102 // FIXME: Verify that MemberDecl isn't a bitfield.
2103 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2105 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
2108 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2113 Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
2114 TypeTy *arg1, TypeTy *arg2,
2115 SourceLocation RPLoc) {
2116 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2117 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2119 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2121 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
2124 Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
2125 ExprTy *expr1, ExprTy *expr2,
2126 SourceLocation RPLoc) {
2127 Expr *CondExpr = static_cast<Expr*>(cond);
2128 Expr *LHSExpr = static_cast<Expr*>(expr1);
2129 Expr *RHSExpr = static_cast<Expr*>(expr2);
2131 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2133 // The conditional expression is required to be a constant expression.
2134 llvm::APSInt condEval(32);
2135 SourceLocation ExpLoc;
2136 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2137 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2138 CondExpr->getSourceRange());
2140 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2141 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2143 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2146 /// ExprsMatchFnType - return true if the Exprs in array Args have
2147 /// QualTypes that match the QualTypes of the arguments of the FnType.
2148 /// The number of arguments has already been validated to match the number of
2149 /// arguments in FnType.
2150 static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
2151 unsigned NumParams = FnType->getNumArgs();
2152 for (unsigned i = 0; i != NumParams; ++i)
2153 if (Args[i]->getType().getCanonicalType() !=
2154 FnType->getArgType(i).getCanonicalType())
2159 Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2160 SourceLocation *CommaLocs,
2161 SourceLocation BuiltinLoc,
2162 SourceLocation RParenLoc) {
2163 // __builtin_overload requires at least 2 arguments
2165 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2166 SourceRange(BuiltinLoc, RParenLoc));
2168 // The first argument is required to be a constant expression. It tells us
2169 // the number of arguments to pass to each of the functions to be overloaded.
2170 Expr **Args = reinterpret_cast<Expr**>(args);
2171 Expr *NParamsExpr = Args[0];
2172 llvm::APSInt constEval(32);
2173 SourceLocation ExpLoc;
2174 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2175 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2176 NParamsExpr->getSourceRange());
2178 // Verify that the number of parameters is > 0
2179 unsigned NumParams = constEval.getZExtValue();
2181 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2182 NParamsExpr->getSourceRange());
2183 // Verify that we have at least 1 + NumParams arguments to the builtin.
2184 if ((NumParams + 1) > NumArgs)
2185 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2186 SourceRange(BuiltinLoc, RParenLoc));
2188 // Figure out the return type, by matching the args to one of the functions
2189 // listed after the parameters.
2190 OverloadExpr *OE = 0;
2191 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2192 // UsualUnaryConversions will convert the function DeclRefExpr into a
2193 // pointer to function.
2194 Expr *Fn = UsualUnaryConversions(Args[i]);
2195 FunctionTypeProto *FnType = 0;
2196 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2197 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2198 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2201 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2202 // parameters, and the number of parameters must match the value passed to
2204 if (!FnType || (FnType->getNumArgs() != NumParams))
2205 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2206 Fn->getSourceRange());
2208 // Scan the parameter list for the FunctionType, checking the QualType of
2209 // each parameter against the QualTypes of the arguments to the builtin.
2210 // If they match, return a new OverloadExpr.
2211 if (ExprsMatchFnType(Args+1, FnType)) {
2213 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2214 OE->getFn()->getSourceRange());
2215 // Remember our match, and continue processing the remaining arguments
2216 // to catch any errors.
2217 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2218 BuiltinLoc, RParenLoc);
2221 // Return the newly created OverloadExpr node, if we succeded in matching
2222 // exactly one of the candidate functions.
2226 // If we didn't find a matching function Expr in the __builtin_overload list
2227 // the return an error.
2228 std::string typeNames;
2229 for (unsigned i = 0; i != NumParams; ++i) {
2230 if (i != 0) typeNames += ", ";
2231 typeNames += Args[i+1]->getType().getAsString();
2234 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2235 SourceRange(BuiltinLoc, RParenLoc));
2238 Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2239 ExprTy *expr, TypeTy *type,
2240 SourceLocation RPLoc) {
2241 Expr *E = static_cast<Expr*>(expr);
2242 QualType T = QualType::getFromOpaquePtr(type);
2244 InitBuiltinVaListType();
2246 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2248 return Diag(E->getLocStart(),
2249 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2250 E->getType().getAsString(),
2251 E->getSourceRange());
2253 // FIXME: Warn if a non-POD type is passed in.
2255 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2258 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2260 QualType DstType, QualType SrcType,
2261 Expr *SrcExpr, const char *Flavor) {
2262 // Decode the result (notice that AST's are still created for extensions).
2263 bool isInvalid = false;
2266 default: assert(0 && "Unknown conversion type");
2267 case Compatible: return false;
2269 DiagKind = diag::ext_typecheck_convert_pointer_int;
2272 DiagKind = diag::ext_typecheck_convert_int_pointer;
2274 case IncompatiblePointer:
2275 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2277 case FunctionVoidPointer:
2278 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2280 case CompatiblePointerDiscardsQualifiers:
2281 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2284 DiagKind = diag::err_typecheck_convert_incompatible;
2289 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2290 SrcExpr->getSourceRange());