Amazing that there are still issues with the fields of anonymous struct/unions..
[clang.git] / lib / Sema / SemaExpr.cpp
blob2429c75880e133766239f002d61aab0f037eef7a
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/AnalysisBasedWarnings.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Designator.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Template.h"
39 using namespace clang;
40 using namespace sema;
43 /// \brief Determine whether the use of this declaration is valid, and
44 /// emit any corresponding diagnostics.
45 ///
46 /// This routine diagnoses various problems with referencing
47 /// declarations that can occur when using a declaration. For example,
48 /// it might warn if a deprecated or unavailable declaration is being
49 /// used, or produce an error (and return true) if a C++0x deleted
50 /// function is being used.
51 ///
52 /// If IgnoreDeprecated is set to true, this should not warn about deprecated
53 /// decls.
54 ///
55 /// \returns true if there was an error (this declaration cannot be
56 /// referenced), false otherwise.
57 ///
58 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
59 bool UnknownObjCClass) {
60 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
70 // Clear out the list of suppressed diagnostics, so that we don't emit
71 // them again for this specialization. However, we don't remove this
72 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
78 // See if the decl is deprecated.
79 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
80 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
82 // See if the decl is unavailable
83 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
84 if (UA->getMessage().empty()) {
85 if (!UnknownObjCClass)
86 Diag(Loc, diag::err_unavailable) << D->getDeclName();
87 else
88 Diag(Loc, diag::warn_unavailable_fwdclass_message)
89 << D->getDeclName();
91 else
92 Diag(Loc, diag::err_unavailable_message)
93 << D->getDeclName() << UA->getMessage();
94 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
97 // See if this is a deleted function.
98 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
99 if (FD->isDeleted()) {
100 Diag(Loc, diag::err_deleted_function_use);
101 Diag(D->getLocation(), diag::note_unavailable_here) << true;
102 return true;
106 // Warn if this is used but marked unused.
107 if (D->hasAttr<UnusedAttr>())
108 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
110 return false;
113 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
114 /// (and other functions in future), which have been declared with sentinel
115 /// attribute. It warns if call does not have the sentinel argument.
117 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
118 Expr **Args, unsigned NumArgs) {
119 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
120 if (!attr)
121 return;
123 // FIXME: In C++0x, if any of the arguments are parameter pack
124 // expansions, we can't check for the sentinel now.
125 int sentinelPos = attr->getSentinel();
126 int nullPos = attr->getNullPos();
128 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
129 // base class. Then we won't be needing two versions of the same code.
130 unsigned int i = 0;
131 bool warnNotEnoughArgs = false;
132 int isMethod = 0;
133 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
134 // skip over named parameters.
135 ObjCMethodDecl::param_iterator P, E = MD->param_end();
136 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
137 if (nullPos)
138 --nullPos;
139 else
140 ++i;
142 warnNotEnoughArgs = (P != E || i >= NumArgs);
143 isMethod = 1;
144 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
145 // skip over named parameters.
146 ObjCMethodDecl::param_iterator P, E = FD->param_end();
147 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
148 if (nullPos)
149 --nullPos;
150 else
151 ++i;
153 warnNotEnoughArgs = (P != E || i >= NumArgs);
154 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
155 // block or function pointer call.
156 QualType Ty = V->getType();
157 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
158 const FunctionType *FT = Ty->isFunctionPointerType()
159 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
160 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
161 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
162 unsigned NumArgsInProto = Proto->getNumArgs();
163 unsigned k;
164 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
165 if (nullPos)
166 --nullPos;
167 else
168 ++i;
170 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
172 if (Ty->isBlockPointerType())
173 isMethod = 2;
174 } else
175 return;
176 } else
177 return;
179 if (warnNotEnoughArgs) {
180 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
182 return;
184 int sentinel = i;
185 while (sentinelPos > 0 && i < NumArgs-1) {
186 --sentinelPos;
187 ++i;
189 if (sentinelPos > 0) {
190 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
191 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
192 return;
194 while (i < NumArgs-1) {
195 ++i;
196 ++sentinel;
198 Expr *sentinelExpr = Args[sentinel];
199 if (!sentinelExpr) return;
200 if (sentinelExpr->isTypeDependent()) return;
201 if (sentinelExpr->isValueDependent()) return;
203 // nullptr_t is always treated as null.
204 if (sentinelExpr->getType()->isNullPtrType()) return;
206 if (sentinelExpr->getType()->isAnyPointerType() &&
207 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
208 Expr::NPC_ValueDependentIsNull))
209 return;
211 // Unfortunately, __null has type 'int'.
212 if (isa<GNUNullExpr>(sentinelExpr)) return;
214 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
215 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
218 SourceRange Sema::getExprRange(ExprTy *E) const {
219 Expr *Ex = (Expr *)E;
220 return Ex? Ex->getSourceRange() : SourceRange();
223 //===----------------------------------------------------------------------===//
224 // Standard Promotions and Conversions
225 //===----------------------------------------------------------------------===//
227 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
228 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
229 QualType Ty = E->getType();
230 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
232 if (Ty->isFunctionType())
233 ImpCastExprToType(E, Context.getPointerType(Ty),
234 CK_FunctionToPointerDecay);
235 else if (Ty->isArrayType()) {
236 // In C90 mode, arrays only promote to pointers if the array expression is
237 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
238 // type 'array of type' is converted to an expression that has type 'pointer
239 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
240 // that has type 'array of type' ...". The relevant change is "an lvalue"
241 // (C90) to "an expression" (C99).
243 // C++ 4.2p1:
244 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
245 // T" can be converted to an rvalue of type "pointer to T".
247 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
248 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
249 CK_ArrayToPointerDecay);
253 void Sema::DefaultLvalueConversion(Expr *&E) {
254 // C++ [conv.lval]p1:
255 // A glvalue of a non-function, non-array type T can be
256 // converted to a prvalue.
257 if (!E->isGLValue()) return;
259 QualType T = E->getType();
260 assert(!T.isNull() && "r-value conversion on typeless expression?");
262 // Create a load out of an ObjCProperty l-value, if necessary.
263 if (E->getObjectKind() == OK_ObjCProperty) {
264 ConvertPropertyForRValue(E);
265 if (!E->isGLValue())
266 return;
269 // We don't want to throw lvalue-to-rvalue casts on top of
270 // expressions of certain types in C++.
271 if (getLangOptions().CPlusPlus &&
272 (E->getType() == Context.OverloadTy ||
273 T->isDependentType() ||
274 T->isRecordType()))
275 return;
277 // The C standard is actually really unclear on this point, and
278 // DR106 tells us what the result should be but not why. It's
279 // generally best to say that void types just doesn't undergo
280 // lvalue-to-rvalue at all. Note that expressions of unqualified
281 // 'void' type are never l-values, but qualified void can be.
282 if (T->isVoidType())
283 return;
285 // C++ [conv.lval]p1:
286 // [...] If T is a non-class type, the type of the prvalue is the
287 // cv-unqualified version of T. Otherwise, the type of the
288 // rvalue is T.
290 // C99 6.3.2.1p2:
291 // If the lvalue has qualified type, the value has the unqualified
292 // version of the type of the lvalue; otherwise, the value has the
293 // type of the lvalue.
294 if (T.hasQualifiers())
295 T = T.getUnqualifiedType();
297 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
298 E, 0, VK_RValue);
301 void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
302 DefaultFunctionArrayConversion(E);
303 DefaultLvalueConversion(E);
307 /// UsualUnaryConversions - Performs various conversions that are common to most
308 /// operators (C99 6.3). The conversions of array and function types are
309 /// sometimes surpressed. For example, the array->pointer conversion doesn't
310 /// apply if the array is an argument to the sizeof or address (&) operators.
311 /// In these instances, this routine should *not* be called.
312 Expr *Sema::UsualUnaryConversions(Expr *&E) {
313 // First, convert to an r-value.
314 DefaultFunctionArrayLvalueConversion(E);
316 QualType Ty = E->getType();
317 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
319 // Try to perform integral promotions if the object has a theoretically
320 // promotable type.
321 if (Ty->isIntegralOrUnscopedEnumerationType()) {
322 // C99 6.3.1.1p2:
324 // The following may be used in an expression wherever an int or
325 // unsigned int may be used:
326 // - an object or expression with an integer type whose integer
327 // conversion rank is less than or equal to the rank of int
328 // and unsigned int.
329 // - A bit-field of type _Bool, int, signed int, or unsigned int.
331 // If an int can represent all values of the original type, the
332 // value is converted to an int; otherwise, it is converted to an
333 // unsigned int. These are called the integer promotions. All
334 // other types are unchanged by the integer promotions.
336 QualType PTy = Context.isPromotableBitField(E);
337 if (!PTy.isNull()) {
338 ImpCastExprToType(E, PTy, CK_IntegralCast);
339 return E;
341 if (Ty->isPromotableIntegerType()) {
342 QualType PT = Context.getPromotedIntegerType(Ty);
343 ImpCastExprToType(E, PT, CK_IntegralCast);
344 return E;
348 return E;
351 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
352 /// do not have a prototype. Arguments that have type float are promoted to
353 /// double. All other argument types are converted by UsualUnaryConversions().
354 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
355 QualType Ty = Expr->getType();
356 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
358 UsualUnaryConversions(Expr);
360 // If this is a 'float' (CVR qualified or typedef) promote to double.
361 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
362 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
365 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
366 /// will warn if the resulting type is not a POD type, and rejects ObjC
367 /// interfaces passed by value. This returns true if the argument type is
368 /// completely illegal.
369 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
370 FunctionDecl *FDecl) {
371 DefaultArgumentPromotion(Expr);
373 // __builtin_va_start takes the second argument as a "varargs" argument, but
374 // it doesn't actually do anything with it. It doesn't need to be non-pod
375 // etc.
376 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
377 return false;
379 if (Expr->getType()->isObjCObjectType() &&
380 DiagRuntimeBehavior(Expr->getLocStart(),
381 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
382 << Expr->getType() << CT))
383 return true;
385 if (!Expr->getType()->isPODType() &&
386 DiagRuntimeBehavior(Expr->getLocStart(),
387 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
388 << Expr->getType() << CT))
389 return true;
391 return false;
394 /// UsualArithmeticConversions - Performs various conversions that are common to
395 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
396 /// routine returns the first non-arithmetic type found. The client is
397 /// responsible for emitting appropriate error diagnostics.
398 /// FIXME: verify the conversion rules for "complex int" are consistent with
399 /// GCC.
400 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
401 bool isCompAssign) {
402 if (!isCompAssign)
403 UsualUnaryConversions(lhsExpr);
405 UsualUnaryConversions(rhsExpr);
407 // For conversion purposes, we ignore any qualifiers.
408 // For example, "const float" and "float" are equivalent.
409 QualType lhs =
410 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
411 QualType rhs =
412 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
414 // If both types are identical, no conversion is needed.
415 if (lhs == rhs)
416 return lhs;
418 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
419 // The caller can deal with this (e.g. pointer + int).
420 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
421 return lhs;
423 // Apply unary and bitfield promotions to the LHS's type.
424 QualType lhs_unpromoted = lhs;
425 if (lhs->isPromotableIntegerType())
426 lhs = Context.getPromotedIntegerType(lhs);
427 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
428 if (!LHSBitfieldPromoteTy.isNull())
429 lhs = LHSBitfieldPromoteTy;
430 if (lhs != lhs_unpromoted && !isCompAssign)
431 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
433 // If both types are identical, no conversion is needed.
434 if (lhs == rhs)
435 return lhs;
437 // At this point, we have two different arithmetic types.
439 // Handle complex types first (C99 6.3.1.8p1).
440 bool LHSComplexFloat = lhs->isComplexType();
441 bool RHSComplexFloat = rhs->isComplexType();
442 if (LHSComplexFloat || RHSComplexFloat) {
443 // if we have an integer operand, the result is the complex type.
445 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
446 if (rhs->isIntegerType()) {
447 QualType fp = cast<ComplexType>(lhs)->getElementType();
448 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
449 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
450 } else {
451 assert(rhs->isComplexIntegerType());
452 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
454 return lhs;
457 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
458 if (!isCompAssign) {
459 // int -> float -> _Complex float
460 if (lhs->isIntegerType()) {
461 QualType fp = cast<ComplexType>(rhs)->getElementType();
462 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
463 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
464 } else {
465 assert(lhs->isComplexIntegerType());
466 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
469 return rhs;
472 // This handles complex/complex, complex/float, or float/complex.
473 // When both operands are complex, the shorter operand is converted to the
474 // type of the longer, and that is the type of the result. This corresponds
475 // to what is done when combining two real floating-point operands.
476 // The fun begins when size promotion occur across type domains.
477 // From H&S 6.3.4: When one operand is complex and the other is a real
478 // floating-point type, the less precise type is converted, within it's
479 // real or complex domain, to the precision of the other type. For example,
480 // when combining a "long double" with a "double _Complex", the
481 // "double _Complex" is promoted to "long double _Complex".
482 int order = Context.getFloatingTypeOrder(lhs, rhs);
484 // If both are complex, just cast to the more precise type.
485 if (LHSComplexFloat && RHSComplexFloat) {
486 if (order > 0) {
487 // _Complex float -> _Complex double
488 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
489 return lhs;
491 } else if (order < 0) {
492 // _Complex float -> _Complex double
493 if (!isCompAssign)
494 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
495 return rhs;
497 return lhs;
500 // If just the LHS is complex, the RHS needs to be converted,
501 // and the LHS might need to be promoted.
502 if (LHSComplexFloat) {
503 if (order > 0) { // LHS is wider
504 // float -> _Complex double
505 QualType fp = cast<ComplexType>(lhs)->getElementType();
506 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
507 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
508 return lhs;
511 // RHS is at least as wide. Find its corresponding complex type.
512 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
514 // double -> _Complex double
515 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
517 // _Complex float -> _Complex double
518 if (!isCompAssign && order < 0)
519 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
521 return result;
524 // Just the RHS is complex, so the LHS needs to be converted
525 // and the RHS might need to be promoted.
526 assert(RHSComplexFloat);
528 if (order < 0) { // RHS is wider
529 // float -> _Complex double
530 if (!isCompAssign) {
531 QualType fp = cast<ComplexType>(rhs)->getElementType();
532 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
533 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
535 return rhs;
538 // LHS is at least as wide. Find its corresponding complex type.
539 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
541 // double -> _Complex double
542 if (!isCompAssign)
543 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
545 // _Complex float -> _Complex double
546 if (order > 0)
547 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
549 return result;
552 // Now handle "real" floating types (i.e. float, double, long double).
553 bool LHSFloat = lhs->isRealFloatingType();
554 bool RHSFloat = rhs->isRealFloatingType();
555 if (LHSFloat || RHSFloat) {
556 // If we have two real floating types, convert the smaller operand
557 // to the bigger result.
558 if (LHSFloat && RHSFloat) {
559 int order = Context.getFloatingTypeOrder(lhs, rhs);
560 if (order > 0) {
561 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
562 return lhs;
565 assert(order < 0 && "illegal float comparison");
566 if (!isCompAssign)
567 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
568 return rhs;
571 // If we have an integer operand, the result is the real floating type.
572 if (LHSFloat) {
573 if (rhs->isIntegerType()) {
574 // Convert rhs to the lhs floating point type.
575 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
576 return lhs;
579 // Convert both sides to the appropriate complex float.
580 assert(rhs->isComplexIntegerType());
581 QualType result = Context.getComplexType(lhs);
583 // _Complex int -> _Complex float
584 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
586 // float -> _Complex float
587 if (!isCompAssign)
588 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
590 return result;
593 assert(RHSFloat);
594 if (lhs->isIntegerType()) {
595 // Convert lhs to the rhs floating point type.
596 if (!isCompAssign)
597 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
598 return rhs;
601 // Convert both sides to the appropriate complex float.
602 assert(lhs->isComplexIntegerType());
603 QualType result = Context.getComplexType(rhs);
605 // _Complex int -> _Complex float
606 if (!isCompAssign)
607 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
609 // float -> _Complex float
610 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
612 return result;
615 // Handle GCC complex int extension.
616 // FIXME: if the operands are (int, _Complex long), we currently
617 // don't promote the complex. Also, signedness?
618 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
619 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
620 if (lhsComplexInt && rhsComplexInt) {
621 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
622 rhsComplexInt->getElementType());
623 assert(order && "inequal types with equal element ordering");
624 if (order > 0) {
625 // _Complex int -> _Complex long
626 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
627 return lhs;
630 if (!isCompAssign)
631 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
632 return rhs;
633 } else if (lhsComplexInt) {
634 // int -> _Complex int
635 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
636 return lhs;
637 } else if (rhsComplexInt) {
638 // int -> _Complex int
639 if (!isCompAssign)
640 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
641 return rhs;
644 // Finally, we have two differing integer types.
645 // The rules for this case are in C99 6.3.1.8
646 int compare = Context.getIntegerTypeOrder(lhs, rhs);
647 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
648 rhsSigned = rhs->hasSignedIntegerRepresentation();
649 if (lhsSigned == rhsSigned) {
650 // Same signedness; use the higher-ranked type
651 if (compare >= 0) {
652 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
653 return lhs;
654 } else if (!isCompAssign)
655 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
656 return rhs;
657 } else if (compare != (lhsSigned ? 1 : -1)) {
658 // The unsigned type has greater than or equal rank to the
659 // signed type, so use the unsigned type
660 if (rhsSigned) {
661 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
662 return lhs;
663 } else if (!isCompAssign)
664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
665 return rhs;
666 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
667 // The two types are different widths; if we are here, that
668 // means the signed type is larger than the unsigned type, so
669 // use the signed type.
670 if (lhsSigned) {
671 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
672 return lhs;
673 } else if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
675 return rhs;
676 } else {
677 // The signed type is higher-ranked than the unsigned type,
678 // but isn't actually any bigger (like unsigned int and long
679 // on most 32-bit systems). Use the unsigned type corresponding
680 // to the signed type.
681 QualType result =
682 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
683 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
684 if (!isCompAssign)
685 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
686 return result;
690 //===----------------------------------------------------------------------===//
691 // Semantic Analysis for various Expression Types
692 //===----------------------------------------------------------------------===//
695 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
696 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
697 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
698 /// multiple tokens. However, the common case is that StringToks points to one
699 /// string.
701 ExprResult
702 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
703 assert(NumStringToks && "Must have at least one string!");
705 StringLiteralParser Literal(StringToks, NumStringToks, PP);
706 if (Literal.hadError)
707 return ExprError();
709 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
710 for (unsigned i = 0; i != NumStringToks; ++i)
711 StringTokLocs.push_back(StringToks[i].getLocation());
713 QualType StrTy = Context.CharTy;
714 if (Literal.AnyWide) StrTy = Context.getWCharType();
715 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
717 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
718 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
719 StrTy.addConst();
721 // Get an array type for the string, according to C99 6.4.5. This includes
722 // the nul terminator character as well as the string length for pascal
723 // strings.
724 StrTy = Context.getConstantArrayType(StrTy,
725 llvm::APInt(32, Literal.GetNumStringChars()+1),
726 ArrayType::Normal, 0);
728 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
729 return Owned(StringLiteral::Create(Context, Literal.GetString(),
730 Literal.GetStringLength(),
731 Literal.AnyWide, StrTy,
732 &StringTokLocs[0],
733 StringTokLocs.size()));
736 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
737 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
738 /// variables defined outside the block) or false if this is not needed (e.g.
739 /// for values inside the block or for globals).
741 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
742 /// up-to-date.
744 static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
745 ValueDecl *VD) {
746 // If the value is defined inside the block, we couldn't snapshot it even if
747 // we wanted to.
748 if (CurBlock->TheDecl == VD->getDeclContext())
749 return false;
751 // If this is an enum constant or function, it is constant, don't snapshot.
752 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
753 return false;
755 // If this is a reference to an extern, static, or global variable, no need to
756 // snapshot it.
757 // FIXME: What about 'const' variables in C++?
758 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
759 if (!Var->hasLocalStorage())
760 return false;
762 // Blocks that have these can't be constant.
763 CurBlock->hasBlockDeclRefExprs = true;
765 // If we have nested blocks, the decl may be declared in an outer block (in
766 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
767 // be defined outside all of the current blocks (in which case the blocks do
768 // all get the bit). Walk the nesting chain.
769 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
770 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
772 if (!NextBlock)
773 continue;
775 // If we found the defining block for the variable, don't mark the block as
776 // having a reference outside it.
777 if (NextBlock->TheDecl == VD->getDeclContext())
778 break;
780 // Otherwise, the DeclRef from the inner block causes the outer one to need
781 // a snapshot as well.
782 NextBlock->hasBlockDeclRefExprs = true;
785 return true;
789 ExprResult
790 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
791 SourceLocation Loc, const CXXScopeSpec *SS) {
792 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
793 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
796 /// BuildDeclRefExpr - Build a DeclRefExpr.
797 ExprResult
798 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
799 ExprValueKind VK,
800 const DeclarationNameInfo &NameInfo,
801 const CXXScopeSpec *SS) {
802 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
803 Diag(NameInfo.getLoc(),
804 diag::err_auto_variable_cannot_appear_in_own_initializer)
805 << D->getDeclName();
806 return ExprError();
809 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
810 if (isa<NonTypeTemplateParmDecl>(VD)) {
811 // Non-type template parameters can be referenced anywhere they are
812 // visible.
813 Ty = Ty.getNonLValueExprType(Context);
814 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
815 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
816 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
817 Diag(NameInfo.getLoc(),
818 diag::err_reference_to_local_var_in_enclosing_function)
819 << D->getIdentifier() << FD->getDeclName();
820 Diag(D->getLocation(), diag::note_local_variable_declared_here)
821 << D->getIdentifier();
822 return ExprError();
826 // This ridiculousness brought to you by 'extern void x;' and the
827 // GNU compiler collection.
828 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
829 Ty->isVoidType()) {
830 VK = VK_RValue;
834 MarkDeclarationReferenced(NameInfo.getLoc(), D);
836 Expr *E = DeclRefExpr::Create(Context,
837 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
838 SS? SS->getRange() : SourceRange(),
839 D, NameInfo, Ty, VK);
841 // Just in case we're building an illegal pointer-to-member.
842 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
843 E->setObjectKind(OK_BitField);
845 return Owned(E);
848 static ExprResult
849 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
850 const CXXScopeSpec &SS, FieldDecl *Field,
851 DeclAccessPair FoundDecl,
852 const DeclarationNameInfo &MemberNameInfo);
854 ExprResult
855 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
856 const CXXScopeSpec &SS,
857 IndirectFieldDecl *IndirectField,
858 Expr *BaseObjectExpr,
859 SourceLocation OpLoc) {
860 // Build the expression that refers to the base object, from
861 // which we will build a sequence of member references to each
862 // of the anonymous union objects and, eventually, the field we
863 // found via name lookup.
864 bool BaseObjectIsPointer = false;
865 Qualifiers BaseQuals;
866 VarDecl *BaseObject = IndirectField->getVarDecl();
867 if (BaseObject) {
868 // BaseObject is an anonymous struct/union variable (and is,
869 // therefore, not part of another non-anonymous record).
870 MarkDeclarationReferenced(Loc, BaseObject);
871 BaseObjectExpr =
872 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
873 VK_LValue, Loc);
874 BaseQuals
875 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
876 } else if (BaseObjectExpr) {
877 // The caller provided the base object expression. Determine
878 // whether its a pointer and whether it adds any qualifiers to the
879 // anonymous struct/union fields we're looking into.
880 QualType ObjectType = BaseObjectExpr->getType();
881 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
882 BaseObjectIsPointer = true;
883 ObjectType = ObjectPtr->getPointeeType();
885 BaseQuals
886 = Context.getCanonicalType(ObjectType).getQualifiers();
887 } else {
888 // We've found a member of an anonymous struct/union that is
889 // inside a non-anonymous struct/union, so in a well-formed
890 // program our base object expression is "this".
891 DeclContext *DC = getFunctionLevelDeclContext();
892 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
893 if (!MD->isStatic()) {
894 QualType AnonFieldType
895 = Context.getTagDeclType(
896 cast<RecordDecl>(
897 (*IndirectField->chain_begin())->getDeclContext()));
898 QualType ThisType = Context.getTagDeclType(MD->getParent());
899 if ((Context.getCanonicalType(AnonFieldType)
900 == Context.getCanonicalType(ThisType)) ||
901 IsDerivedFrom(ThisType, AnonFieldType)) {
902 // Our base object expression is "this".
903 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
904 MD->getThisType(Context),
905 /*isImplicit=*/true);
906 BaseObjectIsPointer = true;
908 } else {
909 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
910 << IndirectField->getDeclName());
912 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
915 if (!BaseObjectExpr) {
916 // The field is referenced for a pointer-to-member expression, e.g:
918 // struct S {
919 // union {
920 // char c;
921 // };
922 // };
923 // char S::*foo = &S::c;
925 FieldDecl *field = IndirectField->getAnonField();
926 DeclarationNameInfo NameInfo(field->getDeclName(), Loc);
927 return BuildDeclRefExpr(field, field->getType().getNonReferenceType(),
928 VK_LValue, NameInfo, &SS);
932 // Build the implicit member references to the field of the
933 // anonymous struct/union.
934 Expr *Result = BaseObjectExpr;
936 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
937 FEnd = IndirectField->chain_end();
939 // Skip the first VarDecl if present.
940 if (BaseObject)
941 FI++;
942 for (; FI != FEnd; FI++) {
943 FieldDecl *Field = cast<FieldDecl>(*FI);
945 // FIXME: these are somewhat meaningless
946 DeclarationNameInfo MemberNameInfo(Field->getDeclName(), Loc);
947 DeclAccessPair FoundDecl = DeclAccessPair::make(Field, Field->getAccess());
949 Result = BuildFieldReferenceExpr(*this, Result, BaseObjectIsPointer,
950 SS, Field, FoundDecl, MemberNameInfo)
951 .take();
953 // All the implicit accesses are dot-accesses.
954 BaseObjectIsPointer = false;
957 return Owned(Result);
960 /// Decomposes the given name into a DeclarationNameInfo, its location, and
961 /// possibly a list of template arguments.
963 /// If this produces template arguments, it is permitted to call
964 /// DecomposeTemplateName.
966 /// This actually loses a lot of source location information for
967 /// non-standard name kinds; we should consider preserving that in
968 /// some way.
969 static void DecomposeUnqualifiedId(Sema &SemaRef,
970 const UnqualifiedId &Id,
971 TemplateArgumentListInfo &Buffer,
972 DeclarationNameInfo &NameInfo,
973 const TemplateArgumentListInfo *&TemplateArgs) {
974 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
975 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
976 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
978 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
979 Id.TemplateId->getTemplateArgs(),
980 Id.TemplateId->NumArgs);
981 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
982 TemplateArgsPtr.release();
984 TemplateName TName = Id.TemplateId->Template.get();
985 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
986 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
987 TemplateArgs = &Buffer;
988 } else {
989 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
990 TemplateArgs = 0;
994 /// Determines whether the given record is "fully-formed" at the given
995 /// location, i.e. whether a qualified lookup into it is assured of
996 /// getting consistent results already.
997 static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
998 if (!Record->hasDefinition())
999 return false;
1001 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1002 E = Record->bases_end(); I != E; ++I) {
1003 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1004 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1005 if (!BaseRT) return false;
1007 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
1008 if (!BaseRecord->hasDefinition() ||
1009 !IsFullyFormedScope(SemaRef, BaseRecord))
1010 return false;
1013 return true;
1016 /// Determines if the given class is provably not derived from all of
1017 /// the prospective base classes.
1018 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1019 CXXRecordDecl *Record,
1020 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
1021 if (Bases.count(Record->getCanonicalDecl()))
1022 return false;
1024 RecordDecl *RD = Record->getDefinition();
1025 if (!RD) return false;
1026 Record = cast<CXXRecordDecl>(RD);
1028 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1029 E = Record->bases_end(); I != E; ++I) {
1030 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1031 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1032 if (!BaseRT) return false;
1034 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
1035 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1036 return false;
1039 return true;
1042 enum IMAKind {
1043 /// The reference is definitely not an instance member access.
1044 IMA_Static,
1046 /// The reference may be an implicit instance member access.
1047 IMA_Mixed,
1049 /// The reference may be to an instance member, but it is invalid if
1050 /// so, because the context is not an instance method.
1051 IMA_Mixed_StaticContext,
1053 /// The reference may be to an instance member, but it is invalid if
1054 /// so, because the context is from an unrelated class.
1055 IMA_Mixed_Unrelated,
1057 /// The reference is definitely an implicit instance member access.
1058 IMA_Instance,
1060 /// The reference may be to an unresolved using declaration.
1061 IMA_Unresolved,
1063 /// The reference may be to an unresolved using declaration and the
1064 /// context is not an instance method.
1065 IMA_Unresolved_StaticContext,
1067 /// All possible referrents are instance members and the current
1068 /// context is not an instance method.
1069 IMA_Error_StaticContext,
1071 /// All possible referrents are instance members of an unrelated
1072 /// class.
1073 IMA_Error_Unrelated
1076 /// The given lookup names class member(s) and is not being used for
1077 /// an address-of-member expression. Classify the type of access
1078 /// according to whether it's possible that this reference names an
1079 /// instance member. This is best-effort; it is okay to
1080 /// conservatively answer "yes", in which case some errors will simply
1081 /// not be caught until template-instantiation.
1082 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1083 const LookupResult &R) {
1084 assert(!R.empty() && (*R.begin())->isCXXClassMember());
1086 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
1087 bool isStaticContext =
1088 (!isa<CXXMethodDecl>(DC) ||
1089 cast<CXXMethodDecl>(DC)->isStatic());
1091 if (R.isUnresolvableResult())
1092 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1094 // Collect all the declaring classes of instance members we find.
1095 bool hasNonInstance = false;
1096 bool hasField = false;
1097 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1098 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1099 NamedDecl *D = *I;
1101 if (D->isCXXInstanceMember()) {
1102 if (dyn_cast<FieldDecl>(D))
1103 hasField = true;
1105 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
1106 Classes.insert(R->getCanonicalDecl());
1108 else
1109 hasNonInstance = true;
1112 // If we didn't find any instance members, it can't be an implicit
1113 // member reference.
1114 if (Classes.empty())
1115 return IMA_Static;
1117 // If the current context is not an instance method, it can't be
1118 // an implicit member reference.
1119 if (isStaticContext) {
1120 if (hasNonInstance)
1121 return IMA_Mixed_StaticContext;
1123 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1124 // C++0x [expr.prim.general]p10:
1125 // An id-expression that denotes a non-static data member or non-static
1126 // member function of a class can only be used:
1127 // (...)
1128 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1129 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1130 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1131 if (isUnevaluatedExpression)
1132 return IMA_Mixed_StaticContext;
1135 return IMA_Error_StaticContext;
1138 // If we can prove that the current context is unrelated to all the
1139 // declaring classes, it can't be an implicit member reference (in
1140 // which case it's an error if any of those members are selected).
1141 if (IsProvablyNotDerivedFrom(SemaRef,
1142 cast<CXXMethodDecl>(DC)->getParent(),
1143 Classes))
1144 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1146 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1149 /// Diagnose a reference to a field with no object available.
1150 static void DiagnoseInstanceReference(Sema &SemaRef,
1151 const CXXScopeSpec &SS,
1152 const LookupResult &R) {
1153 SourceLocation Loc = R.getNameLoc();
1154 SourceRange Range(Loc);
1155 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1157 if (R.getAsSingle<FieldDecl>()) {
1158 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1159 if (MD->isStatic()) {
1160 // "invalid use of member 'x' in static member function"
1161 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1162 << Range << R.getLookupName();
1163 return;
1167 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1168 << R.getLookupName() << Range;
1169 return;
1172 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
1175 /// Diagnose an empty lookup.
1177 /// \return false if new lookup candidates were found
1178 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1179 CorrectTypoContext CTC) {
1180 DeclarationName Name = R.getLookupName();
1182 unsigned diagnostic = diag::err_undeclared_var_use;
1183 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1184 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1185 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1186 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1187 diagnostic = diag::err_undeclared_use;
1188 diagnostic_suggest = diag::err_undeclared_use_suggest;
1191 // If the original lookup was an unqualified lookup, fake an
1192 // unqualified lookup. This is useful when (for example) the
1193 // original lookup would not have found something because it was a
1194 // dependent name.
1195 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1196 DC; DC = DC->getParent()) {
1197 if (isa<CXXRecordDecl>(DC)) {
1198 LookupQualifiedName(R, DC);
1200 if (!R.empty()) {
1201 // Don't give errors about ambiguities in this lookup.
1202 R.suppressDiagnostics();
1204 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1205 bool isInstance = CurMethod &&
1206 CurMethod->isInstance() &&
1207 DC == CurMethod->getParent();
1209 // Give a code modification hint to insert 'this->'.
1210 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1211 // Actually quite difficult!
1212 if (isInstance) {
1213 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1214 CallsUndergoingInstantiation.back()->getCallee());
1215 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1216 CurMethod->getInstantiatedFromMemberFunction());
1217 if (DepMethod) {
1218 Diag(R.getNameLoc(), diagnostic) << Name
1219 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1220 QualType DepThisType = DepMethod->getThisType(Context);
1221 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1222 R.getNameLoc(), DepThisType, false);
1223 TemplateArgumentListInfo TList;
1224 if (ULE->hasExplicitTemplateArgs())
1225 ULE->copyTemplateArgumentsInto(TList);
1226 CXXDependentScopeMemberExpr *DepExpr =
1227 CXXDependentScopeMemberExpr::Create(
1228 Context, DepThis, DepThisType, true, SourceLocation(),
1229 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1230 R.getLookupNameInfo(), &TList);
1231 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1232 } else {
1233 // FIXME: we should be able to handle this case too. It is correct
1234 // to add this-> here. This is a workaround for PR7947.
1235 Diag(R.getNameLoc(), diagnostic) << Name;
1237 } else {
1238 Diag(R.getNameLoc(), diagnostic) << Name;
1241 // Do we really want to note all of these?
1242 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1243 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1245 // Tell the callee to try to recover.
1246 return false;
1249 R.clear();
1253 // We didn't find anything, so try to correct for a typo.
1254 DeclarationName Corrected;
1255 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
1256 if (!R.empty()) {
1257 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1258 if (SS.isEmpty())
1259 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1260 << FixItHint::CreateReplacement(R.getNameLoc(),
1261 R.getLookupName().getAsString());
1262 else
1263 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1264 << Name << computeDeclContext(SS, false) << R.getLookupName()
1265 << SS.getRange()
1266 << FixItHint::CreateReplacement(R.getNameLoc(),
1267 R.getLookupName().getAsString());
1268 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1269 Diag(ND->getLocation(), diag::note_previous_decl)
1270 << ND->getDeclName();
1272 // Tell the callee to try to recover.
1273 return false;
1276 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1277 // FIXME: If we ended up with a typo for a type name or
1278 // Objective-C class name, we're in trouble because the parser
1279 // is in the wrong place to recover. Suggest the typo
1280 // correction, but don't make it a fix-it since we're not going
1281 // to recover well anyway.
1282 if (SS.isEmpty())
1283 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1284 else
1285 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1286 << Name << computeDeclContext(SS, false) << R.getLookupName()
1287 << SS.getRange();
1289 // Don't try to recover; it won't work.
1290 return true;
1292 } else {
1293 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1294 // because we aren't able to recover.
1295 if (SS.isEmpty())
1296 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
1297 else
1298 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1299 << Name << computeDeclContext(SS, false) << Corrected
1300 << SS.getRange();
1301 return true;
1303 R.clear();
1306 // Emit a special diagnostic for failed member lookups.
1307 // FIXME: computing the declaration context might fail here (?)
1308 if (!SS.isEmpty()) {
1309 Diag(R.getNameLoc(), diag::err_no_member)
1310 << Name << computeDeclContext(SS, false)
1311 << SS.getRange();
1312 return true;
1315 // Give up, we can't recover.
1316 Diag(R.getNameLoc(), diagnostic) << Name;
1317 return true;
1320 ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1321 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1322 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1323 if (!IDecl)
1324 return 0;
1325 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1326 if (!ClassImpDecl)
1327 return 0;
1328 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1329 if (!property)
1330 return 0;
1331 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1332 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1333 PIDecl->getPropertyIvarDecl())
1334 return 0;
1335 return property;
1338 bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1339 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1340 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1341 if (!IDecl)
1342 return false;
1343 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1344 if (!ClassImpDecl)
1345 return false;
1346 if (ObjCPropertyImplDecl *PIDecl
1347 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1348 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1349 PIDecl->getPropertyIvarDecl())
1350 return false;
1352 return true;
1355 static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
1356 LookupResult &Lookup,
1357 IdentifierInfo *II,
1358 SourceLocation NameLoc) {
1359 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1360 bool LookForIvars;
1361 if (Lookup.empty())
1362 LookForIvars = true;
1363 else if (CurMeth->isClassMethod())
1364 LookForIvars = false;
1365 else
1366 LookForIvars = (Lookup.isSingleResult() &&
1367 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1368 (Lookup.getAsSingle<VarDecl>() != 0));
1369 if (!LookForIvars)
1370 return 0;
1372 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1373 if (!IDecl)
1374 return 0;
1375 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1376 if (!ClassImpDecl)
1377 return 0;
1378 bool DynamicImplSeen = false;
1379 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1380 if (!property)
1381 return 0;
1382 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
1383 DynamicImplSeen =
1384 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1385 // property implementation has a designated ivar. No need to assume a new
1386 // one.
1387 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1388 return 0;
1390 if (!DynamicImplSeen) {
1391 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1392 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
1393 NameLoc,
1394 II, PropType, /*Dinfo=*/0,
1395 ObjCIvarDecl::Private,
1396 (Expr *)0, true);
1397 ClassImpDecl->addDecl(Ivar);
1398 IDecl->makeDeclVisibleInContext(Ivar, false);
1399 property->setPropertyIvarDecl(Ivar);
1400 return Ivar;
1402 return 0;
1405 ExprResult Sema::ActOnIdExpression(Scope *S,
1406 CXXScopeSpec &SS,
1407 UnqualifiedId &Id,
1408 bool HasTrailingLParen,
1409 bool isAddressOfOperand) {
1410 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1411 "cannot be direct & operand and have a trailing lparen");
1413 if (SS.isInvalid())
1414 return ExprError();
1416 TemplateArgumentListInfo TemplateArgsBuffer;
1418 // Decompose the UnqualifiedId into the following data.
1419 DeclarationNameInfo NameInfo;
1420 const TemplateArgumentListInfo *TemplateArgs;
1421 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1423 DeclarationName Name = NameInfo.getName();
1424 IdentifierInfo *II = Name.getAsIdentifierInfo();
1425 SourceLocation NameLoc = NameInfo.getLoc();
1427 // C++ [temp.dep.expr]p3:
1428 // An id-expression is type-dependent if it contains:
1429 // -- an identifier that was declared with a dependent type,
1430 // (note: handled after lookup)
1431 // -- a template-id that is dependent,
1432 // (note: handled in BuildTemplateIdExpr)
1433 // -- a conversion-function-id that specifies a dependent type,
1434 // -- a nested-name-specifier that contains a class-name that
1435 // names a dependent type.
1436 // Determine whether this is a member of an unknown specialization;
1437 // we need to handle these differently.
1438 bool DependentID = false;
1439 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1440 Name.getCXXNameType()->isDependentType()) {
1441 DependentID = true;
1442 } else if (SS.isSet()) {
1443 DeclContext *DC = computeDeclContext(SS, false);
1444 if (DC) {
1445 if (RequireCompleteDeclContext(SS, DC))
1446 return ExprError();
1447 // FIXME: We should be checking whether DC is the current instantiation.
1448 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1449 DependentID = !IsFullyFormedScope(*this, RD);
1450 } else {
1451 DependentID = true;
1455 if (DependentID) {
1456 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1457 TemplateArgs);
1459 bool IvarLookupFollowUp = false;
1460 // Perform the required lookup.
1461 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1462 if (TemplateArgs) {
1463 // Lookup the template name again to correctly establish the context in
1464 // which it was found. This is really unfortunate as we already did the
1465 // lookup to determine that it was a template name in the first place. If
1466 // this becomes a performance hit, we can work harder to preserve those
1467 // results until we get here but it's likely not worth it.
1468 bool MemberOfUnknownSpecialization;
1469 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1470 MemberOfUnknownSpecialization);
1471 } else {
1472 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1473 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1475 // If this reference is in an Objective-C method, then we need to do
1476 // some special Objective-C lookup, too.
1477 if (IvarLookupFollowUp) {
1478 ExprResult E(LookupInObjCMethod(R, S, II, true));
1479 if (E.isInvalid())
1480 return ExprError();
1482 Expr *Ex = E.takeAs<Expr>();
1483 if (Ex) return Owned(Ex);
1484 // Synthesize ivars lazily
1485 if (getLangOptions().ObjCDefaultSynthProperties &&
1486 getLangOptions().ObjCNonFragileABI2) {
1487 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1488 if (const ObjCPropertyDecl *Property =
1489 canSynthesizeProvisionalIvar(II)) {
1490 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1491 Diag(Property->getLocation(), diag::note_property_declare);
1493 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1494 isAddressOfOperand);
1497 // for further use, this must be set to false if in class method.
1498 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1502 if (R.isAmbiguous())
1503 return ExprError();
1505 // Determine whether this name might be a candidate for
1506 // argument-dependent lookup.
1507 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1509 if (R.empty() && !ADL) {
1510 // Otherwise, this could be an implicitly declared function reference (legal
1511 // in C90, extension in C99, forbidden in C++).
1512 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1513 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1514 if (D) R.addDecl(D);
1517 // If this name wasn't predeclared and if this is not a function
1518 // call, diagnose the problem.
1519 if (R.empty()) {
1520 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1521 return ExprError();
1523 assert(!R.empty() &&
1524 "DiagnoseEmptyLookup returned false but added no results");
1526 // If we found an Objective-C instance variable, let
1527 // LookupInObjCMethod build the appropriate expression to
1528 // reference the ivar.
1529 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1530 R.clear();
1531 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1532 assert(E.isInvalid() || E.get());
1533 return move(E);
1538 // This is guaranteed from this point on.
1539 assert(!R.empty() || ADL);
1541 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
1542 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
1543 !(getLangOptions().ObjCDefaultSynthProperties &&
1544 getLangOptions().ObjCNonFragileABI2) &&
1545 Var->isFileVarDecl()) {
1546 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
1547 if (Property) {
1548 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1549 Diag(Property->getLocation(), diag::note_property_declare);
1550 Diag(Var->getLocation(), diag::note_global_declared_at);
1553 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
1554 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1555 // C99 DR 316 says that, if a function type comes from a
1556 // function definition (without a prototype), that type is only
1557 // used for checking compatibility. Therefore, when referencing
1558 // the function, we pretend that we don't have the full function
1559 // type.
1560 if (DiagnoseUseOfDecl(Func, NameLoc))
1561 return ExprError();
1563 QualType T = Func->getType();
1564 QualType NoProtoType = T;
1565 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
1566 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1567 Proto->getExtInfo());
1568 // Note that functions are r-values in C.
1569 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
1573 // Check whether this might be a C++ implicit instance member access.
1574 // C++ [class.mfct.non-static]p3:
1575 // When an id-expression that is not part of a class member access
1576 // syntax and not used to form a pointer to member is used in the
1577 // body of a non-static member function of class X, if name lookup
1578 // resolves the name in the id-expression to a non-static non-type
1579 // member of some class C, the id-expression is transformed into a
1580 // class member access expression using (*this) as the
1581 // postfix-expression to the left of the . operator.
1583 // But we don't actually need to do this for '&' operands if R
1584 // resolved to a function or overloaded function set, because the
1585 // expression is ill-formed if it actually works out to be a
1586 // non-static member function:
1588 // C++ [expr.ref]p4:
1589 // Otherwise, if E1.E2 refers to a non-static member function. . .
1590 // [t]he expression can be used only as the left-hand operand of a
1591 // member function call.
1593 // There are other safeguards against such uses, but it's important
1594 // to get this right here so that we don't end up making a
1595 // spuriously dependent expression if we're inside a dependent
1596 // instance method.
1597 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1598 bool MightBeImplicitMember;
1599 if (!isAddressOfOperand)
1600 MightBeImplicitMember = true;
1601 else if (!SS.isEmpty())
1602 MightBeImplicitMember = false;
1603 else if (R.isOverloadedResult())
1604 MightBeImplicitMember = false;
1605 else if (R.isUnresolvableResult())
1606 MightBeImplicitMember = true;
1607 else
1608 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1609 isa<IndirectFieldDecl>(R.getFoundDecl());
1611 if (MightBeImplicitMember)
1612 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1615 if (TemplateArgs)
1616 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1618 return BuildDeclarationNameExpr(SS, R, ADL);
1621 /// Builds an expression which might be an implicit member expression.
1622 ExprResult
1623 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1624 LookupResult &R,
1625 const TemplateArgumentListInfo *TemplateArgs) {
1626 switch (ClassifyImplicitMemberAccess(*this, R)) {
1627 case IMA_Instance:
1628 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1630 case IMA_Mixed:
1631 case IMA_Mixed_Unrelated:
1632 case IMA_Unresolved:
1633 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1635 case IMA_Static:
1636 case IMA_Mixed_StaticContext:
1637 case IMA_Unresolved_StaticContext:
1638 if (TemplateArgs)
1639 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1640 return BuildDeclarationNameExpr(SS, R, false);
1642 case IMA_Error_StaticContext:
1643 case IMA_Error_Unrelated:
1644 DiagnoseInstanceReference(*this, SS, R);
1645 return ExprError();
1648 llvm_unreachable("unexpected instance member access kind");
1649 return ExprError();
1652 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1653 /// declaration name, generally during template instantiation.
1654 /// There's a large number of things which don't need to be done along
1655 /// this path.
1656 ExprResult
1657 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1658 const DeclarationNameInfo &NameInfo) {
1659 DeclContext *DC;
1660 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1661 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1663 if (RequireCompleteDeclContext(SS, DC))
1664 return ExprError();
1666 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1667 LookupQualifiedName(R, DC);
1669 if (R.isAmbiguous())
1670 return ExprError();
1672 if (R.empty()) {
1673 Diag(NameInfo.getLoc(), diag::err_no_member)
1674 << NameInfo.getName() << DC << SS.getRange();
1675 return ExprError();
1678 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1681 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1682 /// detected that we're currently inside an ObjC method. Perform some
1683 /// additional lookup.
1685 /// Ideally, most of this would be done by lookup, but there's
1686 /// actually quite a lot of extra work involved.
1688 /// Returns a null sentinel to indicate trivial success.
1689 ExprResult
1690 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1691 IdentifierInfo *II, bool AllowBuiltinCreation) {
1692 SourceLocation Loc = Lookup.getNameLoc();
1693 ObjCMethodDecl *CurMethod = getCurMethodDecl();
1695 // There are two cases to handle here. 1) scoped lookup could have failed,
1696 // in which case we should look for an ivar. 2) scoped lookup could have
1697 // found a decl, but that decl is outside the current instance method (i.e.
1698 // a global variable). In these two cases, we do a lookup for an ivar with
1699 // this name, if the lookup sucedes, we replace it our current decl.
1701 // If we're in a class method, we don't normally want to look for
1702 // ivars. But if we don't find anything else, and there's an
1703 // ivar, that's an error.
1704 bool IsClassMethod = CurMethod->isClassMethod();
1706 bool LookForIvars;
1707 if (Lookup.empty())
1708 LookForIvars = true;
1709 else if (IsClassMethod)
1710 LookForIvars = false;
1711 else
1712 LookForIvars = (Lookup.isSingleResult() &&
1713 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1714 ObjCInterfaceDecl *IFace = 0;
1715 if (LookForIvars) {
1716 IFace = CurMethod->getClassInterface();
1717 ObjCInterfaceDecl *ClassDeclared;
1718 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1719 // Diagnose using an ivar in a class method.
1720 if (IsClassMethod)
1721 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1722 << IV->getDeclName());
1724 // If we're referencing an invalid decl, just return this as a silent
1725 // error node. The error diagnostic was already emitted on the decl.
1726 if (IV->isInvalidDecl())
1727 return ExprError();
1729 // Check if referencing a field with __attribute__((deprecated)).
1730 if (DiagnoseUseOfDecl(IV, Loc))
1731 return ExprError();
1733 // Diagnose the use of an ivar outside of the declaring class.
1734 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1735 ClassDeclared != IFace)
1736 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1738 // FIXME: This should use a new expr for a direct reference, don't
1739 // turn this into Self->ivar, just return a BareIVarExpr or something.
1740 IdentifierInfo &II = Context.Idents.get("self");
1741 UnqualifiedId SelfName;
1742 SelfName.setIdentifier(&II, SourceLocation());
1743 CXXScopeSpec SelfScopeSpec;
1744 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1745 SelfName, false, false);
1746 if (SelfExpr.isInvalid())
1747 return ExprError();
1749 Expr *SelfE = SelfExpr.take();
1750 DefaultLvalueConversion(SelfE);
1752 MarkDeclarationReferenced(Loc, IV);
1753 return Owned(new (Context)
1754 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1755 SelfE, true, true));
1757 } else if (CurMethod->isInstanceMethod()) {
1758 // We should warn if a local variable hides an ivar.
1759 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1760 ObjCInterfaceDecl *ClassDeclared;
1761 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1762 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1763 IFace == ClassDeclared)
1764 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1768 if (Lookup.empty() && II && AllowBuiltinCreation) {
1769 // FIXME. Consolidate this with similar code in LookupName.
1770 if (unsigned BuiltinID = II->getBuiltinID()) {
1771 if (!(getLangOptions().CPlusPlus &&
1772 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1773 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1774 S, Lookup.isForRedeclaration(),
1775 Lookup.getNameLoc());
1776 if (D) Lookup.addDecl(D);
1780 // Sentinel value saying that we didn't do anything special.
1781 return Owned((Expr*) 0);
1784 /// \brief Cast a base object to a member's actual type.
1786 /// Logically this happens in three phases:
1788 /// * First we cast from the base type to the naming class.
1789 /// The naming class is the class into which we were looking
1790 /// when we found the member; it's the qualifier type if a
1791 /// qualifier was provided, and otherwise it's the base type.
1793 /// * Next we cast from the naming class to the declaring class.
1794 /// If the member we found was brought into a class's scope by
1795 /// a using declaration, this is that class; otherwise it's
1796 /// the class declaring the member.
1798 /// * Finally we cast from the declaring class to the "true"
1799 /// declaring class of the member. This conversion does not
1800 /// obey access control.
1801 bool
1802 Sema::PerformObjectMemberConversion(Expr *&From,
1803 NestedNameSpecifier *Qualifier,
1804 NamedDecl *FoundDecl,
1805 NamedDecl *Member) {
1806 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1807 if (!RD)
1808 return false;
1810 QualType DestRecordType;
1811 QualType DestType;
1812 QualType FromRecordType;
1813 QualType FromType = From->getType();
1814 bool PointerConversions = false;
1815 if (isa<FieldDecl>(Member)) {
1816 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
1818 if (FromType->getAs<PointerType>()) {
1819 DestType = Context.getPointerType(DestRecordType);
1820 FromRecordType = FromType->getPointeeType();
1821 PointerConversions = true;
1822 } else {
1823 DestType = DestRecordType;
1824 FromRecordType = FromType;
1826 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1827 if (Method->isStatic())
1828 return false;
1830 DestType = Method->getThisType(Context);
1831 DestRecordType = DestType->getPointeeType();
1833 if (FromType->getAs<PointerType>()) {
1834 FromRecordType = FromType->getPointeeType();
1835 PointerConversions = true;
1836 } else {
1837 FromRecordType = FromType;
1838 DestType = DestRecordType;
1840 } else {
1841 // No conversion necessary.
1842 return false;
1845 if (DestType->isDependentType() || FromType->isDependentType())
1846 return false;
1848 // If the unqualified types are the same, no conversion is necessary.
1849 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1850 return false;
1852 SourceRange FromRange = From->getSourceRange();
1853 SourceLocation FromLoc = FromRange.getBegin();
1855 ExprValueKind VK = CastCategory(From);
1857 // C++ [class.member.lookup]p8:
1858 // [...] Ambiguities can often be resolved by qualifying a name with its
1859 // class name.
1861 // If the member was a qualified name and the qualified referred to a
1862 // specific base subobject type, we'll cast to that intermediate type
1863 // first and then to the object in which the member is declared. That allows
1864 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1866 // class Base { public: int x; };
1867 // class Derived1 : public Base { };
1868 // class Derived2 : public Base { };
1869 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1871 // void VeryDerived::f() {
1872 // x = 17; // error: ambiguous base subobjects
1873 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1874 // }
1875 if (Qualifier) {
1876 QualType QType = QualType(Qualifier->getAsType(), 0);
1877 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1878 assert(QType->isRecordType() && "lookup done with non-record type");
1880 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1882 // In C++98, the qualifier type doesn't actually have to be a base
1883 // type of the object type, in which case we just ignore it.
1884 // Otherwise build the appropriate casts.
1885 if (IsDerivedFrom(FromRecordType, QRecordType)) {
1886 CXXCastPath BasePath;
1887 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
1888 FromLoc, FromRange, &BasePath))
1889 return true;
1891 if (PointerConversions)
1892 QType = Context.getPointerType(QType);
1893 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1894 VK, &BasePath);
1896 FromType = QType;
1897 FromRecordType = QRecordType;
1899 // If the qualifier type was the same as the destination type,
1900 // we're done.
1901 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1902 return false;
1906 bool IgnoreAccess = false;
1908 // If we actually found the member through a using declaration, cast
1909 // down to the using declaration's type.
1911 // Pointer equality is fine here because only one declaration of a
1912 // class ever has member declarations.
1913 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1914 assert(isa<UsingShadowDecl>(FoundDecl));
1915 QualType URecordType = Context.getTypeDeclType(
1916 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1918 // We only need to do this if the naming-class to declaring-class
1919 // conversion is non-trivial.
1920 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1921 assert(IsDerivedFrom(FromRecordType, URecordType));
1922 CXXCastPath BasePath;
1923 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
1924 FromLoc, FromRange, &BasePath))
1925 return true;
1927 QualType UType = URecordType;
1928 if (PointerConversions)
1929 UType = Context.getPointerType(UType);
1930 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
1931 VK, &BasePath);
1932 FromType = UType;
1933 FromRecordType = URecordType;
1936 // We don't do access control for the conversion from the
1937 // declaring class to the true declaring class.
1938 IgnoreAccess = true;
1941 CXXCastPath BasePath;
1942 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1943 FromLoc, FromRange, &BasePath,
1944 IgnoreAccess))
1945 return true;
1947 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
1948 VK, &BasePath);
1949 return false;
1952 /// \brief Build a MemberExpr AST node.
1953 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
1954 const CXXScopeSpec &SS, ValueDecl *Member,
1955 DeclAccessPair FoundDecl,
1956 const DeclarationNameInfo &MemberNameInfo,
1957 QualType Ty,
1958 ExprValueKind VK, ExprObjectKind OK,
1959 const TemplateArgumentListInfo *TemplateArgs = 0) {
1960 NestedNameSpecifier *Qualifier = 0;
1961 SourceRange QualifierRange;
1962 if (SS.isSet()) {
1963 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1964 QualifierRange = SS.getRange();
1967 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1968 Member, FoundDecl, MemberNameInfo,
1969 TemplateArgs, Ty, VK, OK);
1972 static ExprResult
1973 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1974 const CXXScopeSpec &SS, FieldDecl *Field,
1975 DeclAccessPair FoundDecl,
1976 const DeclarationNameInfo &MemberNameInfo) {
1977 // x.a is an l-value if 'a' has a reference type. Otherwise:
1978 // x.a is an l-value/x-value/pr-value if the base is (and note
1979 // that *x is always an l-value), except that if the base isn't
1980 // an ordinary object then we must have an rvalue.
1981 ExprValueKind VK = VK_LValue;
1982 ExprObjectKind OK = OK_Ordinary;
1983 if (!IsArrow) {
1984 if (BaseExpr->getObjectKind() == OK_Ordinary)
1985 VK = BaseExpr->getValueKind();
1986 else
1987 VK = VK_RValue;
1989 if (VK != VK_RValue && Field->isBitField())
1990 OK = OK_BitField;
1992 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1993 QualType MemberType = Field->getType();
1994 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1995 MemberType = Ref->getPointeeType();
1996 VK = VK_LValue;
1997 } else {
1998 QualType BaseType = BaseExpr->getType();
1999 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2001 Qualifiers BaseQuals = BaseType.getQualifiers();
2003 // GC attributes are never picked up by members.
2004 BaseQuals.removeObjCGCAttr();
2006 // CVR attributes from the base are picked up by members,
2007 // except that 'mutable' members don't pick up 'const'.
2008 if (Field->isMutable()) BaseQuals.removeConst();
2010 Qualifiers MemberQuals
2011 = S.Context.getCanonicalType(MemberType).getQualifiers();
2013 // TR 18037 does not allow fields to be declared with address spaces.
2014 assert(!MemberQuals.hasAddressSpace());
2016 Qualifiers Combined = BaseQuals + MemberQuals;
2017 if (Combined != MemberQuals)
2018 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2021 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2022 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2023 FoundDecl, Field))
2024 return ExprError();
2025 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2026 Field, FoundDecl, MemberNameInfo,
2027 MemberType, VK, OK));
2030 /// Builds an implicit member access expression. The current context
2031 /// is known to be an instance method, and the given unqualified lookup
2032 /// set is known to contain only instance members, at least one of which
2033 /// is from an appropriate type.
2034 ExprResult
2035 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2036 LookupResult &R,
2037 const TemplateArgumentListInfo *TemplateArgs,
2038 bool IsKnownInstance) {
2039 assert(!R.empty() && !R.isAmbiguous());
2041 SourceLocation Loc = R.getNameLoc();
2043 // We may have found a field within an anonymous union or struct
2044 // (C++ [class.union]).
2045 // FIXME: This needs to happen post-isImplicitMemberReference?
2046 // FIXME: template-ids inside anonymous structs?
2047 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2048 return BuildAnonymousStructUnionMemberReference(Loc, SS, FD);
2051 // If this is known to be an instance access, go ahead and build a
2052 // 'this' expression now.
2053 DeclContext *DC = getFunctionLevelDeclContext();
2054 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
2055 Expr *This = 0; // null signifies implicit access
2056 if (IsKnownInstance) {
2057 SourceLocation Loc = R.getNameLoc();
2058 if (SS.getRange().isValid())
2059 Loc = SS.getRange().getBegin();
2060 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
2063 return BuildMemberReferenceExpr(This, ThisType,
2064 /*OpLoc*/ SourceLocation(),
2065 /*IsArrow*/ true,
2067 /*FirstQualifierInScope*/ 0,
2068 R, TemplateArgs);
2071 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2072 const LookupResult &R,
2073 bool HasTrailingLParen) {
2074 // Only when used directly as the postfix-expression of a call.
2075 if (!HasTrailingLParen)
2076 return false;
2078 // Never if a scope specifier was provided.
2079 if (SS.isSet())
2080 return false;
2082 // Only in C++ or ObjC++.
2083 if (!getLangOptions().CPlusPlus)
2084 return false;
2086 // Turn off ADL when we find certain kinds of declarations during
2087 // normal lookup:
2088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2089 NamedDecl *D = *I;
2091 // C++0x [basic.lookup.argdep]p3:
2092 // -- a declaration of a class member
2093 // Since using decls preserve this property, we check this on the
2094 // original decl.
2095 if (D->isCXXClassMember())
2096 return false;
2098 // C++0x [basic.lookup.argdep]p3:
2099 // -- a block-scope function declaration that is not a
2100 // using-declaration
2101 // NOTE: we also trigger this for function templates (in fact, we
2102 // don't check the decl type at all, since all other decl types
2103 // turn off ADL anyway).
2104 if (isa<UsingShadowDecl>(D))
2105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2106 else if (D->getDeclContext()->isFunctionOrMethod())
2107 return false;
2109 // C++0x [basic.lookup.argdep]p3:
2110 // -- a declaration that is neither a function or a function
2111 // template
2112 // And also for builtin functions.
2113 if (isa<FunctionDecl>(D)) {
2114 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2116 // But also builtin functions.
2117 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2118 return false;
2119 } else if (!isa<FunctionTemplateDecl>(D))
2120 return false;
2123 return true;
2127 /// Diagnoses obvious problems with the use of the given declaration
2128 /// as an expression. This is only actually called for lookups that
2129 /// were not overloaded, and it doesn't promise that the declaration
2130 /// will in fact be used.
2131 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2132 if (isa<TypedefDecl>(D)) {
2133 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2134 return true;
2137 if (isa<ObjCInterfaceDecl>(D)) {
2138 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2139 return true;
2142 if (isa<NamespaceDecl>(D)) {
2143 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2144 return true;
2147 return false;
2150 ExprResult
2151 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2152 LookupResult &R,
2153 bool NeedsADL) {
2154 // If this is a single, fully-resolved result and we don't need ADL,
2155 // just build an ordinary singleton decl ref.
2156 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2158 R.getFoundDecl());
2160 // We only need to check the declaration if there's exactly one
2161 // result, because in the overloaded case the results can only be
2162 // functions and function templates.
2163 if (R.isSingleResult() &&
2164 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2165 return ExprError();
2167 // Otherwise, just build an unresolved lookup expression. Suppress
2168 // any lookup-related diagnostics; we'll hash these out later, when
2169 // we've picked a target.
2170 R.suppressDiagnostics();
2172 UnresolvedLookupExpr *ULE
2173 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2174 (NestedNameSpecifier*) SS.getScopeRep(),
2175 SS.getRange(), R.getLookupNameInfo(),
2176 NeedsADL, R.isOverloadedResult(),
2177 R.begin(), R.end());
2179 return Owned(ULE);
2182 static ExprValueKind getValueKindForDecl(ASTContext &Context,
2183 const ValueDecl *D) {
2184 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2185 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2186 if (isa<FieldDecl>(D)) return VK_LValue;
2187 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2188 if (isa<FunctionDecl>(D)) {
2189 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2190 return VK_RValue;
2191 return VK_LValue;
2193 return Expr::getValueKindForType(D->getType());
2197 /// \brief Complete semantic analysis for a reference to the given declaration.
2198 ExprResult
2199 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2200 const DeclarationNameInfo &NameInfo,
2201 NamedDecl *D) {
2202 assert(D && "Cannot refer to a NULL declaration");
2203 assert(!isa<FunctionTemplateDecl>(D) &&
2204 "Cannot refer unambiguously to a function template");
2206 SourceLocation Loc = NameInfo.getLoc();
2207 if (CheckDeclInExpr(*this, Loc, D))
2208 return ExprError();
2210 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2211 // Specifically diagnose references to class templates that are missing
2212 // a template argument list.
2213 Diag(Loc, diag::err_template_decl_ref)
2214 << Template << SS.getRange();
2215 Diag(Template->getLocation(), diag::note_template_decl_here);
2216 return ExprError();
2219 // Make sure that we're referring to a value.
2220 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2221 if (!VD) {
2222 Diag(Loc, diag::err_ref_non_value)
2223 << D << SS.getRange();
2224 Diag(D->getLocation(), diag::note_declared_at);
2225 return ExprError();
2228 // Check whether this declaration can be used. Note that we suppress
2229 // this check when we're going to perform argument-dependent lookup
2230 // on this function name, because this might not be the function
2231 // that overload resolution actually selects.
2232 if (DiagnoseUseOfDecl(VD, Loc))
2233 return ExprError();
2235 // Only create DeclRefExpr's for valid Decl's.
2236 if (VD->isInvalidDecl())
2237 return ExprError();
2239 // Handle anonymous.
2240 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
2241 return BuildAnonymousStructUnionMemberReference(Loc, SS, FD);
2243 ExprValueKind VK = getValueKindForDecl(Context, VD);
2245 // If the identifier reference is inside a block, and it refers to a value
2246 // that is outside the block, create a BlockDeclRefExpr instead of a
2247 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2248 // the block is formed.
2250 // We do not do this for things like enum constants, global variables, etc,
2251 // as they do not get snapshotted.
2253 if (getCurBlock() &&
2254 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
2255 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2256 Diag(Loc, diag::err_ref_vm_type);
2257 Diag(D->getLocation(), diag::note_declared_at);
2258 return ExprError();
2261 if (VD->getType()->isArrayType()) {
2262 Diag(Loc, diag::err_ref_array_type);
2263 Diag(D->getLocation(), diag::note_declared_at);
2264 return ExprError();
2267 MarkDeclarationReferenced(Loc, VD);
2268 QualType ExprTy = VD->getType().getNonReferenceType();
2270 // The BlocksAttr indicates the variable is bound by-reference.
2271 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
2272 QualType T = VD->getType();
2273 BlockDeclRefExpr *BDRE;
2275 if (!byrefVar) {
2276 // This is to record that a 'const' was actually synthesize and added.
2277 bool constAdded = !ExprTy.isConstQualified();
2278 // Variable will be bound by-copy, make it const within the closure.
2279 ExprTy.addConst();
2280 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2281 Loc, false, constAdded);
2283 else
2284 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
2286 if (getLangOptions().CPlusPlus) {
2287 if (!T->isDependentType() && !T->isReferenceType()) {
2288 Expr *E = new (Context)
2289 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
2290 VK, SourceLocation());
2291 if (T->getAs<RecordType>())
2292 if (!T->isUnionType()) {
2293 ExprResult Res = PerformCopyInitialization(
2294 InitializedEntity::InitializeBlock(VD->getLocation(),
2295 T, false),
2296 SourceLocation(),
2297 Owned(E));
2298 if (!Res.isInvalid()) {
2299 Res = MaybeCreateExprWithCleanups(Res);
2300 Expr *Init = Res.takeAs<Expr>();
2301 BDRE->setCopyConstructorExpr(Init);
2306 return Owned(BDRE);
2308 // If this reference is not in a block or if the referenced variable is
2309 // within the block, create a normal DeclRefExpr.
2311 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
2312 NameInfo, &SS);
2315 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
2316 tok::TokenKind Kind) {
2317 PredefinedExpr::IdentType IT;
2319 switch (Kind) {
2320 default: assert(0 && "Unknown simple primary expr!");
2321 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2322 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2323 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2326 // Pre-defined identifiers are of type char[x], where x is the length of the
2327 // string.
2329 Decl *currentDecl = getCurFunctionOrMethodDecl();
2330 if (!currentDecl && getCurBlock())
2331 currentDecl = getCurBlock()->TheDecl;
2332 if (!currentDecl) {
2333 Diag(Loc, diag::ext_predef_outside_function);
2334 currentDecl = Context.getTranslationUnitDecl();
2337 QualType ResTy;
2338 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2339 ResTy = Context.DependentTy;
2340 } else {
2341 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2343 llvm::APInt LengthI(32, Length + 1);
2344 ResTy = Context.CharTy.withConst();
2345 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2347 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2350 ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2351 llvm::SmallString<16> CharBuffer;
2352 bool Invalid = false;
2353 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2354 if (Invalid)
2355 return ExprError();
2357 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2358 PP);
2359 if (Literal.hadError())
2360 return ExprError();
2362 QualType Ty;
2363 if (!getLangOptions().CPlusPlus)
2364 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2365 else if (Literal.isWide())
2366 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2367 else if (Literal.isMultiChar())
2368 Ty = Context.IntTy; // 'wxyz' -> int in C++.
2369 else
2370 Ty = Context.CharTy; // 'x' -> char in C++
2372 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2373 Literal.isWide(),
2374 Ty, Tok.getLocation()));
2377 ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2378 // Fast path for a single digit (which is quite common). A single digit
2379 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2380 if (Tok.getLength() == 1) {
2381 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2382 unsigned IntSize = Context.Target.getIntWidth();
2383 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2384 Context.IntTy, Tok.getLocation()));
2387 llvm::SmallString<512> IntegerBuffer;
2388 // Add padding so that NumericLiteralParser can overread by one character.
2389 IntegerBuffer.resize(Tok.getLength()+1);
2390 const char *ThisTokBegin = &IntegerBuffer[0];
2392 // Get the spelling of the token, which eliminates trigraphs, etc.
2393 bool Invalid = false;
2394 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2395 if (Invalid)
2396 return ExprError();
2398 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2399 Tok.getLocation(), PP);
2400 if (Literal.hadError)
2401 return ExprError();
2403 Expr *Res;
2405 if (Literal.isFloatingLiteral()) {
2406 QualType Ty;
2407 if (Literal.isFloat)
2408 Ty = Context.FloatTy;
2409 else if (!Literal.isLong)
2410 Ty = Context.DoubleTy;
2411 else
2412 Ty = Context.LongDoubleTy;
2414 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2416 using llvm::APFloat;
2417 APFloat Val(Format);
2419 APFloat::opStatus result = Literal.GetFloatValue(Val);
2421 // Overflow is always an error, but underflow is only an error if
2422 // we underflowed to zero (APFloat reports denormals as underflow).
2423 if ((result & APFloat::opOverflow) ||
2424 ((result & APFloat::opUnderflow) && Val.isZero())) {
2425 unsigned diagnostic;
2426 llvm::SmallString<20> buffer;
2427 if (result & APFloat::opOverflow) {
2428 diagnostic = diag::warn_float_overflow;
2429 APFloat::getLargest(Format).toString(buffer);
2430 } else {
2431 diagnostic = diag::warn_float_underflow;
2432 APFloat::getSmallest(Format).toString(buffer);
2435 Diag(Tok.getLocation(), diagnostic)
2436 << Ty
2437 << llvm::StringRef(buffer.data(), buffer.size());
2440 bool isExact = (result == APFloat::opOK);
2441 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2443 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2444 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2446 } else if (!Literal.isIntegerLiteral()) {
2447 return ExprError();
2448 } else {
2449 QualType Ty;
2451 // long long is a C99 feature.
2452 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
2453 Literal.isLongLong)
2454 Diag(Tok.getLocation(), diag::ext_longlong);
2456 // Get the value in the widest-possible width.
2457 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
2459 if (Literal.GetIntegerValue(ResultVal)) {
2460 // If this value didn't fit into uintmax_t, warn and force to ull.
2461 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2462 Ty = Context.UnsignedLongLongTy;
2463 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2464 "long long is not intmax_t?");
2465 } else {
2466 // If this value fits into a ULL, try to figure out what else it fits into
2467 // according to the rules of C99 6.4.4.1p5.
2469 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2470 // be an unsigned int.
2471 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2473 // Check from smallest to largest, picking the smallest type we can.
2474 unsigned Width = 0;
2475 if (!Literal.isLong && !Literal.isLongLong) {
2476 // Are int/unsigned possibilities?
2477 unsigned IntSize = Context.Target.getIntWidth();
2479 // Does it fit in a unsigned int?
2480 if (ResultVal.isIntN(IntSize)) {
2481 // Does it fit in a signed int?
2482 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2483 Ty = Context.IntTy;
2484 else if (AllowUnsigned)
2485 Ty = Context.UnsignedIntTy;
2486 Width = IntSize;
2490 // Are long/unsigned long possibilities?
2491 if (Ty.isNull() && !Literal.isLongLong) {
2492 unsigned LongSize = Context.Target.getLongWidth();
2494 // Does it fit in a unsigned long?
2495 if (ResultVal.isIntN(LongSize)) {
2496 // Does it fit in a signed long?
2497 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2498 Ty = Context.LongTy;
2499 else if (AllowUnsigned)
2500 Ty = Context.UnsignedLongTy;
2501 Width = LongSize;
2505 // Finally, check long long if needed.
2506 if (Ty.isNull()) {
2507 unsigned LongLongSize = Context.Target.getLongLongWidth();
2509 // Does it fit in a unsigned long long?
2510 if (ResultVal.isIntN(LongLongSize)) {
2511 // Does it fit in a signed long long?
2512 // To be compatible with MSVC, hex integer literals ending with the
2513 // LL or i64 suffix are always signed in Microsoft mode.
2514 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2515 (getLangOptions().Microsoft && Literal.isLongLong)))
2516 Ty = Context.LongLongTy;
2517 else if (AllowUnsigned)
2518 Ty = Context.UnsignedLongLongTy;
2519 Width = LongLongSize;
2523 // If we still couldn't decide a type, we probably have something that
2524 // does not fit in a signed long long, but has no U suffix.
2525 if (Ty.isNull()) {
2526 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2527 Ty = Context.UnsignedLongLongTy;
2528 Width = Context.Target.getLongLongWidth();
2531 if (ResultVal.getBitWidth() != Width)
2532 ResultVal = ResultVal.trunc(Width);
2534 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2537 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2538 if (Literal.isImaginary)
2539 Res = new (Context) ImaginaryLiteral(Res,
2540 Context.getComplexType(Res->getType()));
2542 return Owned(Res);
2545 ExprResult Sema::ActOnParenExpr(SourceLocation L,
2546 SourceLocation R, Expr *E) {
2547 assert((E != 0) && "ActOnParenExpr() missing expr");
2548 return Owned(new (Context) ParenExpr(L, R, E));
2551 /// The UsualUnaryConversions() function is *not* called by this routine.
2552 /// See C99 6.3.2.1p[2-4] for more details.
2553 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
2554 SourceLocation OpLoc,
2555 SourceRange ExprRange,
2556 bool isSizeof) {
2557 if (exprType->isDependentType())
2558 return false;
2560 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2561 // the result is the size of the referenced type."
2562 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2563 // result shall be the alignment of the referenced type."
2564 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2565 exprType = Ref->getPointeeType();
2567 // C99 6.5.3.4p1:
2568 if (exprType->isFunctionType()) {
2569 // alignof(function) is allowed as an extension.
2570 if (isSizeof)
2571 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2572 return false;
2575 // Allow sizeof(void)/alignof(void) as an extension.
2576 if (exprType->isVoidType()) {
2577 Diag(OpLoc, diag::ext_sizeof_void_type)
2578 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
2579 return false;
2582 if (RequireCompleteType(OpLoc, exprType,
2583 PDiag(diag::err_sizeof_alignof_incomplete_type)
2584 << int(!isSizeof) << ExprRange))
2585 return true;
2587 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2588 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
2589 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
2590 << exprType << isSizeof << ExprRange;
2591 return true;
2594 return false;
2597 static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2598 SourceRange ExprRange) {
2599 E = E->IgnoreParens();
2601 // alignof decl is always ok.
2602 if (isa<DeclRefExpr>(E))
2603 return false;
2605 // Cannot know anything else if the expression is dependent.
2606 if (E->isTypeDependent())
2607 return false;
2609 if (E->getBitField()) {
2610 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2611 return true;
2614 // Alignment of a field access is always okay, so long as it isn't a
2615 // bit-field.
2616 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2617 if (isa<FieldDecl>(ME->getMemberDecl()))
2618 return false;
2620 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2623 /// \brief Build a sizeof or alignof expression given a type operand.
2624 ExprResult
2625 Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
2626 SourceLocation OpLoc,
2627 bool isSizeOf, SourceRange R) {
2628 if (!TInfo)
2629 return ExprError();
2631 QualType T = TInfo->getType();
2633 if (!T->isDependentType() &&
2634 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2635 return ExprError();
2637 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2638 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
2639 Context.getSizeType(), OpLoc,
2640 R.getEnd()));
2643 /// \brief Build a sizeof or alignof expression given an expression
2644 /// operand.
2645 ExprResult
2646 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
2647 bool isSizeOf, SourceRange R) {
2648 // Verify that the operand is valid.
2649 bool isInvalid = false;
2650 if (E->isTypeDependent()) {
2651 // Delay type-checking for type-dependent expressions.
2652 } else if (!isSizeOf) {
2653 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
2654 } else if (E->getBitField()) { // C99 6.5.3.4p1.
2655 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2656 isInvalid = true;
2657 } else if (E->getType()->isPlaceholderType()) {
2658 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2659 if (PE.isInvalid()) return ExprError();
2660 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
2661 } else {
2662 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2665 if (isInvalid)
2666 return ExprError();
2668 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2669 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2670 Context.getSizeType(), OpLoc,
2671 R.getEnd()));
2674 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2675 /// the same for @c alignof and @c __alignof
2676 /// Note that the ArgRange is invalid if isType is false.
2677 ExprResult
2678 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2679 void *TyOrEx, const SourceRange &ArgRange) {
2680 // If error parsing type, ignore.
2681 if (TyOrEx == 0) return ExprError();
2683 if (isType) {
2684 TypeSourceInfo *TInfo;
2685 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
2686 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
2689 Expr *ArgEx = (Expr *)TyOrEx;
2690 ExprResult Result
2691 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2693 return move(Result);
2696 static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2697 bool isReal) {
2698 if (V->isTypeDependent())
2699 return S.Context.DependentTy;
2701 // _Real and _Imag are only l-values for normal l-values.
2702 if (V->getObjectKind() != OK_Ordinary)
2703 S.DefaultLvalueConversion(V);
2705 // These operators return the element type of a complex type.
2706 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
2707 return CT->getElementType();
2709 // Otherwise they pass through real integer and floating point types here.
2710 if (V->getType()->isArithmeticType())
2711 return V->getType();
2713 // Test for placeholders.
2714 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
2715 if (PR.isInvalid()) return QualType();
2716 if (PR.take() != V) {
2717 V = PR.take();
2718 return CheckRealImagOperand(S, V, Loc, isReal);
2721 // Reject anything else.
2722 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2723 << (isReal ? "__real" : "__imag");
2724 return QualType();
2729 ExprResult
2730 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2731 tok::TokenKind Kind, Expr *Input) {
2732 UnaryOperatorKind Opc;
2733 switch (Kind) {
2734 default: assert(0 && "Unknown unary op!");
2735 case tok::plusplus: Opc = UO_PostInc; break;
2736 case tok::minusminus: Opc = UO_PostDec; break;
2739 return BuildUnaryOp(S, OpLoc, Opc, Input);
2742 /// Expressions of certain arbitrary types are forbidden by C from
2743 /// having l-value type. These are:
2744 /// - 'void', but not qualified void
2745 /// - function types
2747 /// The exact rule here is C99 6.3.2.1:
2748 /// An lvalue is an expression with an object type or an incomplete
2749 /// type other than void.
2750 static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2751 return ((T->isVoidType() && !T.hasQualifiers()) ||
2752 T->isFunctionType());
2755 ExprResult
2756 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2757 Expr *Idx, SourceLocation RLoc) {
2758 // Since this might be a postfix expression, get rid of ParenListExprs.
2759 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2760 if (Result.isInvalid()) return ExprError();
2761 Base = Result.take();
2763 Expr *LHSExp = Base, *RHSExp = Idx;
2765 if (getLangOptions().CPlusPlus &&
2766 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2767 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2768 Context.DependentTy,
2769 VK_LValue, OK_Ordinary,
2770 RLoc));
2773 if (getLangOptions().CPlusPlus &&
2774 (LHSExp->getType()->isRecordType() ||
2775 LHSExp->getType()->isEnumeralType() ||
2776 RHSExp->getType()->isRecordType() ||
2777 RHSExp->getType()->isEnumeralType())) {
2778 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
2781 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
2785 ExprResult
2786 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2787 Expr *Idx, SourceLocation RLoc) {
2788 Expr *LHSExp = Base;
2789 Expr *RHSExp = Idx;
2791 // Perform default conversions.
2792 if (!LHSExp->getType()->getAs<VectorType>())
2793 DefaultFunctionArrayLvalueConversion(LHSExp);
2794 DefaultFunctionArrayLvalueConversion(RHSExp);
2796 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
2797 ExprValueKind VK = VK_LValue;
2798 ExprObjectKind OK = OK_Ordinary;
2800 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
2801 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
2802 // in the subscript position. As a result, we need to derive the array base
2803 // and index from the expression types.
2804 Expr *BaseExpr, *IndexExpr;
2805 QualType ResultType;
2806 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2807 BaseExpr = LHSExp;
2808 IndexExpr = RHSExp;
2809 ResultType = Context.DependentTy;
2810 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
2811 BaseExpr = LHSExp;
2812 IndexExpr = RHSExp;
2813 ResultType = PTy->getPointeeType();
2814 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
2815 // Handle the uncommon case of "123[Ptr]".
2816 BaseExpr = RHSExp;
2817 IndexExpr = LHSExp;
2818 ResultType = PTy->getPointeeType();
2819 } else if (const ObjCObjectPointerType *PTy =
2820 LHSTy->getAs<ObjCObjectPointerType>()) {
2821 BaseExpr = LHSExp;
2822 IndexExpr = RHSExp;
2823 ResultType = PTy->getPointeeType();
2824 } else if (const ObjCObjectPointerType *PTy =
2825 RHSTy->getAs<ObjCObjectPointerType>()) {
2826 // Handle the uncommon case of "123[Ptr]".
2827 BaseExpr = RHSExp;
2828 IndexExpr = LHSExp;
2829 ResultType = PTy->getPointeeType();
2830 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
2831 BaseExpr = LHSExp; // vectors: V[123]
2832 IndexExpr = RHSExp;
2833 VK = LHSExp->getValueKind();
2834 if (VK != VK_RValue)
2835 OK = OK_VectorComponent;
2837 // FIXME: need to deal with const...
2838 ResultType = VTy->getElementType();
2839 } else if (LHSTy->isArrayType()) {
2840 // If we see an array that wasn't promoted by
2841 // DefaultFunctionArrayLvalueConversion, it must be an array that
2842 // wasn't promoted because of the C90 rule that doesn't
2843 // allow promoting non-lvalue arrays. Warn, then
2844 // force the promotion here.
2845 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2846 LHSExp->getSourceRange();
2847 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2848 CK_ArrayToPointerDecay);
2849 LHSTy = LHSExp->getType();
2851 BaseExpr = LHSExp;
2852 IndexExpr = RHSExp;
2853 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
2854 } else if (RHSTy->isArrayType()) {
2855 // Same as previous, except for 123[f().a] case
2856 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2857 RHSExp->getSourceRange();
2858 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2859 CK_ArrayToPointerDecay);
2860 RHSTy = RHSExp->getType();
2862 BaseExpr = RHSExp;
2863 IndexExpr = LHSExp;
2864 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
2865 } else {
2866 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2867 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
2869 // C99 6.5.2.1p1
2870 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
2871 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2872 << IndexExpr->getSourceRange());
2874 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
2875 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2876 && !IndexExpr->isTypeDependent())
2877 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2879 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
2880 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2881 // type. Note that Functions are not objects, and that (in C99 parlance)
2882 // incomplete types are not object types.
2883 if (ResultType->isFunctionType()) {
2884 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2885 << ResultType << BaseExpr->getSourceRange();
2886 return ExprError();
2889 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2890 // GNU extension: subscripting on pointer to void
2891 Diag(LLoc, diag::ext_gnu_void_ptr)
2892 << BaseExpr->getSourceRange();
2894 // C forbids expressions of unqualified void type from being l-values.
2895 // See IsCForbiddenLValueType.
2896 if (!ResultType.hasQualifiers()) VK = VK_RValue;
2897 } else if (!ResultType->isDependentType() &&
2898 RequireCompleteType(LLoc, ResultType,
2899 PDiag(diag::err_subscript_incomplete_type)
2900 << BaseExpr->getSourceRange()))
2901 return ExprError();
2903 // Diagnose bad cases where we step over interface counts.
2904 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
2905 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2906 << ResultType << BaseExpr->getSourceRange();
2907 return ExprError();
2910 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2911 !IsCForbiddenLValueType(Context, ResultType));
2913 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2914 ResultType, VK, OK, RLoc));
2917 /// Check an ext-vector component access expression.
2919 /// VK should be set in advance to the value kind of the base
2920 /// expression.
2921 static QualType
2922 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2923 SourceLocation OpLoc, const IdentifierInfo *CompName,
2924 SourceLocation CompLoc) {
2925 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2926 // see FIXME there.
2928 // FIXME: This logic can be greatly simplified by splitting it along
2929 // halving/not halving and reworking the component checking.
2930 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
2932 // The vector accessor can't exceed the number of elements.
2933 const char *compStr = CompName->getNameStart();
2935 // This flag determines whether or not the component is one of the four
2936 // special names that indicate a subset of exactly half the elements are
2937 // to be selected.
2938 bool HalvingSwizzle = false;
2940 // This flag determines whether or not CompName has an 's' char prefix,
2941 // indicating that it is a string of hex values to be used as vector indices.
2942 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
2944 bool HasRepeated = false;
2945 bool HasIndex[16] = {};
2947 int Idx;
2949 // Check that we've found one of the special components, or that the component
2950 // names must come from the same set.
2951 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
2952 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2953 HalvingSwizzle = true;
2954 } else if (!HexSwizzle &&
2955 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2956 do {
2957 if (HasIndex[Idx]) HasRepeated = true;
2958 HasIndex[Idx] = true;
2959 compStr++;
2960 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2961 } else {
2962 if (HexSwizzle) compStr++;
2963 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2964 if (HasIndex[Idx]) HasRepeated = true;
2965 HasIndex[Idx] = true;
2966 compStr++;
2970 if (!HalvingSwizzle && *compStr) {
2971 // We didn't get to the end of the string. This means the component names
2972 // didn't come from the same set *or* we encountered an illegal name.
2973 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2974 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
2975 return QualType();
2978 // Ensure no component accessor exceeds the width of the vector type it
2979 // operates on.
2980 if (!HalvingSwizzle) {
2981 compStr = CompName->getNameStart();
2983 if (HexSwizzle)
2984 compStr++;
2986 while (*compStr) {
2987 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2988 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2989 << baseType << SourceRange(CompLoc);
2990 return QualType();
2995 // The component accessor looks fine - now we need to compute the actual type.
2996 // The vector type is implied by the component accessor. For example,
2997 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
2998 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
2999 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
3000 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
3001 : CompName->getLength();
3002 if (HexSwizzle)
3003 CompSize--;
3005 if (CompSize == 1)
3006 return vecType->getElementType();
3008 if (HasRepeated) VK = VK_RValue;
3010 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
3011 // Now look up the TypeDefDecl from the vector type. Without this,
3012 // diagostics look bad. We want extended vector types to appear built-in.
3013 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3014 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3015 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
3017 return VT; // should never get here (a typedef type should always be found).
3020 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
3021 IdentifierInfo *Member,
3022 const Selector &Sel,
3023 ASTContext &Context) {
3024 if (Member)
3025 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3026 return PD;
3027 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
3028 return OMD;
3030 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3031 E = PDecl->protocol_end(); I != E; ++I) {
3032 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3033 Context))
3034 return D;
3036 return 0;
3039 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3040 IdentifierInfo *Member,
3041 const Selector &Sel,
3042 ASTContext &Context) {
3043 // Check protocols on qualified interfaces.
3044 Decl *GDecl = 0;
3045 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3046 E = QIdTy->qual_end(); I != E; ++I) {
3047 if (Member)
3048 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3049 GDecl = PD;
3050 break;
3052 // Also must look for a getter or setter name which uses property syntax.
3053 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
3054 GDecl = OMD;
3055 break;
3058 if (!GDecl) {
3059 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3060 E = QIdTy->qual_end(); I != E; ++I) {
3061 // Search in the protocol-qualifier list of current protocol.
3062 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3063 Context);
3064 if (GDecl)
3065 return GDecl;
3068 return GDecl;
3071 ExprResult
3072 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
3073 bool IsArrow, SourceLocation OpLoc,
3074 const CXXScopeSpec &SS,
3075 NamedDecl *FirstQualifierInScope,
3076 const DeclarationNameInfo &NameInfo,
3077 const TemplateArgumentListInfo *TemplateArgs) {
3078 // Even in dependent contexts, try to diagnose base expressions with
3079 // obviously wrong types, e.g.:
3081 // T* t;
3082 // t.f;
3084 // In Obj-C++, however, the above expression is valid, since it could be
3085 // accessing the 'f' property if T is an Obj-C interface. The extra check
3086 // allows this, while still reporting an error if T is a struct pointer.
3087 if (!IsArrow) {
3088 const PointerType *PT = BaseType->getAs<PointerType>();
3089 if (PT && (!getLangOptions().ObjC1 ||
3090 PT->getPointeeType()->isRecordType())) {
3091 assert(BaseExpr && "cannot happen with implicit member accesses");
3092 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
3093 << BaseType << BaseExpr->getSourceRange();
3094 return ExprError();
3098 assert(BaseType->isDependentType() ||
3099 NameInfo.getName().isDependentName() ||
3100 isDependentScopeSpecifier(SS));
3102 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3103 // must have pointer type, and the accessed type is the pointee.
3104 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
3105 IsArrow, OpLoc,
3106 SS.getScopeRep(),
3107 SS.getRange(),
3108 FirstQualifierInScope,
3109 NameInfo, TemplateArgs));
3112 /// We know that the given qualified member reference points only to
3113 /// declarations which do not belong to the static type of the base
3114 /// expression. Diagnose the problem.
3115 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3116 Expr *BaseExpr,
3117 QualType BaseType,
3118 const CXXScopeSpec &SS,
3119 const LookupResult &R) {
3120 // If this is an implicit member access, use a different set of
3121 // diagnostics.
3122 if (!BaseExpr)
3123 return DiagnoseInstanceReference(SemaRef, SS, R);
3125 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
3126 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
3129 // Check whether the declarations we found through a nested-name
3130 // specifier in a member expression are actually members of the base
3131 // type. The restriction here is:
3133 // C++ [expr.ref]p2:
3134 // ... In these cases, the id-expression shall name a
3135 // member of the class or of one of its base classes.
3137 // So it's perfectly legitimate for the nested-name specifier to name
3138 // an unrelated class, and for us to find an overload set including
3139 // decls from classes which are not superclasses, as long as the decl
3140 // we actually pick through overload resolution is from a superclass.
3141 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3142 QualType BaseType,
3143 const CXXScopeSpec &SS,
3144 const LookupResult &R) {
3145 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3146 if (!BaseRT) {
3147 // We can't check this yet because the base type is still
3148 // dependent.
3149 assert(BaseType->isDependentType());
3150 return false;
3152 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
3154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3155 // If this is an implicit member reference and we find a
3156 // non-instance member, it's not an error.
3157 if (!BaseExpr && !(*I)->isCXXInstanceMember())
3158 return false;
3160 // Note that we use the DC of the decl, not the underlying decl.
3161 DeclContext *DC = (*I)->getDeclContext();
3162 while (DC->isTransparentContext())
3163 DC = DC->getParent();
3165 if (!DC->isRecord())
3166 continue;
3168 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
3169 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
3171 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3172 return false;
3175 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
3176 return true;
3179 static bool
3180 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3181 SourceRange BaseRange, const RecordType *RTy,
3182 SourceLocation OpLoc, CXXScopeSpec &SS,
3183 bool HasTemplateArgs) {
3184 RecordDecl *RDecl = RTy->getDecl();
3185 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
3186 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
3187 << BaseRange))
3188 return true;
3190 if (HasTemplateArgs) {
3191 // LookupTemplateName doesn't expect these both to exist simultaneously.
3192 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3194 bool MOUS;
3195 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3196 return false;
3199 DeclContext *DC = RDecl;
3200 if (SS.isSet()) {
3201 // If the member name was a qualified-id, look into the
3202 // nested-name-specifier.
3203 DC = SemaRef.computeDeclContext(SS, false);
3205 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
3206 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3207 << SS.getRange() << DC;
3208 return true;
3211 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
3213 if (!isa<TypeDecl>(DC)) {
3214 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3215 << DC << SS.getRange();
3216 return true;
3220 // The record definition is complete, now look up the member.
3221 SemaRef.LookupQualifiedName(R, DC);
3223 if (!R.empty())
3224 return false;
3226 // We didn't find anything with the given name, so try to correct
3227 // for typos.
3228 DeclarationName Name = R.getLookupName();
3229 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
3230 !R.empty() &&
3231 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3232 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3233 << Name << DC << R.getLookupName() << SS.getRange()
3234 << FixItHint::CreateReplacement(R.getNameLoc(),
3235 R.getLookupName().getAsString());
3236 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3237 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3238 << ND->getDeclName();
3239 return false;
3240 } else {
3241 R.clear();
3242 R.setLookupName(Name);
3245 return false;
3248 ExprResult
3249 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3250 SourceLocation OpLoc, bool IsArrow,
3251 CXXScopeSpec &SS,
3252 NamedDecl *FirstQualifierInScope,
3253 const DeclarationNameInfo &NameInfo,
3254 const TemplateArgumentListInfo *TemplateArgs) {
3255 if (BaseType->isDependentType() ||
3256 (SS.isSet() && isDependentScopeSpecifier(SS)))
3257 return ActOnDependentMemberExpr(Base, BaseType,
3258 IsArrow, OpLoc,
3259 SS, FirstQualifierInScope,
3260 NameInfo, TemplateArgs);
3262 LookupResult R(*this, NameInfo, LookupMemberName);
3264 // Implicit member accesses.
3265 if (!Base) {
3266 QualType RecordTy = BaseType;
3267 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3268 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3269 RecordTy->getAs<RecordType>(),
3270 OpLoc, SS, TemplateArgs != 0))
3271 return ExprError();
3273 // Explicit member accesses.
3274 } else {
3275 ExprResult Result =
3276 LookupMemberExpr(R, Base, IsArrow, OpLoc,
3277 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
3279 if (Result.isInvalid()) {
3280 Owned(Base);
3281 return ExprError();
3284 if (Result.get())
3285 return move(Result);
3287 // LookupMemberExpr can modify Base, and thus change BaseType
3288 BaseType = Base->getType();
3291 return BuildMemberReferenceExpr(Base, BaseType,
3292 OpLoc, IsArrow, SS, FirstQualifierInScope,
3293 R, TemplateArgs);
3296 ExprResult
3297 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
3298 SourceLocation OpLoc, bool IsArrow,
3299 const CXXScopeSpec &SS,
3300 NamedDecl *FirstQualifierInScope,
3301 LookupResult &R,
3302 const TemplateArgumentListInfo *TemplateArgs,
3303 bool SuppressQualifierCheck) {
3304 QualType BaseType = BaseExprType;
3305 if (IsArrow) {
3306 assert(BaseType->isPointerType());
3307 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3309 R.setBaseObjectType(BaseType);
3311 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3312 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3313 DeclarationName MemberName = MemberNameInfo.getName();
3314 SourceLocation MemberLoc = MemberNameInfo.getLoc();
3316 if (R.isAmbiguous())
3317 return ExprError();
3319 if (R.empty()) {
3320 // Rederive where we looked up.
3321 DeclContext *DC = (SS.isSet()
3322 ? computeDeclContext(SS, false)
3323 : BaseType->getAs<RecordType>()->getDecl());
3325 Diag(R.getNameLoc(), diag::err_no_member)
3326 << MemberName << DC
3327 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
3328 return ExprError();
3331 // Diagnose lookups that find only declarations from a non-base
3332 // type. This is possible for either qualified lookups (which may
3333 // have been qualified with an unrelated type) or implicit member
3334 // expressions (which were found with unqualified lookup and thus
3335 // may have come from an enclosing scope). Note that it's okay for
3336 // lookup to find declarations from a non-base type as long as those
3337 // aren't the ones picked by overload resolution.
3338 if ((SS.isSet() || !BaseExpr ||
3339 (isa<CXXThisExpr>(BaseExpr) &&
3340 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
3341 !SuppressQualifierCheck &&
3342 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
3343 return ExprError();
3345 // Construct an unresolved result if we in fact got an unresolved
3346 // result.
3347 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
3348 // Suppress any lookup-related diagnostics; we'll do these when we
3349 // pick a member.
3350 R.suppressDiagnostics();
3352 UnresolvedMemberExpr *MemExpr
3353 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
3354 BaseExpr, BaseExprType,
3355 IsArrow, OpLoc,
3356 Qualifier, SS.getRange(),
3357 MemberNameInfo,
3358 TemplateArgs, R.begin(), R.end());
3360 return Owned(MemExpr);
3363 assert(R.isSingleResult());
3364 DeclAccessPair FoundDecl = R.begin().getPair();
3365 NamedDecl *MemberDecl = R.getFoundDecl();
3367 // FIXME: diagnose the presence of template arguments now.
3369 // If the decl being referenced had an error, return an error for this
3370 // sub-expr without emitting another error, in order to avoid cascading
3371 // error cases.
3372 if (MemberDecl->isInvalidDecl())
3373 return ExprError();
3375 // Handle the implicit-member-access case.
3376 if (!BaseExpr) {
3377 // If this is not an instance member, convert to a non-member access.
3378 if (!MemberDecl->isCXXInstanceMember())
3379 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
3381 SourceLocation Loc = R.getNameLoc();
3382 if (SS.getRange().isValid())
3383 Loc = SS.getRange().getBegin();
3384 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
3387 bool ShouldCheckUse = true;
3388 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3389 // Don't diagnose the use of a virtual member function unless it's
3390 // explicitly qualified.
3391 if (MD->isVirtual() && !SS.isSet())
3392 ShouldCheckUse = false;
3395 // Check the use of this member.
3396 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3397 Owned(BaseExpr);
3398 return ExprError();
3401 // Perform a property load on the base regardless of whether we
3402 // actually need it for the declaration.
3403 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3404 ConvertPropertyForRValue(BaseExpr);
3406 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3407 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3408 SS, FD, FoundDecl, MemberNameInfo);
3410 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3411 // We may have found a field within an anonymous union or struct
3412 // (C++ [class.union]).
3413 return BuildAnonymousStructUnionMemberReference(MemberLoc, SS, FD,
3414 BaseExpr, OpLoc);
3416 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3417 MarkDeclarationReferenced(MemberLoc, Var);
3418 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3419 Var, FoundDecl, MemberNameInfo,
3420 Var->getType().getNonReferenceType(),
3421 VK_LValue, OK_Ordinary));
3424 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3425 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3426 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3427 MemberFn, FoundDecl, MemberNameInfo,
3428 MemberFn->getType(),
3429 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3430 OK_Ordinary));
3432 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
3434 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3435 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3436 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3437 Enum, FoundDecl, MemberNameInfo,
3438 Enum->getType(), VK_RValue, OK_Ordinary));
3441 Owned(BaseExpr);
3443 // We found something that we didn't expect. Complain.
3444 if (isa<TypeDecl>(MemberDecl))
3445 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
3446 << MemberName << BaseType << int(IsArrow);
3447 else
3448 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3449 << MemberName << BaseType << int(IsArrow);
3451 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3452 << MemberName;
3453 R.suppressDiagnostics();
3454 return ExprError();
3457 /// Given that normal member access failed on the given expression,
3458 /// and given that the expression's type involves builtin-id or
3459 /// builtin-Class, decide whether substituting in the redefinition
3460 /// types would be profitable. The redefinition type is whatever
3461 /// this translation unit tried to typedef to id/Class; we store
3462 /// it to the side and then re-use it in places like this.
3463 static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3464 const ObjCObjectPointerType *opty
3465 = base->getType()->getAs<ObjCObjectPointerType>();
3466 if (!opty) return false;
3468 const ObjCObjectType *ty = opty->getObjectType();
3470 QualType redef;
3471 if (ty->isObjCId()) {
3472 redef = S.Context.ObjCIdRedefinitionType;
3473 } else if (ty->isObjCClass()) {
3474 redef = S.Context.ObjCClassRedefinitionType;
3475 } else {
3476 return false;
3479 // Do the substitution as long as the redefinition type isn't just a
3480 // possibly-qualified pointer to builtin-id or builtin-Class again.
3481 opty = redef->getAs<ObjCObjectPointerType>();
3482 if (opty && !opty->getObjectType()->getInterface() != 0)
3483 return false;
3485 S.ImpCastExprToType(base, redef, CK_BitCast);
3486 return true;
3489 /// Look up the given member of the given non-type-dependent
3490 /// expression. This can return in one of two ways:
3491 /// * If it returns a sentinel null-but-valid result, the caller will
3492 /// assume that lookup was performed and the results written into
3493 /// the provided structure. It will take over from there.
3494 /// * Otherwise, the returned expression will be produced in place of
3495 /// an ordinary member expression.
3497 /// The ObjCImpDecl bit is a gross hack that will need to be properly
3498 /// fixed for ObjC++.
3499 ExprResult
3500 Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
3501 bool &IsArrow, SourceLocation OpLoc,
3502 CXXScopeSpec &SS,
3503 Decl *ObjCImpDecl, bool HasTemplateArgs) {
3504 assert(BaseExpr && "no base expression");
3506 // Perform default conversions.
3507 DefaultFunctionArrayConversion(BaseExpr);
3508 if (IsArrow) DefaultLvalueConversion(BaseExpr);
3510 QualType BaseType = BaseExpr->getType();
3511 assert(!BaseType->isDependentType());
3513 DeclarationName MemberName = R.getLookupName();
3514 SourceLocation MemberLoc = R.getNameLoc();
3516 // For later type-checking purposes, turn arrow accesses into dot
3517 // accesses. The only access type we support that doesn't follow
3518 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3519 // and those never use arrows, so this is unaffected.
3520 if (IsArrow) {
3521 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3522 BaseType = Ptr->getPointeeType();
3523 else if (const ObjCObjectPointerType *Ptr
3524 = BaseType->getAs<ObjCObjectPointerType>())
3525 BaseType = Ptr->getPointeeType();
3526 else if (BaseType->isRecordType()) {
3527 // Recover from arrow accesses to records, e.g.:
3528 // struct MyRecord foo;
3529 // foo->bar
3530 // This is actually well-formed in C++ if MyRecord has an
3531 // overloaded operator->, but that should have been dealt with
3532 // by now.
3533 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3534 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3535 << FixItHint::CreateReplacement(OpLoc, ".");
3536 IsArrow = false;
3537 } else {
3538 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3539 << BaseType << BaseExpr->getSourceRange();
3540 return ExprError();
3544 // Handle field access to simple records.
3545 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3546 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3547 RTy, OpLoc, SS, HasTemplateArgs))
3548 return ExprError();
3550 // Returning valid-but-null is how we indicate to the caller that
3551 // the lookup result was filled in.
3552 return Owned((Expr*) 0);
3555 // Handle ivar access to Objective-C objects.
3556 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
3557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3559 // There are three cases for the base type:
3560 // - builtin id (qualified or unqualified)
3561 // - builtin Class (qualified or unqualified)
3562 // - an interface
3563 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3564 if (!IDecl) {
3565 // There's an implicit 'isa' ivar on all objects.
3566 // But we only actually find it this way on objects of type 'id',
3567 // apparently.
3568 if (OTy->isObjCId() && Member->isStr("isa"))
3569 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3570 Context.getObjCClassType()));
3572 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3573 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3574 ObjCImpDecl, HasTemplateArgs);
3575 goto fail;
3578 ObjCInterfaceDecl *ClassDeclared;
3579 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3581 if (!IV) {
3582 // Attempt to correct for typos in ivar names.
3583 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3584 LookupMemberName);
3585 if (CorrectTypo(Res, 0, 0, IDecl, false,
3586 IsArrow ? CTC_ObjCIvarLookup
3587 : CTC_ObjCPropertyLookup) &&
3588 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3589 Diag(R.getNameLoc(),
3590 diag::err_typecheck_member_reference_ivar_suggest)
3591 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3592 << FixItHint::CreateReplacement(R.getNameLoc(),
3593 IV->getNameAsString());
3594 Diag(IV->getLocation(), diag::note_previous_decl)
3595 << IV->getDeclName();
3596 } else {
3597 Res.clear();
3598 Res.setLookupName(Member);
3600 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3601 << IDecl->getDeclName() << MemberName
3602 << BaseExpr->getSourceRange();
3603 return ExprError();
3607 // If the decl being referenced had an error, return an error for this
3608 // sub-expr without emitting another error, in order to avoid cascading
3609 // error cases.
3610 if (IV->isInvalidDecl())
3611 return ExprError();
3613 // Check whether we can reference this field.
3614 if (DiagnoseUseOfDecl(IV, MemberLoc))
3615 return ExprError();
3616 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3617 IV->getAccessControl() != ObjCIvarDecl::Package) {
3618 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3619 if (ObjCMethodDecl *MD = getCurMethodDecl())
3620 ClassOfMethodDecl = MD->getClassInterface();
3621 else if (ObjCImpDecl && getCurFunctionDecl()) {
3622 // Case of a c-function declared inside an objc implementation.
3623 // FIXME: For a c-style function nested inside an objc implementation
3624 // class, there is no implementation context available, so we pass
3625 // down the context as argument to this routine. Ideally, this context
3626 // need be passed down in the AST node and somehow calculated from the
3627 // AST for a function decl.
3628 if (ObjCImplementationDecl *IMPD =
3629 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3630 ClassOfMethodDecl = IMPD->getClassInterface();
3631 else if (ObjCCategoryImplDecl* CatImplClass =
3632 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3633 ClassOfMethodDecl = CatImplClass->getClassInterface();
3636 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3637 if (ClassDeclared != IDecl ||
3638 ClassOfMethodDecl != ClassDeclared)
3639 Diag(MemberLoc, diag::error_private_ivar_access)
3640 << IV->getDeclName();
3641 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3642 // @protected
3643 Diag(MemberLoc, diag::error_protected_ivar_access)
3644 << IV->getDeclName();
3647 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3648 MemberLoc, BaseExpr,
3649 IsArrow));
3652 // Objective-C property access.
3653 const ObjCObjectPointerType *OPT;
3654 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3655 // This actually uses the base as an r-value.
3656 DefaultLvalueConversion(BaseExpr);
3657 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3659 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3661 const ObjCObjectType *OT = OPT->getObjectType();
3663 // id, with and without qualifiers.
3664 if (OT->isObjCId()) {
3665 // Check protocols on qualified interfaces.
3666 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3667 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3668 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3669 // Check the use of this declaration
3670 if (DiagnoseUseOfDecl(PD, MemberLoc))
3671 return ExprError();
3673 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3674 VK_LValue,
3675 OK_ObjCProperty,
3676 MemberLoc,
3677 BaseExpr));
3680 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3681 // Check the use of this method.
3682 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3683 return ExprError();
3684 Selector SetterSel =
3685 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3686 PP.getSelectorTable(), Member);
3687 ObjCMethodDecl *SMD = 0;
3688 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3689 SetterSel, Context))
3690 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3691 QualType PType = OMD->getSendResultType();
3693 ExprValueKind VK = VK_LValue;
3694 if (!getLangOptions().CPlusPlus &&
3695 IsCForbiddenLValueType(Context, PType))
3696 VK = VK_RValue;
3697 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3699 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3700 VK, OK,
3701 MemberLoc, BaseExpr));
3705 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3706 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3707 ObjCImpDecl, HasTemplateArgs);
3709 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3710 << MemberName << BaseType);
3713 // 'Class', unqualified only.
3714 if (OT->isObjCClass()) {
3715 // Only works in a method declaration (??!).
3716 ObjCMethodDecl *MD = getCurMethodDecl();
3717 if (!MD) {
3718 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3719 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3720 ObjCImpDecl, HasTemplateArgs);
3722 goto fail;
3725 // Also must look for a getter name which uses property syntax.
3726 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3727 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3728 ObjCMethodDecl *Getter;
3729 if ((Getter = IFace->lookupClassMethod(Sel))) {
3730 // Check the use of this method.
3731 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3732 return ExprError();
3733 } else
3734 Getter = IFace->lookupPrivateMethod(Sel, false);
3735 // If we found a getter then this may be a valid dot-reference, we
3736 // will look for the matching setter, in case it is needed.
3737 Selector SetterSel =
3738 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3739 PP.getSelectorTable(), Member);
3740 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3741 if (!Setter) {
3742 // If this reference is in an @implementation, also check for 'private'
3743 // methods.
3744 Setter = IFace->lookupPrivateMethod(SetterSel, false);
3746 // Look through local category implementations associated with the class.
3747 if (!Setter)
3748 Setter = IFace->getCategoryClassMethod(SetterSel);
3750 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3751 return ExprError();
3753 if (Getter || Setter) {
3754 QualType PType;
3756 ExprValueKind VK = VK_LValue;
3757 if (Getter) {
3758 PType = Getter->getSendResultType();
3759 if (!getLangOptions().CPlusPlus &&
3760 IsCForbiddenLValueType(Context, PType))
3761 VK = VK_RValue;
3762 } else {
3763 // Get the expression type from Setter's incoming parameter.
3764 PType = (*(Setter->param_end() -1))->getType();
3766 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3768 // FIXME: we must check that the setter has property type.
3769 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3770 PType, VK, OK,
3771 MemberLoc, BaseExpr));
3774 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3775 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3776 ObjCImpDecl, HasTemplateArgs);
3778 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3779 << MemberName << BaseType);
3782 // Normal property access.
3783 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3784 SourceLocation(), QualType(), false);
3787 // Handle 'field access' to vectors, such as 'V.xx'.
3788 if (BaseType->isExtVectorType()) {
3789 // FIXME: this expr should store IsArrow.
3790 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3791 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
3792 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3793 Member, MemberLoc);
3794 if (ret.isNull())
3795 return ExprError();
3797 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3798 *Member, MemberLoc));
3801 // Adjust builtin-sel to the appropriate redefinition type if that's
3802 // not just a pointer to builtin-sel again.
3803 if (IsArrow &&
3804 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3805 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3806 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3807 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3808 ObjCImpDecl, HasTemplateArgs);
3811 // Failure cases.
3812 fail:
3814 // There's a possible road to recovery for function types.
3815 const FunctionType *Fun = 0;
3817 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3818 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3819 // fall out, handled below.
3821 // Recover from dot accesses to pointers, e.g.:
3822 // type *foo;
3823 // foo.bar
3824 // This is actually well-formed in two cases:
3825 // - 'type' is an Objective C type
3826 // - 'bar' is a pseudo-destructor name which happens to refer to
3827 // the appropriate pointer type
3828 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
3829 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3830 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3831 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3832 << FixItHint::CreateReplacement(OpLoc, "->");
3834 // Recurse as an -> access.
3835 IsArrow = true;
3836 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3837 ObjCImpDecl, HasTemplateArgs);
3839 } else {
3840 Fun = BaseType->getAs<FunctionType>();
3843 // If the user is trying to apply -> or . to a function pointer
3844 // type, it's probably because they forgot parentheses to call that
3845 // function. Suggest the addition of those parentheses, build the
3846 // call, and continue on.
3847 if (Fun || BaseType == Context.OverloadTy) {
3848 bool TryCall;
3849 if (BaseType == Context.OverloadTy) {
3850 TryCall = true;
3851 } else {
3852 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
3853 TryCall = (FPT->getNumArgs() == 0);
3854 } else {
3855 TryCall = true;
3858 if (TryCall) {
3859 QualType ResultTy = Fun->getResultType();
3860 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
3861 (IsArrow && ResultTy->isPointerType() &&
3862 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
3867 if (TryCall) {
3868 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3869 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
3870 << QualType(Fun, 0)
3871 << FixItHint::CreateInsertion(Loc, "()");
3873 ExprResult NewBase
3874 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
3875 if (NewBase.isInvalid())
3876 return ExprError();
3877 BaseExpr = NewBase.takeAs<Expr>();
3880 DefaultFunctionArrayConversion(BaseExpr);
3881 BaseType = BaseExpr->getType();
3883 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3884 ObjCImpDecl, HasTemplateArgs);
3888 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3889 << BaseType << BaseExpr->getSourceRange();
3891 return ExprError();
3894 /// The main callback when the parser finds something like
3895 /// expression . [nested-name-specifier] identifier
3896 /// expression -> [nested-name-specifier] identifier
3897 /// where 'identifier' encompasses a fairly broad spectrum of
3898 /// possibilities, including destructor and operator references.
3900 /// \param OpKind either tok::arrow or tok::period
3901 /// \param HasTrailingLParen whether the next token is '(', which
3902 /// is used to diagnose mis-uses of special members that can
3903 /// only be called
3904 /// \param ObjCImpDecl the current ObjC @implementation decl;
3905 /// this is an ugly hack around the fact that ObjC @implementations
3906 /// aren't properly put in the context chain
3907 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
3908 SourceLocation OpLoc,
3909 tok::TokenKind OpKind,
3910 CXXScopeSpec &SS,
3911 UnqualifiedId &Id,
3912 Decl *ObjCImpDecl,
3913 bool HasTrailingLParen) {
3914 if (SS.isSet() && SS.isInvalid())
3915 return ExprError();
3917 // Warn about the explicit constructor calls Microsoft extension.
3918 if (getLangOptions().Microsoft &&
3919 Id.getKind() == UnqualifiedId::IK_ConstructorName)
3920 Diag(Id.getSourceRange().getBegin(),
3921 diag::ext_ms_explicit_constructor_call);
3923 TemplateArgumentListInfo TemplateArgsBuffer;
3925 // Decompose the name into its component parts.
3926 DeclarationNameInfo NameInfo;
3927 const TemplateArgumentListInfo *TemplateArgs;
3928 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3929 NameInfo, TemplateArgs);
3931 DeclarationName Name = NameInfo.getName();
3932 bool IsArrow = (OpKind == tok::arrow);
3934 NamedDecl *FirstQualifierInScope
3935 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3936 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3938 // This is a postfix expression, so get rid of ParenListExprs.
3939 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3940 if (Result.isInvalid()) return ExprError();
3941 Base = Result.take();
3943 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3944 isDependentScopeSpecifier(SS)) {
3945 Result = ActOnDependentMemberExpr(Base, Base->getType(),
3946 IsArrow, OpLoc,
3947 SS, FirstQualifierInScope,
3948 NameInfo, TemplateArgs);
3949 } else {
3950 LookupResult R(*this, NameInfo, LookupMemberName);
3951 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3952 SS, ObjCImpDecl, TemplateArgs != 0);
3954 if (Result.isInvalid()) {
3955 Owned(Base);
3956 return ExprError();
3959 if (Result.get()) {
3960 // The only way a reference to a destructor can be used is to
3961 // immediately call it, which falls into this case. If the
3962 // next token is not a '(', produce a diagnostic and build the
3963 // call now.
3964 if (!HasTrailingLParen &&
3965 Id.getKind() == UnqualifiedId::IK_DestructorName)
3966 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
3968 return move(Result);
3971 Result = BuildMemberReferenceExpr(Base, Base->getType(),
3972 OpLoc, IsArrow, SS, FirstQualifierInScope,
3973 R, TemplateArgs);
3976 return move(Result);
3979 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3980 FunctionDecl *FD,
3981 ParmVarDecl *Param) {
3982 if (Param->hasUnparsedDefaultArg()) {
3983 Diag(CallLoc,
3984 diag::err_use_of_default_argument_to_function_declared_later) <<
3985 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3986 Diag(UnparsedDefaultArgLocs[Param],
3987 diag::note_default_argument_declared_here);
3988 return ExprError();
3991 if (Param->hasUninstantiatedDefaultArg()) {
3992 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3994 // Instantiate the expression.
3995 MultiLevelTemplateArgumentList ArgList
3996 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3998 std::pair<const TemplateArgument *, unsigned> Innermost
3999 = ArgList.getInnermost();
4000 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4001 Innermost.second);
4003 ExprResult Result;
4005 // C++ [dcl.fct.default]p5:
4006 // The names in the [default argument] expression are bound, and
4007 // the semantic constraints are checked, at the point where the
4008 // default argument expression appears.
4009 ContextRAII SavedContext(*this, FD);
4010 Result = SubstExpr(UninstExpr, ArgList);
4012 if (Result.isInvalid())
4013 return ExprError();
4015 // Check the expression as an initializer for the parameter.
4016 InitializedEntity Entity
4017 = InitializedEntity::InitializeParameter(Context, Param);
4018 InitializationKind Kind
4019 = InitializationKind::CreateCopy(Param->getLocation(),
4020 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4021 Expr *ResultE = Result.takeAs<Expr>();
4023 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4024 Result = InitSeq.Perform(*this, Entity, Kind,
4025 MultiExprArg(*this, &ResultE, 1));
4026 if (Result.isInvalid())
4027 return ExprError();
4029 // Build the default argument expression.
4030 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4031 Result.takeAs<Expr>()));
4034 // If the default expression creates temporaries, we need to
4035 // push them to the current stack of expression temporaries so they'll
4036 // be properly destroyed.
4037 // FIXME: We should really be rebuilding the default argument with new
4038 // bound temporaries; see the comment in PR5810.
4039 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4040 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4041 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4042 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4043 ExprTemporaries.push_back(Temporary);
4046 // We already type-checked the argument, so we know it works.
4047 // Just mark all of the declarations in this potentially-evaluated expression
4048 // as being "referenced".
4049 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
4050 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
4053 /// ConvertArgumentsForCall - Converts the arguments specified in
4054 /// Args/NumArgs to the parameter types of the function FDecl with
4055 /// function prototype Proto. Call is the call expression itself, and
4056 /// Fn is the function expression. For a C++ member function, this
4057 /// routine does not attempt to convert the object argument. Returns
4058 /// true if the call is ill-formed.
4059 bool
4060 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4061 FunctionDecl *FDecl,
4062 const FunctionProtoType *Proto,
4063 Expr **Args, unsigned NumArgs,
4064 SourceLocation RParenLoc) {
4065 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4066 // assignment, to the types of the corresponding parameter, ...
4067 unsigned NumArgsInProto = Proto->getNumArgs();
4068 bool Invalid = false;
4070 // If too few arguments are available (and we don't have default
4071 // arguments for the remaining parameters), don't make the call.
4072 if (NumArgs < NumArgsInProto) {
4073 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4074 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4075 << Fn->getType()->isBlockPointerType()
4076 << NumArgsInProto << NumArgs << Fn->getSourceRange();
4077 Call->setNumArgs(Context, NumArgsInProto);
4080 // If too many are passed and not variadic, error on the extras and drop
4081 // them.
4082 if (NumArgs > NumArgsInProto) {
4083 if (!Proto->isVariadic()) {
4084 Diag(Args[NumArgsInProto]->getLocStart(),
4085 diag::err_typecheck_call_too_many_args)
4086 << Fn->getType()->isBlockPointerType()
4087 << NumArgsInProto << NumArgs << Fn->getSourceRange()
4088 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4089 Args[NumArgs-1]->getLocEnd());
4090 // This deletes the extra arguments.
4091 Call->setNumArgs(Context, NumArgsInProto);
4092 return true;
4095 llvm::SmallVector<Expr *, 8> AllArgs;
4096 VariadicCallType CallType =
4097 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4098 if (Fn->getType()->isBlockPointerType())
4099 CallType = VariadicBlock; // Block
4100 else if (isa<MemberExpr>(Fn))
4101 CallType = VariadicMethod;
4102 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
4103 Proto, 0, Args, NumArgs, AllArgs, CallType);
4104 if (Invalid)
4105 return true;
4106 unsigned TotalNumArgs = AllArgs.size();
4107 for (unsigned i = 0; i < TotalNumArgs; ++i)
4108 Call->setArg(i, AllArgs[i]);
4110 return false;
4113 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4114 FunctionDecl *FDecl,
4115 const FunctionProtoType *Proto,
4116 unsigned FirstProtoArg,
4117 Expr **Args, unsigned NumArgs,
4118 llvm::SmallVector<Expr *, 8> &AllArgs,
4119 VariadicCallType CallType) {
4120 unsigned NumArgsInProto = Proto->getNumArgs();
4121 unsigned NumArgsToCheck = NumArgs;
4122 bool Invalid = false;
4123 if (NumArgs != NumArgsInProto)
4124 // Use default arguments for missing arguments
4125 NumArgsToCheck = NumArgsInProto;
4126 unsigned ArgIx = 0;
4127 // Continue to check argument types (even if we have too few/many args).
4128 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4129 QualType ProtoArgType = Proto->getArgType(i);
4131 Expr *Arg;
4132 if (ArgIx < NumArgs) {
4133 Arg = Args[ArgIx++];
4135 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4136 ProtoArgType,
4137 PDiag(diag::err_call_incomplete_argument)
4138 << Arg->getSourceRange()))
4139 return true;
4141 // Pass the argument
4142 ParmVarDecl *Param = 0;
4143 if (FDecl && i < FDecl->getNumParams())
4144 Param = FDecl->getParamDecl(i);
4146 InitializedEntity Entity =
4147 Param? InitializedEntity::InitializeParameter(Context, Param)
4148 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
4149 ExprResult ArgE = PerformCopyInitialization(Entity,
4150 SourceLocation(),
4151 Owned(Arg));
4152 if (ArgE.isInvalid())
4153 return true;
4155 Arg = ArgE.takeAs<Expr>();
4156 } else {
4157 ParmVarDecl *Param = FDecl->getParamDecl(i);
4159 ExprResult ArgExpr =
4160 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4161 if (ArgExpr.isInvalid())
4162 return true;
4164 Arg = ArgExpr.takeAs<Expr>();
4166 AllArgs.push_back(Arg);
4169 // If this is a variadic call, handle args passed through "...".
4170 if (CallType != VariadicDoesNotApply) {
4171 // Promote the arguments (C99 6.5.2.2p7).
4172 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4173 Expr *Arg = Args[i];
4174 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
4175 AllArgs.push_back(Arg);
4178 return Invalid;
4181 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4182 /// This provides the location of the left/right parens and a list of comma
4183 /// locations.
4184 ExprResult
4185 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4186 MultiExprArg args, SourceLocation RParenLoc) {
4187 unsigned NumArgs = args.size();
4189 // Since this might be a postfix expression, get rid of ParenListExprs.
4190 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4191 if (Result.isInvalid()) return ExprError();
4192 Fn = Result.take();
4194 Expr **Args = args.release();
4196 if (getLangOptions().CPlusPlus) {
4197 // If this is a pseudo-destructor expression, build the call immediately.
4198 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4199 if (NumArgs > 0) {
4200 // Pseudo-destructor calls should not have any arguments.
4201 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4202 << FixItHint::CreateRemoval(
4203 SourceRange(Args[0]->getLocStart(),
4204 Args[NumArgs-1]->getLocEnd()));
4206 NumArgs = 0;
4209 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
4210 VK_RValue, RParenLoc));
4213 // Determine whether this is a dependent call inside a C++ template,
4214 // in which case we won't do any semantic analysis now.
4215 // FIXME: Will need to cache the results of name lookup (including ADL) in
4216 // Fn.
4217 bool Dependent = false;
4218 if (Fn->isTypeDependent())
4219 Dependent = true;
4220 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4221 Dependent = true;
4223 if (Dependent)
4224 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4225 Context.DependentTy, VK_RValue,
4226 RParenLoc));
4228 // Determine whether this is a call to an object (C++ [over.call.object]).
4229 if (Fn->getType()->isRecordType())
4230 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
4231 RParenLoc));
4233 Expr *NakedFn = Fn->IgnoreParens();
4235 // Determine whether this is a call to an unresolved member function.
4236 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4237 // If lookup was unresolved but not dependent (i.e. didn't find
4238 // an unresolved using declaration), it has to be an overloaded
4239 // function set, which means it must contain either multiple
4240 // declarations (all methods or method templates) or a single
4241 // method template.
4242 assert((MemE->getNumDecls() > 1) ||
4243 isa<FunctionTemplateDecl>(
4244 (*MemE->decls_begin())->getUnderlyingDecl()));
4245 (void)MemE;
4247 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4248 RParenLoc);
4251 // Determine whether this is a call to a member function.
4252 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
4253 NamedDecl *MemDecl = MemExpr->getMemberDecl();
4254 if (isa<CXXMethodDecl>(MemDecl))
4255 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4256 RParenLoc);
4259 // Determine whether this is a call to a pointer-to-member function.
4260 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
4261 if (BO->getOpcode() == BO_PtrMemD ||
4262 BO->getOpcode() == BO_PtrMemI) {
4263 if (const FunctionProtoType *FPT
4264 = BO->getType()->getAs<FunctionProtoType>()) {
4265 QualType ResultTy = FPT->getCallResultType(Context);
4266 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
4268 CXXMemberCallExpr *TheCall
4269 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
4270 NumArgs, ResultTy, VK,
4271 RParenLoc);
4273 if (CheckCallReturnType(FPT->getResultType(),
4274 BO->getRHS()->getSourceRange().getBegin(),
4275 TheCall, 0))
4276 return ExprError();
4278 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
4279 RParenLoc))
4280 return ExprError();
4282 return MaybeBindToTemporary(TheCall);
4284 return ExprError(Diag(Fn->getLocStart(),
4285 diag::err_typecheck_call_not_function)
4286 << Fn->getType() << Fn->getSourceRange());
4291 // If we're directly calling a function, get the appropriate declaration.
4292 // Also, in C++, keep track of whether we should perform argument-dependent
4293 // lookup and whether there were any explicitly-specified template arguments.
4295 Expr *NakedFn = Fn->IgnoreParens();
4296 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4297 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4298 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4299 RParenLoc);
4302 NamedDecl *NDecl = 0;
4303 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4304 if (UnOp->getOpcode() == UO_AddrOf)
4305 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4307 if (isa<DeclRefExpr>(NakedFn))
4308 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4310 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4313 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4314 /// i.e. an expression not of \p OverloadTy. The expression should
4315 /// unary-convert to an expression of function-pointer or
4316 /// block-pointer type.
4318 /// \param NDecl the declaration being called, if available
4319 ExprResult
4320 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4321 SourceLocation LParenLoc,
4322 Expr **Args, unsigned NumArgs,
4323 SourceLocation RParenLoc) {
4324 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4326 // Promote the function operand.
4327 UsualUnaryConversions(Fn);
4329 // Make the call expr early, before semantic checks. This guarantees cleanup
4330 // of arguments and function on error.
4331 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4332 Args, NumArgs,
4333 Context.BoolTy,
4334 VK_RValue,
4335 RParenLoc);
4337 const FunctionType *FuncT;
4338 if (!Fn->getType()->isBlockPointerType()) {
4339 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4340 // have type pointer to function".
4341 const PointerType *PT = Fn->getType()->getAs<PointerType>();
4342 if (PT == 0)
4343 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4344 << Fn->getType() << Fn->getSourceRange());
4345 FuncT = PT->getPointeeType()->getAs<FunctionType>();
4346 } else { // This is a block call.
4347 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
4348 getAs<FunctionType>();
4350 if (FuncT == 0)
4351 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4352 << Fn->getType() << Fn->getSourceRange());
4354 // Check for a valid return type
4355 if (CheckCallReturnType(FuncT->getResultType(),
4356 Fn->getSourceRange().getBegin(), TheCall,
4357 FDecl))
4358 return ExprError();
4360 // We know the result type of the call, set it.
4361 TheCall->setType(FuncT->getCallResultType(Context));
4362 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4364 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
4365 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4366 RParenLoc))
4367 return ExprError();
4368 } else {
4369 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4371 if (FDecl) {
4372 // Check if we have too few/too many template arguments, based
4373 // on our knowledge of the function definition.
4374 const FunctionDecl *Def = 0;
4375 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4376 const FunctionProtoType *Proto
4377 = Def->getType()->getAs<FunctionProtoType>();
4378 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4379 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4380 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4383 // If the function we're calling isn't a function prototype, but we have
4384 // a function prototype from a prior declaratiom, use that prototype.
4385 if (!FDecl->hasPrototype())
4386 Proto = FDecl->getType()->getAs<FunctionProtoType>();
4389 // Promote the arguments (C99 6.5.2.2p6).
4390 for (unsigned i = 0; i != NumArgs; i++) {
4391 Expr *Arg = Args[i];
4393 if (Proto && i < Proto->getNumArgs()) {
4394 InitializedEntity Entity
4395 = InitializedEntity::InitializeParameter(Context,
4396 Proto->getArgType(i));
4397 ExprResult ArgE = PerformCopyInitialization(Entity,
4398 SourceLocation(),
4399 Owned(Arg));
4400 if (ArgE.isInvalid())
4401 return true;
4403 Arg = ArgE.takeAs<Expr>();
4405 } else {
4406 DefaultArgumentPromotion(Arg);
4409 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4410 Arg->getType(),
4411 PDiag(diag::err_call_incomplete_argument)
4412 << Arg->getSourceRange()))
4413 return ExprError();
4415 TheCall->setArg(i, Arg);
4419 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4420 if (!Method->isStatic())
4421 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4422 << Fn->getSourceRange());
4424 // Check for sentinels
4425 if (NDecl)
4426 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4428 // Do special checking on direct calls to functions.
4429 if (FDecl) {
4430 if (CheckFunctionCall(FDecl, TheCall))
4431 return ExprError();
4433 if (unsigned BuiltinID = FDecl->getBuiltinID())
4434 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4435 } else if (NDecl) {
4436 if (CheckBlockCall(NDecl, TheCall))
4437 return ExprError();
4440 return MaybeBindToTemporary(TheCall);
4443 ExprResult
4444 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4445 SourceLocation RParenLoc, Expr *InitExpr) {
4446 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4447 // FIXME: put back this assert when initializers are worked out.
4448 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4450 TypeSourceInfo *TInfo;
4451 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4452 if (!TInfo)
4453 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4455 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4458 ExprResult
4459 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4460 SourceLocation RParenLoc, Expr *literalExpr) {
4461 QualType literalType = TInfo->getType();
4463 if (literalType->isArrayType()) {
4464 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4465 PDiag(diag::err_illegal_decl_array_incomplete_type)
4466 << SourceRange(LParenLoc,
4467 literalExpr->getSourceRange().getEnd())))
4468 return ExprError();
4469 if (literalType->isVariableArrayType())
4470 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4471 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
4472 } else if (!literalType->isDependentType() &&
4473 RequireCompleteType(LParenLoc, literalType,
4474 PDiag(diag::err_typecheck_decl_incomplete_type)
4475 << SourceRange(LParenLoc,
4476 literalExpr->getSourceRange().getEnd())))
4477 return ExprError();
4479 InitializedEntity Entity
4480 = InitializedEntity::InitializeTemporary(literalType);
4481 InitializationKind Kind
4482 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
4483 /*IsCStyleCast=*/true);
4484 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
4485 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4486 MultiExprArg(*this, &literalExpr, 1),
4487 &literalType);
4488 if (Result.isInvalid())
4489 return ExprError();
4490 literalExpr = Result.get();
4492 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4493 if (isFileScope) { // 6.5.2.5p3
4494 if (CheckForConstantInitializer(literalExpr, literalType))
4495 return ExprError();
4498 // In C, compound literals are l-values for some reason.
4499 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4501 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4502 VK, literalExpr, isFileScope));
4505 ExprResult
4506 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
4507 SourceLocation RBraceLoc) {
4508 unsigned NumInit = initlist.size();
4509 Expr **InitList = initlist.release();
4511 // Semantic analysis for initializers is done by ActOnDeclarator() and
4512 // CheckInitializer() - it requires knowledge of the object being intialized.
4514 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4515 NumInit, RBraceLoc);
4516 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4517 return Owned(E);
4520 /// Prepares for a scalar cast, performing all the necessary stages
4521 /// except the final cast and returning the kind required.
4522 static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4523 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4524 // Also, callers should have filtered out the invalid cases with
4525 // pointers. Everything else should be possible.
4527 QualType SrcTy = Src->getType();
4528 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
4529 return CK_NoOp;
4531 switch (SrcTy->getScalarTypeKind()) {
4532 case Type::STK_MemberPointer:
4533 llvm_unreachable("member pointer type in C");
4535 case Type::STK_Pointer:
4536 switch (DestTy->getScalarTypeKind()) {
4537 case Type::STK_Pointer:
4538 return DestTy->isObjCObjectPointerType() ?
4539 CK_AnyPointerToObjCPointerCast :
4540 CK_BitCast;
4541 case Type::STK_Bool:
4542 return CK_PointerToBoolean;
4543 case Type::STK_Integral:
4544 return CK_PointerToIntegral;
4545 case Type::STK_Floating:
4546 case Type::STK_FloatingComplex:
4547 case Type::STK_IntegralComplex:
4548 case Type::STK_MemberPointer:
4549 llvm_unreachable("illegal cast from pointer");
4551 break;
4553 case Type::STK_Bool: // casting from bool is like casting from an integer
4554 case Type::STK_Integral:
4555 switch (DestTy->getScalarTypeKind()) {
4556 case Type::STK_Pointer:
4557 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
4558 return CK_NullToPointer;
4559 return CK_IntegralToPointer;
4560 case Type::STK_Bool:
4561 return CK_IntegralToBoolean;
4562 case Type::STK_Integral:
4563 return CK_IntegralCast;
4564 case Type::STK_Floating:
4565 return CK_IntegralToFloating;
4566 case Type::STK_IntegralComplex:
4567 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4568 CK_IntegralCast);
4569 return CK_IntegralRealToComplex;
4570 case Type::STK_FloatingComplex:
4571 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4572 CK_IntegralToFloating);
4573 return CK_FloatingRealToComplex;
4574 case Type::STK_MemberPointer:
4575 llvm_unreachable("member pointer type in C");
4577 break;
4579 case Type::STK_Floating:
4580 switch (DestTy->getScalarTypeKind()) {
4581 case Type::STK_Floating:
4582 return CK_FloatingCast;
4583 case Type::STK_Bool:
4584 return CK_FloatingToBoolean;
4585 case Type::STK_Integral:
4586 return CK_FloatingToIntegral;
4587 case Type::STK_FloatingComplex:
4588 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4589 CK_FloatingCast);
4590 return CK_FloatingRealToComplex;
4591 case Type::STK_IntegralComplex:
4592 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4593 CK_FloatingToIntegral);
4594 return CK_IntegralRealToComplex;
4595 case Type::STK_Pointer:
4596 llvm_unreachable("valid float->pointer cast?");
4597 case Type::STK_MemberPointer:
4598 llvm_unreachable("member pointer type in C");
4600 break;
4602 case Type::STK_FloatingComplex:
4603 switch (DestTy->getScalarTypeKind()) {
4604 case Type::STK_FloatingComplex:
4605 return CK_FloatingComplexCast;
4606 case Type::STK_IntegralComplex:
4607 return CK_FloatingComplexToIntegralComplex;
4608 case Type::STK_Floating: {
4609 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
4610 if (S.Context.hasSameType(ET, DestTy))
4611 return CK_FloatingComplexToReal;
4612 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4613 return CK_FloatingCast;
4615 case Type::STK_Bool:
4616 return CK_FloatingComplexToBoolean;
4617 case Type::STK_Integral:
4618 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
4619 CK_FloatingComplexToReal);
4620 return CK_FloatingToIntegral;
4621 case Type::STK_Pointer:
4622 llvm_unreachable("valid complex float->pointer cast?");
4623 case Type::STK_MemberPointer:
4624 llvm_unreachable("member pointer type in C");
4626 break;
4628 case Type::STK_IntegralComplex:
4629 switch (DestTy->getScalarTypeKind()) {
4630 case Type::STK_FloatingComplex:
4631 return CK_IntegralComplexToFloatingComplex;
4632 case Type::STK_IntegralComplex:
4633 return CK_IntegralComplexCast;
4634 case Type::STK_Integral: {
4635 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
4636 if (S.Context.hasSameType(ET, DestTy))
4637 return CK_IntegralComplexToReal;
4638 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4639 return CK_IntegralCast;
4641 case Type::STK_Bool:
4642 return CK_IntegralComplexToBoolean;
4643 case Type::STK_Floating:
4644 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
4645 CK_IntegralComplexToReal);
4646 return CK_IntegralToFloating;
4647 case Type::STK_Pointer:
4648 llvm_unreachable("valid complex int->pointer cast?");
4649 case Type::STK_MemberPointer:
4650 llvm_unreachable("member pointer type in C");
4652 break;
4655 llvm_unreachable("Unhandled scalar cast");
4656 return CK_BitCast;
4659 /// CheckCastTypes - Check type constraints for casting between types.
4660 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4661 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4662 CXXCastPath &BasePath, bool FunctionalStyle) {
4663 if (getLangOptions().CPlusPlus)
4664 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4665 castExpr->getLocEnd()),
4666 castType, VK, castExpr, Kind, BasePath,
4667 FunctionalStyle);
4669 // We only support r-value casts in C.
4670 VK = VK_RValue;
4672 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4673 // type needs to be scalar.
4674 if (castType->isVoidType()) {
4675 // We don't necessarily do lvalue-to-rvalue conversions on this.
4676 IgnoredValueConversions(castExpr);
4678 // Cast to void allows any expr type.
4679 Kind = CK_ToVoid;
4680 return false;
4683 DefaultFunctionArrayLvalueConversion(castExpr);
4685 if (RequireCompleteType(TyR.getBegin(), castType,
4686 diag::err_typecheck_cast_to_incomplete))
4687 return true;
4689 if (!castType->isScalarType() && !castType->isVectorType()) {
4690 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
4691 (castType->isStructureType() || castType->isUnionType())) {
4692 // GCC struct/union extension: allow cast to self.
4693 // FIXME: Check that the cast destination type is complete.
4694 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4695 << castType << castExpr->getSourceRange();
4696 Kind = CK_NoOp;
4697 return false;
4700 if (castType->isUnionType()) {
4701 // GCC cast to union extension
4702 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
4703 RecordDecl::field_iterator Field, FieldEnd;
4704 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
4705 Field != FieldEnd; ++Field) {
4706 if (Context.hasSameUnqualifiedType(Field->getType(),
4707 castExpr->getType()) &&
4708 !Field->isUnnamedBitfield()) {
4709 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4710 << castExpr->getSourceRange();
4711 break;
4714 if (Field == FieldEnd)
4715 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4716 << castExpr->getType() << castExpr->getSourceRange();
4717 Kind = CK_ToUnion;
4718 return false;
4721 // Reject any other conversions to non-scalar types.
4722 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4723 << castType << castExpr->getSourceRange();
4726 // The type we're casting to is known to be a scalar or vector.
4728 // Require the operand to be a scalar or vector.
4729 if (!castExpr->getType()->isScalarType() &&
4730 !castExpr->getType()->isVectorType()) {
4731 return Diag(castExpr->getLocStart(),
4732 diag::err_typecheck_expect_scalar_operand)
4733 << castExpr->getType() << castExpr->getSourceRange();
4736 if (castType->isExtVectorType())
4737 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
4739 if (castType->isVectorType())
4740 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4741 if (castExpr->getType()->isVectorType())
4742 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4744 // The source and target types are both scalars, i.e.
4745 // - arithmetic types (fundamental, enum, and complex)
4746 // - all kinds of pointers
4747 // Note that member pointers were filtered out with C++, above.
4749 if (isa<ObjCSelectorExpr>(castExpr))
4750 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4752 // If either type is a pointer, the other type has to be either an
4753 // integer or a pointer.
4754 if (!castType->isArithmeticType()) {
4755 QualType castExprType = castExpr->getType();
4756 if (!castExprType->isIntegralType(Context) &&
4757 castExprType->isArithmeticType())
4758 return Diag(castExpr->getLocStart(),
4759 diag::err_cast_pointer_from_non_pointer_int)
4760 << castExprType << castExpr->getSourceRange();
4761 } else if (!castExpr->getType()->isArithmeticType()) {
4762 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
4763 return Diag(castExpr->getLocStart(),
4764 diag::err_cast_pointer_to_non_pointer_int)
4765 << castType << castExpr->getSourceRange();
4768 Kind = PrepareScalarCast(*this, castExpr, castType);
4770 if (Kind == CK_BitCast)
4771 CheckCastAlign(castExpr, castType, TyR);
4773 return false;
4776 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4777 CastKind &Kind) {
4778 assert(VectorTy->isVectorType() && "Not a vector type!");
4780 if (Ty->isVectorType() || Ty->isIntegerType()) {
4781 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4782 return Diag(R.getBegin(),
4783 Ty->isVectorType() ?
4784 diag::err_invalid_conversion_between_vectors :
4785 diag::err_invalid_conversion_between_vector_and_integer)
4786 << VectorTy << Ty << R;
4787 } else
4788 return Diag(R.getBegin(),
4789 diag::err_invalid_conversion_between_vector_and_scalar)
4790 << VectorTy << Ty << R;
4792 Kind = CK_BitCast;
4793 return false;
4796 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
4797 CastKind &Kind) {
4798 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4800 QualType SrcTy = CastExpr->getType();
4802 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4803 // an ExtVectorType.
4804 if (SrcTy->isVectorType()) {
4805 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4806 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4807 << DestTy << SrcTy << R;
4808 Kind = CK_BitCast;
4809 return false;
4812 // All non-pointer scalars can be cast to ExtVector type. The appropriate
4813 // conversion will take place first from scalar to elt type, and then
4814 // splat from elt type to vector.
4815 if (SrcTy->isPointerType())
4816 return Diag(R.getBegin(),
4817 diag::err_invalid_conversion_between_vector_and_scalar)
4818 << DestTy << SrcTy << R;
4820 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4821 ImpCastExprToType(CastExpr, DestElemTy,
4822 PrepareScalarCast(*this, CastExpr, DestElemTy));
4824 Kind = CK_VectorSplat;
4825 return false;
4828 ExprResult
4829 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
4830 SourceLocation RParenLoc, Expr *castExpr) {
4831 assert((Ty != 0) && (castExpr != 0) &&
4832 "ActOnCastExpr(): missing type or expr");
4834 TypeSourceInfo *castTInfo;
4835 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4836 if (!castTInfo)
4837 castTInfo = Context.getTrivialTypeSourceInfo(castType);
4839 // If the Expr being casted is a ParenListExpr, handle it specially.
4840 if (isa<ParenListExpr>(castExpr))
4841 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
4842 castTInfo);
4844 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
4847 ExprResult
4848 Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
4849 SourceLocation RParenLoc, Expr *castExpr) {
4850 CastKind Kind = CK_Invalid;
4851 ExprValueKind VK = VK_RValue;
4852 CXXCastPath BasePath;
4853 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
4854 Kind, VK, BasePath))
4855 return ExprError();
4857 return Owned(CStyleCastExpr::Create(Context,
4858 Ty->getType().getNonLValueExprType(Context),
4859 VK, Kind, castExpr, &BasePath, Ty,
4860 LParenLoc, RParenLoc));
4863 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4864 /// of comma binary operators.
4865 ExprResult
4866 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
4867 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4868 if (!E)
4869 return Owned(expr);
4871 ExprResult Result(E->getExpr(0));
4873 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4874 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4875 E->getExpr(i));
4877 if (Result.isInvalid()) return ExprError();
4879 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4882 ExprResult
4883 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4884 SourceLocation RParenLoc, Expr *Op,
4885 TypeSourceInfo *TInfo) {
4886 ParenListExpr *PE = cast<ParenListExpr>(Op);
4887 QualType Ty = TInfo->getType();
4888 bool isAltiVecLiteral = false;
4890 // Check for an altivec literal,
4891 // i.e. all the elements are integer constants.
4892 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4893 if (PE->getNumExprs() == 0) {
4894 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4895 return ExprError();
4897 if (PE->getNumExprs() == 1) {
4898 if (!PE->getExpr(0)->getType()->isVectorType())
4899 isAltiVecLiteral = true;
4901 else
4902 isAltiVecLiteral = true;
4905 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4906 // then handle it as such.
4907 if (isAltiVecLiteral) {
4908 llvm::SmallVector<Expr *, 8> initExprs;
4909 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4910 initExprs.push_back(PE->getExpr(i));
4912 // FIXME: This means that pretty-printing the final AST will produce curly
4913 // braces instead of the original commas.
4914 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4915 &initExprs[0],
4916 initExprs.size(), RParenLoc);
4917 E->setType(Ty);
4918 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
4919 } else {
4920 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4921 // sequence of BinOp comma operators.
4922 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
4923 if (Result.isInvalid()) return ExprError();
4924 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
4928 ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
4929 SourceLocation R,
4930 MultiExprArg Val,
4931 ParsedType TypeOfCast) {
4932 unsigned nexprs = Val.size();
4933 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4934 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4935 Expr *expr;
4936 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4937 expr = new (Context) ParenExpr(L, R, exprs[0]);
4938 else
4939 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
4940 return Owned(expr);
4943 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4944 /// In that case, lhs = cond.
4945 /// C99 6.5.15
4946 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4947 Expr *&SAVE, ExprValueKind &VK,
4948 ExprObjectKind &OK,
4949 SourceLocation QuestionLoc) {
4950 // If both LHS and RHS are overloaded functions, try to resolve them.
4951 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4952 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4953 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4954 if (LHSResult.isInvalid())
4955 return QualType();
4957 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4958 if (RHSResult.isInvalid())
4959 return QualType();
4961 LHS = LHSResult.take();
4962 RHS = RHSResult.take();
4965 // C++ is sufficiently different to merit its own checker.
4966 if (getLangOptions().CPlusPlus)
4967 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4968 VK, OK, QuestionLoc);
4970 VK = VK_RValue;
4971 OK = OK_Ordinary;
4973 UsualUnaryConversions(Cond);
4974 if (SAVE) {
4975 SAVE = LHS = Cond;
4977 else
4978 UsualUnaryConversions(LHS);
4979 UsualUnaryConversions(RHS);
4980 QualType CondTy = Cond->getType();
4981 QualType LHSTy = LHS->getType();
4982 QualType RHSTy = RHS->getType();
4984 // first, check the condition.
4985 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4986 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4987 // Throw an error if its not either.
4988 if (getLangOptions().OpenCL) {
4989 if (!CondTy->isVectorType()) {
4990 Diag(Cond->getLocStart(),
4991 diag::err_typecheck_cond_expect_scalar_or_vector)
4992 << CondTy;
4993 return QualType();
4996 else {
4997 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4998 << CondTy;
4999 return QualType();
5003 // Now check the two expressions.
5004 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5005 return CheckVectorOperands(QuestionLoc, LHS, RHS);
5007 // OpenCL: If the condition is a vector, and both operands are scalar,
5008 // attempt to implicity convert them to the vector type to act like the
5009 // built in select.
5010 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5011 // Both operands should be of scalar type.
5012 if (!LHSTy->isScalarType()) {
5013 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5014 << CondTy;
5015 return QualType();
5017 if (!RHSTy->isScalarType()) {
5018 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5019 << CondTy;
5020 return QualType();
5022 // Implicity convert these scalars to the type of the condition.
5023 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5024 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5027 // If both operands have arithmetic type, do the usual arithmetic conversions
5028 // to find a common type: C99 6.5.15p3,5.
5029 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5030 UsualArithmeticConversions(LHS, RHS);
5031 return LHS->getType();
5034 // If both operands are the same structure or union type, the result is that
5035 // type.
5036 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5037 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5038 if (LHSRT->getDecl() == RHSRT->getDecl())
5039 // "If both the operands have structure or union type, the result has
5040 // that type." This implies that CV qualifiers are dropped.
5041 return LHSTy.getUnqualifiedType();
5042 // FIXME: Type of conditional expression must be complete in C mode.
5045 // C99 6.5.15p5: "If both operands have void type, the result has void type."
5046 // The following || allows only one side to be void (a GCC-ism).
5047 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5048 if (!LHSTy->isVoidType())
5049 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5050 << RHS->getSourceRange();
5051 if (!RHSTy->isVoidType())
5052 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5053 << LHS->getSourceRange();
5054 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5055 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
5056 return Context.VoidTy;
5058 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5059 // the type of the other operand."
5060 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
5061 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5062 // promote the null to a pointer.
5063 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
5064 return LHSTy;
5066 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
5067 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5068 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
5069 return RHSTy;
5072 // All objective-c pointer type analysis is done here.
5073 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5074 QuestionLoc);
5075 if (!compositeType.isNull())
5076 return compositeType;
5079 // Handle block pointer types.
5080 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5081 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5082 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5083 QualType destType = Context.getPointerType(Context.VoidTy);
5084 ImpCastExprToType(LHS, destType, CK_BitCast);
5085 ImpCastExprToType(RHS, destType, CK_BitCast);
5086 return destType;
5088 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5089 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5090 return QualType();
5092 // We have 2 block pointer types.
5093 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5094 // Two identical block pointer types are always compatible.
5095 return LHSTy;
5097 // The block pointer types aren't identical, continue checking.
5098 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5099 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
5101 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5102 rhptee.getUnqualifiedType())) {
5103 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5104 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5105 // In this situation, we assume void* type. No especially good
5106 // reason, but this is what gcc does, and we do have to pick
5107 // to get a consistent AST.
5108 QualType incompatTy = Context.getPointerType(Context.VoidTy);
5109 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5110 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5111 return incompatTy;
5113 // The block pointer types are compatible.
5114 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5115 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5116 return LHSTy;
5119 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5120 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5121 // get the "pointed to" types
5122 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5123 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5125 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5126 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5127 // Figure out necessary qualifiers (C99 6.5.15p6)
5128 QualType destPointee
5129 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5130 QualType destType = Context.getPointerType(destPointee);
5131 // Add qualifiers if necessary.
5132 ImpCastExprToType(LHS, destType, CK_NoOp);
5133 // Promote to void*.
5134 ImpCastExprToType(RHS, destType, CK_BitCast);
5135 return destType;
5137 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5138 QualType destPointee
5139 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5140 QualType destType = Context.getPointerType(destPointee);
5141 // Add qualifiers if necessary.
5142 ImpCastExprToType(RHS, destType, CK_NoOp);
5143 // Promote to void*.
5144 ImpCastExprToType(LHS, destType, CK_BitCast);
5145 return destType;
5148 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5149 // Two identical pointer types are always compatible.
5150 return LHSTy;
5152 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5153 rhptee.getUnqualifiedType())) {
5154 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5155 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5156 // In this situation, we assume void* type. No especially good
5157 // reason, but this is what gcc does, and we do have to pick
5158 // to get a consistent AST.
5159 QualType incompatTy = Context.getPointerType(Context.VoidTy);
5160 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5161 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5162 return incompatTy;
5164 // The pointer types are compatible.
5165 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5166 // differently qualified versions of compatible types, the result type is
5167 // a pointer to an appropriately qualified version of the *composite*
5168 // type.
5169 // FIXME: Need to calculate the composite type.
5170 // FIXME: Need to add qualifiers
5171 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5172 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5173 return LHSTy;
5176 // GCC compatibility: soften pointer/integer mismatch. Note that
5177 // null pointers have been filtered out by this point.
5178 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5179 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5180 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5181 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
5182 return RHSTy;
5184 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5185 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5186 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5187 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
5188 return LHSTy;
5191 // Otherwise, the operands are not compatible.
5192 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5193 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5194 return QualType();
5197 /// FindCompositeObjCPointerType - Helper method to find composite type of
5198 /// two objective-c pointer types of the two input expressions.
5199 QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5200 SourceLocation QuestionLoc) {
5201 QualType LHSTy = LHS->getType();
5202 QualType RHSTy = RHS->getType();
5204 // Handle things like Class and struct objc_class*. Here we case the result
5205 // to the pseudo-builtin, because that will be implicitly cast back to the
5206 // redefinition type if an attempt is made to access its fields.
5207 if (LHSTy->isObjCClassType() &&
5208 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
5209 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5210 return LHSTy;
5212 if (RHSTy->isObjCClassType() &&
5213 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
5214 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5215 return RHSTy;
5217 // And the same for struct objc_object* / id
5218 if (LHSTy->isObjCIdType() &&
5219 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
5220 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5221 return LHSTy;
5223 if (RHSTy->isObjCIdType() &&
5224 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
5225 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5226 return RHSTy;
5228 // And the same for struct objc_selector* / SEL
5229 if (Context.isObjCSelType(LHSTy) &&
5230 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
5231 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5232 return LHSTy;
5234 if (Context.isObjCSelType(RHSTy) &&
5235 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
5236 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5237 return RHSTy;
5239 // Check constraints for Objective-C object pointers types.
5240 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5242 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5243 // Two identical object pointer types are always compatible.
5244 return LHSTy;
5246 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5247 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5248 QualType compositeType = LHSTy;
5250 // If both operands are interfaces and either operand can be
5251 // assigned to the other, use that type as the composite
5252 // type. This allows
5253 // xxx ? (A*) a : (B*) b
5254 // where B is a subclass of A.
5256 // Additionally, as for assignment, if either type is 'id'
5257 // allow silent coercion. Finally, if the types are
5258 // incompatible then make sure to use 'id' as the composite
5259 // type so the result is acceptable for sending messages to.
5261 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5262 // It could return the composite type.
5263 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5264 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5265 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5266 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5267 } else if ((LHSTy->isObjCQualifiedIdType() ||
5268 RHSTy->isObjCQualifiedIdType()) &&
5269 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5270 // Need to handle "id<xx>" explicitly.
5271 // GCC allows qualified id and any Objective-C type to devolve to
5272 // id. Currently localizing to here until clear this should be
5273 // part of ObjCQualifiedIdTypesAreCompatible.
5274 compositeType = Context.getObjCIdType();
5275 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5276 compositeType = Context.getObjCIdType();
5277 } else if (!(compositeType =
5278 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5280 else {
5281 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5282 << LHSTy << RHSTy
5283 << LHS->getSourceRange() << RHS->getSourceRange();
5284 QualType incompatTy = Context.getObjCIdType();
5285 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5286 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5287 return incompatTy;
5289 // The object pointer types are compatible.
5290 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5291 ImpCastExprToType(RHS, compositeType, CK_BitCast);
5292 return compositeType;
5294 // Check Objective-C object pointer types and 'void *'
5295 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5296 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5297 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5298 QualType destPointee
5299 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5300 QualType destType = Context.getPointerType(destPointee);
5301 // Add qualifiers if necessary.
5302 ImpCastExprToType(LHS, destType, CK_NoOp);
5303 // Promote to void*.
5304 ImpCastExprToType(RHS, destType, CK_BitCast);
5305 return destType;
5307 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5308 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5309 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5310 QualType destPointee
5311 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5312 QualType destType = Context.getPointerType(destPointee);
5313 // Add qualifiers if necessary.
5314 ImpCastExprToType(RHS, destType, CK_NoOp);
5315 // Promote to void*.
5316 ImpCastExprToType(LHS, destType, CK_BitCast);
5317 return destType;
5319 return QualType();
5322 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5323 /// in the case of a the GNU conditional expr extension.
5324 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5325 SourceLocation ColonLoc,
5326 Expr *CondExpr, Expr *LHSExpr,
5327 Expr *RHSExpr) {
5328 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5329 // was the condition.
5330 bool isLHSNull = LHSExpr == 0;
5331 Expr *SAVEExpr = 0;
5332 if (isLHSNull) {
5333 LHSExpr = SAVEExpr = CondExpr;
5336 ExprValueKind VK = VK_RValue;
5337 ExprObjectKind OK = OK_Ordinary;
5338 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
5339 SAVEExpr, VK, OK, QuestionLoc);
5340 if (result.isNull())
5341 return ExprError();
5343 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5344 LHSExpr, ColonLoc,
5345 RHSExpr, SAVEExpr,
5346 result, VK, OK));
5349 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
5350 // being closely modeled after the C99 spec:-). The odd characteristic of this
5351 // routine is it effectively iqnores the qualifiers on the top level pointee.
5352 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5353 // FIXME: add a couple examples in this comment.
5354 Sema::AssignConvertType
5355 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
5356 QualType lhptee, rhptee;
5358 if ((lhsType->isObjCClassType() &&
5359 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
5360 (rhsType->isObjCClassType() &&
5361 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
5362 return Compatible;
5365 // get the "pointed to" type (ignoring qualifiers at the top level)
5366 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
5367 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
5369 // make sure we operate on the canonical type
5370 lhptee = Context.getCanonicalType(lhptee);
5371 rhptee = Context.getCanonicalType(rhptee);
5373 AssignConvertType ConvTy = Compatible;
5375 // C99 6.5.16.1p1: This following citation is common to constraints
5376 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5377 // qualifiers of the type *pointed to* by the right;
5378 // FIXME: Handle ExtQualType
5379 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5380 ConvTy = CompatiblePointerDiscardsQualifiers;
5382 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5383 // incomplete type and the other is a pointer to a qualified or unqualified
5384 // version of void...
5385 if (lhptee->isVoidType()) {
5386 if (rhptee->isIncompleteOrObjectType())
5387 return ConvTy;
5389 // As an extension, we allow cast to/from void* to function pointer.
5390 assert(rhptee->isFunctionType());
5391 return FunctionVoidPointer;
5394 if (rhptee->isVoidType()) {
5395 if (lhptee->isIncompleteOrObjectType())
5396 return ConvTy;
5398 // As an extension, we allow cast to/from void* to function pointer.
5399 assert(lhptee->isFunctionType());
5400 return FunctionVoidPointer;
5402 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5403 // unqualified versions of compatible types, ...
5404 lhptee = lhptee.getUnqualifiedType();
5405 rhptee = rhptee.getUnqualifiedType();
5406 if (!Context.typesAreCompatible(lhptee, rhptee)) {
5407 // Check if the pointee types are compatible ignoring the sign.
5408 // We explicitly check for char so that we catch "char" vs
5409 // "unsigned char" on systems where "char" is unsigned.
5410 if (lhptee->isCharType())
5411 lhptee = Context.UnsignedCharTy;
5412 else if (lhptee->hasSignedIntegerRepresentation())
5413 lhptee = Context.getCorrespondingUnsignedType(lhptee);
5415 if (rhptee->isCharType())
5416 rhptee = Context.UnsignedCharTy;
5417 else if (rhptee->hasSignedIntegerRepresentation())
5418 rhptee = Context.getCorrespondingUnsignedType(rhptee);
5420 if (lhptee == rhptee) {
5421 // Types are compatible ignoring the sign. Qualifier incompatibility
5422 // takes priority over sign incompatibility because the sign
5423 // warning can be disabled.
5424 if (ConvTy != Compatible)
5425 return ConvTy;
5426 return IncompatiblePointerSign;
5429 // If we are a multi-level pointer, it's possible that our issue is simply
5430 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5431 // the eventual target type is the same and the pointers have the same
5432 // level of indirection, this must be the issue.
5433 if (lhptee->isPointerType() && rhptee->isPointerType()) {
5434 do {
5435 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
5436 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
5438 lhptee = Context.getCanonicalType(lhptee);
5439 rhptee = Context.getCanonicalType(rhptee);
5440 } while (lhptee->isPointerType() && rhptee->isPointerType());
5442 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
5443 return IncompatibleNestedPointerQualifiers;
5446 // General pointer incompatibility takes priority over qualifiers.
5447 return IncompatiblePointer;
5449 return ConvTy;
5452 /// CheckBlockPointerTypesForAssignment - This routine determines whether two
5453 /// block pointer types are compatible or whether a block and normal pointer
5454 /// are compatible. It is more restrict than comparing two function pointer
5455 // types.
5456 Sema::AssignConvertType
5457 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
5458 QualType rhsType) {
5459 QualType lhptee, rhptee;
5461 // get the "pointed to" type (ignoring qualifiers at the top level)
5462 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
5463 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
5465 // make sure we operate on the canonical type
5466 lhptee = Context.getCanonicalType(lhptee);
5467 rhptee = Context.getCanonicalType(rhptee);
5469 AssignConvertType ConvTy = Compatible;
5471 // For blocks we enforce that qualifiers are identical.
5472 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
5473 ConvTy = CompatiblePointerDiscardsQualifiers;
5475 if (!getLangOptions().CPlusPlus) {
5476 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5477 return IncompatibleBlockPointer;
5479 else if (!Context.typesAreCompatible(lhptee, rhptee))
5480 return IncompatibleBlockPointer;
5481 return ConvTy;
5484 /// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
5485 /// for assignment compatibility.
5486 Sema::AssignConvertType
5487 Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
5488 if (lhsType->isObjCBuiltinType()) {
5489 // Class is not compatible with ObjC object pointers.
5490 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5491 !rhsType->isObjCQualifiedClassType())
5492 return IncompatiblePointer;
5493 return Compatible;
5495 if (rhsType->isObjCBuiltinType()) {
5496 // Class is not compatible with ObjC object pointers.
5497 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5498 !lhsType->isObjCQualifiedClassType())
5499 return IncompatiblePointer;
5500 return Compatible;
5502 QualType lhptee =
5503 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5504 QualType rhptee =
5505 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5506 // make sure we operate on the canonical type
5507 lhptee = Context.getCanonicalType(lhptee);
5508 rhptee = Context.getCanonicalType(rhptee);
5509 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5510 return CompatiblePointerDiscardsQualifiers;
5512 if (Context.typesAreCompatible(lhsType, rhsType))
5513 return Compatible;
5514 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5515 return IncompatibleObjCQualifiedId;
5516 return IncompatiblePointer;
5519 Sema::AssignConvertType
5520 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5521 QualType lhsType, QualType rhsType) {
5522 // Fake up an opaque expression. We don't actually care about what
5523 // cast operations are required, so if CheckAssignmentConstraints
5524 // adds casts to this they'll be wasted, but fortunately that doesn't
5525 // usually happen on valid code.
5526 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
5527 Expr *rhsPtr = &rhs;
5528 CastKind K = CK_Invalid;
5530 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5533 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5534 /// has code to accommodate several GCC extensions when type checking
5535 /// pointers. Here are some objectionable examples that GCC considers warnings:
5537 /// int a, *pint;
5538 /// short *pshort;
5539 /// struct foo *pfoo;
5541 /// pint = pshort; // warning: assignment from incompatible pointer type
5542 /// a = pint; // warning: assignment makes integer from pointer without a cast
5543 /// pint = a; // warning: assignment makes pointer from integer without a cast
5544 /// pint = pfoo; // warning: assignment from incompatible pointer type
5546 /// As a result, the code for dealing with pointers is more complex than the
5547 /// C99 spec dictates.
5549 /// Sets 'Kind' for any result kind except Incompatible.
5550 Sema::AssignConvertType
5551 Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
5552 CastKind &Kind) {
5553 QualType rhsType = rhs->getType();
5555 // Get canonical types. We're not formatting these types, just comparing
5556 // them.
5557 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5558 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
5560 if (lhsType == rhsType) {
5561 Kind = CK_NoOp;
5562 return Compatible; // Common case: fast path an exact match.
5565 if ((lhsType->isObjCClassType() &&
5566 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
5567 (rhsType->isObjCClassType() &&
5568 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
5569 Kind = CK_BitCast;
5570 return Compatible;
5573 // If the left-hand side is a reference type, then we are in a
5574 // (rare!) case where we've allowed the use of references in C,
5575 // e.g., as a parameter type in a built-in function. In this case,
5576 // just make sure that the type referenced is compatible with the
5577 // right-hand side type. The caller is responsible for adjusting
5578 // lhsType so that the resulting expression does not have reference
5579 // type.
5580 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
5581 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5582 Kind = CK_LValueBitCast;
5583 return Compatible;
5585 return Incompatible;
5587 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5588 // to the same ExtVector type.
5589 if (lhsType->isExtVectorType()) {
5590 if (rhsType->isExtVectorType())
5591 return Incompatible;
5592 if (rhsType->isArithmeticType()) {
5593 // CK_VectorSplat does T -> vector T, so first cast to the
5594 // element type.
5595 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5596 if (elType != rhsType) {
5597 Kind = PrepareScalarCast(*this, rhs, elType);
5598 ImpCastExprToType(rhs, elType, Kind);
5600 Kind = CK_VectorSplat;
5601 return Compatible;
5605 if (lhsType->isVectorType() || rhsType->isVectorType()) {
5606 if (lhsType->isVectorType() && rhsType->isVectorType()) {
5607 // Allow assignments of an AltiVec vector type to an equivalent GCC
5608 // vector type and vice versa
5609 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5610 Kind = CK_BitCast;
5611 return Compatible;
5614 // If we are allowing lax vector conversions, and LHS and RHS are both
5615 // vectors, the total size only needs to be the same. This is a bitcast;
5616 // no bits are changed but the result type is different.
5617 if (getLangOptions().LaxVectorConversions &&
5618 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
5619 Kind = CK_BitCast;
5620 return IncompatibleVectors;
5623 return Incompatible;
5626 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
5627 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
5628 Kind = PrepareScalarCast(*this, rhs, lhsType);
5629 return Compatible;
5632 if (isa<PointerType>(lhsType)) {
5633 if (rhsType->isIntegerType()) {
5634 Kind = CK_IntegralToPointer; // FIXME: null?
5635 return IntToPointer;
5638 if (isa<PointerType>(rhsType)) {
5639 Kind = CK_BitCast;
5640 return CheckPointerTypesForAssignment(lhsType, rhsType);
5643 // In general, C pointers are not compatible with ObjC object pointers.
5644 if (isa<ObjCObjectPointerType>(rhsType)) {
5645 Kind = CK_AnyPointerToObjCPointerCast;
5646 if (lhsType->isVoidPointerType()) // an exception to the rule.
5647 return Compatible;
5648 return IncompatiblePointer;
5650 if (rhsType->getAs<BlockPointerType>()) {
5651 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5652 Kind = CK_BitCast;
5653 return Compatible;
5656 // Treat block pointers as objects.
5657 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) {
5658 Kind = CK_AnyPointerToObjCPointerCast;
5659 return Compatible;
5662 return Incompatible;
5665 if (isa<BlockPointerType>(lhsType)) {
5666 if (rhsType->isIntegerType()) {
5667 Kind = CK_IntegralToPointer; // FIXME: null
5668 return IntToBlockPointer;
5671 Kind = CK_AnyPointerToObjCPointerCast;
5673 // Treat block pointers as objects.
5674 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
5675 return Compatible;
5677 if (rhsType->isBlockPointerType())
5678 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
5680 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
5681 if (RHSPT->getPointeeType()->isVoidType())
5682 return Compatible;
5684 return Incompatible;
5687 if (isa<ObjCObjectPointerType>(lhsType)) {
5688 if (rhsType->isIntegerType()) {
5689 Kind = CK_IntegralToPointer; // FIXME: null
5690 return IntToPointer;
5693 Kind = CK_BitCast;
5695 // In general, C pointers are not compatible with ObjC object pointers.
5696 if (isa<PointerType>(rhsType)) {
5697 if (rhsType->isVoidPointerType()) // an exception to the rule.
5698 return Compatible;
5699 return IncompatiblePointer;
5701 if (rhsType->isObjCObjectPointerType()) {
5702 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
5704 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
5705 if (RHSPT->getPointeeType()->isVoidType())
5706 return Compatible;
5708 // Treat block pointers as objects.
5709 if (rhsType->isBlockPointerType())
5710 return Compatible;
5711 return Incompatible;
5713 if (isa<PointerType>(rhsType)) {
5714 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
5715 if (lhsType == Context.BoolTy) {
5716 Kind = CK_PointerToBoolean;
5717 return Compatible;
5720 if (lhsType->isIntegerType()) {
5721 Kind = CK_PointerToIntegral;
5722 return PointerToInt;
5725 if (isa<BlockPointerType>(lhsType) &&
5726 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5727 Kind = CK_AnyPointerToBlockPointerCast;
5728 return Compatible;
5730 return Incompatible;
5732 if (isa<ObjCObjectPointerType>(rhsType)) {
5733 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
5734 if (lhsType == Context.BoolTy) {
5735 Kind = CK_PointerToBoolean;
5736 return Compatible;
5739 if (lhsType->isIntegerType()) {
5740 Kind = CK_PointerToIntegral;
5741 return PointerToInt;
5744 Kind = CK_BitCast;
5746 // In general, C pointers are not compatible with ObjC object pointers.
5747 if (isa<PointerType>(lhsType)) {
5748 if (lhsType->isVoidPointerType()) // an exception to the rule.
5749 return Compatible;
5750 return IncompatiblePointer;
5752 if (isa<BlockPointerType>(lhsType) &&
5753 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5754 Kind = CK_AnyPointerToBlockPointerCast;
5755 return Compatible;
5757 return Incompatible;
5760 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
5761 if (Context.typesAreCompatible(lhsType, rhsType)) {
5762 Kind = CK_NoOp;
5763 return Compatible;
5766 return Incompatible;
5769 /// \brief Constructs a transparent union from an expression that is
5770 /// used to initialize the transparent union.
5771 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
5772 QualType UnionType, FieldDecl *Field) {
5773 // Build an initializer list that designates the appropriate member
5774 // of the transparent union.
5775 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5776 &E, 1,
5777 SourceLocation());
5778 Initializer->setType(UnionType);
5779 Initializer->setInitializedFieldInUnion(Field);
5781 // Build a compound literal constructing a value of the transparent
5782 // union type from this initializer list.
5783 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5784 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5785 VK_RValue, Initializer, false);
5788 Sema::AssignConvertType
5789 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5790 QualType FromType = rExpr->getType();
5792 // If the ArgType is a Union type, we want to handle a potential
5793 // transparent_union GCC extension.
5794 const RecordType *UT = ArgType->getAsUnionType();
5795 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5796 return Incompatible;
5798 // The field to initialize within the transparent union.
5799 RecordDecl *UD = UT->getDecl();
5800 FieldDecl *InitField = 0;
5801 // It's compatible if the expression matches any of the fields.
5802 for (RecordDecl::field_iterator it = UD->field_begin(),
5803 itend = UD->field_end();
5804 it != itend; ++it) {
5805 if (it->getType()->isPointerType()) {
5806 // If the transparent union contains a pointer type, we allow:
5807 // 1) void pointer
5808 // 2) null pointer constant
5809 if (FromType->isPointerType())
5810 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5811 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
5812 InitField = *it;
5813 break;
5816 if (rExpr->isNullPointerConstant(Context,
5817 Expr::NPC_ValueDependentIsNull)) {
5818 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
5819 InitField = *it;
5820 break;
5824 Expr *rhs = rExpr;
5825 CastKind Kind = CK_Invalid;
5826 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
5827 == Compatible) {
5828 ImpCastExprToType(rhs, it->getType(), Kind);
5829 rExpr = rhs;
5830 InitField = *it;
5831 break;
5835 if (!InitField)
5836 return Incompatible;
5838 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5839 return Compatible;
5842 Sema::AssignConvertType
5843 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
5844 if (getLangOptions().CPlusPlus) {
5845 if (!lhsType->isRecordType()) {
5846 // C++ 5.17p3: If the left operand is not of class type, the
5847 // expression is implicitly converted (C++ 4) to the
5848 // cv-unqualified type of the left operand.
5849 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
5850 AA_Assigning))
5851 return Incompatible;
5852 return Compatible;
5855 // FIXME: Currently, we fall through and treat C++ classes like C
5856 // structures.
5859 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5860 // a null pointer constant.
5861 if ((lhsType->isPointerType() ||
5862 lhsType->isObjCObjectPointerType() ||
5863 lhsType->isBlockPointerType())
5864 && rExpr->isNullPointerConstant(Context,
5865 Expr::NPC_ValueDependentIsNull)) {
5866 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
5867 return Compatible;
5870 // This check seems unnatural, however it is necessary to ensure the proper
5871 // conversion of functions/arrays. If the conversion were done for all
5872 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5873 // expressions that suppress this implicit conversion (&, sizeof).
5875 // Suppress this for references: C++ 8.5.3p5.
5876 if (!lhsType->isReferenceType())
5877 DefaultFunctionArrayLvalueConversion(rExpr);
5879 CastKind Kind = CK_Invalid;
5880 Sema::AssignConvertType result =
5881 CheckAssignmentConstraints(lhsType, rExpr, Kind);
5883 // C99 6.5.16.1p2: The value of the right operand is converted to the
5884 // type of the assignment expression.
5885 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5886 // so that we can use references in built-in functions even in C.
5887 // The getNonReferenceType() call makes sure that the resulting expression
5888 // does not have reference type.
5889 if (result != Incompatible && rExpr->getType() != lhsType)
5890 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
5891 return result;
5894 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
5895 Diag(Loc, diag::err_typecheck_invalid_operands)
5896 << lex->getType() << rex->getType()
5897 << lex->getSourceRange() << rex->getSourceRange();
5898 return QualType();
5901 QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
5902 // For conversion purposes, we ignore any qualifiers.
5903 // For example, "const float" and "float" are equivalent.
5904 QualType lhsType =
5905 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5906 QualType rhsType =
5907 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
5909 // If the vector types are identical, return.
5910 if (lhsType == rhsType)
5911 return lhsType;
5913 // Handle the case of a vector & extvector type of the same size and element
5914 // type. It would be nice if we only had one vector type someday.
5915 if (getLangOptions().LaxVectorConversions) {
5916 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
5917 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
5918 if (LV->getElementType() == RV->getElementType() &&
5919 LV->getNumElements() == RV->getNumElements()) {
5920 if (lhsType->isExtVectorType()) {
5921 ImpCastExprToType(rex, lhsType, CK_BitCast);
5922 return lhsType;
5925 ImpCastExprToType(lex, rhsType, CK_BitCast);
5926 return rhsType;
5927 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5928 // If we are allowing lax vector conversions, and LHS and RHS are both
5929 // vectors, the total size only needs to be the same. This is a
5930 // bitcast; no bits are changed but the result type is different.
5931 ImpCastExprToType(rex, lhsType, CK_BitCast);
5932 return lhsType;
5938 // Handle the case of equivalent AltiVec and GCC vector types
5939 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5940 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5941 ImpCastExprToType(lex, rhsType, CK_BitCast);
5942 return rhsType;
5945 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5946 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5947 bool swapped = false;
5948 if (rhsType->isExtVectorType()) {
5949 swapped = true;
5950 std::swap(rex, lex);
5951 std::swap(rhsType, lhsType);
5954 // Handle the case of an ext vector and scalar.
5955 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
5956 QualType EltTy = LV->getElementType();
5957 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
5958 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5959 if (order > 0)
5960 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5961 if (order >= 0) {
5962 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
5963 if (swapped) std::swap(rex, lex);
5964 return lhsType;
5967 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5968 rhsType->isRealFloatingType()) {
5969 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5970 if (order > 0)
5971 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5972 if (order >= 0) {
5973 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
5974 if (swapped) std::swap(rex, lex);
5975 return lhsType;
5980 // Vectors of different size or scalar and non-ext-vector are errors.
5981 Diag(Loc, diag::err_typecheck_vector_not_convertable)
5982 << lex->getType() << rex->getType()
5983 << lex->getSourceRange() << rex->getSourceRange();
5984 return QualType();
5987 QualType Sema::CheckMultiplyDivideOperands(
5988 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5989 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5990 return CheckVectorOperands(Loc, lex, rex);
5992 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
5994 if (!lex->getType()->isArithmeticType() ||
5995 !rex->getType()->isArithmeticType())
5996 return InvalidOperands(Loc, lex, rex);
5998 // Check for division by zero.
5999 if (isDiv &&
6000 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6001 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
6002 << rex->getSourceRange());
6004 return compType;
6007 QualType Sema::CheckRemainderOperands(
6008 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
6009 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6010 if (lex->getType()->hasIntegerRepresentation() &&
6011 rex->getType()->hasIntegerRepresentation())
6012 return CheckVectorOperands(Loc, lex, rex);
6013 return InvalidOperands(Loc, lex, rex);
6016 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6018 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6019 return InvalidOperands(Loc, lex, rex);
6021 // Check for remainder by zero.
6022 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6023 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6024 << rex->getSourceRange());
6026 return compType;
6029 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6030 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
6031 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6032 QualType compType = CheckVectorOperands(Loc, lex, rex);
6033 if (CompLHSTy) *CompLHSTy = compType;
6034 return compType;
6037 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6039 // handle the common case first (both operands are arithmetic).
6040 if (lex->getType()->isArithmeticType() &&
6041 rex->getType()->isArithmeticType()) {
6042 if (CompLHSTy) *CompLHSTy = compType;
6043 return compType;
6046 // Put any potential pointer into PExp
6047 Expr* PExp = lex, *IExp = rex;
6048 if (IExp->getType()->isAnyPointerType())
6049 std::swap(PExp, IExp);
6051 if (PExp->getType()->isAnyPointerType()) {
6053 if (IExp->getType()->isIntegerType()) {
6054 QualType PointeeTy = PExp->getType()->getPointeeType();
6056 // Check for arithmetic on pointers to incomplete types.
6057 if (PointeeTy->isVoidType()) {
6058 if (getLangOptions().CPlusPlus) {
6059 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6060 << lex->getSourceRange() << rex->getSourceRange();
6061 return QualType();
6064 // GNU extension: arithmetic on pointer to void
6065 Diag(Loc, diag::ext_gnu_void_ptr)
6066 << lex->getSourceRange() << rex->getSourceRange();
6067 } else if (PointeeTy->isFunctionType()) {
6068 if (getLangOptions().CPlusPlus) {
6069 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6070 << lex->getType() << lex->getSourceRange();
6071 return QualType();
6074 // GNU extension: arithmetic on pointer to function
6075 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6076 << lex->getType() << lex->getSourceRange();
6077 } else {
6078 // Check if we require a complete type.
6079 if (((PExp->getType()->isPointerType() &&
6080 !PExp->getType()->isDependentType()) ||
6081 PExp->getType()->isObjCObjectPointerType()) &&
6082 RequireCompleteType(Loc, PointeeTy,
6083 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6084 << PExp->getSourceRange()
6085 << PExp->getType()))
6086 return QualType();
6088 // Diagnose bad cases where we step over interface counts.
6089 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6090 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6091 << PointeeTy << PExp->getSourceRange();
6092 return QualType();
6095 if (CompLHSTy) {
6096 QualType LHSTy = Context.isPromotableBitField(lex);
6097 if (LHSTy.isNull()) {
6098 LHSTy = lex->getType();
6099 if (LHSTy->isPromotableIntegerType())
6100 LHSTy = Context.getPromotedIntegerType(LHSTy);
6102 *CompLHSTy = LHSTy;
6104 return PExp->getType();
6108 return InvalidOperands(Loc, lex, rex);
6111 // C99 6.5.6
6112 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
6113 SourceLocation Loc, QualType* CompLHSTy) {
6114 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6115 QualType compType = CheckVectorOperands(Loc, lex, rex);
6116 if (CompLHSTy) *CompLHSTy = compType;
6117 return compType;
6120 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6122 // Enforce type constraints: C99 6.5.6p3.
6124 // Handle the common case first (both operands are arithmetic).
6125 if (lex->getType()->isArithmeticType()
6126 && rex->getType()->isArithmeticType()) {
6127 if (CompLHSTy) *CompLHSTy = compType;
6128 return compType;
6131 // Either ptr - int or ptr - ptr.
6132 if (lex->getType()->isAnyPointerType()) {
6133 QualType lpointee = lex->getType()->getPointeeType();
6135 // The LHS must be an completely-defined object type.
6137 bool ComplainAboutVoid = false;
6138 Expr *ComplainAboutFunc = 0;
6139 if (lpointee->isVoidType()) {
6140 if (getLangOptions().CPlusPlus) {
6141 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6142 << lex->getSourceRange() << rex->getSourceRange();
6143 return QualType();
6146 // GNU C extension: arithmetic on pointer to void
6147 ComplainAboutVoid = true;
6148 } else if (lpointee->isFunctionType()) {
6149 if (getLangOptions().CPlusPlus) {
6150 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6151 << lex->getType() << lex->getSourceRange();
6152 return QualType();
6155 // GNU C extension: arithmetic on pointer to function
6156 ComplainAboutFunc = lex;
6157 } else if (!lpointee->isDependentType() &&
6158 RequireCompleteType(Loc, lpointee,
6159 PDiag(diag::err_typecheck_sub_ptr_object)
6160 << lex->getSourceRange()
6161 << lex->getType()))
6162 return QualType();
6164 // Diagnose bad cases where we step over interface counts.
6165 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6166 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6167 << lpointee << lex->getSourceRange();
6168 return QualType();
6171 // The result type of a pointer-int computation is the pointer type.
6172 if (rex->getType()->isIntegerType()) {
6173 if (ComplainAboutVoid)
6174 Diag(Loc, diag::ext_gnu_void_ptr)
6175 << lex->getSourceRange() << rex->getSourceRange();
6176 if (ComplainAboutFunc)
6177 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6178 << ComplainAboutFunc->getType()
6179 << ComplainAboutFunc->getSourceRange();
6181 if (CompLHSTy) *CompLHSTy = lex->getType();
6182 return lex->getType();
6185 // Handle pointer-pointer subtractions.
6186 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
6187 QualType rpointee = RHSPTy->getPointeeType();
6189 // RHS must be a completely-type object type.
6190 // Handle the GNU void* extension.
6191 if (rpointee->isVoidType()) {
6192 if (getLangOptions().CPlusPlus) {
6193 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6194 << lex->getSourceRange() << rex->getSourceRange();
6195 return QualType();
6198 ComplainAboutVoid = true;
6199 } else if (rpointee->isFunctionType()) {
6200 if (getLangOptions().CPlusPlus) {
6201 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6202 << rex->getType() << rex->getSourceRange();
6203 return QualType();
6206 // GNU extension: arithmetic on pointer to function
6207 if (!ComplainAboutFunc)
6208 ComplainAboutFunc = rex;
6209 } else if (!rpointee->isDependentType() &&
6210 RequireCompleteType(Loc, rpointee,
6211 PDiag(diag::err_typecheck_sub_ptr_object)
6212 << rex->getSourceRange()
6213 << rex->getType()))
6214 return QualType();
6216 if (getLangOptions().CPlusPlus) {
6217 // Pointee types must be the same: C++ [expr.add]
6218 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6219 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6220 << lex->getType() << rex->getType()
6221 << lex->getSourceRange() << rex->getSourceRange();
6222 return QualType();
6224 } else {
6225 // Pointee types must be compatible C99 6.5.6p3
6226 if (!Context.typesAreCompatible(
6227 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6228 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6229 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6230 << lex->getType() << rex->getType()
6231 << lex->getSourceRange() << rex->getSourceRange();
6232 return QualType();
6236 if (ComplainAboutVoid)
6237 Diag(Loc, diag::ext_gnu_void_ptr)
6238 << lex->getSourceRange() << rex->getSourceRange();
6239 if (ComplainAboutFunc)
6240 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6241 << ComplainAboutFunc->getType()
6242 << ComplainAboutFunc->getSourceRange();
6244 if (CompLHSTy) *CompLHSTy = lex->getType();
6245 return Context.getPointerDiffType();
6249 return InvalidOperands(Loc, lex, rex);
6252 static bool isScopedEnumerationType(QualType T) {
6253 if (const EnumType *ET = dyn_cast<EnumType>(T))
6254 return ET->getDecl()->isScoped();
6255 return false;
6258 // C99 6.5.7
6259 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
6260 bool isCompAssign) {
6261 // C99 6.5.7p2: Each of the operands shall have integer type.
6262 if (!lex->getType()->hasIntegerRepresentation() ||
6263 !rex->getType()->hasIntegerRepresentation())
6264 return InvalidOperands(Loc, lex, rex);
6266 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6267 // hasIntegerRepresentation() above instead of this.
6268 if (isScopedEnumerationType(lex->getType()) ||
6269 isScopedEnumerationType(rex->getType())) {
6270 return InvalidOperands(Loc, lex, rex);
6273 // Vector shifts promote their scalar inputs to vector type.
6274 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6275 return CheckVectorOperands(Loc, lex, rex);
6277 // Shifts don't perform usual arithmetic conversions, they just do integer
6278 // promotions on each operand. C99 6.5.7p3
6280 // For the LHS, do usual unary conversions, but then reset them away
6281 // if this is a compound assignment.
6282 Expr *old_lex = lex;
6283 UsualUnaryConversions(lex);
6284 QualType LHSTy = lex->getType();
6285 if (isCompAssign) lex = old_lex;
6287 // The RHS is simpler.
6288 UsualUnaryConversions(rex);
6290 // Sanity-check shift operands
6291 llvm::APSInt Right;
6292 // Check right/shifter operand
6293 if (!rex->isValueDependent() &&
6294 rex->isIntegerConstantExpr(Right, Context)) {
6295 if (Right.isNegative())
6296 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6297 else {
6298 llvm::APInt LeftBits(Right.getBitWidth(),
6299 Context.getTypeSize(lex->getType()));
6300 if (Right.uge(LeftBits))
6301 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6305 // "The type of the result is that of the promoted left operand."
6306 return LHSTy;
6309 static bool IsWithinTemplateSpecialization(Decl *D) {
6310 if (DeclContext *DC = D->getDeclContext()) {
6311 if (isa<ClassTemplateSpecializationDecl>(DC))
6312 return true;
6313 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6314 return FD->isFunctionTemplateSpecialization();
6316 return false;
6319 // C99 6.5.8, C++ [expr.rel]
6320 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
6321 unsigned OpaqueOpc, bool isRelational) {
6322 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6324 // Handle vector comparisons separately.
6325 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6326 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
6328 QualType lType = lex->getType();
6329 QualType rType = rex->getType();
6331 if (!lType->hasFloatingRepresentation() &&
6332 !(lType->isBlockPointerType() && isRelational) &&
6333 !lex->getLocStart().isMacroID() &&
6334 !rex->getLocStart().isMacroID()) {
6335 // For non-floating point types, check for self-comparisons of the form
6336 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6337 // often indicate logic errors in the program.
6339 // NOTE: Don't warn about comparison expressions resulting from macro
6340 // expansion. Also don't warn about comparisons which are only self
6341 // comparisons within a template specialization. The warnings should catch
6342 // obvious cases in the definition of the template anyways. The idea is to
6343 // warn when the typed comparison operator will always evaluate to the same
6344 // result.
6345 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6346 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6347 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6348 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6349 if (DRL->getDecl() == DRR->getDecl() &&
6350 !IsWithinTemplateSpecialization(DRL->getDecl())) {
6351 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6352 << 0 // self-
6353 << (Opc == BO_EQ
6354 || Opc == BO_LE
6355 || Opc == BO_GE));
6356 } else if (lType->isArrayType() && rType->isArrayType() &&
6357 !DRL->getDecl()->getType()->isReferenceType() &&
6358 !DRR->getDecl()->getType()->isReferenceType()) {
6359 // what is it always going to eval to?
6360 char always_evals_to;
6361 switch(Opc) {
6362 case BO_EQ: // e.g. array1 == array2
6363 always_evals_to = 0; // false
6364 break;
6365 case BO_NE: // e.g. array1 != array2
6366 always_evals_to = 1; // true
6367 break;
6368 default:
6369 // best we can say is 'a constant'
6370 always_evals_to = 2; // e.g. array1 <= array2
6371 break;
6373 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6374 << 1 // array
6375 << always_evals_to);
6380 if (isa<CastExpr>(LHSStripped))
6381 LHSStripped = LHSStripped->IgnoreParenCasts();
6382 if (isa<CastExpr>(RHSStripped))
6383 RHSStripped = RHSStripped->IgnoreParenCasts();
6385 // Warn about comparisons against a string constant (unless the other
6386 // operand is null), the user probably wants strcmp.
6387 Expr *literalString = 0;
6388 Expr *literalStringStripped = 0;
6389 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6390 !RHSStripped->isNullPointerConstant(Context,
6391 Expr::NPC_ValueDependentIsNull)) {
6392 literalString = lex;
6393 literalStringStripped = LHSStripped;
6394 } else if ((isa<StringLiteral>(RHSStripped) ||
6395 isa<ObjCEncodeExpr>(RHSStripped)) &&
6396 !LHSStripped->isNullPointerConstant(Context,
6397 Expr::NPC_ValueDependentIsNull)) {
6398 literalString = rex;
6399 literalStringStripped = RHSStripped;
6402 if (literalString) {
6403 std::string resultComparison;
6404 switch (Opc) {
6405 case BO_LT: resultComparison = ") < 0"; break;
6406 case BO_GT: resultComparison = ") > 0"; break;
6407 case BO_LE: resultComparison = ") <= 0"; break;
6408 case BO_GE: resultComparison = ") >= 0"; break;
6409 case BO_EQ: resultComparison = ") == 0"; break;
6410 case BO_NE: resultComparison = ") != 0"; break;
6411 default: assert(false && "Invalid comparison operator");
6414 DiagRuntimeBehavior(Loc,
6415 PDiag(diag::warn_stringcompare)
6416 << isa<ObjCEncodeExpr>(literalStringStripped)
6417 << literalString->getSourceRange());
6421 // C99 6.5.8p3 / C99 6.5.9p4
6422 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6423 UsualArithmeticConversions(lex, rex);
6424 else {
6425 UsualUnaryConversions(lex);
6426 UsualUnaryConversions(rex);
6429 lType = lex->getType();
6430 rType = rex->getType();
6432 // The result of comparisons is 'bool' in C++, 'int' in C.
6433 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
6435 if (isRelational) {
6436 if (lType->isRealType() && rType->isRealType())
6437 return ResultTy;
6438 } else {
6439 // Check for comparisons of floating point operands using != and ==.
6440 if (lType->hasFloatingRepresentation())
6441 CheckFloatComparison(Loc,lex,rex);
6443 if (lType->isArithmeticType() && rType->isArithmeticType())
6444 return ResultTy;
6447 bool LHSIsNull = lex->isNullPointerConstant(Context,
6448 Expr::NPC_ValueDependentIsNull);
6449 bool RHSIsNull = rex->isNullPointerConstant(Context,
6450 Expr::NPC_ValueDependentIsNull);
6452 // All of the following pointer-related warnings are GCC extensions, except
6453 // when handling null pointer constants.
6454 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
6455 QualType LCanPointeeTy =
6456 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
6457 QualType RCanPointeeTy =
6458 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
6460 if (getLangOptions().CPlusPlus) {
6461 if (LCanPointeeTy == RCanPointeeTy)
6462 return ResultTy;
6463 if (!isRelational &&
6464 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6465 // Valid unless comparison between non-null pointer and function pointer
6466 // This is a gcc extension compatibility comparison.
6467 // In a SFINAE context, we treat this as a hard error to maintain
6468 // conformance with the C++ standard.
6469 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6470 && !LHSIsNull && !RHSIsNull) {
6471 Diag(Loc,
6472 isSFINAEContext()?
6473 diag::err_typecheck_comparison_of_fptr_to_void
6474 : diag::ext_typecheck_comparison_of_fptr_to_void)
6475 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6477 if (isSFINAEContext())
6478 return QualType();
6480 ImpCastExprToType(rex, lType, CK_BitCast);
6481 return ResultTy;
6485 // C++ [expr.rel]p2:
6486 // [...] Pointer conversions (4.10) and qualification
6487 // conversions (4.4) are performed on pointer operands (or on
6488 // a pointer operand and a null pointer constant) to bring
6489 // them to their composite pointer type. [...]
6491 // C++ [expr.eq]p1 uses the same notion for (in)equality
6492 // comparisons of pointers.
6493 bool NonStandardCompositeType = false;
6494 QualType T = FindCompositePointerType(Loc, lex, rex,
6495 isSFINAEContext()? 0 : &NonStandardCompositeType);
6496 if (T.isNull()) {
6497 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6498 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6499 return QualType();
6500 } else if (NonStandardCompositeType) {
6501 Diag(Loc,
6502 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6503 << lType << rType << T
6504 << lex->getSourceRange() << rex->getSourceRange();
6507 ImpCastExprToType(lex, T, CK_BitCast);
6508 ImpCastExprToType(rex, T, CK_BitCast);
6509 return ResultTy;
6511 // C99 6.5.9p2 and C99 6.5.8p2
6512 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6513 RCanPointeeTy.getUnqualifiedType())) {
6514 // Valid unless a relational comparison of function pointers
6515 if (isRelational && LCanPointeeTy->isFunctionType()) {
6516 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6517 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6519 } else if (!isRelational &&
6520 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6521 // Valid unless comparison between non-null pointer and function pointer
6522 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6523 && !LHSIsNull && !RHSIsNull) {
6524 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6525 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6527 } else {
6528 // Invalid
6529 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6530 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6532 if (LCanPointeeTy != RCanPointeeTy)
6533 ImpCastExprToType(rex, lType, CK_BitCast);
6534 return ResultTy;
6537 if (getLangOptions().CPlusPlus) {
6538 // Comparison of nullptr_t with itself.
6539 if (lType->isNullPtrType() && rType->isNullPtrType())
6540 return ResultTy;
6542 // Comparison of pointers with null pointer constants and equality
6543 // comparisons of member pointers to null pointer constants.
6544 if (RHSIsNull &&
6545 ((lType->isPointerType() || lType->isNullPtrType()) ||
6546 (!isRelational && lType->isMemberPointerType()))) {
6547 ImpCastExprToType(rex, lType,
6548 lType->isMemberPointerType()
6549 ? CK_NullToMemberPointer
6550 : CK_NullToPointer);
6551 return ResultTy;
6553 if (LHSIsNull &&
6554 ((rType->isPointerType() || rType->isNullPtrType()) ||
6555 (!isRelational && rType->isMemberPointerType()))) {
6556 ImpCastExprToType(lex, rType,
6557 rType->isMemberPointerType()
6558 ? CK_NullToMemberPointer
6559 : CK_NullToPointer);
6560 return ResultTy;
6563 // Comparison of member pointers.
6564 if (!isRelational &&
6565 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6566 // C++ [expr.eq]p2:
6567 // In addition, pointers to members can be compared, or a pointer to
6568 // member and a null pointer constant. Pointer to member conversions
6569 // (4.11) and qualification conversions (4.4) are performed to bring
6570 // them to a common type. If one operand is a null pointer constant,
6571 // the common type is the type of the other operand. Otherwise, the
6572 // common type is a pointer to member type similar (4.4) to the type
6573 // of one of the operands, with a cv-qualification signature (4.4)
6574 // that is the union of the cv-qualification signatures of the operand
6575 // types.
6576 bool NonStandardCompositeType = false;
6577 QualType T = FindCompositePointerType(Loc, lex, rex,
6578 isSFINAEContext()? 0 : &NonStandardCompositeType);
6579 if (T.isNull()) {
6580 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6581 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6582 return QualType();
6583 } else if (NonStandardCompositeType) {
6584 Diag(Loc,
6585 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6586 << lType << rType << T
6587 << lex->getSourceRange() << rex->getSourceRange();
6590 ImpCastExprToType(lex, T, CK_BitCast);
6591 ImpCastExprToType(rex, T, CK_BitCast);
6592 return ResultTy;
6596 // Handle block pointer types.
6597 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
6598 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6599 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
6601 if (!LHSIsNull && !RHSIsNull &&
6602 !Context.typesAreCompatible(lpointee, rpointee)) {
6603 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6604 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6606 ImpCastExprToType(rex, lType, CK_BitCast);
6607 return ResultTy;
6609 // Allow block pointers to be compared with null pointer constants.
6610 if (!isRelational
6611 && ((lType->isBlockPointerType() && rType->isPointerType())
6612 || (lType->isPointerType() && rType->isBlockPointerType()))) {
6613 if (!LHSIsNull && !RHSIsNull) {
6614 if (!((rType->isPointerType() && rType->getAs<PointerType>()
6615 ->getPointeeType()->isVoidType())
6616 || (lType->isPointerType() && lType->getAs<PointerType>()
6617 ->getPointeeType()->isVoidType())))
6618 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6619 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6621 ImpCastExprToType(rex, lType, CK_BitCast);
6622 return ResultTy;
6625 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
6626 if (lType->isPointerType() || rType->isPointerType()) {
6627 const PointerType *LPT = lType->getAs<PointerType>();
6628 const PointerType *RPT = rType->getAs<PointerType>();
6629 bool LPtrToVoid = LPT ?
6630 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
6631 bool RPtrToVoid = RPT ?
6632 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
6634 if (!LPtrToVoid && !RPtrToVoid &&
6635 !Context.typesAreCompatible(lType, rType)) {
6636 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6637 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6639 ImpCastExprToType(rex, lType, CK_BitCast);
6640 return ResultTy;
6642 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
6643 if (!Context.areComparableObjCPointerTypes(lType, rType))
6644 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6645 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6646 ImpCastExprToType(rex, lType, CK_BitCast);
6647 return ResultTy;
6650 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6651 (lType->isIntegerType() && rType->isAnyPointerType())) {
6652 unsigned DiagID = 0;
6653 bool isError = false;
6654 if ((LHSIsNull && lType->isIntegerType()) ||
6655 (RHSIsNull && rType->isIntegerType())) {
6656 if (isRelational && !getLangOptions().CPlusPlus)
6657 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
6658 } else if (isRelational && !getLangOptions().CPlusPlus)
6659 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
6660 else if (getLangOptions().CPlusPlus) {
6661 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6662 isError = true;
6663 } else
6664 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
6666 if (DiagID) {
6667 Diag(Loc, DiagID)
6668 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6669 if (isError)
6670 return QualType();
6673 if (lType->isIntegerType())
6674 ImpCastExprToType(lex, rType,
6675 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6676 else
6677 ImpCastExprToType(rex, lType,
6678 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6679 return ResultTy;
6682 // Handle block pointers.
6683 if (!isRelational && RHSIsNull
6684 && lType->isBlockPointerType() && rType->isIntegerType()) {
6685 ImpCastExprToType(rex, lType, CK_NullToPointer);
6686 return ResultTy;
6688 if (!isRelational && LHSIsNull
6689 && lType->isIntegerType() && rType->isBlockPointerType()) {
6690 ImpCastExprToType(lex, rType, CK_NullToPointer);
6691 return ResultTy;
6693 return InvalidOperands(Loc, lex, rex);
6696 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
6697 /// operates on extended vector types. Instead of producing an IntTy result,
6698 /// like a scalar comparison, a vector comparison produces a vector of integer
6699 /// types.
6700 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
6701 SourceLocation Loc,
6702 bool isRelational) {
6703 // Check to make sure we're operating on vectors of the same type and width,
6704 // Allowing one side to be a scalar of element type.
6705 QualType vType = CheckVectorOperands(Loc, lex, rex);
6706 if (vType.isNull())
6707 return vType;
6709 // If AltiVec, the comparison results in a numeric type, i.e.
6710 // bool for C++, int for C
6711 if (getLangOptions().AltiVec)
6712 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6714 QualType lType = lex->getType();
6715 QualType rType = rex->getType();
6717 // For non-floating point types, check for self-comparisons of the form
6718 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6719 // often indicate logic errors in the program.
6720 if (!lType->hasFloatingRepresentation()) {
6721 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6722 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6723 if (DRL->getDecl() == DRR->getDecl())
6724 DiagRuntimeBehavior(Loc,
6725 PDiag(diag::warn_comparison_always)
6726 << 0 // self-
6727 << 2 // "a constant"
6731 // Check for comparisons of floating point operands using != and ==.
6732 if (!isRelational && lType->hasFloatingRepresentation()) {
6733 assert (rType->hasFloatingRepresentation());
6734 CheckFloatComparison(Loc,lex,rex);
6737 // Return the type for the comparison, which is the same as vector type for
6738 // integer vectors, or an integer type of identical size and number of
6739 // elements for floating point vectors.
6740 if (lType->hasIntegerRepresentation())
6741 return lType;
6743 const VectorType *VTy = lType->getAs<VectorType>();
6744 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6745 if (TypeSize == Context.getTypeSize(Context.IntTy))
6746 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6747 if (TypeSize == Context.getTypeSize(Context.LongTy))
6748 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6750 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6751 "Unhandled vector element size in vector compare");
6752 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6755 inline QualType Sema::CheckBitwiseOperands(
6756 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
6757 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6758 if (lex->getType()->hasIntegerRepresentation() &&
6759 rex->getType()->hasIntegerRepresentation())
6760 return CheckVectorOperands(Loc, lex, rex);
6762 return InvalidOperands(Loc, lex, rex);
6765 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6767 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6768 rex->getType()->isIntegralOrUnscopedEnumerationType())
6769 return compType;
6770 return InvalidOperands(Loc, lex, rex);
6773 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
6774 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6776 // Diagnose cases where the user write a logical and/or but probably meant a
6777 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6778 // is a constant.
6779 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
6780 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
6781 // Don't warn in macros.
6782 !Loc.isMacroID()) {
6783 // If the RHS can be constant folded, and if it constant folds to something
6784 // that isn't 0 or 1 (which indicate a potential logical operation that
6785 // happened to fold to true/false) then warn.
6786 Expr::EvalResult Result;
6787 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6788 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6789 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6790 << rex->getSourceRange()
6791 << (Opc == BO_LAnd ? "&&" : "||")
6792 << (Opc == BO_LAnd ? "&" : "|");
6796 if (!Context.getLangOptions().CPlusPlus) {
6797 UsualUnaryConversions(lex);
6798 UsualUnaryConversions(rex);
6800 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6801 return InvalidOperands(Loc, lex, rex);
6803 return Context.IntTy;
6806 // The following is safe because we only use this method for
6807 // non-overloadable operands.
6809 // C++ [expr.log.and]p1
6810 // C++ [expr.log.or]p1
6811 // The operands are both contextually converted to type bool.
6812 if (PerformContextuallyConvertToBool(lex) ||
6813 PerformContextuallyConvertToBool(rex))
6814 return InvalidOperands(Loc, lex, rex);
6816 // C++ [expr.log.and]p2
6817 // C++ [expr.log.or]p2
6818 // The result is a bool.
6819 return Context.BoolTy;
6822 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6823 /// is a read-only property; return true if so. A readonly property expression
6824 /// depends on various declarations and thus must be treated specially.
6826 static bool IsReadonlyProperty(Expr *E, Sema &S) {
6827 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6828 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6829 if (PropExpr->isImplicitProperty()) return false;
6831 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6832 QualType BaseType = PropExpr->isSuperReceiver() ?
6833 PropExpr->getSuperReceiverType() :
6834 PropExpr->getBase()->getType();
6836 if (const ObjCObjectPointerType *OPT =
6837 BaseType->getAsObjCInterfacePointerType())
6838 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6839 if (S.isPropertyReadonly(PDecl, IFace))
6840 return true;
6842 return false;
6845 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6846 /// emit an error and return true. If so, return false.
6847 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
6848 SourceLocation OrigLoc = Loc;
6849 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
6850 &Loc);
6851 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6852 IsLV = Expr::MLV_ReadonlyProperty;
6853 if (IsLV == Expr::MLV_Valid)
6854 return false;
6856 unsigned Diag = 0;
6857 bool NeedType = false;
6858 switch (IsLV) { // C99 6.5.16p2
6859 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
6860 case Expr::MLV_ArrayType:
6861 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6862 NeedType = true;
6863 break;
6864 case Expr::MLV_NotObjectType:
6865 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6866 NeedType = true;
6867 break;
6868 case Expr::MLV_LValueCast:
6869 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6870 break;
6871 case Expr::MLV_Valid:
6872 llvm_unreachable("did not take early return for MLV_Valid");
6873 case Expr::MLV_InvalidExpression:
6874 case Expr::MLV_MemberFunction:
6875 case Expr::MLV_ClassTemporary:
6876 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6877 break;
6878 case Expr::MLV_IncompleteType:
6879 case Expr::MLV_IncompleteVoidType:
6880 return S.RequireCompleteType(Loc, E->getType(),
6881 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
6882 << E->getSourceRange());
6883 case Expr::MLV_DuplicateVectorComponents:
6884 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6885 break;
6886 case Expr::MLV_NotBlockQualified:
6887 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6888 break;
6889 case Expr::MLV_ReadonlyProperty:
6890 Diag = diag::error_readonly_property_assignment;
6891 break;
6892 case Expr::MLV_NoSetterProperty:
6893 Diag = diag::error_nosetter_property_assignment;
6894 break;
6895 case Expr::MLV_SubObjCPropertySetting:
6896 Diag = diag::error_no_subobject_property_setting;
6897 break;
6900 SourceRange Assign;
6901 if (Loc != OrigLoc)
6902 Assign = SourceRange(OrigLoc, OrigLoc);
6903 if (NeedType)
6904 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
6905 else
6906 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6907 return true;
6912 // C99 6.5.16.1
6913 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6914 SourceLocation Loc,
6915 QualType CompoundType) {
6916 // Verify that LHS is a modifiable lvalue, and emit error if not.
6917 if (CheckForModifiableLvalue(LHS, Loc, *this))
6918 return QualType();
6920 QualType LHSType = LHS->getType();
6921 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
6922 AssignConvertType ConvTy;
6923 if (CompoundType.isNull()) {
6924 QualType LHSTy(LHSType);
6925 // Simple assignment "x = y".
6926 if (LHS->getObjectKind() == OK_ObjCProperty)
6927 ConvertPropertyForLValue(LHS, RHS, LHSTy);
6928 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
6929 // Special case of NSObject attributes on c-style pointer types.
6930 if (ConvTy == IncompatiblePointer &&
6931 ((Context.isObjCNSObjectType(LHSType) &&
6932 RHSType->isObjCObjectPointerType()) ||
6933 (Context.isObjCNSObjectType(RHSType) &&
6934 LHSType->isObjCObjectPointerType())))
6935 ConvTy = Compatible;
6937 if (ConvTy == Compatible &&
6938 getLangOptions().ObjCNonFragileABI &&
6939 LHSType->isObjCObjectType())
6940 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6941 << LHSType;
6943 // If the RHS is a unary plus or minus, check to see if they = and + are
6944 // right next to each other. If so, the user may have typo'd "x =+ 4"
6945 // instead of "x += 4".
6946 Expr *RHSCheck = RHS;
6947 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6948 RHSCheck = ICE->getSubExpr();
6949 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
6950 if ((UO->getOpcode() == UO_Plus ||
6951 UO->getOpcode() == UO_Minus) &&
6952 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
6953 // Only if the two operators are exactly adjacent.
6954 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6955 // And there is a space or other character before the subexpr of the
6956 // unary +/-. We don't want to warn on "x=-1".
6957 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6958 UO->getSubExpr()->getLocStart().isFileID()) {
6959 Diag(Loc, diag::warn_not_compound_assign)
6960 << (UO->getOpcode() == UO_Plus ? "+" : "-")
6961 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
6964 } else {
6965 // Compound assignment "x += y"
6966 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
6969 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
6970 RHS, AA_Assigning))
6971 return QualType();
6974 // Check to see if the destination operand is a dereferenced null pointer. If
6975 // so, and if not volatile-qualified, this is undefined behavior that the
6976 // optimizer will delete, so warn about it. People sometimes try to use this
6977 // to get a deterministic trap and are surprised by clang's behavior. This
6978 // only handles the pattern "*null = whatever", which is a very syntactic
6979 // check.
6980 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
6981 if (UO->getOpcode() == UO_Deref &&
6982 UO->getSubExpr()->IgnoreParenCasts()->
6983 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6984 !UO->getType().isVolatileQualified()) {
6985 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6986 << UO->getSubExpr()->getSourceRange();
6987 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6990 // C99 6.5.16p3: The type of an assignment expression is the type of the
6991 // left operand unless the left operand has qualified type, in which case
6992 // it is the unqualified version of the type of the left operand.
6993 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6994 // is converted to the type of the assignment expression (above).
6995 // C++ 5.17p1: the type of the assignment expression is that of its left
6996 // operand.
6997 return (getLangOptions().CPlusPlus
6998 ? LHSType : LHSType.getUnqualifiedType());
7001 // C99 6.5.17
7002 static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
7003 SourceLocation Loc) {
7004 S.DiagnoseUnusedExprResult(LHS);
7006 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
7007 if (LHSResult.isInvalid())
7008 return QualType();
7010 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
7011 if (RHSResult.isInvalid())
7012 return QualType();
7013 RHS = RHSResult.take();
7015 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7016 // operands, but not unary promotions.
7017 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7019 // So we treat the LHS as a ignored value, and in C++ we allow the
7020 // containing site to determine what should be done with the RHS.
7021 S.IgnoredValueConversions(LHS);
7023 if (!S.getLangOptions().CPlusPlus) {
7024 S.DefaultFunctionArrayLvalueConversion(RHS);
7025 if (!RHS->getType()->isVoidType())
7026 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
7029 return RHS->getType();
7032 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7033 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7034 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7035 ExprValueKind &VK,
7036 SourceLocation OpLoc,
7037 bool isInc, bool isPrefix) {
7038 if (Op->isTypeDependent())
7039 return S.Context.DependentTy;
7041 QualType ResType = Op->getType();
7042 assert(!ResType.isNull() && "no type for increment/decrement expression");
7044 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
7045 // Decrement of bool is not allowed.
7046 if (!isInc) {
7047 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7048 return QualType();
7050 // Increment of bool sets it to true, but is deprecated.
7051 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7052 } else if (ResType->isRealType()) {
7053 // OK!
7054 } else if (ResType->isAnyPointerType()) {
7055 QualType PointeeTy = ResType->getPointeeType();
7057 // C99 6.5.2.4p2, 6.5.6p2
7058 if (PointeeTy->isVoidType()) {
7059 if (S.getLangOptions().CPlusPlus) {
7060 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
7061 << Op->getSourceRange();
7062 return QualType();
7065 // Pointer to void is a GNU extension in C.
7066 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
7067 } else if (PointeeTy->isFunctionType()) {
7068 if (S.getLangOptions().CPlusPlus) {
7069 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
7070 << Op->getType() << Op->getSourceRange();
7071 return QualType();
7074 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
7075 << ResType << Op->getSourceRange();
7076 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7077 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7078 << Op->getSourceRange()
7079 << ResType))
7080 return QualType();
7081 // Diagnose bad cases where we step over interface counts.
7082 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7083 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
7084 << PointeeTy << Op->getSourceRange();
7085 return QualType();
7087 } else if (ResType->isAnyComplexType()) {
7088 // C99 does not support ++/-- on complex types, we allow as an extension.
7089 S.Diag(OpLoc, diag::ext_integer_increment_complex)
7090 << ResType << Op->getSourceRange();
7091 } else if (ResType->isPlaceholderType()) {
7092 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
7093 if (PR.isInvalid()) return QualType();
7094 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7095 isInc, isPrefix);
7096 } else {
7097 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7098 << ResType << int(isInc) << Op->getSourceRange();
7099 return QualType();
7101 // At this point, we know we have a real, complex or pointer type.
7102 // Now make sure the operand is a modifiable lvalue.
7103 if (CheckForModifiableLvalue(Op, OpLoc, S))
7104 return QualType();
7105 // In C++, a prefix increment is the same type as the operand. Otherwise
7106 // (in C or with postfix), the increment is the unqualified type of the
7107 // operand.
7108 if (isPrefix && S.getLangOptions().CPlusPlus) {
7109 VK = VK_LValue;
7110 return ResType;
7111 } else {
7112 VK = VK_RValue;
7113 return ResType.getUnqualifiedType();
7117 void Sema::ConvertPropertyForRValue(Expr *&E) {
7118 assert(E->getValueKind() == VK_LValue &&
7119 E->getObjectKind() == OK_ObjCProperty);
7120 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7122 ExprValueKind VK = VK_RValue;
7123 if (PRE->isImplicitProperty()) {
7124 if (const ObjCMethodDecl *GetterMethod =
7125 PRE->getImplicitPropertyGetter()) {
7126 QualType Result = GetterMethod->getResultType();
7127 VK = Expr::getValueKindForType(Result);
7129 else {
7130 Diag(PRE->getLocation(), diag::err_getter_not_found)
7131 << PRE->getBase()->getType();
7135 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7136 E, 0, VK);
7138 ExprResult Result = MaybeBindToTemporary(E);
7139 if (!Result.isInvalid())
7140 E = Result.take();
7143 void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7144 assert(LHS->getValueKind() == VK_LValue &&
7145 LHS->getObjectKind() == OK_ObjCProperty);
7146 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7148 if (PRE->isImplicitProperty()) {
7149 // If using property-dot syntax notation for assignment, and there is a
7150 // setter, RHS expression is being passed to the setter argument. So,
7151 // type conversion (and comparison) is RHS to setter's argument type.
7152 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7153 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7154 LHSTy = (*P)->getType();
7156 // Otherwise, if the getter returns an l-value, just call that.
7157 } else {
7158 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7159 ExprValueKind VK = Expr::getValueKindForType(Result);
7160 if (VK == VK_LValue) {
7161 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7162 CK_GetObjCProperty, LHS, 0, VK);
7163 return;
7168 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
7169 InitializedEntity Entity =
7170 InitializedEntity::InitializeParameter(Context, LHSTy);
7171 Expr *Arg = RHS;
7172 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7173 Owned(Arg));
7174 if (!ArgE.isInvalid())
7175 RHS = ArgE.takeAs<Expr>();
7180 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7181 /// This routine allows us to typecheck complex/recursive expressions
7182 /// where the declaration is needed for type checking. We only need to
7183 /// handle cases when the expression references a function designator
7184 /// or is an lvalue. Here are some examples:
7185 /// - &(x) => x
7186 /// - &*****f => f for f a function designator.
7187 /// - &s.xx => s
7188 /// - &s.zz[1].yy -> s, if zz is an array
7189 /// - *(x + 1) -> x, if x is an array
7190 /// - &"123"[2] -> 0
7191 /// - & __real__ x -> x
7192 static NamedDecl *getPrimaryDecl(Expr *E) {
7193 switch (E->getStmtClass()) {
7194 case Stmt::DeclRefExprClass:
7195 return cast<DeclRefExpr>(E)->getDecl();
7196 case Stmt::MemberExprClass:
7197 // If this is an arrow operator, the address is an offset from
7198 // the base's value, so the object the base refers to is
7199 // irrelevant.
7200 if (cast<MemberExpr>(E)->isArrow())
7201 return 0;
7202 // Otherwise, the expression refers to a part of the base
7203 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7204 case Stmt::ArraySubscriptExprClass: {
7205 // FIXME: This code shouldn't be necessary! We should catch the implicit
7206 // promotion of register arrays earlier.
7207 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7208 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7209 if (ICE->getSubExpr()->getType()->isArrayType())
7210 return getPrimaryDecl(ICE->getSubExpr());
7212 return 0;
7214 case Stmt::UnaryOperatorClass: {
7215 UnaryOperator *UO = cast<UnaryOperator>(E);
7217 switch(UO->getOpcode()) {
7218 case UO_Real:
7219 case UO_Imag:
7220 case UO_Extension:
7221 return getPrimaryDecl(UO->getSubExpr());
7222 default:
7223 return 0;
7226 case Stmt::ParenExprClass:
7227 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7228 case Stmt::ImplicitCastExprClass:
7229 // If the result of an implicit cast is an l-value, we care about
7230 // the sub-expression; otherwise, the result here doesn't matter.
7231 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7232 default:
7233 return 0;
7237 /// CheckAddressOfOperand - The operand of & must be either a function
7238 /// designator or an lvalue designating an object. If it is an lvalue, the
7239 /// object cannot be declared with storage class register or be a bit field.
7240 /// Note: The usual conversions are *not* applied to the operand of the &
7241 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7242 /// In C++, the operand might be an overloaded function name, in which case
7243 /// we allow the '&' but retain the overloaded-function type.
7244 static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7245 SourceLocation OpLoc) {
7246 if (OrigOp->isTypeDependent())
7247 return S.Context.DependentTy;
7248 if (OrigOp->getType() == S.Context.OverloadTy)
7249 return S.Context.OverloadTy;
7251 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
7252 if (PR.isInvalid()) return QualType();
7253 OrigOp = PR.take();
7255 // Make sure to ignore parentheses in subsequent checks
7256 Expr *op = OrigOp->IgnoreParens();
7258 if (S.getLangOptions().C99) {
7259 // Implement C99-only parts of addressof rules.
7260 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7261 if (uOp->getOpcode() == UO_Deref)
7262 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7263 // (assuming the deref expression is valid).
7264 return uOp->getSubExpr()->getType();
7266 // Technically, there should be a check for array subscript
7267 // expressions here, but the result of one is always an lvalue anyway.
7269 NamedDecl *dcl = getPrimaryDecl(op);
7270 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7272 if (lval == Expr::LV_ClassTemporary) {
7273 bool sfinae = S.isSFINAEContext();
7274 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7275 : diag::ext_typecheck_addrof_class_temporary)
7276 << op->getType() << op->getSourceRange();
7277 if (sfinae)
7278 return QualType();
7279 } else if (isa<ObjCSelectorExpr>(op)) {
7280 return S.Context.getPointerType(op->getType());
7281 } else if (lval == Expr::LV_MemberFunction) {
7282 // If it's an instance method, make a member pointer.
7283 // The expression must have exactly the form &A::foo.
7285 // If the underlying expression isn't a decl ref, give up.
7286 if (!isa<DeclRefExpr>(op)) {
7287 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7288 << OrigOp->getSourceRange();
7289 return QualType();
7291 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7292 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7294 // The id-expression was parenthesized.
7295 if (OrigOp != DRE) {
7296 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7297 << OrigOp->getSourceRange();
7299 // The method was named without a qualifier.
7300 } else if (!DRE->getQualifier()) {
7301 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7302 << op->getSourceRange();
7305 return S.Context.getMemberPointerType(op->getType(),
7306 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7307 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7308 // C99 6.5.3.2p1
7309 // The operand must be either an l-value or a function designator
7310 if (!op->getType()->isFunctionType()) {
7311 // FIXME: emit more specific diag...
7312 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7313 << op->getSourceRange();
7314 return QualType();
7316 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7317 // The operand cannot be a bit-field
7318 S.Diag(OpLoc, diag::err_typecheck_address_of)
7319 << "bit-field" << op->getSourceRange();
7320 return QualType();
7321 } else if (op->getObjectKind() == OK_VectorComponent) {
7322 // The operand cannot be an element of a vector
7323 S.Diag(OpLoc, diag::err_typecheck_address_of)
7324 << "vector element" << op->getSourceRange();
7325 return QualType();
7326 } else if (op->getObjectKind() == OK_ObjCProperty) {
7327 // cannot take address of a property expression.
7328 S.Diag(OpLoc, diag::err_typecheck_address_of)
7329 << "property expression" << op->getSourceRange();
7330 return QualType();
7331 } else if (dcl) { // C99 6.5.3.2p1
7332 // We have an lvalue with a decl. Make sure the decl is not declared
7333 // with the register storage-class specifier.
7334 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7335 // in C++ it is not error to take address of a register
7336 // variable (c++03 7.1.1P3)
7337 if (vd->getStorageClass() == SC_Register &&
7338 !S.getLangOptions().CPlusPlus) {
7339 S.Diag(OpLoc, diag::err_typecheck_address_of)
7340 << "register variable" << op->getSourceRange();
7341 return QualType();
7343 } else if (isa<FunctionTemplateDecl>(dcl)) {
7344 return S.Context.OverloadTy;
7345 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
7346 // Okay: we can take the address of a field.
7347 // Could be a pointer to member, though, if there is an explicit
7348 // scope qualifier for the class.
7349 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7350 DeclContext *Ctx = dcl->getDeclContext();
7351 if (Ctx && Ctx->isRecord()) {
7352 if (FD->getType()->isReferenceType()) {
7353 S.Diag(OpLoc,
7354 diag::err_cannot_form_pointer_to_member_of_reference_type)
7355 << FD->getDeclName() << FD->getType();
7356 return QualType();
7359 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7360 Ctx = Ctx->getParent();
7361 return S.Context.getMemberPointerType(op->getType(),
7362 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7365 } else if (!isa<FunctionDecl>(dcl))
7366 assert(0 && "Unknown/unexpected decl type");
7369 if (lval == Expr::LV_IncompleteVoidType) {
7370 // Taking the address of a void variable is technically illegal, but we
7371 // allow it in cases which are otherwise valid.
7372 // Example: "extern void x; void* y = &x;".
7373 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7376 // If the operand has type "type", the result has type "pointer to type".
7377 if (op->getType()->isObjCObjectType())
7378 return S.Context.getObjCObjectPointerType(op->getType());
7379 return S.Context.getPointerType(op->getType());
7382 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7383 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7384 SourceLocation OpLoc) {
7385 if (Op->isTypeDependent())
7386 return S.Context.DependentTy;
7388 S.UsualUnaryConversions(Op);
7389 QualType OpTy = Op->getType();
7390 QualType Result;
7392 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7393 // is an incomplete type or void. It would be possible to warn about
7394 // dereferencing a void pointer, but it's completely well-defined, and such a
7395 // warning is unlikely to catch any mistakes.
7396 if (const PointerType *PT = OpTy->getAs<PointerType>())
7397 Result = PT->getPointeeType();
7398 else if (const ObjCObjectPointerType *OPT =
7399 OpTy->getAs<ObjCObjectPointerType>())
7400 Result = OPT->getPointeeType();
7401 else {
7402 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
7403 if (PR.isInvalid()) return QualType();
7404 if (PR.take() != Op)
7405 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
7408 if (Result.isNull()) {
7409 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
7410 << OpTy << Op->getSourceRange();
7411 return QualType();
7414 // Dereferences are usually l-values...
7415 VK = VK_LValue;
7417 // ...except that certain expressions are never l-values in C.
7418 if (!S.getLangOptions().CPlusPlus &&
7419 IsCForbiddenLValueType(S.Context, Result))
7420 VK = VK_RValue;
7422 return Result;
7425 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
7426 tok::TokenKind Kind) {
7427 BinaryOperatorKind Opc;
7428 switch (Kind) {
7429 default: assert(0 && "Unknown binop!");
7430 case tok::periodstar: Opc = BO_PtrMemD; break;
7431 case tok::arrowstar: Opc = BO_PtrMemI; break;
7432 case tok::star: Opc = BO_Mul; break;
7433 case tok::slash: Opc = BO_Div; break;
7434 case tok::percent: Opc = BO_Rem; break;
7435 case tok::plus: Opc = BO_Add; break;
7436 case tok::minus: Opc = BO_Sub; break;
7437 case tok::lessless: Opc = BO_Shl; break;
7438 case tok::greatergreater: Opc = BO_Shr; break;
7439 case tok::lessequal: Opc = BO_LE; break;
7440 case tok::less: Opc = BO_LT; break;
7441 case tok::greaterequal: Opc = BO_GE; break;
7442 case tok::greater: Opc = BO_GT; break;
7443 case tok::exclaimequal: Opc = BO_NE; break;
7444 case tok::equalequal: Opc = BO_EQ; break;
7445 case tok::amp: Opc = BO_And; break;
7446 case tok::caret: Opc = BO_Xor; break;
7447 case tok::pipe: Opc = BO_Or; break;
7448 case tok::ampamp: Opc = BO_LAnd; break;
7449 case tok::pipepipe: Opc = BO_LOr; break;
7450 case tok::equal: Opc = BO_Assign; break;
7451 case tok::starequal: Opc = BO_MulAssign; break;
7452 case tok::slashequal: Opc = BO_DivAssign; break;
7453 case tok::percentequal: Opc = BO_RemAssign; break;
7454 case tok::plusequal: Opc = BO_AddAssign; break;
7455 case tok::minusequal: Opc = BO_SubAssign; break;
7456 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7457 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7458 case tok::ampequal: Opc = BO_AndAssign; break;
7459 case tok::caretequal: Opc = BO_XorAssign; break;
7460 case tok::pipeequal: Opc = BO_OrAssign; break;
7461 case tok::comma: Opc = BO_Comma; break;
7463 return Opc;
7466 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
7467 tok::TokenKind Kind) {
7468 UnaryOperatorKind Opc;
7469 switch (Kind) {
7470 default: assert(0 && "Unknown unary op!");
7471 case tok::plusplus: Opc = UO_PreInc; break;
7472 case tok::minusminus: Opc = UO_PreDec; break;
7473 case tok::amp: Opc = UO_AddrOf; break;
7474 case tok::star: Opc = UO_Deref; break;
7475 case tok::plus: Opc = UO_Plus; break;
7476 case tok::minus: Opc = UO_Minus; break;
7477 case tok::tilde: Opc = UO_Not; break;
7478 case tok::exclaim: Opc = UO_LNot; break;
7479 case tok::kw___real: Opc = UO_Real; break;
7480 case tok::kw___imag: Opc = UO_Imag; break;
7481 case tok::kw___extension__: Opc = UO_Extension; break;
7483 return Opc;
7486 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7487 /// This warning is only emitted for builtin assignment operations. It is also
7488 /// suppressed in the event of macro expansions.
7489 static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7490 SourceLocation OpLoc) {
7491 if (!S.ActiveTemplateInstantiations.empty())
7492 return;
7493 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7494 return;
7495 lhs = lhs->IgnoreParenImpCasts();
7496 rhs = rhs->IgnoreParenImpCasts();
7497 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7498 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7499 if (!LeftDeclRef || !RightDeclRef ||
7500 LeftDeclRef->getLocation().isMacroID() ||
7501 RightDeclRef->getLocation().isMacroID())
7502 return;
7503 const ValueDecl *LeftDecl =
7504 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7505 const ValueDecl *RightDecl =
7506 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7507 if (LeftDecl != RightDecl)
7508 return;
7509 if (LeftDecl->getType().isVolatileQualified())
7510 return;
7511 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7512 if (RefTy->getPointeeType().isVolatileQualified())
7513 return;
7515 S.Diag(OpLoc, diag::warn_self_assignment)
7516 << LeftDeclRef->getType()
7517 << lhs->getSourceRange() << rhs->getSourceRange();
7520 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7521 /// operator @p Opc at location @c TokLoc. This routine only supports
7522 /// built-in operations; ActOnBinOp handles overloaded operators.
7523 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
7524 BinaryOperatorKind Opc,
7525 Expr *lhs, Expr *rhs) {
7526 QualType ResultTy; // Result type of the binary operator.
7527 // The following two variables are used for compound assignment operators
7528 QualType CompLHSTy; // Type of LHS after promotions for computation
7529 QualType CompResultTy; // Type of computation result
7530 ExprValueKind VK = VK_RValue;
7531 ExprObjectKind OK = OK_Ordinary;
7533 switch (Opc) {
7534 case BO_Assign:
7535 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
7536 if (getLangOptions().CPlusPlus &&
7537 lhs->getObjectKind() != OK_ObjCProperty) {
7538 VK = lhs->getValueKind();
7539 OK = lhs->getObjectKind();
7541 if (!ResultTy.isNull())
7542 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
7543 break;
7544 case BO_PtrMemD:
7545 case BO_PtrMemI:
7546 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
7547 Opc == BO_PtrMemI);
7548 break;
7549 case BO_Mul:
7550 case BO_Div:
7551 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
7552 Opc == BO_Div);
7553 break;
7554 case BO_Rem:
7555 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7556 break;
7557 case BO_Add:
7558 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7559 break;
7560 case BO_Sub:
7561 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7562 break;
7563 case BO_Shl:
7564 case BO_Shr:
7565 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7566 break;
7567 case BO_LE:
7568 case BO_LT:
7569 case BO_GE:
7570 case BO_GT:
7571 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
7572 break;
7573 case BO_EQ:
7574 case BO_NE:
7575 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
7576 break;
7577 case BO_And:
7578 case BO_Xor:
7579 case BO_Or:
7580 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7581 break;
7582 case BO_LAnd:
7583 case BO_LOr:
7584 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
7585 break;
7586 case BO_MulAssign:
7587 case BO_DivAssign:
7588 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
7589 Opc == BO_DivAssign);
7590 CompLHSTy = CompResultTy;
7591 if (!CompResultTy.isNull())
7592 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7593 break;
7594 case BO_RemAssign:
7595 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7596 CompLHSTy = CompResultTy;
7597 if (!CompResultTy.isNull())
7598 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7599 break;
7600 case BO_AddAssign:
7601 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7602 if (!CompResultTy.isNull())
7603 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7604 break;
7605 case BO_SubAssign:
7606 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7607 if (!CompResultTy.isNull())
7608 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7609 break;
7610 case BO_ShlAssign:
7611 case BO_ShrAssign:
7612 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7613 CompLHSTy = CompResultTy;
7614 if (!CompResultTy.isNull())
7615 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7616 break;
7617 case BO_AndAssign:
7618 case BO_XorAssign:
7619 case BO_OrAssign:
7620 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7621 CompLHSTy = CompResultTy;
7622 if (!CompResultTy.isNull())
7623 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7624 break;
7625 case BO_Comma:
7626 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
7627 if (getLangOptions().CPlusPlus) {
7628 VK = rhs->getValueKind();
7629 OK = rhs->getObjectKind();
7631 break;
7633 if (ResultTy.isNull())
7634 return ExprError();
7635 if (CompResultTy.isNull())
7636 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7637 VK, OK, OpLoc));
7639 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
7640 VK = VK_LValue;
7641 OK = lhs->getObjectKind();
7643 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7644 VK, OK, CompLHSTy,
7645 CompResultTy, OpLoc));
7648 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7649 /// ParenRange in parentheses.
7650 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7651 const PartialDiagnostic &PD,
7652 const PartialDiagnostic &FirstNote,
7653 SourceRange FirstParenRange,
7654 const PartialDiagnostic &SecondNote,
7655 SourceRange SecondParenRange) {
7656 Self.Diag(Loc, PD);
7658 if (!FirstNote.getDiagID())
7659 return;
7661 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7662 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7663 // We can't display the parentheses, so just return.
7664 return;
7667 Self.Diag(Loc, FirstNote)
7668 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
7669 << FixItHint::CreateInsertion(EndLoc, ")");
7671 if (!SecondNote.getDiagID())
7672 return;
7674 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7675 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7676 // We can't display the parentheses, so just dig the
7677 // warning/error and return.
7678 Self.Diag(Loc, SecondNote);
7679 return;
7682 Self.Diag(Loc, SecondNote)
7683 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7684 << FixItHint::CreateInsertion(EndLoc, ")");
7687 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7688 /// operators are mixed in a way that suggests that the programmer forgot that
7689 /// comparison operators have higher precedence. The most typical example of
7690 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
7691 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
7692 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
7693 typedef BinaryOperator BinOp;
7694 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7695 rhsopc = static_cast<BinOp::Opcode>(-1);
7696 if (BinOp *BO = dyn_cast<BinOp>(lhs))
7697 lhsopc = BO->getOpcode();
7698 if (BinOp *BO = dyn_cast<BinOp>(rhs))
7699 rhsopc = BO->getOpcode();
7701 // Subs are not binary operators.
7702 if (lhsopc == -1 && rhsopc == -1)
7703 return;
7705 // Bitwise operations are sometimes used as eager logical ops.
7706 // Don't diagnose this.
7707 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7708 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
7709 return;
7711 if (BinOp::isComparisonOp(lhsopc))
7712 SuggestParentheses(Self, OpLoc,
7713 Self.PDiag(diag::warn_precedence_bitwise_rel)
7714 << SourceRange(lhs->getLocStart(), OpLoc)
7715 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
7716 Self.PDiag(diag::note_precedence_bitwise_first)
7717 << BinOp::getOpcodeStr(Opc),
7718 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7719 Self.PDiag(diag::note_precedence_bitwise_silence)
7720 << BinOp::getOpcodeStr(lhsopc),
7721 lhs->getSourceRange());
7722 else if (BinOp::isComparisonOp(rhsopc))
7723 SuggestParentheses(Self, OpLoc,
7724 Self.PDiag(diag::warn_precedence_bitwise_rel)
7725 << SourceRange(OpLoc, rhs->getLocEnd())
7726 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
7727 Self.PDiag(diag::note_precedence_bitwise_first)
7728 << BinOp::getOpcodeStr(Opc),
7729 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7730 Self.PDiag(diag::note_precedence_bitwise_silence)
7731 << BinOp::getOpcodeStr(rhsopc),
7732 rhs->getSourceRange());
7735 /// \brief It accepts a '&&' expr that is inside a '||' one.
7736 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7737 /// in parentheses.
7738 static void
7739 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7740 Expr *E) {
7741 assert(isa<BinaryOperator>(E) &&
7742 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7743 SuggestParentheses(Self, OpLoc,
7744 Self.PDiag(diag::warn_logical_and_in_logical_or)
7745 << E->getSourceRange(),
7746 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7747 E->getSourceRange(),
7748 Self.PDiag(0), SourceRange());
7751 /// \brief Returns true if the given expression can be evaluated as a constant
7752 /// 'true'.
7753 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7754 bool Res;
7755 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7758 /// \brief Returns true if the given expression can be evaluated as a constant
7759 /// 'false'.
7760 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7761 bool Res;
7762 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7765 /// \brief Look for '&&' in the left hand of a '||' expr.
7766 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
7767 Expr *OrLHS, Expr *OrRHS) {
7768 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
7769 if (Bop->getOpcode() == BO_LAnd) {
7770 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7771 if (EvaluatesAsFalse(S, OrRHS))
7772 return;
7773 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7774 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7775 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7776 } else if (Bop->getOpcode() == BO_LOr) {
7777 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7778 // If it's "a || b && 1 || c" we didn't warn earlier for
7779 // "a || b && 1", but warn now.
7780 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7781 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7787 /// \brief Look for '&&' in the right hand of a '||' expr.
7788 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
7789 Expr *OrLHS, Expr *OrRHS) {
7790 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
7791 if (Bop->getOpcode() == BO_LAnd) {
7792 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7793 if (EvaluatesAsFalse(S, OrLHS))
7794 return;
7795 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7796 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7797 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7802 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
7803 /// precedence.
7804 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
7805 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
7806 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
7807 if (BinaryOperator::isBitwiseOp(Opc))
7808 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7810 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7811 // We don't warn for 'assert(a || b && "bad")' since this is safe.
7812 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7813 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7814 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
7818 // Binary Operators. 'Tok' is the token for the operator.
7819 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
7820 tok::TokenKind Kind,
7821 Expr *lhs, Expr *rhs) {
7822 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
7823 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7824 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
7826 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7827 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7829 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7832 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
7833 BinaryOperatorKind Opc,
7834 Expr *lhs, Expr *rhs) {
7835 if (getLangOptions().CPlusPlus) {
7836 bool UseBuiltinOperator;
7838 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7839 UseBuiltinOperator = false;
7840 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7841 UseBuiltinOperator = true;
7842 } else {
7843 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7844 !rhs->getType()->isOverloadableType();
7847 if (!UseBuiltinOperator) {
7848 // Find all of the overloaded operators visible from this
7849 // point. We perform both an operator-name lookup from the local
7850 // scope and an argument-dependent lookup based on the types of
7851 // the arguments.
7852 UnresolvedSet<16> Functions;
7853 OverloadedOperatorKind OverOp
7854 = BinaryOperator::getOverloadedOperator(Opc);
7855 if (S && OverOp != OO_None)
7856 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7857 Functions);
7859 // Build the (potentially-overloaded, potentially-dependent)
7860 // binary operation.
7861 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7865 // Build a built-in binary operation.
7866 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
7869 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
7870 UnaryOperatorKind Opc,
7871 Expr *Input) {
7872 ExprValueKind VK = VK_RValue;
7873 ExprObjectKind OK = OK_Ordinary;
7874 QualType resultType;
7875 switch (Opc) {
7876 case UO_PreInc:
7877 case UO_PreDec:
7878 case UO_PostInc:
7879 case UO_PostDec:
7880 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
7881 Opc == UO_PreInc ||
7882 Opc == UO_PostInc,
7883 Opc == UO_PreInc ||
7884 Opc == UO_PreDec);
7885 break;
7886 case UO_AddrOf:
7887 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
7888 break;
7889 case UO_Deref:
7890 DefaultFunctionArrayLvalueConversion(Input);
7891 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
7892 break;
7893 case UO_Plus:
7894 case UO_Minus:
7895 UsualUnaryConversions(Input);
7896 resultType = Input->getType();
7897 if (resultType->isDependentType())
7898 break;
7899 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7900 resultType->isVectorType())
7901 break;
7902 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7903 resultType->isEnumeralType())
7904 break;
7905 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
7906 Opc == UO_Plus &&
7907 resultType->isPointerType())
7908 break;
7909 else if (resultType->isPlaceholderType()) {
7910 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7911 if (PR.isInvalid()) return ExprError();
7912 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
7915 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7916 << resultType << Input->getSourceRange());
7917 case UO_Not: // bitwise complement
7918 UsualUnaryConversions(Input);
7919 resultType = Input->getType();
7920 if (resultType->isDependentType())
7921 break;
7922 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7923 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7924 // C99 does not support '~' for complex conjugation.
7925 Diag(OpLoc, diag::ext_integer_complement_complex)
7926 << resultType << Input->getSourceRange();
7927 else if (resultType->hasIntegerRepresentation())
7928 break;
7929 else if (resultType->isPlaceholderType()) {
7930 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7931 if (PR.isInvalid()) return ExprError();
7932 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
7933 } else {
7934 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7935 << resultType << Input->getSourceRange());
7937 break;
7938 case UO_LNot: // logical negation
7939 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
7940 DefaultFunctionArrayLvalueConversion(Input);
7941 resultType = Input->getType();
7942 if (resultType->isDependentType())
7943 break;
7944 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7945 // ok, fallthrough
7946 } else if (resultType->isPlaceholderType()) {
7947 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7948 if (PR.isInvalid()) return ExprError();
7949 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
7950 } else {
7951 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7952 << resultType << Input->getSourceRange());
7955 // LNot always has type int. C99 6.5.3.3p5.
7956 // In C++, it's bool. C++ 5.3.1p8
7957 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
7958 break;
7959 case UO_Real:
7960 case UO_Imag:
7961 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
7962 // _Real and _Imag map ordinary l-values into ordinary l-values.
7963 if (Input->getValueKind() != VK_RValue &&
7964 Input->getObjectKind() == OK_Ordinary)
7965 VK = Input->getValueKind();
7966 break;
7967 case UO_Extension:
7968 resultType = Input->getType();
7969 VK = Input->getValueKind();
7970 OK = Input->getObjectKind();
7971 break;
7973 if (resultType.isNull())
7974 return ExprError();
7976 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7977 VK, OK, OpLoc));
7980 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
7981 UnaryOperatorKind Opc,
7982 Expr *Input) {
7983 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
7984 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
7985 // Find all of the overloaded operators visible from this
7986 // point. We perform both an operator-name lookup from the local
7987 // scope and an argument-dependent lookup based on the types of
7988 // the arguments.
7989 UnresolvedSet<16> Functions;
7990 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
7991 if (S && OverOp != OO_None)
7992 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7993 Functions);
7995 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
7998 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8001 // Unary Operators. 'Tok' is the token for the operator.
8002 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8003 tok::TokenKind Op, Expr *Input) {
8004 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8007 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8008 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
8009 SourceLocation LabLoc,
8010 IdentifierInfo *LabelII) {
8011 // Look up the record for this label identifier.
8012 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
8014 // If we haven't seen this label yet, create a forward reference. It
8015 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
8016 if (LabelDecl == 0)
8017 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
8019 LabelDecl->setUsed();
8020 // Create the AST node. The address of a label always has type 'void*'.
8021 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8022 Context.getPointerType(Context.VoidTy)));
8025 ExprResult
8026 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8027 SourceLocation RPLoc) { // "({..})"
8028 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8029 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8031 bool isFileScope
8032 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8033 if (isFileScope)
8034 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8036 // FIXME: there are a variety of strange constraints to enforce here, for
8037 // example, it is not possible to goto into a stmt expression apparently.
8038 // More semantic analysis is needed.
8040 // If there are sub stmts in the compound stmt, take the type of the last one
8041 // as the type of the stmtexpr.
8042 QualType Ty = Context.VoidTy;
8043 bool StmtExprMayBindToTemp = false;
8044 if (!Compound->body_empty()) {
8045 Stmt *LastStmt = Compound->body_back();
8046 LabelStmt *LastLabelStmt = 0;
8047 // If LastStmt is a label, skip down through into the body.
8048 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8049 LastLabelStmt = Label;
8050 LastStmt = Label->getSubStmt();
8052 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
8053 // Do function/array conversion on the last expression, but not
8054 // lvalue-to-rvalue. However, initialize an unqualified type.
8055 DefaultFunctionArrayConversion(LastExpr);
8056 Ty = LastExpr->getType().getUnqualifiedType();
8058 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8059 ExprResult Res = PerformCopyInitialization(
8060 InitializedEntity::InitializeResult(LPLoc,
8062 false),
8063 SourceLocation(),
8064 Owned(LastExpr));
8065 if (Res.isInvalid())
8066 return ExprError();
8067 if ((LastExpr = Res.takeAs<Expr>())) {
8068 if (!LastLabelStmt)
8069 Compound->setLastStmt(LastExpr);
8070 else
8071 LastLabelStmt->setSubStmt(LastExpr);
8072 StmtExprMayBindToTemp = true;
8078 // FIXME: Check that expression type is complete/non-abstract; statement
8079 // expressions are not lvalues.
8080 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8081 if (StmtExprMayBindToTemp)
8082 return MaybeBindToTemporary(ResStmtExpr);
8083 return Owned(ResStmtExpr);
8086 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8087 TypeSourceInfo *TInfo,
8088 OffsetOfComponent *CompPtr,
8089 unsigned NumComponents,
8090 SourceLocation RParenLoc) {
8091 QualType ArgTy = TInfo->getType();
8092 bool Dependent = ArgTy->isDependentType();
8093 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8095 // We must have at least one component that refers to the type, and the first
8096 // one is known to be a field designator. Verify that the ArgTy represents
8097 // a struct/union/class.
8098 if (!Dependent && !ArgTy->isRecordType())
8099 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8100 << ArgTy << TypeRange);
8102 // Type must be complete per C99 7.17p3 because a declaring a variable
8103 // with an incomplete type would be ill-formed.
8104 if (!Dependent
8105 && RequireCompleteType(BuiltinLoc, ArgTy,
8106 PDiag(diag::err_offsetof_incomplete_type)
8107 << TypeRange))
8108 return ExprError();
8110 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8111 // GCC extension, diagnose them.
8112 // FIXME: This diagnostic isn't actually visible because the location is in
8113 // a system header!
8114 if (NumComponents != 1)
8115 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8116 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8118 bool DidWarnAboutNonPOD = false;
8119 QualType CurrentType = ArgTy;
8120 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8121 llvm::SmallVector<OffsetOfNode, 4> Comps;
8122 llvm::SmallVector<Expr*, 4> Exprs;
8123 for (unsigned i = 0; i != NumComponents; ++i) {
8124 const OffsetOfComponent &OC = CompPtr[i];
8125 if (OC.isBrackets) {
8126 // Offset of an array sub-field. TODO: Should we allow vector elements?
8127 if (!CurrentType->isDependentType()) {
8128 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8129 if(!AT)
8130 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8131 << CurrentType);
8132 CurrentType = AT->getElementType();
8133 } else
8134 CurrentType = Context.DependentTy;
8136 // The expression must be an integral expression.
8137 // FIXME: An integral constant expression?
8138 Expr *Idx = static_cast<Expr*>(OC.U.E);
8139 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8140 !Idx->getType()->isIntegerType())
8141 return ExprError(Diag(Idx->getLocStart(),
8142 diag::err_typecheck_subscript_not_integer)
8143 << Idx->getSourceRange());
8145 // Record this array index.
8146 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8147 Exprs.push_back(Idx);
8148 continue;
8151 // Offset of a field.
8152 if (CurrentType->isDependentType()) {
8153 // We have the offset of a field, but we can't look into the dependent
8154 // type. Just record the identifier of the field.
8155 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8156 CurrentType = Context.DependentTy;
8157 continue;
8160 // We need to have a complete type to look into.
8161 if (RequireCompleteType(OC.LocStart, CurrentType,
8162 diag::err_offsetof_incomplete_type))
8163 return ExprError();
8165 // Look for the designated field.
8166 const RecordType *RC = CurrentType->getAs<RecordType>();
8167 if (!RC)
8168 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8169 << CurrentType);
8170 RecordDecl *RD = RC->getDecl();
8172 // C++ [lib.support.types]p5:
8173 // The macro offsetof accepts a restricted set of type arguments in this
8174 // International Standard. type shall be a POD structure or a POD union
8175 // (clause 9).
8176 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8177 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8178 DiagRuntimeBehavior(BuiltinLoc,
8179 PDiag(diag::warn_offsetof_non_pod_type)
8180 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8181 << CurrentType))
8182 DidWarnAboutNonPOD = true;
8185 // Look for the field.
8186 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8187 LookupQualifiedName(R, RD);
8188 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
8189 IndirectFieldDecl *IndirectMemberDecl = 0;
8190 if (!MemberDecl) {
8191 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
8192 MemberDecl = IndirectMemberDecl->getAnonField();
8195 if (!MemberDecl)
8196 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8197 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8198 OC.LocEnd));
8200 // C99 7.17p3:
8201 // (If the specified member is a bit-field, the behavior is undefined.)
8203 // We diagnose this as an error.
8204 if (MemberDecl->getBitWidth()) {
8205 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8206 << MemberDecl->getDeclName()
8207 << SourceRange(BuiltinLoc, RParenLoc);
8208 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8209 return ExprError();
8212 RecordDecl *Parent = MemberDecl->getParent();
8213 if (IndirectMemberDecl)
8214 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
8216 // If the member was found in a base class, introduce OffsetOfNodes for
8217 // the base class indirections.
8218 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8219 /*DetectVirtual=*/false);
8220 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
8221 CXXBasePath &Path = Paths.front();
8222 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8223 B != BEnd; ++B)
8224 Comps.push_back(OffsetOfNode(B->Base));
8227 if (IndirectMemberDecl) {
8228 for (IndirectFieldDecl::chain_iterator FI =
8229 IndirectMemberDecl->chain_begin(),
8230 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8231 assert(isa<FieldDecl>(*FI));
8232 Comps.push_back(OffsetOfNode(OC.LocStart,
8233 cast<FieldDecl>(*FI), OC.LocEnd));
8235 } else
8236 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
8238 CurrentType = MemberDecl->getType().getNonReferenceType();
8241 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8242 TInfo, Comps.data(), Comps.size(),
8243 Exprs.data(), Exprs.size(), RParenLoc));
8246 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
8247 SourceLocation BuiltinLoc,
8248 SourceLocation TypeLoc,
8249 ParsedType argty,
8250 OffsetOfComponent *CompPtr,
8251 unsigned NumComponents,
8252 SourceLocation RPLoc) {
8254 TypeSourceInfo *ArgTInfo;
8255 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8256 if (ArgTy.isNull())
8257 return ExprError();
8259 if (!ArgTInfo)
8260 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8262 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8263 RPLoc);
8267 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
8268 Expr *CondExpr,
8269 Expr *LHSExpr, Expr *RHSExpr,
8270 SourceLocation RPLoc) {
8271 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8273 ExprValueKind VK = VK_RValue;
8274 ExprObjectKind OK = OK_Ordinary;
8275 QualType resType;
8276 bool ValueDependent = false;
8277 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
8278 resType = Context.DependentTy;
8279 ValueDependent = true;
8280 } else {
8281 // The conditional expression is required to be a constant expression.
8282 llvm::APSInt condEval(32);
8283 SourceLocation ExpLoc;
8284 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
8285 return ExprError(Diag(ExpLoc,
8286 diag::err_typecheck_choose_expr_requires_constant)
8287 << CondExpr->getSourceRange());
8289 // If the condition is > zero, then the AST type is the same as the LSHExpr.
8290 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8292 resType = ActiveExpr->getType();
8293 ValueDependent = ActiveExpr->isValueDependent();
8294 VK = ActiveExpr->getValueKind();
8295 OK = ActiveExpr->getObjectKind();
8298 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
8299 resType, VK, OK, RPLoc,
8300 resType->isDependentType(),
8301 ValueDependent));
8304 //===----------------------------------------------------------------------===//
8305 // Clang Extensions.
8306 //===----------------------------------------------------------------------===//
8308 /// ActOnBlockStart - This callback is invoked when a block literal is started.
8309 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
8310 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8311 PushBlockScope(BlockScope, Block);
8312 CurContext->addDecl(Block);
8313 if (BlockScope)
8314 PushDeclContext(BlockScope, Block);
8315 else
8316 CurContext = Block;
8319 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
8320 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
8321 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
8322 BlockScopeInfo *CurBlock = getCurBlock();
8324 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
8325 QualType T = Sig->getType();
8327 // GetTypeForDeclarator always produces a function type for a block
8328 // literal signature. Furthermore, it is always a FunctionProtoType
8329 // unless the function was written with a typedef.
8330 assert(T->isFunctionType() &&
8331 "GetTypeForDeclarator made a non-function block signature");
8333 // Look for an explicit signature in that function type.
8334 FunctionProtoTypeLoc ExplicitSignature;
8336 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8337 if (isa<FunctionProtoTypeLoc>(tmp)) {
8338 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8340 // Check whether that explicit signature was synthesized by
8341 // GetTypeForDeclarator. If so, don't save that as part of the
8342 // written signature.
8343 if (ExplicitSignature.getLParenLoc() ==
8344 ExplicitSignature.getRParenLoc()) {
8345 // This would be much cheaper if we stored TypeLocs instead of
8346 // TypeSourceInfos.
8347 TypeLoc Result = ExplicitSignature.getResultLoc();
8348 unsigned Size = Result.getFullDataSize();
8349 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8350 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8352 ExplicitSignature = FunctionProtoTypeLoc();
8356 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8357 CurBlock->FunctionType = T;
8359 const FunctionType *Fn = T->getAs<FunctionType>();
8360 QualType RetTy = Fn->getResultType();
8361 bool isVariadic =
8362 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8364 CurBlock->TheDecl->setIsVariadic(isVariadic);
8366 // Don't allow returning a objc interface by value.
8367 if (RetTy->isObjCObjectType()) {
8368 Diag(ParamInfo.getSourceRange().getBegin(),
8369 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8370 return;
8373 // Context.DependentTy is used as a placeholder for a missing block
8374 // return type. TODO: what should we do with declarators like:
8375 // ^ * { ... }
8376 // If the answer is "apply template argument deduction"....
8377 if (RetTy != Context.DependentTy)
8378 CurBlock->ReturnType = RetTy;
8380 // Push block parameters from the declarator if we had them.
8381 llvm::SmallVector<ParmVarDecl*, 8> Params;
8382 if (ExplicitSignature) {
8383 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8384 ParmVarDecl *Param = ExplicitSignature.getArg(I);
8385 if (Param->getIdentifier() == 0 &&
8386 !Param->isImplicit() &&
8387 !Param->isInvalidDecl() &&
8388 !getLangOptions().CPlusPlus)
8389 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8390 Params.push_back(Param);
8393 // Fake up parameter variables if we have a typedef, like
8394 // ^ fntype { ... }
8395 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8396 for (FunctionProtoType::arg_type_iterator
8397 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8398 ParmVarDecl *Param =
8399 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8400 ParamInfo.getSourceRange().getBegin(),
8401 *I);
8402 Params.push_back(Param);
8406 // Set the parameters on the block decl.
8407 if (!Params.empty()) {
8408 CurBlock->TheDecl->setParams(Params.data(), Params.size());
8409 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8410 CurBlock->TheDecl->param_end(),
8411 /*CheckParameterNames=*/false);
8414 // Finally we can process decl attributes.
8415 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
8417 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
8418 Diag(ParamInfo.getAttributes()->getLoc(),
8419 diag::warn_attribute_sentinel_not_variadic) << 1;
8420 // FIXME: remove the attribute.
8423 // Put the parameter variables in scope. We can bail out immediately
8424 // if we don't have any.
8425 if (Params.empty())
8426 return;
8428 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
8429 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8430 (*AI)->setOwningFunction(CurBlock->TheDecl);
8432 // If this has an identifier, add it to the scope stack.
8433 if ((*AI)->getIdentifier()) {
8434 CheckShadow(CurBlock->TheScope, *AI);
8436 PushOnScopeChains(*AI, CurBlock->TheScope);
8441 /// ActOnBlockError - If there is an error parsing a block, this callback
8442 /// is invoked to pop the information about the block from the action impl.
8443 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
8444 // Pop off CurBlock, handle nested blocks.
8445 PopDeclContext();
8446 PopFunctionOrBlockScope();
8449 /// ActOnBlockStmtExpr - This is called when the body of a block statement
8450 /// literal was successfully completed. ^(int x){...}
8451 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
8452 Stmt *Body, Scope *CurScope) {
8453 // If blocks are disabled, emit an error.
8454 if (!LangOpts.Blocks)
8455 Diag(CaretLoc, diag::err_blocks_disable);
8457 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
8459 PopDeclContext();
8461 QualType RetTy = Context.VoidTy;
8462 if (!BSI->ReturnType.isNull())
8463 RetTy = BSI->ReturnType;
8465 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
8466 QualType BlockTy;
8468 // If the user wrote a function type in some form, try to use that.
8469 if (!BSI->FunctionType.isNull()) {
8470 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8472 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8473 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8475 // Turn protoless block types into nullary block types.
8476 if (isa<FunctionNoProtoType>(FTy)) {
8477 FunctionProtoType::ExtProtoInfo EPI;
8478 EPI.ExtInfo = Ext;
8479 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8481 // Otherwise, if we don't need to change anything about the function type,
8482 // preserve its sugar structure.
8483 } else if (FTy->getResultType() == RetTy &&
8484 (!NoReturn || FTy->getNoReturnAttr())) {
8485 BlockTy = BSI->FunctionType;
8487 // Otherwise, make the minimal modifications to the function type.
8488 } else {
8489 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8490 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8491 EPI.TypeQuals = 0; // FIXME: silently?
8492 EPI.ExtInfo = Ext;
8493 BlockTy = Context.getFunctionType(RetTy,
8494 FPT->arg_type_begin(),
8495 FPT->getNumArgs(),
8496 EPI);
8499 // If we don't have a function type, just build one from nothing.
8500 } else {
8501 FunctionProtoType::ExtProtoInfo EPI;
8502 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8503 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8506 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8507 BSI->TheDecl->param_end());
8508 BlockTy = Context.getBlockPointerType(BlockTy);
8510 // If needed, diagnose invalid gotos and switches in the block.
8511 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
8512 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
8514 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
8516 bool Good = true;
8517 // Check goto/label use.
8518 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8519 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8520 LabelStmt *L = I->second;
8522 // Verify that we have no forward references left. If so, there was a goto
8523 // or address of a label taken, but no definition of it.
8524 if (L->getSubStmt() != 0) {
8525 if (!L->isUsed())
8526 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
8527 continue;
8530 // Emit error.
8531 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8532 Good = false;
8534 if (!Good) {
8535 PopFunctionOrBlockScope();
8536 return ExprError();
8539 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8540 BSI->hasBlockDeclRefExprs);
8542 // Issue any analysis-based warnings.
8543 const sema::AnalysisBasedWarnings::Policy &WP =
8544 AnalysisWarnings.getDefaultPolicy();
8545 AnalysisWarnings.IssueWarnings(WP, Result);
8547 PopFunctionOrBlockScope();
8548 return Owned(Result);
8551 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
8552 Expr *expr, ParsedType type,
8553 SourceLocation RPLoc) {
8554 TypeSourceInfo *TInfo;
8555 GetTypeFromParser(type, &TInfo);
8556 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
8559 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
8560 Expr *E, TypeSourceInfo *TInfo,
8561 SourceLocation RPLoc) {
8562 Expr *OrigExpr = E;
8564 // Get the va_list type
8565 QualType VaListType = Context.getBuiltinVaListType();
8566 if (VaListType->isArrayType()) {
8567 // Deal with implicit array decay; for example, on x86-64,
8568 // va_list is an array, but it's supposed to decay to
8569 // a pointer for va_arg.
8570 VaListType = Context.getArrayDecayedType(VaListType);
8571 // Make sure the input expression also decays appropriately.
8572 UsualUnaryConversions(E);
8573 } else {
8574 // Otherwise, the va_list argument must be an l-value because
8575 // it is modified by va_arg.
8576 if (!E->isTypeDependent() &&
8577 CheckForModifiableLvalue(E, BuiltinLoc, *this))
8578 return ExprError();
8581 if (!E->isTypeDependent() &&
8582 !Context.hasSameType(VaListType, E->getType())) {
8583 return ExprError(Diag(E->getLocStart(),
8584 diag::err_first_argument_to_va_arg_not_of_type_va_list)
8585 << OrigExpr->getType() << E->getSourceRange());
8588 // FIXME: Check that type is complete/non-abstract
8589 // FIXME: Warn if a non-POD type is passed in.
8591 QualType T = TInfo->getType().getNonLValueExprType(Context);
8592 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
8595 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
8596 // The type of __null will be int or long, depending on the size of
8597 // pointers on the target.
8598 QualType Ty;
8599 unsigned pw = Context.Target.getPointerWidth(0);
8600 if (pw == Context.Target.getIntWidth())
8601 Ty = Context.IntTy;
8602 else if (pw == Context.Target.getLongWidth())
8603 Ty = Context.LongTy;
8604 else if (pw == Context.Target.getLongLongWidth())
8605 Ty = Context.LongLongTy;
8606 else {
8607 assert(!"I don't know size of pointer!");
8608 Ty = Context.IntTy;
8611 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
8614 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
8615 Expr *SrcExpr, FixItHint &Hint) {
8616 if (!SemaRef.getLangOptions().ObjC1)
8617 return;
8619 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8620 if (!PT)
8621 return;
8623 // Check if the destination is of type 'id'.
8624 if (!PT->isObjCIdType()) {
8625 // Check if the destination is the 'NSString' interface.
8626 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8627 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8628 return;
8631 // Strip off any parens and casts.
8632 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8633 if (!SL || SL->isWide())
8634 return;
8636 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
8639 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8640 SourceLocation Loc,
8641 QualType DstType, QualType SrcType,
8642 Expr *SrcExpr, AssignmentAction Action,
8643 bool *Complained) {
8644 if (Complained)
8645 *Complained = false;
8647 // Decode the result (notice that AST's are still created for extensions).
8648 bool isInvalid = false;
8649 unsigned DiagKind;
8650 FixItHint Hint;
8652 switch (ConvTy) {
8653 default: assert(0 && "Unknown conversion type");
8654 case Compatible: return false;
8655 case PointerToInt:
8656 DiagKind = diag::ext_typecheck_convert_pointer_int;
8657 break;
8658 case IntToPointer:
8659 DiagKind = diag::ext_typecheck_convert_int_pointer;
8660 break;
8661 case IncompatiblePointer:
8662 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
8663 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8664 break;
8665 case IncompatiblePointerSign:
8666 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8667 break;
8668 case FunctionVoidPointer:
8669 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8670 break;
8671 case CompatiblePointerDiscardsQualifiers:
8672 // If the qualifiers lost were because we were applying the
8673 // (deprecated) C++ conversion from a string literal to a char*
8674 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8675 // Ideally, this check would be performed in
8676 // CheckPointerTypesForAssignment. However, that would require a
8677 // bit of refactoring (so that the second argument is an
8678 // expression, rather than a type), which should be done as part
8679 // of a larger effort to fix CheckPointerTypesForAssignment for
8680 // C++ semantics.
8681 if (getLangOptions().CPlusPlus &&
8682 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8683 return false;
8684 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8685 break;
8686 case IncompatibleNestedPointerQualifiers:
8687 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
8688 break;
8689 case IntToBlockPointer:
8690 DiagKind = diag::err_int_to_block_pointer;
8691 break;
8692 case IncompatibleBlockPointer:
8693 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
8694 break;
8695 case IncompatibleObjCQualifiedId:
8696 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
8697 // it can give a more specific diagnostic.
8698 DiagKind = diag::warn_incompatible_qualified_id;
8699 break;
8700 case IncompatibleVectors:
8701 DiagKind = diag::warn_incompatible_vectors;
8702 break;
8703 case Incompatible:
8704 DiagKind = diag::err_typecheck_convert_incompatible;
8705 isInvalid = true;
8706 break;
8709 QualType FirstType, SecondType;
8710 switch (Action) {
8711 case AA_Assigning:
8712 case AA_Initializing:
8713 // The destination type comes first.
8714 FirstType = DstType;
8715 SecondType = SrcType;
8716 break;
8718 case AA_Returning:
8719 case AA_Passing:
8720 case AA_Converting:
8721 case AA_Sending:
8722 case AA_Casting:
8723 // The source type comes first.
8724 FirstType = SrcType;
8725 SecondType = DstType;
8726 break;
8729 Diag(Loc, DiagKind) << FirstType << SecondType << Action
8730 << SrcExpr->getSourceRange() << Hint;
8731 if (Complained)
8732 *Complained = true;
8733 return isInvalid;
8736 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
8737 llvm::APSInt ICEResult;
8738 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8739 if (Result)
8740 *Result = ICEResult;
8741 return false;
8744 Expr::EvalResult EvalResult;
8746 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
8747 EvalResult.HasSideEffects) {
8748 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8750 if (EvalResult.Diag) {
8751 // We only show the note if it's not the usual "invalid subexpression"
8752 // or if it's actually in a subexpression.
8753 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8754 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8755 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8758 return true;
8761 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8762 E->getSourceRange();
8764 if (EvalResult.Diag &&
8765 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8766 != Diagnostic::Ignored)
8767 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8769 if (Result)
8770 *Result = EvalResult.Val.getInt();
8771 return false;
8774 void
8775 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
8776 ExprEvalContexts.push_back(
8777 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
8780 void
8781 Sema::PopExpressionEvaluationContext() {
8782 // Pop the current expression evaluation context off the stack.
8783 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8784 ExprEvalContexts.pop_back();
8786 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8787 if (Rec.PotentiallyReferenced) {
8788 // Mark any remaining declarations in the current position of the stack
8789 // as "referenced". If they were not meant to be referenced, semantic
8790 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
8791 for (PotentiallyReferencedDecls::iterator
8792 I = Rec.PotentiallyReferenced->begin(),
8793 IEnd = Rec.PotentiallyReferenced->end();
8794 I != IEnd; ++I)
8795 MarkDeclarationReferenced(I->first, I->second);
8798 if (Rec.PotentiallyDiagnosed) {
8799 // Emit any pending diagnostics.
8800 for (PotentiallyEmittedDiagnostics::iterator
8801 I = Rec.PotentiallyDiagnosed->begin(),
8802 IEnd = Rec.PotentiallyDiagnosed->end();
8803 I != IEnd; ++I)
8804 Diag(I->first, I->second);
8808 // When are coming out of an unevaluated context, clear out any
8809 // temporaries that we may have created as part of the evaluation of
8810 // the expression in that context: they aren't relevant because they
8811 // will never be constructed.
8812 if (Rec.Context == Unevaluated &&
8813 ExprTemporaries.size() > Rec.NumTemporaries)
8814 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8815 ExprTemporaries.end());
8817 // Destroy the popped expression evaluation record.
8818 Rec.Destroy();
8821 /// \brief Note that the given declaration was referenced in the source code.
8823 /// This routine should be invoke whenever a given declaration is referenced
8824 /// in the source code, and where that reference occurred. If this declaration
8825 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8826 /// C99 6.9p3), then the declaration will be marked as used.
8828 /// \param Loc the location where the declaration was referenced.
8830 /// \param D the declaration that has been referenced by the source code.
8831 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8832 assert(D && "No declaration?");
8834 if (D->isUsed(false))
8835 return;
8837 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8838 // template or not. The reason for this is that unevaluated expressions
8839 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8840 // -Wunused-parameters)
8841 if (isa<ParmVarDecl>(D) ||
8842 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
8843 D->setUsed();
8844 return;
8847 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8848 return;
8850 // Do not mark anything as "used" within a dependent context; wait for
8851 // an instantiation.
8852 if (CurContext->isDependentContext())
8853 return;
8855 switch (ExprEvalContexts.back().Context) {
8856 case Unevaluated:
8857 // We are in an expression that is not potentially evaluated; do nothing.
8858 return;
8860 case PotentiallyEvaluated:
8861 // We are in a potentially-evaluated expression, so this declaration is
8862 // "used"; handle this below.
8863 break;
8865 case PotentiallyPotentiallyEvaluated:
8866 // We are in an expression that may be potentially evaluated; queue this
8867 // declaration reference until we know whether the expression is
8868 // potentially evaluated.
8869 ExprEvalContexts.back().addReferencedDecl(Loc, D);
8870 return;
8872 case PotentiallyEvaluatedIfUsed:
8873 // Referenced declarations will only be used if the construct in the
8874 // containing expression is used.
8875 return;
8878 // Note that this declaration has been used.
8879 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
8880 unsigned TypeQuals;
8881 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
8882 if (Constructor->getParent()->hasTrivialConstructor())
8883 return;
8884 if (!Constructor->isUsed(false))
8885 DefineImplicitDefaultConstructor(Loc, Constructor);
8886 } else if (Constructor->isImplicit() &&
8887 Constructor->isCopyConstructor(TypeQuals)) {
8888 if (!Constructor->isUsed(false))
8889 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8892 MarkVTableUsed(Loc, Constructor->getParent());
8893 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
8894 if (Destructor->isImplicit() && !Destructor->isUsed(false))
8895 DefineImplicitDestructor(Loc, Destructor);
8896 if (Destructor->isVirtual())
8897 MarkVTableUsed(Loc, Destructor->getParent());
8898 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8899 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8900 MethodDecl->getOverloadedOperator() == OO_Equal) {
8901 if (!MethodDecl->isUsed(false))
8902 DefineImplicitCopyAssignment(Loc, MethodDecl);
8903 } else if (MethodDecl->isVirtual())
8904 MarkVTableUsed(Loc, MethodDecl->getParent());
8906 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
8907 // Implicit instantiation of function templates and member functions of
8908 // class templates.
8909 if (Function->isImplicitlyInstantiable()) {
8910 bool AlreadyInstantiated = false;
8911 if (FunctionTemplateSpecializationInfo *SpecInfo
8912 = Function->getTemplateSpecializationInfo()) {
8913 if (SpecInfo->getPointOfInstantiation().isInvalid())
8914 SpecInfo->setPointOfInstantiation(Loc);
8915 else if (SpecInfo->getTemplateSpecializationKind()
8916 == TSK_ImplicitInstantiation)
8917 AlreadyInstantiated = true;
8918 } else if (MemberSpecializationInfo *MSInfo
8919 = Function->getMemberSpecializationInfo()) {
8920 if (MSInfo->getPointOfInstantiation().isInvalid())
8921 MSInfo->setPointOfInstantiation(Loc);
8922 else if (MSInfo->getTemplateSpecializationKind()
8923 == TSK_ImplicitInstantiation)
8924 AlreadyInstantiated = true;
8927 if (!AlreadyInstantiated) {
8928 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8929 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8930 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8931 Loc));
8932 else
8933 PendingInstantiations.push_back(std::make_pair(Function, Loc));
8935 } else // Walk redefinitions, as some of them may be instantiable.
8936 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8937 e(Function->redecls_end()); i != e; ++i) {
8938 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
8939 MarkDeclarationReferenced(Loc, *i);
8942 // FIXME: keep track of references to static functions
8944 // Recursive functions should be marked when used from another function.
8945 if (CurContext != Function)
8946 Function->setUsed(true);
8948 return;
8951 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
8952 // Implicit instantiation of static data members of class templates.
8953 if (Var->isStaticDataMember() &&
8954 Var->getInstantiatedFromStaticDataMember()) {
8955 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8956 assert(MSInfo && "Missing member specialization information?");
8957 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8958 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8959 MSInfo->setPointOfInstantiation(Loc);
8960 PendingInstantiations.push_back(std::make_pair(Var, Loc));
8964 // FIXME: keep track of references to static data?
8966 D->setUsed(true);
8967 return;
8971 namespace {
8972 // Mark all of the declarations referenced
8973 // FIXME: Not fully implemented yet! We need to have a better understanding
8974 // of when we're entering
8975 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8976 Sema &S;
8977 SourceLocation Loc;
8979 public:
8980 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
8982 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
8984 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8985 bool TraverseRecordType(RecordType *T);
8989 bool MarkReferencedDecls::TraverseTemplateArgument(
8990 const TemplateArgument &Arg) {
8991 if (Arg.getKind() == TemplateArgument::Declaration) {
8992 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8995 return Inherited::TraverseTemplateArgument(Arg);
8998 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
8999 if (ClassTemplateSpecializationDecl *Spec
9000 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9001 const TemplateArgumentList &Args = Spec->getTemplateArgs();
9002 return TraverseTemplateArguments(Args.data(), Args.size());
9005 return true;
9008 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9009 MarkReferencedDecls Marker(*this, Loc);
9010 Marker.TraverseType(Context.getCanonicalType(T));
9013 namespace {
9014 /// \brief Helper class that marks all of the declarations referenced by
9015 /// potentially-evaluated subexpressions as "referenced".
9016 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9017 Sema &S;
9019 public:
9020 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9022 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9024 void VisitDeclRefExpr(DeclRefExpr *E) {
9025 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9028 void VisitMemberExpr(MemberExpr *E) {
9029 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
9030 Inherited::VisitMemberExpr(E);
9033 void VisitCXXNewExpr(CXXNewExpr *E) {
9034 if (E->getConstructor())
9035 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9036 if (E->getOperatorNew())
9037 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9038 if (E->getOperatorDelete())
9039 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9040 Inherited::VisitCXXNewExpr(E);
9043 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9044 if (E->getOperatorDelete())
9045 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9046 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9047 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9048 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9049 S.MarkDeclarationReferenced(E->getLocStart(),
9050 S.LookupDestructor(Record));
9053 Inherited::VisitCXXDeleteExpr(E);
9056 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9057 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9058 Inherited::VisitCXXConstructExpr(E);
9061 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9062 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9065 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9066 Visit(E->getExpr());
9071 /// \brief Mark any declarations that appear within this expression or any
9072 /// potentially-evaluated subexpressions as "referenced".
9073 void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9074 EvaluatedExprMarker(*this).Visit(E);
9077 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
9078 /// of the program being compiled.
9080 /// This routine emits the given diagnostic when the code currently being
9081 /// type-checked is "potentially evaluated", meaning that there is a
9082 /// possibility that the code will actually be executable. Code in sizeof()
9083 /// expressions, code used only during overload resolution, etc., are not
9084 /// potentially evaluated. This routine will suppress such diagnostics or,
9085 /// in the absolutely nutty case of potentially potentially evaluated
9086 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
9087 /// later.
9089 /// This routine should be used for all diagnostics that describe the run-time
9090 /// behavior of a program, such as passing a non-POD value through an ellipsis.
9091 /// Failure to do so will likely result in spurious diagnostics or failures
9092 /// during overload resolution or within sizeof/alignof/typeof/typeid.
9093 bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
9094 const PartialDiagnostic &PD) {
9095 switch (ExprEvalContexts.back().Context ) {
9096 case Unevaluated:
9097 // The argument will never be evaluated, so don't complain.
9098 break;
9100 case PotentiallyEvaluated:
9101 case PotentiallyEvaluatedIfUsed:
9102 Diag(Loc, PD);
9103 return true;
9105 case PotentiallyPotentiallyEvaluated:
9106 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9107 break;
9110 return false;
9113 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9114 CallExpr *CE, FunctionDecl *FD) {
9115 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9116 return false;
9118 PartialDiagnostic Note =
9119 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9120 << FD->getDeclName() : PDiag();
9121 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
9123 if (RequireCompleteType(Loc, ReturnType,
9124 FD ?
9125 PDiag(diag::err_call_function_incomplete_return)
9126 << CE->getSourceRange() << FD->getDeclName() :
9127 PDiag(diag::err_call_incomplete_return)
9128 << CE->getSourceRange(),
9129 std::make_pair(NoteLoc, Note)))
9130 return true;
9132 return false;
9135 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
9136 // will prevent this condition from triggering, which is what we want.
9137 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9138 SourceLocation Loc;
9140 unsigned diagnostic = diag::warn_condition_is_assignment;
9141 bool IsOrAssign = false;
9143 if (isa<BinaryOperator>(E)) {
9144 BinaryOperator *Op = cast<BinaryOperator>(E);
9145 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
9146 return;
9148 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9150 // Greylist some idioms by putting them into a warning subcategory.
9151 if (ObjCMessageExpr *ME
9152 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9153 Selector Sel = ME->getSelector();
9155 // self = [<foo> init...]
9156 if (isSelfExpr(Op->getLHS())
9157 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9158 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9160 // <foo> = [<bar> nextObject]
9161 else if (Sel.isUnarySelector() &&
9162 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9163 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9166 Loc = Op->getOperatorLoc();
9167 } else if (isa<CXXOperatorCallExpr>(E)) {
9168 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9169 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
9170 return;
9172 IsOrAssign = Op->getOperator() == OO_PipeEqual;
9173 Loc = Op->getOperatorLoc();
9174 } else {
9175 // Not an assignment.
9176 return;
9179 SourceLocation Open = E->getSourceRange().getBegin();
9180 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9182 Diag(Loc, diagnostic) << E->getSourceRange();
9184 if (IsOrAssign)
9185 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9186 << FixItHint::CreateReplacement(Loc, "!=");
9187 else
9188 Diag(Loc, diag::note_condition_assign_to_comparison)
9189 << FixItHint::CreateReplacement(Loc, "==");
9191 Diag(Loc, diag::note_condition_assign_silence)
9192 << FixItHint::CreateInsertion(Open, "(")
9193 << FixItHint::CreateInsertion(Close, ")");
9196 bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9197 DiagnoseAssignmentAsCondition(E);
9199 if (!E->isTypeDependent()) {
9200 if (E->isBoundMemberFunction(Context))
9201 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9202 << E->getSourceRange();
9204 if (getLangOptions().CPlusPlus)
9205 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9207 DefaultFunctionArrayLvalueConversion(E);
9209 QualType T = E->getType();
9210 if (!T->isScalarType()) // C99 6.8.4.1p1
9211 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9212 << T << E->getSourceRange();
9215 return false;
9218 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9219 Expr *Sub) {
9220 if (!Sub)
9221 return ExprError();
9223 if (CheckBooleanCondition(Sub, Loc))
9224 return ExprError();
9226 return Owned(Sub);
9229 /// Check for operands with placeholder types and complain if found.
9230 /// Returns true if there was an error and no recovery was possible.
9231 ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9232 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9233 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9235 // If this is overload, check for a single overload.
9236 if (BT->getKind() == BuiltinType::Overload) {
9237 if (FunctionDecl *Specialization
9238 = ResolveSingleFunctionTemplateSpecialization(E)) {
9239 // The access doesn't really matter in this case.
9240 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9241 Specialization->getAccess());
9242 E = FixOverloadedFunctionReference(E, Found, Specialization);
9243 if (!E) return ExprError();
9244 return Owned(E);
9247 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
9248 return ExprError();
9251 // Otherwise it's a use of undeduced auto.
9252 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9254 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9255 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9256 << DRE->getDecl() << E->getSourceRange();
9257 return ExprError();