blob: 76407ef7a7093a3ba0dde74c4c8c671fbddd18a9 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
Ted Kremeneke0e53132010-01-28 23:39:18 +000016#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000017#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000018#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000020#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000021#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000022#include "clang/AST/DeclObjC.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000025#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000026#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000027#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/STLExtras.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000031#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000032using namespace clang;
33
Chris Lattner60800082009-02-18 17:49:48 +000034/// getLocationOfStringLiteralByte - Return a source location that points to the
35/// specified byte of the specified string literal.
36///
37/// Strings are amazingly complex. They can be formed from multiple tokens and
38/// can have escape sequences in them in addition to the usual trigraph and
39/// escaped newline business. This routine handles this complexity.
40///
41SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
42 unsigned ByteNo) const {
43 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045 // Loop over all of the tokens in this string until we find the one that
46 // contains the byte we're looking for.
47 unsigned TokNo = 0;
48 while (1) {
49 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
50 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000051
Chris Lattner60800082009-02-18 17:49:48 +000052 // Get the spelling of the string so that we can get the data that makes up
53 // the string literal, not the identifier for the macro it is potentially
54 // expanded through.
55 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
56
57 // Re-lex the token to get its length and original spelling.
58 std::pair<FileID, unsigned> LocInfo =
59 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
Douglas Gregorf715ca12010-03-16 00:06:06 +000060 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000061 llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +000062 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +000063 return StrTokSpellingLoc;
64
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000065 const char *StrData = Buffer.data()+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner60800082009-02-18 17:49:48 +000067 // Create a langops struct and enable trigraphs. This is sufficient for
68 // relexing tokens.
69 LangOptions LangOpts;
70 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner60800082009-02-18 17:49:48 +000072 // Create a lexer starting at the beginning of this token.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000073 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData,
74 Buffer.end());
Chris Lattner60800082009-02-18 17:49:48 +000075 Token TheTok;
76 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Chris Lattner443e53c2009-02-18 19:26:42 +000078 // Use the StringLiteralParser to compute the length of the string in bytes.
Douglas Gregorb90f4b32010-05-26 05:35:51 +000079 StringLiteralParser SLP(&TheTok, 1, PP, /*Complain=*/false);
Chris Lattner443e53c2009-02-18 19:26:42 +000080 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000081
Chris Lattner2197c962009-02-18 18:52:52 +000082 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000083 if (ByteNo < TokNumBytes ||
84 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000085 unsigned Offset =
Douglas Gregorb90f4b32010-05-26 05:35:51 +000086 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP,
87 /*Complain=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattner719e6152009-02-18 19:21:10 +000089 // Now that we know the offset of the token in the spelling, use the
90 // preprocessor to get the offset in the original source.
91 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000092 }
Mike Stump1eb44332009-09-09 15:08:12 +000093
Chris Lattner60800082009-02-18 17:49:48 +000094 // Move to the next string token.
95 ++TokNo;
96 ByteNo -= TokNumBytes;
97 }
98}
99
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000100/// CheckablePrintfAttr - does a function call have a "printf" attribute
101/// and arguments that merit checking?
102bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
103 if (Format->getType() == "printf") return true;
104 if (Format->getType() == "printf0") {
105 // printf0 allows null "format" string; if so don't check format/args
106 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000107 // Does the index refer to the implicit object argument?
108 if (isa<CXXMemberCallExpr>(TheCall)) {
109 if (format_idx == 0)
110 return false;
111 --format_idx;
112 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000113 if (format_idx < TheCall->getNumArgs()) {
114 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +0000115 if (!Format->isNullPointerConstant(Context,
116 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000117 return true;
118 }
119 }
120 return false;
121}
Chris Lattner60800082009-02-18 17:49:48 +0000122
Sebastian Redl0eb23302009-01-19 00:08:26 +0000123Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000124Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000126
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000138 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000160 case Builtin::BI__builtin_return_address:
Eric Christopher691ebc32010-04-17 02:26:23 +0000161 case Builtin::BI__builtin_frame_address: {
162 llvm::APSInt Result;
163 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000166 }
167 case Builtin::BI__builtin_eh_return_data_regno: {
168 llvm::APSInt Result;
169 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Chris Lattner21fb98e2009-09-23 06:06:36 +0000170 return ExprError();
171 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000172 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000173 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 return SemaBuiltinShuffleVector(TheCall);
175 // TheCall will be freed by the smart pointer here, but that's fine, since
176 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000177 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000178 if (SemaBuiltinPrefetch(TheCall))
179 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000180 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000181 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000182 if (SemaBuiltinObjectSize(TheCall))
183 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000184 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000185 case Builtin::BI__builtin_longjmp:
186 if (SemaBuiltinLongjmp(TheCall))
187 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000188 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000189 case Builtin::BI__sync_fetch_and_add:
190 case Builtin::BI__sync_fetch_and_sub:
191 case Builtin::BI__sync_fetch_and_or:
192 case Builtin::BI__sync_fetch_and_and:
193 case Builtin::BI__sync_fetch_and_xor:
194 case Builtin::BI__sync_add_and_fetch:
195 case Builtin::BI__sync_sub_and_fetch:
196 case Builtin::BI__sync_and_and_fetch:
197 case Builtin::BI__sync_or_and_fetch:
198 case Builtin::BI__sync_xor_and_fetch:
199 case Builtin::BI__sync_val_compare_and_swap:
200 case Builtin::BI__sync_bool_compare_and_swap:
201 case Builtin::BI__sync_lock_test_and_set:
202 case Builtin::BI__sync_lock_release:
203 if (SemaBuiltinAtomicOverloaded(TheCall))
204 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000205 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000206 }
207
208 // Since the target specific builtins for each arch overlap, only check those
209 // of the arch we are compiling for.
210 if (BuiltinID >= Builtin::FirstTSBuiltin) {
211 switch (Context.Target.getTriple().getArch()) {
212 case llvm::Triple::arm:
213 case llvm::Triple::thumb:
214 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
215 return ExprError();
216 break;
217 case llvm::Triple::x86:
218 case llvm::Triple::x86_64:
219 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
220 return ExprError();
221 break;
222 default:
223 break;
224 }
225 }
226
227 return move(TheCallResult);
228}
229
230bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
231 switch (BuiltinID) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000232 case X86::BI__builtin_ia32_palignr128:
233 case X86::BI__builtin_ia32_palignr: {
234 llvm::APSInt Result;
235 if (SemaBuiltinConstantArg(TheCall, 2, Result))
Nate Begeman26a31422010-06-08 02:47:44 +0000236 return true;
Eric Christopher691ebc32010-04-17 02:26:23 +0000237 break;
238 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000239 }
Nate Begeman26a31422010-06-08 02:47:44 +0000240 return false;
241}
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Nate Begeman26a31422010-06-08 02:47:44 +0000243bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
244 // TODO: verify NEON intrinsic constant args.
245 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000246}
Daniel Dunbarde454282008-10-02 18:44:07 +0000247
Anders Carlssond406bf02009-08-16 01:56:34 +0000248/// CheckFunctionCall - Check a direct function call for various correctness
249/// and safety properties not strictly enforced by the C type system.
250bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
251 // Get the IdentifierInfo* for the called function.
252 IdentifierInfo *FnInfo = FDecl->getIdentifier();
253
254 // None of the checks below are needed for functions that don't have
255 // simple names (e.g., C++ conversion functions).
256 if (!FnInfo)
257 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Daniel Dunbarde454282008-10-02 18:44:07 +0000259 // FIXME: This mechanism should be abstracted to be less fragile and
260 // more efficient. For example, just map function ids to custom
261 // handlers.
262
Chris Lattner59907c42007-08-10 20:18:51 +0000263 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000264 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000265 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000266 bool HasVAListArg = Format->getFirstArg() == 0;
Douglas Gregor3c385e52009-02-14 18:57:46 +0000267 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000268 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000269 }
Chris Lattner59907c42007-08-10 20:18:51 +0000270 }
Mike Stump1eb44332009-09-09 15:08:12 +0000271
272 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000273 NonNull = NonNull->getNext<NonNullAttr>())
274 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000275
Anders Carlssond406bf02009-08-16 01:56:34 +0000276 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000277}
278
Anders Carlssond406bf02009-08-16 01:56:34 +0000279bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000280 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000281 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000282 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000283 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000285 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
286 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000287 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000289 QualType Ty = V->getType();
290 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000291 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Anders Carlssond406bf02009-08-16 01:56:34 +0000293 if (!CheckablePrintfAttr(Format, TheCall))
294 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Anders Carlssond406bf02009-08-16 01:56:34 +0000296 bool HasVAListArg = Format->getFirstArg() == 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000297 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
298 HasVAListArg ? 0 : Format->getFirstArg() - 1);
299
300 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000301}
302
Chris Lattner5caa3702009-05-08 06:58:22 +0000303/// SemaBuiltinAtomicOverloaded - We have a call to a function like
304/// __sync_fetch_and_add, which is an overloaded function based on the pointer
305/// type of its first argument. The main ActOnCallExpr routines have already
306/// promoted the types of arguments because all of these calls are prototyped as
307/// void(...).
308///
309/// This function goes through and does final semantic checking for these
310/// builtins,
311bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
312 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
313 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
314
315 // Ensure that we have at least one argument to do type inference from.
316 if (TheCall->getNumArgs() < 1)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000317 return Diag(TheCall->getLocEnd(),
318 diag::err_typecheck_call_too_few_args_at_least)
319 << 0 << 1 << TheCall->getNumArgs()
320 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner5caa3702009-05-08 06:58:22 +0000322 // Inspect the first argument of the atomic builtin. This should always be
323 // a pointer type, whose element is an integral scalar or pointer type.
324 // Because it is a pointer type, we don't have to worry about any implicit
325 // casts here.
326 Expr *FirstArg = TheCall->getArg(0);
327 if (!FirstArg->getType()->isPointerType())
328 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
329 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Ted Kremenek6217b802009-07-29 21:53:49 +0000331 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000332 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000333 !ValType->isBlockPointerType())
334 return Diag(DRE->getLocStart(),
335 diag::err_atomic_builtin_must_be_pointer_intptr)
336 << FirstArg->getType() << FirstArg->getSourceRange();
337
338 // We need to figure out which concrete builtin this maps onto. For example,
339 // __sync_fetch_and_add with a 2 byte object turns into
340 // __sync_fetch_and_add_2.
341#define BUILTIN_ROW(x) \
342 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
343 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Chris Lattner5caa3702009-05-08 06:58:22 +0000345 static const unsigned BuiltinIndices[][5] = {
346 BUILTIN_ROW(__sync_fetch_and_add),
347 BUILTIN_ROW(__sync_fetch_and_sub),
348 BUILTIN_ROW(__sync_fetch_and_or),
349 BUILTIN_ROW(__sync_fetch_and_and),
350 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Chris Lattner5caa3702009-05-08 06:58:22 +0000352 BUILTIN_ROW(__sync_add_and_fetch),
353 BUILTIN_ROW(__sync_sub_and_fetch),
354 BUILTIN_ROW(__sync_and_and_fetch),
355 BUILTIN_ROW(__sync_or_and_fetch),
356 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattner5caa3702009-05-08 06:58:22 +0000358 BUILTIN_ROW(__sync_val_compare_and_swap),
359 BUILTIN_ROW(__sync_bool_compare_and_swap),
360 BUILTIN_ROW(__sync_lock_test_and_set),
361 BUILTIN_ROW(__sync_lock_release)
362 };
Mike Stump1eb44332009-09-09 15:08:12 +0000363#undef BUILTIN_ROW
364
Chris Lattner5caa3702009-05-08 06:58:22 +0000365 // Determine the index of the size.
366 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000367 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000368 case 1: SizeIndex = 0; break;
369 case 2: SizeIndex = 1; break;
370 case 4: SizeIndex = 2; break;
371 case 8: SizeIndex = 3; break;
372 case 16: SizeIndex = 4; break;
373 default:
374 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
375 << FirstArg->getType() << FirstArg->getSourceRange();
376 }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Chris Lattner5caa3702009-05-08 06:58:22 +0000378 // Each of these builtins has one pointer argument, followed by some number of
379 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
380 // that we ignore. Find out which row of BuiltinIndices to read from as well
381 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000382 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000383 unsigned BuiltinIndex, NumFixed = 1;
384 switch (BuiltinID) {
385 default: assert(0 && "Unknown overloaded atomic builtin!");
386 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
387 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
388 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
389 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
390 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000392 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
393 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
394 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
395 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
396 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner5caa3702009-05-08 06:58:22 +0000398 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000399 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000400 NumFixed = 2;
401 break;
402 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000403 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000404 NumFixed = 2;
405 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000406 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000407 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000408 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000409 NumFixed = 0;
410 break;
411 }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattner5caa3702009-05-08 06:58:22 +0000413 // Now that we know how many fixed arguments we expect, first check that we
414 // have at least that many.
415 if (TheCall->getNumArgs() < 1+NumFixed)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000416 return Diag(TheCall->getLocEnd(),
417 diag::err_typecheck_call_too_few_args_at_least)
418 << 0 << 1+NumFixed << TheCall->getNumArgs()
419 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000420
421
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000422 // Get the decl for the concrete builtin from this, we can tell what the
423 // concrete integer type we should convert to is.
424 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
425 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
426 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000427 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000428 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
429 TUScope, false, DRE->getLocStart()));
430 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000431 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000432 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000434 // If the first type needs to be converted (e.g. void** -> int*), do it now.
435 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000436 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000437 TheCall->setArg(0, FirstArg);
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner5caa3702009-05-08 06:58:22 +0000440 // Next, walk the valid ones promoting to the right type.
441 for (unsigned i = 0; i != NumFixed; ++i) {
442 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattner5caa3702009-05-08 06:58:22 +0000444 // If the argument is an implicit cast, then there was a promotion due to
445 // "...", just remove it now.
446 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
447 Arg = ICE->getSubExpr();
448 ICE->setSubExpr(0);
449 ICE->Destroy(Context);
450 TheCall->setArg(i+1, Arg);
451 }
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattner5caa3702009-05-08 06:58:22 +0000453 // GCC does an implicit conversion to the pointer or integer ValType. This
454 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000455 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000456 CXXBaseSpecifierArray BasePath;
457 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
Chris Lattner5caa3702009-05-08 06:58:22 +0000458 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Chris Lattner5caa3702009-05-08 06:58:22 +0000460 // Okay, we have something that *can* be converted to the right type. Check
461 // to see if there is a potentially weird extension going on here. This can
462 // happen when you do an atomic operation on something like an char* and
463 // pass in 42. The 42 gets converted to char. This is even more strange
464 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000465 // FIXME: Do this check.
Anders Carlsson80971bd2010-04-24 16:36:20 +0000466 ImpCastExprToType(Arg, ValType, Kind);
Chris Lattner5caa3702009-05-08 06:58:22 +0000467 TheCall->setArg(i+1, Arg);
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Chris Lattner5caa3702009-05-08 06:58:22 +0000470 // Switch the DeclRefExpr to refer to the new decl.
471 DRE->setDecl(NewBuiltinDecl);
472 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 // Set the callee in the CallExpr.
475 // FIXME: This leaks the original parens and implicit casts.
476 Expr *PromotedCall = DRE;
477 UsualUnaryConversions(PromotedCall);
478 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner5caa3702009-05-08 06:58:22 +0000480
481 // Change the result type of the call to match the result type of the decl.
482 TheCall->setType(NewBuiltinDecl->getResultType());
483 return false;
484}
485
486
Chris Lattner69039812009-02-18 06:01:06 +0000487/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000488/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000489/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000490/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000491/// belong to the input codeset UTF-8"
492/// Note: It might also make sense to do the UTF-16 conversion here (would
493/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000494bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000495 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000496 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
497
498 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000499 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
500 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000501 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000502 }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Daniel Dunbarf015b032009-09-22 10:03:52 +0000504 const char *Data = Literal->getStrData();
505 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Daniel Dunbarf015b032009-09-22 10:03:52 +0000507 for (unsigned i = 0; i < Length; ++i) {
508 if (!Data[i]) {
509 Diag(getLocationOfStringLiteralByte(Literal, i),
510 diag::warn_cfstring_literal_contains_nul_character)
511 << Arg->getSourceRange();
512 break;
513 }
514 }
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000516 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000517}
518
Chris Lattnerc27c6652007-12-20 00:05:45 +0000519/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
520/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000521bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
522 Expr *Fn = TheCall->getCallee();
523 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000524 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000525 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000526 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
527 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000528 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000529 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000530 return true;
531 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000532
533 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000534 return Diag(TheCall->getLocEnd(),
535 diag::err_typecheck_call_too_few_args_at_least)
536 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000537 }
538
Chris Lattnerc27c6652007-12-20 00:05:45 +0000539 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000540 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000541 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000542 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000543 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000544 else if (FunctionDecl *FD = getCurFunctionDecl())
545 isVariadic = FD->isVariadic();
546 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000547 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattnerc27c6652007-12-20 00:05:45 +0000549 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000550 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
551 return true;
552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Chris Lattner30ce3442007-12-19 23:59:04 +0000554 // Verify that the second argument to the builtin is the last argument of the
555 // current function or method.
556 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000557 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Anders Carlsson88cf2262008-02-11 04:20:54 +0000559 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
560 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000561 // FIXME: This isn't correct for methods (results in bogus warning).
562 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000563 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000564 if (CurBlock)
565 LastArg = *(CurBlock->TheDecl->param_end()-1);
566 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000567 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000568 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000569 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000570 SecondArgIsLastNamedArgument = PV == LastArg;
571 }
572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Chris Lattner30ce3442007-12-19 23:59:04 +0000574 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000575 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000576 diag::warn_second_parameter_of_va_start_not_last_named_argument);
577 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000578}
Chris Lattner30ce3442007-12-19 23:59:04 +0000579
Chris Lattner1b9a0792007-12-20 00:26:33 +0000580/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
581/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000582bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
583 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000584 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000585 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000586 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000587 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000588 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000589 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000590 << SourceRange(TheCall->getArg(2)->getLocStart(),
591 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner925e60d2007-12-28 05:29:59 +0000593 Expr *OrigArg0 = TheCall->getArg(0);
594 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000595
Chris Lattner1b9a0792007-12-20 00:26:33 +0000596 // Do standard promotions between the two arguments, returning their common
597 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000598 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000599
600 // Make sure any conversions are pushed back into the call; this is
601 // type safe since unordered compare builtins are declared as "_Bool
602 // foo(...)".
603 TheCall->setArg(0, OrigArg0);
604 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Douglas Gregorcde01732009-05-19 22:10:17 +0000606 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
607 return false;
608
Chris Lattner1b9a0792007-12-20 00:26:33 +0000609 // If the common type isn't a real floating type, then the arguments were
610 // invalid for this operation.
611 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000612 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000613 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000614 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000615 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Chris Lattner1b9a0792007-12-20 00:26:33 +0000617 return false;
618}
619
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000620/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
621/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000622/// to check everything. We expect the last argument to be a floating point
623/// value.
624bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
625 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000626 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000627 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000628 if (TheCall->getNumArgs() > NumArgs)
629 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000630 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000631 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000632 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000633 (*(TheCall->arg_end()-1))->getLocEnd());
634
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000635 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Eli Friedman9ac6f622009-08-31 20:06:00 +0000637 if (OrigArg->isTypeDependent())
638 return false;
639
Chris Lattner81368fb2010-05-06 05:50:07 +0000640 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000641 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000642 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000643 diag::err_typecheck_call_invalid_unary_fp)
644 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Chris Lattner81368fb2010-05-06 05:50:07 +0000646 // If this is an implicit conversion from float -> double, remove it.
647 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
648 Expr *CastArg = Cast->getSubExpr();
649 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
650 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
651 "promotion from float to double is the only expected cast here");
652 Cast->setSubExpr(0);
653 Cast->Destroy(Context);
654 TheCall->setArg(NumArgs-1, CastArg);
655 OrigArg = CastArg;
656 }
657 }
658
Eli Friedman9ac6f622009-08-31 20:06:00 +0000659 return false;
660}
661
Eli Friedmand38617c2008-05-14 19:38:39 +0000662/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
663// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000664Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000665 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000666 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000667 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000668 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000669 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000670
Nate Begeman37b6a572010-06-08 00:16:34 +0000671 // Determine which of the following types of shufflevector we're checking:
672 // 1) unary, vector mask: (lhs, mask)
673 // 2) binary, vector mask: (lhs, rhs, mask)
674 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
675 QualType resType = TheCall->getArg(0)->getType();
676 unsigned numElements = 0;
677
Douglas Gregorcde01732009-05-19 22:10:17 +0000678 if (!TheCall->getArg(0)->isTypeDependent() &&
679 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000680 QualType LHSType = TheCall->getArg(0)->getType();
681 QualType RHSType = TheCall->getArg(1)->getType();
682
683 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000684 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000685 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000686 TheCall->getArg(1)->getLocEnd());
687 return ExprError();
688 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000689
690 numElements = LHSType->getAs<VectorType>()->getNumElements();
691 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Nate Begeman37b6a572010-06-08 00:16:34 +0000693 // Check to see if we have a call with 2 vector arguments, the unary shuffle
694 // with mask. If so, verify that RHS is an integer vector type with the
695 // same number of elts as lhs.
696 if (TheCall->getNumArgs() == 2) {
697 if (!RHSType->isIntegerType() ||
698 RHSType->getAs<VectorType>()->getNumElements() != numElements)
699 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
700 << SourceRange(TheCall->getArg(1)->getLocStart(),
701 TheCall->getArg(1)->getLocEnd());
702 numResElements = numElements;
703 }
704 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000705 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000706 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000707 TheCall->getArg(1)->getLocEnd());
708 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000709 } else if (numElements != numResElements) {
710 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
711 resType = Context.getVectorType(eltType, numResElements, false, false);
Douglas Gregorcde01732009-05-19 22:10:17 +0000712 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000713 }
714
715 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000716 if (TheCall->getArg(i)->isTypeDependent() ||
717 TheCall->getArg(i)->isValueDependent())
718 continue;
719
Nate Begeman37b6a572010-06-08 00:16:34 +0000720 llvm::APSInt Result(32);
721 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
722 return ExprError(Diag(TheCall->getLocStart(),
723 diag::err_shufflevector_nonconstant_argument)
724 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000725
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000726 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000727 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000728 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000729 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000730 }
731
732 llvm::SmallVector<Expr*, 32> exprs;
733
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000734 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000735 exprs.push_back(TheCall->getArg(i));
736 TheCall->setArg(i, 0);
737 }
738
Nate Begemana88dc302009-08-12 02:10:25 +0000739 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000740 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000741 TheCall->getCallee()->getLocStart(),
742 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000743}
Chris Lattner30ce3442007-12-19 23:59:04 +0000744
Daniel Dunbar4493f792008-07-21 22:59:13 +0000745/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
746// This is declared to take (const void*, ...) and can take two
747// optional constant int args.
748bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000749 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000750
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000751 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000752 return Diag(TheCall->getLocEnd(),
753 diag::err_typecheck_call_too_many_args_at_most)
754 << 0 /*function call*/ << 3 << NumArgs
755 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000756
757 // Argument 0 is checked for us and the remaining arguments must be
758 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000759 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000760 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000761
Eli Friedman9aef7262009-12-04 00:30:06 +0000762 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000763 if (SemaBuiltinConstantArg(TheCall, i, Result))
764 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Daniel Dunbar4493f792008-07-21 22:59:13 +0000766 // FIXME: gcc issues a warning and rewrites these to 0. These
767 // seems especially odd for the third argument since the default
768 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000769 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000770 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000771 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000772 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000773 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000774 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000775 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000776 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000777 }
778 }
779
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000780 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000781}
782
Eric Christopher691ebc32010-04-17 02:26:23 +0000783/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
784/// TheCall is a constant expression.
785bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
786 llvm::APSInt &Result) {
787 Expr *Arg = TheCall->getArg(ArgNum);
788 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
789 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
790
791 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
792
793 if (!Arg->isIntegerConstantExpr(Result, Context))
794 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000795 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000796
Chris Lattner21fb98e2009-09-23 06:06:36 +0000797 return false;
798}
799
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000800/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
801/// int type). This simply type checks that type is one of the defined
802/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000803// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000804bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000805 llvm::APSInt Result;
806
807 // Check constant-ness first.
808 if (SemaBuiltinConstantArg(TheCall, 1, Result))
809 return true;
810
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000811 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000812 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000813 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
814 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000815 }
816
817 return false;
818}
819
Eli Friedman586d6a82009-05-03 06:04:26 +0000820/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000821/// This checks that val is a constant 1.
822bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
823 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000824 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000825
Eric Christopher691ebc32010-04-17 02:26:23 +0000826 // TODO: This is less than ideal. Overload this to take a value.
827 if (SemaBuiltinConstantArg(TheCall, 1, Result))
828 return true;
829
830 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000831 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
832 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
833
834 return false;
835}
836
Ted Kremenekd30ef872009-01-12 23:09:09 +0000837// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000838bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
839 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000840 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000841 if (E->isTypeDependent() || E->isValueDependent())
842 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000843
844 switch (E->getStmtClass()) {
845 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000846 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000847 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000848 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000849 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000850 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000851 }
852
853 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000854 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000855 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000856 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000857 }
858
859 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000860 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000861 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000862 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Ted Kremenek082d9362009-03-20 21:35:28 +0000865 case Stmt::DeclRefExprClass: {
866 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Ted Kremenek082d9362009-03-20 21:35:28 +0000868 // As an exception, do not flag errors for variables binding to
869 // const string literals.
870 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
871 bool isConstant = false;
872 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000873
Ted Kremenek082d9362009-03-20 21:35:28 +0000874 if (const ArrayType *AT = Context.getAsArrayType(T)) {
875 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000876 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000877 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000878 PT->getPointeeType().isConstant(Context);
879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Ted Kremenek082d9362009-03-20 21:35:28 +0000881 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000882 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000883 return SemaCheckStringLiteral(Init, TheCall,
884 HasVAListArg, format_idx, firstDataArg);
885 }
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Anders Carlssond966a552009-06-28 19:55:58 +0000887 // For vprintf* functions (i.e., HasVAListArg==true), we add a
888 // special check to see if the format string is a function parameter
889 // of the function calling the printf function. If the function
890 // has an attribute indicating it is a printf-like function, then we
891 // should suppress warnings concerning non-literals being used in a call
892 // to a vprintf function. For example:
893 //
894 // void
895 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
896 // va_list ap;
897 // va_start(ap, fmt);
898 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
899 // ...
900 //
901 //
902 // FIXME: We don't have full attribute support yet, so just check to see
903 // if the argument is a DeclRefExpr that references a parameter. We'll
904 // add proper support for checking the attribute later.
905 if (HasVAListArg)
906 if (isa<ParmVarDecl>(VD))
907 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000908 }
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Ted Kremenek082d9362009-03-20 21:35:28 +0000910 return false;
911 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000912
Anders Carlsson8f031b32009-06-27 04:05:33 +0000913 case Stmt::CallExprClass: {
914 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000915 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000916 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
917 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
918 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000919 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000920 unsigned ArgIndex = FA->getFormatIdx();
921 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000922
923 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000924 format_idx, firstDataArg);
925 }
926 }
927 }
928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Anders Carlsson8f031b32009-06-27 04:05:33 +0000930 return false;
931 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000932 case Stmt::ObjCStringLiteralClass:
933 case Stmt::StringLiteralClass: {
934 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Ted Kremenek082d9362009-03-20 21:35:28 +0000936 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000937 StrE = ObjCFExpr->getString();
938 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000939 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Ted Kremenekd30ef872009-01-12 23:09:09 +0000941 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000942 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000943 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000944 return true;
945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Ted Kremenekd30ef872009-01-12 23:09:09 +0000947 return false;
948 }
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Ted Kremenek082d9362009-03-20 21:35:28 +0000950 default:
951 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000952 }
953}
954
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000955void
Mike Stump1eb44332009-09-09 15:08:12 +0000956Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
957 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000958 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
959 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000960 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000961 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +0000962 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000963 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
964 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000965 }
966}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000967
Chris Lattner59907c42007-08-10 20:18:51 +0000968/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000969/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000970///
971/// HasVAListArg - A predicate indicating whether the printf-like
972/// function is passed an explicit va_arg argument (e.g., vprintf)
973///
974/// format_idx - The index into Args for the format string.
975///
976/// Improper format strings to functions in the printf family can be
977/// the source of bizarre bugs and very serious security holes. A
978/// good source of information is available in the following paper
979/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000980///
981/// FormatGuard: Automatic Protection From printf Format String
982/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000983///
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000984/// TODO:
Ted Kremenek71895b92007-08-14 17:39:48 +0000985/// Functionality implemented:
986///
987/// We can statically check the following properties for string
988/// literal format strings for non v.*printf functions (where the
989/// arguments are passed directly):
990//
991/// (1) Are the number of format conversions equal to the number of
992/// data arguments?
993///
994/// (2) Does each format conversion correctly match the type of the
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000995/// corresponding data argument?
Ted Kremenek71895b92007-08-14 17:39:48 +0000996///
997/// Moreover, for all printf functions we can:
998///
999/// (3) Check for a missing format string (when not caught by type checking).
1000///
1001/// (4) Check for no-operation flags; e.g. using "#" with format
1002/// conversion 'c' (TODO)
1003///
1004/// (5) Check the use of '%n', a major source of security holes.
1005///
1006/// (6) Check for malformed format conversions that don't specify anything.
1007///
1008/// (7) Check for empty format strings. e.g: printf("");
1009///
1010/// (8) Check that the format string is a wide literal.
1011///
1012/// All of these checks can be done by parsing the format string.
1013///
Chris Lattner59907c42007-08-10 20:18:51 +00001014void
Mike Stump1eb44332009-09-09 15:08:12 +00001015Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001016 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +00001017 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001018
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001019 // The way the format attribute works in GCC, the implicit this argument
1020 // of member functions is counted. However, it doesn't appear in our own
1021 // lists, so decrement format_idx in that case.
1022 if (isa<CXXMemberCallExpr>(TheCall)) {
1023 // Catch a format attribute mistakenly referring to the object argument.
1024 if (format_idx == 0)
1025 return;
1026 --format_idx;
1027 if(firstDataArg != 0)
1028 --firstDataArg;
1029 }
1030
Mike Stump1eb44332009-09-09 15:08:12 +00001031 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001032 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001033 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1034 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001035 return;
1036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Ted Kremenek082d9362009-03-20 21:35:28 +00001038 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner59907c42007-08-10 20:18:51 +00001040 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001041 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001042 // Dynamically generated format strings are difficult to
1043 // automatically vet at compile time. Requiring that format strings
1044 // are string literals: (1) permits the checking of format strings by
1045 // the compiler and thereby (2) can practically remove the source of
1046 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001047
Mike Stump1eb44332009-09-09 15:08:12 +00001048 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001049 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001050 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001051 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001052 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1053 firstDataArg))
1054 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001055
Chris Lattner655f1412009-04-29 04:59:47 +00001056 // If there are no arguments specified, warn with -Wformat-security, otherwise
1057 // warn only with -Wformat-nonliteral.
1058 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001059 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001060 diag::warn_printf_nonliteral_noargs)
1061 << OrigFormatExpr->getSourceRange();
1062 else
Mike Stump1eb44332009-09-09 15:08:12 +00001063 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001064 diag::warn_printf_nonliteral)
1065 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001066}
Ted Kremenek71895b92007-08-14 17:39:48 +00001067
Ted Kremeneke0e53132010-01-28 23:39:18 +00001068namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001069class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001070 Sema &S;
1071 const StringLiteral *FExpr;
1072 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001073 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001074 const unsigned NumDataArgs;
1075 const bool IsObjCLiteral;
1076 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001077 const bool HasVAListArg;
1078 const CallExpr *TheCall;
1079 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001080 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001081 bool usesPositionalArgs;
1082 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001083public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001084 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001085 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001086 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001087 const char *beg, bool hasVAListArg,
1088 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001089 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001090 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001091 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001092 IsObjCLiteral(isObjCLiteral), Beg(beg),
1093 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001094 TheCall(theCall), FormatIdx(formatIdx),
1095 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001096 CoveredArgs.resize(numDataArgs);
1097 CoveredArgs.reset();
1098 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001099
Ted Kremenek07d161f2010-01-29 01:50:07 +00001100 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001101
Ted Kremenek808015a2010-01-29 03:16:21 +00001102 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1103 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001104
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001105 bool
Ted Kremenek74d56a12010-02-04 20:46:58 +00001106 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1107 const char *startSpecifier,
1108 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001109
Ted Kremenekefaff192010-02-27 01:41:03 +00001110 virtual void HandleInvalidPosition(const char *startSpecifier,
1111 unsigned specifierLen,
1112 analyze_printf::PositionContext p);
1113
1114 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1115
Ted Kremeneke0e53132010-01-28 23:39:18 +00001116 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001117
Ted Kremeneke0e53132010-01-28 23:39:18 +00001118 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1119 const char *startSpecifier,
1120 unsigned specifierLen);
1121private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001122 SourceRange getFormatStringRange();
1123 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001124 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001125 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001126
Ted Kremenekefaff192010-02-27 01:41:03 +00001127 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1128 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001129 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1130 llvm::StringRef flag, llvm::StringRef cspec,
1131 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001132
Ted Kremenek0d277352010-01-29 01:06:55 +00001133 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001134};
1135}
1136
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001137SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001138 return OrigFormatExpr->getSourceRange();
1139}
1140
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001141SourceRange CheckPrintfHandler::
1142getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1143 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001144 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001145}
1146
Ted Kremeneke0e53132010-01-28 23:39:18 +00001147SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001148 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001149}
1150
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001151void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001152HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001153 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001154 SourceLocation Loc = getLocationOfByte(startSpecifier);
1155 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001156 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001157}
1158
Ted Kremenekefaff192010-02-27 01:41:03 +00001159void
1160CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1161 analyze_printf::PositionContext p) {
1162 SourceLocation Loc = getLocationOfByte(startPos);
1163 S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1164 << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1165}
1166
1167void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1168 unsigned posLen) {
1169 SourceLocation Loc = getLocationOfByte(startPos);
1170 S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1171 << getFormatSpecifierRange(startPos, posLen);
1172}
1173
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001174bool CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001175HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1176 const char *startSpecifier,
1177 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001178
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001179 unsigned argIndex = FS.getArgIndex();
1180 bool keepGoing = true;
1181 if (argIndex < NumDataArgs) {
1182 // Consider the argument coverered, even though the specifier doesn't
1183 // make sense.
1184 CoveredArgs.set(argIndex);
1185 }
1186 else {
1187 // If argIndex exceeds the number of data arguments we
1188 // don't issue a warning because that is just a cascade of warnings (and
1189 // they may have intended '%%' anyway). We don't want to continue processing
1190 // the format string after this point, however, as we will like just get
1191 // gibberish when trying to match arguments.
1192 keepGoing = false;
1193 }
1194
Ted Kremenek808015a2010-01-29 03:16:21 +00001195 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001196 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001197 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001198 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001199 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001200 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001201
1202 return keepGoing;
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001203}
1204
Ted Kremeneke0e53132010-01-28 23:39:18 +00001205void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1206 // The presence of a null character is likely an error.
1207 S.Diag(getLocationOfByte(nullCharacter),
1208 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001209 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001210}
1211
Ted Kremenek0d277352010-01-29 01:06:55 +00001212const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001213 return TheCall->getArg(FirstDataArg + i);
Ted Kremenek0d277352010-01-29 01:06:55 +00001214}
1215
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001216void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1217 llvm::StringRef flag,
1218 llvm::StringRef cspec,
1219 const char *startSpecifier,
1220 unsigned specifierLen) {
1221 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1222 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1223 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1224}
1225
Ted Kremenek0d277352010-01-29 01:06:55 +00001226bool
1227CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekefaff192010-02-27 01:41:03 +00001228 unsigned k, const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001229 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001230
1231 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001232 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001233 unsigned argIndex = Amt.getArgIndex();
1234 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001235 S.Diag(getLocationOfByte(Amt.getStart()),
1236 diag::warn_printf_asterisk_missing_arg)
1237 << k << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001238 // Don't do any more checking. We will just emit
1239 // spurious errors.
1240 return false;
1241 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001242
Ted Kremenek0d277352010-01-29 01:06:55 +00001243 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001244 // Although not in conformance with C99, we also allow the argument to be
1245 // an 'unsigned int' as that is a reasonably safe case. GCC also
1246 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001247 CoveredArgs.set(argIndex);
1248 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001249 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001250
1251 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1252 assert(ATR.isValid());
1253
1254 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001255 S.Diag(getLocationOfByte(Amt.getStart()),
1256 diag::warn_printf_asterisk_wrong_type)
1257 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001258 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001259 << getFormatSpecifierRange(startSpecifier, specifierLen)
1260 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001261 // Don't do any more checking. We will just emit
1262 // spurious errors.
1263 return false;
1264 }
1265 }
1266 }
1267 return true;
1268}
Ted Kremenek0d277352010-01-29 01:06:55 +00001269
Ted Kremeneke0e53132010-01-28 23:39:18 +00001270bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001271CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1272 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001273 const char *startSpecifier,
1274 unsigned specifierLen) {
1275
Ted Kremenekefaff192010-02-27 01:41:03 +00001276 using namespace analyze_printf;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001277 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1278
Ted Kremenekefaff192010-02-27 01:41:03 +00001279 if (atFirstArg) {
1280 atFirstArg = false;
1281 usesPositionalArgs = FS.usesPositionalArg();
1282 }
1283 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1284 // Cannot mix-and-match positional and non-positional arguments.
1285 S.Diag(getLocationOfByte(CS.getStart()),
1286 diag::warn_printf_mix_positional_nonpositional_args)
1287 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001288 return false;
1289 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001290
Ted Kremenekefaff192010-02-27 01:41:03 +00001291 // First check if the field width, precision, and conversion specifier
1292 // have matching data arguments.
1293 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1294 startSpecifier, specifierLen)) {
1295 return false;
1296 }
1297
1298 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1299 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001300 return false;
1301 }
1302
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001303 if (!CS.consumesDataArgument()) {
1304 // FIXME: Technically specifying a precision or field width here
1305 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001306 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001307 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001308
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001309 // Consume the argument.
1310 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001311 if (argIndex < NumDataArgs) {
1312 // The check to see if the argIndex is valid will come later.
1313 // We set the bit here because we may exit early from this
1314 // function if we encounter some other error.
1315 CoveredArgs.set(argIndex);
1316 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001317
1318 // Check for using an Objective-C specific conversion specifier
1319 // in a non-ObjC literal.
1320 if (!IsObjCLiteral && CS.isObjCArg()) {
1321 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1322 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001323
Ted Kremeneke82d8042010-01-29 01:35:25 +00001324 // Are we using '%n'? Issue a warning about this being
1325 // a possible security issue.
1326 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1327 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001328 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001329 // Continue checking the other format specifiers.
1330 return true;
1331 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001332
1333 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1334 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001335 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001336 diag::warn_printf_nonsensical_precision)
1337 << CS.getCharacters()
1338 << getFormatSpecifierRange(startSpecifier, specifierLen);
1339 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001340 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1341 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001342 // FIXME: Instead of using "0", "+", etc., eventually get them from
1343 // the FormatSpecifier.
1344 if (FS.hasLeadingZeros())
1345 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1346 if (FS.hasPlusPrefix())
1347 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1348 if (FS.hasSpacePrefix())
1349 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001350 }
1351
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001352 // The remaining checks depend on the data arguments.
1353 if (HasVAListArg)
1354 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001355
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001356 if (argIndex >= NumDataArgs) {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001357 if (FS.usesPositionalArg()) {
1358 S.Diag(getLocationOfByte(CS.getStart()),
1359 diag::warn_printf_positional_arg_exceeds_data_args)
1360 << (argIndex+1) << NumDataArgs
1361 << getFormatSpecifierRange(startSpecifier, specifierLen);
1362 }
1363 else {
1364 S.Diag(getLocationOfByte(CS.getStart()),
1365 diag::warn_printf_insufficient_data_args)
1366 << getFormatSpecifierRange(startSpecifier, specifierLen);
1367 }
1368
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001369 // Don't do any more checking.
1370 return false;
1371 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001372
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001373 // Now type check the data expression that matches the
1374 // format specifier.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001375 const Expr *Ex = getDataArg(argIndex);
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001376 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001377 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1378 // Check if we didn't match because of an implicit cast from a 'char'
1379 // or 'short' to an 'int'. This is done because printf is a varargs
1380 // function.
1381 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1382 if (ICE->getType() == S.Context.IntTy)
1383 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1384 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001385
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001386 S.Diag(getLocationOfByte(CS.getStart()),
1387 diag::warn_printf_conversion_argument_type_mismatch)
1388 << ATR.getRepresentativeType(S.Context) << Ex->getType()
Ted Kremenek1497bff2010-02-11 19:37:25 +00001389 << getFormatSpecifierRange(startSpecifier, specifierLen)
1390 << Ex->getSourceRange();
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001391 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001392
1393 return true;
1394}
1395
Ted Kremenek07d161f2010-01-29 01:50:07 +00001396void CheckPrintfHandler::DoneProcessing() {
1397 // Does the number of data arguments exceed the number of
1398 // format conversions in the format string?
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001399 if (!HasVAListArg) {
1400 // Find any arguments that weren't covered.
1401 CoveredArgs.flip();
1402 signed notCoveredArg = CoveredArgs.find_first();
1403 if (notCoveredArg >= 0) {
1404 assert((unsigned)notCoveredArg < NumDataArgs);
1405 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1406 diag::warn_printf_data_arg_not_used)
1407 << getFormatStringRange();
1408 }
1409 }
Ted Kremenek07d161f2010-01-29 01:50:07 +00001410}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001411
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001412void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001413 const Expr *OrigFormatExpr,
1414 const CallExpr *TheCall, bool HasVAListArg,
1415 unsigned format_idx, unsigned firstDataArg) {
1416
Ted Kremeneke0e53132010-01-28 23:39:18 +00001417 // CHECK: is the format string a wide literal?
1418 if (FExpr->isWide()) {
1419 Diag(FExpr->getLocStart(),
1420 diag::warn_printf_format_string_is_wide_literal)
1421 << OrigFormatExpr->getSourceRange();
1422 return;
1423 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001424
Ted Kremeneke0e53132010-01-28 23:39:18 +00001425 // Str - The format string. NOTE: this is NOT null-terminated!
1426 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001427
Ted Kremeneke0e53132010-01-28 23:39:18 +00001428 // CHECK: empty format string?
1429 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001430
Ted Kremeneke0e53132010-01-28 23:39:18 +00001431 if (StrLen == 0) {
1432 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1433 << OrigFormatExpr->getSourceRange();
1434 return;
1435 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001436
Ted Kremenek6ee76532010-03-25 03:59:12 +00001437 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001438 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001439 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1440 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001441
Ted Kremenek74d56a12010-02-04 20:46:58 +00001442 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001443 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001444}
1445
Ted Kremenek06de2762007-08-17 16:46:58 +00001446//===--- CHECK: Return Address of Stack Variable --------------------------===//
1447
1448static DeclRefExpr* EvalVal(Expr *E);
1449static DeclRefExpr* EvalAddr(Expr* E);
1450
1451/// CheckReturnStackAddr - Check if a return statement returns the address
1452/// of a stack variable.
1453void
1454Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1455 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Ted Kremenek06de2762007-08-17 16:46:58 +00001457 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001458 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001459 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001460 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001461 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Steve Naroffc50a4a52008-09-16 22:25:10 +00001463 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001464 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001465
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001466 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001467 if (C->hasBlockDeclRefExprs())
1468 Diag(C->getLocStart(), diag::err_ret_local_block)
1469 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001470
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001471 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1472 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1473 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001474
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001475 } else if (lhsType->isReferenceType()) {
1476 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001477 // Check for a reference to the stack
1478 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001479 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001480 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001481 }
1482}
1483
1484/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1485/// check if the expression in a return statement evaluates to an address
1486/// to a location on the stack. The recursion is used to traverse the
1487/// AST of the return expression, with recursion backtracking when we
1488/// encounter a subexpression that (1) clearly does not lead to the address
1489/// of a stack variable or (2) is something we cannot determine leads to
1490/// the address of a stack variable based on such local checking.
1491///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001492/// EvalAddr processes expressions that are pointers that are used as
1493/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001494/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001495/// the refers to a stack variable.
1496///
1497/// This implementation handles:
1498///
1499/// * pointer-to-pointer casts
1500/// * implicit conversions from array references to pointers
1501/// * taking the address of fields
1502/// * arbitrary interplay between "&" and "*" operators
1503/// * pointer arithmetic from an address of a stack variable
1504/// * taking the address of an array element where the array is on the stack
1505static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001506 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001507 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001508 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001509 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001510 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Ted Kremenek06de2762007-08-17 16:46:58 +00001512 // Our "symbolic interpreter" is just a dispatch off the currently
1513 // viewed AST node. We then recursively traverse the AST by calling
1514 // EvalAddr and EvalVal appropriately.
1515 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001516 case Stmt::ParenExprClass:
1517 // Ignore parentheses.
1518 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001519
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001520 case Stmt::UnaryOperatorClass: {
1521 // The only unary operator that make sense to handle here
1522 // is AddrOf. All others don't make sense as pointers.
1523 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001525 if (U->getOpcode() == UnaryOperator::AddrOf)
1526 return EvalVal(U->getSubExpr());
1527 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001528 return NULL;
1529 }
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001531 case Stmt::BinaryOperatorClass: {
1532 // Handle pointer arithmetic. All other binary operators are not valid
1533 // in this context.
1534 BinaryOperator *B = cast<BinaryOperator>(E);
1535 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001537 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1538 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001540 Expr *Base = B->getLHS();
1541
1542 // Determine which argument is the real pointer base. It could be
1543 // the RHS argument instead of the LHS.
1544 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001546 assert (Base->getType()->isPointerType());
1547 return EvalAddr(Base);
1548 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001549
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001550 // For conditional operators we need to see if either the LHS or RHS are
1551 // valid DeclRefExpr*s. If one of them is valid, we return it.
1552 case Stmt::ConditionalOperatorClass: {
1553 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001555 // Handle the GNU extension for missing LHS.
1556 if (Expr *lhsExpr = C->getLHS())
1557 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1558 return LHS;
1559
1560 return EvalAddr(C->getRHS());
1561 }
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Ted Kremenek54b52742008-08-07 00:49:01 +00001563 // For casts, we need to handle conversions from arrays to
1564 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001565 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001566 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001567 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001568 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001569 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Steve Naroffdd972f22008-09-05 22:11:13 +00001571 if (SubExpr->getType()->isPointerType() ||
1572 SubExpr->getType()->isBlockPointerType() ||
1573 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001574 return EvalAddr(SubExpr);
1575 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001576 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001577 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001578 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001579 }
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001581 // C++ casts. For dynamic casts, static casts, and const casts, we
1582 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001583 // through the cast. In the case the dynamic cast doesn't fail (and
1584 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001585 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001586 // FIXME: The comment about is wrong; we're not always converting
1587 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001588 // handle references to objects.
1589 case Stmt::CXXStaticCastExprClass:
1590 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001591 case Stmt::CXXConstCastExprClass:
1592 case Stmt::CXXReinterpretCastExprClass: {
1593 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001594 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001595 return EvalAddr(S);
1596 else
1597 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001598 }
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001600 // Everything else: we simply don't reason about them.
1601 default:
1602 return NULL;
1603 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001604}
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Ted Kremenek06de2762007-08-17 16:46:58 +00001606
1607/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1608/// See the comments for EvalAddr for more details.
1609static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001611 // We should only be called for evaluating non-pointer expressions, or
1612 // expressions with a pointer type that are not used as references but instead
1613 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Ted Kremenek06de2762007-08-17 16:46:58 +00001615 // Our "symbolic interpreter" is just a dispatch off the currently
1616 // viewed AST node. We then recursively traverse the AST by calling
1617 // EvalAddr and EvalVal appropriately.
1618 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001619 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001620 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1621 // at code that refers to a variable's name. We check if it has local
1622 // storage within the function, and if so, return the expression.
1623 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Ted Kremenek06de2762007-08-17 16:46:58 +00001625 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001626 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1627
Ted Kremenek06de2762007-08-17 16:46:58 +00001628 return NULL;
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Ted Kremenek06de2762007-08-17 16:46:58 +00001631 case Stmt::ParenExprClass:
1632 // Ignore parentheses.
1633 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Ted Kremenek06de2762007-08-17 16:46:58 +00001635 case Stmt::UnaryOperatorClass: {
1636 // The only unary operator that make sense to handle here
1637 // is Deref. All others don't resolve to a "name." This includes
1638 // handling all sorts of rvalues passed to a unary operator.
1639 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Ted Kremenek06de2762007-08-17 16:46:58 +00001641 if (U->getOpcode() == UnaryOperator::Deref)
1642 return EvalAddr(U->getSubExpr());
1643
1644 return NULL;
1645 }
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Ted Kremenek06de2762007-08-17 16:46:58 +00001647 case Stmt::ArraySubscriptExprClass: {
1648 // Array subscripts are potential references to data on the stack. We
1649 // retrieve the DeclRefExpr* for the array variable if it indeed
1650 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001651 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001652 }
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Ted Kremenek06de2762007-08-17 16:46:58 +00001654 case Stmt::ConditionalOperatorClass: {
1655 // For conditional operators we need to see if either the LHS or RHS are
1656 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1657 ConditionalOperator *C = cast<ConditionalOperator>(E);
1658
Anders Carlsson39073232007-11-30 19:04:31 +00001659 // Handle the GNU extension for missing LHS.
1660 if (Expr *lhsExpr = C->getLHS())
1661 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1662 return LHS;
1663
1664 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Ted Kremenek06de2762007-08-17 16:46:58 +00001667 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001668 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001669 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Ted Kremenek06de2762007-08-17 16:46:58 +00001671 // Check for indirect access. We only want direct field accesses.
1672 if (!M->isArrow())
1673 return EvalVal(M->getBase());
1674 else
1675 return NULL;
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Ted Kremenek06de2762007-08-17 16:46:58 +00001678 // Everything else: we simply don't reason about them.
1679 default:
1680 return NULL;
1681 }
1682}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001683
1684//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1685
1686/// Check for comparisons of floating point operands using != and ==.
1687/// Issue a warning if these are no self-comparisons, as they are not likely
1688/// to do what the programmer intended.
1689void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1690 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001692 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001693 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001694
1695 // Special case: check for x == x (which is OK).
1696 // Do not emit warnings for such cases.
1697 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1698 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1699 if (DRL->getDecl() == DRR->getDecl())
1700 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001701
1702
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001703 // Special case: check for comparisons against literals that can be exactly
1704 // represented by APFloat. In such cases, do not emit a warning. This
1705 // is a heuristic: often comparison against such literals are used to
1706 // detect if a value in a variable has not changed. This clearly can
1707 // lead to false negatives.
1708 if (EmitWarning) {
1709 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1710 if (FLL->isExact())
1711 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001712 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001713 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1714 if (FLR->isExact())
1715 EmitWarning = false;
1716 }
1717 }
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001719 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001720 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001721 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001722 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001723 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Sebastian Redl0eb23302009-01-19 00:08:26 +00001725 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001726 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001727 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001728 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001730 // Emit the diagnostic.
1731 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001732 Diag(loc, diag::warn_floatingpoint_eq)
1733 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001734}
John McCallba26e582010-01-04 23:21:16 +00001735
John McCallf2370c92010-01-06 05:24:50 +00001736//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1737//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001738
John McCallf2370c92010-01-06 05:24:50 +00001739namespace {
John McCallba26e582010-01-04 23:21:16 +00001740
John McCallf2370c92010-01-06 05:24:50 +00001741/// Structure recording the 'active' range of an integer-valued
1742/// expression.
1743struct IntRange {
1744 /// The number of bits active in the int.
1745 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001746
John McCallf2370c92010-01-06 05:24:50 +00001747 /// True if the int is known not to have negative values.
1748 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001749
John McCallf2370c92010-01-06 05:24:50 +00001750 IntRange() {}
1751 IntRange(unsigned Width, bool NonNegative)
1752 : Width(Width), NonNegative(NonNegative)
1753 {}
John McCallba26e582010-01-04 23:21:16 +00001754
John McCallf2370c92010-01-06 05:24:50 +00001755 // Returns the range of the bool type.
1756 static IntRange forBoolType() {
1757 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001758 }
1759
John McCallf2370c92010-01-06 05:24:50 +00001760 // Returns the range of an integral type.
1761 static IntRange forType(ASTContext &C, QualType T) {
1762 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001763 }
1764
John McCallf2370c92010-01-06 05:24:50 +00001765 // Returns the range of an integeral type based on its canonical
1766 // representation.
1767 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1768 assert(T->isCanonicalUnqualified());
1769
1770 if (const VectorType *VT = dyn_cast<VectorType>(T))
1771 T = VT->getElementType().getTypePtr();
1772 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1773 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00001774
1775 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
1776 EnumDecl *Enum = ET->getDecl();
1777 unsigned NumPositive = Enum->getNumPositiveBits();
1778 unsigned NumNegative = Enum->getNumNegativeBits();
1779
1780 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
1781 }
John McCallf2370c92010-01-06 05:24:50 +00001782
1783 const BuiltinType *BT = cast<BuiltinType>(T);
1784 assert(BT->isInteger());
1785
1786 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1787 }
1788
1789 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001790 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00001791 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001792 L.NonNegative && R.NonNegative);
1793 }
1794
1795 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001796 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00001797 return IntRange(std::min(L.Width, R.Width),
1798 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001799 }
1800};
1801
1802IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1803 if (value.isSigned() && value.isNegative())
1804 return IntRange(value.getMinSignedBits(), false);
1805
1806 if (value.getBitWidth() > MaxWidth)
1807 value.trunc(MaxWidth);
1808
1809 // isNonNegative() just checks the sign bit without considering
1810 // signedness.
1811 return IntRange(value.getActiveBits(), true);
1812}
1813
John McCall0acc3112010-01-06 22:57:21 +00001814IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001815 unsigned MaxWidth) {
1816 if (result.isInt())
1817 return GetValueRange(C, result.getInt(), MaxWidth);
1818
1819 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001820 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1821 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1822 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1823 R = IntRange::join(R, El);
1824 }
John McCallf2370c92010-01-06 05:24:50 +00001825 return R;
1826 }
1827
1828 if (result.isComplexInt()) {
1829 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1830 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1831 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001832 }
1833
1834 // This can happen with lossless casts to intptr_t of "based" lvalues.
1835 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001836 // FIXME: The only reason we need to pass the type in here is to get
1837 // the sign right on this one case. It would be nice if APValue
1838 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001839 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001840 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001841}
John McCallf2370c92010-01-06 05:24:50 +00001842
1843/// Pseudo-evaluate the given integer expression, estimating the
1844/// range of values it might take.
1845///
1846/// \param MaxWidth - the width to which the value will be truncated
1847IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1848 E = E->IgnoreParens();
1849
1850 // Try a full evaluation first.
1851 Expr::EvalResult result;
1852 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001853 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001854
1855 // I think we only want to look through implicit casts here; if the
1856 // user has an explicit widening cast, we should treat the value as
1857 // being of the new, wider type.
1858 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1859 if (CE->getCastKind() == CastExpr::CK_NoOp)
1860 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1861
1862 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1863
John McCall60fad452010-01-06 22:07:33 +00001864 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1865 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1866 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1867
John McCallf2370c92010-01-06 05:24:50 +00001868 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001869 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001870 return OutputTypeRange;
1871
1872 IntRange SubRange
1873 = GetExprRange(C, CE->getSubExpr(),
1874 std::min(MaxWidth, OutputTypeRange.Width));
1875
1876 // Bail out if the subexpr's range is as wide as the cast type.
1877 if (SubRange.Width >= OutputTypeRange.Width)
1878 return OutputTypeRange;
1879
1880 // Otherwise, we take the smaller width, and we're non-negative if
1881 // either the output type or the subexpr is.
1882 return IntRange(SubRange.Width,
1883 SubRange.NonNegative || OutputTypeRange.NonNegative);
1884 }
1885
1886 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1887 // If we can fold the condition, just take that operand.
1888 bool CondResult;
1889 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1890 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1891 : CO->getFalseExpr(),
1892 MaxWidth);
1893
1894 // Otherwise, conservatively merge.
1895 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1896 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1897 return IntRange::join(L, R);
1898 }
1899
1900 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1901 switch (BO->getOpcode()) {
1902
1903 // Boolean-valued operations are single-bit and positive.
1904 case BinaryOperator::LAnd:
1905 case BinaryOperator::LOr:
1906 case BinaryOperator::LT:
1907 case BinaryOperator::GT:
1908 case BinaryOperator::LE:
1909 case BinaryOperator::GE:
1910 case BinaryOperator::EQ:
1911 case BinaryOperator::NE:
1912 return IntRange::forBoolType();
1913
John McCallc0cd21d2010-02-23 19:22:29 +00001914 // The type of these compound assignments is the type of the LHS,
1915 // so the RHS is not necessarily an integer.
1916 case BinaryOperator::MulAssign:
1917 case BinaryOperator::DivAssign:
1918 case BinaryOperator::RemAssign:
1919 case BinaryOperator::AddAssign:
1920 case BinaryOperator::SubAssign:
1921 return IntRange::forType(C, E->getType());
1922
John McCallf2370c92010-01-06 05:24:50 +00001923 // Operations with opaque sources are black-listed.
1924 case BinaryOperator::PtrMemD:
1925 case BinaryOperator::PtrMemI:
1926 return IntRange::forType(C, E->getType());
1927
John McCall60fad452010-01-06 22:07:33 +00001928 // Bitwise-and uses the *infinum* of the two source ranges.
1929 case BinaryOperator::And:
John McCallc0cd21d2010-02-23 19:22:29 +00001930 case BinaryOperator::AndAssign:
John McCall60fad452010-01-06 22:07:33 +00001931 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1932 GetExprRange(C, BO->getRHS(), MaxWidth));
1933
John McCallf2370c92010-01-06 05:24:50 +00001934 // Left shift gets black-listed based on a judgement call.
1935 case BinaryOperator::Shl:
John McCall3aae6092010-04-07 01:14:35 +00001936 // ...except that we want to treat '1 << (blah)' as logically
1937 // positive. It's an important idiom.
1938 if (IntegerLiteral *I
1939 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
1940 if (I->getValue() == 1) {
1941 IntRange R = IntRange::forType(C, E->getType());
1942 return IntRange(R.Width, /*NonNegative*/ true);
1943 }
1944 }
1945 // fallthrough
1946
John McCallc0cd21d2010-02-23 19:22:29 +00001947 case BinaryOperator::ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00001948 return IntRange::forType(C, E->getType());
1949
John McCall60fad452010-01-06 22:07:33 +00001950 // Right shift by a constant can narrow its left argument.
John McCallc0cd21d2010-02-23 19:22:29 +00001951 case BinaryOperator::Shr:
1952 case BinaryOperator::ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00001953 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1954
1955 // If the shift amount is a positive constant, drop the width by
1956 // that much.
1957 llvm::APSInt shift;
1958 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1959 shift.isNonNegative()) {
1960 unsigned zext = shift.getZExtValue();
1961 if (zext >= L.Width)
1962 L.Width = (L.NonNegative ? 0 : 1);
1963 else
1964 L.Width -= zext;
1965 }
1966
1967 return L;
1968 }
1969
1970 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001971 case BinaryOperator::Comma:
1972 return GetExprRange(C, BO->getRHS(), MaxWidth);
1973
John McCall60fad452010-01-06 22:07:33 +00001974 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001975 case BinaryOperator::Sub:
1976 if (BO->getLHS()->getType()->isPointerType())
1977 return IntRange::forType(C, E->getType());
1978 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001979
John McCallf2370c92010-01-06 05:24:50 +00001980 default:
1981 break;
1982 }
1983
1984 // Treat every other operator as if it were closed on the
1985 // narrowest type that encompasses both operands.
1986 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1987 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1988 return IntRange::join(L, R);
1989 }
1990
1991 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1992 switch (UO->getOpcode()) {
1993 // Boolean-valued operations are white-listed.
1994 case UnaryOperator::LNot:
1995 return IntRange::forBoolType();
1996
1997 // Operations with opaque sources are black-listed.
1998 case UnaryOperator::Deref:
1999 case UnaryOperator::AddrOf: // should be impossible
2000 case UnaryOperator::OffsetOf:
2001 return IntRange::forType(C, E->getType());
2002
2003 default:
2004 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2005 }
2006 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002007
2008 if (dyn_cast<OffsetOfExpr>(E)) {
2009 IntRange::forType(C, E->getType());
2010 }
John McCallf2370c92010-01-06 05:24:50 +00002011
2012 FieldDecl *BitField = E->getBitField();
2013 if (BitField) {
2014 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2015 unsigned BitWidth = BitWidthAP.getZExtValue();
2016
2017 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2018 }
2019
2020 return IntRange::forType(C, E->getType());
2021}
John McCall51313c32010-01-04 23:31:57 +00002022
John McCall323ed742010-05-06 08:58:33 +00002023IntRange GetExprRange(ASTContext &C, Expr *E) {
2024 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2025}
2026
John McCall51313c32010-01-04 23:31:57 +00002027/// Checks whether the given value, which currently has the given
2028/// source semantics, has the same value when coerced through the
2029/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002030bool IsSameFloatAfterCast(const llvm::APFloat &value,
2031 const llvm::fltSemantics &Src,
2032 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002033 llvm::APFloat truncated = value;
2034
2035 bool ignored;
2036 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2037 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2038
2039 return truncated.bitwiseIsEqual(value);
2040}
2041
2042/// Checks whether the given value, which currently has the given
2043/// source semantics, has the same value when coerced through the
2044/// target semantics.
2045///
2046/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002047bool IsSameFloatAfterCast(const APValue &value,
2048 const llvm::fltSemantics &Src,
2049 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002050 if (value.isFloat())
2051 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2052
2053 if (value.isVector()) {
2054 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2055 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2056 return false;
2057 return true;
2058 }
2059
2060 assert(value.isComplexFloat());
2061 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2062 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2063}
2064
John McCall323ed742010-05-06 08:58:33 +00002065void AnalyzeImplicitConversions(Sema &S, Expr *E);
2066
2067bool IsZero(Sema &S, Expr *E) {
2068 llvm::APSInt Value;
2069 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2070}
2071
2072void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2073 BinaryOperator::Opcode op = E->getOpcode();
2074 if (op == BinaryOperator::LT && IsZero(S, E->getRHS())) {
2075 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2076 << "< 0" << "false"
2077 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2078 } else if (op == BinaryOperator::GE && IsZero(S, E->getRHS())) {
2079 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2080 << ">= 0" << "true"
2081 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2082 } else if (op == BinaryOperator::GT && IsZero(S, E->getLHS())) {
2083 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2084 << "0 >" << "false"
2085 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2086 } else if (op == BinaryOperator::LE && IsZero(S, E->getLHS())) {
2087 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2088 << "0 <=" << "true"
2089 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2090 }
2091}
2092
2093/// Analyze the operands of the given comparison. Implements the
2094/// fallback case from AnalyzeComparison.
2095void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2096 AnalyzeImplicitConversions(S, E->getLHS());
2097 AnalyzeImplicitConversions(S, E->getRHS());
2098}
John McCall51313c32010-01-04 23:31:57 +00002099
John McCallba26e582010-01-04 23:21:16 +00002100/// \brief Implements -Wsign-compare.
2101///
2102/// \param lex the left-hand expression
2103/// \param rex the right-hand expression
2104/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002105/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002106void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2107 // The type the comparison is being performed in.
2108 QualType T = E->getLHS()->getType();
2109 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2110 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002111
John McCall323ed742010-05-06 08:58:33 +00002112 // We don't do anything special if this isn't an unsigned integral
2113 // comparison: we're only interested in integral comparisons, and
2114 // signed comparisons only happen in cases we don't care to warn about.
2115 if (!T->isUnsignedIntegerType())
2116 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002117
John McCall323ed742010-05-06 08:58:33 +00002118 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2119 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002120
John McCall323ed742010-05-06 08:58:33 +00002121 // Check to see if one of the (unmodified) operands is of different
2122 // signedness.
2123 Expr *signedOperand, *unsignedOperand;
2124 if (lex->getType()->isSignedIntegerType()) {
2125 assert(!rex->getType()->isSignedIntegerType() &&
2126 "unsigned comparison between two signed integer expressions?");
2127 signedOperand = lex;
2128 unsignedOperand = rex;
2129 } else if (rex->getType()->isSignedIntegerType()) {
2130 signedOperand = rex;
2131 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002132 } else {
John McCall323ed742010-05-06 08:58:33 +00002133 CheckTrivialUnsignedComparison(S, E);
2134 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002135 }
2136
John McCall323ed742010-05-06 08:58:33 +00002137 // Otherwise, calculate the effective range of the signed operand.
2138 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002139
John McCall323ed742010-05-06 08:58:33 +00002140 // Go ahead and analyze implicit conversions in the operands. Note
2141 // that we skip the implicit conversions on both sides.
2142 AnalyzeImplicitConversions(S, lex);
2143 AnalyzeImplicitConversions(S, rex);
John McCallba26e582010-01-04 23:21:16 +00002144
John McCall323ed742010-05-06 08:58:33 +00002145 // If the signed range is non-negative, -Wsign-compare won't fire,
2146 // but we should still check for comparisons which are always true
2147 // or false.
2148 if (signedRange.NonNegative)
2149 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002150
2151 // For (in)equality comparisons, if the unsigned operand is a
2152 // constant which cannot collide with a overflowed signed operand,
2153 // then reinterpreting the signed operand as unsigned will not
2154 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002155 if (E->isEqualityOp()) {
2156 unsigned comparisonWidth = S.Context.getIntWidth(T);
2157 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002158
John McCall323ed742010-05-06 08:58:33 +00002159 // We should never be unable to prove that the unsigned operand is
2160 // non-negative.
2161 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2162
2163 if (unsignedRange.Width < comparisonWidth)
2164 return;
2165 }
2166
2167 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2168 << lex->getType() << rex->getType()
2169 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002170}
2171
John McCall51313c32010-01-04 23:31:57 +00002172/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCall323ed742010-05-06 08:58:33 +00002173void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
John McCall51313c32010-01-04 23:31:57 +00002174 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2175}
2176
John McCall323ed742010-05-06 08:58:33 +00002177void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2178 bool *ICContext = 0) {
2179 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002180
John McCall323ed742010-05-06 08:58:33 +00002181 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2182 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2183 if (Source == Target) return;
2184 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002185
2186 // Never diagnose implicit casts to bool.
2187 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2188 return;
2189
2190 // Strip vector types.
2191 if (isa<VectorType>(Source)) {
2192 if (!isa<VectorType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002193 return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002194
2195 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2196 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2197 }
2198
2199 // Strip complex types.
2200 if (isa<ComplexType>(Source)) {
2201 if (!isa<ComplexType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002202 return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002203
2204 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2205 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2206 }
2207
2208 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2209 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2210
2211 // If the source is floating point...
2212 if (SourceBT && SourceBT->isFloatingPoint()) {
2213 // ...and the target is floating point...
2214 if (TargetBT && TargetBT->isFloatingPoint()) {
2215 // ...then warn if we're dropping FP rank.
2216
2217 // Builtin FP kinds are ordered by increasing FP rank.
2218 if (SourceBT->getKind() > TargetBT->getKind()) {
2219 // Don't warn about float constants that are precisely
2220 // representable in the target type.
2221 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002222 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002223 // Value might be a float, a float vector, or a float complex.
2224 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002225 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2226 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002227 return;
2228 }
2229
John McCall323ed742010-05-06 08:58:33 +00002230 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002231 }
2232 return;
2233 }
2234
2235 // If the target is integral, always warn.
2236 if ((TargetBT && TargetBT->isInteger()))
2237 // TODO: don't warn for integer values?
John McCall323ed742010-05-06 08:58:33 +00002238 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer);
John McCall51313c32010-01-04 23:31:57 +00002239
2240 return;
2241 }
2242
John McCallf2370c92010-01-06 05:24:50 +00002243 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002244 return;
2245
John McCall323ed742010-05-06 08:58:33 +00002246 IntRange SourceRange = GetExprRange(S.Context, E);
2247 IntRange TargetRange = IntRange::forCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002248
2249 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002250 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2251 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002252 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall323ed742010-05-06 08:58:33 +00002253 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32);
2254 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision);
2255 }
2256
2257 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2258 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2259 SourceRange.Width == TargetRange.Width)) {
2260 unsigned DiagID = diag::warn_impcast_integer_sign;
2261
2262 // Traditionally, gcc has warned about this under -Wsign-compare.
2263 // We also want to warn about it in -Wconversion.
2264 // So if -Wconversion is off, use a completely identical diagnostic
2265 // in the sign-compare group.
2266 // The conditional-checking code will
2267 if (ICContext) {
2268 DiagID = diag::warn_impcast_integer_sign_conditional;
2269 *ICContext = true;
2270 }
2271
2272 return DiagnoseImpCast(S, E, T, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002273 }
2274
2275 return;
2276}
2277
John McCall323ed742010-05-06 08:58:33 +00002278void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2279
2280void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2281 bool &ICContext) {
2282 E = E->IgnoreParenImpCasts();
2283
2284 if (isa<ConditionalOperator>(E))
2285 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2286
2287 AnalyzeImplicitConversions(S, E);
2288 if (E->getType() != T)
2289 return CheckImplicitConversion(S, E, T, &ICContext);
2290 return;
2291}
2292
2293void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2294 AnalyzeImplicitConversions(S, E->getCond());
2295
2296 bool Suspicious = false;
2297 CheckConditionalOperand(S, E->getTrueExpr(), T, Suspicious);
2298 CheckConditionalOperand(S, E->getFalseExpr(), T, Suspicious);
2299
2300 // If -Wconversion would have warned about either of the candidates
2301 // for a signedness conversion to the context type...
2302 if (!Suspicious) return;
2303
2304 // ...but it's currently ignored...
2305 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2306 return;
2307
2308 // ...and -Wsign-compare isn't...
2309 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2310 return;
2311
2312 // ...then check whether it would have warned about either of the
2313 // candidates for a signedness conversion to the condition type.
2314 if (E->getType() != T) {
2315 Suspicious = false;
2316 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2317 E->getType(), &Suspicious);
2318 if (!Suspicious)
2319 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2320 E->getType(), &Suspicious);
2321 if (!Suspicious)
2322 return;
2323 }
2324
2325 // If so, emit a diagnostic under -Wsign-compare.
2326 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2327 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2328 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2329 << lex->getType() << rex->getType()
2330 << lex->getSourceRange() << rex->getSourceRange();
2331}
2332
2333/// AnalyzeImplicitConversions - Find and report any interesting
2334/// implicit conversions in the given expression. There are a couple
2335/// of competing diagnostics here, -Wconversion and -Wsign-compare.
2336void AnalyzeImplicitConversions(Sema &S, Expr *OrigE) {
2337 QualType T = OrigE->getType();
2338 Expr *E = OrigE->IgnoreParenImpCasts();
2339
2340 // For conditional operators, we analyze the arguments as if they
2341 // were being fed directly into the output.
2342 if (isa<ConditionalOperator>(E)) {
2343 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2344 CheckConditionalOperator(S, CO, T);
2345 return;
2346 }
2347
2348 // Go ahead and check any implicit conversions we might have skipped.
2349 // The non-canonical typecheck is just an optimization;
2350 // CheckImplicitConversion will filter out dead implicit conversions.
2351 if (E->getType() != T)
2352 CheckImplicitConversion(S, E, T);
2353
2354 // Now continue drilling into this expression.
2355
2356 // Skip past explicit casts.
2357 if (isa<ExplicitCastExpr>(E)) {
2358 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
2359 return AnalyzeImplicitConversions(S, E);
2360 }
2361
2362 // Do a somewhat different check with comparison operators.
2363 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isComparisonOp())
2364 return AnalyzeComparison(S, cast<BinaryOperator>(E));
2365
2366 // These break the otherwise-useful invariant below. Fortunately,
2367 // we don't really need to recurse into them, because any internal
2368 // expressions should have been analyzed already when they were
2369 // built into statements.
2370 if (isa<StmtExpr>(E)) return;
2371
2372 // Don't descend into unevaluated contexts.
2373 if (isa<SizeOfAlignOfExpr>(E)) return;
2374
2375 // Now just recurse over the expression's children.
2376 for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2377 I != IE; ++I)
2378 AnalyzeImplicitConversions(S, cast<Expr>(*I));
2379}
2380
2381} // end anonymous namespace
2382
2383/// Diagnoses "dangerous" implicit conversions within the given
2384/// expression (which is a full expression). Implements -Wconversion
2385/// and -Wsign-compare.
2386void Sema::CheckImplicitConversions(Expr *E) {
2387 // Don't diagnose in unevaluated contexts.
2388 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2389 return;
2390
2391 // Don't diagnose for value- or type-dependent expressions.
2392 if (E->isTypeDependent() || E->isValueDependent())
2393 return;
2394
2395 AnalyzeImplicitConversions(*this, E);
2396}
2397
Mike Stumpf8c49212010-01-21 03:59:47 +00002398/// CheckParmsForFunctionDef - Check that the parameters of the given
2399/// function are appropriate for the definition of a function. This
2400/// takes care of any checks that cannot be performed on the
2401/// declaration itself, e.g., that the types of each of the function
2402/// parameters are complete.
2403bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2404 bool HasInvalidParm = false;
2405 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2406 ParmVarDecl *Param = FD->getParamDecl(p);
2407
2408 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2409 // function declarator that is part of a function definition of
2410 // that function shall not have incomplete type.
2411 //
2412 // This is also C++ [dcl.fct]p6.
2413 if (!Param->isInvalidDecl() &&
2414 RequireCompleteType(Param->getLocation(), Param->getType(),
2415 diag::err_typecheck_decl_incomplete_type)) {
2416 Param->setInvalidDecl();
2417 HasInvalidParm = true;
2418 }
2419
2420 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2421 // declaration of each parameter shall include an identifier.
2422 if (Param->getIdentifier() == 0 &&
2423 !Param->isImplicit() &&
2424 !getLangOptions().CPlusPlus)
2425 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002426
2427 // C99 6.7.5.3p12:
2428 // If the function declarator is not part of a definition of that
2429 // function, parameters may have incomplete type and may use the [*]
2430 // notation in their sequences of declarator specifiers to specify
2431 // variable length array types.
2432 QualType PType = Param->getOriginalType();
2433 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2434 if (AT->getSizeModifier() == ArrayType::Star) {
2435 // FIXME: This diagnosic should point the the '[*]' if source-location
2436 // information is added for it.
2437 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2438 }
2439 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002440 }
2441
2442 return HasInvalidParm;
2443}