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/Initialization.h"
16 #include "clang/Sema/Sema.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/Lookup.h"
20 #include "clang/Sema/ScopeInfo.h"
21 #include "clang/Analysis/Analyses/FormatString.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/EvaluatedExprVisitor.h"
30 #include "clang/AST/DeclObjC.h"
31 #include "clang/AST/StmtCXX.h"
32 #include "clang/AST/StmtObjC.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "clang/Basic/TargetBuiltins.h"
39 #include "clang/Basic/TargetInfo.h"
40 #include "clang/Basic/ConvertUTF.h"
42 using namespace clang;
45 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
47 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
48 PP.getLangOpts(), PP.getTargetInfo());
51 /// Checks that a call expression's argument count is the desired number.
52 /// This is useful when doing custom type-checking. Returns true on error.
53 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
71 /// Check that the first argument to __builtin_annotation is an integer
72 /// and the second argument is a non-wide string literal.
73 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
100 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
101 ExprResult TheCallResult(Owned(TheCall));
103 // Find out if any arguments are required to be integer constant expressions.
104 unsigned ICEArguments = 0;
105 ASTContext::GetBuiltinTypeError Error;
106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
107 if (Error != ASTContext::GE_None)
108 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
110 // If any arguments are required to be ICE's, check and diagnose.
111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
112 // Skip arguments not required to be ICE's.
113 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
118 ICEArguments &= ~(1 << ArgNo);
122 case Builtin::BI__builtin___CFStringMakeConstantString:
123 assert(TheCall->getNumArgs() == 1 &&
124 "Wrong # arguments to builtin CFStringMakeConstantString");
125 if (CheckObjCString(TheCall->getArg(0)))
128 case Builtin::BI__builtin_stdarg_start:
129 case Builtin::BI__builtin_va_start:
130 if (SemaBuiltinVAStart(TheCall))
133 case Builtin::BI__builtin_isgreater:
134 case Builtin::BI__builtin_isgreaterequal:
135 case Builtin::BI__builtin_isless:
136 case Builtin::BI__builtin_islessequal:
137 case Builtin::BI__builtin_islessgreater:
138 case Builtin::BI__builtin_isunordered:
139 if (SemaBuiltinUnorderedCompare(TheCall))
142 case Builtin::BI__builtin_fpclassify:
143 if (SemaBuiltinFPClassification(TheCall, 6))
146 case Builtin::BI__builtin_isfinite:
147 case Builtin::BI__builtin_isinf:
148 case Builtin::BI__builtin_isinf_sign:
149 case Builtin::BI__builtin_isnan:
150 case Builtin::BI__builtin_isnormal:
151 if (SemaBuiltinFPClassification(TheCall, 1))
154 case Builtin::BI__builtin_shufflevector:
155 return SemaBuiltinShuffleVector(TheCall);
156 // TheCall will be freed by the smart pointer here, but that's fine, since
157 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
158 case Builtin::BI__builtin_prefetch:
159 if (SemaBuiltinPrefetch(TheCall))
162 case Builtin::BI__builtin_object_size:
163 if (SemaBuiltinObjectSize(TheCall))
166 case Builtin::BI__builtin_longjmp:
167 if (SemaBuiltinLongjmp(TheCall))
171 case Builtin::BI__builtin_classify_type:
172 if (checkArgCount(*this, TheCall, 1)) return true;
173 TheCall->setType(Context.IntTy);
175 case Builtin::BI__builtin_constant_p:
176 if (checkArgCount(*this, TheCall, 1)) return true;
177 TheCall->setType(Context.IntTy);
179 case Builtin::BI__sync_fetch_and_add:
180 case Builtin::BI__sync_fetch_and_add_1:
181 case Builtin::BI__sync_fetch_and_add_2:
182 case Builtin::BI__sync_fetch_and_add_4:
183 case Builtin::BI__sync_fetch_and_add_8:
184 case Builtin::BI__sync_fetch_and_add_16:
185 case Builtin::BI__sync_fetch_and_sub:
186 case Builtin::BI__sync_fetch_and_sub_1:
187 case Builtin::BI__sync_fetch_and_sub_2:
188 case Builtin::BI__sync_fetch_and_sub_4:
189 case Builtin::BI__sync_fetch_and_sub_8:
190 case Builtin::BI__sync_fetch_and_sub_16:
191 case Builtin::BI__sync_fetch_and_or:
192 case Builtin::BI__sync_fetch_and_or_1:
193 case Builtin::BI__sync_fetch_and_or_2:
194 case Builtin::BI__sync_fetch_and_or_4:
195 case Builtin::BI__sync_fetch_and_or_8:
196 case Builtin::BI__sync_fetch_and_or_16:
197 case Builtin::BI__sync_fetch_and_and:
198 case Builtin::BI__sync_fetch_and_and_1:
199 case Builtin::BI__sync_fetch_and_and_2:
200 case Builtin::BI__sync_fetch_and_and_4:
201 case Builtin::BI__sync_fetch_and_and_8:
202 case Builtin::BI__sync_fetch_and_and_16:
203 case Builtin::BI__sync_fetch_and_xor:
204 case Builtin::BI__sync_fetch_and_xor_1:
205 case Builtin::BI__sync_fetch_and_xor_2:
206 case Builtin::BI__sync_fetch_and_xor_4:
207 case Builtin::BI__sync_fetch_and_xor_8:
208 case Builtin::BI__sync_fetch_and_xor_16:
209 case Builtin::BI__sync_add_and_fetch:
210 case Builtin::BI__sync_add_and_fetch_1:
211 case Builtin::BI__sync_add_and_fetch_2:
212 case Builtin::BI__sync_add_and_fetch_4:
213 case Builtin::BI__sync_add_and_fetch_8:
214 case Builtin::BI__sync_add_and_fetch_16:
215 case Builtin::BI__sync_sub_and_fetch:
216 case Builtin::BI__sync_sub_and_fetch_1:
217 case Builtin::BI__sync_sub_and_fetch_2:
218 case Builtin::BI__sync_sub_and_fetch_4:
219 case Builtin::BI__sync_sub_and_fetch_8:
220 case Builtin::BI__sync_sub_and_fetch_16:
221 case Builtin::BI__sync_and_and_fetch:
222 case Builtin::BI__sync_and_and_fetch_1:
223 case Builtin::BI__sync_and_and_fetch_2:
224 case Builtin::BI__sync_and_and_fetch_4:
225 case Builtin::BI__sync_and_and_fetch_8:
226 case Builtin::BI__sync_and_and_fetch_16:
227 case Builtin::BI__sync_or_and_fetch:
228 case Builtin::BI__sync_or_and_fetch_1:
229 case Builtin::BI__sync_or_and_fetch_2:
230 case Builtin::BI__sync_or_and_fetch_4:
231 case Builtin::BI__sync_or_and_fetch_8:
232 case Builtin::BI__sync_or_and_fetch_16:
233 case Builtin::BI__sync_xor_and_fetch:
234 case Builtin::BI__sync_xor_and_fetch_1:
235 case Builtin::BI__sync_xor_and_fetch_2:
236 case Builtin::BI__sync_xor_and_fetch_4:
237 case Builtin::BI__sync_xor_and_fetch_8:
238 case Builtin::BI__sync_xor_and_fetch_16:
239 case Builtin::BI__sync_val_compare_and_swap:
240 case Builtin::BI__sync_val_compare_and_swap_1:
241 case Builtin::BI__sync_val_compare_and_swap_2:
242 case Builtin::BI__sync_val_compare_and_swap_4:
243 case Builtin::BI__sync_val_compare_and_swap_8:
244 case Builtin::BI__sync_val_compare_and_swap_16:
245 case Builtin::BI__sync_bool_compare_and_swap:
246 case Builtin::BI__sync_bool_compare_and_swap_1:
247 case Builtin::BI__sync_bool_compare_and_swap_2:
248 case Builtin::BI__sync_bool_compare_and_swap_4:
249 case Builtin::BI__sync_bool_compare_and_swap_8:
250 case Builtin::BI__sync_bool_compare_and_swap_16:
251 case Builtin::BI__sync_lock_test_and_set:
252 case Builtin::BI__sync_lock_test_and_set_1:
253 case Builtin::BI__sync_lock_test_and_set_2:
254 case Builtin::BI__sync_lock_test_and_set_4:
255 case Builtin::BI__sync_lock_test_and_set_8:
256 case Builtin::BI__sync_lock_test_and_set_16:
257 case Builtin::BI__sync_lock_release:
258 case Builtin::BI__sync_lock_release_1:
259 case Builtin::BI__sync_lock_release_2:
260 case Builtin::BI__sync_lock_release_4:
261 case Builtin::BI__sync_lock_release_8:
262 case Builtin::BI__sync_lock_release_16:
263 case Builtin::BI__sync_swap:
264 case Builtin::BI__sync_swap_1:
265 case Builtin::BI__sync_swap_2:
266 case Builtin::BI__sync_swap_4:
267 case Builtin::BI__sync_swap_8:
268 case Builtin::BI__sync_swap_16:
269 return SemaBuiltinAtomicOverloaded(TheCallResult);
270 #define BUILTIN(ID, TYPE, ATTRS)
271 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
272 case Builtin::BI##ID: \
273 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
274 #include "clang/Basic/Builtins.def"
275 case Builtin::BI__builtin_annotation:
276 if (SemaBuiltinAnnotation(*this, TheCall))
281 // Since the target specific builtins for each arch overlap, only check those
282 // of the arch we are compiling for.
283 if (BuiltinID >= Builtin::FirstTSBuiltin) {
284 switch (Context.getTargetInfo().getTriple().getArch()) {
285 case llvm::Triple::arm:
286 case llvm::Triple::thumb:
287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
290 case llvm::Triple::mips:
291 case llvm::Triple::mipsel:
292 case llvm::Triple::mips64:
293 case llvm::Triple::mips64el:
294 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
302 return TheCallResult;
305 // Get the valid immediate range for the specified NEON type code.
306 static unsigned RFT(unsigned t, bool shift = false) {
307 NeonTypeFlags Type(t);
308 int IsQuad = Type.isQuad();
309 switch (Type.getEltType()) {
310 case NeonTypeFlags::Int8:
311 case NeonTypeFlags::Poly8:
312 return shift ? 7 : (8 << IsQuad) - 1;
313 case NeonTypeFlags::Int16:
314 case NeonTypeFlags::Poly16:
315 return shift ? 15 : (4 << IsQuad) - 1;
316 case NeonTypeFlags::Int32:
317 return shift ? 31 : (2 << IsQuad) - 1;
318 case NeonTypeFlags::Int64:
319 return shift ? 63 : (1 << IsQuad) - 1;
320 case NeonTypeFlags::Float16:
321 assert(!shift && "cannot shift float types!");
322 return (4 << IsQuad) - 1;
323 case NeonTypeFlags::Float32:
324 assert(!shift && "cannot shift float types!");
325 return (2 << IsQuad) - 1;
327 llvm_unreachable("Invalid NeonTypeFlag!");
330 /// getNeonEltType - Return the QualType corresponding to the elements of
331 /// the vector type specified by the NeonTypeFlags. This is used to check
332 /// the pointer arguments for Neon load/store intrinsics.
333 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
334 switch (Flags.getEltType()) {
335 case NeonTypeFlags::Int8:
336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
337 case NeonTypeFlags::Int16:
338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
339 case NeonTypeFlags::Int32:
340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
341 case NeonTypeFlags::Int64:
342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
343 case NeonTypeFlags::Poly8:
344 return Context.SignedCharTy;
345 case NeonTypeFlags::Poly16:
346 return Context.ShortTy;
347 case NeonTypeFlags::Float16:
348 return Context.UnsignedShortTy;
349 case NeonTypeFlags::Float32:
350 return Context.FloatTy;
352 llvm_unreachable("Invalid NeonTypeFlag!");
355 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
361 bool HasConstPtr = false;
363 #define GET_NEON_OVERLOAD_CHECK
364 #include "clang/Basic/arm_neon.inc"
365 #undef GET_NEON_OVERLOAD_CHECK
368 // For NEON intrinsics which are overloaded on vector element type, validate
369 // the immediate which specifies which variant to emit.
370 unsigned ImmArg = TheCall->getNumArgs()-1;
372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
375 TV = Result.getLimitedValue(64);
376 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
378 << TheCall->getArg(ImmArg)->getSourceRange();
381 if (PtrArgNum >= 0) {
382 // Check that pointer arguments have the specified type.
383 Expr *Arg = TheCall->getArg(PtrArgNum);
384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
385 Arg = ICE->getSubExpr();
386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
387 QualType RHSTy = RHS.get()->getType();
388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
390 EltTy = EltTy.withConst();
391 QualType LHSTy = Context.getPointerType(EltTy);
392 AssignConvertType ConvTy;
393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
397 RHS.get(), AA_Assigning))
401 // For NEON intrinsics which take an immediate value as part of the
402 // instruction, range check them here.
403 unsigned i = 0, l = 0, u = 0;
405 default: return false;
406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
408 case ARM::BI__builtin_arm_vcvtr_f:
409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
410 #define GET_NEON_IMMEDIATE_CHECK
411 #include "clang/Basic/arm_neon.inc"
412 #undef GET_NEON_IMMEDIATE_CHECK
415 // We can't check the value of a dependent argument.
416 if (TheCall->getArg(i)->isTypeDependent() ||
417 TheCall->getArg(i)->isValueDependent())
420 // Check that the immediate argument is actually a constant.
421 if (SemaBuiltinConstantArg(TheCall, i, Result))
424 // Range check against the upper/lower values for this isntruction.
425 unsigned Val = Result.getZExtValue();
426 if (Val < l || Val > (u + l))
427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
428 << l << u+l << TheCall->getArg(i)->getSourceRange();
430 // FIXME: VFP Intrinsics should error if VFP not present.
434 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
435 unsigned i = 0, l = 0, u = 0;
437 default: return false;
438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
440 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
441 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
442 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
444 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
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.
454 if (SemaBuiltinConstantArg(TheCall, i, Result))
457 // Range check against the upper/lower values for this instruction.
458 unsigned Val = Result.getZExtValue();
459 if (Val < l || Val > u)
460 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
461 << l << u << TheCall->getArg(i)->getSourceRange();
466 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
467 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
468 /// Returns true when the format fits the function and the FormatStringInfo has
470 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
471 FormatStringInfo *FSI) {
472 FSI->HasVAListArg = Format->getFirstArg() == 0;
473 FSI->FormatIdx = Format->getFormatIdx() - 1;
474 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
476 // The way the format attribute works in GCC, the implicit this argument
477 // of member functions is counted. However, it doesn't appear in our own
478 // lists, so decrement format_idx in that case.
480 if(FSI->FormatIdx == 0)
483 if (FSI->FirstDataArg != 0)
489 /// Handles the checks for format strings, non-POD arguments to vararg
490 /// functions, and NULL arguments passed to non-NULL parameters.
491 void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
493 unsigned NumProtoArgs,
494 bool IsMemberFunction,
497 VariadicCallType CallType) {
498 if (CurContext->isDependentContext())
501 // Printf and scanf checking.
502 bool HandledFormatString = false;
503 for (specific_attr_iterator<FormatAttr>
504 I = FDecl->specific_attr_begin<FormatAttr>(),
505 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
506 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
508 HandledFormatString = true;
510 // Refuse POD arguments that weren't caught by the format string
512 if (!HandledFormatString && CallType != VariadicDoesNotApply)
513 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx) {
514 // Args[ArgIdx] can be null in malformed code.
515 if (Expr *Arg = Args[ArgIdx])
516 variadicArgumentPODCheck(Arg, CallType);
519 for (specific_attr_iterator<NonNullAttr>
520 I = FDecl->specific_attr_begin<NonNullAttr>(),
521 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
522 CheckNonNullArguments(*I, Args, Loc);
524 // Type safety checking.
525 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
526 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
527 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
528 CheckArgumentWithTypeTag(*i, Args);
532 /// CheckConstructorCall - Check a constructor call for correctness and safety
533 /// properties not enforced by the C type system.
534 void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
536 const FunctionProtoType *Proto,
537 SourceLocation Loc) {
538 VariadicCallType CallType =
539 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
540 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
541 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
544 /// CheckFunctionCall - Check a direct function call for various correctness
545 /// and safety properties not strictly enforced by the C type system.
546 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
547 const FunctionProtoType *Proto) {
548 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
549 isa<CXXMethodDecl>(FDecl);
550 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
551 IsMemberOperatorCall;
552 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
553 TheCall->getCallee());
554 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
555 Expr** Args = TheCall->getArgs();
556 unsigned NumArgs = TheCall->getNumArgs();
557 if (IsMemberOperatorCall) {
558 // If this is a call to a member operator, hide the first argument
560 // FIXME: Our choice of AST representation here is less than ideal.
564 checkCall(FDecl, Args, NumArgs, NumProtoArgs,
565 IsMemberFunction, TheCall->getRParenLoc(),
566 TheCall->getCallee()->getSourceRange(), CallType);
568 IdentifierInfo *FnInfo = FDecl->getIdentifier();
569 // None of the checks below are needed for functions that don't have
570 // simple names (e.g., C++ conversion functions).
574 unsigned CMId = FDecl->getMemoryFunctionKind();
578 // Handle memory setting and copying functions.
579 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
580 CheckStrlcpycatArguments(TheCall, FnInfo);
581 else if (CMId == Builtin::BIstrncat)
582 CheckStrncatArguments(TheCall, FnInfo);
584 CheckMemaccessArguments(TheCall, CMId, FnInfo);
589 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
590 Expr **Args, unsigned NumArgs) {
591 VariadicCallType CallType =
592 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
594 checkCall(Method, Args, NumArgs, Method->param_size(),
595 /*IsMemberFunction=*/false,
596 lbrac, Method->getSourceRange(), CallType);
601 bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
602 const FunctionProtoType *Proto) {
603 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
607 QualType Ty = V->getType();
608 if (!Ty->isBlockPointerType())
611 VariadicCallType CallType =
612 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
613 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
615 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
616 NumProtoArgs, /*IsMemberFunction=*/false,
617 TheCall->getRParenLoc(),
618 TheCall->getCallee()->getSourceRange(), CallType);
623 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
624 AtomicExpr::AtomicOp Op) {
625 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
626 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
628 // All these operations take one of the following forms:
630 // C __c11_atomic_init(A *, C)
632 // C __c11_atomic_load(A *, int)
634 // void __atomic_load(A *, CP, int)
636 // C __c11_atomic_add(A *, M, int)
638 // C __atomic_exchange_n(A *, CP, int)
640 // void __atomic_exchange(A *, C *, CP, int)
642 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
644 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
647 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
648 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
650 // C is an appropriate type,
651 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
652 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
653 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
654 // the int parameters are for orderings.
656 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
657 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
658 && "need to update code for modified C11 atomics");
659 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
660 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
661 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
662 Op == AtomicExpr::AO__atomic_store_n ||
663 Op == AtomicExpr::AO__atomic_exchange_n ||
664 Op == AtomicExpr::AO__atomic_compare_exchange_n;
665 bool IsAddSub = false;
668 case AtomicExpr::AO__c11_atomic_init:
672 case AtomicExpr::AO__c11_atomic_load:
673 case AtomicExpr::AO__atomic_load_n:
677 case AtomicExpr::AO__c11_atomic_store:
678 case AtomicExpr::AO__atomic_load:
679 case AtomicExpr::AO__atomic_store:
680 case AtomicExpr::AO__atomic_store_n:
684 case AtomicExpr::AO__c11_atomic_fetch_add:
685 case AtomicExpr::AO__c11_atomic_fetch_sub:
686 case AtomicExpr::AO__atomic_fetch_add:
687 case AtomicExpr::AO__atomic_fetch_sub:
688 case AtomicExpr::AO__atomic_add_fetch:
689 case AtomicExpr::AO__atomic_sub_fetch:
692 case AtomicExpr::AO__c11_atomic_fetch_and:
693 case AtomicExpr::AO__c11_atomic_fetch_or:
694 case AtomicExpr::AO__c11_atomic_fetch_xor:
695 case AtomicExpr::AO__atomic_fetch_and:
696 case AtomicExpr::AO__atomic_fetch_or:
697 case AtomicExpr::AO__atomic_fetch_xor:
698 case AtomicExpr::AO__atomic_fetch_nand:
699 case AtomicExpr::AO__atomic_and_fetch:
700 case AtomicExpr::AO__atomic_or_fetch:
701 case AtomicExpr::AO__atomic_xor_fetch:
702 case AtomicExpr::AO__atomic_nand_fetch:
706 case AtomicExpr::AO__c11_atomic_exchange:
707 case AtomicExpr::AO__atomic_exchange_n:
711 case AtomicExpr::AO__atomic_exchange:
715 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
716 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
720 case AtomicExpr::AO__atomic_compare_exchange:
721 case AtomicExpr::AO__atomic_compare_exchange_n:
726 // Check we have the right number of arguments.
727 if (TheCall->getNumArgs() < NumArgs[Form]) {
728 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
729 << 0 << NumArgs[Form] << TheCall->getNumArgs()
730 << TheCall->getCallee()->getSourceRange();
732 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
733 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
734 diag::err_typecheck_call_too_many_args)
735 << 0 << NumArgs[Form] << TheCall->getNumArgs()
736 << TheCall->getCallee()->getSourceRange();
740 // Inspect the first argument of the atomic operation.
741 Expr *Ptr = TheCall->getArg(0);
742 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
743 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
745 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
746 << Ptr->getType() << Ptr->getSourceRange();
750 // For a __c11 builtin, this should be a pointer to an _Atomic type.
751 QualType AtomTy = pointerType->getPointeeType(); // 'A'
752 QualType ValType = AtomTy; // 'C'
754 if (!AtomTy->isAtomicType()) {
755 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
756 << Ptr->getType() << Ptr->getSourceRange();
759 if (AtomTy.isConstQualified()) {
760 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
761 << Ptr->getType() << Ptr->getSourceRange();
764 ValType = AtomTy->getAs<AtomicType>()->getValueType();
767 // For an arithmetic operation, the implied arithmetic must be well-formed.
768 if (Form == Arithmetic) {
769 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
770 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
771 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
772 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
775 if (!IsAddSub && !ValType->isIntegerType()) {
776 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
777 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
780 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
781 // For __atomic_*_n operations, the value type must be a scalar integral or
782 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
783 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
784 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
788 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
789 // For GNU atomics, require a trivially-copyable type. This is not part of
790 // the GNU atomics specification, but we enforce it for sanity.
791 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
792 << Ptr->getType() << Ptr->getSourceRange();
796 // FIXME: For any builtin other than a load, the ValType must not be
799 switch (ValType.getObjCLifetime()) {
800 case Qualifiers::OCL_None:
801 case Qualifiers::OCL_ExplicitNone:
805 case Qualifiers::OCL_Weak:
806 case Qualifiers::OCL_Strong:
807 case Qualifiers::OCL_Autoreleasing:
808 // FIXME: Can this happen? By this point, ValType should be known
809 // to be trivially copyable.
810 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
811 << ValType << Ptr->getSourceRange();
815 QualType ResultType = ValType;
816 if (Form == Copy || Form == GNUXchg || Form == Init)
817 ResultType = Context.VoidTy;
818 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
819 ResultType = Context.BoolTy;
821 // The type of a parameter passed 'by value'. In the GNU atomics, such
822 // arguments are actually passed as pointers.
823 QualType ByValType = ValType; // 'CP'
825 ByValType = Ptr->getType();
827 // The first argument --- the pointer --- has a fixed type; we
828 // deduce the types of the rest of the arguments accordingly. Walk
829 // the remaining arguments, converting them to the deduced value type.
830 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
832 if (i < NumVals[Form] + 1) {
835 // The second argument is the non-atomic operand. For arithmetic, this
836 // is always passed by value, and for a compare_exchange it is always
837 // passed by address. For the rest, GNU uses by-address and C11 uses
839 assert(Form != Load);
840 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
842 else if (Form == Copy || Form == Xchg)
844 else if (Form == Arithmetic)
845 Ty = Context.getPointerDiffType();
847 Ty = Context.getPointerType(ValType.getUnqualifiedType());
850 // The third argument to compare_exchange / GNU exchange is a
851 // (pointer to a) desired value.
855 // The fourth argument to GNU compare_exchange is a 'weak' flag.
860 // The order(s) are always converted to int.
864 InitializedEntity Entity =
865 InitializedEntity::InitializeParameter(Context, Ty, false);
866 ExprResult Arg = TheCall->getArg(i);
867 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
870 TheCall->setArg(i, Arg.get());
873 // Permute the arguments into a 'consistent' order.
874 SmallVector<Expr*, 5> SubExprs;
875 SubExprs.push_back(Ptr);
878 // Note, AtomicExpr::getVal1() has a special case for this atomic.
879 SubExprs.push_back(TheCall->getArg(1)); // Val1
882 SubExprs.push_back(TheCall->getArg(1)); // Order
887 SubExprs.push_back(TheCall->getArg(2)); // Order
888 SubExprs.push_back(TheCall->getArg(1)); // Val1
891 // Note, AtomicExpr::getVal2() has a special case for this atomic.
892 SubExprs.push_back(TheCall->getArg(3)); // Order
893 SubExprs.push_back(TheCall->getArg(1)); // Val1
894 SubExprs.push_back(TheCall->getArg(2)); // Val2
897 SubExprs.push_back(TheCall->getArg(3)); // Order
898 SubExprs.push_back(TheCall->getArg(1)); // Val1
899 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
900 SubExprs.push_back(TheCall->getArg(2)); // Val2
903 SubExprs.push_back(TheCall->getArg(4)); // Order
904 SubExprs.push_back(TheCall->getArg(1)); // Val1
905 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
906 SubExprs.push_back(TheCall->getArg(2)); // Val2
907 SubExprs.push_back(TheCall->getArg(3)); // Weak
911 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
912 SubExprs, ResultType, Op,
913 TheCall->getRParenLoc()));
917 /// checkBuiltinArgument - Given a call to a builtin function, perform
918 /// normal type-checking on the given argument, updating the call in
919 /// place. This is useful when a builtin function requires custom
920 /// type-checking for some of its arguments but not necessarily all of
923 /// Returns true on error.
924 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
925 FunctionDecl *Fn = E->getDirectCallee();
926 assert(Fn && "builtin call without direct callee!");
928 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
929 InitializedEntity Entity =
930 InitializedEntity::InitializeParameter(S.Context, Param);
932 ExprResult Arg = E->getArg(0);
933 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
937 E->setArg(ArgIndex, Arg.take());
941 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
942 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
943 /// type of its first argument. The main ActOnCallExpr routines have already
944 /// promoted the types of arguments because all of these calls are prototyped as
947 /// This function goes through and does final semantic checking for these
950 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
951 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
952 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
953 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
955 // Ensure that we have at least one argument to do type inference from.
956 if (TheCall->getNumArgs() < 1) {
957 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
958 << 0 << 1 << TheCall->getNumArgs()
959 << TheCall->getCallee()->getSourceRange();
963 // Inspect the first argument of the atomic builtin. This should always be
964 // a pointer type, whose element is an integral scalar or pointer type.
965 // Because it is a pointer type, we don't have to worry about any implicit
967 // FIXME: We don't allow floating point scalars as input.
968 Expr *FirstArg = TheCall->getArg(0);
969 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
970 if (FirstArgResult.isInvalid())
972 FirstArg = FirstArgResult.take();
973 TheCall->setArg(0, FirstArg);
975 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
977 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
978 << FirstArg->getType() << FirstArg->getSourceRange();
982 QualType ValType = pointerType->getPointeeType();
983 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
984 !ValType->isBlockPointerType()) {
985 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
986 << FirstArg->getType() << FirstArg->getSourceRange();
990 switch (ValType.getObjCLifetime()) {
991 case Qualifiers::OCL_None:
992 case Qualifiers::OCL_ExplicitNone:
996 case Qualifiers::OCL_Weak:
997 case Qualifiers::OCL_Strong:
998 case Qualifiers::OCL_Autoreleasing:
999 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1000 << ValType << FirstArg->getSourceRange();
1004 // Strip any qualifiers off ValType.
1005 ValType = ValType.getUnqualifiedType();
1007 // The majority of builtins return a value, but a few have special return
1008 // types, so allow them to override appropriately below.
1009 QualType ResultType = ValType;
1011 // We need to figure out which concrete builtin this maps onto. For example,
1012 // __sync_fetch_and_add with a 2 byte object turns into
1013 // __sync_fetch_and_add_2.
1014 #define BUILTIN_ROW(x) \
1015 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1016 Builtin::BI##x##_8, Builtin::BI##x##_16 }
1018 static const unsigned BuiltinIndices[][5] = {
1019 BUILTIN_ROW(__sync_fetch_and_add),
1020 BUILTIN_ROW(__sync_fetch_and_sub),
1021 BUILTIN_ROW(__sync_fetch_and_or),
1022 BUILTIN_ROW(__sync_fetch_and_and),
1023 BUILTIN_ROW(__sync_fetch_and_xor),
1025 BUILTIN_ROW(__sync_add_and_fetch),
1026 BUILTIN_ROW(__sync_sub_and_fetch),
1027 BUILTIN_ROW(__sync_and_and_fetch),
1028 BUILTIN_ROW(__sync_or_and_fetch),
1029 BUILTIN_ROW(__sync_xor_and_fetch),
1031 BUILTIN_ROW(__sync_val_compare_and_swap),
1032 BUILTIN_ROW(__sync_bool_compare_and_swap),
1033 BUILTIN_ROW(__sync_lock_test_and_set),
1034 BUILTIN_ROW(__sync_lock_release),
1035 BUILTIN_ROW(__sync_swap)
1039 // Determine the index of the size.
1041 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1042 case 1: SizeIndex = 0; break;
1043 case 2: SizeIndex = 1; break;
1044 case 4: SizeIndex = 2; break;
1045 case 8: SizeIndex = 3; break;
1046 case 16: SizeIndex = 4; break;
1048 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1049 << FirstArg->getType() << FirstArg->getSourceRange();
1053 // Each of these builtins has one pointer argument, followed by some number of
1054 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1055 // that we ignore. Find out which row of BuiltinIndices to read from as well
1056 // as the number of fixed args.
1057 unsigned BuiltinID = FDecl->getBuiltinID();
1058 unsigned BuiltinIndex, NumFixed = 1;
1059 switch (BuiltinID) {
1060 default: llvm_unreachable("Unknown overloaded atomic builtin!");
1061 case Builtin::BI__sync_fetch_and_add:
1062 case Builtin::BI__sync_fetch_and_add_1:
1063 case Builtin::BI__sync_fetch_and_add_2:
1064 case Builtin::BI__sync_fetch_and_add_4:
1065 case Builtin::BI__sync_fetch_and_add_8:
1066 case Builtin::BI__sync_fetch_and_add_16:
1070 case Builtin::BI__sync_fetch_and_sub:
1071 case Builtin::BI__sync_fetch_and_sub_1:
1072 case Builtin::BI__sync_fetch_and_sub_2:
1073 case Builtin::BI__sync_fetch_and_sub_4:
1074 case Builtin::BI__sync_fetch_and_sub_8:
1075 case Builtin::BI__sync_fetch_and_sub_16:
1079 case Builtin::BI__sync_fetch_and_or:
1080 case Builtin::BI__sync_fetch_and_or_1:
1081 case Builtin::BI__sync_fetch_and_or_2:
1082 case Builtin::BI__sync_fetch_and_or_4:
1083 case Builtin::BI__sync_fetch_and_or_8:
1084 case Builtin::BI__sync_fetch_and_or_16:
1088 case Builtin::BI__sync_fetch_and_and:
1089 case Builtin::BI__sync_fetch_and_and_1:
1090 case Builtin::BI__sync_fetch_and_and_2:
1091 case Builtin::BI__sync_fetch_and_and_4:
1092 case Builtin::BI__sync_fetch_and_and_8:
1093 case Builtin::BI__sync_fetch_and_and_16:
1097 case Builtin::BI__sync_fetch_and_xor:
1098 case Builtin::BI__sync_fetch_and_xor_1:
1099 case Builtin::BI__sync_fetch_and_xor_2:
1100 case Builtin::BI__sync_fetch_and_xor_4:
1101 case Builtin::BI__sync_fetch_and_xor_8:
1102 case Builtin::BI__sync_fetch_and_xor_16:
1106 case Builtin::BI__sync_add_and_fetch:
1107 case Builtin::BI__sync_add_and_fetch_1:
1108 case Builtin::BI__sync_add_and_fetch_2:
1109 case Builtin::BI__sync_add_and_fetch_4:
1110 case Builtin::BI__sync_add_and_fetch_8:
1111 case Builtin::BI__sync_add_and_fetch_16:
1115 case Builtin::BI__sync_sub_and_fetch:
1116 case Builtin::BI__sync_sub_and_fetch_1:
1117 case Builtin::BI__sync_sub_and_fetch_2:
1118 case Builtin::BI__sync_sub_and_fetch_4:
1119 case Builtin::BI__sync_sub_and_fetch_8:
1120 case Builtin::BI__sync_sub_and_fetch_16:
1124 case Builtin::BI__sync_and_and_fetch:
1125 case Builtin::BI__sync_and_and_fetch_1:
1126 case Builtin::BI__sync_and_and_fetch_2:
1127 case Builtin::BI__sync_and_and_fetch_4:
1128 case Builtin::BI__sync_and_and_fetch_8:
1129 case Builtin::BI__sync_and_and_fetch_16:
1133 case Builtin::BI__sync_or_and_fetch:
1134 case Builtin::BI__sync_or_and_fetch_1:
1135 case Builtin::BI__sync_or_and_fetch_2:
1136 case Builtin::BI__sync_or_and_fetch_4:
1137 case Builtin::BI__sync_or_and_fetch_8:
1138 case Builtin::BI__sync_or_and_fetch_16:
1142 case Builtin::BI__sync_xor_and_fetch:
1143 case Builtin::BI__sync_xor_and_fetch_1:
1144 case Builtin::BI__sync_xor_and_fetch_2:
1145 case Builtin::BI__sync_xor_and_fetch_4:
1146 case Builtin::BI__sync_xor_and_fetch_8:
1147 case Builtin::BI__sync_xor_and_fetch_16:
1151 case Builtin::BI__sync_val_compare_and_swap:
1152 case Builtin::BI__sync_val_compare_and_swap_1:
1153 case Builtin::BI__sync_val_compare_and_swap_2:
1154 case Builtin::BI__sync_val_compare_and_swap_4:
1155 case Builtin::BI__sync_val_compare_and_swap_8:
1156 case Builtin::BI__sync_val_compare_and_swap_16:
1161 case Builtin::BI__sync_bool_compare_and_swap:
1162 case Builtin::BI__sync_bool_compare_and_swap_1:
1163 case Builtin::BI__sync_bool_compare_and_swap_2:
1164 case Builtin::BI__sync_bool_compare_and_swap_4:
1165 case Builtin::BI__sync_bool_compare_and_swap_8:
1166 case Builtin::BI__sync_bool_compare_and_swap_16:
1169 ResultType = Context.BoolTy;
1172 case Builtin::BI__sync_lock_test_and_set:
1173 case Builtin::BI__sync_lock_test_and_set_1:
1174 case Builtin::BI__sync_lock_test_and_set_2:
1175 case Builtin::BI__sync_lock_test_and_set_4:
1176 case Builtin::BI__sync_lock_test_and_set_8:
1177 case Builtin::BI__sync_lock_test_and_set_16:
1181 case Builtin::BI__sync_lock_release:
1182 case Builtin::BI__sync_lock_release_1:
1183 case Builtin::BI__sync_lock_release_2:
1184 case Builtin::BI__sync_lock_release_4:
1185 case Builtin::BI__sync_lock_release_8:
1186 case Builtin::BI__sync_lock_release_16:
1189 ResultType = Context.VoidTy;
1192 case Builtin::BI__sync_swap:
1193 case Builtin::BI__sync_swap_1:
1194 case Builtin::BI__sync_swap_2:
1195 case Builtin::BI__sync_swap_4:
1196 case Builtin::BI__sync_swap_8:
1197 case Builtin::BI__sync_swap_16:
1202 // Now that we know how many fixed arguments we expect, first check that we
1203 // have at least that many.
1204 if (TheCall->getNumArgs() < 1+NumFixed) {
1205 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1206 << 0 << 1+NumFixed << TheCall->getNumArgs()
1207 << TheCall->getCallee()->getSourceRange();
1211 // Get the decl for the concrete builtin from this, we can tell what the
1212 // concrete integer type we should convert to is.
1213 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1214 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1215 FunctionDecl *NewBuiltinDecl;
1216 if (NewBuiltinID == BuiltinID)
1217 NewBuiltinDecl = FDecl;
1219 // Perform builtin lookup to avoid redeclaring it.
1220 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1221 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1222 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1223 assert(Res.getFoundDecl());
1224 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1225 if (NewBuiltinDecl == 0)
1229 // The first argument --- the pointer --- has a fixed type; we
1230 // deduce the types of the rest of the arguments accordingly. Walk
1231 // the remaining arguments, converting them to the deduced value type.
1232 for (unsigned i = 0; i != NumFixed; ++i) {
1233 ExprResult Arg = TheCall->getArg(i+1);
1235 // GCC does an implicit conversion to the pointer or integer ValType. This
1236 // can fail in some cases (1i -> int**), check for this error case now.
1237 // Initialize the argument.
1238 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1239 ValType, /*consume*/ false);
1240 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1241 if (Arg.isInvalid())
1244 // Okay, we have something that *can* be converted to the right type. Check
1245 // to see if there is a potentially weird extension going on here. This can
1246 // happen when you do an atomic operation on something like an char* and
1247 // pass in 42. The 42 gets converted to char. This is even more strange
1248 // for things like 45.123 -> char, etc.
1249 // FIXME: Do this check.
1250 TheCall->setArg(i+1, Arg.take());
1253 ASTContext& Context = this->getASTContext();
1255 // Create a new DeclRefExpr to refer to the new decl.
1256 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1258 DRE->getQualifierLoc(),
1261 /*enclosing*/ false,
1263 Context.BuiltinFnTy,
1264 DRE->getValueKind());
1266 // Set the callee in the CallExpr.
1267 // FIXME: This loses syntactic information.
1268 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1269 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1270 CK_BuiltinFnToFnPtr);
1271 TheCall->setCallee(PromotedCall.take());
1273 // Change the result type of the call to match the original value type. This
1274 // is arbitrary, but the codegen for these builtins ins design to handle it
1276 TheCall->setType(ResultType);
1278 return TheCallResult;
1281 /// CheckObjCString - Checks that the argument to the builtin
1282 /// CFString constructor is correct
1283 /// Note: It might also make sense to do the UTF-16 conversion here (would
1284 /// simplify the backend).
1285 bool Sema::CheckObjCString(Expr *Arg) {
1286 Arg = Arg->IgnoreParenCasts();
1287 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1289 if (!Literal || !Literal->isAscii()) {
1290 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1291 << Arg->getSourceRange();
1295 if (Literal->containsNonAsciiOrNull()) {
1296 StringRef String = Literal->getString();
1297 unsigned NumBytes = String.size();
1298 SmallVector<UTF16, 128> ToBuf(NumBytes);
1299 const UTF8 *FromPtr = (const UTF8 *)String.data();
1300 UTF16 *ToPtr = &ToBuf[0];
1302 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1303 &ToPtr, ToPtr + NumBytes,
1305 // Check for conversion failure.
1306 if (Result != conversionOK)
1307 Diag(Arg->getLocStart(),
1308 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1313 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1314 /// Emit an error and return true on failure, return false on success.
1315 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1316 Expr *Fn = TheCall->getCallee();
1317 if (TheCall->getNumArgs() > 2) {
1318 Diag(TheCall->getArg(2)->getLocStart(),
1319 diag::err_typecheck_call_too_many_args)
1320 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1321 << Fn->getSourceRange()
1322 << SourceRange(TheCall->getArg(2)->getLocStart(),
1323 (*(TheCall->arg_end()-1))->getLocEnd());
1327 if (TheCall->getNumArgs() < 2) {
1328 return Diag(TheCall->getLocEnd(),
1329 diag::err_typecheck_call_too_few_args_at_least)
1330 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1333 // Type-check the first argument normally.
1334 if (checkBuiltinArgument(*this, TheCall, 0))
1337 // Determine whether the current function is variadic or not.
1338 BlockScopeInfo *CurBlock = getCurBlock();
1341 isVariadic = CurBlock->TheDecl->isVariadic();
1342 else if (FunctionDecl *FD = getCurFunctionDecl())
1343 isVariadic = FD->isVariadic();
1345 isVariadic = getCurMethodDecl()->isVariadic();
1348 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1352 // Verify that the second argument to the builtin is the last argument of the
1353 // current function or method.
1354 bool SecondArgIsLastNamedArgument = false;
1355 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1357 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1358 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1359 // FIXME: This isn't correct for methods (results in bogus warning).
1360 // Get the last formal in the current function.
1361 const ParmVarDecl *LastArg;
1363 LastArg = *(CurBlock->TheDecl->param_end()-1);
1364 else if (FunctionDecl *FD = getCurFunctionDecl())
1365 LastArg = *(FD->param_end()-1);
1367 LastArg = *(getCurMethodDecl()->param_end()-1);
1368 SecondArgIsLastNamedArgument = PV == LastArg;
1372 if (!SecondArgIsLastNamedArgument)
1373 Diag(TheCall->getArg(1)->getLocStart(),
1374 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1378 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1379 /// friends. This is declared to take (...), so we have to check everything.
1380 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1381 if (TheCall->getNumArgs() < 2)
1382 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1383 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1384 if (TheCall->getNumArgs() > 2)
1385 return Diag(TheCall->getArg(2)->getLocStart(),
1386 diag::err_typecheck_call_too_many_args)
1387 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1388 << SourceRange(TheCall->getArg(2)->getLocStart(),
1389 (*(TheCall->arg_end()-1))->getLocEnd());
1391 ExprResult OrigArg0 = TheCall->getArg(0);
1392 ExprResult OrigArg1 = TheCall->getArg(1);
1394 // Do standard promotions between the two arguments, returning their common
1396 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1397 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1400 // Make sure any conversions are pushed back into the call; this is
1401 // type safe since unordered compare builtins are declared as "_Bool
1403 TheCall->setArg(0, OrigArg0.get());
1404 TheCall->setArg(1, OrigArg1.get());
1406 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1409 // If the common type isn't a real floating type, then the arguments were
1410 // invalid for this operation.
1411 if (Res.isNull() || !Res->isRealFloatingType())
1412 return Diag(OrigArg0.get()->getLocStart(),
1413 diag::err_typecheck_call_invalid_ordered_compare)
1414 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1415 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1420 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1421 /// __builtin_isnan and friends. This is declared to take (...), so we have
1422 /// to check everything. We expect the last argument to be a floating point
1424 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1425 if (TheCall->getNumArgs() < NumArgs)
1426 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1427 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1428 if (TheCall->getNumArgs() > NumArgs)
1429 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1430 diag::err_typecheck_call_too_many_args)
1431 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1432 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1433 (*(TheCall->arg_end()-1))->getLocEnd());
1435 Expr *OrigArg = TheCall->getArg(NumArgs-1);
1437 if (OrigArg->isTypeDependent())
1440 // This operation requires a non-_Complex floating-point number.
1441 if (!OrigArg->getType()->isRealFloatingType())
1442 return Diag(OrigArg->getLocStart(),
1443 diag::err_typecheck_call_invalid_unary_fp)
1444 << OrigArg->getType() << OrigArg->getSourceRange();
1446 // If this is an implicit conversion from float -> double, remove it.
1447 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1448 Expr *CastArg = Cast->getSubExpr();
1449 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1450 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1451 "promotion from float to double is the only expected cast here");
1452 Cast->setSubExpr(0);
1453 TheCall->setArg(NumArgs-1, CastArg);
1460 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1461 // This is declared to take (...), so we have to check everything.
1462 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1463 if (TheCall->getNumArgs() < 2)
1464 return ExprError(Diag(TheCall->getLocEnd(),
1465 diag::err_typecheck_call_too_few_args_at_least)
1466 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1467 << TheCall->getSourceRange());
1469 // Determine which of the following types of shufflevector we're checking:
1470 // 1) unary, vector mask: (lhs, mask)
1471 // 2) binary, vector mask: (lhs, rhs, mask)
1472 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1473 QualType resType = TheCall->getArg(0)->getType();
1474 unsigned numElements = 0;
1476 if (!TheCall->getArg(0)->isTypeDependent() &&
1477 !TheCall->getArg(1)->isTypeDependent()) {
1478 QualType LHSType = TheCall->getArg(0)->getType();
1479 QualType RHSType = TheCall->getArg(1)->getType();
1481 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1482 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1483 << SourceRange(TheCall->getArg(0)->getLocStart(),
1484 TheCall->getArg(1)->getLocEnd());
1488 numElements = LHSType->getAs<VectorType>()->getNumElements();
1489 unsigned numResElements = TheCall->getNumArgs() - 2;
1491 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1492 // with mask. If so, verify that RHS is an integer vector type with the
1493 // same number of elts as lhs.
1494 if (TheCall->getNumArgs() == 2) {
1495 if (!RHSType->hasIntegerRepresentation() ||
1496 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1497 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1498 << SourceRange(TheCall->getArg(1)->getLocStart(),
1499 TheCall->getArg(1)->getLocEnd());
1500 numResElements = numElements;
1502 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1503 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1504 << SourceRange(TheCall->getArg(0)->getLocStart(),
1505 TheCall->getArg(1)->getLocEnd());
1507 } else if (numElements != numResElements) {
1508 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1509 resType = Context.getVectorType(eltType, numResElements,
1510 VectorType::GenericVector);
1514 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1515 if (TheCall->getArg(i)->isTypeDependent() ||
1516 TheCall->getArg(i)->isValueDependent())
1519 llvm::APSInt Result(32);
1520 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1521 return ExprError(Diag(TheCall->getLocStart(),
1522 diag::err_shufflevector_nonconstant_argument)
1523 << TheCall->getArg(i)->getSourceRange());
1525 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1526 return ExprError(Diag(TheCall->getLocStart(),
1527 diag::err_shufflevector_argument_too_large)
1528 << TheCall->getArg(i)->getSourceRange());
1531 SmallVector<Expr*, 32> exprs;
1533 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1534 exprs.push_back(TheCall->getArg(i));
1535 TheCall->setArg(i, 0);
1538 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1539 TheCall->getCallee()->getLocStart(),
1540 TheCall->getRParenLoc()));
1543 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1544 // This is declared to take (const void*, ...) and can take two
1545 // optional constant int args.
1546 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1547 unsigned NumArgs = TheCall->getNumArgs();
1550 return Diag(TheCall->getLocEnd(),
1551 diag::err_typecheck_call_too_many_args_at_most)
1552 << 0 /*function call*/ << 3 << NumArgs
1553 << TheCall->getSourceRange();
1555 // Argument 0 is checked for us and the remaining arguments must be
1556 // constant integers.
1557 for (unsigned i = 1; i != NumArgs; ++i) {
1558 Expr *Arg = TheCall->getArg(i);
1560 // We can't check the value of a dependent argument.
1561 if (Arg->isTypeDependent() || Arg->isValueDependent())
1564 llvm::APSInt Result;
1565 if (SemaBuiltinConstantArg(TheCall, i, Result))
1568 // FIXME: gcc issues a warning and rewrites these to 0. These
1569 // seems especially odd for the third argument since the default
1572 if (Result.getLimitedValue() > 1)
1573 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1574 << "0" << "1" << Arg->getSourceRange();
1576 if (Result.getLimitedValue() > 3)
1577 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1578 << "0" << "3" << Arg->getSourceRange();
1585 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1586 /// TheCall is a constant expression.
1587 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1588 llvm::APSInt &Result) {
1589 Expr *Arg = TheCall->getArg(ArgNum);
1590 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1591 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1593 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1595 if (!Arg->isIntegerConstantExpr(Result, Context))
1596 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1597 << FDecl->getDeclName() << Arg->getSourceRange();
1602 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1603 /// int type). This simply type checks that type is one of the defined
1604 /// constants (0-3).
1605 // For compatibility check 0-3, llvm only handles 0 and 2.
1606 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1607 llvm::APSInt Result;
1609 // We can't check the value of a dependent argument.
1610 if (TheCall->getArg(1)->isTypeDependent() ||
1611 TheCall->getArg(1)->isValueDependent())
1614 // Check constant-ness first.
1615 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1618 Expr *Arg = TheCall->getArg(1);
1619 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1620 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1621 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1627 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1628 /// This checks that val is a constant 1.
1629 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1630 Expr *Arg = TheCall->getArg(1);
1631 llvm::APSInt Result;
1633 // TODO: This is less than ideal. Overload this to take a value.
1634 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1638 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1639 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1644 // Determine if an expression is a string literal or constant string.
1645 // If this function returns false on the arguments to a function expecting a
1646 // format string, we will usually need to emit a warning.
1647 // True string literals are then checked by CheckFormatString.
1648 Sema::StringLiteralCheckType
1649 Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1650 unsigned NumArgs, bool HasVAListArg,
1651 unsigned format_idx, unsigned firstDataArg,
1652 FormatStringType Type, VariadicCallType CallType,
1653 bool inFunctionCall) {
1655 if (E->isTypeDependent() || E->isValueDependent())
1656 return SLCT_NotALiteral;
1658 E = E->IgnoreParenCasts();
1660 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1661 // Technically -Wformat-nonliteral does not warn about this case.
1662 // The behavior of printf and friends in this case is implementation
1663 // dependent. Ideally if the format string cannot be null then
1664 // it should have a 'nonnull' attribute in the function prototype.
1665 return SLCT_CheckedLiteral;
1667 switch (E->getStmtClass()) {
1668 case Stmt::BinaryConditionalOperatorClass:
1669 case Stmt::ConditionalOperatorClass: {
1670 // The expression is a literal if both sub-expressions were, and it was
1671 // completely checked only if both sub-expressions were checked.
1672 const AbstractConditionalOperator *C =
1673 cast<AbstractConditionalOperator>(E);
1674 StringLiteralCheckType Left =
1675 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1676 HasVAListArg, format_idx, firstDataArg,
1677 Type, CallType, inFunctionCall);
1678 if (Left == SLCT_NotALiteral)
1679 return SLCT_NotALiteral;
1680 StringLiteralCheckType Right =
1681 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1682 HasVAListArg, format_idx, firstDataArg,
1683 Type, CallType, inFunctionCall);
1684 return Left < Right ? Left : Right;
1687 case Stmt::ImplicitCastExprClass: {
1688 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1692 case Stmt::OpaqueValueExprClass:
1693 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1697 return SLCT_NotALiteral;
1699 case Stmt::PredefinedExprClass:
1700 // While __func__, etc., are technically not string literals, they
1701 // cannot contain format specifiers and thus are not a security
1703 return SLCT_UncheckedLiteral;
1705 case Stmt::DeclRefExprClass: {
1706 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1708 // As an exception, do not flag errors for variables binding to
1709 // const string literals.
1710 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1711 bool isConstant = false;
1712 QualType T = DR->getType();
1714 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1715 isConstant = AT->getElementType().isConstant(Context);
1716 } else if (const PointerType *PT = T->getAs<PointerType>()) {
1717 isConstant = T.isConstant(Context) &&
1718 PT->getPointeeType().isConstant(Context);
1719 } else if (T->isObjCObjectPointerType()) {
1720 // In ObjC, there is usually no "const ObjectPointer" type,
1721 // so don't check if the pointee type is constant.
1722 isConstant = T.isConstant(Context);
1726 if (const Expr *Init = VD->getAnyInitializer()) {
1727 // Look through initializers like const char c[] = { "foo" }
1728 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1729 if (InitList->isStringLiteralInit())
1730 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1732 return checkFormatStringExpr(Init, Args, NumArgs,
1733 HasVAListArg, format_idx,
1734 firstDataArg, Type, CallType,
1735 /*inFunctionCall*/false);
1739 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1740 // special check to see if the format string is a function parameter
1741 // of the function calling the printf function. If the function
1742 // has an attribute indicating it is a printf-like function, then we
1743 // should suppress warnings concerning non-literals being used in a call
1744 // to a vprintf function. For example:
1747 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1749 // va_start(ap, fmt);
1750 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1754 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1755 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1756 int PVIndex = PV->getFunctionScopeIndex() + 1;
1757 for (specific_attr_iterator<FormatAttr>
1758 i = ND->specific_attr_begin<FormatAttr>(),
1759 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1760 FormatAttr *PVFormat = *i;
1761 // adjust for implicit parameter
1762 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1763 if (MD->isInstance())
1765 // We also check if the formats are compatible.
1766 // We can't pass a 'scanf' string to a 'printf' function.
1767 if (PVIndex == PVFormat->getFormatIdx() &&
1768 Type == GetFormatStringType(PVFormat))
1769 return SLCT_UncheckedLiteral;
1776 return SLCT_NotALiteral;
1779 case Stmt::CallExprClass:
1780 case Stmt::CXXMemberCallExprClass: {
1781 const CallExpr *CE = cast<CallExpr>(E);
1782 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1783 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1784 unsigned ArgIndex = FA->getFormatIdx();
1785 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1786 if (MD->isInstance())
1788 const Expr *Arg = CE->getArg(ArgIndex - 1);
1790 return checkFormatStringExpr(Arg, Args, NumArgs,
1791 HasVAListArg, format_idx, firstDataArg,
1792 Type, CallType, inFunctionCall);
1793 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1794 unsigned BuiltinID = FD->getBuiltinID();
1795 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1796 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1797 const Expr *Arg = CE->getArg(0);
1798 return checkFormatStringExpr(Arg, Args, NumArgs,
1799 HasVAListArg, format_idx,
1800 firstDataArg, Type, CallType,
1806 return SLCT_NotALiteral;
1808 case Stmt::ObjCStringLiteralClass:
1809 case Stmt::StringLiteralClass: {
1810 const StringLiteral *StrE = NULL;
1812 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1813 StrE = ObjCFExpr->getString();
1815 StrE = cast<StringLiteral>(E);
1818 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
1819 firstDataArg, Type, inFunctionCall, CallType);
1820 return SLCT_CheckedLiteral;
1823 return SLCT_NotALiteral;
1827 return SLCT_NotALiteral;
1832 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1833 const Expr * const *ExprArgs,
1834 SourceLocation CallSiteLoc) {
1835 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1836 e = NonNull->args_end();
1838 const Expr *ArgExpr = ExprArgs[*i];
1839 if (ArgExpr->isNullPointerConstant(Context,
1840 Expr::NPC_ValueDependentIsNotNull))
1841 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1845 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1846 return llvm::StringSwitch<FormatStringType>(Format->getType())
1847 .Case("scanf", FST_Scanf)
1848 .Cases("printf", "printf0", FST_Printf)
1849 .Cases("NSString", "CFString", FST_NSString)
1850 .Case("strftime", FST_Strftime)
1851 .Case("strfmon", FST_Strfmon)
1852 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1853 .Default(FST_Unknown);
1856 /// CheckFormatArguments - Check calls to printf and scanf (and similar
1857 /// functions) for correct use of format strings.
1858 /// Returns true if a format string has been fully checked.
1859 bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1860 unsigned NumArgs, bool IsCXXMember,
1861 VariadicCallType CallType,
1862 SourceLocation Loc, SourceRange Range) {
1863 FormatStringInfo FSI;
1864 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1865 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1866 FSI.FirstDataArg, GetFormatStringType(Format),
1867 CallType, Loc, Range);
1871 bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1872 bool HasVAListArg, unsigned format_idx,
1873 unsigned firstDataArg, FormatStringType Type,
1874 VariadicCallType CallType,
1875 SourceLocation Loc, SourceRange Range) {
1876 // CHECK: printf/scanf-like function is called with no format string.
1877 if (format_idx >= NumArgs) {
1878 Diag(Loc, diag::warn_missing_format_string) << Range;
1882 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
1884 // CHECK: format string is not a string literal.
1886 // Dynamically generated format strings are difficult to
1887 // automatically vet at compile time. Requiring that format strings
1888 // are string literals: (1) permits the checking of format strings by
1889 // the compiler and thereby (2) can practically remove the source of
1890 // many format string exploits.
1892 // Format string can be either ObjC string (e.g. @"%d") or
1893 // C string (e.g. "%d")
1894 // ObjC string uses the same format specifiers as C string, so we can use
1895 // the same format string checking logic for both ObjC and C strings.
1896 StringLiteralCheckType CT =
1897 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
1898 format_idx, firstDataArg, Type, CallType);
1899 if (CT != SLCT_NotALiteral)
1900 // Literal format string found, check done!
1901 return CT == SLCT_CheckedLiteral;
1903 // Strftime is particular as it always uses a single 'time' argument,
1904 // so it is safe to pass a non-literal string.
1905 if (Type == FST_Strftime)
1908 // Do not emit diag when the string param is a macro expansion and the
1909 // format is either NSString or CFString. This is a hack to prevent
1910 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1911 // which are usually used in place of NS and CF string literals.
1912 if (Type == FST_NSString &&
1913 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
1916 // If there are no arguments specified, warn with -Wformat-security, otherwise
1917 // warn only with -Wformat-nonliteral.
1918 if (NumArgs == format_idx+1)
1919 Diag(Args[format_idx]->getLocStart(),
1920 diag::warn_format_nonliteral_noargs)
1921 << OrigFormatExpr->getSourceRange();
1923 Diag(Args[format_idx]->getLocStart(),
1924 diag::warn_format_nonliteral)
1925 << OrigFormatExpr->getSourceRange();
1930 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1933 const StringLiteral *FExpr;
1934 const Expr *OrigFormatExpr;
1935 const unsigned FirstDataArg;
1936 const unsigned NumDataArgs;
1937 const char *Beg; // Start of format string.
1938 const bool HasVAListArg;
1939 const Expr * const *Args;
1940 const unsigned NumArgs;
1942 llvm::BitVector CoveredArgs;
1943 bool usesPositionalArgs;
1945 bool inFunctionCall;
1946 Sema::VariadicCallType CallType;
1948 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1949 const Expr *origFormatExpr, unsigned firstDataArg,
1950 unsigned numDataArgs, const char *beg, bool hasVAListArg,
1951 Expr **args, unsigned numArgs,
1952 unsigned formatIdx, bool inFunctionCall,
1953 Sema::VariadicCallType callType)
1954 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1955 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1956 Beg(beg), HasVAListArg(hasVAListArg),
1957 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
1958 usesPositionalArgs(false), atFirstArg(true),
1959 inFunctionCall(inFunctionCall), CallType(callType) {
1960 CoveredArgs.resize(numDataArgs);
1961 CoveredArgs.reset();
1964 void DoneProcessing();
1966 void HandleIncompleteSpecifier(const char *startSpecifier,
1967 unsigned specifierLen);
1969 void HandleInvalidLengthModifier(
1970 const analyze_format_string::FormatSpecifier &FS,
1971 const analyze_format_string::ConversionSpecifier &CS,
1972 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
1974 void HandleNonStandardLengthModifier(
1975 const analyze_format_string::FormatSpecifier &FS,
1976 const char *startSpecifier, unsigned specifierLen);
1978 void HandleNonStandardConversionSpecifier(
1979 const analyze_format_string::ConversionSpecifier &CS,
1980 const char *startSpecifier, unsigned specifierLen);
1982 virtual void HandlePosition(const char *startPos, unsigned posLen);
1984 virtual void HandleInvalidPosition(const char *startSpecifier,
1985 unsigned specifierLen,
1986 analyze_format_string::PositionContext p);
1988 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1990 void HandleNullChar(const char *nullCharacter);
1992 template <typename Range>
1993 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1994 const Expr *ArgumentExpr,
1995 PartialDiagnostic PDiag,
1996 SourceLocation StringLoc,
1997 bool IsStringLocation, Range StringRange,
1998 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
2001 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2002 const char *startSpec,
2003 unsigned specifierLen,
2004 const char *csStart, unsigned csLen);
2006 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2007 const char *startSpec,
2008 unsigned specifierLen);
2010 SourceRange getFormatStringRange();
2011 CharSourceRange getSpecifierRange(const char *startSpecifier,
2012 unsigned specifierLen);
2013 SourceLocation getLocationOfByte(const char *x);
2015 const Expr *getDataArg(unsigned i) const;
2017 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2018 const analyze_format_string::ConversionSpecifier &CS,
2019 const char *startSpecifier, unsigned specifierLen,
2022 template <typename Range>
2023 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2024 bool IsStringLocation, Range StringRange,
2025 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
2027 void CheckPositionalAndNonpositionalArgs(
2028 const analyze_format_string::FormatSpecifier *FS);
2032 SourceRange CheckFormatHandler::getFormatStringRange() {
2033 return OrigFormatExpr->getSourceRange();
2036 CharSourceRange CheckFormatHandler::
2037 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2038 SourceLocation Start = getLocationOfByte(startSpecifier);
2039 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2041 // Advance the end SourceLocation by one due to half-open ranges.
2042 End = End.getLocWithOffset(1);
2044 return CharSourceRange::getCharRange(Start, End);
2047 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2048 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2051 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2052 unsigned specifierLen){
2053 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2054 getLocationOfByte(startSpecifier),
2055 /*IsStringLocation*/true,
2056 getSpecifierRange(startSpecifier, specifierLen));
2059 void CheckFormatHandler::HandleInvalidLengthModifier(
2060 const analyze_format_string::FormatSpecifier &FS,
2061 const analyze_format_string::ConversionSpecifier &CS,
2062 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2063 using namespace analyze_format_string;
2065 const LengthModifier &LM = FS.getLengthModifier();
2066 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2068 // See if we know how to fix this length modifier.
2069 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2071 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2072 getLocationOfByte(LM.getStart()),
2073 /*IsStringLocation*/true,
2074 getSpecifierRange(startSpecifier, specifierLen));
2076 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2077 << FixedLM->toString()
2078 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2082 if (DiagID == diag::warn_format_nonsensical_length)
2083 Hint = FixItHint::CreateRemoval(LMRange);
2085 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2086 getLocationOfByte(LM.getStart()),
2087 /*IsStringLocation*/true,
2088 getSpecifierRange(startSpecifier, specifierLen),
2093 void CheckFormatHandler::HandleNonStandardLengthModifier(
2094 const analyze_format_string::FormatSpecifier &FS,
2095 const char *startSpecifier, unsigned specifierLen) {
2096 using namespace analyze_format_string;
2098 const LengthModifier &LM = FS.getLengthModifier();
2099 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2101 // See if we know how to fix this length modifier.
2102 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2104 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2105 << LM.toString() << 0,
2106 getLocationOfByte(LM.getStart()),
2107 /*IsStringLocation*/true,
2108 getSpecifierRange(startSpecifier, specifierLen));
2110 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2111 << FixedLM->toString()
2112 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2115 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2116 << LM.toString() << 0,
2117 getLocationOfByte(LM.getStart()),
2118 /*IsStringLocation*/true,
2119 getSpecifierRange(startSpecifier, specifierLen));
2123 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2124 const analyze_format_string::ConversionSpecifier &CS,
2125 const char *startSpecifier, unsigned specifierLen) {
2126 using namespace analyze_format_string;
2128 // See if we know how to fix this conversion specifier.
2129 llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2131 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2132 << CS.toString() << /*conversion specifier*/1,
2133 getLocationOfByte(CS.getStart()),
2134 /*IsStringLocation*/true,
2135 getSpecifierRange(startSpecifier, specifierLen));
2137 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2138 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2139 << FixedCS->toString()
2140 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2142 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2143 << CS.toString() << /*conversion specifier*/1,
2144 getLocationOfByte(CS.getStart()),
2145 /*IsStringLocation*/true,
2146 getSpecifierRange(startSpecifier, specifierLen));
2150 void CheckFormatHandler::HandlePosition(const char *startPos,
2152 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2153 getLocationOfByte(startPos),
2154 /*IsStringLocation*/true,
2155 getSpecifierRange(startPos, posLen));
2159 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2160 analyze_format_string::PositionContext p) {
2161 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2163 getLocationOfByte(startPos), /*IsStringLocation*/true,
2164 getSpecifierRange(startPos, posLen));
2167 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2169 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2170 getLocationOfByte(startPos),
2171 /*IsStringLocation*/true,
2172 getSpecifierRange(startPos, posLen));
2175 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2176 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2177 // The presence of a null character is likely an error.
2178 EmitFormatDiagnostic(
2179 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2180 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2181 getFormatStringRange());
2185 // Note that this may return NULL if there was an error parsing or building
2186 // one of the argument expressions.
2187 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2188 return Args[FirstDataArg + i];
2191 void CheckFormatHandler::DoneProcessing() {
2192 // Does the number of data arguments exceed the number of
2193 // format conversions in the format string?
2194 if (!HasVAListArg) {
2195 // Find any arguments that weren't covered.
2197 signed notCoveredArg = CoveredArgs.find_first();
2198 if (notCoveredArg >= 0) {
2199 assert((unsigned)notCoveredArg < NumDataArgs);
2200 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2201 SourceLocation Loc = E->getLocStart();
2202 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2203 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2204 Loc, /*IsStringLocation*/false,
2205 getFormatStringRange());
2213 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2215 const char *startSpec,
2216 unsigned specifierLen,
2217 const char *csStart,
2220 bool keepGoing = true;
2221 if (argIndex < NumDataArgs) {
2222 // Consider the argument coverered, even though the specifier doesn't
2224 CoveredArgs.set(argIndex);
2227 // If argIndex exceeds the number of data arguments we
2228 // don't issue a warning because that is just a cascade of warnings (and
2229 // they may have intended '%%' anyway). We don't want to continue processing
2230 // the format string after this point, however, as we will like just get
2231 // gibberish when trying to match arguments.
2235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2236 << StringRef(csStart, csLen),
2237 Loc, /*IsStringLocation*/true,
2238 getSpecifierRange(startSpec, specifierLen));
2244 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2245 const char *startSpec,
2246 unsigned specifierLen) {
2247 EmitFormatDiagnostic(
2248 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2249 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2253 CheckFormatHandler::CheckNumArgs(
2254 const analyze_format_string::FormatSpecifier &FS,
2255 const analyze_format_string::ConversionSpecifier &CS,
2256 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2258 if (argIndex >= NumDataArgs) {
2259 PartialDiagnostic PDiag = FS.usesPositionalArg()
2260 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2261 << (argIndex+1) << NumDataArgs)
2262 : S.PDiag(diag::warn_printf_insufficient_data_args);
2263 EmitFormatDiagnostic(
2264 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2265 getSpecifierRange(startSpecifier, specifierLen));
2271 template<typename Range>
2272 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2274 bool IsStringLocation,
2276 ArrayRef<FixItHint> FixIt) {
2277 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2278 Loc, IsStringLocation, StringRange, FixIt);
2281 /// \brief If the format string is not within the funcion call, emit a note
2282 /// so that the function call and string are in diagnostic messages.
2284 /// \param InFunctionCall if true, the format string is within the function
2285 /// call and only one diagnostic message will be produced. Otherwise, an
2286 /// extra note will be emitted pointing to location of the format string.
2288 /// \param ArgumentExpr the expression that is passed as the format string
2289 /// argument in the function call. Used for getting locations when two
2290 /// diagnostics are emitted.
2292 /// \param PDiag the callee should already have provided any strings for the
2293 /// diagnostic message. This function only adds locations and fixits
2296 /// \param Loc primary location for diagnostic. If two diagnostics are
2297 /// required, one will be at Loc and a new SourceLocation will be created for
2300 /// \param IsStringLocation if true, Loc points to the format string should be
2301 /// used for the note. Otherwise, Loc points to the argument list and will
2302 /// be used with PDiag.
2304 /// \param StringRange some or all of the string to highlight. This is
2305 /// templated so it can accept either a CharSourceRange or a SourceRange.
2307 /// \param FixIt optional fix it hint for the format string.
2308 template<typename Range>
2309 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2310 const Expr *ArgumentExpr,
2311 PartialDiagnostic PDiag,
2313 bool IsStringLocation,
2315 ArrayRef<FixItHint> FixIt) {
2316 if (InFunctionCall) {
2317 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2319 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2324 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2325 << ArgumentExpr->getSourceRange();
2327 const Sema::SemaDiagnosticBuilder &Note =
2328 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2329 diag::note_format_string_defined);
2331 Note << StringRange;
2332 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2339 //===--- CHECK: Printf format string checking ------------------------------===//
2342 class CheckPrintfHandler : public CheckFormatHandler {
2345 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2346 const Expr *origFormatExpr, unsigned firstDataArg,
2347 unsigned numDataArgs, bool isObjC,
2348 const char *beg, bool hasVAListArg,
2349 Expr **Args, unsigned NumArgs,
2350 unsigned formatIdx, bool inFunctionCall,
2351 Sema::VariadicCallType CallType)
2352 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2353 numDataArgs, beg, hasVAListArg, Args, NumArgs,
2354 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2358 bool HandleInvalidPrintfConversionSpecifier(
2359 const analyze_printf::PrintfSpecifier &FS,
2360 const char *startSpecifier,
2361 unsigned specifierLen);
2363 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2364 const char *startSpecifier,
2365 unsigned specifierLen);
2366 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2367 const char *StartSpecifier,
2368 unsigned SpecifierLen,
2371 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2372 const char *startSpecifier, unsigned specifierLen);
2373 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2374 const analyze_printf::OptionalAmount &Amt,
2376 const char *startSpecifier, unsigned specifierLen);
2377 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2378 const analyze_printf::OptionalFlag &flag,
2379 const char *startSpecifier, unsigned specifierLen);
2380 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2381 const analyze_printf::OptionalFlag &ignoredFlag,
2382 const analyze_printf::OptionalFlag &flag,
2383 const char *startSpecifier, unsigned specifierLen);
2384 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2385 const Expr *E, const CharSourceRange &CSR);
2390 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2391 const analyze_printf::PrintfSpecifier &FS,
2392 const char *startSpecifier,
2393 unsigned specifierLen) {
2394 const analyze_printf::PrintfConversionSpecifier &CS =
2395 FS.getConversionSpecifier();
2397 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2398 getLocationOfByte(CS.getStart()),
2399 startSpecifier, specifierLen,
2400 CS.getStart(), CS.getLength());
2403 bool CheckPrintfHandler::HandleAmount(
2404 const analyze_format_string::OptionalAmount &Amt,
2405 unsigned k, const char *startSpecifier,
2406 unsigned specifierLen) {
2408 if (Amt.hasDataArgument()) {
2409 if (!HasVAListArg) {
2410 unsigned argIndex = Amt.getArgIndex();
2411 if (argIndex >= NumDataArgs) {
2412 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2414 getLocationOfByte(Amt.getStart()),
2415 /*IsStringLocation*/true,
2416 getSpecifierRange(startSpecifier, specifierLen));
2417 // Don't do any more checking. We will just emit
2422 // Type check the data argument. It should be an 'int'.
2423 // Although not in conformance with C99, we also allow the argument to be
2424 // an 'unsigned int' as that is a reasonably safe case. GCC also
2425 // doesn't emit a warning for that case.
2426 CoveredArgs.set(argIndex);
2427 const Expr *Arg = getDataArg(argIndex);
2431 QualType T = Arg->getType();
2433 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2434 assert(AT.isValid());
2436 if (!AT.matchesType(S.Context, T)) {
2437 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2438 << k << AT.getRepresentativeTypeName(S.Context)
2439 << T << Arg->getSourceRange(),
2440 getLocationOfByte(Amt.getStart()),
2441 /*IsStringLocation*/true,
2442 getSpecifierRange(startSpecifier, specifierLen));
2443 // Don't do any more checking. We will just emit
2452 void CheckPrintfHandler::HandleInvalidAmount(
2453 const analyze_printf::PrintfSpecifier &FS,
2454 const analyze_printf::OptionalAmount &Amt,
2456 const char *startSpecifier,
2457 unsigned specifierLen) {
2458 const analyze_printf::PrintfConversionSpecifier &CS =
2459 FS.getConversionSpecifier();
2462 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2463 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2464 Amt.getConstantLength()))
2467 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2468 << type << CS.toString(),
2469 getLocationOfByte(Amt.getStart()),
2470 /*IsStringLocation*/true,
2471 getSpecifierRange(startSpecifier, specifierLen),
2475 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2476 const analyze_printf::OptionalFlag &flag,
2477 const char *startSpecifier,
2478 unsigned specifierLen) {
2479 // Warn about pointless flag with a fixit removal.
2480 const analyze_printf::PrintfConversionSpecifier &CS =
2481 FS.getConversionSpecifier();
2482 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2483 << flag.toString() << CS.toString(),
2484 getLocationOfByte(flag.getPosition()),
2485 /*IsStringLocation*/true,
2486 getSpecifierRange(startSpecifier, specifierLen),
2487 FixItHint::CreateRemoval(
2488 getSpecifierRange(flag.getPosition(), 1)));
2491 void CheckPrintfHandler::HandleIgnoredFlag(
2492 const analyze_printf::PrintfSpecifier &FS,
2493 const analyze_printf::OptionalFlag &ignoredFlag,
2494 const analyze_printf::OptionalFlag &flag,
2495 const char *startSpecifier,
2496 unsigned specifierLen) {
2497 // Warn about ignored flag with a fixit removal.
2498 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2499 << ignoredFlag.toString() << flag.toString(),
2500 getLocationOfByte(ignoredFlag.getPosition()),
2501 /*IsStringLocation*/true,
2502 getSpecifierRange(startSpecifier, specifierLen),
2503 FixItHint::CreateRemoval(
2504 getSpecifierRange(ignoredFlag.getPosition(), 1)));
2507 // Determines if the specified is a C++ class or struct containing
2508 // a member with the specified name and kind (e.g. a CXXMethodDecl named
2510 template<typename MemberKind>
2511 static llvm::SmallPtrSet<MemberKind*, 1>
2512 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2513 const RecordType *RT = Ty->getAs<RecordType>();
2514 llvm::SmallPtrSet<MemberKind*, 1> Results;
2518 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2522 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2523 Sema::LookupMemberName);
2525 // We just need to include all members of the right kind turned up by the
2526 // filter, at this point.
2527 if (S.LookupQualifiedName(R, RT->getDecl()))
2528 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2529 NamedDecl *decl = (*I)->getUnderlyingDecl();
2530 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2536 // Check if a (w)string was passed when a (w)char* was needed, and offer a
2537 // better diagnostic if so. AT is assumed to be valid.
2538 // Returns true when a c_str() conversion method is found.
2539 bool CheckPrintfHandler::checkForCStrMembers(
2540 const analyze_printf::ArgType &AT, const Expr *E,
2541 const CharSourceRange &CSR) {
2542 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2545 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2547 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2549 const CXXMethodDecl *Method = *MI;
2550 if (Method->getNumParams() == 0 &&
2551 AT.matchesType(S.Context, Method->getResultType())) {
2552 // FIXME: Suggest parens if the expression needs them.
2553 SourceLocation EndLoc =
2554 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2555 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2557 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2566 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2568 const char *startSpecifier,
2569 unsigned specifierLen) {
2571 using namespace analyze_format_string;
2572 using namespace analyze_printf;
2573 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2575 if (FS.consumesDataArgument()) {
2578 usesPositionalArgs = FS.usesPositionalArg();
2580 else if (usesPositionalArgs != FS.usesPositionalArg()) {
2581 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2582 startSpecifier, specifierLen);
2587 // First check if the field width, precision, and conversion specifier
2588 // have matching data arguments.
2589 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2590 startSpecifier, specifierLen)) {
2594 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2595 startSpecifier, specifierLen)) {
2599 if (!CS.consumesDataArgument()) {
2600 // FIXME: Technically specifying a precision or field width here
2601 // makes no sense. Worth issuing a warning at some point.
2605 // Consume the argument.
2606 unsigned argIndex = FS.getArgIndex();
2607 if (argIndex < NumDataArgs) {
2608 // The check to see if the argIndex is valid will come later.
2609 // We set the bit here because we may exit early from this
2610 // function if we encounter some other error.
2611 CoveredArgs.set(argIndex);
2614 // FreeBSD extensions
2615 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
2616 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
2617 // claim the second argument
2618 CoveredArgs.set(argIndex + 1);
2620 // Now type check the data expression that matches the
2621 // format specifier.
2622 const Expr *Ex = getDataArg(argIndex);
2623 const analyze_printf::ArgType &AT =
2624 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
2625 ArgType(S.Context.IntTy) : ArgType::CStrTy;
2626 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
2627 S.Diag(getLocationOfByte(CS.getStart()),
2628 diag::warn_printf_conversion_argument_type_mismatch)
2629 << AT.getRepresentativeType(S.Context) << Ex->getType()
2630 << getSpecifierRange(startSpecifier, specifierLen)
2631 << Ex->getSourceRange();
2633 // Now type check the data expression that matches the
2634 // format specifier.
2635 Ex = getDataArg(argIndex + 1);
2636 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
2637 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
2638 S.Diag(getLocationOfByte(CS.getStart()),
2639 diag::warn_printf_conversion_argument_type_mismatch)
2640 << AT2.getRepresentativeType(S.Context) << Ex->getType()
2641 << getSpecifierRange(startSpecifier, specifierLen)
2642 << Ex->getSourceRange();
2646 // END OF FREEBSD EXTENSIONS
2648 // Check for using an Objective-C specific conversion specifier
2649 // in a non-ObjC literal.
2650 if (!ObjCContext && CS.isObjCArg()) {
2651 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2655 // Check for invalid use of field width
2656 if (!FS.hasValidFieldWidth()) {
2657 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
2658 startSpecifier, specifierLen);
2661 // Check for invalid use of precision
2662 if (!FS.hasValidPrecision()) {
2663 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2664 startSpecifier, specifierLen);
2667 // Check each flag does not conflict with any other component.
2668 if (!FS.hasValidThousandsGroupingPrefix())
2669 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
2670 if (!FS.hasValidLeadingZeros())
2671 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2672 if (!FS.hasValidPlusPrefix())
2673 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
2674 if (!FS.hasValidSpacePrefix())
2675 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
2676 if (!FS.hasValidAlternativeForm())
2677 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2678 if (!FS.hasValidLeftJustified())
2679 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2681 // Check that flags are not ignored by another flag
2682 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2683 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2684 startSpecifier, specifierLen);
2685 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2686 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2687 startSpecifier, specifierLen);
2689 // Check the length modifier is valid with the given conversion specifier.
2690 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
2691 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2692 diag::warn_format_nonsensical_length);
2693 else if (!FS.hasStandardLengthModifier())
2694 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
2695 else if (!FS.hasStandardLengthConversionCombination())
2696 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2697 diag::warn_format_non_standard_conversion_spec);
2699 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2700 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2702 // The remaining checks depend on the data arguments.
2706 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2709 const Expr *Arg = getDataArg(argIndex);
2713 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
2716 static bool requiresParensToAddCast(const Expr *E) {
2717 // FIXME: We should have a general way to reason about operator
2718 // precedence and whether parens are actually needed here.
2719 // Take care of a few common cases where they aren't.
2720 const Expr *Inside = E->IgnoreImpCasts();
2721 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2722 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2724 switch (Inside->getStmtClass()) {
2725 case Stmt::ArraySubscriptExprClass:
2726 case Stmt::CallExprClass:
2727 case Stmt::DeclRefExprClass:
2728 case Stmt::MemberExprClass:
2729 case Stmt::ObjCIvarRefExprClass:
2730 case Stmt::ObjCMessageExprClass:
2731 case Stmt::ObjCPropertyRefExprClass:
2732 case Stmt::ParenExprClass:
2733 case Stmt::UnaryOperatorClass:
2741 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2742 const char *StartSpecifier,
2743 unsigned SpecifierLen,
2745 using namespace analyze_format_string;
2746 using namespace analyze_printf;
2747 // Now type check the data expression that matches the
2748 // format specifier.
2749 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2754 QualType IntendedTy = E->getType();
2755 if (AT.matchesType(S.Context, IntendedTy))
2758 // Look through argument promotions for our error message's reported type.
2759 // This includes the integral and floating promotions, but excludes array
2760 // and function pointer decay; seeing that an argument intended to be a
2761 // string has type 'char [6]' is probably more confusing than 'char *'.
2762 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2763 if (ICE->getCastKind() == CK_IntegralCast ||
2764 ICE->getCastKind() == CK_FloatingCast) {
2765 E = ICE->getSubExpr();
2766 IntendedTy = E->getType();
2768 // Check if we didn't match because of an implicit cast from a 'char'
2769 // or 'short' to an 'int'. This is done because printf is a varargs
2771 if (ICE->getType() == S.Context.IntTy ||
2772 ICE->getType() == S.Context.UnsignedIntTy) {
2773 // All further checking is done on the subexpression.
2774 if (AT.matchesType(S.Context, IntendedTy))
2780 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2781 // Special-case some of Darwin's platform-independence types.
2782 if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
2783 StringRef Name = UserTy->getDecl()->getName();
2784 IntendedTy = llvm::StringSwitch<QualType>(Name)
2785 .Case("NSInteger", S.Context.LongTy)
2786 .Case("NSUInteger", S.Context.UnsignedLongTy)
2787 .Case("SInt32", S.Context.IntTy)
2788 .Case("UInt32", S.Context.UnsignedIntTy)
2789 .Default(IntendedTy);
2793 // We may be able to offer a FixItHint if it is a supported type.
2794 PrintfSpecifier fixedFS = FS;
2795 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
2796 S.Context, ObjCContext);
2799 // Get the fix string from the fixed format specifier
2800 SmallString<16> buf;
2801 llvm::raw_svector_ostream os(buf);
2802 fixedFS.toString(os);
2804 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2806 if (IntendedTy != E->getType()) {
2807 // The canonical type for formatting this value is different from the
2808 // actual type of the expression. (This occurs, for example, with Darwin's
2809 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2810 // should be printed as 'long' for 64-bit compatibility.)
2811 // Rather than emitting a normal format/argument mismatch, we want to
2812 // add a cast to the recommended type (and correct the format string
2814 SmallString<16> CastBuf;
2815 llvm::raw_svector_ostream CastFix(CastBuf);
2817 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2820 SmallVector<FixItHint,4> Hints;
2821 if (!AT.matchesType(S.Context, IntendedTy))
2822 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2824 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2825 // If there's already a cast present, just replace it.
2826 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2827 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2829 } else if (!requiresParensToAddCast(E)) {
2830 // If the expression has high enough precedence,
2831 // just write the C-style cast.
2832 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2835 // Otherwise, add parens around the expression as well as the cast.
2837 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2840 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2841 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2844 // We extract the name from the typedef because we don't want to show
2845 // the underlying type in the diagnostic.
2846 const TypedefType *UserTy = cast<TypedefType>(E->getType());
2847 StringRef Name = UserTy->getDecl()->getName();
2849 // Finally, emit the diagnostic.
2850 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2851 << Name << IntendedTy
2852 << E->getSourceRange(),
2853 E->getLocStart(), /*IsStringLocation=*/false,
2856 EmitFormatDiagnostic(
2857 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2858 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2859 << E->getSourceRange(),
2861 /*IsStringLocation*/false,
2863 FixItHint::CreateReplacement(SpecRange, os.str()));
2866 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2868 // Since the warning for passing non-POD types to variadic functions
2869 // was deferred until now, we emit a warning for non-POD
2871 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
2873 if (E->getType()->isObjCObjectType())
2874 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2876 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2878 EmitFormatDiagnostic(
2880 << S.getLangOpts().CPlusPlus0x
2883 << AT.getRepresentativeTypeName(S.Context)
2885 << E->getSourceRange(),
2886 E->getLocStart(), /*IsStringLocation*/false, CSR);
2888 checkForCStrMembers(AT, E, CSR);
2890 EmitFormatDiagnostic(
2891 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2892 << AT.getRepresentativeTypeName(S.Context) << E->getType()
2894 << E->getSourceRange(),
2895 E->getLocStart(), /*IsStringLocation*/false, CSR);
2901 //===--- CHECK: Scanf format string checking ------------------------------===//
2904 class CheckScanfHandler : public CheckFormatHandler {
2906 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2907 const Expr *origFormatExpr, unsigned firstDataArg,
2908 unsigned numDataArgs, const char *beg, bool hasVAListArg,
2909 Expr **Args, unsigned NumArgs,
2910 unsigned formatIdx, bool inFunctionCall,
2911 Sema::VariadicCallType CallType)
2912 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2913 numDataArgs, beg, hasVAListArg,
2914 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2917 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2918 const char *startSpecifier,
2919 unsigned specifierLen);
2921 bool HandleInvalidScanfConversionSpecifier(
2922 const analyze_scanf::ScanfSpecifier &FS,
2923 const char *startSpecifier,
2924 unsigned specifierLen);
2926 void HandleIncompleteScanList(const char *start, const char *end);
2930 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2932 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2933 getLocationOfByte(end), /*IsStringLocation*/true,
2934 getSpecifierRange(start, end - start));
2937 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2938 const analyze_scanf::ScanfSpecifier &FS,
2939 const char *startSpecifier,
2940 unsigned specifierLen) {
2942 const analyze_scanf::ScanfConversionSpecifier &CS =
2943 FS.getConversionSpecifier();
2945 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2946 getLocationOfByte(CS.getStart()),
2947 startSpecifier, specifierLen,
2948 CS.getStart(), CS.getLength());
2951 bool CheckScanfHandler::HandleScanfSpecifier(
2952 const analyze_scanf::ScanfSpecifier &FS,
2953 const char *startSpecifier,
2954 unsigned specifierLen) {
2956 using namespace analyze_scanf;
2957 using namespace analyze_format_string;
2959 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
2961 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2962 // be used to decide if we are using positional arguments consistently.
2963 if (FS.consumesDataArgument()) {
2966 usesPositionalArgs = FS.usesPositionalArg();
2968 else if (usesPositionalArgs != FS.usesPositionalArg()) {
2969 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2970 startSpecifier, specifierLen);
2975 // Check if the field with is non-zero.
2976 const OptionalAmount &Amt = FS.getFieldWidth();
2977 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2978 if (Amt.getConstantAmount() == 0) {
2979 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2980 Amt.getConstantLength());
2981 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2982 getLocationOfByte(Amt.getStart()),
2983 /*IsStringLocation*/true, R,
2984 FixItHint::CreateRemoval(R));
2988 if (!FS.consumesDataArgument()) {
2989 // FIXME: Technically specifying a precision or field width here
2990 // makes no sense. Worth issuing a warning at some point.
2994 // Consume the argument.
2995 unsigned argIndex = FS.getArgIndex();
2996 if (argIndex < NumDataArgs) {
2997 // The check to see if the argIndex is valid will come later.
2998 // We set the bit here because we may exit early from this
2999 // function if we encounter some other error.
3000 CoveredArgs.set(argIndex);
3003 // Check the length modifier is valid with the given conversion specifier.
3004 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3005 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3006 diag::warn_format_nonsensical_length);
3007 else if (!FS.hasStandardLengthModifier())
3008 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3009 else if (!FS.hasStandardLengthConversionCombination())
3010 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3011 diag::warn_format_non_standard_conversion_spec);
3013 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3014 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3016 // The remaining checks depend on the data arguments.
3020 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3023 // Check that the argument type matches the format specifier.
3024 const Expr *Ex = getDataArg(argIndex);
3028 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3029 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3030 ScanfSpecifier fixedFS = FS;
3031 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3035 // Get the fix string from the fixed format specifier.
3036 SmallString<128> buf;
3037 llvm::raw_svector_ostream os(buf);
3038 fixedFS.toString(os);
3040 EmitFormatDiagnostic(
3041 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3042 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3043 << Ex->getSourceRange(),
3045 /*IsStringLocation*/false,
3046 getSpecifierRange(startSpecifier, specifierLen),
3047 FixItHint::CreateReplacement(
3048 getSpecifierRange(startSpecifier, specifierLen),
3051 EmitFormatDiagnostic(
3052 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3053 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3054 << Ex->getSourceRange(),
3056 /*IsStringLocation*/false,
3057 getSpecifierRange(startSpecifier, specifierLen));
3064 void Sema::CheckFormatString(const StringLiteral *FExpr,
3065 const Expr *OrigFormatExpr,
3066 Expr **Args, unsigned NumArgs,
3067 bool HasVAListArg, unsigned format_idx,
3068 unsigned firstDataArg, FormatStringType Type,
3069 bool inFunctionCall, VariadicCallType CallType) {
3071 // CHECK: is the format string a wide literal?
3072 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3073 CheckFormatHandler::EmitFormatDiagnostic(
3074 *this, inFunctionCall, Args[format_idx],
3075 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3076 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3080 // Str - The format string. NOTE: this is NOT null-terminated!
3081 StringRef StrRef = FExpr->getString();
3082 const char *Str = StrRef.data();
3083 unsigned StrLen = StrRef.size();
3084 const unsigned numDataArgs = NumArgs - firstDataArg;
3086 // CHECK: empty format string?
3087 if (StrLen == 0 && numDataArgs > 0) {
3088 CheckFormatHandler::EmitFormatDiagnostic(
3089 *this, inFunctionCall, Args[format_idx],
3090 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3091 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3095 if (Type == FST_Printf || Type == FST_NSString) {
3096 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3097 numDataArgs, (Type == FST_NSString),
3098 Str, HasVAListArg, Args, NumArgs, format_idx,
3099 inFunctionCall, CallType);
3101 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3103 Context.getTargetInfo()))
3105 } else if (Type == FST_Scanf) {
3106 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3107 Str, HasVAListArg, Args, NumArgs, format_idx,
3108 inFunctionCall, CallType);
3110 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3112 Context.getTargetInfo()))
3114 } // TODO: handle other formats
3117 //===--- CHECK: Standard memory functions ---------------------------------===//
3119 /// \brief Determine whether the given type is a dynamic class type (e.g.,
3120 /// whether it has a vtable).
3121 static bool isDynamicClassType(QualType T) {
3122 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3123 if (CXXRecordDecl *Definition = Record->getDefinition())
3124 if (Definition->isDynamicClass())
3130 /// \brief If E is a sizeof expression, returns its argument expression,
3131 /// otherwise returns NULL.
3132 static const Expr *getSizeOfExprArg(const Expr* E) {
3133 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3134 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3135 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3136 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3141 /// \brief If E is a sizeof expression, returns its argument type.
3142 static QualType getSizeOfArgType(const Expr* E) {
3143 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3144 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3145 if (SizeOf->getKind() == clang::UETT_SizeOf)
3146 return SizeOf->getTypeOfArgument();
3151 /// \brief Check for dangerous or invalid arguments to memset().
3153 /// This issues warnings on known problematic, dangerous or unspecified
3154 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3157 /// \param Call The call expression to diagnose.
3158 void Sema::CheckMemaccessArguments(const CallExpr *Call,
3160 IdentifierInfo *FnName) {
3163 // It is possible to have a non-standard definition of memset. Validate
3164 // we have enough arguments, and if not, abort further checking.
3165 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
3166 if (Call->getNumArgs() < ExpectedNumArgs)
3169 unsigned LastArg = (BId == Builtin::BImemset ||
3170 BId == Builtin::BIstrndup ? 1 : 2);
3171 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
3172 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
3174 // We have special checking when the length is a sizeof expression.
3175 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3176 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3177 llvm::FoldingSetNodeID SizeOfArgID;
3179 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3180 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
3181 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
3183 QualType DestTy = Dest->getType();
3184 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3185 QualType PointeeTy = DestPtrTy->getPointeeType();
3187 // Never warn about void type pointers. This can be used to suppress
3189 if (PointeeTy->isVoidType())
3192 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3193 // actually comparing the expressions for equality. Because computing the
3194 // expression IDs can be expensive, we only do this if the diagnostic is
3197 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3198 SizeOfArg->getExprLoc())) {
3199 // We only compute IDs for expressions if the warning is enabled, and
3200 // cache the sizeof arg's ID.
3201 if (SizeOfArgID == llvm::FoldingSetNodeID())
3202 SizeOfArg->Profile(SizeOfArgID, Context, true);
3203 llvm::FoldingSetNodeID DestID;
3204 Dest->Profile(DestID, Context, true);
3205 if (DestID == SizeOfArgID) {
3206 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3207 // over sizeof(src) as well.
3208 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
3209 StringRef ReadableName = FnName->getName();
3211 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
3212 if (UnaryOp->getOpcode() == UO_AddrOf)
3213 ActionIdx = 1; // If its an address-of operator, just remove it.
3214 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
3215 ActionIdx = 2; // If the pointee's size is sizeof(char),
3216 // suggest an explicit length.
3218 // If the function is defined as a builtin macro, do not show macro
3220 SourceLocation SL = SizeOfArg->getExprLoc();
3221 SourceRange DSR = Dest->getSourceRange();
3222 SourceRange SSR = SizeOfArg->getSourceRange();
3223 SourceManager &SM = PP.getSourceManager();
3225 if (SM.isMacroArgExpansion(SL)) {
3226 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3227 SL = SM.getSpellingLoc(SL);
3228 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3229 SM.getSpellingLoc(DSR.getEnd()));
3230 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3231 SM.getSpellingLoc(SSR.getEnd()));
3234 DiagRuntimeBehavior(SL, SizeOfArg,
3235 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
3241 DiagRuntimeBehavior(SL, SizeOfArg,
3242 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3250 // Also check for cases where the sizeof argument is the exact same
3251 // type as the memory argument, and where it points to a user-defined
3253 if (SizeOfArgTy != QualType()) {
3254 if (PointeeTy->isRecordType() &&
3255 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3256 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3257 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3258 << FnName << SizeOfArgTy << ArgIdx
3259 << PointeeTy << Dest->getSourceRange()
3260 << LenExpr->getSourceRange());
3265 // Always complain about dynamic classes.
3266 if (isDynamicClassType(PointeeTy)) {
3268 unsigned OperationType = 0;
3269 // "overwritten" if we're warning about the destination for any call
3270 // but memcmp; otherwise a verb appropriate to the call.
3271 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3272 if (BId == Builtin::BImemcpy)
3274 else if(BId == Builtin::BImemmove)
3276 else if (BId == Builtin::BImemcmp)
3280 DiagRuntimeBehavior(
3281 Dest->getExprLoc(), Dest,
3282 PDiag(diag::warn_dyn_class_memaccess)
3283 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
3284 << FnName << PointeeTy
3286 << Call->getCallee()->getSourceRange());
3287 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3288 BId != Builtin::BImemset)
3289 DiagRuntimeBehavior(
3290 Dest->getExprLoc(), Dest,
3291 PDiag(diag::warn_arc_object_memaccess)
3292 << ArgIdx << FnName << PointeeTy
3293 << Call->getCallee()->getSourceRange());
3297 DiagRuntimeBehavior(
3298 Dest->getExprLoc(), Dest,
3299 PDiag(diag::note_bad_memaccess_silence)
3300 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3306 // A little helper routine: ignore addition and subtraction of integer literals.
3307 // This intentionally does not ignore all integer constant expressions because
3308 // we don't want to remove sizeof().
3309 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3310 Ex = Ex->IgnoreParenCasts();
3313 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3314 if (!BO || !BO->isAdditiveOp())
3317 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3318 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3320 if (isa<IntegerLiteral>(RHS))
3322 else if (isa<IntegerLiteral>(LHS))
3331 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3332 ASTContext &Context) {
3333 // Only handle constant-sized or VLAs, but not flexible members.
3334 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3335 // Only issue the FIXIT for arrays of size > 1.
3336 if (CAT->getSize().getSExtValue() <= 1)
3338 } else if (!Ty->isVariableArrayType()) {
3344 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3345 // be the size of the source, instead of the destination.
3346 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3347 IdentifierInfo *FnName) {
3349 // Don't crash if the user has the wrong number of arguments
3350 if (Call->getNumArgs() != 3)
3353 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3354 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3355 const Expr *CompareWithSrc = NULL;
3357 // Look for 'strlcpy(dst, x, sizeof(x))'
3358 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3359 CompareWithSrc = Ex;
3361 // Look for 'strlcpy(dst, x, strlen(x))'
3362 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
3363 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
3364 && SizeCall->getNumArgs() == 1)
3365 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3369 if (!CompareWithSrc)
3372 // Determine if the argument to sizeof/strlen is equal to the source
3373 // argument. In principle there's all kinds of things you could do
3374 // here, for instance creating an == expression and evaluating it with
3375 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3376 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3380 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3381 if (!CompareWithSrcDRE ||
3382 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3385 const Expr *OriginalSizeArg = Call->getArg(2);
3386 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3387 << OriginalSizeArg->getSourceRange() << FnName;
3389 // Output a FIXIT hint if the destination is an array (rather than a
3390 // pointer to an array). This could be enhanced to handle some
3391 // pointers if we know the actual size, like if DstArg is 'array+2'
3392 // we could say 'sizeof(array)-2'.
3393 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
3394 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
3397 SmallString<128> sizeString;
3398 llvm::raw_svector_ostream OS(sizeString);
3400 DstArg->printPretty(OS, 0, getPrintingPolicy());
3403 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3404 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3408 /// Check if two expressions refer to the same declaration.
3409 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3410 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3411 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3412 return D1->getDecl() == D2->getDecl();
3416 static const Expr *getStrlenExprArg(const Expr *E) {
3417 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3418 const FunctionDecl *FD = CE->getDirectCallee();
3419 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3421 return CE->getArg(0)->IgnoreParenCasts();
3426 // Warn on anti-patterns as the 'size' argument to strncat.
3427 // The correct size argument should look like following:
3428 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3429 void Sema::CheckStrncatArguments(const CallExpr *CE,
3430 IdentifierInfo *FnName) {
3431 // Don't crash if the user has the wrong number of arguments.
3432 if (CE->getNumArgs() < 3)
3434 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3435 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3436 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3438 // Identify common expressions, which are wrongly used as the size argument
3439 // to strncat and may lead to buffer overflows.
3440 unsigned PatternType = 0;
3441 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3443 if (referToTheSameDecl(SizeOfArg, DstArg))
3446 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3448 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3449 if (BE->getOpcode() == BO_Sub) {
3450 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3451 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3452 // - sizeof(dst) - strlen(dst)
3453 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3454 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3456 // - sizeof(src) - (anything)
3457 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3462 if (PatternType == 0)
3465 // Generate the diagnostic.
3466 SourceLocation SL = LenArg->getLocStart();
3467 SourceRange SR = LenArg->getSourceRange();
3468 SourceManager &SM = PP.getSourceManager();
3470 // If the function is defined as a builtin macro, do not show macro expansion.
3471 if (SM.isMacroArgExpansion(SL)) {
3472 SL = SM.getSpellingLoc(SL);
3473 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3474 SM.getSpellingLoc(SR.getEnd()));
3477 // Check if the destination is an array (rather than a pointer to an array).
3478 QualType DstTy = DstArg->getType();
3479 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3481 if (!isKnownSizeArray) {
3482 if (PatternType == 1)
3483 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3485 Diag(SL, diag::warn_strncat_src_size) << SR;
3489 if (PatternType == 1)
3490 Diag(SL, diag::warn_strncat_large_size) << SR;
3492 Diag(SL, diag::warn_strncat_src_size) << SR;
3494 SmallString<128> sizeString;
3495 llvm::raw_svector_ostream OS(sizeString);
3497 DstArg->printPretty(OS, 0, getPrintingPolicy());
3500 DstArg->printPretty(OS, 0, getPrintingPolicy());
3503 Diag(SL, diag::note_strncat_wrong_size)
3504 << FixItHint::CreateReplacement(SR, OS.str());
3507 //===--- CHECK: Return Address of Stack Variable --------------------------===//
3509 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3511 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3514 /// CheckReturnStackAddr - Check if a return statement returns the address
3515 /// of a stack variable.
3517 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3518 SourceLocation ReturnLoc) {
3521 SmallVector<DeclRefExpr *, 8> refVars;
3523 // Perform checking for returned stack addresses, local blocks,
3524 // label addresses or references to temporaries.
3525 if (lhsType->isPointerType() ||
3526 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
3527 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
3528 } else if (lhsType->isReferenceType()) {
3529 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
3533 return; // Nothing suspicious was found.
3535 SourceLocation diagLoc;
3536 SourceRange diagRange;
3537 if (refVars.empty()) {
3538 diagLoc = stackE->getLocStart();
3539 diagRange = stackE->getSourceRange();
3541 // We followed through a reference variable. 'stackE' contains the
3542 // problematic expression but we will warn at the return statement pointing
3543 // at the reference variable. We will later display the "trail" of
3544 // reference variables using notes.
3545 diagLoc = refVars[0]->getLocStart();
3546 diagRange = refVars[0]->getSourceRange();
3549 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3550 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3551 : diag::warn_ret_stack_addr)
3552 << DR->getDecl()->getDeclName() << diagRange;
3553 } else if (isa<BlockExpr>(stackE)) { // local block.
3554 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3555 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3556 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3557 } else { // local temporary.
3558 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3559 : diag::warn_ret_local_temp_addr)
3563 // Display the "trail" of reference variables that we followed until we
3564 // found the problematic expression using notes.
3565 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3566 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3567 // If this var binds to another reference var, show the range of the next
3568 // var, otherwise the var binds to the problematic expression, in which case
3569 // show the range of the expression.
3570 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3571 : stackE->getSourceRange();
3572 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3573 << VD->getDeclName() << range;
3577 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3578 /// check if the expression in a return statement evaluates to an address
3579 /// to a location on the stack, a local block, an address of a label, or a
3580 /// reference to local temporary. The recursion is used to traverse the
3581 /// AST of the return expression, with recursion backtracking when we
3582 /// encounter a subexpression that (1) clearly does not lead to one of the
3583 /// above problematic expressions (2) is something we cannot determine leads to
3584 /// a problematic expression based on such local checking.
3586 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
3587 /// the expression that they point to. Such variables are added to the
3588 /// 'refVars' vector so that we know what the reference variable "trail" was.
3590 /// EvalAddr processes expressions that are pointers that are used as
3591 /// references (and not L-values). EvalVal handles all other values.
3592 /// At the base case of the recursion is a check for the above problematic
3595 /// This implementation handles:
3597 /// * pointer-to-pointer casts
3598 /// * implicit conversions from array references to pointers
3599 /// * taking the address of fields
3600 /// * arbitrary interplay between "&" and "*" operators
3601 /// * pointer arithmetic from an address of a stack variable
3602 /// * taking the address of an array element where the array is on the stack
3603 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3605 if (E->isTypeDependent())
3608 // We should only be called for evaluating pointer expressions.
3609 assert((E->getType()->isAnyPointerType() ||
3610 E->getType()->isBlockPointerType() ||
3611 E->getType()->isObjCQualifiedIdType()) &&
3612 "EvalAddr only works on pointers");
3614 E = E->IgnoreParens();
3616 // Our "symbolic interpreter" is just a dispatch off the currently
3617 // viewed AST node. We then recursively traverse the AST by calling
3618 // EvalAddr and EvalVal appropriately.
3619 switch (E->getStmtClass()) {
3620 case Stmt::DeclRefExprClass: {
3621 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3623 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3624 // If this is a reference variable, follow through to the expression that
3626 if (V->hasLocalStorage() &&
3627 V->getType()->isReferenceType() && V->hasInit()) {
3628 // Add the reference variable to the "trail".
3629 refVars.push_back(DR);
3630 return EvalAddr(V->getInit(), refVars, ParentDecl);
3636 case Stmt::UnaryOperatorClass: {
3637 // The only unary operator that make sense to handle here
3638 // is AddrOf. All others don't make sense as pointers.
3639 UnaryOperator *U = cast<UnaryOperator>(E);
3641 if (U->getOpcode() == UO_AddrOf)
3642 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
3647 case Stmt::BinaryOperatorClass: {
3648 // Handle pointer arithmetic. All other binary operators are not valid
3650 BinaryOperator *B = cast<BinaryOperator>(E);
3651 BinaryOperatorKind op = B->getOpcode();
3653 if (op != BO_Add && op != BO_Sub)
3656 Expr *Base = B->getLHS();
3658 // Determine which argument is the real pointer base. It could be
3659 // the RHS argument instead of the LHS.
3660 if (!Base->getType()->isPointerType()) Base = B->getRHS();
3662 assert (Base->getType()->isPointerType());
3663 return EvalAddr(Base, refVars, ParentDecl);
3666 // For conditional operators we need to see if either the LHS or RHS are
3667 // valid DeclRefExpr*s. If one of them is valid, we return it.
3668 case Stmt::ConditionalOperatorClass: {
3669 ConditionalOperator *C = cast<ConditionalOperator>(E);
3671 // Handle the GNU extension for missing LHS.
3672 if (Expr *lhsExpr = C->getLHS()) {
3673 // In C++, we can have a throw-expression, which has 'void' type.
3674 if (!lhsExpr->getType()->isVoidType())
3675 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
3679 // In C++, we can have a throw-expression, which has 'void' type.
3680 if (C->getRHS()->getType()->isVoidType())
3683 return EvalAddr(C->getRHS(), refVars, ParentDecl);
3686 case Stmt::BlockExprClass:
3687 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
3688 return E; // local block.
3691 case Stmt::AddrLabelExprClass:
3692 return E; // address of label.
3694 case Stmt::ExprWithCleanupsClass:
3695 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3698 // For casts, we need to handle conversions from arrays to
3699 // pointer values, and pointer-to-pointer conversions.
3700 case Stmt::ImplicitCastExprClass:
3701 case Stmt::CStyleCastExprClass:
3702 case Stmt::CXXFunctionalCastExprClass:
3703 case Stmt::ObjCBridgedCastExprClass:
3704 case Stmt::CXXStaticCastExprClass:
3705 case Stmt::CXXDynamicCastExprClass:
3706 case Stmt::CXXConstCastExprClass:
3707 case Stmt::CXXReinterpretCastExprClass: {
3708 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3709 switch (cast<CastExpr>(E)->getCastKind()) {
3711 case CK_LValueToRValue:
3713 case CK_BaseToDerived:
3714 case CK_DerivedToBase:
3715 case CK_UncheckedDerivedToBase:
3717 case CK_CPointerToObjCPointerCast:
3718 case CK_BlockPointerToObjCPointerCast:
3719 case CK_AnyPointerToBlockPointerCast:
3720 return EvalAddr(SubExpr, refVars, ParentDecl);
3722 case CK_ArrayToPointerDecay:
3723 return EvalVal(SubExpr, refVars, ParentDecl);
3730 case Stmt::MaterializeTemporaryExprClass:
3731 if (Expr *Result = EvalAddr(
3732 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3733 refVars, ParentDecl))
3738 // Everything else: we simply don't reason about them.
3745 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
3746 /// See the comments for EvalAddr for more details.
3747 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3750 // We should only be called for evaluating non-pointer expressions, or
3751 // expressions with a pointer type that are not used as references but instead
3752 // are l-values (e.g., DeclRefExpr with a pointer type).
3754 // Our "symbolic interpreter" is just a dispatch off the currently
3755 // viewed AST node. We then recursively traverse the AST by calling
3756 // EvalAddr and EvalVal appropriately.
3758 E = E->IgnoreParens();
3759 switch (E->getStmtClass()) {
3760 case Stmt::ImplicitCastExprClass: {
3761 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
3762 if (IE->getValueKind() == VK_LValue) {
3763 E = IE->getSubExpr();
3769 case Stmt::ExprWithCleanupsClass:
3770 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
3772 case Stmt::DeclRefExprClass: {
3773 // When we hit a DeclRefExpr we are looking at code that refers to a
3774 // variable's name. If it's not a reference variable we check if it has
3775 // local storage within the function, and if so, return the expression.
3776 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3778 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3779 // Check if it refers to itself, e.g. "int& i = i;".
3780 if (V == ParentDecl)
3783 if (V->hasLocalStorage()) {
3784 if (!V->getType()->isReferenceType())
3787 // Reference variable, follow through to the expression that
3790 // Add the reference variable to the "trail".
3791 refVars.push_back(DR);
3792 return EvalVal(V->getInit(), refVars, V);
3800 case Stmt::UnaryOperatorClass: {
3801 // The only unary operator that make sense to handle here
3802 // is Deref. All others don't resolve to a "name." This includes
3803 // handling all sorts of rvalues passed to a unary operator.
3804 UnaryOperator *U = cast<UnaryOperator>(E);
3806 if (U->getOpcode() == UO_Deref)
3807 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
3812 case Stmt::ArraySubscriptExprClass: {
3813 // Array subscripts are potential references to data on the stack. We
3814 // retrieve the DeclRefExpr* for the array variable if it indeed
3815 // has local storage.
3816 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
3819 case Stmt::ConditionalOperatorClass: {
3820 // For conditional operators we need to see if either the LHS or RHS are
3821 // non-NULL Expr's. If one is non-NULL, we return it.
3822 ConditionalOperator *C = cast<ConditionalOperator>(E);
3824 // Handle the GNU extension for missing LHS.
3825 if (Expr *lhsExpr = C->getLHS())
3826 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
3829 return EvalVal(C->getRHS(), refVars, ParentDecl);
3832 // Accesses to members are potential references to data on the stack.
3833 case Stmt::MemberExprClass: {
3834 MemberExpr *M = cast<MemberExpr>(E);
3836 // Check for indirect access. We only want direct field accesses.
3840 // Check whether the member type is itself a reference, in which case
3841 // we're not going to refer to the member, but to what the member refers to.
3842 if (M->getMemberDecl()->getType()->isReferenceType())
3845 return EvalVal(M->getBase(), refVars, ParentDecl);
3848 case Stmt::MaterializeTemporaryExprClass:
3849 if (Expr *Result = EvalVal(
3850 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3851 refVars, ParentDecl))
3857 // Check that we don't return or take the address of a reference to a
3858 // temporary. This is only useful in C++.
3859 if (!E->isTypeDependent() && E->isRValue())
3862 // Everything else: we simply don't reason about them.
3868 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3870 /// Check for comparisons of floating point operands using != and ==.
3871 /// Issue a warning if these are no self-comparisons, as they are not likely
3872 /// to do what the programmer intended.
3873 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
3874 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3875 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
3877 // Special case: check for x == x (which is OK).
3878 // Do not emit warnings for such cases.
3879 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3880 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3881 if (DRL->getDecl() == DRR->getDecl())
3885 // Special case: check for comparisons against literals that can be exactly
3886 // represented by APFloat. In such cases, do not emit a warning. This
3887 // is a heuristic: often comparison against such literals are used to
3888 // detect if a value in a variable has not changed. This clearly can
3889 // lead to false negatives.
3890 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3894 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3898 // Check for comparisons with builtin types.
3899 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3900 if (CL->isBuiltinCall())
3903 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3904 if (CR->isBuiltinCall())
3907 // Emit the diagnostic.
3908 Diag(Loc, diag::warn_floatingpoint_eq)
3909 << LHS->getSourceRange() << RHS->getSourceRange();
3912 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3913 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
3917 /// Structure recording the 'active' range of an integer-valued
3920 /// The number of bits active in the int.
3923 /// True if the int is known not to have negative values.
3926 IntRange(unsigned Width, bool NonNegative)
3927 : Width(Width), NonNegative(NonNegative)
3930 /// Returns the range of the bool type.
3931 static IntRange forBoolType() {
3932 return IntRange(1, true);
3935 /// Returns the range of an opaque value of the given integral type.
3936 static IntRange forValueOfType(ASTContext &C, QualType T) {
3937 return forValueOfCanonicalType(C,
3938 T->getCanonicalTypeInternal().getTypePtr());
3941 /// Returns the range of an opaque value of a canonical integral type.
3942 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
3943 assert(T->isCanonicalUnqualified());
3945 if (const VectorType *VT = dyn_cast<VectorType>(T))
3946 T = VT->getElementType().getTypePtr();
3947 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3948 T = CT->getElementType().getTypePtr();
3950 // For enum types, use the known bit width of the enumerators.
3951 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3952 EnumDecl *Enum = ET->getDecl();
3953 if (!Enum->isCompleteDefinition())
3954 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3956 unsigned NumPositive = Enum->getNumPositiveBits();
3957 unsigned NumNegative = Enum->getNumNegativeBits();
3959 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3962 const BuiltinType *BT = cast<BuiltinType>(T);
3963 assert(BT->isInteger());
3965 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3968 /// Returns the "target" range of a canonical integral type, i.e.
3969 /// the range of values expressible in the type.
3971 /// This matches forValueOfCanonicalType except that enums have the
3972 /// full range of their type, not the range of their enumerators.
3973 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3974 assert(T->isCanonicalUnqualified());
3976 if (const VectorType *VT = dyn_cast<VectorType>(T))
3977 T = VT->getElementType().getTypePtr();
3978 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3979 T = CT->getElementType().getTypePtr();
3980 if (const EnumType *ET = dyn_cast<EnumType>(T))
3981 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
3983 const BuiltinType *BT = cast<BuiltinType>(T);
3984 assert(BT->isInteger());
3986 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3989 /// Returns the supremum of two ranges: i.e. their conservative merge.
3990 static IntRange join(IntRange L, IntRange R) {
3991 return IntRange(std::max(L.Width, R.Width),
3992 L.NonNegative && R.NonNegative);
3995 /// Returns the infinum of two ranges: i.e. their aggressive merge.
3996 static IntRange meet(IntRange L, IntRange R) {
3997 return IntRange(std::min(L.Width, R.Width),
3998 L.NonNegative || R.NonNegative);
4002 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4003 unsigned MaxWidth) {
4004 if (value.isSigned() && value.isNegative())
4005 return IntRange(value.getMinSignedBits(), false);
4007 if (value.getBitWidth() > MaxWidth)
4008 value = value.trunc(MaxWidth);
4010 // isNonNegative() just checks the sign bit without considering
4012 return IntRange(value.getActiveBits(), true);
4015 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4016 unsigned MaxWidth) {
4018 return GetValueRange(C, result.getInt(), MaxWidth);
4020 if (result.isVector()) {
4021 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4022 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4023 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4024 R = IntRange::join(R, El);
4029 if (result.isComplexInt()) {
4030 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4031 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4032 return IntRange::join(R, I);
4035 // This can happen with lossless casts to intptr_t of "based" lvalues.
4036 // Assume it might use arbitrary bits.
4037 // FIXME: The only reason we need to pass the type in here is to get
4038 // the sign right on this one case. It would be nice if APValue
4040 assert(result.isLValue() || result.isAddrLabelDiff());
4041 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4044 /// Pseudo-evaluate the given integer expression, estimating the
4045 /// range of values it might take.
4047 /// \param MaxWidth - the width to which the value will be truncated
4048 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4049 E = E->IgnoreParens();
4051 // Try a full evaluation first.
4052 Expr::EvalResult result;
4053 if (E->EvaluateAsRValue(result, C))
4054 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
4056 // I think we only want to look through implicit casts here; if the
4057 // user has an explicit widening cast, we should treat the value as
4058 // being of the new, wider type.
4059 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4060 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4061 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4063 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
4065 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4067 // Assume that non-integer casts can span the full range of the type.
4069 return OutputTypeRange;
4072 = GetExprRange(C, CE->getSubExpr(),
4073 std::min(MaxWidth, OutputTypeRange.Width));
4075 // Bail out if the subexpr's range is as wide as the cast type.
4076 if (SubRange.Width >= OutputTypeRange.Width)
4077 return OutputTypeRange;
4079 // Otherwise, we take the smaller width, and we're non-negative if
4080 // either the output type or the subexpr is.
4081 return IntRange(SubRange.Width,
4082 SubRange.NonNegative || OutputTypeRange.NonNegative);
4085 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4086 // If we can fold the condition, just take that operand.
4088 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4089 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4090 : CO->getFalseExpr(),
4093 // Otherwise, conservatively merge.
4094 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4095 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4096 return IntRange::join(L, R);
4099 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4100 switch (BO->getOpcode()) {
4102 // Boolean-valued operations are single-bit and positive.
4111 return IntRange::forBoolType();
4113 // The type of the assignments is the type of the LHS, so the RHS
4114 // is not necessarily the same type.
4123 return IntRange::forValueOfType(C, E->getType());
4125 // Simple assignments just pass through the RHS, which will have
4126 // been coerced to the LHS type.
4129 return GetExprRange(C, BO->getRHS(), MaxWidth);
4131 // Operations with opaque sources are black-listed.
4134 return IntRange::forValueOfType(C, E->getType());
4136 // Bitwise-and uses the *infinum* of the two source ranges.
4139 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4140 GetExprRange(C, BO->getRHS(), MaxWidth));
4142 // Left shift gets black-listed based on a judgement call.
4144 // ...except that we want to treat '1 << (blah)' as logically
4145 // positive. It's an important idiom.
4146 if (IntegerLiteral *I
4147 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4148 if (I->getValue() == 1) {
4149 IntRange R = IntRange::forValueOfType(C, E->getType());
4150 return IntRange(R.Width, /*NonNegative*/ true);
4156 return IntRange::forValueOfType(C, E->getType());
4158 // Right shift by a constant can narrow its left argument.
4160 case BO_ShrAssign: {
4161 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4163 // If the shift amount is a positive constant, drop the width by
4166 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4167 shift.isNonNegative()) {
4168 unsigned zext = shift.getZExtValue();
4169 if (zext >= L.Width)
4170 L.Width = (L.NonNegative ? 0 : 1);
4178 // Comma acts as its right operand.
4180 return GetExprRange(C, BO->getRHS(), MaxWidth);
4182 // Black-list pointer subtractions.
4184 if (BO->getLHS()->getType()->isPointerType())
4185 return IntRange::forValueOfType(C, E->getType());
4188 // The width of a division result is mostly determined by the size
4191 // Don't 'pre-truncate' the operands.
4192 unsigned opWidth = C.getIntWidth(E->getType());
4193 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4195 // If the divisor is constant, use that.
4196 llvm::APSInt divisor;
4197 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4198 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4199 if (log2 >= L.Width)
4200 L.Width = (L.NonNegative ? 0 : 1);
4202 L.Width = std::min(L.Width - log2, MaxWidth);
4206 // Otherwise, just use the LHS's width.
4207 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4208 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4211 // The result of a remainder can't be larger than the result of
4214 // Don't 'pre-truncate' the operands.
4215 unsigned opWidth = C.getIntWidth(E->getType());
4216 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4217 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4219 IntRange meet = IntRange::meet(L, R);
4220 meet.Width = std::min(meet.Width, MaxWidth);
4224 // The default behavior is okay for these.
4232 // The default case is to treat the operation as if it were closed
4233 // on the narrowest type that encompasses both operands.
4234 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4235 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4236 return IntRange::join(L, R);
4239 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4240 switch (UO->getOpcode()) {
4241 // Boolean-valued operations are white-listed.
4243 return IntRange::forBoolType();
4245 // Operations with opaque sources are black-listed.
4247 case UO_AddrOf: // should be impossible
4248 return IntRange::forValueOfType(C, E->getType());
4251 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4255 if (dyn_cast<OffsetOfExpr>(E)) {
4256 IntRange::forValueOfType(C, E->getType());
4259 if (FieldDecl *BitField = E->getBitField())
4260 return IntRange(BitField->getBitWidthValue(C),
4261 BitField->getType()->isUnsignedIntegerOrEnumerationType());
4263 return IntRange::forValueOfType(C, E->getType());
4266 static IntRange GetExprRange(ASTContext &C, Expr *E) {
4267 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4270 /// Checks whether the given value, which currently has the given
4271 /// source semantics, has the same value when coerced through the
4272 /// target semantics.
4273 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4274 const llvm::fltSemantics &Src,
4275 const llvm::fltSemantics &Tgt) {
4276 llvm::APFloat truncated = value;
4279 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4280 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4282 return truncated.bitwiseIsEqual(value);
4285 /// Checks whether the given value, which currently has the given
4286 /// source semantics, has the same value when coerced through the
4287 /// target semantics.
4289 /// The value might be a vector of floats (or a complex number).
4290 static bool IsSameFloatAfterCast(const APValue &value,
4291 const llvm::fltSemantics &Src,
4292 const llvm::fltSemantics &Tgt) {
4293 if (value.isFloat())
4294 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4296 if (value.isVector()) {
4297 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4298 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4303 assert(value.isComplexFloat());
4304 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4305 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4308 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
4310 static bool IsZero(Sema &S, Expr *E) {
4311 // Suppress cases where we are comparing against an enum constant.
4312 if (const DeclRefExpr *DR =
4313 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4314 if (isa<EnumConstantDecl>(DR->getDecl()))
4317 // Suppress cases where the '0' value is expanded from a macro.
4318 if (E->getLocStart().isMacroID())
4322 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4325 static bool HasEnumType(Expr *E) {
4326 // Strip off implicit integral promotions.
4327 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4328 if (ICE->getCastKind() != CK_IntegralCast &&
4329 ICE->getCastKind() != CK_NoOp)
4331 E = ICE->getSubExpr();
4334 return E->getType()->isEnumeralType();
4337 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
4338 BinaryOperatorKind op = E->getOpcode();
4339 if (E->isValueDependent())
4342 if (op == BO_LT && IsZero(S, E->getRHS())) {
4343 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4344 << "< 0" << "false" << HasEnumType(E->getLHS())
4345 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4346 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
4347 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4348 << ">= 0" << "true" << HasEnumType(E->getLHS())
4349 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4350 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
4351 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4352 << "0 >" << "false" << HasEnumType(E->getRHS())
4353 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4354 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
4355 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4356 << "0 <=" << "true" << HasEnumType(E->getRHS())
4357 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4361 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
4362 Expr *Constant, Expr *Other,
4365 BinaryOperatorKind op = E->getOpcode();
4366 QualType OtherT = Other->getType();
4367 QualType ConstantT = Constant->getType();
4368 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
4370 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
4371 && "comparison with non-integer type");
4372 // FIXME. handle cases for signedness to catch (signed char)N == 200
4373 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
4374 IntRange LitRange = GetValueRange(S.Context, Value, Value.getBitWidth());
4375 if (OtherRange.Width >= LitRange.Width)
4380 else if (op == BO_NE)
4382 else if (RhsConstant) {
4383 if (op == BO_GT || op == BO_GE)
4384 IsTrue = !LitRange.NonNegative;
4385 else // op == BO_LT || op == BO_LE
4386 IsTrue = LitRange.NonNegative;
4388 if (op == BO_LT || op == BO_LE)
4389 IsTrue = !LitRange.NonNegative;
4390 else // op == BO_GT || op == BO_GE
4391 IsTrue = LitRange.NonNegative;
4393 SmallString<16> PrettySourceValue(Value.toString(10));
4394 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4395 << PrettySourceValue << OtherT << IsTrue
4396 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4399 /// Analyze the operands of the given comparison. Implements the
4400 /// fallback case from AnalyzeComparison.
4401 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
4402 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4403 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4406 /// \brief Implements -Wsign-compare.
4408 /// \param E the binary operator to check for warnings
4409 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
4410 // The type the comparison is being performed in.
4411 QualType T = E->getLHS()->getType();
4412 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4413 && "comparison with mismatched types");
4414 if (E->isValueDependent())
4415 return AnalyzeImpConvsInComparison(S, E);
4417 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4418 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
4420 bool IsComparisonConstant = false;
4422 // Check whether an integer constant comparison results in a value
4423 // of 'true' or 'false'.
4424 if (T->isIntegralType(S.Context)) {
4425 llvm::APSInt RHSValue;
4426 bool IsRHSIntegralLiteral =
4427 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4428 llvm::APSInt LHSValue;
4429 bool IsLHSIntegralLiteral =
4430 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4431 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4432 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4433 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4434 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4436 IsComparisonConstant =
4437 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
4438 } else if (!T->hasUnsignedIntegerRepresentation())
4439 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
4441 // We don't do anything special if this isn't an unsigned integral
4442 // comparison: we're only interested in integral comparisons, and
4443 // signed comparisons only happen in cases we don't care to warn about.
4445 // We also don't care about value-dependent expressions or expressions
4446 // whose result is a constant.
4447 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
4448 return AnalyzeImpConvsInComparison(S, E);
4450 // Check to see if one of the (unmodified) operands is of different
4452 Expr *signedOperand, *unsignedOperand;
4453 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4454 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
4455 "unsigned comparison between two signed integer expressions?");
4456 signedOperand = LHS;
4457 unsignedOperand = RHS;
4458 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4459 signedOperand = RHS;
4460 unsignedOperand = LHS;
4462 CheckTrivialUnsignedComparison(S, E);
4463 return AnalyzeImpConvsInComparison(S, E);
4466 // Otherwise, calculate the effective range of the signed operand.
4467 IntRange signedRange = GetExprRange(S.Context, signedOperand);
4469 // Go ahead and analyze implicit conversions in the operands. Note
4470 // that we skip the implicit conversions on both sides.
4471 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4472 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
4474 // If the signed range is non-negative, -Wsign-compare won't fire,
4475 // but we should still check for comparisons which are always true
4477 if (signedRange.NonNegative)
4478 return CheckTrivialUnsignedComparison(S, E);
4480 // For (in)equality comparisons, if the unsigned operand is a
4481 // constant which cannot collide with a overflowed signed operand,
4482 // then reinterpreting the signed operand as unsigned will not
4483 // change the result of the comparison.
4484 if (E->isEqualityOp()) {
4485 unsigned comparisonWidth = S.Context.getIntWidth(T);
4486 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
4488 // We should never be unable to prove that the unsigned operand is
4490 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4492 if (unsignedRange.Width < comparisonWidth)
4496 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4497 S.PDiag(diag::warn_mixed_sign_comparison)
4498 << LHS->getType() << RHS->getType()
4499 << LHS->getSourceRange() << RHS->getSourceRange());
4502 /// Analyzes an attempt to assign the given value to a bitfield.
4504 /// Returns true if there was something fishy about the attempt.
4505 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4506 SourceLocation InitLoc) {
4507 assert(Bitfield->isBitField());
4508 if (Bitfield->isInvalidDecl())
4511 // White-list bool bitfields.
4512 if (Bitfield->getType()->isBooleanType())
4515 // Ignore value- or type-dependent expressions.
4516 if (Bitfield->getBitWidth()->isValueDependent() ||
4517 Bitfield->getBitWidth()->isTypeDependent() ||
4518 Init->isValueDependent() ||
4519 Init->isTypeDependent())
4522 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4525 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
4528 unsigned OriginalWidth = Value.getBitWidth();
4529 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
4531 if (OriginalWidth <= FieldWidth)
4534 // Compute the value which the bitfield will contain.
4535 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
4536 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
4538 // Check whether the stored value is equal to the original value.
4539 TruncatedValue = TruncatedValue.extend(OriginalWidth);
4540 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
4543 // Special-case bitfields of width 1: booleans are naturally 0/1, and
4544 // therefore don't strictly fit into a signed bitfield of width 1.
4545 if (FieldWidth == 1 && Value == 1)
4548 std::string PrettyValue = Value.toString(10);
4549 std::string PrettyTrunc = TruncatedValue.toString(10);
4551 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4552 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4553 << Init->getSourceRange();
4558 /// Analyze the given simple or compound assignment for warning-worthy
4560 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
4561 // Just recurse on the LHS.
4562 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4564 // We want to recurse on the RHS as normal unless we're assigning to
4566 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
4567 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4568 E->getOperatorLoc())) {
4569 // Recurse, ignoring any implicit conversions on the RHS.
4570 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4571 E->getOperatorLoc());
4575 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4578 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
4579 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
4580 SourceLocation CContext, unsigned diag,
4581 bool pruneControlFlow = false) {
4582 if (pruneControlFlow) {
4583 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4585 << SourceType << T << E->getSourceRange()
4586 << SourceRange(CContext));
4589 S.Diag(E->getExprLoc(), diag)
4590 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4593 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
4594 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
4595 SourceLocation CContext, unsigned diag,
4596 bool pruneControlFlow = false) {
4597 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
4600 /// Diagnose an implicit cast from a literal expression. Does not warn when the
4601 /// cast wouldn't lose information.
4602 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4603 SourceLocation CContext) {
4604 // Try to convert the literal exactly to an integer. If we can, don't warn.
4605 bool isExact = false;
4606 const llvm::APFloat &Value = FL->getValue();
4607 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4608 T->hasUnsignedIntegerRepresentation());
4609 if (Value.convertToInteger(IntegerValue,
4610 llvm::APFloat::rmTowardZero, &isExact)
4611 == llvm::APFloat::opOK && isExact)
4614 SmallString<16> PrettySourceValue;
4615 Value.toString(PrettySourceValue);
4616 SmallString<16> PrettyTargetValue;
4617 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4618 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4620 IntegerValue.toString(PrettyTargetValue);
4622 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
4623 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4624 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
4627 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4628 if (!Range.Width) return "0";
4630 llvm::APSInt ValueInRange = Value;
4631 ValueInRange.setIsSigned(!Range.NonNegative);
4632 ValueInRange = ValueInRange.trunc(Range.Width);
4633 return ValueInRange.toString(10);
4636 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4637 if (!isa<ImplicitCastExpr>(Ex))
4640 Expr *InnerE = Ex->IgnoreParenImpCasts();
4641 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4642 const Type *Source =
4643 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4644 if (Target->isDependentType())
4647 const BuiltinType *FloatCandidateBT =
4648 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4649 const Type *BoolCandidateType = ToBool ? Target : Source;
4651 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4652 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4655 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4656 SourceLocation CC) {
4657 unsigned NumArgs = TheCall->getNumArgs();
4658 for (unsigned i = 0; i < NumArgs; ++i) {
4659 Expr *CurrA = TheCall->getArg(i);
4660 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4663 bool IsSwapped = ((i > 0) &&
4664 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4665 IsSwapped |= ((i < (NumArgs - 1)) &&
4666 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4668 // Warn on this floating-point to bool conversion.
4669 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4670 CurrA->getType(), CC,
4671 diag::warn_impcast_floating_point_to_bool);
4676 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
4677 SourceLocation CC, bool *ICContext = 0) {
4678 if (E->isTypeDependent() || E->isValueDependent()) return;
4680 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4681 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4682 if (Source == Target) return;
4683 if (Target->isDependentType()) return;
4685 // If the conversion context location is invalid don't complain. We also
4686 // don't want to emit a warning if the issue occurs from the expansion of
4687 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4688 // delay this check as long as possible. Once we detect we are in that
4689 // scenario, we just return.
4693 // Diagnose implicit casts to bool.
4694 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4695 if (isa<StringLiteral>(E))
4696 // Warn on string literal to bool. Checks for string literals in logical
4697 // expressions, for instances, assert(0 && "error here"), is prevented
4698 // by a check in AnalyzeImplicitConversions().
4699 return DiagnoseImpCast(S, E, T, CC,
4700 diag::warn_impcast_string_literal_to_bool);
4701 if (Source->isFunctionType()) {
4702 // Warn on function to bool. Checks free functions and static member
4703 // functions. Weakly imported functions are excluded from the check,
4704 // since it's common to test their value to check whether the linker
4705 // found a definition for them.
4707 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4709 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4710 D = M->getMemberDecl();
4713 if (D && !D->isWeak()) {
4714 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4715 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4716 << F << E->getSourceRange() << SourceRange(CC);
4717 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4718 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4719 QualType ReturnType;
4720 UnresolvedSet<4> NonTemplateOverloads;
4721 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4722 if (!ReturnType.isNull()
4723 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4724 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4725 << FixItHint::CreateInsertion(
4726 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
4733 // Strip vector types.
4734 if (isa<VectorType>(Source)) {
4735 if (!isa<VectorType>(Target)) {
4736 if (S.SourceMgr.isInSystemMacro(CC))
4738 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
4741 // If the vector cast is cast between two vectors of the same size, it is
4742 // a bitcast, not a conversion.
4743 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4746 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4747 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4750 // Strip complex types.
4751 if (isa<ComplexType>(Source)) {
4752 if (!isa<ComplexType>(Target)) {
4753 if (S.SourceMgr.isInSystemMacro(CC))
4756 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
4759 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4760 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4763 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4764 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4766 // If the source is floating point...
4767 if (SourceBT && SourceBT->isFloatingPoint()) {
4768 // ...and the target is floating point...
4769 if (TargetBT && TargetBT->isFloatingPoint()) {
4770 // ...then warn if we're dropping FP rank.
4772 // Builtin FP kinds are ordered by increasing FP rank.
4773 if (SourceBT->getKind() > TargetBT->getKind()) {
4774 // Don't warn about float constants that are precisely
4775 // representable in the target type.
4776 Expr::EvalResult result;
4777 if (E->EvaluateAsRValue(result, S.Context)) {
4778 // Value might be a float, a float vector, or a float complex.
4779 if (IsSameFloatAfterCast(result.Val,
4780 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4781 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
4785 if (S.SourceMgr.isInSystemMacro(CC))
4788 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
4793 // If the target is integral, always warn.
4794 if (TargetBT && TargetBT->isInteger()) {
4795 if (S.SourceMgr.isInSystemMacro(CC))
4798 Expr *InnerE = E->IgnoreParenImpCasts();
4799 // We also want to warn on, e.g., "int i = -1.234"
4800 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4801 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4802 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4804 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4805 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
4807 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4811 // If the target is bool, warn if expr is a function or method call.
4812 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4814 // Check last argument of function call to see if it is an
4815 // implicit cast from a type matching the type the result
4816 // is being cast to.
4817 CallExpr *CEx = cast<CallExpr>(E);
4818 unsigned NumArgs = CEx->getNumArgs();
4820 Expr *LastA = CEx->getArg(NumArgs - 1);
4821 Expr *InnerE = LastA->IgnoreParenImpCasts();
4822 const Type *InnerType =
4823 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4824 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4825 // Warn on this floating-point to bool conversion
4826 DiagnoseImpCast(S, E, T, CC,
4827 diag::warn_impcast_floating_point_to_bool);
4834 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4835 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
4836 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
4837 && Target->isScalarType()) {
4838 SourceLocation Loc = E->getSourceRange().getBegin();
4839 if (Loc.isMacroID())
4840 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
4841 if (!Loc.isMacroID() || CC.isMacroID())
4842 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4843 << T << clang::SourceRange(CC)
4844 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
4847 if (!Source->isIntegerType() || !Target->isIntegerType())
4850 // TODO: remove this early return once the false positives for constant->bool
4851 // in templates, macros, etc, are reduced or removed.
4852 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4855 IntRange SourceRange = GetExprRange(S.Context, E);
4856 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
4858 if (SourceRange.Width > TargetRange.Width) {
4859 // If the source is a constant, use a default-on diagnostic.
4860 // TODO: this should happen for bitfield stores, too.
4861 llvm::APSInt Value(32);
4862 if (E->isIntegerConstantExpr(Value, S.Context)) {
4863 if (S.SourceMgr.isInSystemMacro(CC))
4866 std::string PrettySourceValue = Value.toString(10);
4867 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4869 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4870 S.PDiag(diag::warn_impcast_integer_precision_constant)
4871 << PrettySourceValue << PrettyTargetValue
4872 << E->getType() << T << E->getSourceRange()
4873 << clang::SourceRange(CC));
4877 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
4878 if (S.SourceMgr.isInSystemMacro(CC))
4881 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
4882 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4883 /* pruneControlFlow */ true);
4884 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
4887 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4888 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4889 SourceRange.Width == TargetRange.Width)) {
4891 if (S.SourceMgr.isInSystemMacro(CC))
4894 unsigned DiagID = diag::warn_impcast_integer_sign;
4896 // Traditionally, gcc has warned about this under -Wsign-compare.
4897 // We also want to warn about it in -Wconversion.
4898 // So if -Wconversion is off, use a completely identical diagnostic
4899 // in the sign-compare group.
4900 // The conditional-checking code will
4902 DiagID = diag::warn_impcast_integer_sign_conditional;
4906 return DiagnoseImpCast(S, E, T, CC, DiagID);
4909 // Diagnose conversions between different enumeration types.
4910 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4911 // type, to give us better diagnostics.
4912 QualType SourceType = E->getType();
4913 if (!S.getLangOpts().CPlusPlus) {
4914 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4915 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4916 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4917 SourceType = S.Context.getTypeDeclType(Enum);
4918 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4922 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4923 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4924 if ((SourceEnum->getDecl()->getIdentifier() ||
4925 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
4926 (TargetEnum->getDecl()->getIdentifier() ||
4927 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
4928 SourceEnum != TargetEnum) {
4929 if (S.SourceMgr.isInSystemMacro(CC))
4932 return DiagnoseImpCast(S, E, SourceType, T, CC,
4933 diag::warn_impcast_different_enum_types);
4939 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4940 SourceLocation CC, QualType T);
4942 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
4943 SourceLocation CC, bool &ICContext) {
4944 E = E->IgnoreParenImpCasts();
4946 if (isa<ConditionalOperator>(E))
4947 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
4949 AnalyzeImplicitConversions(S, E, CC);
4950 if (E->getType() != T)
4951 return CheckImplicitConversion(S, E, T, CC, &ICContext);
4955 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4956 SourceLocation CC, QualType T) {
4957 AnalyzeImplicitConversions(S, E->getCond(), CC);
4959 bool Suspicious = false;
4960 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4961 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
4963 // If -Wconversion would have warned about either of the candidates
4964 // for a signedness conversion to the context type...
4965 if (!Suspicious) return;
4967 // ...but it's currently ignored...
4968 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4972 // ...then check whether it would have warned about either of the
4973 // candidates for a signedness conversion to the condition type.
4974 if (E->getType() == T) return;
4977 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4978 E->getType(), CC, &Suspicious);
4980 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
4981 E->getType(), CC, &Suspicious);
4984 /// AnalyzeImplicitConversions - Find and report any interesting
4985 /// implicit conversions in the given expression. There are a couple
4986 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
4987 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
4988 QualType T = OrigE->getType();
4989 Expr *E = OrigE->IgnoreParenImpCasts();
4991 if (E->isTypeDependent() || E->isValueDependent())
4994 // For conditional operators, we analyze the arguments as if they
4995 // were being fed directly into the output.
4996 if (isa<ConditionalOperator>(E)) {
4997 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4998 CheckConditionalOperator(S, CO, CC, T);
5002 // Check implicit argument conversions for function calls.
5003 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5004 CheckImplicitArgumentConversions(S, Call, CC);
5006 // Go ahead and check any implicit conversions we might have skipped.
5007 // The non-canonical typecheck is just an optimization;
5008 // CheckImplicitConversion will filter out dead implicit conversions.
5009 if (E->getType() != T)
5010 CheckImplicitConversion(S, E, T, CC);
5012 // Now continue drilling into this expression.
5014 // Skip past explicit casts.
5015 if (isa<ExplicitCastExpr>(E)) {
5016 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
5017 return AnalyzeImplicitConversions(S, E, CC);
5020 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5021 // Do a somewhat different check with comparison operators.
5022 if (BO->isComparisonOp())
5023 return AnalyzeComparison(S, BO);
5025 // And with simple assignments.
5026 if (BO->getOpcode() == BO_Assign)
5027 return AnalyzeAssignment(S, BO);
5030 // These break the otherwise-useful invariant below. Fortunately,
5031 // we don't really need to recurse into them, because any internal
5032 // expressions should have been analyzed already when they were
5033 // built into statements.
5034 if (isa<StmtExpr>(E)) return;
5036 // Don't descend into unevaluated contexts.
5037 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
5039 // Now just recurse over the expression's children.
5040 CC = E->getExprLoc();
5041 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5042 bool IsLogicalOperator = BO && BO->isLogicalOp();
5043 for (Stmt::child_range I = E->children(); I; ++I) {
5044 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
5048 if (IsLogicalOperator &&
5049 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5050 // Ignore checking string literals that are in logical operators.
5052 AnalyzeImplicitConversions(S, ChildExpr, CC);
5056 } // end anonymous namespace
5058 /// Diagnoses "dangerous" implicit conversions within the given
5059 /// expression (which is a full expression). Implements -Wconversion
5060 /// and -Wsign-compare.
5062 /// \param CC the "context" location of the implicit conversion, i.e.
5063 /// the most location of the syntactic entity requiring the implicit
5065 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
5066 // Don't diagnose in unevaluated contexts.
5067 if (isUnevaluatedContext())
5070 // Don't diagnose for value- or type-dependent expressions.
5071 if (E->isTypeDependent() || E->isValueDependent())
5074 // Check for array bounds violations in cases where the check isn't triggered
5075 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5076 // ArraySubscriptExpr is on the RHS of a variable initialization.
5077 CheckArrayAccess(E);
5079 // This is not the right CC for (e.g.) a variable initialization.
5080 AnalyzeImplicitConversions(*this, E, CC);
5083 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5084 FieldDecl *BitField,
5086 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5089 /// CheckParmsForFunctionDef - Check that the parameters of the given
5090 /// function are appropriate for the definition of a function. This
5091 /// takes care of any checks that cannot be performed on the
5092 /// declaration itself, e.g., that the types of each of the function
5093 /// parameters are complete.
5094 bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5095 bool CheckParameterNames) {
5096 bool HasInvalidParm = false;
5097 for (; P != PEnd; ++P) {
5098 ParmVarDecl *Param = *P;
5100 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5101 // function declarator that is part of a function definition of
5102 // that function shall not have incomplete type.
5104 // This is also C++ [dcl.fct]p6.
5105 if (!Param->isInvalidDecl() &&
5106 RequireCompleteType(Param->getLocation(), Param->getType(),
5107 diag::err_typecheck_decl_incomplete_type)) {
5108 Param->setInvalidDecl();
5109 HasInvalidParm = true;
5112 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5113 // declaration of each parameter shall include an identifier.
5114 if (CheckParameterNames &&
5115 Param->getIdentifier() == 0 &&
5116 !Param->isImplicit() &&
5117 !getLangOpts().CPlusPlus)
5118 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
5121 // If the function declarator is not part of a definition of that
5122 // function, parameters may have incomplete type and may use the [*]
5123 // notation in their sequences of declarator specifiers to specify
5124 // variable length array types.
5125 QualType PType = Param->getOriginalType();
5126 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
5127 if (AT->getSizeModifier() == ArrayType::Star) {
5128 // FIXME: This diagnosic should point the '[*]' if source-location
5129 // information is added for it.
5130 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
5135 return HasInvalidParm;
5138 /// CheckCastAlign - Implements -Wcast-align, which warns when a
5139 /// pointer cast increases the alignment requirements.
5140 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5141 // This is actually a lot of work to potentially be doing on every
5142 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
5143 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5145 == DiagnosticsEngine::Ignored)
5148 // Ignore dependent types.
5149 if (T->isDependentType() || Op->getType()->isDependentType())
5152 // Require that the destination be a pointer type.
5153 const PointerType *DestPtr = T->getAs<PointerType>();
5154 if (!DestPtr) return;
5156 // If the destination has alignment 1, we're done.
5157 QualType DestPointee = DestPtr->getPointeeType();
5158 if (DestPointee->isIncompleteType()) return;
5159 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5160 if (DestAlign.isOne()) return;
5162 // Require that the source be a pointer type.
5163 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5164 if (!SrcPtr) return;
5165 QualType SrcPointee = SrcPtr->getPointeeType();
5167 // Whitelist casts from cv void*. We already implicitly
5168 // whitelisted casts to cv void*, since they have alignment 1.
5169 // Also whitelist casts involving incomplete types, which implicitly
5171 if (SrcPointee->isIncompleteType()) return;
5173 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5174 if (SrcAlign >= DestAlign) return;
5176 Diag(TRange.getBegin(), diag::warn_cast_align)
5177 << Op->getType() << T
5178 << static_cast<unsigned>(SrcAlign.getQuantity())
5179 << static_cast<unsigned>(DestAlign.getQuantity())
5180 << TRange << Op->getSourceRange();
5183 static const Type* getElementType(const Expr *BaseExpr) {
5184 const Type* EltType = BaseExpr->getType().getTypePtr();
5185 if (EltType->isAnyPointerType())
5186 return EltType->getPointeeType().getTypePtr();
5187 else if (EltType->isArrayType())
5188 return EltType->getBaseElementTypeUnsafe();
5192 /// \brief Check whether this array fits the idiom of a size-one tail padded
5193 /// array member of a struct.
5195 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
5196 /// commonly used to emulate flexible arrays in C89 code.
5197 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5198 const NamedDecl *ND) {
5199 if (Size != 1 || !ND) return false;
5201 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5202 if (!FD) return false;
5204 // Don't consider sizes resulting from macro expansions or template argument
5205 // substitution to form C89 tail-padded arrays.
5207 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
5209 TypeLoc TL = TInfo->getTypeLoc();
5210 // Look through typedefs.
5211 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
5213 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
5214 TInfo = TDL->getTypeSourceInfo();
5217 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
5218 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
5219 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5224 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
5225 if (!RD) return false;
5226 if (RD->isUnion()) return false;
5227 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5228 if (!CRD->isStandardLayout()) return false;
5231 // See if this is the last field decl in the record.
5233 while ((D = D->getNextDeclInContext()))
5234 if (isa<FieldDecl>(D))
5239 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
5240 const ArraySubscriptExpr *ASE,
5241 bool AllowOnePastEnd, bool IndexNegated) {
5242 IndexExpr = IndexExpr->IgnoreParenImpCasts();
5243 if (IndexExpr->isValueDependent())
5246 const Type *EffectiveType = getElementType(BaseExpr);
5247 BaseExpr = BaseExpr->IgnoreParenCasts();
5248 const ConstantArrayType *ArrayTy =
5249 Context.getAsConstantArrayType(BaseExpr->getType());
5254 if (!IndexExpr->EvaluateAsInt(index, Context))
5259 const NamedDecl *ND = NULL;
5260 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5261 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5262 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5263 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5265 if (index.isUnsigned() || !index.isNegative()) {
5266 llvm::APInt size = ArrayTy->getSize();
5267 if (!size.isStrictlyPositive())
5270 const Type* BaseType = getElementType(BaseExpr);
5271 if (BaseType != EffectiveType) {
5272 // Make sure we're comparing apples to apples when comparing index to size
5273 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5274 uint64_t array_typesize = Context.getTypeSize(BaseType);
5275 // Handle ptrarith_typesize being zero, such as when casting to void*
5276 if (!ptrarith_typesize) ptrarith_typesize = 1;
5277 if (ptrarith_typesize != array_typesize) {
5278 // There's a cast to a different size type involved
5279 uint64_t ratio = array_typesize / ptrarith_typesize;
5280 // TODO: Be smarter about handling cases where array_typesize is not a
5281 // multiple of ptrarith_typesize
5282 if (ptrarith_typesize * ratio == array_typesize)
5283 size *= llvm::APInt(size.getBitWidth(), ratio);
5287 if (size.getBitWidth() > index.getBitWidth())
5288 index = index.zext(size.getBitWidth());
5289 else if (size.getBitWidth() < index.getBitWidth())
5290 size = size.zext(index.getBitWidth());
5292 // For array subscripting the index must be less than size, but for pointer
5293 // arithmetic also allow the index (offset) to be equal to size since
5294 // computing the next address after the end of the array is legal and
5295 // commonly done e.g. in C++ iterators and range-based for loops.
5296 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
5299 // Also don't warn for arrays of size 1 which are members of some
5300 // structure. These are often used to approximate flexible arrays in C89
5302 if (IsTailPaddedMemberArray(*this, size, ND))
5305 // Suppress the warning if the subscript expression (as identified by the
5306 // ']' location) and the index expression are both from macro expansions
5307 // within a system header.
5309 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5310 ASE->getRBracketLoc());
5311 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5312 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5313 IndexExpr->getLocStart());
5314 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5319 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
5321 DiagID = diag::warn_array_index_exceeds_bounds;
5323 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5324 PDiag(DiagID) << index.toString(10, true)
5325 << size.toString(10, true)
5326 << (unsigned)size.getLimitedValue(~0U)
5327 << IndexExpr->getSourceRange());
5329 unsigned DiagID = diag::warn_array_index_precedes_bounds;
5331 DiagID = diag::warn_ptr_arith_precedes_bounds;
5332 if (index.isNegative()) index = -index;
5335 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5336 PDiag(DiagID) << index.toString(10, true)
5337 << IndexExpr->getSourceRange());
5341 // Try harder to find a NamedDecl to point at in the note.
5342 while (const ArraySubscriptExpr *ASE =
5343 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5344 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5345 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5346 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5347 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5348 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5352 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5353 PDiag(diag::note_array_index_out_of_bounds)
5354 << ND->getDeclName());
5357 void Sema::CheckArrayAccess(const Expr *expr) {
5358 int AllowOnePastEnd = 0;
5360 expr = expr->IgnoreParenImpCasts();
5361 switch (expr->getStmtClass()) {
5362 case Stmt::ArraySubscriptExprClass: {
5363 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
5364 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
5365 AllowOnePastEnd > 0);
5368 case Stmt::UnaryOperatorClass: {
5369 // Only unwrap the * and & unary operators
5370 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5371 expr = UO->getSubExpr();
5372 switch (UO->getOpcode()) {
5384 case Stmt::ConditionalOperatorClass: {
5385 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5386 if (const Expr *lhs = cond->getLHS())
5387 CheckArrayAccess(lhs);
5388 if (const Expr *rhs = cond->getRHS())
5389 CheckArrayAccess(rhs);
5398 //===--- CHECK: Objective-C retain cycles ----------------------------------//
5401 struct RetainCycleOwner {
5402 RetainCycleOwner() : Variable(0), Indirect(false) {}
5408 void setLocsFrom(Expr *e) {
5409 Loc = e->getExprLoc();
5410 Range = e->getSourceRange();
5415 /// Consider whether capturing the given variable can possibly lead to
5417 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
5418 // In ARC, it's captured strongly iff the variable has __strong
5419 // lifetime. In MRR, it's captured strongly if the variable is
5420 // __block and has an appropriate type.
5421 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5424 owner.Variable = var;
5426 owner.setLocsFrom(ref);
5430 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
5432 e = e->IgnoreParens();
5433 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5434 switch (cast->getCastKind()) {
5436 case CK_LValueBitCast:
5437 case CK_LValueToRValue:
5438 case CK_ARCReclaimReturnedObject:
5439 e = cast->getSubExpr();
5447 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5448 ObjCIvarDecl *ivar = ref->getDecl();
5449 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5452 // Try to find a retain cycle in the base.
5453 if (!findRetainCycleOwner(S, ref->getBase(), owner))
5456 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5457 owner.Indirect = true;
5461 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5462 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5463 if (!var) return false;
5464 return considerVariable(var, ref, owner);
5467 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5468 if (member->isArrow()) return false;
5470 // Don't count this as an indirect ownership.
5471 e = member->getBase();
5475 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5476 // Only pay attention to pseudo-objects on property references.
5477 ObjCPropertyRefExpr *pre
5478 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5480 if (!pre) return false;
5481 if (pre->isImplicitProperty()) return false;
5482 ObjCPropertyDecl *property = pre->getExplicitProperty();
5483 if (!property->isRetaining() &&
5484 !(property->getPropertyIvarDecl() &&
5485 property->getPropertyIvarDecl()->getType()
5486 .getObjCLifetime() == Qualifiers::OCL_Strong))
5489 owner.Indirect = true;
5490 if (pre->isSuperReceiver()) {
5491 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5492 if (!owner.Variable)
5494 owner.Loc = pre->getLocation();
5495 owner.Range = pre->getSourceRange();
5498 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5510 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5511 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5512 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5513 Variable(variable), Capturer(0) {}
5518 void VisitDeclRefExpr(DeclRefExpr *ref) {
5519 if (ref->getDecl() == Variable && !Capturer)
5523 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5524 if (Capturer) return;
5525 Visit(ref->getBase());
5526 if (Capturer && ref->isFreeIvar())
5530 void VisitBlockExpr(BlockExpr *block) {
5531 // Look inside nested blocks
5532 if (block->getBlockDecl()->capturesVariable(Variable))
5533 Visit(block->getBlockDecl()->getBody());
5536 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
5537 if (Capturer) return;
5538 if (OVE->getSourceExpr())
5539 Visit(OVE->getSourceExpr());
5544 /// Check whether the given argument is a block which captures a
5546 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5547 assert(owner.Variable && owner.Loc.isValid());
5549 e = e->IgnoreParenCasts();
5551 // Look through [^{...} copy] and Block_copy(^{...}).
5552 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
5553 Selector Cmd = ME->getSelector();
5554 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
5555 e = ME->getInstanceReceiver();
5558 e = e->IgnoreParenCasts();
5560 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
5561 if (CE->getNumArgs() == 1) {
5562 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
5564 const IdentifierInfo *FnI = Fn->getIdentifier();
5565 if (FnI && FnI->isStr("_Block_copy")) {
5566 e = CE->getArg(0)->IgnoreParenCasts();
5572 BlockExpr *block = dyn_cast<BlockExpr>(e);
5573 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5576 FindCaptureVisitor visitor(S.Context, owner.Variable);
5577 visitor.Visit(block->getBlockDecl()->getBody());
5578 return visitor.Capturer;
5581 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5582 RetainCycleOwner &owner) {
5584 assert(owner.Variable && owner.Loc.isValid());
5586 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5587 << owner.Variable << capturer->getSourceRange();
5588 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5589 << owner.Indirect << owner.Range;
5592 /// Check for a keyword selector that starts with the word 'add' or
5594 static bool isSetterLikeSelector(Selector sel) {
5595 if (sel.isUnarySelector()) return false;
5597 StringRef str = sel.getNameForSlot(0);
5598 while (!str.empty() && str.front() == '_') str = str.substr(1);
5599 if (str.startswith("set"))
5600 str = str.substr(3);
5601 else if (str.startswith("add")) {
5602 // Specially whitelist 'addOperationWithBlock:'.
5603 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5605 str = str.substr(3);
5610 if (str.empty()) return true;
5611 return !islower(str.front());
5614 /// Check a message send to see if it's likely to cause a retain cycle.
5615 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5616 // Only check instance methods whose selector looks like a setter.
5617 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5620 // Try to find a variable that the receiver is strongly owned by.
5621 RetainCycleOwner owner;
5622 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
5623 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
5626 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5627 owner.Variable = getCurMethodDecl()->getSelfDecl();
5628 owner.Loc = msg->getSuperLoc();
5629 owner.Range = msg->getSuperLoc();
5632 // Check whether the receiver is captured by any of the arguments.
5633 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5634 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5635 return diagnoseRetainCycle(*this, capturer, owner);
5638 /// Check a property assign to see if it's likely to cause a retain cycle.
5639 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5640 RetainCycleOwner owner;
5641 if (!findRetainCycleOwner(*this, receiver, owner))
5644 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5645 diagnoseRetainCycle(*this, capturer, owner);
5648 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
5649 RetainCycleOwner Owner;
5650 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
5653 // Because we don't have an expression for the variable, we have to set the
5654 // location explicitly here.
5655 Owner.Loc = Var->getLocation();
5656 Owner.Range = Var->getSourceRange();
5658 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
5659 diagnoseRetainCycle(*this, Capturer, Owner);
5662 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
5663 QualType LHS, Expr *RHS) {
5664 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5665 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
5667 // strip off any implicit cast added to get to the one arc-specific
5668 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5669 if (cast->getCastKind() == CK_ARCConsumeObject) {
5670 Diag(Loc, diag::warn_arc_retained_assign)
5671 << (LT == Qualifiers::OCL_ExplicitNone) << 1
5672 << RHS->getSourceRange();
5675 RHS = cast->getSubExpr();
5680 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5681 Expr *LHS, Expr *RHS) {
5683 // PropertyRef on LHS type need be directly obtained from
5684 // its declaration as it has a PsuedoType.
5685 ObjCPropertyRefExpr *PRE
5686 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5687 if (PRE && !PRE->isImplicitProperty()) {
5688 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5690 LHSType = PD->getType();
5693 if (LHSType.isNull())
5694 LHSType = LHS->getType();
5696 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5698 if (LT == Qualifiers::OCL_Weak) {
5699 DiagnosticsEngine::Level Level =
5700 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
5701 if (Level != DiagnosticsEngine::Ignored)
5702 getCurFunction()->markSafeWeakUse(LHS);
5705 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5708 // FIXME. Check for other life times.
5709 if (LT != Qualifiers::OCL_None)
5713 if (PRE->isImplicitProperty())
5715 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5719 unsigned Attributes = PD->getPropertyAttributes();
5720 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5721 // when 'assign' attribute was not explicitly specified
5722 // by user, ignore it and rely on property type itself
5723 // for lifetime info.
5724 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5725 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5726 LHSType->isObjCRetainableType())
5729 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5730 if (cast->getCastKind() == CK_ARCConsumeObject) {
5731 Diag(Loc, diag::warn_arc_retained_property_assign)
5732 << RHS->getSourceRange();
5735 RHS = cast->getSubExpr();
5738 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
5739 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5740 if (cast->getCastKind() == CK_ARCConsumeObject) {
5741 Diag(Loc, diag::warn_arc_retained_assign)
5742 << 0 << 0<< RHS->getSourceRange();
5745 RHS = cast->getSubExpr();
5751 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5754 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5755 SourceLocation StmtLoc,
5756 const NullStmt *Body) {
5757 // Do not warn if the body is a macro that expands to nothing, e.g:
5763 if (Body->hasLeadingEmptyMacro())
5766 // Get line numbers of statement and body.
5767 bool StmtLineInvalid;
5768 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5770 if (StmtLineInvalid)
5773 bool BodyLineInvalid;
5774 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5776 if (BodyLineInvalid)
5779 // Warn if null statement and body are on the same line.
5780 if (StmtLine != BodyLine)
5785 } // Unnamed namespace
5787 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5790 // Since this is a syntactic check, don't emit diagnostic for template
5791 // instantiations, this just adds noise.
5792 if (CurrentInstantiationScope)
5795 // The body should be a null statement.
5796 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5800 // Do the usual checks.
5801 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5804 Diag(NBody->getSemiLoc(), DiagID);
5805 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5808 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5809 const Stmt *PossibleBody) {
5810 assert(!CurrentInstantiationScope); // Ensured by caller
5812 SourceLocation StmtLoc;
5815 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5816 StmtLoc = FS->getRParenLoc();
5817 Body = FS->getBody();
5818 DiagID = diag::warn_empty_for_body;
5819 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5820 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5821 Body = WS->getBody();
5822 DiagID = diag::warn_empty_while_body;
5824 return; // Neither `for' nor `while'.
5826 // The body should be a null statement.
5827 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5831 // Skip expensive checks if diagnostic is disabled.
5832 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5833 DiagnosticsEngine::Ignored)
5836 // Do the usual checks.
5837 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5840 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5841 // noise level low, emit diagnostics only if for/while is followed by a
5842 // CompoundStmt, e.g.:
5843 // for (int i = 0; i < n; i++);
5847 // or if for/while is followed by a statement with more indentation
5848 // than for/while itself:
5849 // for (int i = 0; i < n; i++);
5851 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5852 if (!ProbableTypo) {
5853 bool BodyColInvalid;
5854 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5855 PossibleBody->getLocStart(),
5860 bool StmtColInvalid;
5861 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5867 if (BodyCol > StmtCol)
5868 ProbableTypo = true;
5872 Diag(NBody->getSemiLoc(), DiagID);
5873 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5877 //===--- Layout compatibility ----------------------------------------------//
5881 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
5883 /// \brief Check if two enumeration types are layout-compatible.
5884 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
5885 // C++11 [dcl.enum] p8:
5886 // Two enumeration types are layout-compatible if they have the same
5888 return ED1->isComplete() && ED2->isComplete() &&
5889 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
5892 /// \brief Check if two fields are layout-compatible.
5893 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
5894 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
5897 if (Field1->isBitField() != Field2->isBitField())
5900 if (Field1->isBitField()) {
5901 // Make sure that the bit-fields are the same length.
5902 unsigned Bits1 = Field1->getBitWidthValue(C);
5903 unsigned Bits2 = Field2->getBitWidthValue(C);
5912 /// \brief Check if two standard-layout structs are layout-compatible.
5913 /// (C++11 [class.mem] p17)
5914 bool isLayoutCompatibleStruct(ASTContext &C,
5917 // If both records are C++ classes, check that base classes match.
5918 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
5919 // If one of records is a CXXRecordDecl we are in C++ mode,
5920 // thus the other one is a CXXRecordDecl, too.
5921 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
5922 // Check number of base classes.
5923 if (D1CXX->getNumBases() != D2CXX->getNumBases())
5926 // Check the base classes.
5927 for (CXXRecordDecl::base_class_const_iterator
5928 Base1 = D1CXX->bases_begin(),
5929 BaseEnd1 = D1CXX->bases_end(),
5930 Base2 = D2CXX->bases_begin();
5933 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
5936 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
5937 // If only RD2 is a C++ class, it should have zero base classes.
5938 if (D2CXX->getNumBases() > 0)
5942 // Check the fields.
5943 RecordDecl::field_iterator Field2 = RD2->field_begin(),
5944 Field2End = RD2->field_end(),
5945 Field1 = RD1->field_begin(),
5946 Field1End = RD1->field_end();
5947 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
5948 if (!isLayoutCompatible(C, *Field1, *Field2))
5951 if (Field1 != Field1End || Field2 != Field2End)
5957 /// \brief Check if two standard-layout unions are layout-compatible.
5958 /// (C++11 [class.mem] p18)
5959 bool isLayoutCompatibleUnion(ASTContext &C,
5962 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
5963 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
5964 Field2End = RD2->field_end();
5965 Field2 != Field2End; ++Field2) {
5966 UnmatchedFields.insert(*Field2);
5969 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
5970 Field1End = RD1->field_end();
5971 Field1 != Field1End; ++Field1) {
5972 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
5973 I = UnmatchedFields.begin(),
5974 E = UnmatchedFields.end();
5976 for ( ; I != E; ++I) {
5977 if (isLayoutCompatible(C, *Field1, *I)) {
5978 bool Result = UnmatchedFields.erase(*I);
5988 return UnmatchedFields.empty();
5991 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
5992 if (RD1->isUnion() != RD2->isUnion())
5996 return isLayoutCompatibleUnion(C, RD1, RD2);
5998 return isLayoutCompatibleStruct(C, RD1, RD2);
6001 /// \brief Check if two types are layout-compatible in C++11 sense.
6002 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6003 if (T1.isNull() || T2.isNull())
6006 // C++11 [basic.types] p11:
6007 // If two types T1 and T2 are the same type, then T1 and T2 are
6008 // layout-compatible types.
6009 if (C.hasSameType(T1, T2))
6012 T1 = T1.getCanonicalType().getUnqualifiedType();
6013 T2 = T2.getCanonicalType().getUnqualifiedType();
6015 const Type::TypeClass TC1 = T1->getTypeClass();
6016 const Type::TypeClass TC2 = T2->getTypeClass();
6021 if (TC1 == Type::Enum) {
6022 return isLayoutCompatible(C,
6023 cast<EnumType>(T1)->getDecl(),
6024 cast<EnumType>(T2)->getDecl());
6025 } else if (TC1 == Type::Record) {
6026 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6029 return isLayoutCompatible(C,
6030 cast<RecordType>(T1)->getDecl(),
6031 cast<RecordType>(T2)->getDecl());
6038 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6041 /// \brief Given a type tag expression find the type tag itself.
6043 /// \param TypeExpr Type tag expression, as it appears in user's code.
6045 /// \param VD Declaration of an identifier that appears in a type tag.
6047 /// \param MagicValue Type tag magic value.
6048 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6049 const ValueDecl **VD, uint64_t *MagicValue) {
6054 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6056 switch (TypeExpr->getStmtClass()) {
6057 case Stmt::UnaryOperatorClass: {
6058 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6059 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6060 TypeExpr = UO->getSubExpr();
6066 case Stmt::DeclRefExprClass: {
6067 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6068 *VD = DRE->getDecl();
6072 case Stmt::IntegerLiteralClass: {
6073 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6074 llvm::APInt MagicValueAPInt = IL->getValue();
6075 if (MagicValueAPInt.getActiveBits() <= 64) {
6076 *MagicValue = MagicValueAPInt.getZExtValue();
6082 case Stmt::BinaryConditionalOperatorClass:
6083 case Stmt::ConditionalOperatorClass: {
6084 const AbstractConditionalOperator *ACO =
6085 cast<AbstractConditionalOperator>(TypeExpr);
6087 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6089 TypeExpr = ACO->getTrueExpr();
6091 TypeExpr = ACO->getFalseExpr();
6097 case Stmt::BinaryOperatorClass: {
6098 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6099 if (BO->getOpcode() == BO_Comma) {
6100 TypeExpr = BO->getRHS();
6112 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
6114 /// \param TypeExpr Expression that specifies a type tag.
6116 /// \param MagicValues Registered magic values.
6118 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6121 /// \param TypeInfo Information about the corresponding C type.
6123 /// \returns true if the corresponding C type was found.
6124 bool GetMatchingCType(
6125 const IdentifierInfo *ArgumentKind,
6126 const Expr *TypeExpr, const ASTContext &Ctx,
6127 const llvm::DenseMap<Sema::TypeTagMagicValue,
6128 Sema::TypeTagData> *MagicValues,
6129 bool &FoundWrongKind,
6130 Sema::TypeTagData &TypeInfo) {
6131 FoundWrongKind = false;
6133 // Variable declaration that has type_tag_for_datatype attribute.
6134 const ValueDecl *VD = NULL;
6136 uint64_t MagicValue;
6138 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6142 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6143 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6144 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6146 if (I->getArgumentKind() != ArgumentKind) {
6147 FoundWrongKind = true;
6150 TypeInfo.Type = I->getMatchingCType();
6151 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6152 TypeInfo.MustBeNull = I->getMustBeNull();
6161 llvm::DenseMap<Sema::TypeTagMagicValue,
6162 Sema::TypeTagData>::const_iterator I =
6163 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6164 if (I == MagicValues->end())
6167 TypeInfo = I->second;
6170 } // unnamed namespace
6172 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6173 uint64_t MagicValue, QualType Type,
6174 bool LayoutCompatible,
6176 if (!TypeTagForDatatypeMagicValues)
6177 TypeTagForDatatypeMagicValues.reset(
6178 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6180 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6181 (*TypeTagForDatatypeMagicValues)[Magic] =
6182 TypeTagData(Type, LayoutCompatible, MustBeNull);
6186 bool IsSameCharType(QualType T1, QualType T2) {
6187 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6191 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6195 BuiltinType::Kind T1Kind = BT1->getKind();
6196 BuiltinType::Kind T2Kind = BT2->getKind();
6198 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6199 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6200 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6201 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6203 } // unnamed namespace
6205 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6206 const Expr * const *ExprArgs) {
6207 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6208 bool IsPointerAttr = Attr->getIsPointer();
6210 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6211 bool FoundWrongKind;
6212 TypeTagData TypeInfo;
6213 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6214 TypeTagForDatatypeMagicValues.get(),
6215 FoundWrongKind, TypeInfo)) {
6217 Diag(TypeTagExpr->getExprLoc(),
6218 diag::warn_type_tag_for_datatype_wrong_kind)
6219 << TypeTagExpr->getSourceRange();
6223 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6224 if (IsPointerAttr) {
6225 // Skip implicit cast of pointer to `void *' (as a function argument).
6226 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
6227 if (ICE->getType()->isVoidPointerType() &&
6228 ICE->getCastKind() == CK_BitCast)
6229 ArgumentExpr = ICE->getSubExpr();
6231 QualType ArgumentType = ArgumentExpr->getType();
6233 // Passing a `void*' pointer shouldn't trigger a warning.
6234 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6237 if (TypeInfo.MustBeNull) {
6238 // Type tag with matching void type requires a null pointer.
6239 if (!ArgumentExpr->isNullPointerConstant(Context,
6240 Expr::NPC_ValueDependentIsNotNull)) {
6241 Diag(ArgumentExpr->getExprLoc(),
6242 diag::warn_type_safety_null_pointer_required)
6243 << ArgumentKind->getName()
6244 << ArgumentExpr->getSourceRange()
6245 << TypeTagExpr->getSourceRange();
6250 QualType RequiredType = TypeInfo.Type;
6252 RequiredType = Context.getPointerType(RequiredType);
6254 bool mismatch = false;
6255 if (!TypeInfo.LayoutCompatible) {
6256 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6258 // C++11 [basic.fundamental] p1:
6259 // Plain char, signed char, and unsigned char are three distinct types.
6261 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6262 // char' depending on the current char signedness mode.
6264 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6265 RequiredType->getPointeeType())) ||
6266 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6270 mismatch = !isLayoutCompatible(Context,
6271 ArgumentType->getPointeeType(),
6272 RequiredType->getPointeeType());
6274 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6277 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6278 << ArgumentType << ArgumentKind->getName()
6279 << TypeInfo.LayoutCompatible << RequiredType
6280 << ArgumentExpr->getSourceRange()
6281 << TypeTagExpr->getSourceRange();