1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "Sema.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include <limits>
23 using namespace clang;
24 
25 /// getLocationOfStringLiteralByte - Return a source location that points to the
26 /// specified byte of the specified string literal.
27 ///
28 /// Strings are amazingly complex.  They can be formed from multiple tokens and
29 /// can have escape sequences in them in addition to the usual trigraph and
30 /// escaped newline business.  This routine handles this complexity.
31 ///
32 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
33                                                     unsigned ByteNo) const {
34   assert(!SL->isWide() && "This doesn't work for wide strings yet");
35 
36   // Loop over all of the tokens in this string until we find the one that
37   // contains the byte we're looking for.
38   unsigned TokNo = 0;
39   while (1) {
40     assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
41     SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
42 
43     // Get the spelling of the string so that we can get the data that makes up
44     // the string literal, not the identifier for the macro it is potentially
45     // expanded through.
46     SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
47 
48     // Re-lex the token to get its length and original spelling.
49     std::pair<FileID, unsigned> LocInfo =
50       SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
51     std::pair<const char *,const char *> Buffer =
52       SourceMgr.getBufferData(LocInfo.first);
53     const char *StrData = Buffer.first+LocInfo.second;
54 
55     // Create a langops struct and enable trigraphs.  This is sufficient for
56     // relexing tokens.
57     LangOptions LangOpts;
58     LangOpts.Trigraphs = true;
59 
60     // Create a lexer starting at the beginning of this token.
61     Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
62                    Buffer.second);
63     Token TheTok;
64     TheLexer.LexFromRawLexer(TheTok);
65 
66     // Use the StringLiteralParser to compute the length of the string in bytes.
67     StringLiteralParser SLP(&TheTok, 1, PP);
68     unsigned TokNumBytes = SLP.GetStringLength();
69 
70     // If the byte is in this token, return the location of the byte.
71     if (ByteNo < TokNumBytes ||
72         (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
73       unsigned Offset =
74         StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
75 
76       // Now that we know the offset of the token in the spelling, use the
77       // preprocessor to get the offset in the original source.
78       return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
79     }
80 
81     // Move to the next string token.
82     ++TokNo;
83     ByteNo -= TokNumBytes;
84   }
85 }
86 
87 
88 /// CheckFunctionCall - Check a direct function call for various correctness
89 /// and safety properties not strictly enforced by the C type system.
90 Action::OwningExprResult
91 Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
92   OwningExprResult TheCallResult(Owned(TheCall));
93   // Get the IdentifierInfo* for the called function.
94   IdentifierInfo *FnInfo = FDecl->getIdentifier();
95 
96   // None of the checks below are needed for functions that don't have
97   // simple names (e.g., C++ conversion functions).
98   if (!FnInfo)
99     return move(TheCallResult);
100 
101   switch (FDecl->getBuiltinID(Context)) {
102   case Builtin::BI__builtin___CFStringMakeConstantString:
103     assert(TheCall->getNumArgs() == 1 &&
104            "Wrong # arguments to builtin CFStringMakeConstantString");
105     if (CheckObjCString(TheCall->getArg(0)))
106       return ExprError();
107     return move(TheCallResult);
108   case Builtin::BI__builtin_stdarg_start:
109   case Builtin::BI__builtin_va_start:
110     if (SemaBuiltinVAStart(TheCall))
111       return ExprError();
112     return move(TheCallResult);
113   case Builtin::BI__builtin_isgreater:
114   case Builtin::BI__builtin_isgreaterequal:
115   case Builtin::BI__builtin_isless:
116   case Builtin::BI__builtin_islessequal:
117   case Builtin::BI__builtin_islessgreater:
118   case Builtin::BI__builtin_isunordered:
119     if (SemaBuiltinUnorderedCompare(TheCall))
120       return ExprError();
121     return move(TheCallResult);
122   case Builtin::BI__builtin_return_address:
123   case Builtin::BI__builtin_frame_address:
124     if (SemaBuiltinStackAddress(TheCall))
125       return ExprError();
126     return move(TheCallResult);
127   case Builtin::BI__builtin_shufflevector:
128     return SemaBuiltinShuffleVector(TheCall);
129     // TheCall will be freed by the smart pointer here, but that's fine, since
130     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
131   case Builtin::BI__builtin_prefetch:
132     if (SemaBuiltinPrefetch(TheCall))
133       return ExprError();
134     return move(TheCallResult);
135   case Builtin::BI__builtin_object_size:
136     if (SemaBuiltinObjectSize(TheCall))
137       return ExprError();
138     return move(TheCallResult);
139   case Builtin::BI__builtin_longjmp:
140     if (SemaBuiltinLongjmp(TheCall))
141       return ExprError();
142     return move(TheCallResult);
143   case Builtin::BI__sync_fetch_and_add:
144   case Builtin::BI__sync_fetch_and_sub:
145   case Builtin::BI__sync_fetch_and_or:
146   case Builtin::BI__sync_fetch_and_and:
147   case Builtin::BI__sync_fetch_and_xor:
148   case Builtin::BI__sync_fetch_and_nand:
149   case Builtin::BI__sync_add_and_fetch:
150   case Builtin::BI__sync_sub_and_fetch:
151   case Builtin::BI__sync_and_and_fetch:
152   case Builtin::BI__sync_or_and_fetch:
153   case Builtin::BI__sync_xor_and_fetch:
154   case Builtin::BI__sync_nand_and_fetch:
155   case Builtin::BI__sync_val_compare_and_swap:
156   case Builtin::BI__sync_bool_compare_and_swap:
157   case Builtin::BI__sync_lock_test_and_set:
158   case Builtin::BI__sync_lock_release:
159     if (SemaBuiltinAtomicOverloaded(TheCall))
160       return ExprError();
161     return move(TheCallResult);
162   }
163 
164   // FIXME: This mechanism should be abstracted to be less fragile and
165   // more efficient. For example, just map function ids to custom
166   // handlers.
167 
168   // Printf checking.
169   if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
170     if (Format->getType() == "printf") {
171       bool HasVAListArg = Format->getFirstArg() == 0;
172       if (!HasVAListArg) {
173         if (const FunctionProtoType *Proto
174             = FDecl->getType()->getAsFunctionProtoType())
175         HasVAListArg = !Proto->isVariadic();
176       }
177       CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
178                            HasVAListArg ? 0 : Format->getFirstArg() - 1);
179     }
180   }
181   for (const Attr *attr = FDecl->getAttrs(); attr; attr = attr->getNext()) {
182     if (const NonNullAttr *NonNull = dyn_cast<NonNullAttr>(attr))
183       CheckNonNullArguments(NonNull, TheCall);
184   }
185 
186   return move(TheCallResult);
187 }
188 
189 Action::OwningExprResult
190 Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
191 
192   OwningExprResult TheCallResult(Owned(TheCall));
193   // Printf checking.
194   const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
195   if (!Format)
196     return move(TheCallResult);
197   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
198   if (!V)
199     return move(TheCallResult);
200   QualType Ty = V->getType();
201   if (!Ty->isBlockPointerType())
202     return move(TheCallResult);
203   if (Format->getType() == "printf") {
204       bool HasVAListArg = Format->getFirstArg() == 0;
205       if (!HasVAListArg) {
206         const FunctionType *FT =
207           Ty->getAsBlockPointerType()->getPointeeType()->getAsFunctionType();
208         if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
209           HasVAListArg = !Proto->isVariadic();
210       }
211       CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
212                            HasVAListArg ? 0 : Format->getFirstArg() - 1);
213   }
214   return move(TheCallResult);
215 }
216 
217 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
218 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
219 /// type of its first argument.  The main ActOnCallExpr routines have already
220 /// promoted the types of arguments because all of these calls are prototyped as
221 /// void(...).
222 ///
223 /// This function goes through and does final semantic checking for these
224 /// builtins,
225 bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
226   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
227   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
228 
229   // Ensure that we have at least one argument to do type inference from.
230   if (TheCall->getNumArgs() < 1)
231     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
232               << 0 << TheCall->getCallee()->getSourceRange();
233 
234   // Inspect the first argument of the atomic builtin.  This should always be
235   // a pointer type, whose element is an integral scalar or pointer type.
236   // Because it is a pointer type, we don't have to worry about any implicit
237   // casts here.
238   Expr *FirstArg = TheCall->getArg(0);
239   if (!FirstArg->getType()->isPointerType())
240     return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
241              << FirstArg->getType() << FirstArg->getSourceRange();
242 
243   QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType();
244   if (!ValType->isIntegerType() && !ValType->isPointerType() &&
245       !ValType->isBlockPointerType())
246     return Diag(DRE->getLocStart(),
247                 diag::err_atomic_builtin_must_be_pointer_intptr)
248              << FirstArg->getType() << FirstArg->getSourceRange();
249 
250   // We need to figure out which concrete builtin this maps onto.  For example,
251   // __sync_fetch_and_add with a 2 byte object turns into
252   // __sync_fetch_and_add_2.
253 #define BUILTIN_ROW(x) \
254   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
255     Builtin::BI##x##_8, Builtin::BI##x##_16 }
256 
257   static const unsigned BuiltinIndices[][5] = {
258     BUILTIN_ROW(__sync_fetch_and_add),
259     BUILTIN_ROW(__sync_fetch_and_sub),
260     BUILTIN_ROW(__sync_fetch_and_or),
261     BUILTIN_ROW(__sync_fetch_and_and),
262     BUILTIN_ROW(__sync_fetch_and_xor),
263     BUILTIN_ROW(__sync_fetch_and_nand),
264 
265     BUILTIN_ROW(__sync_add_and_fetch),
266     BUILTIN_ROW(__sync_sub_and_fetch),
267     BUILTIN_ROW(__sync_and_and_fetch),
268     BUILTIN_ROW(__sync_or_and_fetch),
269     BUILTIN_ROW(__sync_xor_and_fetch),
270     BUILTIN_ROW(__sync_nand_and_fetch),
271 
272     BUILTIN_ROW(__sync_val_compare_and_swap),
273     BUILTIN_ROW(__sync_bool_compare_and_swap),
274     BUILTIN_ROW(__sync_lock_test_and_set),
275     BUILTIN_ROW(__sync_lock_release)
276   };
277 #undef BUILTIN_ROW
278 
279   // Determine the index of the size.
280   unsigned SizeIndex;
281   switch (Context.getTypeSize(ValType)/8) {
282   case 1: SizeIndex = 0; break;
283   case 2: SizeIndex = 1; break;
284   case 4: SizeIndex = 2; break;
285   case 8: SizeIndex = 3; break;
286   case 16: SizeIndex = 4; break;
287   default:
288     return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
289              << FirstArg->getType() << FirstArg->getSourceRange();
290   }
291 
292   // Each of these builtins has one pointer argument, followed by some number of
293   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
294   // that we ignore.  Find out which row of BuiltinIndices to read from as well
295   // as the number of fixed args.
296   unsigned BuiltinID = FDecl->getBuiltinID(Context);
297   unsigned BuiltinIndex, NumFixed = 1;
298   switch (BuiltinID) {
299   default: assert(0 && "Unknown overloaded atomic builtin!");
300   case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
301   case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
302   case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
303   case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
304   case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
305   case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
306 
307   case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
308   case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
309   case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
310   case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 9; break;
311   case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
312   case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
313 
314   case Builtin::BI__sync_val_compare_and_swap:
315     BuiltinIndex = 12;
316     NumFixed = 2;
317     break;
318   case Builtin::BI__sync_bool_compare_and_swap:
319     BuiltinIndex = 13;
320     NumFixed = 2;
321     break;
322   case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
323   case Builtin::BI__sync_lock_release:
324     BuiltinIndex = 15;
325     NumFixed = 0;
326     break;
327   }
328 
329   // Now that we know how many fixed arguments we expect, first check that we
330   // have at least that many.
331   if (TheCall->getNumArgs() < 1+NumFixed)
332     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
333             << 0 << TheCall->getCallee()->getSourceRange();
334 
335 
336   // Get the decl for the concrete builtin from this, we can tell what the
337   // concrete integer type we should convert to is.
338   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
339   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
340   IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
341   FunctionDecl *NewBuiltinDecl =
342     cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
343                                            TUScope, false, DRE->getLocStart()));
344   const FunctionProtoType *BuiltinFT =
345     NewBuiltinDecl->getType()->getAsFunctionProtoType();
346   ValType = BuiltinFT->getArgType(0)->getAsPointerType()->getPointeeType();
347 
348   // If the first type needs to be converted (e.g. void** -> int*), do it now.
349   if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
350     ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), false);
351     TheCall->setArg(0, FirstArg);
352   }
353 
354   // Next, walk the valid ones promoting to the right type.
355   for (unsigned i = 0; i != NumFixed; ++i) {
356     Expr *Arg = TheCall->getArg(i+1);
357 
358     // If the argument is an implicit cast, then there was a promotion due to
359     // "...", just remove it now.
360     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
361       Arg = ICE->getSubExpr();
362       ICE->setSubExpr(0);
363       ICE->Destroy(Context);
364       TheCall->setArg(i+1, Arg);
365     }
366 
367     // GCC does an implicit conversion to the pointer or integer ValType.  This
368     // can fail in some cases (1i -> int**), check for this error case now.
369     if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
370       return true;
371 
372     // Okay, we have something that *can* be converted to the right type.  Check
373     // to see if there is a potentially weird extension going on here.  This can
374     // happen when you do an atomic operation on something like an char* and
375     // pass in 42.  The 42 gets converted to char.  This is even more strange
376     // for things like 45.123 -> char, etc.
377     // FIXME: Do this check.
378     ImpCastExprToType(Arg, ValType, false);
379     TheCall->setArg(i+1, Arg);
380   }
381 
382   // Switch the DeclRefExpr to refer to the new decl.
383   DRE->setDecl(NewBuiltinDecl);
384   DRE->setType(NewBuiltinDecl->getType());
385 
386   // Set the callee in the CallExpr.
387   // FIXME: This leaks the original parens and implicit casts.
388   Expr *PromotedCall = DRE;
389   UsualUnaryConversions(PromotedCall);
390   TheCall->setCallee(PromotedCall);
391 
392 
393   // Change the result type of the call to match the result type of the decl.
394   TheCall->setType(NewBuiltinDecl->getResultType());
395   return false;
396 }
397 
398 
399 /// CheckObjCString - Checks that the argument to the builtin
400 /// CFString constructor is correct
401 /// FIXME: GCC currently emits the following warning:
402 /// "warning: input conversion stopped due to an input byte that does not
403 ///           belong to the input codeset UTF-8"
404 /// Note: It might also make sense to do the UTF-16 conversion here (would
405 /// simplify the backend).
406 bool Sema::CheckObjCString(Expr *Arg) {
407   Arg = Arg->IgnoreParenCasts();
408   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
409 
410   if (!Literal || Literal->isWide()) {
411     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
412       << Arg->getSourceRange();
413     return true;
414   }
415 
416   const char *Data = Literal->getStrData();
417   unsigned Length = Literal->getByteLength();
418 
419   for (unsigned i = 0; i < Length; ++i) {
420     if (!Data[i]) {
421       Diag(getLocationOfStringLiteralByte(Literal, i),
422            diag::warn_cfstring_literal_contains_nul_character)
423         << Arg->getSourceRange();
424       break;
425     }
426   }
427 
428   return false;
429 }
430 
431 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
432 /// Emit an error and return true on failure, return false on success.
433 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
434   Expr *Fn = TheCall->getCallee();
435   if (TheCall->getNumArgs() > 2) {
436     Diag(TheCall->getArg(2)->getLocStart(),
437          diag::err_typecheck_call_too_many_args)
438       << 0 /*function call*/ << Fn->getSourceRange()
439       << SourceRange(TheCall->getArg(2)->getLocStart(),
440                      (*(TheCall->arg_end()-1))->getLocEnd());
441     return true;
442   }
443 
444   if (TheCall->getNumArgs() < 2) {
445     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
446       << 0 /*function call*/;
447   }
448 
449   // Determine whether the current function is variadic or not.
450   bool isVariadic;
451   if (CurBlock)
452     isVariadic = CurBlock->isVariadic;
453   else if (getCurFunctionDecl()) {
454     if (FunctionProtoType* FTP =
455             dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
456       isVariadic = FTP->isVariadic();
457     else
458       isVariadic = false;
459   } else {
460     isVariadic = getCurMethodDecl()->isVariadic();
461   }
462 
463   if (!isVariadic) {
464     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
465     return true;
466   }
467 
468   // Verify that the second argument to the builtin is the last argument of the
469   // current function or method.
470   bool SecondArgIsLastNamedArgument = false;
471   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
472 
473   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
474     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
475       // FIXME: This isn't correct for methods (results in bogus warning).
476       // Get the last formal in the current function.
477       const ParmVarDecl *LastArg;
478       if (CurBlock)
479         LastArg = *(CurBlock->TheDecl->param_end()-1);
480       else if (FunctionDecl *FD = getCurFunctionDecl())
481         LastArg = *(FD->param_end()-1);
482       else
483         LastArg = *(getCurMethodDecl()->param_end()-1);
484       SecondArgIsLastNamedArgument = PV == LastArg;
485     }
486   }
487 
488   if (!SecondArgIsLastNamedArgument)
489     Diag(TheCall->getArg(1)->getLocStart(),
490          diag::warn_second_parameter_of_va_start_not_last_named_argument);
491   return false;
492 }
493 
494 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
495 /// friends.  This is declared to take (...), so we have to check everything.
496 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
497   if (TheCall->getNumArgs() < 2)
498     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
499       << 0 /*function call*/;
500   if (TheCall->getNumArgs() > 2)
501     return Diag(TheCall->getArg(2)->getLocStart(),
502                 diag::err_typecheck_call_too_many_args)
503       << 0 /*function call*/
504       << SourceRange(TheCall->getArg(2)->getLocStart(),
505                      (*(TheCall->arg_end()-1))->getLocEnd());
506 
507   Expr *OrigArg0 = TheCall->getArg(0);
508   Expr *OrigArg1 = TheCall->getArg(1);
509 
510   // Do standard promotions between the two arguments, returning their common
511   // type.
512   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
513 
514   // Make sure any conversions are pushed back into the call; this is
515   // type safe since unordered compare builtins are declared as "_Bool
516   // foo(...)".
517   TheCall->setArg(0, OrigArg0);
518   TheCall->setArg(1, OrigArg1);
519 
520   if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
521     return false;
522 
523   // If the common type isn't a real floating type, then the arguments were
524   // invalid for this operation.
525   if (!Res->isRealFloatingType())
526     return Diag(OrigArg0->getLocStart(),
527                 diag::err_typecheck_call_invalid_ordered_compare)
528       << OrigArg0->getType() << OrigArg1->getType()
529       << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
530 
531   return false;
532 }
533 
534 bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
535   // The signature for these builtins is exact; the only thing we need
536   // to check is that the argument is a constant.
537   SourceLocation Loc;
538   if (!TheCall->getArg(0)->isTypeDependent() &&
539       !TheCall->getArg(0)->isValueDependent() &&
540       !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
541     return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
542 
543   return false;
544 }
545 
546 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
547 // This is declared to take (...), so we have to check everything.
548 Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
549   if (TheCall->getNumArgs() < 3)
550     return ExprError(Diag(TheCall->getLocEnd(),
551                           diag::err_typecheck_call_too_few_args)
552       << 0 /*function call*/ << TheCall->getSourceRange());
553 
554   unsigned numElements = std::numeric_limits<unsigned>::max();
555   if (!TheCall->getArg(0)->isTypeDependent() &&
556       !TheCall->getArg(1)->isTypeDependent()) {
557     QualType FAType = TheCall->getArg(0)->getType();
558     QualType SAType = TheCall->getArg(1)->getType();
559 
560     if (!FAType->isVectorType() || !SAType->isVectorType()) {
561       Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
562         << SourceRange(TheCall->getArg(0)->getLocStart(),
563                        TheCall->getArg(1)->getLocEnd());
564       return ExprError();
565     }
566 
567     if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
568         Context.getCanonicalType(SAType).getUnqualifiedType()) {
569       Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
570         << SourceRange(TheCall->getArg(0)->getLocStart(),
571                        TheCall->getArg(1)->getLocEnd());
572       return ExprError();
573     }
574 
575     numElements = FAType->getAsVectorType()->getNumElements();
576     if (TheCall->getNumArgs() != numElements+2) {
577       if (TheCall->getNumArgs() < numElements+2)
578         return ExprError(Diag(TheCall->getLocEnd(),
579                               diag::err_typecheck_call_too_few_args)
580                  << 0 /*function call*/ << TheCall->getSourceRange());
581       return ExprError(Diag(TheCall->getLocEnd(),
582                             diag::err_typecheck_call_too_many_args)
583                  << 0 /*function call*/ << TheCall->getSourceRange());
584     }
585   }
586 
587   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
588     if (TheCall->getArg(i)->isTypeDependent() ||
589         TheCall->getArg(i)->isValueDependent())
590       continue;
591 
592     llvm::APSInt Result(32);
593     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
594       return ExprError(Diag(TheCall->getLocStart(),
595                   diag::err_shufflevector_nonconstant_argument)
596                 << TheCall->getArg(i)->getSourceRange());
597 
598     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
599       return ExprError(Diag(TheCall->getLocStart(),
600                   diag::err_shufflevector_argument_too_large)
601                << TheCall->getArg(i)->getSourceRange());
602   }
603 
604   llvm::SmallVector<Expr*, 32> exprs;
605 
606   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
607     exprs.push_back(TheCall->getArg(i));
608     TheCall->setArg(i, 0);
609   }
610 
611   return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), exprs.size(),
612                                                exprs[0]->getType(),
613                                             TheCall->getCallee()->getLocStart(),
614                                             TheCall->getRParenLoc()));
615 }
616 
617 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
618 // This is declared to take (const void*, ...) and can take two
619 // optional constant int args.
620 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
621   unsigned NumArgs = TheCall->getNumArgs();
622 
623   if (NumArgs > 3)
624     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
625              << 0 /*function call*/ << TheCall->getSourceRange();
626 
627   // Argument 0 is checked for us and the remaining arguments must be
628   // constant integers.
629   for (unsigned i = 1; i != NumArgs; ++i) {
630     Expr *Arg = TheCall->getArg(i);
631     if (Arg->isTypeDependent())
632       continue;
633 
634     QualType RWType = Arg->getType();
635 
636     const BuiltinType *BT = RWType->getAsBuiltinType();
637     llvm::APSInt Result;
638     if (!BT || BT->getKind() != BuiltinType::Int)
639       return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
640               << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
641 
642     if (Arg->isValueDependent())
643       continue;
644 
645     if (!Arg->isIntegerConstantExpr(Result, Context))
646       return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
647         << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
648 
649     // FIXME: gcc issues a warning and rewrites these to 0. These
650     // seems especially odd for the third argument since the default
651     // is 3.
652     if (i == 1) {
653       if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
654         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
655              << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
656     } else {
657       if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
658         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
659             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
660     }
661   }
662 
663   return false;
664 }
665 
666 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
667 /// int type). This simply type checks that type is one of the defined
668 /// constants (0-3).
669 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
670   Expr *Arg = TheCall->getArg(1);
671   if (Arg->isTypeDependent())
672     return false;
673 
674   QualType ArgType = Arg->getType();
675   const BuiltinType *BT = ArgType->getAsBuiltinType();
676   llvm::APSInt Result(32);
677   if (!BT || BT->getKind() != BuiltinType::Int)
678     return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
679              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
680 
681   if (Arg->isValueDependent())
682     return false;
683 
684   if (!Arg->isIntegerConstantExpr(Result, Context)) {
685     return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
686              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
687   }
688 
689   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
690     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
691              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
692   }
693 
694   return false;
695 }
696 
697 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
698 /// This checks that val is a constant 1.
699 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
700   Expr *Arg = TheCall->getArg(1);
701   if (Arg->isTypeDependent() || Arg->isValueDependent())
702     return false;
703 
704   llvm::APSInt Result(32);
705   if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
706     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
707              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
708 
709   return false;
710 }
711 
712 // Handle i > 1 ? "x" : "y", recursivelly
713 bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
714                                   bool HasVAListArg,
715                                   unsigned format_idx, unsigned firstDataArg) {
716   if (E->isTypeDependent() || E->isValueDependent())
717     return false;
718 
719   switch (E->getStmtClass()) {
720   case Stmt::ConditionalOperatorClass: {
721     const ConditionalOperator *C = cast<ConditionalOperator>(E);
722     return SemaCheckStringLiteral(C->getLHS(), TheCall,
723                                   HasVAListArg, format_idx, firstDataArg)
724         && SemaCheckStringLiteral(C->getRHS(), TheCall,
725                                   HasVAListArg, format_idx, firstDataArg);
726   }
727 
728   case Stmt::ImplicitCastExprClass: {
729     const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
730     return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
731                                   format_idx, firstDataArg);
732   }
733 
734   case Stmt::ParenExprClass: {
735     const ParenExpr *Expr = cast<ParenExpr>(E);
736     return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
737                                   format_idx, firstDataArg);
738   }
739 
740   case Stmt::DeclRefExprClass: {
741     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
742 
743     // As an exception, do not flag errors for variables binding to
744     // const string literals.
745     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
746       bool isConstant = false;
747       QualType T = DR->getType();
748 
749       if (const ArrayType *AT = Context.getAsArrayType(T)) {
750         isConstant = AT->getElementType().isConstant(Context);
751       }
752       else if (const PointerType *PT = T->getAsPointerType()) {
753         isConstant = T.isConstant(Context) &&
754                      PT->getPointeeType().isConstant(Context);
755       }
756 
757       if (isConstant) {
758         const VarDecl *Def = 0;
759         if (const Expr *Init = VD->getDefinition(Def))
760           return SemaCheckStringLiteral(Init, TheCall,
761                                         HasVAListArg, format_idx, firstDataArg);
762       }
763     }
764 
765     return false;
766   }
767 
768   case Stmt::ObjCStringLiteralClass:
769   case Stmt::StringLiteralClass: {
770     const StringLiteral *StrE = NULL;
771 
772     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
773       StrE = ObjCFExpr->getString();
774     else
775       StrE = cast<StringLiteral>(E);
776 
777     if (StrE) {
778       CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
779                         firstDataArg);
780       return true;
781     }
782 
783     return false;
784   }
785 
786   default:
787     return false;
788   }
789 }
790 
791 void
792 Sema::CheckNonNullArguments(const NonNullAttr *NonNull, const CallExpr *TheCall)
793 {
794   for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
795        i != e; ++i) {
796     const Expr *ArgExpr = TheCall->getArg(*i);
797     if (ArgExpr->isNullPointerConstant(Context))
798       Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
799         << ArgExpr->getSourceRange();
800   }
801 }
802 
803 /// CheckPrintfArguments - Check calls to printf (and similar functions) for
804 /// correct use of format strings.
805 ///
806 ///  HasVAListArg - A predicate indicating whether the printf-like
807 ///    function is passed an explicit va_arg argument (e.g., vprintf)
808 ///
809 ///  format_idx - The index into Args for the format string.
810 ///
811 /// Improper format strings to functions in the printf family can be
812 /// the source of bizarre bugs and very serious security holes.  A
813 /// good source of information is available in the following paper
814 /// (which includes additional references):
815 ///
816 ///  FormatGuard: Automatic Protection From printf Format String
817 ///  Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
818 ///
819 /// Functionality implemented:
820 ///
821 ///  We can statically check the following properties for string
822 ///  literal format strings for non v.*printf functions (where the
823 ///  arguments are passed directly):
824 //
825 ///  (1) Are the number of format conversions equal to the number of
826 ///      data arguments?
827 ///
828 ///  (2) Does each format conversion correctly match the type of the
829 ///      corresponding data argument?  (TODO)
830 ///
831 /// Moreover, for all printf functions we can:
832 ///
833 ///  (3) Check for a missing format string (when not caught by type checking).
834 ///
835 ///  (4) Check for no-operation flags; e.g. using "#" with format
836 ///      conversion 'c'  (TODO)
837 ///
838 ///  (5) Check the use of '%n', a major source of security holes.
839 ///
840 ///  (6) Check for malformed format conversions that don't specify anything.
841 ///
842 ///  (7) Check for empty format strings.  e.g: printf("");
843 ///
844 ///  (8) Check that the format string is a wide literal.
845 ///
846 ///  (9) Also check the arguments of functions with the __format__ attribute.
847 ///      (TODO).
848 ///
849 /// All of these checks can be done by parsing the format string.
850 ///
851 /// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
852 void
853 Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
854                            unsigned format_idx, unsigned firstDataArg) {
855   const Expr *Fn = TheCall->getCallee();
856 
857   // CHECK: printf-like function is called with no format string.
858   if (format_idx >= TheCall->getNumArgs()) {
859     Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
860       << Fn->getSourceRange();
861     return;
862   }
863 
864   const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
865 
866   // CHECK: format string is not a string literal.
867   //
868   // Dynamically generated format strings are difficult to
869   // automatically vet at compile time.  Requiring that format strings
870   // are string literals: (1) permits the checking of format strings by
871   // the compiler and thereby (2) can practically remove the source of
872   // many format string exploits.
873 
874   // Format string can be either ObjC string (e.g. @"%d") or
875   // C string (e.g. "%d")
876   // ObjC string uses the same format specifiers as C string, so we can use
877   // the same format string checking logic for both ObjC and C strings.
878   if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
879                              firstDataArg))
880     return;  // Literal format string found, check done!
881 
882   // For vprintf* functions (i.e., HasVAListArg==true), we add a
883   // special check to see if the format string is a function parameter
884   // of the function calling the printf function.  If the function
885   // has an attribute indicating it is a printf-like function, then we
886   // should suppress warnings concerning non-literals being used in a call
887   // to a vprintf function.  For example:
888   //
889   // void
890   // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
891   //      va_list ap;
892   //      va_start(ap, fmt);
893   //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
894   //      ...
895   //
896   //
897   //  FIXME: We don't have full attribute support yet, so just check to see
898   //    if the argument is a DeclRefExpr that references a parameter.  We'll
899   //    add proper support for checking the attribute later.
900   if (HasVAListArg)
901     if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
902       if (isa<ParmVarDecl>(DR->getDecl()))
903         return;
904 
905   // If there are no arguments specified, warn with -Wformat-security, otherwise
906   // warn only with -Wformat-nonliteral.
907   if (TheCall->getNumArgs() == format_idx+1)
908     Diag(TheCall->getArg(format_idx)->getLocStart(),
909          diag::warn_printf_nonliteral_noargs)
910       << OrigFormatExpr->getSourceRange();
911   else
912     Diag(TheCall->getArg(format_idx)->getLocStart(),
913          diag::warn_printf_nonliteral)
914            << OrigFormatExpr->getSourceRange();
915 }
916 
917 void Sema::CheckPrintfString(const StringLiteral *FExpr,
918                              const Expr *OrigFormatExpr,
919                              const CallExpr *TheCall, bool HasVAListArg,
920                              unsigned format_idx, unsigned firstDataArg) {
921 
922   const ObjCStringLiteral *ObjCFExpr =
923     dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
924 
925   // CHECK: is the format string a wide literal?
926   if (FExpr->isWide()) {
927     Diag(FExpr->getLocStart(),
928          diag::warn_printf_format_string_is_wide_literal)
929       << OrigFormatExpr->getSourceRange();
930     return;
931   }
932 
933   // Str - The format string.  NOTE: this is NOT null-terminated!
934   const char *Str = FExpr->getStrData();
935 
936   // CHECK: empty format string?
937   unsigned StrLen = FExpr->getByteLength();
938 
939   if (StrLen == 0) {
940     Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
941       << OrigFormatExpr->getSourceRange();
942     return;
943   }
944 
945   // We process the format string using a binary state machine.  The
946   // current state is stored in CurrentState.
947   enum {
948     state_OrdChr,
949     state_Conversion
950   } CurrentState = state_OrdChr;
951 
952   // numConversions - The number of conversions seen so far.  This is
953   //  incremented as we traverse the format string.
954   unsigned numConversions = 0;
955 
956   // numDataArgs - The number of data arguments after the format
957   //  string.  This can only be determined for non vprintf-like
958   //  functions.  For those functions, this value is 1 (the sole
959   //  va_arg argument).
960   unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
961 
962   // Inspect the format string.
963   unsigned StrIdx = 0;
964 
965   // LastConversionIdx - Index within the format string where we last saw
966   //  a '%' character that starts a new format conversion.
967   unsigned LastConversionIdx = 0;
968 
969   for (; StrIdx < StrLen; ++StrIdx) {
970 
971     // Is the number of detected conversion conversions greater than
972     // the number of matching data arguments?  If so, stop.
973     if (!HasVAListArg && numConversions > numDataArgs) break;
974 
975     // Handle "\0"
976     if (Str[StrIdx] == '\0') {
977       // The string returned by getStrData() is not null-terminated,
978       // so the presence of a null character is likely an error.
979       Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
980            diag::warn_printf_format_string_contains_null_char)
981         <<  OrigFormatExpr->getSourceRange();
982       return;
983     }
984 
985     // Ordinary characters (not processing a format conversion).
986     if (CurrentState == state_OrdChr) {
987       if (Str[StrIdx] == '%') {
988         CurrentState = state_Conversion;
989         LastConversionIdx = StrIdx;
990       }
991       continue;
992     }
993 
994     // Seen '%'.  Now processing a format conversion.
995     switch (Str[StrIdx]) {
996     // Handle dynamic precision or width specifier.
997     case '*': {
998       ++numConversions;
999 
1000       if (!HasVAListArg) {
1001         if (numConversions > numDataArgs) {
1002           SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
1003 
1004           if (Str[StrIdx-1] == '.')
1005             Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1006               << OrigFormatExpr->getSourceRange();
1007           else
1008             Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1009               << OrigFormatExpr->getSourceRange();
1010 
1011           // Don't do any more checking.  We'll just emit spurious errors.
1012           return;
1013         }
1014 
1015         // Perform type checking on width/precision specifier.
1016         const Expr *E = TheCall->getArg(format_idx+numConversions);
1017         if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
1018           if (BT->getKind() == BuiltinType::Int)
1019             break;
1020 
1021         SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
1022 
1023         if (Str[StrIdx-1] == '.')
1024           Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1025           << E->getType() << E->getSourceRange();
1026         else
1027           Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1028           << E->getType() << E->getSourceRange();
1029 
1030         break;
1031       }
1032     }
1033 
1034     // Characters which can terminate a format conversion
1035     // (e.g. "%d").  Characters that specify length modifiers or
1036     // other flags are handled by the default case below.
1037     //
1038     // FIXME: additional checks will go into the following cases.
1039     case 'i':
1040     case 'd':
1041     case 'o':
1042     case 'u':
1043     case 'x':
1044     case 'X':
1045     case 'D':
1046     case 'O':
1047     case 'U':
1048     case 'e':
1049     case 'E':
1050     case 'f':
1051     case 'F':
1052     case 'g':
1053     case 'G':
1054     case 'a':
1055     case 'A':
1056     case 'c':
1057     case 'C':
1058     case 'S':
1059     case 's':
1060     case 'p':
1061       ++numConversions;
1062       CurrentState = state_OrdChr;
1063       break;
1064 
1065     case 'm':
1066       // FIXME: Warn in situations where this isn't supported!
1067       CurrentState = state_OrdChr;
1068       break;
1069 
1070     // CHECK: Are we using "%n"?  Issue a warning.
1071     case 'n': {
1072       ++numConversions;
1073       CurrentState = state_OrdChr;
1074       SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1075                                                           LastConversionIdx);
1076 
1077       Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
1078       break;
1079     }
1080 
1081     // Handle "%@"
1082     case '@':
1083       // %@ is allowed in ObjC format strings only.
1084       if(ObjCFExpr != NULL)
1085         CurrentState = state_OrdChr;
1086       else {
1087         // Issue a warning: invalid format conversion.
1088         SourceLocation Loc =
1089           getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1090 
1091         Diag(Loc, diag::warn_printf_invalid_conversion)
1092           <<  std::string(Str+LastConversionIdx,
1093                           Str+std::min(LastConversionIdx+2, StrLen))
1094           << OrigFormatExpr->getSourceRange();
1095       }
1096       ++numConversions;
1097       break;
1098 
1099     // Handle "%%"
1100     case '%':
1101       // Sanity check: Was the first "%" character the previous one?
1102       // If not, we will assume that we have a malformed format
1103       // conversion, and that the current "%" character is the start
1104       // of a new conversion.
1105       if (StrIdx - LastConversionIdx == 1)
1106         CurrentState = state_OrdChr;
1107       else {
1108         // Issue a warning: invalid format conversion.
1109         SourceLocation Loc =
1110           getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1111 
1112         Diag(Loc, diag::warn_printf_invalid_conversion)
1113           << std::string(Str+LastConversionIdx, Str+StrIdx)
1114           << OrigFormatExpr->getSourceRange();
1115 
1116         // This conversion is broken.  Advance to the next format
1117         // conversion.
1118         LastConversionIdx = StrIdx;
1119         ++numConversions;
1120       }
1121       break;
1122 
1123     default:
1124       // This case catches all other characters: flags, widths, etc.
1125       // We should eventually process those as well.
1126       break;
1127     }
1128   }
1129 
1130   if (CurrentState == state_Conversion) {
1131     // Issue a warning: invalid format conversion.
1132     SourceLocation Loc =
1133       getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1134 
1135     Diag(Loc, diag::warn_printf_invalid_conversion)
1136       << std::string(Str+LastConversionIdx,
1137                      Str+std::min(LastConversionIdx+2, StrLen))
1138       << OrigFormatExpr->getSourceRange();
1139     return;
1140   }
1141 
1142   if (!HasVAListArg) {
1143     // CHECK: Does the number of format conversions exceed the number
1144     //        of data arguments?
1145     if (numConversions > numDataArgs) {
1146       SourceLocation Loc =
1147         getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1148 
1149       Diag(Loc, diag::warn_printf_insufficient_data_args)
1150         << OrigFormatExpr->getSourceRange();
1151     }
1152     // CHECK: Does the number of data arguments exceed the number of
1153     //        format conversions in the format string?
1154     else if (numConversions < numDataArgs)
1155       Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
1156            diag::warn_printf_too_many_data_args)
1157         << OrigFormatExpr->getSourceRange();
1158   }
1159 }
1160 
1161 //===--- CHECK: Return Address of Stack Variable --------------------------===//
1162 
1163 static DeclRefExpr* EvalVal(Expr *E);
1164 static DeclRefExpr* EvalAddr(Expr* E);
1165 
1166 /// CheckReturnStackAddr - Check if a return statement returns the address
1167 ///   of a stack variable.
1168 void
1169 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1170                            SourceLocation ReturnLoc) {
1171 
1172   // Perform checking for returned stack addresses.
1173   if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1174     if (DeclRefExpr *DR = EvalAddr(RetValExp))
1175       Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
1176        << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1177 
1178     // Skip over implicit cast expressions when checking for block expressions.
1179     if (ImplicitCastExpr *IcExpr =
1180           dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1181       RetValExp = IcExpr->getSubExpr();
1182 
1183     if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
1184       if (C->hasBlockDeclRefExprs())
1185         Diag(C->getLocStart(), diag::err_ret_local_block)
1186           << C->getSourceRange();
1187   }
1188   // Perform checking for stack values returned by reference.
1189   else if (lhsType->isReferenceType()) {
1190     // Check for a reference to the stack
1191     if (DeclRefExpr *DR = EvalVal(RetValExp))
1192       Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
1193         << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1194   }
1195 }
1196 
1197 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1198 ///  check if the expression in a return statement evaluates to an address
1199 ///  to a location on the stack.  The recursion is used to traverse the
1200 ///  AST of the return expression, with recursion backtracking when we
1201 ///  encounter a subexpression that (1) clearly does not lead to the address
1202 ///  of a stack variable or (2) is something we cannot determine leads to
1203 ///  the address of a stack variable based on such local checking.
1204 ///
1205 ///  EvalAddr processes expressions that are pointers that are used as
1206 ///  references (and not L-values).  EvalVal handles all other values.
1207 ///  At the base case of the recursion is a check for a DeclRefExpr* in
1208 ///  the refers to a stack variable.
1209 ///
1210 ///  This implementation handles:
1211 ///
1212 ///   * pointer-to-pointer casts
1213 ///   * implicit conversions from array references to pointers
1214 ///   * taking the address of fields
1215 ///   * arbitrary interplay between "&" and "*" operators
1216 ///   * pointer arithmetic from an address of a stack variable
1217 ///   * taking the address of an array element where the array is on the stack
1218 static DeclRefExpr* EvalAddr(Expr *E) {
1219   // We should only be called for evaluating pointer expressions.
1220   assert((E->getType()->isPointerType() ||
1221           E->getType()->isBlockPointerType() ||
1222           E->getType()->isObjCQualifiedIdType()) &&
1223          "EvalAddr only works on pointers");
1224 
1225   // Our "symbolic interpreter" is just a dispatch off the currently
1226   // viewed AST node.  We then recursively traverse the AST by calling
1227   // EvalAddr and EvalVal appropriately.
1228   switch (E->getStmtClass()) {
1229   case Stmt::ParenExprClass:
1230     // Ignore parentheses.
1231     return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
1232 
1233   case Stmt::UnaryOperatorClass: {
1234     // The only unary operator that make sense to handle here
1235     // is AddrOf.  All others don't make sense as pointers.
1236     UnaryOperator *U = cast<UnaryOperator>(E);
1237 
1238     if (U->getOpcode() == UnaryOperator::AddrOf)
1239       return EvalVal(U->getSubExpr());
1240     else
1241       return NULL;
1242   }
1243 
1244   case Stmt::BinaryOperatorClass: {
1245     // Handle pointer arithmetic.  All other binary operators are not valid
1246     // in this context.
1247     BinaryOperator *B = cast<BinaryOperator>(E);
1248     BinaryOperator::Opcode op = B->getOpcode();
1249 
1250     if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1251       return NULL;
1252 
1253     Expr *Base = B->getLHS();
1254 
1255     // Determine which argument is the real pointer base.  It could be
1256     // the RHS argument instead of the LHS.
1257     if (!Base->getType()->isPointerType()) Base = B->getRHS();
1258 
1259     assert (Base->getType()->isPointerType());
1260     return EvalAddr(Base);
1261   }
1262 
1263   // For conditional operators we need to see if either the LHS or RHS are
1264   // valid DeclRefExpr*s.  If one of them is valid, we return it.
1265   case Stmt::ConditionalOperatorClass: {
1266     ConditionalOperator *C = cast<ConditionalOperator>(E);
1267 
1268     // Handle the GNU extension for missing LHS.
1269     if (Expr *lhsExpr = C->getLHS())
1270       if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1271         return LHS;
1272 
1273      return EvalAddr(C->getRHS());
1274   }
1275 
1276   // For casts, we need to handle conversions from arrays to
1277   // pointer values, and pointer-to-pointer conversions.
1278   case Stmt::ImplicitCastExprClass:
1279   case Stmt::CStyleCastExprClass:
1280   case Stmt::CXXFunctionalCastExprClass: {
1281     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1282     QualType T = SubExpr->getType();
1283 
1284     if (SubExpr->getType()->isPointerType() ||
1285         SubExpr->getType()->isBlockPointerType() ||
1286         SubExpr->getType()->isObjCQualifiedIdType())
1287       return EvalAddr(SubExpr);
1288     else if (T->isArrayType())
1289       return EvalVal(SubExpr);
1290     else
1291       return 0;
1292   }
1293 
1294   // C++ casts.  For dynamic casts, static casts, and const casts, we
1295   // are always converting from a pointer-to-pointer, so we just blow
1296   // through the cast.  In the case the dynamic cast doesn't fail (and
1297   // return NULL), we take the conservative route and report cases
1298   // where we return the address of a stack variable.  For Reinterpre
1299   // FIXME: The comment about is wrong; we're not always converting
1300   // from pointer to pointer. I'm guessing that this code should also
1301   // handle references to objects.
1302   case Stmt::CXXStaticCastExprClass:
1303   case Stmt::CXXDynamicCastExprClass:
1304   case Stmt::CXXConstCastExprClass:
1305   case Stmt::CXXReinterpretCastExprClass: {
1306       Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
1307       if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
1308         return EvalAddr(S);
1309       else
1310         return NULL;
1311   }
1312 
1313   // Everything else: we simply don't reason about them.
1314   default:
1315     return NULL;
1316   }
1317 }
1318 
1319 
1320 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
1321 ///   See the comments for EvalAddr for more details.
1322 static DeclRefExpr* EvalVal(Expr *E) {
1323 
1324   // We should only be called for evaluating non-pointer expressions, or
1325   // expressions with a pointer type that are not used as references but instead
1326   // are l-values (e.g., DeclRefExpr with a pointer type).
1327 
1328   // Our "symbolic interpreter" is just a dispatch off the currently
1329   // viewed AST node.  We then recursively traverse the AST by calling
1330   // EvalAddr and EvalVal appropriately.
1331   switch (E->getStmtClass()) {
1332   case Stmt::DeclRefExprClass:
1333   case Stmt::QualifiedDeclRefExprClass: {
1334     // DeclRefExpr: the base case.  When we hit a DeclRefExpr we are looking
1335     //  at code that refers to a variable's name.  We check if it has local
1336     //  storage within the function, and if so, return the expression.
1337     DeclRefExpr *DR = cast<DeclRefExpr>(E);
1338 
1339     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1340       if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1341 
1342     return NULL;
1343   }
1344 
1345   case Stmt::ParenExprClass:
1346     // Ignore parentheses.
1347     return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1348 
1349   case Stmt::UnaryOperatorClass: {
1350     // The only unary operator that make sense to handle here
1351     // is Deref.  All others don't resolve to a "name."  This includes
1352     // handling all sorts of rvalues passed to a unary operator.
1353     UnaryOperator *U = cast<UnaryOperator>(E);
1354 
1355     if (U->getOpcode() == UnaryOperator::Deref)
1356       return EvalAddr(U->getSubExpr());
1357 
1358     return NULL;
1359   }
1360 
1361   case Stmt::ArraySubscriptExprClass: {
1362     // Array subscripts are potential references to data on the stack.  We
1363     // retrieve the DeclRefExpr* for the array variable if it indeed
1364     // has local storage.
1365     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
1366   }
1367 
1368   case Stmt::ConditionalOperatorClass: {
1369     // For conditional operators we need to see if either the LHS or RHS are
1370     // non-NULL DeclRefExpr's.  If one is non-NULL, we return it.
1371     ConditionalOperator *C = cast<ConditionalOperator>(E);
1372 
1373     // Handle the GNU extension for missing LHS.
1374     if (Expr *lhsExpr = C->getLHS())
1375       if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1376         return LHS;
1377 
1378     return EvalVal(C->getRHS());
1379   }
1380 
1381   // Accesses to members are potential references to data on the stack.
1382   case Stmt::MemberExprClass: {
1383     MemberExpr *M = cast<MemberExpr>(E);
1384 
1385     // Check for indirect access.  We only want direct field accesses.
1386     if (!M->isArrow())
1387       return EvalVal(M->getBase());
1388     else
1389       return NULL;
1390   }
1391 
1392   // Everything else: we simply don't reason about them.
1393   default:
1394     return NULL;
1395   }
1396 }
1397 
1398 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1399 
1400 /// Check for comparisons of floating point operands using != and ==.
1401 /// Issue a warning if these are no self-comparisons, as they are not likely
1402 /// to do what the programmer intended.
1403 void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1404   bool EmitWarning = true;
1405 
1406   Expr* LeftExprSansParen = lex->IgnoreParens();
1407   Expr* RightExprSansParen = rex->IgnoreParens();
1408 
1409   // Special case: check for x == x (which is OK).
1410   // Do not emit warnings for such cases.
1411   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1412     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1413       if (DRL->getDecl() == DRR->getDecl())
1414         EmitWarning = false;
1415 
1416 
1417   // Special case: check for comparisons against literals that can be exactly
1418   //  represented by APFloat.  In such cases, do not emit a warning.  This
1419   //  is a heuristic: often comparison against such literals are used to
1420   //  detect if a value in a variable has not changed.  This clearly can
1421   //  lead to false negatives.
1422   if (EmitWarning) {
1423     if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1424       if (FLL->isExact())
1425         EmitWarning = false;
1426     }
1427     else
1428       if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1429         if (FLR->isExact())
1430           EmitWarning = false;
1431     }
1432   }
1433 
1434   // Check for comparisons with builtin types.
1435   if (EmitWarning)
1436     if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1437       if (CL->isBuiltinCall(Context))
1438         EmitWarning = false;
1439 
1440   if (EmitWarning)
1441     if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1442       if (CR->isBuiltinCall(Context))
1443         EmitWarning = false;
1444 
1445   // Emit the diagnostic.
1446   if (EmitWarning)
1447     Diag(loc, diag::warn_floatingpoint_eq)
1448       << lex->getSourceRange() << rex->getSourceRange();
1449 }
1450