1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements extra semantic analysis beyond what is enforced
11 // by the C type system.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "llvm/ADT/SmallBitVector.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
41 using namespace clang;
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
46 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
47 PP.getLangOpts(), PP.getTargetInfo());
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking. Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
115 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
116 ExprResult TheCallResult(Owned(TheCall));
118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
133 ICEArguments &= ~(1 << ArgNo);
137 case Builtin::BI__builtin___CFStringMakeConstantString:
138 assert(TheCall->getNumArgs() == 1 &&
139 "Wrong # arguments to builtin CFStringMakeConstantString");
140 if (CheckObjCString(TheCall->getArg(0)))
143 case Builtin::BI__builtin_stdarg_start:
144 case Builtin::BI__builtin_va_start:
145 if (SemaBuiltinVAStart(TheCall))
148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
154 if (SemaBuiltinUnorderedCompare(TheCall))
157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
166 if (SemaBuiltinFPClassification(TheCall, 1))
169 case Builtin::BI__builtin_shufflevector:
170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
173 case Builtin::BI__builtin_prefetch:
174 if (SemaBuiltinPrefetch(TheCall))
177 case Builtin::BI__builtin_object_size:
178 if (SemaBuiltinObjectSize(TheCall))
181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
190 case Builtin::BI__builtin_constant_p:
191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
194 case Builtin::BI__sync_fetch_and_add:
195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
200 case Builtin::BI__sync_fetch_and_sub:
201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
206 case Builtin::BI__sync_fetch_and_or:
207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
212 case Builtin::BI__sync_fetch_and_and:
213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
218 case Builtin::BI__sync_fetch_and_xor:
219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
224 case Builtin::BI__sync_add_and_fetch:
225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
230 case Builtin::BI__sync_sub_and_fetch:
231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
236 case Builtin::BI__sync_and_and_fetch:
237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
242 case Builtin::BI__sync_or_and_fetch:
243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
248 case Builtin::BI__sync_xor_and_fetch:
249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
254 case Builtin::BI__sync_val_compare_and_swap:
255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
260 case Builtin::BI__sync_bool_compare_and_swap:
261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
266 case Builtin::BI__sync_lock_test_and_set:
267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
272 case Builtin::BI__sync_lock_release:
273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
278 case Builtin::BI__sync_swap:
279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
284 return SemaBuiltinAtomicOverloaded(TheCallResult);
285 #define BUILTIN(ID, TYPE, ATTRS)
286 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
289 #include "clang/Basic/Builtins.def"
290 case Builtin::BI__builtin_annotation:
291 if (SemaBuiltinAnnotation(*this, TheCall))
294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
303 switch (Context.getTargetInfo().getTriple().getArch()) {
304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
325 return TheCallResult;
328 // Get the valid immediate range for the specified NEON type code.
329 static unsigned RFT(unsigned t, bool shift = false) {
330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
342 case NeonTypeFlags::Poly64:
343 return shift ? 63 : (1 << IsQuad) - 1;
344 case NeonTypeFlags::Float16:
345 assert(!shift && "cannot shift float types!");
346 return (4 << IsQuad) - 1;
347 case NeonTypeFlags::Float32:
348 assert(!shift && "cannot shift float types!");
349 return (2 << IsQuad) - 1;
350 case NeonTypeFlags::Float64:
351 assert(!shift && "cannot shift float types!");
352 return (1 << IsQuad) - 1;
354 llvm_unreachable("Invalid NeonTypeFlag!");
357 /// getNeonEltType - Return the QualType corresponding to the elements of
358 /// the vector type specified by the NeonTypeFlags. This is used to check
359 /// the pointer arguments for Neon load/store intrinsics.
360 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
362 switch (Flags.getEltType()) {
363 case NeonTypeFlags::Int8:
364 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
365 case NeonTypeFlags::Int16:
366 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
367 case NeonTypeFlags::Int32:
368 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
369 case NeonTypeFlags::Int64:
370 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
371 case NeonTypeFlags::Poly8:
372 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
373 case NeonTypeFlags::Poly16:
374 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
375 case NeonTypeFlags::Poly64:
376 return Context.UnsignedLongLongTy;
377 case NeonTypeFlags::Float16:
378 return Context.HalfTy;
379 case NeonTypeFlags::Float32:
380 return Context.FloatTy;
381 case NeonTypeFlags::Float64:
382 return Context.DoubleTy;
384 llvm_unreachable("Invalid NeonTypeFlag!");
387 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
395 bool HasConstPtr = false;
397 #define GET_NEON_AARCH64_OVERLOAD_CHECK
398 #include "clang/Basic/arm_neon.inc"
399 #undef GET_NEON_AARCH64_OVERLOAD_CHECK
402 // For NEON intrinsics which are overloaded on vector element type, validate
403 // the immediate which specifies which variant to emit.
404 unsigned ImmArg = TheCall->getNumArgs() - 1;
406 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
409 TV = Result.getLimitedValue(64);
410 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
411 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
412 << TheCall->getArg(ImmArg)->getSourceRange();
415 if (PtrArgNum >= 0) {
416 // Check that pointer arguments have the specified type.
417 Expr *Arg = TheCall->getArg(PtrArgNum);
418 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
419 Arg = ICE->getSubExpr();
420 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
421 QualType RHSTy = RHS.get()->getType();
422 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true);
424 EltTy = EltTy.withConst();
425 QualType LHSTy = Context.getPointerType(EltTy);
426 AssignConvertType ConvTy;
427 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
430 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
431 RHS.get(), AA_Assigning))
435 // For NEON intrinsics which take an immediate value as part of the
436 // instruction, range check them here.
437 unsigned i = 0, l = 0, u = 0;
441 #define GET_NEON_AARCH64_IMMEDIATE_CHECK
442 #include "clang/Basic/arm_neon.inc"
443 #undef GET_NEON_AARCH64_IMMEDIATE_CHECK
447 // We can't check the value of a dependent argument.
448 if (TheCall->getArg(i)->isTypeDependent() ||
449 TheCall->getArg(i)->isValueDependent())
452 // Check that the immediate argument is actually a constant.
453 if (SemaBuiltinConstantArg(TheCall, i, Result))
456 // Range check against the upper/lower values for this isntruction.
457 unsigned Val = Result.getZExtValue();
458 if (Val < l || Val > (u + l))
459 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460 << l << u + l << TheCall->getArg(i)->getSourceRange();
465 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
466 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
467 BuiltinID == ARM::BI__builtin_arm_strex) &&
468 "unexpected ARM builtin");
469 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
471 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
473 // Ensure that we have the proper number of arguments.
474 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
477 // Inspect the pointer argument of the atomic builtin. This should always be
478 // a pointer type, whose element is an integral scalar or pointer type.
479 // Because it is a pointer type, we don't have to worry about any implicit
481 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
482 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
483 if (PointerArgRes.isInvalid())
485 PointerArg = PointerArgRes.take();
487 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
489 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
490 << PointerArg->getType() << PointerArg->getSourceRange();
494 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
495 // task is to insert the appropriate casts into the AST. First work out just
496 // what the appropriate type is.
497 QualType ValType = pointerType->getPointeeType();
498 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
502 // Issue a warning if the cast is dodgy.
503 CastKind CastNeeded = CK_NoOp;
504 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
505 CastNeeded = CK_BitCast;
506 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
507 << PointerArg->getType()
508 << Context.getPointerType(AddrType)
509 << AA_Passing << PointerArg->getSourceRange();
512 // Finally, do the cast and replace the argument with the corrected version.
513 AddrType = Context.getPointerType(AddrType);
514 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
515 if (PointerArgRes.isInvalid())
517 PointerArg = PointerArgRes.take();
519 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
521 // In general, we allow ints, floats and pointers to be loaded and stored.
522 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
523 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
524 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
525 << PointerArg->getType() << PointerArg->getSourceRange();
529 // But ARM doesn't have instructions to deal with 128-bit versions.
530 if (Context.getTypeSize(ValType) > 64) {
531 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
532 << PointerArg->getType() << PointerArg->getSourceRange();
536 switch (ValType.getObjCLifetime()) {
537 case Qualifiers::OCL_None:
538 case Qualifiers::OCL_ExplicitNone:
542 case Qualifiers::OCL_Weak:
543 case Qualifiers::OCL_Strong:
544 case Qualifiers::OCL_Autoreleasing:
545 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
546 << ValType << PointerArg->getSourceRange();
552 TheCall->setType(ValType);
556 // Initialize the argument to be stored.
557 ExprResult ValArg = TheCall->getArg(0);
558 InitializedEntity Entity = InitializedEntity::InitializeParameter(
559 Context, ValType, /*consume*/ false);
560 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
561 if (ValArg.isInvalid())
563 TheCall->setArg(0, ValArg.get());
565 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
566 // but the custom checker bypasses all default analysis.
567 TheCall->setType(Context.IntTy);
571 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
574 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
575 BuiltinID == ARM::BI__builtin_arm_strex) {
576 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
582 bool HasConstPtr = false;
584 #define GET_NEON_OVERLOAD_CHECK
585 #include "clang/Basic/arm_neon.inc"
586 #undef GET_NEON_OVERLOAD_CHECK
589 // For NEON intrinsics which are overloaded on vector element type, validate
590 // the immediate which specifies which variant to emit.
591 unsigned ImmArg = TheCall->getNumArgs()-1;
593 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
596 TV = Result.getLimitedValue(64);
597 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
598 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
599 << TheCall->getArg(ImmArg)->getSourceRange();
602 if (PtrArgNum >= 0) {
603 // Check that pointer arguments have the specified type.
604 Expr *Arg = TheCall->getArg(PtrArgNum);
605 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
606 Arg = ICE->getSubExpr();
607 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
608 QualType RHSTy = RHS.get()->getType();
609 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false);
611 EltTy = EltTy.withConst();
612 QualType LHSTy = Context.getPointerType(EltTy);
613 AssignConvertType ConvTy;
614 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
617 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
618 RHS.get(), AA_Assigning))
622 // For NEON intrinsics which take an immediate value as part of the
623 // instruction, range check them here.
624 unsigned i = 0, l = 0, u = 0;
626 default: return false;
627 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
628 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
629 case ARM::BI__builtin_arm_vcvtr_f:
630 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
631 case ARM::BI__builtin_arm_dmb:
632 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
633 #define GET_NEON_IMMEDIATE_CHECK
634 #include "clang/Basic/arm_neon.inc"
635 #undef GET_NEON_IMMEDIATE_CHECK
638 // We can't check the value of a dependent argument.
639 if (TheCall->getArg(i)->isTypeDependent() ||
640 TheCall->getArg(i)->isValueDependent())
643 // Check that the immediate argument is actually a constant.
644 if (SemaBuiltinConstantArg(TheCall, i, Result))
647 // Range check against the upper/lower values for this isntruction.
648 unsigned Val = Result.getZExtValue();
649 if (Val < l || Val > (u + l))
650 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
651 << l << u+l << TheCall->getArg(i)->getSourceRange();
653 // FIXME: VFP Intrinsics should error if VFP not present.
657 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
658 unsigned i = 0, l = 0, u = 0;
660 default: return false;
661 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
662 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
663 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
664 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
665 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
666 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
667 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
670 // We can't check the value of a dependent argument.
671 if (TheCall->getArg(i)->isTypeDependent() ||
672 TheCall->getArg(i)->isValueDependent())
675 // Check that the immediate argument is actually a constant.
677 if (SemaBuiltinConstantArg(TheCall, i, Result))
680 // Range check against the upper/lower values for this instruction.
681 unsigned Val = Result.getZExtValue();
682 if (Val < l || Val > u)
683 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
684 << l << u << TheCall->getArg(i)->getSourceRange();
689 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
690 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
691 /// Returns true when the format fits the function and the FormatStringInfo has
693 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
694 FormatStringInfo *FSI) {
695 FSI->HasVAListArg = Format->getFirstArg() == 0;
696 FSI->FormatIdx = Format->getFormatIdx() - 1;
697 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
699 // The way the format attribute works in GCC, the implicit this argument
700 // of member functions is counted. However, it doesn't appear in our own
701 // lists, so decrement format_idx in that case.
703 if(FSI->FormatIdx == 0)
706 if (FSI->FirstDataArg != 0)
712 /// Handles the checks for format strings, non-POD arguments to vararg
713 /// functions, and NULL arguments passed to non-NULL parameters.
714 void Sema::checkCall(NamedDecl *FDecl,
715 ArrayRef<const Expr *> Args,
716 unsigned NumProtoArgs,
717 bool IsMemberFunction,
720 VariadicCallType CallType) {
721 // FIXME: We should check as much as we can in the template definition.
722 if (CurContext->isDependentContext())
725 // Printf and scanf checking.
726 llvm::SmallBitVector CheckedVarArgs;
728 for (specific_attr_iterator<FormatAttr>
729 I = FDecl->specific_attr_begin<FormatAttr>(),
730 E = FDecl->specific_attr_end<FormatAttr>();
732 // Only create vector if there are format attributes.
733 CheckedVarArgs.resize(Args.size());
735 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
740 // Refuse POD arguments that weren't caught by the format string
742 if (CallType != VariadicDoesNotApply) {
743 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
744 // Args[ArgIdx] can be null in malformed code.
745 if (const Expr *Arg = Args[ArgIdx]) {
746 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
747 checkVariadicArgument(Arg, CallType);
753 for (specific_attr_iterator<NonNullAttr>
754 I = FDecl->specific_attr_begin<NonNullAttr>(),
755 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
756 CheckNonNullArguments(*I, Args.data(), Loc);
758 // Type safety checking.
759 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
760 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
761 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
763 CheckArgumentWithTypeTag(*i, Args.data());
768 /// CheckConstructorCall - Check a constructor call for correctness and safety
769 /// properties not enforced by the C type system.
770 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
771 ArrayRef<const Expr *> Args,
772 const FunctionProtoType *Proto,
773 SourceLocation Loc) {
774 VariadicCallType CallType =
775 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
776 checkCall(FDecl, Args, Proto->getNumArgs(),
777 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
780 /// CheckFunctionCall - Check a direct function call for various correctness
781 /// and safety properties not strictly enforced by the C type system.
782 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
783 const FunctionProtoType *Proto) {
784 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
785 isa<CXXMethodDecl>(FDecl);
786 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
787 IsMemberOperatorCall;
788 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
789 TheCall->getCallee());
790 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
791 Expr** Args = TheCall->getArgs();
792 unsigned NumArgs = TheCall->getNumArgs();
793 if (IsMemberOperatorCall) {
794 // If this is a call to a member operator, hide the first argument
796 // FIXME: Our choice of AST representation here is less than ideal.
800 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
802 IsMemberFunction, TheCall->getRParenLoc(),
803 TheCall->getCallee()->getSourceRange(), CallType);
805 IdentifierInfo *FnInfo = FDecl->getIdentifier();
806 // None of the checks below are needed for functions that don't have
807 // simple names (e.g., C++ conversion functions).
811 unsigned CMId = FDecl->getMemoryFunctionKind();
815 // Handle memory setting and copying functions.
816 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
817 CheckStrlcpycatArguments(TheCall, FnInfo);
818 else if (CMId == Builtin::BIstrncat)
819 CheckStrncatArguments(TheCall, FnInfo);
821 CheckMemaccessArguments(TheCall, CMId, FnInfo);
826 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
827 ArrayRef<const Expr *> Args) {
828 VariadicCallType CallType =
829 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
831 checkCall(Method, Args, Method->param_size(),
832 /*IsMemberFunction=*/false,
833 lbrac, Method->getSourceRange(), CallType);
838 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
839 const FunctionProtoType *Proto) {
840 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
844 QualType Ty = V->getType();
845 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
848 VariadicCallType CallType;
849 if (!Proto || !Proto->isVariadic()) {
850 CallType = VariadicDoesNotApply;
851 } else if (Ty->isBlockPointerType()) {
852 CallType = VariadicBlock;
853 } else { // Ty->isFunctionPointerType()
854 CallType = VariadicFunction;
856 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
859 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
860 TheCall->getNumArgs()),
861 NumProtoArgs, /*IsMemberFunction=*/false,
862 TheCall->getRParenLoc(),
863 TheCall->getCallee()->getSourceRange(), CallType);
868 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
869 /// such as function pointers returned from functions.
870 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
871 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
872 TheCall->getCallee());
873 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
875 checkCall(/*FDecl=*/0,
876 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
877 TheCall->getNumArgs()),
878 NumProtoArgs, /*IsMemberFunction=*/false,
879 TheCall->getRParenLoc(),
880 TheCall->getCallee()->getSourceRange(), CallType);
885 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
886 AtomicExpr::AtomicOp Op) {
887 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
888 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
890 // All these operations take one of the following forms:
892 // C __c11_atomic_init(A *, C)
894 // C __c11_atomic_load(A *, int)
896 // void __atomic_load(A *, CP, int)
898 // C __c11_atomic_add(A *, M, int)
900 // C __atomic_exchange_n(A *, CP, int)
902 // void __atomic_exchange(A *, C *, CP, int)
904 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
906 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
909 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
910 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
912 // C is an appropriate type,
913 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
914 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
915 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
916 // the int parameters are for orderings.
918 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
919 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
920 && "need to update code for modified C11 atomics");
921 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
922 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
923 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
924 Op == AtomicExpr::AO__atomic_store_n ||
925 Op == AtomicExpr::AO__atomic_exchange_n ||
926 Op == AtomicExpr::AO__atomic_compare_exchange_n;
927 bool IsAddSub = false;
930 case AtomicExpr::AO__c11_atomic_init:
934 case AtomicExpr::AO__c11_atomic_load:
935 case AtomicExpr::AO__atomic_load_n:
939 case AtomicExpr::AO__c11_atomic_store:
940 case AtomicExpr::AO__atomic_load:
941 case AtomicExpr::AO__atomic_store:
942 case AtomicExpr::AO__atomic_store_n:
946 case AtomicExpr::AO__c11_atomic_fetch_add:
947 case AtomicExpr::AO__c11_atomic_fetch_sub:
948 case AtomicExpr::AO__atomic_fetch_add:
949 case AtomicExpr::AO__atomic_fetch_sub:
950 case AtomicExpr::AO__atomic_add_fetch:
951 case AtomicExpr::AO__atomic_sub_fetch:
954 case AtomicExpr::AO__c11_atomic_fetch_and:
955 case AtomicExpr::AO__c11_atomic_fetch_or:
956 case AtomicExpr::AO__c11_atomic_fetch_xor:
957 case AtomicExpr::AO__atomic_fetch_and:
958 case AtomicExpr::AO__atomic_fetch_or:
959 case AtomicExpr::AO__atomic_fetch_xor:
960 case AtomicExpr::AO__atomic_fetch_nand:
961 case AtomicExpr::AO__atomic_and_fetch:
962 case AtomicExpr::AO__atomic_or_fetch:
963 case AtomicExpr::AO__atomic_xor_fetch:
964 case AtomicExpr::AO__atomic_nand_fetch:
968 case AtomicExpr::AO__c11_atomic_exchange:
969 case AtomicExpr::AO__atomic_exchange_n:
973 case AtomicExpr::AO__atomic_exchange:
977 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
978 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
982 case AtomicExpr::AO__atomic_compare_exchange:
983 case AtomicExpr::AO__atomic_compare_exchange_n:
988 // Check we have the right number of arguments.
989 if (TheCall->getNumArgs() < NumArgs[Form]) {
990 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
991 << 0 << NumArgs[Form] << TheCall->getNumArgs()
992 << TheCall->getCallee()->getSourceRange();
994 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
995 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
996 diag::err_typecheck_call_too_many_args)
997 << 0 << NumArgs[Form] << TheCall->getNumArgs()
998 << TheCall->getCallee()->getSourceRange();
1002 // Inspect the first argument of the atomic operation.
1003 Expr *Ptr = TheCall->getArg(0);
1004 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1005 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1007 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1008 << Ptr->getType() << Ptr->getSourceRange();
1012 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1013 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1014 QualType ValType = AtomTy; // 'C'
1016 if (!AtomTy->isAtomicType()) {
1017 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1018 << Ptr->getType() << Ptr->getSourceRange();
1021 if (AtomTy.isConstQualified()) {
1022 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1023 << Ptr->getType() << Ptr->getSourceRange();
1026 ValType = AtomTy->getAs<AtomicType>()->getValueType();
1029 // For an arithmetic operation, the implied arithmetic must be well-formed.
1030 if (Form == Arithmetic) {
1031 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1032 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1033 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1034 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1037 if (!IsAddSub && !ValType->isIntegerType()) {
1038 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1039 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1042 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1043 // For __atomic_*_n operations, the value type must be a scalar integral or
1044 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1045 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1046 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1050 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1051 !AtomTy->isScalarType()) {
1052 // For GNU atomics, require a trivially-copyable type. This is not part of
1053 // the GNU atomics specification, but we enforce it for sanity.
1054 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1055 << Ptr->getType() << Ptr->getSourceRange();
1059 // FIXME: For any builtin other than a load, the ValType must not be
1062 switch (ValType.getObjCLifetime()) {
1063 case Qualifiers::OCL_None:
1064 case Qualifiers::OCL_ExplicitNone:
1068 case Qualifiers::OCL_Weak:
1069 case Qualifiers::OCL_Strong:
1070 case Qualifiers::OCL_Autoreleasing:
1071 // FIXME: Can this happen? By this point, ValType should be known
1072 // to be trivially copyable.
1073 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1074 << ValType << Ptr->getSourceRange();
1078 QualType ResultType = ValType;
1079 if (Form == Copy || Form == GNUXchg || Form == Init)
1080 ResultType = Context.VoidTy;
1081 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1082 ResultType = Context.BoolTy;
1084 // The type of a parameter passed 'by value'. In the GNU atomics, such
1085 // arguments are actually passed as pointers.
1086 QualType ByValType = ValType; // 'CP'
1088 ByValType = Ptr->getType();
1090 // The first argument --- the pointer --- has a fixed type; we
1091 // deduce the types of the rest of the arguments accordingly. Walk
1092 // the remaining arguments, converting them to the deduced value type.
1093 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1095 if (i < NumVals[Form] + 1) {
1098 // The second argument is the non-atomic operand. For arithmetic, this
1099 // is always passed by value, and for a compare_exchange it is always
1100 // passed by address. For the rest, GNU uses by-address and C11 uses
1102 assert(Form != Load);
1103 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1105 else if (Form == Copy || Form == Xchg)
1107 else if (Form == Arithmetic)
1108 Ty = Context.getPointerDiffType();
1110 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1113 // The third argument to compare_exchange / GNU exchange is a
1114 // (pointer to a) desired value.
1118 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1119 Ty = Context.BoolTy;
1123 // The order(s) are always converted to int.
1127 InitializedEntity Entity =
1128 InitializedEntity::InitializeParameter(Context, Ty, false);
1129 ExprResult Arg = TheCall->getArg(i);
1130 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1131 if (Arg.isInvalid())
1133 TheCall->setArg(i, Arg.get());
1136 // Permute the arguments into a 'consistent' order.
1137 SmallVector<Expr*, 5> SubExprs;
1138 SubExprs.push_back(Ptr);
1141 // Note, AtomicExpr::getVal1() has a special case for this atomic.
1142 SubExprs.push_back(TheCall->getArg(1)); // Val1
1145 SubExprs.push_back(TheCall->getArg(1)); // Order
1150 SubExprs.push_back(TheCall->getArg(2)); // Order
1151 SubExprs.push_back(TheCall->getArg(1)); // Val1
1154 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1155 SubExprs.push_back(TheCall->getArg(3)); // Order
1156 SubExprs.push_back(TheCall->getArg(1)); // Val1
1157 SubExprs.push_back(TheCall->getArg(2)); // Val2
1160 SubExprs.push_back(TheCall->getArg(3)); // Order
1161 SubExprs.push_back(TheCall->getArg(1)); // Val1
1162 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1163 SubExprs.push_back(TheCall->getArg(2)); // Val2
1166 SubExprs.push_back(TheCall->getArg(4)); // Order
1167 SubExprs.push_back(TheCall->getArg(1)); // Val1
1168 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1169 SubExprs.push_back(TheCall->getArg(2)); // Val2
1170 SubExprs.push_back(TheCall->getArg(3)); // Weak
1174 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1175 SubExprs, ResultType, Op,
1176 TheCall->getRParenLoc());
1178 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1179 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1180 Context.AtomicUsesUnsupportedLibcall(AE))
1181 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1182 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1188 /// checkBuiltinArgument - Given a call to a builtin function, perform
1189 /// normal type-checking on the given argument, updating the call in
1190 /// place. This is useful when a builtin function requires custom
1191 /// type-checking for some of its arguments but not necessarily all of
1194 /// Returns true on error.
1195 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1196 FunctionDecl *Fn = E->getDirectCallee();
1197 assert(Fn && "builtin call without direct callee!");
1199 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1200 InitializedEntity Entity =
1201 InitializedEntity::InitializeParameter(S.Context, Param);
1203 ExprResult Arg = E->getArg(0);
1204 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1205 if (Arg.isInvalid())
1208 E->setArg(ArgIndex, Arg.take());
1212 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1213 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1214 /// type of its first argument. The main ActOnCallExpr routines have already
1215 /// promoted the types of arguments because all of these calls are prototyped as
1218 /// This function goes through and does final semantic checking for these
1221 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1222 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1223 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1224 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1226 // Ensure that we have at least one argument to do type inference from.
1227 if (TheCall->getNumArgs() < 1) {
1228 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1229 << 0 << 1 << TheCall->getNumArgs()
1230 << TheCall->getCallee()->getSourceRange();
1234 // Inspect the first argument of the atomic builtin. This should always be
1235 // a pointer type, whose element is an integral scalar or pointer type.
1236 // Because it is a pointer type, we don't have to worry about any implicit
1238 // FIXME: We don't allow floating point scalars as input.
1239 Expr *FirstArg = TheCall->getArg(0);
1240 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1241 if (FirstArgResult.isInvalid())
1243 FirstArg = FirstArgResult.take();
1244 TheCall->setArg(0, FirstArg);
1246 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1248 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1249 << FirstArg->getType() << FirstArg->getSourceRange();
1253 QualType ValType = pointerType->getPointeeType();
1254 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1255 !ValType->isBlockPointerType()) {
1256 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1257 << FirstArg->getType() << FirstArg->getSourceRange();
1261 switch (ValType.getObjCLifetime()) {
1262 case Qualifiers::OCL_None:
1263 case Qualifiers::OCL_ExplicitNone:
1267 case Qualifiers::OCL_Weak:
1268 case Qualifiers::OCL_Strong:
1269 case Qualifiers::OCL_Autoreleasing:
1270 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1271 << ValType << FirstArg->getSourceRange();
1275 // Strip any qualifiers off ValType.
1276 ValType = ValType.getUnqualifiedType();
1278 // The majority of builtins return a value, but a few have special return
1279 // types, so allow them to override appropriately below.
1280 QualType ResultType = ValType;
1282 // We need to figure out which concrete builtin this maps onto. For example,
1283 // __sync_fetch_and_add with a 2 byte object turns into
1284 // __sync_fetch_and_add_2.
1285 #define BUILTIN_ROW(x) \
1286 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1287 Builtin::BI##x##_8, Builtin::BI##x##_16 }
1289 static const unsigned BuiltinIndices[][5] = {
1290 BUILTIN_ROW(__sync_fetch_and_add),
1291 BUILTIN_ROW(__sync_fetch_and_sub),
1292 BUILTIN_ROW(__sync_fetch_and_or),
1293 BUILTIN_ROW(__sync_fetch_and_and),
1294 BUILTIN_ROW(__sync_fetch_and_xor),
1296 BUILTIN_ROW(__sync_add_and_fetch),
1297 BUILTIN_ROW(__sync_sub_and_fetch),
1298 BUILTIN_ROW(__sync_and_and_fetch),
1299 BUILTIN_ROW(__sync_or_and_fetch),
1300 BUILTIN_ROW(__sync_xor_and_fetch),
1302 BUILTIN_ROW(__sync_val_compare_and_swap),
1303 BUILTIN_ROW(__sync_bool_compare_and_swap),
1304 BUILTIN_ROW(__sync_lock_test_and_set),
1305 BUILTIN_ROW(__sync_lock_release),
1306 BUILTIN_ROW(__sync_swap)
1310 // Determine the index of the size.
1312 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1313 case 1: SizeIndex = 0; break;
1314 case 2: SizeIndex = 1; break;
1315 case 4: SizeIndex = 2; break;
1316 case 8: SizeIndex = 3; break;
1317 case 16: SizeIndex = 4; break;
1319 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1320 << FirstArg->getType() << FirstArg->getSourceRange();
1324 // Each of these builtins has one pointer argument, followed by some number of
1325 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1326 // that we ignore. Find out which row of BuiltinIndices to read from as well
1327 // as the number of fixed args.
1328 unsigned BuiltinID = FDecl->getBuiltinID();
1329 unsigned BuiltinIndex, NumFixed = 1;
1330 switch (BuiltinID) {
1331 default: llvm_unreachable("Unknown overloaded atomic builtin!");
1332 case Builtin::BI__sync_fetch_and_add:
1333 case Builtin::BI__sync_fetch_and_add_1:
1334 case Builtin::BI__sync_fetch_and_add_2:
1335 case Builtin::BI__sync_fetch_and_add_4:
1336 case Builtin::BI__sync_fetch_and_add_8:
1337 case Builtin::BI__sync_fetch_and_add_16:
1341 case Builtin::BI__sync_fetch_and_sub:
1342 case Builtin::BI__sync_fetch_and_sub_1:
1343 case Builtin::BI__sync_fetch_and_sub_2:
1344 case Builtin::BI__sync_fetch_and_sub_4:
1345 case Builtin::BI__sync_fetch_and_sub_8:
1346 case Builtin::BI__sync_fetch_and_sub_16:
1350 case Builtin::BI__sync_fetch_and_or:
1351 case Builtin::BI__sync_fetch_and_or_1:
1352 case Builtin::BI__sync_fetch_and_or_2:
1353 case Builtin::BI__sync_fetch_and_or_4:
1354 case Builtin::BI__sync_fetch_and_or_8:
1355 case Builtin::BI__sync_fetch_and_or_16:
1359 case Builtin::BI__sync_fetch_and_and:
1360 case Builtin::BI__sync_fetch_and_and_1:
1361 case Builtin::BI__sync_fetch_and_and_2:
1362 case Builtin::BI__sync_fetch_and_and_4:
1363 case Builtin::BI__sync_fetch_and_and_8:
1364 case Builtin::BI__sync_fetch_and_and_16:
1368 case Builtin::BI__sync_fetch_and_xor:
1369 case Builtin::BI__sync_fetch_and_xor_1:
1370 case Builtin::BI__sync_fetch_and_xor_2:
1371 case Builtin::BI__sync_fetch_and_xor_4:
1372 case Builtin::BI__sync_fetch_and_xor_8:
1373 case Builtin::BI__sync_fetch_and_xor_16:
1377 case Builtin::BI__sync_add_and_fetch:
1378 case Builtin::BI__sync_add_and_fetch_1:
1379 case Builtin::BI__sync_add_and_fetch_2:
1380 case Builtin::BI__sync_add_and_fetch_4:
1381 case Builtin::BI__sync_add_and_fetch_8:
1382 case Builtin::BI__sync_add_and_fetch_16:
1386 case Builtin::BI__sync_sub_and_fetch:
1387 case Builtin::BI__sync_sub_and_fetch_1:
1388 case Builtin::BI__sync_sub_and_fetch_2:
1389 case Builtin::BI__sync_sub_and_fetch_4:
1390 case Builtin::BI__sync_sub_and_fetch_8:
1391 case Builtin::BI__sync_sub_and_fetch_16:
1395 case Builtin::BI__sync_and_and_fetch:
1396 case Builtin::BI__sync_and_and_fetch_1:
1397 case Builtin::BI__sync_and_and_fetch_2:
1398 case Builtin::BI__sync_and_and_fetch_4:
1399 case Builtin::BI__sync_and_and_fetch_8:
1400 case Builtin::BI__sync_and_and_fetch_16:
1404 case Builtin::BI__sync_or_and_fetch:
1405 case Builtin::BI__sync_or_and_fetch_1:
1406 case Builtin::BI__sync_or_and_fetch_2:
1407 case Builtin::BI__sync_or_and_fetch_4:
1408 case Builtin::BI__sync_or_and_fetch_8:
1409 case Builtin::BI__sync_or_and_fetch_16:
1413 case Builtin::BI__sync_xor_and_fetch:
1414 case Builtin::BI__sync_xor_and_fetch_1:
1415 case Builtin::BI__sync_xor_and_fetch_2:
1416 case Builtin::BI__sync_xor_and_fetch_4:
1417 case Builtin::BI__sync_xor_and_fetch_8:
1418 case Builtin::BI__sync_xor_and_fetch_16:
1422 case Builtin::BI__sync_val_compare_and_swap:
1423 case Builtin::BI__sync_val_compare_and_swap_1:
1424 case Builtin::BI__sync_val_compare_and_swap_2:
1425 case Builtin::BI__sync_val_compare_and_swap_4:
1426 case Builtin::BI__sync_val_compare_and_swap_8:
1427 case Builtin::BI__sync_val_compare_and_swap_16:
1432 case Builtin::BI__sync_bool_compare_and_swap:
1433 case Builtin::BI__sync_bool_compare_and_swap_1:
1434 case Builtin::BI__sync_bool_compare_and_swap_2:
1435 case Builtin::BI__sync_bool_compare_and_swap_4:
1436 case Builtin::BI__sync_bool_compare_and_swap_8:
1437 case Builtin::BI__sync_bool_compare_and_swap_16:
1440 ResultType = Context.BoolTy;
1443 case Builtin::BI__sync_lock_test_and_set:
1444 case Builtin::BI__sync_lock_test_and_set_1:
1445 case Builtin::BI__sync_lock_test_and_set_2:
1446 case Builtin::BI__sync_lock_test_and_set_4:
1447 case Builtin::BI__sync_lock_test_and_set_8:
1448 case Builtin::BI__sync_lock_test_and_set_16:
1452 case Builtin::BI__sync_lock_release:
1453 case Builtin::BI__sync_lock_release_1:
1454 case Builtin::BI__sync_lock_release_2:
1455 case Builtin::BI__sync_lock_release_4:
1456 case Builtin::BI__sync_lock_release_8:
1457 case Builtin::BI__sync_lock_release_16:
1460 ResultType = Context.VoidTy;
1463 case Builtin::BI__sync_swap:
1464 case Builtin::BI__sync_swap_1:
1465 case Builtin::BI__sync_swap_2:
1466 case Builtin::BI__sync_swap_4:
1467 case Builtin::BI__sync_swap_8:
1468 case Builtin::BI__sync_swap_16:
1473 // Now that we know how many fixed arguments we expect, first check that we
1474 // have at least that many.
1475 if (TheCall->getNumArgs() < 1+NumFixed) {
1476 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1477 << 0 << 1+NumFixed << TheCall->getNumArgs()
1478 << TheCall->getCallee()->getSourceRange();
1482 // Get the decl for the concrete builtin from this, we can tell what the
1483 // concrete integer type we should convert to is.
1484 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1485 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1486 FunctionDecl *NewBuiltinDecl;
1487 if (NewBuiltinID == BuiltinID)
1488 NewBuiltinDecl = FDecl;
1490 // Perform builtin lookup to avoid redeclaring it.
1491 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1492 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1493 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1494 assert(Res.getFoundDecl());
1495 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1496 if (NewBuiltinDecl == 0)
1500 // The first argument --- the pointer --- has a fixed type; we
1501 // deduce the types of the rest of the arguments accordingly. Walk
1502 // the remaining arguments, converting them to the deduced value type.
1503 for (unsigned i = 0; i != NumFixed; ++i) {
1504 ExprResult Arg = TheCall->getArg(i+1);
1506 // GCC does an implicit conversion to the pointer or integer ValType. This
1507 // can fail in some cases (1i -> int**), check for this error case now.
1508 // Initialize the argument.
1509 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1510 ValType, /*consume*/ false);
1511 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1512 if (Arg.isInvalid())
1515 // Okay, we have something that *can* be converted to the right type. Check
1516 // to see if there is a potentially weird extension going on here. This can
1517 // happen when you do an atomic operation on something like an char* and
1518 // pass in 42. The 42 gets converted to char. This is even more strange
1519 // for things like 45.123 -> char, etc.
1520 // FIXME: Do this check.
1521 TheCall->setArg(i+1, Arg.take());
1524 ASTContext& Context = this->getASTContext();
1526 // Create a new DeclRefExpr to refer to the new decl.
1527 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1529 DRE->getQualifierLoc(),
1532 /*enclosing*/ false,
1534 Context.BuiltinFnTy,
1535 DRE->getValueKind());
1537 // Set the callee in the CallExpr.
1538 // FIXME: This loses syntactic information.
1539 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1540 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1541 CK_BuiltinFnToFnPtr);
1542 TheCall->setCallee(PromotedCall.take());
1544 // Change the result type of the call to match the original value type. This
1545 // is arbitrary, but the codegen for these builtins ins design to handle it
1547 TheCall->setType(ResultType);
1549 return TheCallResult;
1552 /// CheckObjCString - Checks that the argument to the builtin
1553 /// CFString constructor is correct
1554 /// Note: It might also make sense to do the UTF-16 conversion here (would
1555 /// simplify the backend).
1556 bool Sema::CheckObjCString(Expr *Arg) {
1557 Arg = Arg->IgnoreParenCasts();
1558 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1560 if (!Literal || !Literal->isAscii()) {
1561 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1562 << Arg->getSourceRange();
1566 if (Literal->containsNonAsciiOrNull()) {
1567 StringRef String = Literal->getString();
1568 unsigned NumBytes = String.size();
1569 SmallVector<UTF16, 128> ToBuf(NumBytes);
1570 const UTF8 *FromPtr = (const UTF8 *)String.data();
1571 UTF16 *ToPtr = &ToBuf[0];
1573 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1574 &ToPtr, ToPtr + NumBytes,
1576 // Check for conversion failure.
1577 if (Result != conversionOK)
1578 Diag(Arg->getLocStart(),
1579 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1584 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1585 /// Emit an error and return true on failure, return false on success.
1586 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1587 Expr *Fn = TheCall->getCallee();
1588 if (TheCall->getNumArgs() > 2) {
1589 Diag(TheCall->getArg(2)->getLocStart(),
1590 diag::err_typecheck_call_too_many_args)
1591 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1592 << Fn->getSourceRange()
1593 << SourceRange(TheCall->getArg(2)->getLocStart(),
1594 (*(TheCall->arg_end()-1))->getLocEnd());
1598 if (TheCall->getNumArgs() < 2) {
1599 return Diag(TheCall->getLocEnd(),
1600 diag::err_typecheck_call_too_few_args_at_least)
1601 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1604 // Type-check the first argument normally.
1605 if (checkBuiltinArgument(*this, TheCall, 0))
1608 // Determine whether the current function is variadic or not.
1609 BlockScopeInfo *CurBlock = getCurBlock();
1612 isVariadic = CurBlock->TheDecl->isVariadic();
1613 else if (FunctionDecl *FD = getCurFunctionDecl())
1614 isVariadic = FD->isVariadic();
1616 isVariadic = getCurMethodDecl()->isVariadic();
1619 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1623 // Verify that the second argument to the builtin is the last argument of the
1624 // current function or method.
1625 bool SecondArgIsLastNamedArgument = false;
1626 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1628 // These are valid if SecondArgIsLastNamedArgument is false after the next
1631 SourceLocation ParamLoc;
1633 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1634 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1635 // FIXME: This isn't correct for methods (results in bogus warning).
1636 // Get the last formal in the current function.
1637 const ParmVarDecl *LastArg;
1639 LastArg = *(CurBlock->TheDecl->param_end()-1);
1640 else if (FunctionDecl *FD = getCurFunctionDecl())
1641 LastArg = *(FD->param_end()-1);
1643 LastArg = *(getCurMethodDecl()->param_end()-1);
1644 SecondArgIsLastNamedArgument = PV == LastArg;
1646 Type = PV->getType();
1647 ParamLoc = PV->getLocation();
1651 if (!SecondArgIsLastNamedArgument)
1652 Diag(TheCall->getArg(1)->getLocStart(),
1653 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1654 else if (Type->isReferenceType()) {
1655 Diag(Arg->getLocStart(),
1656 diag::warn_va_start_of_reference_type_is_undefined);
1657 Diag(ParamLoc, diag::note_parameter_type) << Type;
1660 TheCall->setType(Context.VoidTy);
1664 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1665 /// friends. This is declared to take (...), so we have to check everything.
1666 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1667 if (TheCall->getNumArgs() < 2)
1668 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1669 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1670 if (TheCall->getNumArgs() > 2)
1671 return Diag(TheCall->getArg(2)->getLocStart(),
1672 diag::err_typecheck_call_too_many_args)
1673 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1674 << SourceRange(TheCall->getArg(2)->getLocStart(),
1675 (*(TheCall->arg_end()-1))->getLocEnd());
1677 ExprResult OrigArg0 = TheCall->getArg(0);
1678 ExprResult OrigArg1 = TheCall->getArg(1);
1680 // Do standard promotions between the two arguments, returning their common
1682 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1683 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1686 // Make sure any conversions are pushed back into the call; this is
1687 // type safe since unordered compare builtins are declared as "_Bool
1689 TheCall->setArg(0, OrigArg0.get());
1690 TheCall->setArg(1, OrigArg1.get());
1692 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1695 // If the common type isn't a real floating type, then the arguments were
1696 // invalid for this operation.
1697 if (Res.isNull() || !Res->isRealFloatingType())
1698 return Diag(OrigArg0.get()->getLocStart(),
1699 diag::err_typecheck_call_invalid_ordered_compare)
1700 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1701 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1706 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1707 /// __builtin_isnan and friends. This is declared to take (...), so we have
1708 /// to check everything. We expect the last argument to be a floating point
1710 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1711 if (TheCall->getNumArgs() < NumArgs)
1712 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1713 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1714 if (TheCall->getNumArgs() > NumArgs)
1715 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1716 diag::err_typecheck_call_too_many_args)
1717 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1718 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1719 (*(TheCall->arg_end()-1))->getLocEnd());
1721 Expr *OrigArg = TheCall->getArg(NumArgs-1);
1723 if (OrigArg->isTypeDependent())
1726 // This operation requires a non-_Complex floating-point number.
1727 if (!OrigArg->getType()->isRealFloatingType())
1728 return Diag(OrigArg->getLocStart(),
1729 diag::err_typecheck_call_invalid_unary_fp)
1730 << OrigArg->getType() << OrigArg->getSourceRange();
1732 // If this is an implicit conversion from float -> double, remove it.
1733 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1734 Expr *CastArg = Cast->getSubExpr();
1735 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1736 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1737 "promotion from float to double is the only expected cast here");
1738 Cast->setSubExpr(0);
1739 TheCall->setArg(NumArgs-1, CastArg);
1746 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1747 // This is declared to take (...), so we have to check everything.
1748 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1749 if (TheCall->getNumArgs() < 2)
1750 return ExprError(Diag(TheCall->getLocEnd(),
1751 diag::err_typecheck_call_too_few_args_at_least)
1752 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1753 << TheCall->getSourceRange());
1755 // Determine which of the following types of shufflevector we're checking:
1756 // 1) unary, vector mask: (lhs, mask)
1757 // 2) binary, vector mask: (lhs, rhs, mask)
1758 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1759 QualType resType = TheCall->getArg(0)->getType();
1760 unsigned numElements = 0;
1762 if (!TheCall->getArg(0)->isTypeDependent() &&
1763 !TheCall->getArg(1)->isTypeDependent()) {
1764 QualType LHSType = TheCall->getArg(0)->getType();
1765 QualType RHSType = TheCall->getArg(1)->getType();
1767 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1768 return ExprError(Diag(TheCall->getLocStart(),
1769 diag::err_shufflevector_non_vector)
1770 << SourceRange(TheCall->getArg(0)->getLocStart(),
1771 TheCall->getArg(1)->getLocEnd()));
1773 numElements = LHSType->getAs<VectorType>()->getNumElements();
1774 unsigned numResElements = TheCall->getNumArgs() - 2;
1776 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1777 // with mask. If so, verify that RHS is an integer vector type with the
1778 // same number of elts as lhs.
1779 if (TheCall->getNumArgs() == 2) {
1780 if (!RHSType->hasIntegerRepresentation() ||
1781 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1782 return ExprError(Diag(TheCall->getLocStart(),
1783 diag::err_shufflevector_incompatible_vector)
1784 << SourceRange(TheCall->getArg(1)->getLocStart(),
1785 TheCall->getArg(1)->getLocEnd()));
1786 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1787 return ExprError(Diag(TheCall->getLocStart(),
1788 diag::err_shufflevector_incompatible_vector)
1789 << SourceRange(TheCall->getArg(0)->getLocStart(),
1790 TheCall->getArg(1)->getLocEnd()));
1791 } else if (numElements != numResElements) {
1792 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1793 resType = Context.getVectorType(eltType, numResElements,
1794 VectorType::GenericVector);
1798 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1799 if (TheCall->getArg(i)->isTypeDependent() ||
1800 TheCall->getArg(i)->isValueDependent())
1803 llvm::APSInt Result(32);
1804 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1805 return ExprError(Diag(TheCall->getLocStart(),
1806 diag::err_shufflevector_nonconstant_argument)
1807 << TheCall->getArg(i)->getSourceRange());
1809 // Allow -1 which will be translated to undef in the IR.
1810 if (Result.isSigned() && Result.isAllOnesValue())
1813 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1814 return ExprError(Diag(TheCall->getLocStart(),
1815 diag::err_shufflevector_argument_too_large)
1816 << TheCall->getArg(i)->getSourceRange());
1819 SmallVector<Expr*, 32> exprs;
1821 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1822 exprs.push_back(TheCall->getArg(i));
1823 TheCall->setArg(i, 0);
1826 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1827 TheCall->getCallee()->getLocStart(),
1828 TheCall->getRParenLoc()));
1831 /// SemaConvertVectorExpr - Handle __builtin_convertvector
1832 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1833 SourceLocation BuiltinLoc,
1834 SourceLocation RParenLoc) {
1835 ExprValueKind VK = VK_RValue;
1836 ExprObjectKind OK = OK_Ordinary;
1837 QualType DstTy = TInfo->getType();
1838 QualType SrcTy = E->getType();
1840 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1841 return ExprError(Diag(BuiltinLoc,
1842 diag::err_convertvector_non_vector)
1843 << E->getSourceRange());
1844 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1845 return ExprError(Diag(BuiltinLoc,
1846 diag::err_convertvector_non_vector_type));
1848 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1849 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1850 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1851 if (SrcElts != DstElts)
1852 return ExprError(Diag(BuiltinLoc,
1853 diag::err_convertvector_incompatible_vector)
1854 << E->getSourceRange());
1857 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1858 BuiltinLoc, RParenLoc));
1862 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1863 // This is declared to take (const void*, ...) and can take two
1864 // optional constant int args.
1865 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1866 unsigned NumArgs = TheCall->getNumArgs();
1869 return Diag(TheCall->getLocEnd(),
1870 diag::err_typecheck_call_too_many_args_at_most)
1871 << 0 /*function call*/ << 3 << NumArgs
1872 << TheCall->getSourceRange();
1874 // Argument 0 is checked for us and the remaining arguments must be
1875 // constant integers.
1876 for (unsigned i = 1; i != NumArgs; ++i) {
1877 Expr *Arg = TheCall->getArg(i);
1879 // We can't check the value of a dependent argument.
1880 if (Arg->isTypeDependent() || Arg->isValueDependent())
1883 llvm::APSInt Result;
1884 if (SemaBuiltinConstantArg(TheCall, i, Result))
1887 // FIXME: gcc issues a warning and rewrites these to 0. These
1888 // seems especially odd for the third argument since the default
1891 if (Result.getLimitedValue() > 1)
1892 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1893 << "0" << "1" << Arg->getSourceRange();
1895 if (Result.getLimitedValue() > 3)
1896 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1897 << "0" << "3" << Arg->getSourceRange();
1904 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1905 /// TheCall is a constant expression.
1906 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1907 llvm::APSInt &Result) {
1908 Expr *Arg = TheCall->getArg(ArgNum);
1909 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1910 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1912 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1914 if (!Arg->isIntegerConstantExpr(Result, Context))
1915 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1916 << FDecl->getDeclName() << Arg->getSourceRange();
1921 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1922 /// int type). This simply type checks that type is one of the defined
1923 /// constants (0-3).
1924 // For compatibility check 0-3, llvm only handles 0 and 2.
1925 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1926 llvm::APSInt Result;
1928 // We can't check the value of a dependent argument.
1929 if (TheCall->getArg(1)->isTypeDependent() ||
1930 TheCall->getArg(1)->isValueDependent())
1933 // Check constant-ness first.
1934 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1937 Expr *Arg = TheCall->getArg(1);
1938 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1939 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1940 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1946 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1947 /// This checks that val is a constant 1.
1948 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1949 Expr *Arg = TheCall->getArg(1);
1950 llvm::APSInt Result;
1952 // TODO: This is less than ideal. Overload this to take a value.
1953 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1957 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1958 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1964 enum StringLiteralCheckType {
1966 SLCT_UncheckedLiteral,
1971 // Determine if an expression is a string literal or constant string.
1972 // If this function returns false on the arguments to a function expecting a
1973 // format string, we will usually need to emit a warning.
1974 // True string literals are then checked by CheckFormatString.
1975 static StringLiteralCheckType
1976 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1977 bool HasVAListArg, unsigned format_idx,
1978 unsigned firstDataArg, Sema::FormatStringType Type,
1979 Sema::VariadicCallType CallType, bool InFunctionCall,
1980 llvm::SmallBitVector &CheckedVarArgs) {
1982 if (E->isTypeDependent() || E->isValueDependent())
1983 return SLCT_NotALiteral;
1985 E = E->IgnoreParenCasts();
1987 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
1988 // Technically -Wformat-nonliteral does not warn about this case.
1989 // The behavior of printf and friends in this case is implementation
1990 // dependent. Ideally if the format string cannot be null then
1991 // it should have a 'nonnull' attribute in the function prototype.
1992 return SLCT_UncheckedLiteral;
1994 switch (E->getStmtClass()) {
1995 case Stmt::BinaryConditionalOperatorClass:
1996 case Stmt::ConditionalOperatorClass: {
1997 // The expression is a literal if both sub-expressions were, and it was
1998 // completely checked only if both sub-expressions were checked.
1999 const AbstractConditionalOperator *C =
2000 cast<AbstractConditionalOperator>(E);
2001 StringLiteralCheckType Left =
2002 checkFormatStringExpr(S, C->getTrueExpr(), Args,
2003 HasVAListArg, format_idx, firstDataArg,
2004 Type, CallType, InFunctionCall, CheckedVarArgs);
2005 if (Left == SLCT_NotALiteral)
2006 return SLCT_NotALiteral;
2007 StringLiteralCheckType Right =
2008 checkFormatStringExpr(S, C->getFalseExpr(), Args,
2009 HasVAListArg, format_idx, firstDataArg,
2010 Type, CallType, InFunctionCall, CheckedVarArgs);
2011 return Left < Right ? Left : Right;
2014 case Stmt::ImplicitCastExprClass: {
2015 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2019 case Stmt::OpaqueValueExprClass:
2020 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2024 return SLCT_NotALiteral;
2026 case Stmt::PredefinedExprClass:
2027 // While __func__, etc., are technically not string literals, they
2028 // cannot contain format specifiers and thus are not a security
2030 return SLCT_UncheckedLiteral;
2032 case Stmt::DeclRefExprClass: {
2033 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2035 // As an exception, do not flag errors for variables binding to
2036 // const string literals.
2037 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2038 bool isConstant = false;
2039 QualType T = DR->getType();
2041 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2042 isConstant = AT->getElementType().isConstant(S.Context);
2043 } else if (const PointerType *PT = T->getAs<PointerType>()) {
2044 isConstant = T.isConstant(S.Context) &&
2045 PT->getPointeeType().isConstant(S.Context);
2046 } else if (T->isObjCObjectPointerType()) {
2047 // In ObjC, there is usually no "const ObjectPointer" type,
2048 // so don't check if the pointee type is constant.
2049 isConstant = T.isConstant(S.Context);
2053 if (const Expr *Init = VD->getAnyInitializer()) {
2054 // Look through initializers like const char c[] = { "foo" }
2055 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2056 if (InitList->isStringLiteralInit())
2057 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2059 return checkFormatStringExpr(S, Init, Args,
2060 HasVAListArg, format_idx,
2061 firstDataArg, Type, CallType,
2062 /*InFunctionCall*/false, CheckedVarArgs);
2066 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2067 // special check to see if the format string is a function parameter
2068 // of the function calling the printf function. If the function
2069 // has an attribute indicating it is a printf-like function, then we
2070 // should suppress warnings concerning non-literals being used in a call
2071 // to a vprintf function. For example:
2074 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2076 // va_start(ap, fmt);
2077 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2081 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2082 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2083 int PVIndex = PV->getFunctionScopeIndex() + 1;
2084 for (specific_attr_iterator<FormatAttr>
2085 i = ND->specific_attr_begin<FormatAttr>(),
2086 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2087 FormatAttr *PVFormat = *i;
2088 // adjust for implicit parameter
2089 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2090 if (MD->isInstance())
2092 // We also check if the formats are compatible.
2093 // We can't pass a 'scanf' string to a 'printf' function.
2094 if (PVIndex == PVFormat->getFormatIdx() &&
2095 Type == S.GetFormatStringType(PVFormat))
2096 return SLCT_UncheckedLiteral;
2103 return SLCT_NotALiteral;
2106 case Stmt::CallExprClass:
2107 case Stmt::CXXMemberCallExprClass: {
2108 const CallExpr *CE = cast<CallExpr>(E);
2109 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2110 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2111 unsigned ArgIndex = FA->getFormatIdx();
2112 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2113 if (MD->isInstance())
2115 const Expr *Arg = CE->getArg(ArgIndex - 1);
2117 return checkFormatStringExpr(S, Arg, Args,
2118 HasVAListArg, format_idx, firstDataArg,
2119 Type, CallType, InFunctionCall,
2121 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2122 unsigned BuiltinID = FD->getBuiltinID();
2123 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2124 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2125 const Expr *Arg = CE->getArg(0);
2126 return checkFormatStringExpr(S, Arg, Args,
2127 HasVAListArg, format_idx,
2128 firstDataArg, Type, CallType,
2129 InFunctionCall, CheckedVarArgs);
2134 return SLCT_NotALiteral;
2137 case Stmt::ObjCMessageExprClass: {
2138 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2139 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2140 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2141 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2142 unsigned ArgIndex = FA->getFormatIdx();
2143 if (ArgIndex <= ME->getNumArgs()) {
2144 const Expr *Arg = ME->getArg(ArgIndex-1);
2145 return checkFormatStringExpr(S, Arg, Args,
2146 HasVAListArg, format_idx,
2147 firstDataArg, Type, CallType,
2148 InFunctionCall, CheckedVarArgs);
2154 return SLCT_NotALiteral;
2157 case Stmt::ObjCStringLiteralClass:
2158 case Stmt::StringLiteralClass: {
2159 const StringLiteral *StrE = NULL;
2161 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2162 StrE = ObjCFExpr->getString();
2164 StrE = cast<StringLiteral>(E);
2167 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2168 Type, InFunctionCall, CallType, CheckedVarArgs);
2169 return SLCT_CheckedLiteral;
2172 return SLCT_NotALiteral;
2176 return SLCT_NotALiteral;
2181 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
2182 const Expr * const *ExprArgs,
2183 SourceLocation CallSiteLoc) {
2184 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2185 e = NonNull->args_end();
2187 const Expr *ArgExpr = ExprArgs[*i];
2189 // As a special case, transparent unions initialized with zero are
2190 // considered null for the purposes of the nonnull attribute.
2191 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2192 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2193 if (const CompoundLiteralExpr *CLE =
2194 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2195 if (const InitListExpr *ILE =
2196 dyn_cast<InitListExpr>(CLE->getInitializer()))
2197 ArgExpr = ILE->getInit(0);
2201 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
2202 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
2206 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2207 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2208 .Case("scanf", FST_Scanf)
2209 .Cases("printf", "printf0", FST_Printf)
2210 .Cases("NSString", "CFString", FST_NSString)
2211 .Case("strftime", FST_Strftime)
2212 .Case("strfmon", FST_Strfmon)
2213 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2214 .Default(FST_Unknown);
2217 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2218 /// functions) for correct use of format strings.
2219 /// Returns true if a format string has been fully checked.
2220 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2221 ArrayRef<const Expr *> Args,
2223 VariadicCallType CallType,
2224 SourceLocation Loc, SourceRange Range,
2225 llvm::SmallBitVector &CheckedVarArgs) {
2226 FormatStringInfo FSI;
2227 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2228 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2229 FSI.FirstDataArg, GetFormatStringType(Format),
2230 CallType, Loc, Range, CheckedVarArgs);
2234 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2235 bool HasVAListArg, unsigned format_idx,
2236 unsigned firstDataArg, FormatStringType Type,
2237 VariadicCallType CallType,
2238 SourceLocation Loc, SourceRange Range,
2239 llvm::SmallBitVector &CheckedVarArgs) {
2240 // CHECK: printf/scanf-like function is called with no format string.
2241 if (format_idx >= Args.size()) {
2242 Diag(Loc, diag::warn_missing_format_string) << Range;
2246 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2248 // CHECK: format string is not a string literal.
2250 // Dynamically generated format strings are difficult to
2251 // automatically vet at compile time. Requiring that format strings
2252 // are string literals: (1) permits the checking of format strings by
2253 // the compiler and thereby (2) can practically remove the source of
2254 // many format string exploits.
2256 // Format string can be either ObjC string (e.g. @"%d") or
2257 // C string (e.g. "%d")
2258 // ObjC string uses the same format specifiers as C string, so we can use
2259 // the same format string checking logic for both ObjC and C strings.
2260 StringLiteralCheckType CT =
2261 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2262 format_idx, firstDataArg, Type, CallType,
2263 /*IsFunctionCall*/true, CheckedVarArgs);
2264 if (CT != SLCT_NotALiteral)
2265 // Literal format string found, check done!
2266 return CT == SLCT_CheckedLiteral;
2268 // Strftime is particular as it always uses a single 'time' argument,
2269 // so it is safe to pass a non-literal string.
2270 if (Type == FST_Strftime)
2273 // Do not emit diag when the string param is a macro expansion and the
2274 // format is either NSString or CFString. This is a hack to prevent
2275 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2276 // which are usually used in place of NS and CF string literals.
2277 if (Type == FST_NSString &&
2278 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2281 // If there are no arguments specified, warn with -Wformat-security, otherwise
2282 // warn only with -Wformat-nonliteral.
2283 if (Args.size() == firstDataArg)
2284 Diag(Args[format_idx]->getLocStart(),
2285 diag::warn_format_nonliteral_noargs)
2286 << OrigFormatExpr->getSourceRange();
2288 Diag(Args[format_idx]->getLocStart(),
2289 diag::warn_format_nonliteral)
2290 << OrigFormatExpr->getSourceRange();
2295 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2298 const StringLiteral *FExpr;
2299 const Expr *OrigFormatExpr;
2300 const unsigned FirstDataArg;
2301 const unsigned NumDataArgs;
2302 const char *Beg; // Start of format string.
2303 const bool HasVAListArg;
2304 ArrayRef<const Expr *> Args;
2306 llvm::SmallBitVector CoveredArgs;
2307 bool usesPositionalArgs;
2309 bool inFunctionCall;
2310 Sema::VariadicCallType CallType;
2311 llvm::SmallBitVector &CheckedVarArgs;
2313 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2314 const Expr *origFormatExpr, unsigned firstDataArg,
2315 unsigned numDataArgs, const char *beg, bool hasVAListArg,
2316 ArrayRef<const Expr *> Args,
2317 unsigned formatIdx, bool inFunctionCall,
2318 Sema::VariadicCallType callType,
2319 llvm::SmallBitVector &CheckedVarArgs)
2320 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2321 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2322 Beg(beg), HasVAListArg(hasVAListArg),
2323 Args(Args), FormatIdx(formatIdx),
2324 usesPositionalArgs(false), atFirstArg(true),
2325 inFunctionCall(inFunctionCall), CallType(callType),
2326 CheckedVarArgs(CheckedVarArgs) {
2327 CoveredArgs.resize(numDataArgs);
2328 CoveredArgs.reset();
2331 void DoneProcessing();
2333 void HandleIncompleteSpecifier(const char *startSpecifier,
2334 unsigned specifierLen);
2336 void HandleInvalidLengthModifier(
2337 const analyze_format_string::FormatSpecifier &FS,
2338 const analyze_format_string::ConversionSpecifier &CS,
2339 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
2341 void HandleNonStandardLengthModifier(
2342 const analyze_format_string::FormatSpecifier &FS,
2343 const char *startSpecifier, unsigned specifierLen);
2345 void HandleNonStandardConversionSpecifier(
2346 const analyze_format_string::ConversionSpecifier &CS,
2347 const char *startSpecifier, unsigned specifierLen);
2349 virtual void HandlePosition(const char *startPos, unsigned posLen);
2351 virtual void HandleInvalidPosition(const char *startSpecifier,
2352 unsigned specifierLen,
2353 analyze_format_string::PositionContext p);
2355 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2357 void HandleNullChar(const char *nullCharacter);
2359 template <typename Range>
2360 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2361 const Expr *ArgumentExpr,
2362 PartialDiagnostic PDiag,
2363 SourceLocation StringLoc,
2364 bool IsStringLocation, Range StringRange,
2365 ArrayRef<FixItHint> Fixit = None);
2368 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2369 const char *startSpec,
2370 unsigned specifierLen,
2371 const char *csStart, unsigned csLen);
2373 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2374 const char *startSpec,
2375 unsigned specifierLen);
2377 SourceRange getFormatStringRange();
2378 CharSourceRange getSpecifierRange(const char *startSpecifier,
2379 unsigned specifierLen);
2380 SourceLocation getLocationOfByte(const char *x);
2382 const Expr *getDataArg(unsigned i) const;
2384 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2385 const analyze_format_string::ConversionSpecifier &CS,
2386 const char *startSpecifier, unsigned specifierLen,
2389 template <typename Range>
2390 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2391 bool IsStringLocation, Range StringRange,
2392 ArrayRef<FixItHint> Fixit = None);
2394 void CheckPositionalAndNonpositionalArgs(
2395 const analyze_format_string::FormatSpecifier *FS);
2399 SourceRange CheckFormatHandler::getFormatStringRange() {
2400 return OrigFormatExpr->getSourceRange();
2403 CharSourceRange CheckFormatHandler::
2404 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2405 SourceLocation Start = getLocationOfByte(startSpecifier);
2406 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2408 // Advance the end SourceLocation by one due to half-open ranges.
2409 End = End.getLocWithOffset(1);
2411 return CharSourceRange::getCharRange(Start, End);
2414 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2415 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2418 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2419 unsigned specifierLen){
2420 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2421 getLocationOfByte(startSpecifier),
2422 /*IsStringLocation*/true,
2423 getSpecifierRange(startSpecifier, specifierLen));
2426 void CheckFormatHandler::HandleInvalidLengthModifier(
2427 const analyze_format_string::FormatSpecifier &FS,
2428 const analyze_format_string::ConversionSpecifier &CS,
2429 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2430 using namespace analyze_format_string;
2432 const LengthModifier &LM = FS.getLengthModifier();
2433 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2435 // See if we know how to fix this length modifier.
2436 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2438 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2439 getLocationOfByte(LM.getStart()),
2440 /*IsStringLocation*/true,
2441 getSpecifierRange(startSpecifier, specifierLen));
2443 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2444 << FixedLM->toString()
2445 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2449 if (DiagID == diag::warn_format_nonsensical_length)
2450 Hint = FixItHint::CreateRemoval(LMRange);
2452 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2453 getLocationOfByte(LM.getStart()),
2454 /*IsStringLocation*/true,
2455 getSpecifierRange(startSpecifier, specifierLen),
2460 void CheckFormatHandler::HandleNonStandardLengthModifier(
2461 const analyze_format_string::FormatSpecifier &FS,
2462 const char *startSpecifier, unsigned specifierLen) {
2463 using namespace analyze_format_string;
2465 const LengthModifier &LM = FS.getLengthModifier();
2466 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2468 // See if we know how to fix this length modifier.
2469 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2471 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2472 << LM.toString() << 0,
2473 getLocationOfByte(LM.getStart()),
2474 /*IsStringLocation*/true,
2475 getSpecifierRange(startSpecifier, specifierLen));
2477 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2478 << FixedLM->toString()
2479 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2482 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2483 << LM.toString() << 0,
2484 getLocationOfByte(LM.getStart()),
2485 /*IsStringLocation*/true,
2486 getSpecifierRange(startSpecifier, specifierLen));
2490 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2491 const analyze_format_string::ConversionSpecifier &CS,
2492 const char *startSpecifier, unsigned specifierLen) {
2493 using namespace analyze_format_string;
2495 // See if we know how to fix this conversion specifier.
2496 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2498 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2499 << CS.toString() << /*conversion specifier*/1,
2500 getLocationOfByte(CS.getStart()),
2501 /*IsStringLocation*/true,
2502 getSpecifierRange(startSpecifier, specifierLen));
2504 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2505 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2506 << FixedCS->toString()
2507 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2509 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2510 << CS.toString() << /*conversion specifier*/1,
2511 getLocationOfByte(CS.getStart()),
2512 /*IsStringLocation*/true,
2513 getSpecifierRange(startSpecifier, specifierLen));
2517 void CheckFormatHandler::HandlePosition(const char *startPos,
2519 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2520 getLocationOfByte(startPos),
2521 /*IsStringLocation*/true,
2522 getSpecifierRange(startPos, posLen));
2526 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2527 analyze_format_string::PositionContext p) {
2528 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2530 getLocationOfByte(startPos), /*IsStringLocation*/true,
2531 getSpecifierRange(startPos, posLen));
2534 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2536 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2537 getLocationOfByte(startPos),
2538 /*IsStringLocation*/true,
2539 getSpecifierRange(startPos, posLen));
2542 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2543 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2544 // The presence of a null character is likely an error.
2545 EmitFormatDiagnostic(
2546 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2547 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2548 getFormatStringRange());
2552 // Note that this may return NULL if there was an error parsing or building
2553 // one of the argument expressions.
2554 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2555 return Args[FirstDataArg + i];
2558 void CheckFormatHandler::DoneProcessing() {
2559 // Does the number of data arguments exceed the number of
2560 // format conversions in the format string?
2561 if (!HasVAListArg) {
2562 // Find any arguments that weren't covered.
2564 signed notCoveredArg = CoveredArgs.find_first();
2565 if (notCoveredArg >= 0) {
2566 assert((unsigned)notCoveredArg < NumDataArgs);
2567 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2568 SourceLocation Loc = E->getLocStart();
2569 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2570 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2571 Loc, /*IsStringLocation*/false,
2572 getFormatStringRange());
2580 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2582 const char *startSpec,
2583 unsigned specifierLen,
2584 const char *csStart,
2587 bool keepGoing = true;
2588 if (argIndex < NumDataArgs) {
2589 // Consider the argument coverered, even though the specifier doesn't
2591 CoveredArgs.set(argIndex);
2594 // If argIndex exceeds the number of data arguments we
2595 // don't issue a warning because that is just a cascade of warnings (and
2596 // they may have intended '%%' anyway). We don't want to continue processing
2597 // the format string after this point, however, as we will like just get
2598 // gibberish when trying to match arguments.
2602 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2603 << StringRef(csStart, csLen),
2604 Loc, /*IsStringLocation*/true,
2605 getSpecifierRange(startSpec, specifierLen));
2611 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2612 const char *startSpec,
2613 unsigned specifierLen) {
2614 EmitFormatDiagnostic(
2615 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2616 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2620 CheckFormatHandler::CheckNumArgs(
2621 const analyze_format_string::FormatSpecifier &FS,
2622 const analyze_format_string::ConversionSpecifier &CS,
2623 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2625 if (argIndex >= NumDataArgs) {
2626 PartialDiagnostic PDiag = FS.usesPositionalArg()
2627 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2628 << (argIndex+1) << NumDataArgs)
2629 : S.PDiag(diag::warn_printf_insufficient_data_args);
2630 EmitFormatDiagnostic(
2631 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2632 getSpecifierRange(startSpecifier, specifierLen));
2638 template<typename Range>
2639 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2641 bool IsStringLocation,
2643 ArrayRef<FixItHint> FixIt) {
2644 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2645 Loc, IsStringLocation, StringRange, FixIt);
2648 /// \brief If the format string is not within the funcion call, emit a note
2649 /// so that the function call and string are in diagnostic messages.
2651 /// \param InFunctionCall if true, the format string is within the function
2652 /// call and only one diagnostic message will be produced. Otherwise, an
2653 /// extra note will be emitted pointing to location of the format string.
2655 /// \param ArgumentExpr the expression that is passed as the format string
2656 /// argument in the function call. Used for getting locations when two
2657 /// diagnostics are emitted.
2659 /// \param PDiag the callee should already have provided any strings for the
2660 /// diagnostic message. This function only adds locations and fixits
2663 /// \param Loc primary location for diagnostic. If two diagnostics are
2664 /// required, one will be at Loc and a new SourceLocation will be created for
2667 /// \param IsStringLocation if true, Loc points to the format string should be
2668 /// used for the note. Otherwise, Loc points to the argument list and will
2669 /// be used with PDiag.
2671 /// \param StringRange some or all of the string to highlight. This is
2672 /// templated so it can accept either a CharSourceRange or a SourceRange.
2674 /// \param FixIt optional fix it hint for the format string.
2675 template<typename Range>
2676 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2677 const Expr *ArgumentExpr,
2678 PartialDiagnostic PDiag,
2680 bool IsStringLocation,
2682 ArrayRef<FixItHint> FixIt) {
2683 if (InFunctionCall) {
2684 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2686 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2691 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2692 << ArgumentExpr->getSourceRange();
2694 const Sema::SemaDiagnosticBuilder &Note =
2695 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2696 diag::note_format_string_defined);
2698 Note << StringRange;
2699 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2706 //===--- CHECK: Printf format string checking ------------------------------===//
2709 class CheckPrintfHandler : public CheckFormatHandler {
2712 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2713 const Expr *origFormatExpr, unsigned firstDataArg,
2714 unsigned numDataArgs, bool isObjC,
2715 const char *beg, bool hasVAListArg,
2716 ArrayRef<const Expr *> Args,
2717 unsigned formatIdx, bool inFunctionCall,
2718 Sema::VariadicCallType CallType,
2719 llvm::SmallBitVector &CheckedVarArgs)
2720 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2721 numDataArgs, beg, hasVAListArg, Args,
2722 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2727 bool HandleInvalidPrintfConversionSpecifier(
2728 const analyze_printf::PrintfSpecifier &FS,
2729 const char *startSpecifier,
2730 unsigned specifierLen);
2732 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2733 const char *startSpecifier,
2734 unsigned specifierLen);
2735 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2736 const char *StartSpecifier,
2737 unsigned SpecifierLen,
2740 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2741 const char *startSpecifier, unsigned specifierLen);
2742 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2743 const analyze_printf::OptionalAmount &Amt,
2745 const char *startSpecifier, unsigned specifierLen);
2746 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2747 const analyze_printf::OptionalFlag &flag,
2748 const char *startSpecifier, unsigned specifierLen);
2749 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2750 const analyze_printf::OptionalFlag &ignoredFlag,
2751 const analyze_printf::OptionalFlag &flag,
2752 const char *startSpecifier, unsigned specifierLen);
2753 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2754 const Expr *E, const CharSourceRange &CSR);
2759 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2760 const analyze_printf::PrintfSpecifier &FS,
2761 const char *startSpecifier,
2762 unsigned specifierLen) {
2763 const analyze_printf::PrintfConversionSpecifier &CS =
2764 FS.getConversionSpecifier();
2766 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2767 getLocationOfByte(CS.getStart()),
2768 startSpecifier, specifierLen,
2769 CS.getStart(), CS.getLength());
2772 bool CheckPrintfHandler::HandleAmount(
2773 const analyze_format_string::OptionalAmount &Amt,
2774 unsigned k, const char *startSpecifier,
2775 unsigned specifierLen) {
2777 if (Amt.hasDataArgument()) {
2778 if (!HasVAListArg) {
2779 unsigned argIndex = Amt.getArgIndex();
2780 if (argIndex >= NumDataArgs) {
2781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2783 getLocationOfByte(Amt.getStart()),
2784 /*IsStringLocation*/true,
2785 getSpecifierRange(startSpecifier, specifierLen));
2786 // Don't do any more checking. We will just emit
2791 // Type check the data argument. It should be an 'int'.
2792 // Although not in conformance with C99, we also allow the argument to be
2793 // an 'unsigned int' as that is a reasonably safe case. GCC also
2794 // doesn't emit a warning for that case.
2795 CoveredArgs.set(argIndex);
2796 const Expr *Arg = getDataArg(argIndex);
2800 QualType T = Arg->getType();
2802 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2803 assert(AT.isValid());
2805 if (!AT.matchesType(S.Context, T)) {
2806 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2807 << k << AT.getRepresentativeTypeName(S.Context)
2808 << T << Arg->getSourceRange(),
2809 getLocationOfByte(Amt.getStart()),
2810 /*IsStringLocation*/true,
2811 getSpecifierRange(startSpecifier, specifierLen));
2812 // Don't do any more checking. We will just emit
2821 void CheckPrintfHandler::HandleInvalidAmount(
2822 const analyze_printf::PrintfSpecifier &FS,
2823 const analyze_printf::OptionalAmount &Amt,
2825 const char *startSpecifier,
2826 unsigned specifierLen) {
2827 const analyze_printf::PrintfConversionSpecifier &CS =
2828 FS.getConversionSpecifier();
2831 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2832 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2833 Amt.getConstantLength()))
2836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2837 << type << CS.toString(),
2838 getLocationOfByte(Amt.getStart()),
2839 /*IsStringLocation*/true,
2840 getSpecifierRange(startSpecifier, specifierLen),
2844 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2845 const analyze_printf::OptionalFlag &flag,
2846 const char *startSpecifier,
2847 unsigned specifierLen) {
2848 // Warn about pointless flag with a fixit removal.
2849 const analyze_printf::PrintfConversionSpecifier &CS =
2850 FS.getConversionSpecifier();
2851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2852 << flag.toString() << CS.toString(),
2853 getLocationOfByte(flag.getPosition()),
2854 /*IsStringLocation*/true,
2855 getSpecifierRange(startSpecifier, specifierLen),
2856 FixItHint::CreateRemoval(
2857 getSpecifierRange(flag.getPosition(), 1)));
2860 void CheckPrintfHandler::HandleIgnoredFlag(
2861 const analyze_printf::PrintfSpecifier &FS,
2862 const analyze_printf::OptionalFlag &ignoredFlag,
2863 const analyze_printf::OptionalFlag &flag,
2864 const char *startSpecifier,
2865 unsigned specifierLen) {
2866 // Warn about ignored flag with a fixit removal.
2867 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2868 << ignoredFlag.toString() << flag.toString(),
2869 getLocationOfByte(ignoredFlag.getPosition()),
2870 /*IsStringLocation*/true,
2871 getSpecifierRange(startSpecifier, specifierLen),
2872 FixItHint::CreateRemoval(
2873 getSpecifierRange(ignoredFlag.getPosition(), 1)));
2876 // Determines if the specified is a C++ class or struct containing
2877 // a member with the specified name and kind (e.g. a CXXMethodDecl named
2879 template<typename MemberKind>
2880 static llvm::SmallPtrSet<MemberKind*, 1>
2881 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2882 const RecordType *RT = Ty->getAs<RecordType>();
2883 llvm::SmallPtrSet<MemberKind*, 1> Results;
2887 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2891 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2892 Sema::LookupMemberName);
2894 // We just need to include all members of the right kind turned up by the
2895 // filter, at this point.
2896 if (S.LookupQualifiedName(R, RT->getDecl()))
2897 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2898 NamedDecl *decl = (*I)->getUnderlyingDecl();
2899 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2905 // Check if a (w)string was passed when a (w)char* was needed, and offer a
2906 // better diagnostic if so. AT is assumed to be valid.
2907 // Returns true when a c_str() conversion method is found.
2908 bool CheckPrintfHandler::checkForCStrMembers(
2909 const analyze_printf::ArgType &AT, const Expr *E,
2910 const CharSourceRange &CSR) {
2911 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2914 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2916 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2918 const CXXMethodDecl *Method = *MI;
2919 if (Method->getNumParams() == 0 &&
2920 AT.matchesType(S.Context, Method->getResultType())) {
2921 // FIXME: Suggest parens if the expression needs them.
2922 SourceLocation EndLoc =
2923 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2924 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2926 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2935 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2937 const char *startSpecifier,
2938 unsigned specifierLen) {
2940 using namespace analyze_format_string;
2941 using namespace analyze_printf;
2942 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2944 if (FS.consumesDataArgument()) {
2947 usesPositionalArgs = FS.usesPositionalArg();
2949 else if (usesPositionalArgs != FS.usesPositionalArg()) {
2950 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2951 startSpecifier, specifierLen);
2956 // First check if the field width, precision, and conversion specifier
2957 // have matching data arguments.
2958 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2959 startSpecifier, specifierLen)) {
2963 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2964 startSpecifier, specifierLen)) {
2968 if (!CS.consumesDataArgument()) {
2969 // FIXME: Technically specifying a precision or field width here
2970 // makes no sense. Worth issuing a warning at some point.
2974 // Consume the argument.
2975 unsigned argIndex = FS.getArgIndex();
2976 if (argIndex < NumDataArgs) {
2977 // The check to see if the argIndex is valid will come later.
2978 // We set the bit here because we may exit early from this
2979 // function if we encounter some other error.
2980 CoveredArgs.set(argIndex);
2983 // FreeBSD extensions
2984 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
2985 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
2986 // claim the second argument
2987 CoveredArgs.set(argIndex + 1);
2989 // Now type check the data expression that matches the
2990 // format specifier.
2991 const Expr *Ex = getDataArg(argIndex);
2992 const analyze_printf::ArgType &AT =
2993 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
2994 ArgType(S.Context.IntTy) : ArgType::CStrTy;
2995 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
2996 S.Diag(getLocationOfByte(CS.getStart()),
2997 diag::warn_printf_conversion_argument_type_mismatch)
2998 << AT.getRepresentativeType(S.Context) << Ex->getType()
2999 << getSpecifierRange(startSpecifier, specifierLen)
3000 << Ex->getSourceRange();
3002 // Now type check the data expression that matches the
3003 // format specifier.
3004 Ex = getDataArg(argIndex + 1);
3005 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3006 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3007 S.Diag(getLocationOfByte(CS.getStart()),
3008 diag::warn_printf_conversion_argument_type_mismatch)
3009 << AT2.getRepresentativeType(S.Context) << Ex->getType()
3010 << getSpecifierRange(startSpecifier, specifierLen)
3011 << Ex->getSourceRange();
3015 // END OF FREEBSD EXTENSIONS
3017 // Check for using an Objective-C specific conversion specifier
3018 // in a non-ObjC literal.
3019 if (!ObjCContext && CS.isObjCArg()) {
3020 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3024 // Check for invalid use of field width
3025 if (!FS.hasValidFieldWidth()) {
3026 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3027 startSpecifier, specifierLen);
3030 // Check for invalid use of precision
3031 if (!FS.hasValidPrecision()) {
3032 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3033 startSpecifier, specifierLen);
3036 // Check each flag does not conflict with any other component.
3037 if (!FS.hasValidThousandsGroupingPrefix())
3038 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3039 if (!FS.hasValidLeadingZeros())
3040 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3041 if (!FS.hasValidPlusPrefix())
3042 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3043 if (!FS.hasValidSpacePrefix())
3044 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3045 if (!FS.hasValidAlternativeForm())
3046 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3047 if (!FS.hasValidLeftJustified())
3048 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3050 // Check that flags are not ignored by another flag
3051 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3052 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3053 startSpecifier, specifierLen);
3054 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3055 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3056 startSpecifier, specifierLen);
3058 // Check the length modifier is valid with the given conversion specifier.
3059 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3060 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3061 diag::warn_format_nonsensical_length);
3062 else if (!FS.hasStandardLengthModifier())
3063 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3064 else if (!FS.hasStandardLengthConversionCombination())
3065 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3066 diag::warn_format_non_standard_conversion_spec);
3068 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3069 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3071 // The remaining checks depend on the data arguments.
3075 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3078 const Expr *Arg = getDataArg(argIndex);
3082 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3085 static bool requiresParensToAddCast(const Expr *E) {
3086 // FIXME: We should have a general way to reason about operator
3087 // precedence and whether parens are actually needed here.
3088 // Take care of a few common cases where they aren't.
3089 const Expr *Inside = E->IgnoreImpCasts();
3090 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3091 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3093 switch (Inside->getStmtClass()) {
3094 case Stmt::ArraySubscriptExprClass:
3095 case Stmt::CallExprClass:
3096 case Stmt::CharacterLiteralClass:
3097 case Stmt::CXXBoolLiteralExprClass:
3098 case Stmt::DeclRefExprClass:
3099 case Stmt::FloatingLiteralClass:
3100 case Stmt::IntegerLiteralClass:
3101 case Stmt::MemberExprClass:
3102 case Stmt::ObjCArrayLiteralClass:
3103 case Stmt::ObjCBoolLiteralExprClass:
3104 case Stmt::ObjCBoxedExprClass:
3105 case Stmt::ObjCDictionaryLiteralClass:
3106 case Stmt::ObjCEncodeExprClass:
3107 case Stmt::ObjCIvarRefExprClass:
3108 case Stmt::ObjCMessageExprClass:
3109 case Stmt::ObjCPropertyRefExprClass:
3110 case Stmt::ObjCStringLiteralClass:
3111 case Stmt::ObjCSubscriptRefExprClass:
3112 case Stmt::ParenExprClass:
3113 case Stmt::StringLiteralClass:
3114 case Stmt::UnaryOperatorClass:
3122 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3123 const char *StartSpecifier,
3124 unsigned SpecifierLen,
3126 using namespace analyze_format_string;
3127 using namespace analyze_printf;
3128 // Now type check the data expression that matches the
3129 // format specifier.
3130 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3135 QualType ExprTy = E->getType();
3136 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3137 ExprTy = TET->getUnderlyingExpr()->getType();
3140 if (AT.matchesType(S.Context, ExprTy))
3143 // Look through argument promotions for our error message's reported type.
3144 // This includes the integral and floating promotions, but excludes array
3145 // and function pointer decay; seeing that an argument intended to be a
3146 // string has type 'char [6]' is probably more confusing than 'char *'.
3147 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3148 if (ICE->getCastKind() == CK_IntegralCast ||
3149 ICE->getCastKind() == CK_FloatingCast) {
3150 E = ICE->getSubExpr();
3151 ExprTy = E->getType();
3153 // Check if we didn't match because of an implicit cast from a 'char'
3154 // or 'short' to an 'int'. This is done because printf is a varargs
3156 if (ICE->getType() == S.Context.IntTy ||
3157 ICE->getType() == S.Context.UnsignedIntTy) {
3158 // All further checking is done on the subexpression.
3159 if (AT.matchesType(S.Context, ExprTy))
3163 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3164 // Special case for 'a', which has type 'int' in C.
3165 // Note, however, that we do /not/ want to treat multibyte constants like
3166 // 'MooV' as characters! This form is deprecated but still exists.
3167 if (ExprTy == S.Context.IntTy)
3168 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3169 ExprTy = S.Context.CharTy;
3172 // %C in an Objective-C context prints a unichar, not a wchar_t.
3173 // If the argument is an integer of some kind, believe the %C and suggest
3174 // a cast instead of changing the conversion specifier.
3175 QualType IntendedTy = ExprTy;
3177 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3178 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3179 !ExprTy->isCharType()) {
3180 // 'unichar' is defined as a typedef of unsigned short, but we should
3181 // prefer using the typedef if it is visible.
3182 IntendedTy = S.Context.UnsignedShortTy;
3184 // While we are here, check if the value is an IntegerLiteral that happens
3185 // to be within the valid range.
3186 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3187 const llvm::APInt &V = IL->getValue();
3188 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3192 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3193 Sema::LookupOrdinaryName);
3194 if (S.LookupName(Result, S.getCurScope())) {
3195 NamedDecl *ND = Result.getFoundDecl();
3196 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3197 if (TD->getUnderlyingType() == IntendedTy)
3198 IntendedTy = S.Context.getTypedefType(TD);
3203 // Special-case some of Darwin's platform-independence types by suggesting
3204 // casts to primitive types that are known to be large enough.
3205 bool ShouldNotPrintDirectly = false;
3206 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3207 // Use a 'while' to peel off layers of typedefs.
3208 QualType TyTy = IntendedTy;
3209 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3210 StringRef Name = UserTy->getDecl()->getName();
3211 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3212 .Case("NSInteger", S.Context.LongTy)
3213 .Case("NSUInteger", S.Context.UnsignedLongTy)
3214 .Case("SInt32", S.Context.IntTy)
3215 .Case("UInt32", S.Context.UnsignedIntTy)
3216 .Default(QualType());
3218 if (!CastTy.isNull()) {
3219 ShouldNotPrintDirectly = true;
3220 IntendedTy = CastTy;
3223 TyTy = UserTy->desugar();
3227 // We may be able to offer a FixItHint if it is a supported type.
3228 PrintfSpecifier fixedFS = FS;
3229 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3230 S.Context, ObjCContext);
3233 // Get the fix string from the fixed format specifier
3234 SmallString<16> buf;
3235 llvm::raw_svector_ostream os(buf);
3236 fixedFS.toString(os);
3238 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3240 if (IntendedTy == ExprTy) {
3241 // In this case, the specifier is wrong and should be changed to match
3243 EmitFormatDiagnostic(
3244 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3245 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3246 << E->getSourceRange(),
3248 /*IsStringLocation*/false,
3250 FixItHint::CreateReplacement(SpecRange, os.str()));
3253 // The canonical type for formatting this value is different from the
3254 // actual type of the expression. (This occurs, for example, with Darwin's
3255 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3256 // should be printed as 'long' for 64-bit compatibility.)
3257 // Rather than emitting a normal format/argument mismatch, we want to
3258 // add a cast to the recommended type (and correct the format string
3260 SmallString<16> CastBuf;
3261 llvm::raw_svector_ostream CastFix(CastBuf);
3263 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3266 SmallVector<FixItHint,4> Hints;
3267 if (!AT.matchesType(S.Context, IntendedTy))
3268 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3270 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3271 // If there's already a cast present, just replace it.
3272 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3273 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3275 } else if (!requiresParensToAddCast(E)) {
3276 // If the expression has high enough precedence,
3277 // just write the C-style cast.
3278 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3281 // Otherwise, add parens around the expression as well as the cast.
3283 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3286 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3287 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3290 if (ShouldNotPrintDirectly) {
3291 // The expression has a type that should not be printed directly.
3292 // We extract the name from the typedef because we don't want to show
3293 // the underlying type in the diagnostic.
3294 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
3296 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3297 << Name << IntendedTy
3298 << E->getSourceRange(),
3299 E->getLocStart(), /*IsStringLocation=*/false,
3302 // In this case, the expression could be printed using a different
3303 // specifier, but we've decided that the specifier is probably correct
3304 // and we should cast instead. Just use the normal warning message.
3305 EmitFormatDiagnostic(
3306 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3307 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3308 << E->getSourceRange(),
3309 E->getLocStart(), /*IsStringLocation*/false,
3314 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3316 // Since the warning for passing non-POD types to variadic functions
3317 // was deferred until now, we emit a warning for non-POD
3319 switch (S.isValidVarArgType(ExprTy)) {
3320 case Sema::VAK_Valid:
3321 case Sema::VAK_ValidInCXX11:
3322 EmitFormatDiagnostic(
3323 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3324 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3326 << E->getSourceRange(),
3327 E->getLocStart(), /*IsStringLocation*/false, CSR);
3330 case Sema::VAK_Undefined:
3331 EmitFormatDiagnostic(
3332 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3333 << S.getLangOpts().CPlusPlus11
3336 << AT.getRepresentativeTypeName(S.Context)
3338 << E->getSourceRange(),
3339 E->getLocStart(), /*IsStringLocation*/false, CSR);
3340 checkForCStrMembers(AT, E, CSR);
3343 case Sema::VAK_Invalid:
3344 if (ExprTy->isObjCObjectType())
3345 EmitFormatDiagnostic(
3346 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3347 << S.getLangOpts().CPlusPlus11
3350 << AT.getRepresentativeTypeName(S.Context)
3352 << E->getSourceRange(),
3353 E->getLocStart(), /*IsStringLocation*/false, CSR);
3355 // FIXME: If this is an initializer list, suggest removing the braces
3356 // or inserting a cast to the target type.
3357 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3358 << isa<InitListExpr>(E) << ExprTy << CallType
3359 << AT.getRepresentativeTypeName(S.Context)
3360 << E->getSourceRange();
3364 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3365 "format string specifier index out of range");
3366 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3372 //===--- CHECK: Scanf format string checking ------------------------------===//
3375 class CheckScanfHandler : public CheckFormatHandler {
3377 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3378 const Expr *origFormatExpr, unsigned firstDataArg,
3379 unsigned numDataArgs, const char *beg, bool hasVAListArg,
3380 ArrayRef<const Expr *> Args,
3381 unsigned formatIdx, bool inFunctionCall,
3382 Sema::VariadicCallType CallType,
3383 llvm::SmallBitVector &CheckedVarArgs)
3384 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3385 numDataArgs, beg, hasVAListArg,
3386 Args, formatIdx, inFunctionCall, CallType,
3390 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3391 const char *startSpecifier,
3392 unsigned specifierLen);
3394 bool HandleInvalidScanfConversionSpecifier(
3395 const analyze_scanf::ScanfSpecifier &FS,
3396 const char *startSpecifier,
3397 unsigned specifierLen);
3399 void HandleIncompleteScanList(const char *start, const char *end);
3403 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3405 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3406 getLocationOfByte(end), /*IsStringLocation*/true,
3407 getSpecifierRange(start, end - start));
3410 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3411 const analyze_scanf::ScanfSpecifier &FS,
3412 const char *startSpecifier,
3413 unsigned specifierLen) {
3415 const analyze_scanf::ScanfConversionSpecifier &CS =
3416 FS.getConversionSpecifier();
3418 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3419 getLocationOfByte(CS.getStart()),
3420 startSpecifier, specifierLen,
3421 CS.getStart(), CS.getLength());
3424 bool CheckScanfHandler::HandleScanfSpecifier(
3425 const analyze_scanf::ScanfSpecifier &FS,
3426 const char *startSpecifier,
3427 unsigned specifierLen) {
3429 using namespace analyze_scanf;
3430 using namespace analyze_format_string;
3432 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3434 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3435 // be used to decide if we are using positional arguments consistently.
3436 if (FS.consumesDataArgument()) {
3439 usesPositionalArgs = FS.usesPositionalArg();
3441 else if (usesPositionalArgs != FS.usesPositionalArg()) {
3442 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3443 startSpecifier, specifierLen);
3448 // Check if the field with is non-zero.
3449 const OptionalAmount &Amt = FS.getFieldWidth();
3450 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3451 if (Amt.getConstantAmount() == 0) {
3452 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3453 Amt.getConstantLength());
3454 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3455 getLocationOfByte(Amt.getStart()),
3456 /*IsStringLocation*/true, R,
3457 FixItHint::CreateRemoval(R));
3461 if (!FS.consumesDataArgument()) {
3462 // FIXME: Technically specifying a precision or field width here
3463 // makes no sense. Worth issuing a warning at some point.
3467 // Consume the argument.
3468 unsigned argIndex = FS.getArgIndex();
3469 if (argIndex < NumDataArgs) {
3470 // The check to see if the argIndex is valid will come later.
3471 // We set the bit here because we may exit early from this
3472 // function if we encounter some other error.
3473 CoveredArgs.set(argIndex);
3476 // Check the length modifier is valid with the given conversion specifier.
3477 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3478 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3479 diag::warn_format_nonsensical_length);
3480 else if (!FS.hasStandardLengthModifier())
3481 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3482 else if (!FS.hasStandardLengthConversionCombination())
3483 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3484 diag::warn_format_non_standard_conversion_spec);
3486 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3487 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3489 // The remaining checks depend on the data arguments.
3493 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3496 // Check that the argument type matches the format specifier.
3497 const Expr *Ex = getDataArg(argIndex);
3501 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3502 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3503 ScanfSpecifier fixedFS = FS;
3504 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3508 // Get the fix string from the fixed format specifier.
3509 SmallString<128> buf;
3510 llvm::raw_svector_ostream os(buf);
3511 fixedFS.toString(os);
3513 EmitFormatDiagnostic(
3514 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3515 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3516 << Ex->getSourceRange(),
3518 /*IsStringLocation*/false,
3519 getSpecifierRange(startSpecifier, specifierLen),
3520 FixItHint::CreateReplacement(
3521 getSpecifierRange(startSpecifier, specifierLen),
3524 EmitFormatDiagnostic(
3525 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3526 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3527 << Ex->getSourceRange(),
3529 /*IsStringLocation*/false,
3530 getSpecifierRange(startSpecifier, specifierLen));
3537 void Sema::CheckFormatString(const StringLiteral *FExpr,
3538 const Expr *OrigFormatExpr,
3539 ArrayRef<const Expr *> Args,
3540 bool HasVAListArg, unsigned format_idx,
3541 unsigned firstDataArg, FormatStringType Type,
3542 bool inFunctionCall, VariadicCallType CallType,
3543 llvm::SmallBitVector &CheckedVarArgs) {
3545 // CHECK: is the format string a wide literal?
3546 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3547 CheckFormatHandler::EmitFormatDiagnostic(
3548 *this, inFunctionCall, Args[format_idx],
3549 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3550 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3554 // Str - The format string. NOTE: this is NOT null-terminated!
3555 StringRef StrRef = FExpr->getString();
3556 const char *Str = StrRef.data();
3557 unsigned StrLen = StrRef.size();
3558 const unsigned numDataArgs = Args.size() - firstDataArg;
3560 // CHECK: empty format string?
3561 if (StrLen == 0 && numDataArgs > 0) {
3562 CheckFormatHandler::EmitFormatDiagnostic(
3563 *this, inFunctionCall, Args[format_idx],
3564 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3565 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3569 if (Type == FST_Printf || Type == FST_NSString) {
3570 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3571 numDataArgs, (Type == FST_NSString),
3572 Str, HasVAListArg, Args, format_idx,
3573 inFunctionCall, CallType, CheckedVarArgs);
3575 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3577 Context.getTargetInfo()))
3579 } else if (Type == FST_Scanf) {
3580 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3581 Str, HasVAListArg, Args, format_idx,
3582 inFunctionCall, CallType, CheckedVarArgs);
3584 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3586 Context.getTargetInfo()))
3588 } // TODO: handle other formats
3591 //===--- CHECK: Standard memory functions ---------------------------------===//
3593 /// \brief Determine whether the given type is a dynamic class type (e.g.,
3594 /// whether it has a vtable).
3595 static bool isDynamicClassType(QualType T) {
3596 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3597 if (CXXRecordDecl *Definition = Record->getDefinition())
3598 if (Definition->isDynamicClass())
3604 /// \brief If E is a sizeof expression, returns its argument expression,
3605 /// otherwise returns NULL.
3606 static const Expr *getSizeOfExprArg(const Expr* E) {
3607 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3608 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3609 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3610 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3615 /// \brief If E is a sizeof expression, returns its argument type.
3616 static QualType getSizeOfArgType(const Expr* E) {
3617 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3618 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3619 if (SizeOf->getKind() == clang::UETT_SizeOf)
3620 return SizeOf->getTypeOfArgument();
3625 /// \brief Check for dangerous or invalid arguments to memset().
3627 /// This issues warnings on known problematic, dangerous or unspecified
3628 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3631 /// \param Call The call expression to diagnose.
3632 void Sema::CheckMemaccessArguments(const CallExpr *Call,
3634 IdentifierInfo *FnName) {
3637 // It is possible to have a non-standard definition of memset. Validate
3638 // we have enough arguments, and if not, abort further checking.
3639 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
3640 if (Call->getNumArgs() < ExpectedNumArgs)
3643 unsigned LastArg = (BId == Builtin::BImemset ||
3644 BId == Builtin::BIstrndup ? 1 : 2);
3645 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
3646 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
3648 // We have special checking when the length is a sizeof expression.
3649 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3650 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3651 llvm::FoldingSetNodeID SizeOfArgID;
3653 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3654 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
3655 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
3657 QualType DestTy = Dest->getType();
3658 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3659 QualType PointeeTy = DestPtrTy->getPointeeType();
3661 // Never warn about void type pointers. This can be used to suppress
3663 if (PointeeTy->isVoidType())
3666 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3667 // actually comparing the expressions for equality. Because computing the
3668 // expression IDs can be expensive, we only do this if the diagnostic is
3671 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3672 SizeOfArg->getExprLoc())) {
3673 // We only compute IDs for expressions if the warning is enabled, and
3674 // cache the sizeof arg's ID.
3675 if (SizeOfArgID == llvm::FoldingSetNodeID())
3676 SizeOfArg->Profile(SizeOfArgID, Context, true);
3677 llvm::FoldingSetNodeID DestID;
3678 Dest->Profile(DestID, Context, true);
3679 if (DestID == SizeOfArgID) {
3680 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3681 // over sizeof(src) as well.
3682 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
3683 StringRef ReadableName = FnName->getName();
3685 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
3686 if (UnaryOp->getOpcode() == UO_AddrOf)
3687 ActionIdx = 1; // If its an address-of operator, just remove it.
3688 if (!PointeeTy->isIncompleteType() &&
3689 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
3690 ActionIdx = 2; // If the pointee's size is sizeof(char),
3691 // suggest an explicit length.
3693 // If the function is defined as a builtin macro, do not show macro
3695 SourceLocation SL = SizeOfArg->getExprLoc();
3696 SourceRange DSR = Dest->getSourceRange();
3697 SourceRange SSR = SizeOfArg->getSourceRange();
3698 SourceManager &SM = PP.getSourceManager();
3700 if (SM.isMacroArgExpansion(SL)) {
3701 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3702 SL = SM.getSpellingLoc(SL);
3703 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3704 SM.getSpellingLoc(DSR.getEnd()));
3705 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3706 SM.getSpellingLoc(SSR.getEnd()));
3709 DiagRuntimeBehavior(SL, SizeOfArg,
3710 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
3716 DiagRuntimeBehavior(SL, SizeOfArg,
3717 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3725 // Also check for cases where the sizeof argument is the exact same
3726 // type as the memory argument, and where it points to a user-defined
3728 if (SizeOfArgTy != QualType()) {
3729 if (PointeeTy->isRecordType() &&
3730 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3731 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3732 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3733 << FnName << SizeOfArgTy << ArgIdx
3734 << PointeeTy << Dest->getSourceRange()
3735 << LenExpr->getSourceRange());
3740 // Always complain about dynamic classes.
3741 if (isDynamicClassType(PointeeTy)) {
3743 unsigned OperationType = 0;
3744 // "overwritten" if we're warning about the destination for any call
3745 // but memcmp; otherwise a verb appropriate to the call.
3746 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3747 if (BId == Builtin::BImemcpy)
3749 else if(BId == Builtin::BImemmove)
3751 else if (BId == Builtin::BImemcmp)
3755 DiagRuntimeBehavior(
3756 Dest->getExprLoc(), Dest,
3757 PDiag(diag::warn_dyn_class_memaccess)
3758 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
3759 << FnName << PointeeTy
3761 << Call->getCallee()->getSourceRange());
3762 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3763 BId != Builtin::BImemset)
3764 DiagRuntimeBehavior(
3765 Dest->getExprLoc(), Dest,
3766 PDiag(diag::warn_arc_object_memaccess)
3767 << ArgIdx << FnName << PointeeTy
3768 << Call->getCallee()->getSourceRange());
3772 DiagRuntimeBehavior(
3773 Dest->getExprLoc(), Dest,
3774 PDiag(diag::note_bad_memaccess_silence)
3775 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3781 // A little helper routine: ignore addition and subtraction of integer literals.
3782 // This intentionally does not ignore all integer constant expressions because
3783 // we don't want to remove sizeof().
3784 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3785 Ex = Ex->IgnoreParenCasts();
3788 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3789 if (!BO || !BO->isAdditiveOp())
3792 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3793 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3795 if (isa<IntegerLiteral>(RHS))
3797 else if (isa<IntegerLiteral>(LHS))
3806 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3807 ASTContext &Context) {
3808 // Only handle constant-sized or VLAs, but not flexible members.
3809 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3810 // Only issue the FIXIT for arrays of size > 1.
3811 if (CAT->getSize().getSExtValue() <= 1)
3813 } else if (!Ty->isVariableArrayType()) {
3819 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3820 // be the size of the source, instead of the destination.
3821 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3822 IdentifierInfo *FnName) {
3824 // Don't crash if the user has the wrong number of arguments
3825 if (Call->getNumArgs() != 3)
3828 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3829 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3830 const Expr *CompareWithSrc = NULL;
3832 // Look for 'strlcpy(dst, x, sizeof(x))'
3833 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3834 CompareWithSrc = Ex;
3836 // Look for 'strlcpy(dst, x, strlen(x))'
3837 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
3838 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
3839 && SizeCall->getNumArgs() == 1)
3840 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3844 if (!CompareWithSrc)
3847 // Determine if the argument to sizeof/strlen is equal to the source
3848 // argument. In principle there's all kinds of things you could do
3849 // here, for instance creating an == expression and evaluating it with
3850 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3851 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3855 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3856 if (!CompareWithSrcDRE ||
3857 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3860 const Expr *OriginalSizeArg = Call->getArg(2);
3861 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3862 << OriginalSizeArg->getSourceRange() << FnName;
3864 // Output a FIXIT hint if the destination is an array (rather than a
3865 // pointer to an array). This could be enhanced to handle some
3866 // pointers if we know the actual size, like if DstArg is 'array+2'
3867 // we could say 'sizeof(array)-2'.
3868 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
3869 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
3872 SmallString<128> sizeString;
3873 llvm::raw_svector_ostream OS(sizeString);
3875 DstArg->printPretty(OS, 0, getPrintingPolicy());
3878 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3879 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3883 /// Check if two expressions refer to the same declaration.
3884 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3885 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3886 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3887 return D1->getDecl() == D2->getDecl();
3891 static const Expr *getStrlenExprArg(const Expr *E) {
3892 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3893 const FunctionDecl *FD = CE->getDirectCallee();
3894 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3896 return CE->getArg(0)->IgnoreParenCasts();
3901 // Warn on anti-patterns as the 'size' argument to strncat.
3902 // The correct size argument should look like following:
3903 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3904 void Sema::CheckStrncatArguments(const CallExpr *CE,
3905 IdentifierInfo *FnName) {
3906 // Don't crash if the user has the wrong number of arguments.
3907 if (CE->getNumArgs() < 3)
3909 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3910 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3911 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3913 // Identify common expressions, which are wrongly used as the size argument
3914 // to strncat and may lead to buffer overflows.
3915 unsigned PatternType = 0;
3916 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3918 if (referToTheSameDecl(SizeOfArg, DstArg))
3921 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3923 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3924 if (BE->getOpcode() == BO_Sub) {
3925 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3926 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3927 // - sizeof(dst) - strlen(dst)
3928 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3929 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3931 // - sizeof(src) - (anything)
3932 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3937 if (PatternType == 0)
3940 // Generate the diagnostic.
3941 SourceLocation SL = LenArg->getLocStart();
3942 SourceRange SR = LenArg->getSourceRange();
3943 SourceManager &SM = PP.getSourceManager();
3945 // If the function is defined as a builtin macro, do not show macro expansion.
3946 if (SM.isMacroArgExpansion(SL)) {
3947 SL = SM.getSpellingLoc(SL);
3948 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3949 SM.getSpellingLoc(SR.getEnd()));
3952 // Check if the destination is an array (rather than a pointer to an array).
3953 QualType DstTy = DstArg->getType();
3954 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3956 if (!isKnownSizeArray) {
3957 if (PatternType == 1)
3958 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3960 Diag(SL, diag::warn_strncat_src_size) << SR;
3964 if (PatternType == 1)
3965 Diag(SL, diag::warn_strncat_large_size) << SR;
3967 Diag(SL, diag::warn_strncat_src_size) << SR;
3969 SmallString<128> sizeString;
3970 llvm::raw_svector_ostream OS(sizeString);
3972 DstArg->printPretty(OS, 0, getPrintingPolicy());
3975 DstArg->printPretty(OS, 0, getPrintingPolicy());
3978 Diag(SL, diag::note_strncat_wrong_size)
3979 << FixItHint::CreateReplacement(SR, OS.str());
3982 //===--- CHECK: Return Address of Stack Variable --------------------------===//
3984 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3986 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3989 /// CheckReturnStackAddr - Check if a return statement returns the address
3990 /// of a stack variable.
3992 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3993 SourceLocation ReturnLoc) {
3996 SmallVector<DeclRefExpr *, 8> refVars;
3998 // Perform checking for returned stack addresses, local blocks,
3999 // label addresses or references to temporaries.
4000 if (lhsType->isPointerType() ||
4001 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4002 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
4003 } else if (lhsType->isReferenceType()) {
4004 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
4008 return; // Nothing suspicious was found.
4010 SourceLocation diagLoc;
4011 SourceRange diagRange;
4012 if (refVars.empty()) {
4013 diagLoc = stackE->getLocStart();
4014 diagRange = stackE->getSourceRange();
4016 // We followed through a reference variable. 'stackE' contains the
4017 // problematic expression but we will warn at the return statement pointing
4018 // at the reference variable. We will later display the "trail" of
4019 // reference variables using notes.
4020 diagLoc = refVars[0]->getLocStart();
4021 diagRange = refVars[0]->getSourceRange();
4024 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4025 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4026 : diag::warn_ret_stack_addr)
4027 << DR->getDecl()->getDeclName() << diagRange;
4028 } else if (isa<BlockExpr>(stackE)) { // local block.
4029 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4030 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4031 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4032 } else { // local temporary.
4033 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4034 : diag::warn_ret_local_temp_addr)
4038 // Display the "trail" of reference variables that we followed until we
4039 // found the problematic expression using notes.
4040 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4041 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4042 // If this var binds to another reference var, show the range of the next
4043 // var, otherwise the var binds to the problematic expression, in which case
4044 // show the range of the expression.
4045 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4046 : stackE->getSourceRange();
4047 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4048 << VD->getDeclName() << range;
4052 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4053 /// check if the expression in a return statement evaluates to an address
4054 /// to a location on the stack, a local block, an address of a label, or a
4055 /// reference to local temporary. The recursion is used to traverse the
4056 /// AST of the return expression, with recursion backtracking when we
4057 /// encounter a subexpression that (1) clearly does not lead to one of the
4058 /// above problematic expressions (2) is something we cannot determine leads to
4059 /// a problematic expression based on such local checking.
4061 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
4062 /// the expression that they point to. Such variables are added to the
4063 /// 'refVars' vector so that we know what the reference variable "trail" was.
4065 /// EvalAddr processes expressions that are pointers that are used as
4066 /// references (and not L-values). EvalVal handles all other values.
4067 /// At the base case of the recursion is a check for the above problematic
4070 /// This implementation handles:
4072 /// * pointer-to-pointer casts
4073 /// * implicit conversions from array references to pointers
4074 /// * taking the address of fields
4075 /// * arbitrary interplay between "&" and "*" operators
4076 /// * pointer arithmetic from an address of a stack variable
4077 /// * taking the address of an array element where the array is on the stack
4078 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4080 if (E->isTypeDependent())
4083 // We should only be called for evaluating pointer expressions.
4084 assert((E->getType()->isAnyPointerType() ||
4085 E->getType()->isBlockPointerType() ||
4086 E->getType()->isObjCQualifiedIdType()) &&
4087 "EvalAddr only works on pointers");
4089 E = E->IgnoreParens();
4091 // Our "symbolic interpreter" is just a dispatch off the currently
4092 // viewed AST node. We then recursively traverse the AST by calling
4093 // EvalAddr and EvalVal appropriately.
4094 switch (E->getStmtClass()) {
4095 case Stmt::DeclRefExprClass: {
4096 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4098 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4099 // If this is a reference variable, follow through to the expression that
4101 if (V->hasLocalStorage() &&
4102 V->getType()->isReferenceType() && V->hasInit()) {
4103 // Add the reference variable to the "trail".
4104 refVars.push_back(DR);
4105 return EvalAddr(V->getInit(), refVars, ParentDecl);
4111 case Stmt::UnaryOperatorClass: {
4112 // The only unary operator that make sense to handle here
4113 // is AddrOf. All others don't make sense as pointers.
4114 UnaryOperator *U = cast<UnaryOperator>(E);
4116 if (U->getOpcode() == UO_AddrOf)
4117 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
4122 case Stmt::BinaryOperatorClass: {
4123 // Handle pointer arithmetic. All other binary operators are not valid
4125 BinaryOperator *B = cast<BinaryOperator>(E);
4126 BinaryOperatorKind op = B->getOpcode();
4128 if (op != BO_Add && op != BO_Sub)
4131 Expr *Base = B->getLHS();
4133 // Determine which argument is the real pointer base. It could be
4134 // the RHS argument instead of the LHS.
4135 if (!Base->getType()->isPointerType()) Base = B->getRHS();
4137 assert (Base->getType()->isPointerType());
4138 return EvalAddr(Base, refVars, ParentDecl);
4141 // For conditional operators we need to see if either the LHS or RHS are
4142 // valid DeclRefExpr*s. If one of them is valid, we return it.
4143 case Stmt::ConditionalOperatorClass: {
4144 ConditionalOperator *C = cast<ConditionalOperator>(E);
4146 // Handle the GNU extension for missing LHS.
4147 if (Expr *lhsExpr = C->getLHS()) {
4148 // In C++, we can have a throw-expression, which has 'void' type.
4149 if (!lhsExpr->getType()->isVoidType())
4150 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
4154 // In C++, we can have a throw-expression, which has 'void' type.
4155 if (C->getRHS()->getType()->isVoidType())
4158 return EvalAddr(C->getRHS(), refVars, ParentDecl);
4161 case Stmt::BlockExprClass:
4162 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
4163 return E; // local block.
4166 case Stmt::AddrLabelExprClass:
4167 return E; // address of label.
4169 case Stmt::ExprWithCleanupsClass:
4170 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4173 // For casts, we need to handle conversions from arrays to
4174 // pointer values, and pointer-to-pointer conversions.
4175 case Stmt::ImplicitCastExprClass:
4176 case Stmt::CStyleCastExprClass:
4177 case Stmt::CXXFunctionalCastExprClass:
4178 case Stmt::ObjCBridgedCastExprClass:
4179 case Stmt::CXXStaticCastExprClass:
4180 case Stmt::CXXDynamicCastExprClass:
4181 case Stmt::CXXConstCastExprClass:
4182 case Stmt::CXXReinterpretCastExprClass: {
4183 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4184 switch (cast<CastExpr>(E)->getCastKind()) {
4186 case CK_LValueToRValue:
4188 case CK_BaseToDerived:
4189 case CK_DerivedToBase:
4190 case CK_UncheckedDerivedToBase:
4192 case CK_CPointerToObjCPointerCast:
4193 case CK_BlockPointerToObjCPointerCast:
4194 case CK_AnyPointerToBlockPointerCast:
4195 return EvalAddr(SubExpr, refVars, ParentDecl);
4197 case CK_ArrayToPointerDecay:
4198 return EvalVal(SubExpr, refVars, ParentDecl);
4205 case Stmt::MaterializeTemporaryExprClass:
4206 if (Expr *Result = EvalAddr(
4207 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4208 refVars, ParentDecl))
4213 // Everything else: we simply don't reason about them.
4220 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
4221 /// See the comments for EvalAddr for more details.
4222 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4225 // We should only be called for evaluating non-pointer expressions, or
4226 // expressions with a pointer type that are not used as references but instead
4227 // are l-values (e.g., DeclRefExpr with a pointer type).
4229 // Our "symbolic interpreter" is just a dispatch off the currently
4230 // viewed AST node. We then recursively traverse the AST by calling
4231 // EvalAddr and EvalVal appropriately.
4233 E = E->IgnoreParens();
4234 switch (E->getStmtClass()) {
4235 case Stmt::ImplicitCastExprClass: {
4236 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
4237 if (IE->getValueKind() == VK_LValue) {
4238 E = IE->getSubExpr();
4244 case Stmt::ExprWithCleanupsClass:
4245 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
4247 case Stmt::DeclRefExprClass: {
4248 // When we hit a DeclRefExpr we are looking at code that refers to a
4249 // variable's name. If it's not a reference variable we check if it has
4250 // local storage within the function, and if so, return the expression.
4251 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4253 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4254 // Check if it refers to itself, e.g. "int& i = i;".
4255 if (V == ParentDecl)
4258 if (V->hasLocalStorage()) {
4259 if (!V->getType()->isReferenceType())
4262 // Reference variable, follow through to the expression that
4265 // Add the reference variable to the "trail".
4266 refVars.push_back(DR);
4267 return EvalVal(V->getInit(), refVars, V);
4275 case Stmt::UnaryOperatorClass: {
4276 // The only unary operator that make sense to handle here
4277 // is Deref. All others don't resolve to a "name." This includes
4278 // handling all sorts of rvalues passed to a unary operator.
4279 UnaryOperator *U = cast<UnaryOperator>(E);
4281 if (U->getOpcode() == UO_Deref)
4282 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
4287 case Stmt::ArraySubscriptExprClass: {
4288 // Array subscripts are potential references to data on the stack. We
4289 // retrieve the DeclRefExpr* for the array variable if it indeed
4290 // has local storage.
4291 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
4294 case Stmt::ConditionalOperatorClass: {
4295 // For conditional operators we need to see if either the LHS or RHS are
4296 // non-NULL Expr's. If one is non-NULL, we return it.
4297 ConditionalOperator *C = cast<ConditionalOperator>(E);
4299 // Handle the GNU extension for missing LHS.
4300 if (Expr *lhsExpr = C->getLHS())
4301 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
4304 return EvalVal(C->getRHS(), refVars, ParentDecl);
4307 // Accesses to members are potential references to data on the stack.
4308 case Stmt::MemberExprClass: {
4309 MemberExpr *M = cast<MemberExpr>(E);
4311 // Check for indirect access. We only want direct field accesses.
4315 // Check whether the member type is itself a reference, in which case
4316 // we're not going to refer to the member, but to what the member refers to.
4317 if (M->getMemberDecl()->getType()->isReferenceType())
4320 return EvalVal(M->getBase(), refVars, ParentDecl);
4323 case Stmt::MaterializeTemporaryExprClass:
4324 if (Expr *Result = EvalVal(
4325 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4326 refVars, ParentDecl))
4332 // Check that we don't return or take the address of a reference to a
4333 // temporary. This is only useful in C++.
4334 if (!E->isTypeDependent() && E->isRValue())
4337 // Everything else: we simply don't reason about them.
4343 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4345 /// Check for comparisons of floating point operands using != and ==.
4346 /// Issue a warning if these are no self-comparisons, as they are not likely
4347 /// to do what the programmer intended.
4348 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
4349 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4350 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
4352 // Special case: check for x == x (which is OK).
4353 // Do not emit warnings for such cases.
4354 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4355 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4356 if (DRL->getDecl() == DRR->getDecl())
4360 // Special case: check for comparisons against literals that can be exactly
4361 // represented by APFloat. In such cases, do not emit a warning. This
4362 // is a heuristic: often comparison against such literals are used to
4363 // detect if a value in a variable has not changed. This clearly can
4364 // lead to false negatives.
4365 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4369 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4373 // Check for comparisons with builtin types.
4374 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4375 if (CL->isBuiltinCall())
4378 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4379 if (CR->isBuiltinCall())
4382 // Emit the diagnostic.
4383 Diag(Loc, diag::warn_floatingpoint_eq)
4384 << LHS->getSourceRange() << RHS->getSourceRange();
4387 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4388 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4392 /// Structure recording the 'active' range of an integer-valued
4395 /// The number of bits active in the int.
4398 /// True if the int is known not to have negative values.
4401 IntRange(unsigned Width, bool NonNegative)
4402 : Width(Width), NonNegative(NonNegative)
4405 /// Returns the range of the bool type.
4406 static IntRange forBoolType() {
4407 return IntRange(1, true);
4410 /// Returns the range of an opaque value of the given integral type.
4411 static IntRange forValueOfType(ASTContext &C, QualType T) {
4412 return forValueOfCanonicalType(C,
4413 T->getCanonicalTypeInternal().getTypePtr());
4416 /// Returns the range of an opaque value of a canonical integral type.
4417 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4418 assert(T->isCanonicalUnqualified());
4420 if (const VectorType *VT = dyn_cast<VectorType>(T))
4421 T = VT->getElementType().getTypePtr();
4422 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4423 T = CT->getElementType().getTypePtr();
4425 // For enum types, use the known bit width of the enumerators.
4426 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4427 EnumDecl *Enum = ET->getDecl();
4428 if (!Enum->isCompleteDefinition())
4429 return IntRange(C.getIntWidth(QualType(T, 0)), false);
4431 unsigned NumPositive = Enum->getNumPositiveBits();
4432 unsigned NumNegative = Enum->getNumNegativeBits();
4434 if (NumNegative == 0)
4435 return IntRange(NumPositive, true/*NonNegative*/);
4437 return IntRange(std::max(NumPositive + 1, NumNegative),
4438 false/*NonNegative*/);
4441 const BuiltinType *BT = cast<BuiltinType>(T);
4442 assert(BT->isInteger());
4444 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4447 /// Returns the "target" range of a canonical integral type, i.e.
4448 /// the range of values expressible in the type.
4450 /// This matches forValueOfCanonicalType except that enums have the
4451 /// full range of their type, not the range of their enumerators.
4452 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4453 assert(T->isCanonicalUnqualified());
4455 if (const VectorType *VT = dyn_cast<VectorType>(T))
4456 T = VT->getElementType().getTypePtr();
4457 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4458 T = CT->getElementType().getTypePtr();
4459 if (const EnumType *ET = dyn_cast<EnumType>(T))
4460 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4462 const BuiltinType *BT = cast<BuiltinType>(T);
4463 assert(BT->isInteger());
4465 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4468 /// Returns the supremum of two ranges: i.e. their conservative merge.
4469 static IntRange join(IntRange L, IntRange R) {
4470 return IntRange(std::max(L.Width, R.Width),
4471 L.NonNegative && R.NonNegative);
4474 /// Returns the infinum of two ranges: i.e. their aggressive merge.
4475 static IntRange meet(IntRange L, IntRange R) {
4476 return IntRange(std::min(L.Width, R.Width),
4477 L.NonNegative || R.NonNegative);
4481 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4482 unsigned MaxWidth) {
4483 if (value.isSigned() && value.isNegative())
4484 return IntRange(value.getMinSignedBits(), false);
4486 if (value.getBitWidth() > MaxWidth)
4487 value = value.trunc(MaxWidth);
4489 // isNonNegative() just checks the sign bit without considering
4491 return IntRange(value.getActiveBits(), true);
4494 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4495 unsigned MaxWidth) {
4497 return GetValueRange(C, result.getInt(), MaxWidth);
4499 if (result.isVector()) {
4500 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4501 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4502 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4503 R = IntRange::join(R, El);
4508 if (result.isComplexInt()) {
4509 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4510 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4511 return IntRange::join(R, I);
4514 // This can happen with lossless casts to intptr_t of "based" lvalues.
4515 // Assume it might use arbitrary bits.
4516 // FIXME: The only reason we need to pass the type in here is to get
4517 // the sign right on this one case. It would be nice if APValue
4519 assert(result.isLValue() || result.isAddrLabelDiff());
4520 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4523 static QualType GetExprType(Expr *E) {
4524 QualType Ty = E->getType();
4525 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4526 Ty = AtomicRHS->getValueType();
4530 /// Pseudo-evaluate the given integer expression, estimating the
4531 /// range of values it might take.
4533 /// \param MaxWidth - the width to which the value will be truncated
4534 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4535 E = E->IgnoreParens();
4537 // Try a full evaluation first.
4538 Expr::EvalResult result;
4539 if (E->EvaluateAsRValue(result, C))
4540 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
4542 // I think we only want to look through implicit casts here; if the
4543 // user has an explicit widening cast, we should treat the value as
4544 // being of the new, wider type.
4545 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4546 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4547 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4549 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
4551 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4553 // Assume that non-integer casts can span the full range of the type.
4555 return OutputTypeRange;
4558 = GetExprRange(C, CE->getSubExpr(),
4559 std::min(MaxWidth, OutputTypeRange.Width));
4561 // Bail out if the subexpr's range is as wide as the cast type.
4562 if (SubRange.Width >= OutputTypeRange.Width)
4563 return OutputTypeRange;
4565 // Otherwise, we take the smaller width, and we're non-negative if
4566 // either the output type or the subexpr is.
4567 return IntRange(SubRange.Width,
4568 SubRange.NonNegative || OutputTypeRange.NonNegative);
4571 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4572 // If we can fold the condition, just take that operand.
4574 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4575 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4576 : CO->getFalseExpr(),
4579 // Otherwise, conservatively merge.
4580 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4581 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4582 return IntRange::join(L, R);
4585 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4586 switch (BO->getOpcode()) {
4588 // Boolean-valued operations are single-bit and positive.
4597 return IntRange::forBoolType();
4599 // The type of the assignments is the type of the LHS, so the RHS
4600 // is not necessarily the same type.
4609 return IntRange::forValueOfType(C, GetExprType(E));
4611 // Simple assignments just pass through the RHS, which will have
4612 // been coerced to the LHS type.
4615 return GetExprRange(C, BO->getRHS(), MaxWidth);
4617 // Operations with opaque sources are black-listed.
4620 return IntRange::forValueOfType(C, GetExprType(E));
4622 // Bitwise-and uses the *infinum* of the two source ranges.
4625 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4626 GetExprRange(C, BO->getRHS(), MaxWidth));
4628 // Left shift gets black-listed based on a judgement call.
4630 // ...except that we want to treat '1 << (blah)' as logically
4631 // positive. It's an important idiom.
4632 if (IntegerLiteral *I
4633 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4634 if (I->getValue() == 1) {
4635 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
4636 return IntRange(R.Width, /*NonNegative*/ true);
4642 return IntRange::forValueOfType(C, GetExprType(E));
4644 // Right shift by a constant can narrow its left argument.
4646 case BO_ShrAssign: {
4647 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4649 // If the shift amount is a positive constant, drop the width by
4652 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4653 shift.isNonNegative()) {
4654 unsigned zext = shift.getZExtValue();
4655 if (zext >= L.Width)
4656 L.Width = (L.NonNegative ? 0 : 1);
4664 // Comma acts as its right operand.
4666 return GetExprRange(C, BO->getRHS(), MaxWidth);
4668 // Black-list pointer subtractions.
4670 if (BO->getLHS()->getType()->isPointerType())
4671 return IntRange::forValueOfType(C, GetExprType(E));
4674 // The width of a division result is mostly determined by the size
4677 // Don't 'pre-truncate' the operands.
4678 unsigned opWidth = C.getIntWidth(GetExprType(E));
4679 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4681 // If the divisor is constant, use that.
4682 llvm::APSInt divisor;
4683 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4684 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4685 if (log2 >= L.Width)
4686 L.Width = (L.NonNegative ? 0 : 1);
4688 L.Width = std::min(L.Width - log2, MaxWidth);
4692 // Otherwise, just use the LHS's width.
4693 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4694 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4697 // The result of a remainder can't be larger than the result of
4700 // Don't 'pre-truncate' the operands.
4701 unsigned opWidth = C.getIntWidth(GetExprType(E));
4702 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4703 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4705 IntRange meet = IntRange::meet(L, R);
4706 meet.Width = std::min(meet.Width, MaxWidth);
4710 // The default behavior is okay for these.
4718 // The default case is to treat the operation as if it were closed
4719 // on the narrowest type that encompasses both operands.
4720 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4721 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4722 return IntRange::join(L, R);
4725 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4726 switch (UO->getOpcode()) {
4727 // Boolean-valued operations are white-listed.
4729 return IntRange::forBoolType();
4731 // Operations with opaque sources are black-listed.
4733 case UO_AddrOf: // should be impossible
4734 return IntRange::forValueOfType(C, GetExprType(E));
4737 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4741 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4742 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4744 if (FieldDecl *BitField = E->getSourceBitField())
4745 return IntRange(BitField->getBitWidthValue(C),
4746 BitField->getType()->isUnsignedIntegerOrEnumerationType());
4748 return IntRange::forValueOfType(C, GetExprType(E));
4751 static IntRange GetExprRange(ASTContext &C, Expr *E) {
4752 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
4755 /// Checks whether the given value, which currently has the given
4756 /// source semantics, has the same value when coerced through the
4757 /// target semantics.
4758 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4759 const llvm::fltSemantics &Src,
4760 const llvm::fltSemantics &Tgt) {
4761 llvm::APFloat truncated = value;
4764 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4765 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4767 return truncated.bitwiseIsEqual(value);
4770 /// Checks whether the given value, which currently has the given
4771 /// source semantics, has the same value when coerced through the
4772 /// target semantics.
4774 /// The value might be a vector of floats (or a complex number).
4775 static bool IsSameFloatAfterCast(const APValue &value,
4776 const llvm::fltSemantics &Src,
4777 const llvm::fltSemantics &Tgt) {
4778 if (value.isFloat())
4779 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4781 if (value.isVector()) {
4782 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4783 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4788 assert(value.isComplexFloat());
4789 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4790 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4793 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
4795 static bool IsZero(Sema &S, Expr *E) {
4796 // Suppress cases where we are comparing against an enum constant.
4797 if (const DeclRefExpr *DR =
4798 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4799 if (isa<EnumConstantDecl>(DR->getDecl()))
4802 // Suppress cases where the '0' value is expanded from a macro.
4803 if (E->getLocStart().isMacroID())
4807 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4810 static bool HasEnumType(Expr *E) {
4811 // Strip off implicit integral promotions.
4812 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4813 if (ICE->getCastKind() != CK_IntegralCast &&
4814 ICE->getCastKind() != CK_NoOp)
4816 E = ICE->getSubExpr();
4819 return E->getType()->isEnumeralType();
4822 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
4823 // Disable warning in template instantiations.
4824 if (!S.ActiveTemplateInstantiations.empty())
4827 BinaryOperatorKind op = E->getOpcode();
4828 if (E->isValueDependent())
4831 if (op == BO_LT && IsZero(S, E->getRHS())) {
4832 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4833 << "< 0" << "false" << HasEnumType(E->getLHS())
4834 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4835 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
4836 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4837 << ">= 0" << "true" << HasEnumType(E->getLHS())
4838 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4839 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
4840 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4841 << "0 >" << "false" << HasEnumType(E->getRHS())
4842 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4843 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
4844 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4845 << "0 <=" << "true" << HasEnumType(E->getRHS())
4846 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4850 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
4851 Expr *Constant, Expr *Other,
4854 // Disable warning in template instantiations.
4855 if (!S.ActiveTemplateInstantiations.empty())
4858 // 0 values are handled later by CheckTrivialUnsignedComparison().
4862 BinaryOperatorKind op = E->getOpcode();
4863 QualType OtherT = Other->getType();
4864 QualType ConstantT = Constant->getType();
4865 QualType CommonT = E->getLHS()->getType();
4866 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
4868 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
4869 && "comparison with non-integer type");
4871 bool ConstantSigned = ConstantT->isSignedIntegerType();
4872 bool CommonSigned = CommonT->isSignedIntegerType();
4874 bool EqualityOnly = false;
4876 // TODO: Investigate using GetExprRange() to get tighter bounds on
4877 // on the bit ranges.
4878 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
4879 unsigned OtherWidth = OtherRange.Width;
4882 // The common type is signed, therefore no signed to unsigned conversion.
4883 if (!OtherRange.NonNegative) {
4884 // Check that the constant is representable in type OtherT.
4885 if (ConstantSigned) {
4886 if (OtherWidth >= Value.getMinSignedBits())
4888 } else { // !ConstantSigned
4889 if (OtherWidth >= Value.getActiveBits() + 1)
4892 } else { // !OtherSigned
4893 // Check that the constant is representable in type OtherT.
4894 // Negative values are out of range.
4895 if (ConstantSigned) {
4896 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4898 } else { // !ConstantSigned
4899 if (OtherWidth >= Value.getActiveBits())
4903 } else { // !CommonSigned
4904 if (OtherRange.NonNegative) {
4905 if (OtherWidth >= Value.getActiveBits())
4907 } else if (!OtherRange.NonNegative && !ConstantSigned) {
4908 // Check to see if the constant is representable in OtherT.
4909 if (OtherWidth > Value.getActiveBits())
4911 // Check to see if the constant is equivalent to a negative value
4913 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
4914 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
4916 // The constant value rests between values that OtherT can represent after
4917 // conversion. Relational comparison still works, but equality
4918 // comparisons will be tautological.
4919 EqualityOnly = true;
4920 } else { // OtherSigned && ConstantSigned
4921 assert(0 && "Two signed types converted to unsigned types.");
4925 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4928 if (op == BO_EQ || op == BO_NE) {
4929 IsTrue = op == BO_NE;
4930 } else if (EqualityOnly) {
4932 } else if (RhsConstant) {
4933 if (op == BO_GT || op == BO_GE)
4934 IsTrue = !PositiveConstant;
4935 else // op == BO_LT || op == BO_LE
4936 IsTrue = PositiveConstant;
4938 if (op == BO_LT || op == BO_LE)
4939 IsTrue = !PositiveConstant;
4940 else // op == BO_GT || op == BO_GE
4941 IsTrue = PositiveConstant;
4944 // If this is a comparison to an enum constant, include that
4945 // constant in the diagnostic.
4946 const EnumConstantDecl *ED = 0;
4947 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4948 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4950 SmallString<64> PrettySourceValue;
4951 llvm::raw_svector_ostream OS(PrettySourceValue);
4953 OS << '\'' << *ED << "' (" << Value << ")";
4957 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4958 << OS.str() << OtherT << IsTrue
4959 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4962 /// Analyze the operands of the given comparison. Implements the
4963 /// fallback case from AnalyzeComparison.
4964 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
4965 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4966 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4969 /// \brief Implements -Wsign-compare.
4971 /// \param E the binary operator to check for warnings
4972 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
4973 // The type the comparison is being performed in.
4974 QualType T = E->getLHS()->getType();
4975 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4976 && "comparison with mismatched types");
4977 if (E->isValueDependent())
4978 return AnalyzeImpConvsInComparison(S, E);
4980 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4981 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
4983 bool IsComparisonConstant = false;
4985 // Check whether an integer constant comparison results in a value
4986 // of 'true' or 'false'.
4987 if (T->isIntegralType(S.Context)) {
4988 llvm::APSInt RHSValue;
4989 bool IsRHSIntegralLiteral =
4990 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4991 llvm::APSInt LHSValue;
4992 bool IsLHSIntegralLiteral =
4993 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4994 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4995 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4996 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4997 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4999 IsComparisonConstant =
5000 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
5001 } else if (!T->hasUnsignedIntegerRepresentation())
5002 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
5004 // We don't do anything special if this isn't an unsigned integral
5005 // comparison: we're only interested in integral comparisons, and
5006 // signed comparisons only happen in cases we don't care to warn about.
5008 // We also don't care about value-dependent expressions or expressions
5009 // whose result is a constant.
5010 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
5011 return AnalyzeImpConvsInComparison(S, E);
5013 // Check to see if one of the (unmodified) operands is of different
5015 Expr *signedOperand, *unsignedOperand;
5016 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5017 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
5018 "unsigned comparison between two signed integer expressions?");
5019 signedOperand = LHS;
5020 unsignedOperand = RHS;
5021 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5022 signedOperand = RHS;
5023 unsignedOperand = LHS;
5025 CheckTrivialUnsignedComparison(S, E);
5026 return AnalyzeImpConvsInComparison(S, E);
5029 // Otherwise, calculate the effective range of the signed operand.
5030 IntRange signedRange = GetExprRange(S.Context, signedOperand);
5032 // Go ahead and analyze implicit conversions in the operands. Note
5033 // that we skip the implicit conversions on both sides.
5034 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5035 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
5037 // If the signed range is non-negative, -Wsign-compare won't fire,
5038 // but we should still check for comparisons which are always true
5040 if (signedRange.NonNegative)
5041 return CheckTrivialUnsignedComparison(S, E);
5043 // For (in)equality comparisons, if the unsigned operand is a
5044 // constant which cannot collide with a overflowed signed operand,
5045 // then reinterpreting the signed operand as unsigned will not
5046 // change the result of the comparison.
5047 if (E->isEqualityOp()) {
5048 unsigned comparisonWidth = S.Context.getIntWidth(T);
5049 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
5051 // We should never be unable to prove that the unsigned operand is
5053 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5055 if (unsignedRange.Width < comparisonWidth)
5059 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5060 S.PDiag(diag::warn_mixed_sign_comparison)
5061 << LHS->getType() << RHS->getType()
5062 << LHS->getSourceRange() << RHS->getSourceRange());
5065 /// Analyzes an attempt to assign the given value to a bitfield.
5067 /// Returns true if there was something fishy about the attempt.
5068 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5069 SourceLocation InitLoc) {
5070 assert(Bitfield->isBitField());
5071 if (Bitfield->isInvalidDecl())
5074 // White-list bool bitfields.
5075 if (Bitfield->getType()->isBooleanType())
5078 // Ignore value- or type-dependent expressions.
5079 if (Bitfield->getBitWidth()->isValueDependent() ||
5080 Bitfield->getBitWidth()->isTypeDependent() ||
5081 Init->isValueDependent() ||
5082 Init->isTypeDependent())
5085 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5088 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
5091 unsigned OriginalWidth = Value.getBitWidth();
5092 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
5094 if (OriginalWidth <= FieldWidth)
5097 // Compute the value which the bitfield will contain.
5098 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
5099 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
5101 // Check whether the stored value is equal to the original value.
5102 TruncatedValue = TruncatedValue.extend(OriginalWidth);
5103 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
5106 // Special-case bitfields of width 1: booleans are naturally 0/1, and
5107 // therefore don't strictly fit into a signed bitfield of width 1.
5108 if (FieldWidth == 1 && Value == 1)
5111 std::string PrettyValue = Value.toString(10);
5112 std::string PrettyTrunc = TruncatedValue.toString(10);
5114 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5115 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5116 << Init->getSourceRange();
5121 /// Analyze the given simple or compound assignment for warning-worthy
5123 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
5124 // Just recurse on the LHS.
5125 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5127 // We want to recurse on the RHS as normal unless we're assigning to
5129 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
5130 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
5131 E->getOperatorLoc())) {
5132 // Recurse, ignoring any implicit conversions on the RHS.
5133 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5134 E->getOperatorLoc());
5138 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5141 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
5142 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
5143 SourceLocation CContext, unsigned diag,
5144 bool pruneControlFlow = false) {
5145 if (pruneControlFlow) {
5146 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5148 << SourceType << T << E->getSourceRange()
5149 << SourceRange(CContext));
5152 S.Diag(E->getExprLoc(), diag)
5153 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5156 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
5157 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
5158 SourceLocation CContext, unsigned diag,
5159 bool pruneControlFlow = false) {
5160 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
5163 /// Diagnose an implicit cast from a literal expression. Does not warn when the
5164 /// cast wouldn't lose information.
5165 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5166 SourceLocation CContext) {
5167 // Try to convert the literal exactly to an integer. If we can, don't warn.
5168 bool isExact = false;
5169 const llvm::APFloat &Value = FL->getValue();
5170 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5171 T->hasUnsignedIntegerRepresentation());
5172 if (Value.convertToInteger(IntegerValue,
5173 llvm::APFloat::rmTowardZero, &isExact)
5174 == llvm::APFloat::opOK && isExact)
5177 // FIXME: Force the precision of the source value down so we don't print
5178 // digits which are usually useless (we don't really care here if we
5179 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5180 // would automatically print the shortest representation, but it's a bit
5181 // tricky to implement.
5182 SmallString<16> PrettySourceValue;
5183 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5184 precision = (precision * 59 + 195) / 196;
5185 Value.toString(PrettySourceValue, precision);
5187 SmallString<16> PrettyTargetValue;
5188 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5189 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5191 IntegerValue.toString(PrettyTargetValue);
5193 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
5194 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5195 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
5198 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5199 if (!Range.Width) return "0";
5201 llvm::APSInt ValueInRange = Value;
5202 ValueInRange.setIsSigned(!Range.NonNegative);
5203 ValueInRange = ValueInRange.trunc(Range.Width);
5204 return ValueInRange.toString(10);
5207 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5208 if (!isa<ImplicitCastExpr>(Ex))
5211 Expr *InnerE = Ex->IgnoreParenImpCasts();
5212 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5213 const Type *Source =
5214 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5215 if (Target->isDependentType())
5218 const BuiltinType *FloatCandidateBT =
5219 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5220 const Type *BoolCandidateType = ToBool ? Target : Source;
5222 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5223 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5226 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5227 SourceLocation CC) {
5228 unsigned NumArgs = TheCall->getNumArgs();
5229 for (unsigned i = 0; i < NumArgs; ++i) {
5230 Expr *CurrA = TheCall->getArg(i);
5231 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5234 bool IsSwapped = ((i > 0) &&
5235 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5236 IsSwapped |= ((i < (NumArgs - 1)) &&
5237 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5239 // Warn on this floating-point to bool conversion.
5240 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5241 CurrA->getType(), CC,
5242 diag::warn_impcast_floating_point_to_bool);
5247 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
5248 SourceLocation CC, bool *ICContext = 0) {
5249 if (E->isTypeDependent() || E->isValueDependent()) return;
5251 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5252 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5253 if (Source == Target) return;
5254 if (Target->isDependentType()) return;
5256 // If the conversion context location is invalid don't complain. We also
5257 // don't want to emit a warning if the issue occurs from the expansion of
5258 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5259 // delay this check as long as possible. Once we detect we are in that
5260 // scenario, we just return.
5264 // Diagnose implicit casts to bool.
5265 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5266 if (isa<StringLiteral>(E))
5267 // Warn on string literal to bool. Checks for string literals in logical
5268 // expressions, for instances, assert(0 && "error here"), is prevented
5269 // by a check in AnalyzeImplicitConversions().
5270 return DiagnoseImpCast(S, E, T, CC,
5271 diag::warn_impcast_string_literal_to_bool);
5272 if (Source->isFunctionType()) {
5273 // Warn on function to bool. Checks free functions and static member
5274 // functions. Weakly imported functions are excluded from the check,
5275 // since it's common to test their value to check whether the linker
5276 // found a definition for them.
5278 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5280 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5281 D = M->getMemberDecl();
5284 if (D && !D->isWeak()) {
5285 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5286 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5287 << F << E->getSourceRange() << SourceRange(CC);
5288 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5289 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5290 QualType ReturnType;
5291 UnresolvedSet<4> NonTemplateOverloads;
5292 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
5293 if (!ReturnType.isNull()
5294 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5295 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5296 << FixItHint::CreateInsertion(
5297 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
5304 // Strip vector types.
5305 if (isa<VectorType>(Source)) {
5306 if (!isa<VectorType>(Target)) {
5307 if (S.SourceMgr.isInSystemMacro(CC))
5309 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
5312 // If the vector cast is cast between two vectors of the same size, it is
5313 // a bitcast, not a conversion.
5314 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5317 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5318 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5321 // Strip complex types.
5322 if (isa<ComplexType>(Source)) {
5323 if (!isa<ComplexType>(Target)) {
5324 if (S.SourceMgr.isInSystemMacro(CC))
5327 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
5330 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5331 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5334 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5335 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5337 // If the source is floating point...
5338 if (SourceBT && SourceBT->isFloatingPoint()) {
5339 // ...and the target is floating point...
5340 if (TargetBT && TargetBT->isFloatingPoint()) {
5341 // ...then warn if we're dropping FP rank.
5343 // Builtin FP kinds are ordered by increasing FP rank.
5344 if (SourceBT->getKind() > TargetBT->getKind()) {
5345 // Don't warn about float constants that are precisely
5346 // representable in the target type.
5347 Expr::EvalResult result;
5348 if (E->EvaluateAsRValue(result, S.Context)) {
5349 // Value might be a float, a float vector, or a float complex.
5350 if (IsSameFloatAfterCast(result.Val,
5351 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5352 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
5356 if (S.SourceMgr.isInSystemMacro(CC))
5359 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
5364 // If the target is integral, always warn.
5365 if (TargetBT && TargetBT->isInteger()) {
5366 if (S.SourceMgr.isInSystemMacro(CC))
5369 Expr *InnerE = E->IgnoreParenImpCasts();
5370 // We also want to warn on, e.g., "int i = -1.234"
5371 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5372 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5373 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5375 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5376 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
5378 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5382 // If the target is bool, warn if expr is a function or method call.
5383 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5385 // Check last argument of function call to see if it is an
5386 // implicit cast from a type matching the type the result
5387 // is being cast to.
5388 CallExpr *CEx = cast<CallExpr>(E);
5389 unsigned NumArgs = CEx->getNumArgs();
5391 Expr *LastA = CEx->getArg(NumArgs - 1);
5392 Expr *InnerE = LastA->IgnoreParenImpCasts();
5393 const Type *InnerType =
5394 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5395 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5396 // Warn on this floating-point to bool conversion
5397 DiagnoseImpCast(S, E, T, CC,
5398 diag::warn_impcast_floating_point_to_bool);
5405 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5406 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5407 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5408 && Target->isScalarType() && !Target->isNullPtrType()) {
5409 SourceLocation Loc = E->getSourceRange().getBegin();
5410 if (Loc.isMacroID())
5411 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5412 if (!Loc.isMacroID() || CC.isMacroID())
5413 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5414 << T << clang::SourceRange(CC)
5415 << FixItHint::CreateReplacement(Loc,
5416 S.getFixItZeroLiteralForType(T, Loc));
5419 if (!Source->isIntegerType() || !Target->isIntegerType())
5422 // TODO: remove this early return once the false positives for constant->bool
5423 // in templates, macros, etc, are reduced or removed.
5424 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5427 IntRange SourceRange = GetExprRange(S.Context, E);
5428 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5430 if (SourceRange.Width > TargetRange.Width) {
5431 // If the source is a constant, use a default-on diagnostic.
5432 // TODO: this should happen for bitfield stores, too.
5433 llvm::APSInt Value(32);
5434 if (E->isIntegerConstantExpr(Value, S.Context)) {
5435 if (S.SourceMgr.isInSystemMacro(CC))
5438 std::string PrettySourceValue = Value.toString(10);
5439 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5441 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5442 S.PDiag(diag::warn_impcast_integer_precision_constant)
5443 << PrettySourceValue << PrettyTargetValue
5444 << E->getType() << T << E->getSourceRange()
5445 << clang::SourceRange(CC));
5449 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5450 if (S.SourceMgr.isInSystemMacro(CC))
5453 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5454 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5455 /* pruneControlFlow */ true);
5456 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5459 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5460 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5461 SourceRange.Width == TargetRange.Width)) {
5463 if (S.SourceMgr.isInSystemMacro(CC))
5466 unsigned DiagID = diag::warn_impcast_integer_sign;
5468 // Traditionally, gcc has warned about this under -Wsign-compare.
5469 // We also want to warn about it in -Wconversion.
5470 // So if -Wconversion is off, use a completely identical diagnostic
5471 // in the sign-compare group.
5472 // The conditional-checking code will
5474 DiagID = diag::warn_impcast_integer_sign_conditional;
5478 return DiagnoseImpCast(S, E, T, CC, DiagID);
5481 // Diagnose conversions between different enumeration types.
5482 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5483 // type, to give us better diagnostics.
5484 QualType SourceType = E->getType();
5485 if (!S.getLangOpts().CPlusPlus) {
5486 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5487 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5488 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5489 SourceType = S.Context.getTypeDeclType(Enum);
5490 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5494 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5495 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5496 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5497 TargetEnum->getDecl()->hasNameForLinkage() &&
5498 SourceEnum != TargetEnum) {
5499 if (S.SourceMgr.isInSystemMacro(CC))
5502 return DiagnoseImpCast(S, E, SourceType, T, CC,
5503 diag::warn_impcast_different_enum_types);
5509 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5510 SourceLocation CC, QualType T);
5512 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
5513 SourceLocation CC, bool &ICContext) {
5514 E = E->IgnoreParenImpCasts();
5516 if (isa<ConditionalOperator>(E))
5517 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
5519 AnalyzeImplicitConversions(S, E, CC);
5520 if (E->getType() != T)
5521 return CheckImplicitConversion(S, E, T, CC, &ICContext);
5525 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5526 SourceLocation CC, QualType T) {
5527 AnalyzeImplicitConversions(S, E->getCond(), CC);
5529 bool Suspicious = false;
5530 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5531 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
5533 // If -Wconversion would have warned about either of the candidates
5534 // for a signedness conversion to the context type...
5535 if (!Suspicious) return;
5537 // ...but it's currently ignored...
5538 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5542 // ...then check whether it would have warned about either of the
5543 // candidates for a signedness conversion to the condition type.
5544 if (E->getType() == T) return;
5547 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5548 E->getType(), CC, &Suspicious);
5550 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
5551 E->getType(), CC, &Suspicious);
5554 /// AnalyzeImplicitConversions - Find and report any interesting
5555 /// implicit conversions in the given expression. There are a couple
5556 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
5557 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
5558 QualType T = OrigE->getType();
5559 Expr *E = OrigE->IgnoreParenImpCasts();
5561 if (E->isTypeDependent() || E->isValueDependent())
5564 // For conditional operators, we analyze the arguments as if they
5565 // were being fed directly into the output.
5566 if (isa<ConditionalOperator>(E)) {
5567 ConditionalOperator *CO = cast<ConditionalOperator>(E);
5568 CheckConditionalOperator(S, CO, CC, T);
5572 // Check implicit argument conversions for function calls.
5573 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5574 CheckImplicitArgumentConversions(S, Call, CC);
5576 // Go ahead and check any implicit conversions we might have skipped.
5577 // The non-canonical typecheck is just an optimization;
5578 // CheckImplicitConversion will filter out dead implicit conversions.
5579 if (E->getType() != T)
5580 CheckImplicitConversion(S, E, T, CC);
5582 // Now continue drilling into this expression.
5584 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
5585 if (POE->getResultExpr())
5586 E = POE->getResultExpr();
5589 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5590 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5592 // Skip past explicit casts.
5593 if (isa<ExplicitCastExpr>(E)) {
5594 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
5595 return AnalyzeImplicitConversions(S, E, CC);
5598 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5599 // Do a somewhat different check with comparison operators.
5600 if (BO->isComparisonOp())
5601 return AnalyzeComparison(S, BO);
5603 // And with simple assignments.
5604 if (BO->getOpcode() == BO_Assign)
5605 return AnalyzeAssignment(S, BO);
5608 // These break the otherwise-useful invariant below. Fortunately,
5609 // we don't really need to recurse into them, because any internal
5610 // expressions should have been analyzed already when they were
5611 // built into statements.
5612 if (isa<StmtExpr>(E)) return;
5614 // Don't descend into unevaluated contexts.
5615 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
5617 // Now just recurse over the expression's children.
5618 CC = E->getExprLoc();
5619 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5620 bool IsLogicalOperator = BO && BO->isLogicalOp();
5621 for (Stmt::child_range I = E->children(); I; ++I) {
5622 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
5626 if (IsLogicalOperator &&
5627 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5628 // Ignore checking string literals that are in logical operators.
5630 AnalyzeImplicitConversions(S, ChildExpr, CC);
5634 } // end anonymous namespace
5636 /// Diagnoses "dangerous" implicit conversions within the given
5637 /// expression (which is a full expression). Implements -Wconversion
5638 /// and -Wsign-compare.
5640 /// \param CC the "context" location of the implicit conversion, i.e.
5641 /// the most location of the syntactic entity requiring the implicit
5643 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
5644 // Don't diagnose in unevaluated contexts.
5645 if (isUnevaluatedContext())
5648 // Don't diagnose for value- or type-dependent expressions.
5649 if (E->isTypeDependent() || E->isValueDependent())
5652 // Check for array bounds violations in cases where the check isn't triggered
5653 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5654 // ArraySubscriptExpr is on the RHS of a variable initialization.
5655 CheckArrayAccess(E);
5657 // This is not the right CC for (e.g.) a variable initialization.
5658 AnalyzeImplicitConversions(*this, E, CC);
5661 /// Diagnose when expression is an integer constant expression and its evaluation
5662 /// results in integer overflow
5663 void Sema::CheckForIntOverflow (Expr *E) {
5664 if (isa<BinaryOperator>(E->IgnoreParens()))
5665 E->EvaluateForOverflow(Context);
5669 /// \brief Visitor for expressions which looks for unsequenced operations on the
5671 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5672 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5674 /// \brief A tree of sequenced regions within an expression. Two regions are
5675 /// unsequenced if one is an ancestor or a descendent of the other. When we
5676 /// finish processing an expression with sequencing, such as a comma
5677 /// expression, we fold its tree nodes into its parent, since they are
5678 /// unsequenced with respect to nodes we will visit later.
5679 class SequenceTree {
5681 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5682 unsigned Parent : 31;
5685 SmallVector<Value, 8> Values;
5688 /// \brief A region within an expression which may be sequenced with respect
5689 /// to some other region.
5691 explicit Seq(unsigned N) : Index(N) {}
5693 friend class SequenceTree;
5698 SequenceTree() { Values.push_back(Value(0)); }
5699 Seq root() const { return Seq(0); }
5701 /// \brief Create a new sequence of operations, which is an unsequenced
5702 /// subset of \p Parent. This sequence of operations is sequenced with
5703 /// respect to other children of \p Parent.
5704 Seq allocate(Seq Parent) {
5705 Values.push_back(Value(Parent.Index));
5706 return Seq(Values.size() - 1);
5709 /// \brief Merge a sequence of operations into its parent.
5711 Values[S.Index].Merged = true;
5714 /// \brief Determine whether two operations are unsequenced. This operation
5715 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5716 /// should have been merged into its parent as appropriate.
5717 bool isUnsequenced(Seq Cur, Seq Old) {
5718 unsigned C = representative(Cur.Index);
5719 unsigned Target = representative(Old.Index);
5720 while (C >= Target) {
5723 C = Values[C].Parent;
5729 /// \brief Pick a representative for a sequence.
5730 unsigned representative(unsigned K) {
5731 if (Values[K].Merged)
5732 // Perform path compression as we go.
5733 return Values[K].Parent = representative(Values[K].Parent);
5738 /// An object for which we can track unsequenced uses.
5739 typedef NamedDecl *Object;
5741 /// Different flavors of object usage which we track. We only track the
5742 /// least-sequenced usage of each kind.
5744 /// A read of an object. Multiple unsequenced reads are OK.
5746 /// A modification of an object which is sequenced before the value
5747 /// computation of the expression, such as ++n in C++.
5749 /// A modification of an object which is not sequenced before the value
5750 /// computation of the expression, such as n++.
5753 UK_Count = UK_ModAsSideEffect + 1
5757 Usage() : Use(0), Seq() {}
5759 SequenceTree::Seq Seq;
5763 UsageInfo() : Diagnosed(false) {}
5764 Usage Uses[UK_Count];
5765 /// Have we issued a diagnostic for this variable already?
5768 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5771 /// Sequenced regions within the expression.
5773 /// Declaration modifications and references which we have seen.
5774 UsageInfoMap UsageMap;
5775 /// The region we are currently within.
5776 SequenceTree::Seq Region;
5777 /// Filled in with declarations which were modified as a side-effect
5778 /// (that is, post-increment operations).
5779 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
5780 /// Expressions to check later. We defer checking these to reduce
5782 SmallVectorImpl<Expr *> &WorkList;
5784 /// RAII object wrapping the visitation of a sequenced subexpression of an
5785 /// expression. At the end of this process, the side-effects of the evaluation
5786 /// become sequenced with respect to the value computation of the result, so
5787 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5789 struct SequencedSubexpression {
5790 SequencedSubexpression(SequenceChecker &Self)
5791 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5792 Self.ModAsSideEffect = &ModAsSideEffect;
5794 ~SequencedSubexpression() {
5795 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5796 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5797 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5798 Self.addUsage(U, ModAsSideEffect[I].first,
5799 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5801 Self.ModAsSideEffect = OldModAsSideEffect;
5804 SequenceChecker &Self;
5805 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5806 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5809 /// RAII object wrapping the visitation of a subexpression which we might
5810 /// choose to evaluate as a constant. If any subexpression is evaluated and
5811 /// found to be non-constant, this allows us to suppress the evaluation of
5812 /// the outer expression.
5813 class EvaluationTracker {
5815 EvaluationTracker(SequenceChecker &Self)
5816 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5817 Self.EvalTracker = this;
5819 ~EvaluationTracker() {
5820 Self.EvalTracker = Prev;
5822 Prev->EvalOK &= EvalOK;
5825 bool evaluate(const Expr *E, bool &Result) {
5826 if (!EvalOK || E->isValueDependent())
5828 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5833 SequenceChecker &Self;
5834 EvaluationTracker *Prev;
5838 /// \brief Find the object which is produced by the specified expression,
5840 Object getObject(Expr *E, bool Mod) const {
5841 E = E->IgnoreParenCasts();
5842 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5843 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5844 return getObject(UO->getSubExpr(), Mod);
5845 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5846 if (BO->getOpcode() == BO_Comma)
5847 return getObject(BO->getRHS(), Mod);
5848 if (Mod && BO->isAssignmentOp())
5849 return getObject(BO->getLHS(), Mod);
5850 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5851 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5852 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5853 return ME->getMemberDecl();
5854 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5855 // FIXME: If this is a reference, map through to its value.
5856 return DRE->getDecl();
5860 /// \brief Note that an object was modified or used by an expression.
5861 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5862 Usage &U = UI.Uses[UK];
5863 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5864 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5865 ModAsSideEffect->push_back(std::make_pair(O, U));
5870 /// \brief Check whether a modification or use conflicts with a prior usage.
5871 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5876 const Usage &U = UI.Uses[OtherKind];
5877 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5881 Expr *ModOrUse = Ref;
5882 if (OtherKind == UK_Use)
5883 std::swap(Mod, ModOrUse);
5885 SemaRef.Diag(Mod->getExprLoc(),
5886 IsModMod ? diag::warn_unsequenced_mod_mod
5887 : diag::warn_unsequenced_mod_use)
5888 << O << SourceRange(ModOrUse->getExprLoc());
5889 UI.Diagnosed = true;
5892 void notePreUse(Object O, Expr *Use) {
5893 UsageInfo &U = UsageMap[O];
5894 // Uses conflict with other modifications.
5895 checkUsage(O, U, Use, UK_ModAsValue, false);
5897 void notePostUse(Object O, Expr *Use) {
5898 UsageInfo &U = UsageMap[O];
5899 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5900 addUsage(U, O, Use, UK_Use);
5903 void notePreMod(Object O, Expr *Mod) {
5904 UsageInfo &U = UsageMap[O];
5905 // Modifications conflict with other modifications and with uses.
5906 checkUsage(O, U, Mod, UK_ModAsValue, true);
5907 checkUsage(O, U, Mod, UK_Use, false);
5909 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5910 UsageInfo &U = UsageMap[O];
5911 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5912 addUsage(U, O, Use, UK);
5916 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5917 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5918 WorkList(WorkList), EvalTracker(0) {
5922 void VisitStmt(Stmt *S) {
5923 // Skip all statements which aren't expressions for now.
5926 void VisitExpr(Expr *E) {
5927 // By default, just recurse to evaluated subexpressions.
5931 void VisitCastExpr(CastExpr *E) {
5932 Object O = Object();
5933 if (E->getCastKind() == CK_LValueToRValue)
5934 O = getObject(E->getSubExpr(), false);
5943 void VisitBinComma(BinaryOperator *BO) {
5944 // C++11 [expr.comma]p1:
5945 // Every value computation and side effect associated with the left
5946 // expression is sequenced before every value computation and side
5947 // effect associated with the right expression.
5948 SequenceTree::Seq LHS = Tree.allocate(Region);
5949 SequenceTree::Seq RHS = Tree.allocate(Region);
5950 SequenceTree::Seq OldRegion = Region;
5953 SequencedSubexpression SeqLHS(*this);
5955 Visit(BO->getLHS());
5959 Visit(BO->getRHS());
5963 // Forget that LHS and RHS are sequenced. They are both unsequenced
5964 // with respect to other stuff.
5969 void VisitBinAssign(BinaryOperator *BO) {
5970 // The modification is sequenced after the value computation of the LHS
5971 // and RHS, so check it before inspecting the operands and update the
5973 Object O = getObject(BO->getLHS(), true);
5975 return VisitExpr(BO);
5979 // C++11 [expr.ass]p7:
5980 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5983 // Therefore, for a compound assignment operator, O is considered used
5984 // everywhere except within the evaluation of E1 itself.
5985 if (isa<CompoundAssignOperator>(BO))
5988 Visit(BO->getLHS());
5990 if (isa<CompoundAssignOperator>(BO))
5993 Visit(BO->getRHS());
5995 // C++11 [expr.ass]p1:
5996 // the assignment is sequenced [...] before the value computation of the
5997 // assignment expression.
5998 // C11 6.5.16/3 has no such rule.
5999 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6000 : UK_ModAsSideEffect);
6002 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6003 VisitBinAssign(CAO);
6006 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6007 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6008 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6009 Object O = getObject(UO->getSubExpr(), true);
6011 return VisitExpr(UO);
6014 Visit(UO->getSubExpr());
6015 // C++11 [expr.pre.incr]p1:
6016 // the expression ++x is equivalent to x+=1
6017 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6018 : UK_ModAsSideEffect);
6021 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6022 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6023 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6024 Object O = getObject(UO->getSubExpr(), true);
6026 return VisitExpr(UO);
6029 Visit(UO->getSubExpr());
6030 notePostMod(O, UO, UK_ModAsSideEffect);
6033 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6034 void VisitBinLOr(BinaryOperator *BO) {
6035 // The side-effects of the LHS of an '&&' are sequenced before the
6036 // value computation of the RHS, and hence before the value computation
6037 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6038 // as if they were unconditionally sequenced.
6039 EvaluationTracker Eval(*this);
6041 SequencedSubexpression Sequenced(*this);
6042 Visit(BO->getLHS());
6046 if (Eval.evaluate(BO->getLHS(), Result)) {
6048 Visit(BO->getRHS());
6050 // Check for unsequenced operations in the RHS, treating it as an
6051 // entirely separate evaluation.
6053 // FIXME: If there are operations in the RHS which are unsequenced
6054 // with respect to operations outside the RHS, and those operations
6055 // are unconditionally evaluated, diagnose them.
6056 WorkList.push_back(BO->getRHS());
6059 void VisitBinLAnd(BinaryOperator *BO) {
6060 EvaluationTracker Eval(*this);
6062 SequencedSubexpression Sequenced(*this);
6063 Visit(BO->getLHS());
6067 if (Eval.evaluate(BO->getLHS(), Result)) {
6069 Visit(BO->getRHS());
6071 WorkList.push_back(BO->getRHS());
6075 // Only visit the condition, unless we can be sure which subexpression will
6077 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
6078 EvaluationTracker Eval(*this);
6080 SequencedSubexpression Sequenced(*this);
6081 Visit(CO->getCond());
6085 if (Eval.evaluate(CO->getCond(), Result))
6086 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
6088 WorkList.push_back(CO->getTrueExpr());
6089 WorkList.push_back(CO->getFalseExpr());
6093 void VisitCallExpr(CallExpr *CE) {
6094 // C++11 [intro.execution]p15:
6095 // When calling a function [...], every value computation and side effect
6096 // associated with any argument expression, or with the postfix expression
6097 // designating the called function, is sequenced before execution of every
6098 // expression or statement in the body of the function [and thus before
6099 // the value computation of its result].
6100 SequencedSubexpression Sequenced(*this);
6101 Base::VisitCallExpr(CE);
6103 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6106 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
6107 // This is a call, so all subexpressions are sequenced before the result.
6108 SequencedSubexpression Sequenced(*this);
6110 if (!CCE->isListInitialization())
6111 return VisitExpr(CCE);
6113 // In C++11, list initializations are sequenced.
6114 SmallVector<SequenceTree::Seq, 32> Elts;
6115 SequenceTree::Seq Parent = Region;
6116 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6119 Region = Tree.allocate(Parent);
6120 Elts.push_back(Region);
6124 // Forget that the initializers are sequenced.
6126 for (unsigned I = 0; I < Elts.size(); ++I)
6127 Tree.merge(Elts[I]);
6130 void VisitInitListExpr(InitListExpr *ILE) {
6131 if (!SemaRef.getLangOpts().CPlusPlus11)
6132 return VisitExpr(ILE);
6134 // In C++11, list initializations are sequenced.
6135 SmallVector<SequenceTree::Seq, 32> Elts;
6136 SequenceTree::Seq Parent = Region;
6137 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6138 Expr *E = ILE->getInit(I);
6140 Region = Tree.allocate(Parent);
6141 Elts.push_back(Region);
6145 // Forget that the initializers are sequenced.
6147 for (unsigned I = 0; I < Elts.size(); ++I)
6148 Tree.merge(Elts[I]);
6153 void Sema::CheckUnsequencedOperations(Expr *E) {
6154 SmallVector<Expr *, 8> WorkList;
6155 WorkList.push_back(E);
6156 while (!WorkList.empty()) {
6157 Expr *Item = WorkList.pop_back_val();
6158 SequenceChecker(*this, Item, WorkList);
6162 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6164 CheckImplicitConversions(E, CheckLoc);
6165 CheckUnsequencedOperations(E);
6166 if (!IsConstexpr && !E->isValueDependent())
6167 CheckForIntOverflow(E);
6170 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6171 FieldDecl *BitField,
6173 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6176 /// CheckParmsForFunctionDef - Check that the parameters of the given
6177 /// function are appropriate for the definition of a function. This
6178 /// takes care of any checks that cannot be performed on the
6179 /// declaration itself, e.g., that the types of each of the function
6180 /// parameters are complete.
6181 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6182 ParmVarDecl *const *PEnd,
6183 bool CheckParameterNames) {
6184 bool HasInvalidParm = false;
6185 for (; P != PEnd; ++P) {
6186 ParmVarDecl *Param = *P;
6188 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6189 // function declarator that is part of a function definition of
6190 // that function shall not have incomplete type.
6192 // This is also C++ [dcl.fct]p6.
6193 if (!Param->isInvalidDecl() &&
6194 RequireCompleteType(Param->getLocation(), Param->getType(),
6195 diag::err_typecheck_decl_incomplete_type)) {
6196 Param->setInvalidDecl();
6197 HasInvalidParm = true;
6200 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6201 // declaration of each parameter shall include an identifier.
6202 if (CheckParameterNames &&
6203 Param->getIdentifier() == 0 &&
6204 !Param->isImplicit() &&
6205 !getLangOpts().CPlusPlus)
6206 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6209 // If the function declarator is not part of a definition of that
6210 // function, parameters may have incomplete type and may use the [*]
6211 // notation in their sequences of declarator specifiers to specify
6212 // variable length array types.
6213 QualType PType = Param->getOriginalType();
6214 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
6215 if (AT->getSizeModifier() == ArrayType::Star) {
6216 // FIXME: This diagnostic should point the '[*]' if source-location
6217 // information is added for it.
6218 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
6221 PType= AT->getElementType();
6224 // MSVC destroys objects passed by value in the callee. Therefore a
6225 // function definition which takes such a parameter must be able to call the
6226 // object's destructor.
6227 if (getLangOpts().CPlusPlus &&
6228 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6229 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6230 FinalizeVarWithDestructor(Param, RT);
6234 return HasInvalidParm;
6237 /// CheckCastAlign - Implements -Wcast-align, which warns when a
6238 /// pointer cast increases the alignment requirements.
6239 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6240 // This is actually a lot of work to potentially be doing on every
6241 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
6242 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6244 == DiagnosticsEngine::Ignored)
6247 // Ignore dependent types.
6248 if (T->isDependentType() || Op->getType()->isDependentType())
6251 // Require that the destination be a pointer type.
6252 const PointerType *DestPtr = T->getAs<PointerType>();
6253 if (!DestPtr) return;
6255 // If the destination has alignment 1, we're done.
6256 QualType DestPointee = DestPtr->getPointeeType();
6257 if (DestPointee->isIncompleteType()) return;
6258 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6259 if (DestAlign.isOne()) return;
6261 // Require that the source be a pointer type.
6262 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6263 if (!SrcPtr) return;
6264 QualType SrcPointee = SrcPtr->getPointeeType();
6266 // Whitelist casts from cv void*. We already implicitly
6267 // whitelisted casts to cv void*, since they have alignment 1.
6268 // Also whitelist casts involving incomplete types, which implicitly
6270 if (SrcPointee->isIncompleteType()) return;
6272 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6273 if (SrcAlign >= DestAlign) return;
6275 Diag(TRange.getBegin(), diag::warn_cast_align)
6276 << Op->getType() << T
6277 << static_cast<unsigned>(SrcAlign.getQuantity())
6278 << static_cast<unsigned>(DestAlign.getQuantity())
6279 << TRange << Op->getSourceRange();
6282 static const Type* getElementType(const Expr *BaseExpr) {
6283 const Type* EltType = BaseExpr->getType().getTypePtr();
6284 if (EltType->isAnyPointerType())
6285 return EltType->getPointeeType().getTypePtr();
6286 else if (EltType->isArrayType())
6287 return EltType->getBaseElementTypeUnsafe();
6291 /// \brief Check whether this array fits the idiom of a size-one tail padded
6292 /// array member of a struct.
6294 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
6295 /// commonly used to emulate flexible arrays in C89 code.
6296 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6297 const NamedDecl *ND) {
6298 if (Size != 1 || !ND) return false;
6300 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6301 if (!FD) return false;
6303 // Don't consider sizes resulting from macro expansions or template argument
6304 // substitution to form C89 tail-padded arrays.
6306 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
6308 TypeLoc TL = TInfo->getTypeLoc();
6309 // Look through typedefs.
6310 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6311 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
6312 TInfo = TDL->getTypeSourceInfo();
6315 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6316 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
6317 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6323 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
6324 if (!RD) return false;
6325 if (RD->isUnion()) return false;
6326 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6327 if (!CRD->isStandardLayout()) return false;
6330 // See if this is the last field decl in the record.
6332 while ((D = D->getNextDeclInContext()))
6333 if (isa<FieldDecl>(D))
6338 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6339 const ArraySubscriptExpr *ASE,
6340 bool AllowOnePastEnd, bool IndexNegated) {
6341 IndexExpr = IndexExpr->IgnoreParenImpCasts();
6342 if (IndexExpr->isValueDependent())
6345 const Type *EffectiveType = getElementType(BaseExpr);
6346 BaseExpr = BaseExpr->IgnoreParenCasts();
6347 const ConstantArrayType *ArrayTy =
6348 Context.getAsConstantArrayType(BaseExpr->getType());
6353 if (!IndexExpr->EvaluateAsInt(index, Context))
6358 const NamedDecl *ND = NULL;
6359 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6360 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6361 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6362 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6364 if (index.isUnsigned() || !index.isNegative()) {
6365 llvm::APInt size = ArrayTy->getSize();
6366 if (!size.isStrictlyPositive())
6369 const Type* BaseType = getElementType(BaseExpr);
6370 if (BaseType != EffectiveType) {
6371 // Make sure we're comparing apples to apples when comparing index to size
6372 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6373 uint64_t array_typesize = Context.getTypeSize(BaseType);
6374 // Handle ptrarith_typesize being zero, such as when casting to void*
6375 if (!ptrarith_typesize) ptrarith_typesize = 1;
6376 if (ptrarith_typesize != array_typesize) {
6377 // There's a cast to a different size type involved
6378 uint64_t ratio = array_typesize / ptrarith_typesize;
6379 // TODO: Be smarter about handling cases where array_typesize is not a
6380 // multiple of ptrarith_typesize
6381 if (ptrarith_typesize * ratio == array_typesize)
6382 size *= llvm::APInt(size.getBitWidth(), ratio);
6386 if (size.getBitWidth() > index.getBitWidth())
6387 index = index.zext(size.getBitWidth());
6388 else if (size.getBitWidth() < index.getBitWidth())
6389 size = size.zext(index.getBitWidth());
6391 // For array subscripting the index must be less than size, but for pointer
6392 // arithmetic also allow the index (offset) to be equal to size since
6393 // computing the next address after the end of the array is legal and
6394 // commonly done e.g. in C++ iterators and range-based for loops.
6395 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
6398 // Also don't warn for arrays of size 1 which are members of some
6399 // structure. These are often used to approximate flexible arrays in C89
6401 if (IsTailPaddedMemberArray(*this, size, ND))
6404 // Suppress the warning if the subscript expression (as identified by the
6405 // ']' location) and the index expression are both from macro expansions
6406 // within a system header.
6408 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6409 ASE->getRBracketLoc());
6410 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6411 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6412 IndexExpr->getLocStart());
6413 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
6418 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
6420 DiagID = diag::warn_array_index_exceeds_bounds;
6422 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6423 PDiag(DiagID) << index.toString(10, true)
6424 << size.toString(10, true)
6425 << (unsigned)size.getLimitedValue(~0U)
6426 << IndexExpr->getSourceRange());
6428 unsigned DiagID = diag::warn_array_index_precedes_bounds;
6430 DiagID = diag::warn_ptr_arith_precedes_bounds;
6431 if (index.isNegative()) index = -index;
6434 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6435 PDiag(DiagID) << index.toString(10, true)
6436 << IndexExpr->getSourceRange());
6440 // Try harder to find a NamedDecl to point at in the note.
6441 while (const ArraySubscriptExpr *ASE =
6442 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6443 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6444 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6445 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6446 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6447 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6451 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6452 PDiag(diag::note_array_index_out_of_bounds)
6453 << ND->getDeclName());
6456 void Sema::CheckArrayAccess(const Expr *expr) {
6457 int AllowOnePastEnd = 0;
6459 expr = expr->IgnoreParenImpCasts();
6460 switch (expr->getStmtClass()) {
6461 case Stmt::ArraySubscriptExprClass: {
6462 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
6463 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
6464 AllowOnePastEnd > 0);
6467 case Stmt::UnaryOperatorClass: {
6468 // Only unwrap the * and & unary operators
6469 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6470 expr = UO->getSubExpr();
6471 switch (UO->getOpcode()) {
6483 case Stmt::ConditionalOperatorClass: {
6484 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6485 if (const Expr *lhs = cond->getLHS())
6486 CheckArrayAccess(lhs);
6487 if (const Expr *rhs = cond->getRHS())
6488 CheckArrayAccess(rhs);
6497 //===--- CHECK: Objective-C retain cycles ----------------------------------//
6500 struct RetainCycleOwner {
6501 RetainCycleOwner() : Variable(0), Indirect(false) {}
6507 void setLocsFrom(Expr *e) {
6508 Loc = e->getExprLoc();
6509 Range = e->getSourceRange();
6514 /// Consider whether capturing the given variable can possibly lead to
6516 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
6517 // In ARC, it's captured strongly iff the variable has __strong
6518 // lifetime. In MRR, it's captured strongly if the variable is
6519 // __block and has an appropriate type.
6520 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6523 owner.Variable = var;
6525 owner.setLocsFrom(ref);
6529 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
6531 e = e->IgnoreParens();
6532 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6533 switch (cast->getCastKind()) {
6535 case CK_LValueBitCast:
6536 case CK_LValueToRValue:
6537 case CK_ARCReclaimReturnedObject:
6538 e = cast->getSubExpr();
6546 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6547 ObjCIvarDecl *ivar = ref->getDecl();
6548 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6551 // Try to find a retain cycle in the base.
6552 if (!findRetainCycleOwner(S, ref->getBase(), owner))
6555 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6556 owner.Indirect = true;
6560 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6561 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6562 if (!var) return false;
6563 return considerVariable(var, ref, owner);
6566 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6567 if (member->isArrow()) return false;
6569 // Don't count this as an indirect ownership.
6570 e = member->getBase();
6574 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6575 // Only pay attention to pseudo-objects on property references.
6576 ObjCPropertyRefExpr *pre
6577 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6579 if (!pre) return false;
6580 if (pre->isImplicitProperty()) return false;
6581 ObjCPropertyDecl *property = pre->getExplicitProperty();
6582 if (!property->isRetaining() &&
6583 !(property->getPropertyIvarDecl() &&
6584 property->getPropertyIvarDecl()->getType()
6585 .getObjCLifetime() == Qualifiers::OCL_Strong))
6588 owner.Indirect = true;
6589 if (pre->isSuperReceiver()) {
6590 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6591 if (!owner.Variable)
6593 owner.Loc = pre->getLocation();
6594 owner.Range = pre->getSourceRange();
6597 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6609 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6610 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6611 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6612 Variable(variable), Capturer(0) {}
6617 void VisitDeclRefExpr(DeclRefExpr *ref) {
6618 if (ref->getDecl() == Variable && !Capturer)
6622 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6623 if (Capturer) return;
6624 Visit(ref->getBase());
6625 if (Capturer && ref->isFreeIvar())
6629 void VisitBlockExpr(BlockExpr *block) {
6630 // Look inside nested blocks
6631 if (block->getBlockDecl()->capturesVariable(Variable))
6632 Visit(block->getBlockDecl()->getBody());
6635 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6636 if (Capturer) return;
6637 if (OVE->getSourceExpr())
6638 Visit(OVE->getSourceExpr());
6643 /// Check whether the given argument is a block which captures a
6645 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6646 assert(owner.Variable && owner.Loc.isValid());
6648 e = e->IgnoreParenCasts();
6650 // Look through [^{...} copy] and Block_copy(^{...}).
6651 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6652 Selector Cmd = ME->getSelector();
6653 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6654 e = ME->getInstanceReceiver();
6657 e = e->IgnoreParenCasts();
6659 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6660 if (CE->getNumArgs() == 1) {
6661 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
6663 const IdentifierInfo *FnI = Fn->getIdentifier();
6664 if (FnI && FnI->isStr("_Block_copy")) {
6665 e = CE->getArg(0)->IgnoreParenCasts();
6671 BlockExpr *block = dyn_cast<BlockExpr>(e);
6672 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6675 FindCaptureVisitor visitor(S.Context, owner.Variable);
6676 visitor.Visit(block->getBlockDecl()->getBody());
6677 return visitor.Capturer;
6680 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6681 RetainCycleOwner &owner) {
6683 assert(owner.Variable && owner.Loc.isValid());
6685 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6686 << owner.Variable << capturer->getSourceRange();
6687 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6688 << owner.Indirect << owner.Range;
6691 /// Check for a keyword selector that starts with the word 'add' or
6693 static bool isSetterLikeSelector(Selector sel) {
6694 if (sel.isUnarySelector()) return false;
6696 StringRef str = sel.getNameForSlot(0);
6697 while (!str.empty() && str.front() == '_') str = str.substr(1);
6698 if (str.startswith("set"))
6699 str = str.substr(3);
6700 else if (str.startswith("add")) {
6701 // Specially whitelist 'addOperationWithBlock:'.
6702 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6704 str = str.substr(3);
6709 if (str.empty()) return true;
6710 return !isLowercase(str.front());
6713 /// Check a message send to see if it's likely to cause a retain cycle.
6714 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6715 // Only check instance methods whose selector looks like a setter.
6716 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6719 // Try to find a variable that the receiver is strongly owned by.
6720 RetainCycleOwner owner;
6721 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
6722 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
6725 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6726 owner.Variable = getCurMethodDecl()->getSelfDecl();
6727 owner.Loc = msg->getSuperLoc();
6728 owner.Range = msg->getSuperLoc();
6731 // Check whether the receiver is captured by any of the arguments.
6732 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6733 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6734 return diagnoseRetainCycle(*this, capturer, owner);
6737 /// Check a property assign to see if it's likely to cause a retain cycle.
6738 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6739 RetainCycleOwner owner;
6740 if (!findRetainCycleOwner(*this, receiver, owner))
6743 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6744 diagnoseRetainCycle(*this, capturer, owner);
6747 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6748 RetainCycleOwner Owner;
6749 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6752 // Because we don't have an expression for the variable, we have to set the
6753 // location explicitly here.
6754 Owner.Loc = Var->getLocation();
6755 Owner.Range = Var->getSourceRange();
6757 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6758 diagnoseRetainCycle(*this, Capturer, Owner);
6761 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6762 Expr *RHS, bool isProperty) {
6763 // Check if RHS is an Objective-C object literal, which also can get
6764 // immediately zapped in a weak reference. Note that we explicitly
6765 // allow ObjCStringLiterals, since those are designed to never really die.
6766 RHS = RHS->IgnoreParenImpCasts();
6768 // This enum needs to match with the 'select' in
6769 // warn_objc_arc_literal_assign (off-by-1).
6770 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6771 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6774 S.Diag(Loc, diag::warn_arc_literal_assign)
6776 << (isProperty ? 0 : 1)
6777 << RHS->getSourceRange();
6782 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6783 Qualifiers::ObjCLifetime LT,
6784 Expr *RHS, bool isProperty) {
6785 // Strip off any implicit cast added to get to the one ARC-specific.
6786 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6787 if (cast->getCastKind() == CK_ARCConsumeObject) {
6788 S.Diag(Loc, diag::warn_arc_retained_assign)
6789 << (LT == Qualifiers::OCL_ExplicitNone)
6790 << (isProperty ? 0 : 1)
6791 << RHS->getSourceRange();
6794 RHS = cast->getSubExpr();
6797 if (LT == Qualifiers::OCL_Weak &&
6798 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6804 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6805 QualType LHS, Expr *RHS) {
6806 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6808 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6811 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6817 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6818 Expr *LHS, Expr *RHS) {
6820 // PropertyRef on LHS type need be directly obtained from
6821 // its declaration as it has a PsuedoType.
6822 ObjCPropertyRefExpr *PRE
6823 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6824 if (PRE && !PRE->isImplicitProperty()) {
6825 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6827 LHSType = PD->getType();
6830 if (LHSType.isNull())
6831 LHSType = LHS->getType();
6833 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6835 if (LT == Qualifiers::OCL_Weak) {
6836 DiagnosticsEngine::Level Level =
6837 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6838 if (Level != DiagnosticsEngine::Ignored)
6839 getCurFunction()->markSafeWeakUse(LHS);
6842 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6845 // FIXME. Check for other life times.
6846 if (LT != Qualifiers::OCL_None)
6850 if (PRE->isImplicitProperty())
6852 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6856 unsigned Attributes = PD->getPropertyAttributes();
6857 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
6858 // when 'assign' attribute was not explicitly specified
6859 // by user, ignore it and rely on property type itself
6860 // for lifetime info.
6861 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6862 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6863 LHSType->isObjCRetainableType())
6866 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6867 if (cast->getCastKind() == CK_ARCConsumeObject) {
6868 Diag(Loc, diag::warn_arc_retained_property_assign)
6869 << RHS->getSourceRange();
6872 RHS = cast->getSubExpr();
6875 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
6876 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6882 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6885 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6886 SourceLocation StmtLoc,
6887 const NullStmt *Body) {
6888 // Do not warn if the body is a macro that expands to nothing, e.g:
6894 if (Body->hasLeadingEmptyMacro())
6897 // Get line numbers of statement and body.
6898 bool StmtLineInvalid;
6899 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6901 if (StmtLineInvalid)
6904 bool BodyLineInvalid;
6905 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6907 if (BodyLineInvalid)
6910 // Warn if null statement and body are on the same line.
6911 if (StmtLine != BodyLine)
6916 } // Unnamed namespace
6918 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6921 // Since this is a syntactic check, don't emit diagnostic for template
6922 // instantiations, this just adds noise.
6923 if (CurrentInstantiationScope)
6926 // The body should be a null statement.
6927 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6931 // Do the usual checks.
6932 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6935 Diag(NBody->getSemiLoc(), DiagID);
6936 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6939 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6940 const Stmt *PossibleBody) {
6941 assert(!CurrentInstantiationScope); // Ensured by caller
6943 SourceLocation StmtLoc;
6946 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6947 StmtLoc = FS->getRParenLoc();
6948 Body = FS->getBody();
6949 DiagID = diag::warn_empty_for_body;
6950 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6951 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6952 Body = WS->getBody();
6953 DiagID = diag::warn_empty_while_body;
6955 return; // Neither `for' nor `while'.
6957 // The body should be a null statement.
6958 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6962 // Skip expensive checks if diagnostic is disabled.
6963 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6964 DiagnosticsEngine::Ignored)
6967 // Do the usual checks.
6968 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6971 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6972 // noise level low, emit diagnostics only if for/while is followed by a
6973 // CompoundStmt, e.g.:
6974 // for (int i = 0; i < n; i++);
6978 // or if for/while is followed by a statement with more indentation
6979 // than for/while itself:
6980 // for (int i = 0; i < n; i++);
6982 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6983 if (!ProbableTypo) {
6984 bool BodyColInvalid;
6985 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6986 PossibleBody->getLocStart(),
6991 bool StmtColInvalid;
6992 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6998 if (BodyCol > StmtCol)
6999 ProbableTypo = true;
7003 Diag(NBody->getSemiLoc(), DiagID);
7004 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7008 //===--- Layout compatibility ----------------------------------------------//
7012 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7014 /// \brief Check if two enumeration types are layout-compatible.
7015 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7016 // C++11 [dcl.enum] p8:
7017 // Two enumeration types are layout-compatible if they have the same
7019 return ED1->isComplete() && ED2->isComplete() &&
7020 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7023 /// \brief Check if two fields are layout-compatible.
7024 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7025 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7028 if (Field1->isBitField() != Field2->isBitField())
7031 if (Field1->isBitField()) {
7032 // Make sure that the bit-fields are the same length.
7033 unsigned Bits1 = Field1->getBitWidthValue(C);
7034 unsigned Bits2 = Field2->getBitWidthValue(C);
7043 /// \brief Check if two standard-layout structs are layout-compatible.
7044 /// (C++11 [class.mem] p17)
7045 bool isLayoutCompatibleStruct(ASTContext &C,
7048 // If both records are C++ classes, check that base classes match.
7049 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7050 // If one of records is a CXXRecordDecl we are in C++ mode,
7051 // thus the other one is a CXXRecordDecl, too.
7052 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7053 // Check number of base classes.
7054 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7057 // Check the base classes.
7058 for (CXXRecordDecl::base_class_const_iterator
7059 Base1 = D1CXX->bases_begin(),
7060 BaseEnd1 = D1CXX->bases_end(),
7061 Base2 = D2CXX->bases_begin();
7064 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7067 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7068 // If only RD2 is a C++ class, it should have zero base classes.
7069 if (D2CXX->getNumBases() > 0)
7073 // Check the fields.
7074 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7075 Field2End = RD2->field_end(),
7076 Field1 = RD1->field_begin(),
7077 Field1End = RD1->field_end();
7078 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7079 if (!isLayoutCompatible(C, *Field1, *Field2))
7082 if (Field1 != Field1End || Field2 != Field2End)
7088 /// \brief Check if two standard-layout unions are layout-compatible.
7089 /// (C++11 [class.mem] p18)
7090 bool isLayoutCompatibleUnion(ASTContext &C,
7093 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7094 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7095 Field2End = RD2->field_end();
7096 Field2 != Field2End; ++Field2) {
7097 UnmatchedFields.insert(*Field2);
7100 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7101 Field1End = RD1->field_end();
7102 Field1 != Field1End; ++Field1) {
7103 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7104 I = UnmatchedFields.begin(),
7105 E = UnmatchedFields.end();
7107 for ( ; I != E; ++I) {
7108 if (isLayoutCompatible(C, *Field1, *I)) {
7109 bool Result = UnmatchedFields.erase(*I);
7119 return UnmatchedFields.empty();
7122 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7123 if (RD1->isUnion() != RD2->isUnion())
7127 return isLayoutCompatibleUnion(C, RD1, RD2);
7129 return isLayoutCompatibleStruct(C, RD1, RD2);
7132 /// \brief Check if two types are layout-compatible in C++11 sense.
7133 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7134 if (T1.isNull() || T2.isNull())
7137 // C++11 [basic.types] p11:
7138 // If two types T1 and T2 are the same type, then T1 and T2 are
7139 // layout-compatible types.
7140 if (C.hasSameType(T1, T2))
7143 T1 = T1.getCanonicalType().getUnqualifiedType();
7144 T2 = T2.getCanonicalType().getUnqualifiedType();
7146 const Type::TypeClass TC1 = T1->getTypeClass();
7147 const Type::TypeClass TC2 = T2->getTypeClass();
7152 if (TC1 == Type::Enum) {
7153 return isLayoutCompatible(C,
7154 cast<EnumType>(T1)->getDecl(),
7155 cast<EnumType>(T2)->getDecl());
7156 } else if (TC1 == Type::Record) {
7157 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7160 return isLayoutCompatible(C,
7161 cast<RecordType>(T1)->getDecl(),
7162 cast<RecordType>(T2)->getDecl());
7169 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7172 /// \brief Given a type tag expression find the type tag itself.
7174 /// \param TypeExpr Type tag expression, as it appears in user's code.
7176 /// \param VD Declaration of an identifier that appears in a type tag.
7178 /// \param MagicValue Type tag magic value.
7179 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7180 const ValueDecl **VD, uint64_t *MagicValue) {
7185 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7187 switch (TypeExpr->getStmtClass()) {
7188 case Stmt::UnaryOperatorClass: {
7189 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7190 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7191 TypeExpr = UO->getSubExpr();
7197 case Stmt::DeclRefExprClass: {
7198 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7199 *VD = DRE->getDecl();
7203 case Stmt::IntegerLiteralClass: {
7204 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7205 llvm::APInt MagicValueAPInt = IL->getValue();
7206 if (MagicValueAPInt.getActiveBits() <= 64) {
7207 *MagicValue = MagicValueAPInt.getZExtValue();
7213 case Stmt::BinaryConditionalOperatorClass:
7214 case Stmt::ConditionalOperatorClass: {
7215 const AbstractConditionalOperator *ACO =
7216 cast<AbstractConditionalOperator>(TypeExpr);
7218 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7220 TypeExpr = ACO->getTrueExpr();
7222 TypeExpr = ACO->getFalseExpr();
7228 case Stmt::BinaryOperatorClass: {
7229 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7230 if (BO->getOpcode() == BO_Comma) {
7231 TypeExpr = BO->getRHS();
7243 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
7245 /// \param TypeExpr Expression that specifies a type tag.
7247 /// \param MagicValues Registered magic values.
7249 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7252 /// \param TypeInfo Information about the corresponding C type.
7254 /// \returns true if the corresponding C type was found.
7255 bool GetMatchingCType(
7256 const IdentifierInfo *ArgumentKind,
7257 const Expr *TypeExpr, const ASTContext &Ctx,
7258 const llvm::DenseMap<Sema::TypeTagMagicValue,
7259 Sema::TypeTagData> *MagicValues,
7260 bool &FoundWrongKind,
7261 Sema::TypeTagData &TypeInfo) {
7262 FoundWrongKind = false;
7264 // Variable declaration that has type_tag_for_datatype attribute.
7265 const ValueDecl *VD = NULL;
7267 uint64_t MagicValue;
7269 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7273 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7274 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7275 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7277 if (I->getArgumentKind() != ArgumentKind) {
7278 FoundWrongKind = true;
7281 TypeInfo.Type = I->getMatchingCType();
7282 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7283 TypeInfo.MustBeNull = I->getMustBeNull();
7292 llvm::DenseMap<Sema::TypeTagMagicValue,
7293 Sema::TypeTagData>::const_iterator I =
7294 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7295 if (I == MagicValues->end())
7298 TypeInfo = I->second;
7301 } // unnamed namespace
7303 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7304 uint64_t MagicValue, QualType Type,
7305 bool LayoutCompatible,
7307 if (!TypeTagForDatatypeMagicValues)
7308 TypeTagForDatatypeMagicValues.reset(
7309 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7311 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7312 (*TypeTagForDatatypeMagicValues)[Magic] =
7313 TypeTagData(Type, LayoutCompatible, MustBeNull);
7317 bool IsSameCharType(QualType T1, QualType T2) {
7318 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7322 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7326 BuiltinType::Kind T1Kind = BT1->getKind();
7327 BuiltinType::Kind T2Kind = BT2->getKind();
7329 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7330 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7331 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7332 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7334 } // unnamed namespace
7336 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7337 const Expr * const *ExprArgs) {
7338 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7339 bool IsPointerAttr = Attr->getIsPointer();
7341 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7342 bool FoundWrongKind;
7343 TypeTagData TypeInfo;
7344 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7345 TypeTagForDatatypeMagicValues.get(),
7346 FoundWrongKind, TypeInfo)) {
7348 Diag(TypeTagExpr->getExprLoc(),
7349 diag::warn_type_tag_for_datatype_wrong_kind)
7350 << TypeTagExpr->getSourceRange();
7354 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7355 if (IsPointerAttr) {
7356 // Skip implicit cast of pointer to `void *' (as a function argument).
7357 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
7358 if (ICE->getType()->isVoidPointerType() &&
7359 ICE->getCastKind() == CK_BitCast)
7360 ArgumentExpr = ICE->getSubExpr();
7362 QualType ArgumentType = ArgumentExpr->getType();
7364 // Passing a `void*' pointer shouldn't trigger a warning.
7365 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7368 if (TypeInfo.MustBeNull) {
7369 // Type tag with matching void type requires a null pointer.
7370 if (!ArgumentExpr->isNullPointerConstant(Context,
7371 Expr::NPC_ValueDependentIsNotNull)) {
7372 Diag(ArgumentExpr->getExprLoc(),
7373 diag::warn_type_safety_null_pointer_required)
7374 << ArgumentKind->getName()
7375 << ArgumentExpr->getSourceRange()
7376 << TypeTagExpr->getSourceRange();
7381 QualType RequiredType = TypeInfo.Type;
7383 RequiredType = Context.getPointerType(RequiredType);
7385 bool mismatch = false;
7386 if (!TypeInfo.LayoutCompatible) {
7387 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7389 // C++11 [basic.fundamental] p1:
7390 // Plain char, signed char, and unsigned char are three distinct types.
7392 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7393 // char' depending on the current char signedness mode.
7395 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7396 RequiredType->getPointeeType())) ||
7397 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7401 mismatch = !isLayoutCompatible(Context,
7402 ArgumentType->getPointeeType(),
7403 RequiredType->getPointeeType());
7405 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7408 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7409 << ArgumentType << ArgumentKind->getName()
7410 << TypeInfo.LayoutCompatible << RequiredType
7411 << ArgumentExpr->getSourceRange()
7412 << TypeTagExpr->getSourceRange();