]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaChecking.cpp
Vendor import of clang RELEASE_360/rc1 tag r226102 (effectively, 3.6.0 RC1):
[FreeBSD/FreeBSD.git] / lib / Sema / SemaChecking.cpp
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 "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <limits>
41 using namespace clang;
42 using namespace sema;
43
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                     unsigned ByteNo) const {
46   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47                                Context.getTargetInfo());
48 }
49
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking.  Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53   unsigned argCount = call->getNumArgs();
54   if (argCount == desiredArgCount) return false;
55
56   if (argCount < desiredArgCount)
57     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58         << 0 /*function call*/ << desiredArgCount << argCount
59         << call->getSourceRange();
60
61   // Highlight all the excess arguments.
62   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                     call->getArg(argCount - 1)->getLocEnd());
64     
65   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66     << 0 /*function call*/ << desiredArgCount << argCount
67     << call->getArg(1)->getSourceRange();
68 }
69
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73   if (checkArgCount(S, TheCall, 2))
74     return true;
75
76   // First argument should be an integer.
77   Expr *ValArg = TheCall->getArg(0);
78   QualType Ty = ValArg->getType();
79   if (!Ty->isIntegerType()) {
80     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81       << ValArg->getSourceRange();
82     return true;
83   }
84
85   // Second argument should be a constant string.
86   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88   if (!Literal || !Literal->isAscii()) {
89     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90       << StrArg->getSourceRange();
91     return true;
92   }
93
94   TheCall->setType(Ty);
95   return false;
96 }
97
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101   if (checkArgCount(S, TheCall, 1))
102     return true;
103
104   ExprResult Arg(TheCall->getArg(0));
105   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106   if (ResultType.isNull())
107     return true;
108
109   TheCall->setArg(0, Arg.get());
110   TheCall->setType(ResultType);
111   return false;
112 }
113
114 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115                                   CallExpr *TheCall, unsigned SizeIdx,
116                                   unsigned DstSizeIdx) {
117   if (TheCall->getNumArgs() <= SizeIdx ||
118       TheCall->getNumArgs() <= DstSizeIdx)
119     return;
120
121   const Expr *SizeArg = TheCall->getArg(SizeIdx);
122   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124   llvm::APSInt Size, DstSize;
125
126   // find out if both sizes are known at compile time
127   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129     return;
130
131   if (Size.ule(DstSize))
132     return;
133
134   // confirmed overflow so generate the diagnostic.
135   IdentifierInfo *FnName = FDecl->getIdentifier();
136   SourceLocation SL = TheCall->getLocStart();
137   SourceRange SR = TheCall->getSourceRange();
138
139   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140 }
141
142 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143   if (checkArgCount(S, BuiltinCall, 2))
144     return true;
145
146   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148   Expr *Call = BuiltinCall->getArg(0);
149   Expr *Chain = BuiltinCall->getArg(1);
150
151   if (Call->getStmtClass() != Stmt::CallExprClass) {
152     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153         << Call->getSourceRange();
154     return true;
155   }
156
157   auto CE = cast<CallExpr>(Call);
158   if (CE->getCallee()->getType()->isBlockPointerType()) {
159     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160         << Call->getSourceRange();
161     return true;
162   }
163
164   const Decl *TargetDecl = CE->getCalleeDecl();
165   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166     if (FD->getBuiltinID()) {
167       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168           << Call->getSourceRange();
169       return true;
170     }
171
172   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174         << Call->getSourceRange();
175     return true;
176   }
177
178   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179   if (ChainResult.isInvalid())
180     return true;
181   if (!ChainResult.get()->getType()->isPointerType()) {
182     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183         << Chain->getSourceRange();
184     return true;
185   }
186
187   QualType ReturnTy = CE->getCallReturnType();
188   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189   QualType BuiltinTy = S.Context.getFunctionType(
190       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192
193   Builtin =
194       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195
196   BuiltinCall->setType(CE->getType());
197   BuiltinCall->setValueKind(CE->getValueKind());
198   BuiltinCall->setObjectKind(CE->getObjectKind());
199   BuiltinCall->setCallee(Builtin);
200   BuiltinCall->setArg(1, ChainResult.get());
201
202   return false;
203 }
204
205 ExprResult
206 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
207                                CallExpr *TheCall) {
208   ExprResult TheCallResult(TheCall);
209
210   // Find out if any arguments are required to be integer constant expressions.
211   unsigned ICEArguments = 0;
212   ASTContext::GetBuiltinTypeError Error;
213   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
214   if (Error != ASTContext::GE_None)
215     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
216   
217   // If any arguments are required to be ICE's, check and diagnose.
218   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
219     // Skip arguments not required to be ICE's.
220     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
221     
222     llvm::APSInt Result;
223     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
224       return true;
225     ICEArguments &= ~(1 << ArgNo);
226   }
227   
228   switch (BuiltinID) {
229   case Builtin::BI__builtin___CFStringMakeConstantString:
230     assert(TheCall->getNumArgs() == 1 &&
231            "Wrong # arguments to builtin CFStringMakeConstantString");
232     if (CheckObjCString(TheCall->getArg(0)))
233       return ExprError();
234     break;
235   case Builtin::BI__builtin_stdarg_start:
236   case Builtin::BI__builtin_va_start:
237     if (SemaBuiltinVAStart(TheCall))
238       return ExprError();
239     break;
240   case Builtin::BI__va_start: {
241     switch (Context.getTargetInfo().getTriple().getArch()) {
242     case llvm::Triple::arm:
243     case llvm::Triple::thumb:
244       if (SemaBuiltinVAStartARM(TheCall))
245         return ExprError();
246       break;
247     default:
248       if (SemaBuiltinVAStart(TheCall))
249         return ExprError();
250       break;
251     }
252     break;
253   }
254   case Builtin::BI__builtin_isgreater:
255   case Builtin::BI__builtin_isgreaterequal:
256   case Builtin::BI__builtin_isless:
257   case Builtin::BI__builtin_islessequal:
258   case Builtin::BI__builtin_islessgreater:
259   case Builtin::BI__builtin_isunordered:
260     if (SemaBuiltinUnorderedCompare(TheCall))
261       return ExprError();
262     break;
263   case Builtin::BI__builtin_fpclassify:
264     if (SemaBuiltinFPClassification(TheCall, 6))
265       return ExprError();
266     break;
267   case Builtin::BI__builtin_isfinite:
268   case Builtin::BI__builtin_isinf:
269   case Builtin::BI__builtin_isinf_sign:
270   case Builtin::BI__builtin_isnan:
271   case Builtin::BI__builtin_isnormal:
272     if (SemaBuiltinFPClassification(TheCall, 1))
273       return ExprError();
274     break;
275   case Builtin::BI__builtin_shufflevector:
276     return SemaBuiltinShuffleVector(TheCall);
277     // TheCall will be freed by the smart pointer here, but that's fine, since
278     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
279   case Builtin::BI__builtin_prefetch:
280     if (SemaBuiltinPrefetch(TheCall))
281       return ExprError();
282     break;
283   case Builtin::BI__assume:
284   case Builtin::BI__builtin_assume:
285     if (SemaBuiltinAssume(TheCall))
286       return ExprError();
287     break;
288   case Builtin::BI__builtin_assume_aligned:
289     if (SemaBuiltinAssumeAligned(TheCall))
290       return ExprError();
291     break;
292   case Builtin::BI__builtin_object_size:
293     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
294       return ExprError();
295     break;
296   case Builtin::BI__builtin_longjmp:
297     if (SemaBuiltinLongjmp(TheCall))
298       return ExprError();
299     break;
300
301   case Builtin::BI__builtin_classify_type:
302     if (checkArgCount(*this, TheCall, 1)) return true;
303     TheCall->setType(Context.IntTy);
304     break;
305   case Builtin::BI__builtin_constant_p:
306     if (checkArgCount(*this, TheCall, 1)) return true;
307     TheCall->setType(Context.IntTy);
308     break;
309   case Builtin::BI__sync_fetch_and_add:
310   case Builtin::BI__sync_fetch_and_add_1:
311   case Builtin::BI__sync_fetch_and_add_2:
312   case Builtin::BI__sync_fetch_and_add_4:
313   case Builtin::BI__sync_fetch_and_add_8:
314   case Builtin::BI__sync_fetch_and_add_16:
315   case Builtin::BI__sync_fetch_and_sub:
316   case Builtin::BI__sync_fetch_and_sub_1:
317   case Builtin::BI__sync_fetch_and_sub_2:
318   case Builtin::BI__sync_fetch_and_sub_4:
319   case Builtin::BI__sync_fetch_and_sub_8:
320   case Builtin::BI__sync_fetch_and_sub_16:
321   case Builtin::BI__sync_fetch_and_or:
322   case Builtin::BI__sync_fetch_and_or_1:
323   case Builtin::BI__sync_fetch_and_or_2:
324   case Builtin::BI__sync_fetch_and_or_4:
325   case Builtin::BI__sync_fetch_and_or_8:
326   case Builtin::BI__sync_fetch_and_or_16:
327   case Builtin::BI__sync_fetch_and_and:
328   case Builtin::BI__sync_fetch_and_and_1:
329   case Builtin::BI__sync_fetch_and_and_2:
330   case Builtin::BI__sync_fetch_and_and_4:
331   case Builtin::BI__sync_fetch_and_and_8:
332   case Builtin::BI__sync_fetch_and_and_16:
333   case Builtin::BI__sync_fetch_and_xor:
334   case Builtin::BI__sync_fetch_and_xor_1:
335   case Builtin::BI__sync_fetch_and_xor_2:
336   case Builtin::BI__sync_fetch_and_xor_4:
337   case Builtin::BI__sync_fetch_and_xor_8:
338   case Builtin::BI__sync_fetch_and_xor_16:
339   case Builtin::BI__sync_fetch_and_nand:
340   case Builtin::BI__sync_fetch_and_nand_1:
341   case Builtin::BI__sync_fetch_and_nand_2:
342   case Builtin::BI__sync_fetch_and_nand_4:
343   case Builtin::BI__sync_fetch_and_nand_8:
344   case Builtin::BI__sync_fetch_and_nand_16:
345   case Builtin::BI__sync_add_and_fetch:
346   case Builtin::BI__sync_add_and_fetch_1:
347   case Builtin::BI__sync_add_and_fetch_2:
348   case Builtin::BI__sync_add_and_fetch_4:
349   case Builtin::BI__sync_add_and_fetch_8:
350   case Builtin::BI__sync_add_and_fetch_16:
351   case Builtin::BI__sync_sub_and_fetch:
352   case Builtin::BI__sync_sub_and_fetch_1:
353   case Builtin::BI__sync_sub_and_fetch_2:
354   case Builtin::BI__sync_sub_and_fetch_4:
355   case Builtin::BI__sync_sub_and_fetch_8:
356   case Builtin::BI__sync_sub_and_fetch_16:
357   case Builtin::BI__sync_and_and_fetch:
358   case Builtin::BI__sync_and_and_fetch_1:
359   case Builtin::BI__sync_and_and_fetch_2:
360   case Builtin::BI__sync_and_and_fetch_4:
361   case Builtin::BI__sync_and_and_fetch_8:
362   case Builtin::BI__sync_and_and_fetch_16:
363   case Builtin::BI__sync_or_and_fetch:
364   case Builtin::BI__sync_or_and_fetch_1:
365   case Builtin::BI__sync_or_and_fetch_2:
366   case Builtin::BI__sync_or_and_fetch_4:
367   case Builtin::BI__sync_or_and_fetch_8:
368   case Builtin::BI__sync_or_and_fetch_16:
369   case Builtin::BI__sync_xor_and_fetch:
370   case Builtin::BI__sync_xor_and_fetch_1:
371   case Builtin::BI__sync_xor_and_fetch_2:
372   case Builtin::BI__sync_xor_and_fetch_4:
373   case Builtin::BI__sync_xor_and_fetch_8:
374   case Builtin::BI__sync_xor_and_fetch_16:
375   case Builtin::BI__sync_nand_and_fetch:
376   case Builtin::BI__sync_nand_and_fetch_1:
377   case Builtin::BI__sync_nand_and_fetch_2:
378   case Builtin::BI__sync_nand_and_fetch_4:
379   case Builtin::BI__sync_nand_and_fetch_8:
380   case Builtin::BI__sync_nand_and_fetch_16:
381   case Builtin::BI__sync_val_compare_and_swap:
382   case Builtin::BI__sync_val_compare_and_swap_1:
383   case Builtin::BI__sync_val_compare_and_swap_2:
384   case Builtin::BI__sync_val_compare_and_swap_4:
385   case Builtin::BI__sync_val_compare_and_swap_8:
386   case Builtin::BI__sync_val_compare_and_swap_16:
387   case Builtin::BI__sync_bool_compare_and_swap:
388   case Builtin::BI__sync_bool_compare_and_swap_1:
389   case Builtin::BI__sync_bool_compare_and_swap_2:
390   case Builtin::BI__sync_bool_compare_and_swap_4:
391   case Builtin::BI__sync_bool_compare_and_swap_8:
392   case Builtin::BI__sync_bool_compare_and_swap_16:
393   case Builtin::BI__sync_lock_test_and_set:
394   case Builtin::BI__sync_lock_test_and_set_1:
395   case Builtin::BI__sync_lock_test_and_set_2:
396   case Builtin::BI__sync_lock_test_and_set_4:
397   case Builtin::BI__sync_lock_test_and_set_8:
398   case Builtin::BI__sync_lock_test_and_set_16:
399   case Builtin::BI__sync_lock_release:
400   case Builtin::BI__sync_lock_release_1:
401   case Builtin::BI__sync_lock_release_2:
402   case Builtin::BI__sync_lock_release_4:
403   case Builtin::BI__sync_lock_release_8:
404   case Builtin::BI__sync_lock_release_16:
405   case Builtin::BI__sync_swap:
406   case Builtin::BI__sync_swap_1:
407   case Builtin::BI__sync_swap_2:
408   case Builtin::BI__sync_swap_4:
409   case Builtin::BI__sync_swap_8:
410   case Builtin::BI__sync_swap_16:
411     return SemaBuiltinAtomicOverloaded(TheCallResult);
412 #define BUILTIN(ID, TYPE, ATTRS)
413 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
414   case Builtin::BI##ID: \
415     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
416 #include "clang/Basic/Builtins.def"
417   case Builtin::BI__builtin_annotation:
418     if (SemaBuiltinAnnotation(*this, TheCall))
419       return ExprError();
420     break;
421   case Builtin::BI__builtin_addressof:
422     if (SemaBuiltinAddressof(*this, TheCall))
423       return ExprError();
424     break;
425   case Builtin::BI__builtin_operator_new:
426   case Builtin::BI__builtin_operator_delete:
427     if (!getLangOpts().CPlusPlus) {
428       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
429         << (BuiltinID == Builtin::BI__builtin_operator_new
430                 ? "__builtin_operator_new"
431                 : "__builtin_operator_delete")
432         << "C++";
433       return ExprError();
434     }
435     // CodeGen assumes it can find the global new and delete to call,
436     // so ensure that they are declared.
437     DeclareGlobalNewDelete();
438     break;
439
440   // check secure string manipulation functions where overflows
441   // are detectable at compile time
442   case Builtin::BI__builtin___memcpy_chk:
443   case Builtin::BI__builtin___memmove_chk:
444   case Builtin::BI__builtin___memset_chk:
445   case Builtin::BI__builtin___strlcat_chk:
446   case Builtin::BI__builtin___strlcpy_chk:
447   case Builtin::BI__builtin___strncat_chk:
448   case Builtin::BI__builtin___strncpy_chk:
449   case Builtin::BI__builtin___stpncpy_chk:
450     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
451     break;
452   case Builtin::BI__builtin___memccpy_chk:
453     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
454     break;
455   case Builtin::BI__builtin___snprintf_chk:
456   case Builtin::BI__builtin___vsnprintf_chk:
457     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
458     break;
459
460   case Builtin::BI__builtin_call_with_static_chain:
461     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
462       return ExprError();
463     break;
464   }
465
466   // Since the target specific builtins for each arch overlap, only check those
467   // of the arch we are compiling for.
468   if (BuiltinID >= Builtin::FirstTSBuiltin) {
469     switch (Context.getTargetInfo().getTriple().getArch()) {
470       case llvm::Triple::arm:
471       case llvm::Triple::armeb:
472       case llvm::Triple::thumb:
473       case llvm::Triple::thumbeb:
474         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
475           return ExprError();
476         break;
477       case llvm::Triple::aarch64:
478       case llvm::Triple::aarch64_be:
479         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
480           return ExprError();
481         break;
482       case llvm::Triple::mips:
483       case llvm::Triple::mipsel:
484       case llvm::Triple::mips64:
485       case llvm::Triple::mips64el:
486         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
487           return ExprError();
488         break;
489       case llvm::Triple::x86:
490       case llvm::Triple::x86_64:
491         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
492           return ExprError();
493         break;
494       default:
495         break;
496     }
497   }
498
499   return TheCallResult;
500 }
501
502 // Get the valid immediate range for the specified NEON type code.
503 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
504   NeonTypeFlags Type(t);
505   int IsQuad = ForceQuad ? true : Type.isQuad();
506   switch (Type.getEltType()) {
507   case NeonTypeFlags::Int8:
508   case NeonTypeFlags::Poly8:
509     return shift ? 7 : (8 << IsQuad) - 1;
510   case NeonTypeFlags::Int16:
511   case NeonTypeFlags::Poly16:
512     return shift ? 15 : (4 << IsQuad) - 1;
513   case NeonTypeFlags::Int32:
514     return shift ? 31 : (2 << IsQuad) - 1;
515   case NeonTypeFlags::Int64:
516   case NeonTypeFlags::Poly64:
517     return shift ? 63 : (1 << IsQuad) - 1;
518   case NeonTypeFlags::Poly128:
519     return shift ? 127 : (1 << IsQuad) - 1;
520   case NeonTypeFlags::Float16:
521     assert(!shift && "cannot shift float types!");
522     return (4 << IsQuad) - 1;
523   case NeonTypeFlags::Float32:
524     assert(!shift && "cannot shift float types!");
525     return (2 << IsQuad) - 1;
526   case NeonTypeFlags::Float64:
527     assert(!shift && "cannot shift float types!");
528     return (1 << IsQuad) - 1;
529   }
530   llvm_unreachable("Invalid NeonTypeFlag!");
531 }
532
533 /// getNeonEltType - Return the QualType corresponding to the elements of
534 /// the vector type specified by the NeonTypeFlags.  This is used to check
535 /// the pointer arguments for Neon load/store intrinsics.
536 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
537                                bool IsPolyUnsigned, bool IsInt64Long) {
538   switch (Flags.getEltType()) {
539   case NeonTypeFlags::Int8:
540     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
541   case NeonTypeFlags::Int16:
542     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
543   case NeonTypeFlags::Int32:
544     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
545   case NeonTypeFlags::Int64:
546     if (IsInt64Long)
547       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
548     else
549       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
550                                 : Context.LongLongTy;
551   case NeonTypeFlags::Poly8:
552     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
553   case NeonTypeFlags::Poly16:
554     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
555   case NeonTypeFlags::Poly64:
556     return Context.UnsignedLongTy;
557   case NeonTypeFlags::Poly128:
558     break;
559   case NeonTypeFlags::Float16:
560     return Context.HalfTy;
561   case NeonTypeFlags::Float32:
562     return Context.FloatTy;
563   case NeonTypeFlags::Float64:
564     return Context.DoubleTy;
565   }
566   llvm_unreachable("Invalid NeonTypeFlag!");
567 }
568
569 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
570   llvm::APSInt Result;
571   uint64_t mask = 0;
572   unsigned TV = 0;
573   int PtrArgNum = -1;
574   bool HasConstPtr = false;
575   switch (BuiltinID) {
576 #define GET_NEON_OVERLOAD_CHECK
577 #include "clang/Basic/arm_neon.inc"
578 #undef GET_NEON_OVERLOAD_CHECK
579   }
580
581   // For NEON intrinsics which are overloaded on vector element type, validate
582   // the immediate which specifies which variant to emit.
583   unsigned ImmArg = TheCall->getNumArgs()-1;
584   if (mask) {
585     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
586       return true;
587
588     TV = Result.getLimitedValue(64);
589     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
590       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
591         << TheCall->getArg(ImmArg)->getSourceRange();
592   }
593
594   if (PtrArgNum >= 0) {
595     // Check that pointer arguments have the specified type.
596     Expr *Arg = TheCall->getArg(PtrArgNum);
597     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
598       Arg = ICE->getSubExpr();
599     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
600     QualType RHSTy = RHS.get()->getType();
601
602     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
603     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
604     bool IsInt64Long =
605         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
606     QualType EltTy =
607         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
608     if (HasConstPtr)
609       EltTy = EltTy.withConst();
610     QualType LHSTy = Context.getPointerType(EltTy);
611     AssignConvertType ConvTy;
612     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
613     if (RHS.isInvalid())
614       return true;
615     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
616                                  RHS.get(), AA_Assigning))
617       return true;
618   }
619
620   // For NEON intrinsics which take an immediate value as part of the
621   // instruction, range check them here.
622   unsigned i = 0, l = 0, u = 0;
623   switch (BuiltinID) {
624   default:
625     return false;
626 #define GET_NEON_IMMEDIATE_CHECK
627 #include "clang/Basic/arm_neon.inc"
628 #undef GET_NEON_IMMEDIATE_CHECK
629   }
630
631   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
632 }
633
634 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
635                                         unsigned MaxWidth) {
636   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
637           BuiltinID == ARM::BI__builtin_arm_ldaex ||
638           BuiltinID == ARM::BI__builtin_arm_strex ||
639           BuiltinID == ARM::BI__builtin_arm_stlex ||
640           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
641           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
642           BuiltinID == AArch64::BI__builtin_arm_strex ||
643           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
644          "unexpected ARM builtin");
645   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
646                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
647                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
648                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
649
650   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
651
652   // Ensure that we have the proper number of arguments.
653   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
654     return true;
655
656   // Inspect the pointer argument of the atomic builtin.  This should always be
657   // a pointer type, whose element is an integral scalar or pointer type.
658   // Because it is a pointer type, we don't have to worry about any implicit
659   // casts here.
660   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
661   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
662   if (PointerArgRes.isInvalid())
663     return true;
664   PointerArg = PointerArgRes.get();
665
666   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
667   if (!pointerType) {
668     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
669       << PointerArg->getType() << PointerArg->getSourceRange();
670     return true;
671   }
672
673   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
674   // task is to insert the appropriate casts into the AST. First work out just
675   // what the appropriate type is.
676   QualType ValType = pointerType->getPointeeType();
677   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
678   if (IsLdrex)
679     AddrType.addConst();
680
681   // Issue a warning if the cast is dodgy.
682   CastKind CastNeeded = CK_NoOp;
683   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
684     CastNeeded = CK_BitCast;
685     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
686       << PointerArg->getType()
687       << Context.getPointerType(AddrType)
688       << AA_Passing << PointerArg->getSourceRange();
689   }
690
691   // Finally, do the cast and replace the argument with the corrected version.
692   AddrType = Context.getPointerType(AddrType);
693   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
694   if (PointerArgRes.isInvalid())
695     return true;
696   PointerArg = PointerArgRes.get();
697
698   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
699
700   // In general, we allow ints, floats and pointers to be loaded and stored.
701   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
702       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
703     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
704       << PointerArg->getType() << PointerArg->getSourceRange();
705     return true;
706   }
707
708   // But ARM doesn't have instructions to deal with 128-bit versions.
709   if (Context.getTypeSize(ValType) > MaxWidth) {
710     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
711     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
712       << PointerArg->getType() << PointerArg->getSourceRange();
713     return true;
714   }
715
716   switch (ValType.getObjCLifetime()) {
717   case Qualifiers::OCL_None:
718   case Qualifiers::OCL_ExplicitNone:
719     // okay
720     break;
721
722   case Qualifiers::OCL_Weak:
723   case Qualifiers::OCL_Strong:
724   case Qualifiers::OCL_Autoreleasing:
725     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
726       << ValType << PointerArg->getSourceRange();
727     return true;
728   }
729
730
731   if (IsLdrex) {
732     TheCall->setType(ValType);
733     return false;
734   }
735
736   // Initialize the argument to be stored.
737   ExprResult ValArg = TheCall->getArg(0);
738   InitializedEntity Entity = InitializedEntity::InitializeParameter(
739       Context, ValType, /*consume*/ false);
740   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
741   if (ValArg.isInvalid())
742     return true;
743   TheCall->setArg(0, ValArg.get());
744
745   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
746   // but the custom checker bypasses all default analysis.
747   TheCall->setType(Context.IntTy);
748   return false;
749 }
750
751 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
752   llvm::APSInt Result;
753
754   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
755       BuiltinID == ARM::BI__builtin_arm_ldaex ||
756       BuiltinID == ARM::BI__builtin_arm_strex ||
757       BuiltinID == ARM::BI__builtin_arm_stlex) {
758     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
759   }
760
761   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
762     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
763       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
764   }
765
766   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
767     return true;
768
769   // For intrinsics which take an immediate value as part of the instruction,
770   // range check them here.
771   unsigned i = 0, l = 0, u = 0;
772   switch (BuiltinID) {
773   default: return false;
774   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
775   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
776   case ARM::BI__builtin_arm_vcvtr_f:
777   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
778   case ARM::BI__builtin_arm_dmb:
779   case ARM::BI__builtin_arm_dsb:
780   case ARM::BI__builtin_arm_isb:
781   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
782   }
783
784   // FIXME: VFP Intrinsics should error if VFP not present.
785   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
786 }
787
788 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
789                                          CallExpr *TheCall) {
790   llvm::APSInt Result;
791
792   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
793       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
794       BuiltinID == AArch64::BI__builtin_arm_strex ||
795       BuiltinID == AArch64::BI__builtin_arm_stlex) {
796     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
797   }
798
799   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
800     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
802       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
803       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
804   }
805
806   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
807     return true;
808
809   // For intrinsics which take an immediate value as part of the instruction,
810   // range check them here.
811   unsigned i = 0, l = 0, u = 0;
812   switch (BuiltinID) {
813   default: return false;
814   case AArch64::BI__builtin_arm_dmb:
815   case AArch64::BI__builtin_arm_dsb:
816   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
817   }
818
819   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
820 }
821
822 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
823   unsigned i = 0, l = 0, u = 0;
824   switch (BuiltinID) {
825   default: return false;
826   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
827   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
828   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
829   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
830   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
831   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
832   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
833   }
834
835   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
836 }
837
838 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
839   unsigned i = 0, l = 0, u = 0;
840   switch (BuiltinID) {
841   default: return false;
842   case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
843   case X86::BI__builtin_ia32_cmpps:
844   case X86::BI__builtin_ia32_cmpss:
845   case X86::BI__builtin_ia32_cmppd:
846   case X86::BI__builtin_ia32_cmpsd: i = 2; l = 0; u = 31; break;
847   }
848   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
849 }
850
851 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
852 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
853 /// Returns true when the format fits the function and the FormatStringInfo has
854 /// been populated.
855 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
856                                FormatStringInfo *FSI) {
857   FSI->HasVAListArg = Format->getFirstArg() == 0;
858   FSI->FormatIdx = Format->getFormatIdx() - 1;
859   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
860
861   // The way the format attribute works in GCC, the implicit this argument
862   // of member functions is counted. However, it doesn't appear in our own
863   // lists, so decrement format_idx in that case.
864   if (IsCXXMember) {
865     if(FSI->FormatIdx == 0)
866       return false;
867     --FSI->FormatIdx;
868     if (FSI->FirstDataArg != 0)
869       --FSI->FirstDataArg;
870   }
871   return true;
872 }
873
874 /// Checks if a the given expression evaluates to null.
875 ///
876 /// \brief Returns true if the value evaluates to null.
877 static bool CheckNonNullExpr(Sema &S,
878                              const Expr *Expr) {
879   // As a special case, transparent unions initialized with zero are
880   // considered null for the purposes of the nonnull attribute.
881   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
882     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
883       if (const CompoundLiteralExpr *CLE =
884           dyn_cast<CompoundLiteralExpr>(Expr))
885         if (const InitListExpr *ILE =
886             dyn_cast<InitListExpr>(CLE->getInitializer()))
887           Expr = ILE->getInit(0);
888   }
889
890   bool Result;
891   return (!Expr->isValueDependent() &&
892           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
893           !Result);
894 }
895
896 static void CheckNonNullArgument(Sema &S,
897                                  const Expr *ArgExpr,
898                                  SourceLocation CallSiteLoc) {
899   if (CheckNonNullExpr(S, ArgExpr))
900     S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
901 }
902
903 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
904   FormatStringInfo FSI;
905   if ((GetFormatStringType(Format) == FST_NSString) &&
906       getFormatStringInfo(Format, false, &FSI)) {
907     Idx = FSI.FormatIdx;
908     return true;
909   }
910   return false;
911 }
912 /// \brief Diagnose use of %s directive in an NSString which is being passed
913 /// as formatting string to formatting method.
914 static void
915 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
916                                         const NamedDecl *FDecl,
917                                         Expr **Args,
918                                         unsigned NumArgs) {
919   unsigned Idx = 0;
920   bool Format = false;
921   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
922   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
923     Idx = 2;
924     Format = true;
925   }
926   else
927     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
928       if (S.GetFormatNSStringIdx(I, Idx)) {
929         Format = true;
930         break;
931       }
932     }
933   if (!Format || NumArgs <= Idx)
934     return;
935   const Expr *FormatExpr = Args[Idx];
936   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
937     FormatExpr = CSCE->getSubExpr();
938   const StringLiteral *FormatString;
939   if (const ObjCStringLiteral *OSL =
940       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
941     FormatString = OSL->getString();
942   else
943     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
944   if (!FormatString)
945     return;
946   if (S.FormatStringHasSArg(FormatString)) {
947     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
948       << "%s" << 1 << 1;
949     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
950       << FDecl->getDeclName();
951   }
952 }
953
954 static void CheckNonNullArguments(Sema &S,
955                                   const NamedDecl *FDecl,
956                                   ArrayRef<const Expr *> Args,
957                                   SourceLocation CallSiteLoc) {
958   // Check the attributes attached to the method/function itself.
959   llvm::SmallBitVector NonNullArgs;
960   for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
961     if (!NonNull->args_size()) {
962       // Easy case: all pointer arguments are nonnull.
963       for (const auto *Arg : Args)
964         if (S.isValidPointerAttrType(Arg->getType()))
965           CheckNonNullArgument(S, Arg, CallSiteLoc);
966       return;
967     }
968
969     for (unsigned Val : NonNull->args()) {
970       if (Val >= Args.size())
971         continue;
972       if (NonNullArgs.empty())
973         NonNullArgs.resize(Args.size());
974       NonNullArgs.set(Val);
975     }
976   }
977
978   // Check the attributes on the parameters.
979   ArrayRef<ParmVarDecl*> parms;
980   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
981     parms = FD->parameters();
982   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
983     parms = MD->parameters();
984
985   unsigned ArgIndex = 0;
986   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
987        I != E; ++I, ++ArgIndex) {
988     const ParmVarDecl *PVD = *I;
989     if (PVD->hasAttr<NonNullAttr>() ||
990         (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
991       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
992   }
993
994   // In case this is a variadic call, check any remaining arguments.
995   for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
996     if (NonNullArgs[ArgIndex])
997       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
998 }
999
1000 /// Handles the checks for format strings, non-POD arguments to vararg
1001 /// functions, and NULL arguments passed to non-NULL parameters.
1002 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1003                      unsigned NumParams, bool IsMemberFunction,
1004                      SourceLocation Loc, SourceRange Range,
1005                      VariadicCallType CallType) {
1006   // FIXME: We should check as much as we can in the template definition.
1007   if (CurContext->isDependentContext())
1008     return;
1009
1010   // Printf and scanf checking.
1011   llvm::SmallBitVector CheckedVarArgs;
1012   if (FDecl) {
1013     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1014       // Only create vector if there are format attributes.
1015       CheckedVarArgs.resize(Args.size());
1016
1017       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1018                            CheckedVarArgs);
1019     }
1020   }
1021
1022   // Refuse POD arguments that weren't caught by the format string
1023   // checks above.
1024   if (CallType != VariadicDoesNotApply) {
1025     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1026       // Args[ArgIdx] can be null in malformed code.
1027       if (const Expr *Arg = Args[ArgIdx]) {
1028         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1029           checkVariadicArgument(Arg, CallType);
1030       }
1031     }
1032   }
1033
1034   if (FDecl) {
1035     CheckNonNullArguments(*this, FDecl, Args, Loc);
1036
1037     // Type safety checking.
1038     for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1039       CheckArgumentWithTypeTag(I, Args.data());
1040   }
1041 }
1042
1043 /// CheckConstructorCall - Check a constructor call for correctness and safety
1044 /// properties not enforced by the C type system.
1045 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1046                                 ArrayRef<const Expr *> Args,
1047                                 const FunctionProtoType *Proto,
1048                                 SourceLocation Loc) {
1049   VariadicCallType CallType =
1050     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1051   checkCall(FDecl, Args, Proto->getNumParams(),
1052             /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1053 }
1054
1055 /// CheckFunctionCall - Check a direct function call for various correctness
1056 /// and safety properties not strictly enforced by the C type system.
1057 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1058                              const FunctionProtoType *Proto) {
1059   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1060                               isa<CXXMethodDecl>(FDecl);
1061   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1062                           IsMemberOperatorCall;
1063   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1064                                                   TheCall->getCallee());
1065   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1066   Expr** Args = TheCall->getArgs();
1067   unsigned NumArgs = TheCall->getNumArgs();
1068   if (IsMemberOperatorCall) {
1069     // If this is a call to a member operator, hide the first argument
1070     // from checkCall.
1071     // FIXME: Our choice of AST representation here is less than ideal.
1072     ++Args;
1073     --NumArgs;
1074   }
1075   checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
1076             IsMemberFunction, TheCall->getRParenLoc(),
1077             TheCall->getCallee()->getSourceRange(), CallType);
1078
1079   IdentifierInfo *FnInfo = FDecl->getIdentifier();
1080   // None of the checks below are needed for functions that don't have
1081   // simple names (e.g., C++ conversion functions).
1082   if (!FnInfo)
1083     return false;
1084
1085   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1086   if (getLangOpts().ObjC1)
1087     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1088
1089   unsigned CMId = FDecl->getMemoryFunctionKind();
1090   if (CMId == 0)
1091     return false;
1092
1093   // Handle memory setting and copying functions.
1094   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1095     CheckStrlcpycatArguments(TheCall, FnInfo);
1096   else if (CMId == Builtin::BIstrncat)
1097     CheckStrncatArguments(TheCall, FnInfo);
1098   else
1099     CheckMemaccessArguments(TheCall, CMId, FnInfo);
1100
1101   return false;
1102 }
1103
1104 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 
1105                                ArrayRef<const Expr *> Args) {
1106   VariadicCallType CallType =
1107       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1108
1109   checkCall(Method, Args, Method->param_size(),
1110             /*IsMemberFunction=*/false,
1111             lbrac, Method->getSourceRange(), CallType);
1112
1113   return false;
1114 }
1115
1116 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1117                             const FunctionProtoType *Proto) {
1118   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1119   if (!V)
1120     return false;
1121
1122   QualType Ty = V->getType();
1123   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
1124     return false;
1125
1126   VariadicCallType CallType;
1127   if (!Proto || !Proto->isVariadic()) {
1128     CallType = VariadicDoesNotApply;
1129   } else if (Ty->isBlockPointerType()) {
1130     CallType = VariadicBlock;
1131   } else { // Ty->isFunctionPointerType()
1132     CallType = VariadicFunction;
1133   }
1134   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1135
1136   checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1137                                       TheCall->getNumArgs()),
1138             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1139             TheCall->getCallee()->getSourceRange(), CallType);
1140
1141   return false;
1142 }
1143
1144 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1145 /// such as function pointers returned from functions.
1146 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1147   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1148                                                   TheCall->getCallee());
1149   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1150
1151   checkCall(/*FDecl=*/nullptr,
1152             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1153             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1154             TheCall->getCallee()->getSourceRange(), CallType);
1155
1156   return false;
1157 }
1158
1159 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1160   if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1161       Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1162     return false;
1163
1164   switch (Op) {
1165   case AtomicExpr::AO__c11_atomic_init:
1166     llvm_unreachable("There is no ordering argument for an init");
1167
1168   case AtomicExpr::AO__c11_atomic_load:
1169   case AtomicExpr::AO__atomic_load_n:
1170   case AtomicExpr::AO__atomic_load:
1171     return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1172            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1173
1174   case AtomicExpr::AO__c11_atomic_store:
1175   case AtomicExpr::AO__atomic_store:
1176   case AtomicExpr::AO__atomic_store_n:
1177     return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1178            Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1179            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1180
1181   default:
1182     return true;
1183   }
1184 }
1185
1186 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1187                                          AtomicExpr::AtomicOp Op) {
1188   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1189   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1190
1191   // All these operations take one of the following forms:
1192   enum {
1193     // C    __c11_atomic_init(A *, C)
1194     Init,
1195     // C    __c11_atomic_load(A *, int)
1196     Load,
1197     // void __atomic_load(A *, CP, int)
1198     Copy,
1199     // C    __c11_atomic_add(A *, M, int)
1200     Arithmetic,
1201     // C    __atomic_exchange_n(A *, CP, int)
1202     Xchg,
1203     // void __atomic_exchange(A *, C *, CP, int)
1204     GNUXchg,
1205     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1206     C11CmpXchg,
1207     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1208     GNUCmpXchg
1209   } Form = Init;
1210   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1211   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1212   // where:
1213   //   C is an appropriate type,
1214   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1215   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1216   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1217   //   the int parameters are for orderings.
1218
1219   assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1220          AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1221          && "need to update code for modified C11 atomics");
1222   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1223                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1224   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1225              Op == AtomicExpr::AO__atomic_store_n ||
1226              Op == AtomicExpr::AO__atomic_exchange_n ||
1227              Op == AtomicExpr::AO__atomic_compare_exchange_n;
1228   bool IsAddSub = false;
1229
1230   switch (Op) {
1231   case AtomicExpr::AO__c11_atomic_init:
1232     Form = Init;
1233     break;
1234
1235   case AtomicExpr::AO__c11_atomic_load:
1236   case AtomicExpr::AO__atomic_load_n:
1237     Form = Load;
1238     break;
1239
1240   case AtomicExpr::AO__c11_atomic_store:
1241   case AtomicExpr::AO__atomic_load:
1242   case AtomicExpr::AO__atomic_store:
1243   case AtomicExpr::AO__atomic_store_n:
1244     Form = Copy;
1245     break;
1246
1247   case AtomicExpr::AO__c11_atomic_fetch_add:
1248   case AtomicExpr::AO__c11_atomic_fetch_sub:
1249   case AtomicExpr::AO__atomic_fetch_add:
1250   case AtomicExpr::AO__atomic_fetch_sub:
1251   case AtomicExpr::AO__atomic_add_fetch:
1252   case AtomicExpr::AO__atomic_sub_fetch:
1253     IsAddSub = true;
1254     // Fall through.
1255   case AtomicExpr::AO__c11_atomic_fetch_and:
1256   case AtomicExpr::AO__c11_atomic_fetch_or:
1257   case AtomicExpr::AO__c11_atomic_fetch_xor:
1258   case AtomicExpr::AO__atomic_fetch_and:
1259   case AtomicExpr::AO__atomic_fetch_or:
1260   case AtomicExpr::AO__atomic_fetch_xor:
1261   case AtomicExpr::AO__atomic_fetch_nand:
1262   case AtomicExpr::AO__atomic_and_fetch:
1263   case AtomicExpr::AO__atomic_or_fetch:
1264   case AtomicExpr::AO__atomic_xor_fetch:
1265   case AtomicExpr::AO__atomic_nand_fetch:
1266     Form = Arithmetic;
1267     break;
1268
1269   case AtomicExpr::AO__c11_atomic_exchange:
1270   case AtomicExpr::AO__atomic_exchange_n:
1271     Form = Xchg;
1272     break;
1273
1274   case AtomicExpr::AO__atomic_exchange:
1275     Form = GNUXchg;
1276     break;
1277
1278   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1279   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1280     Form = C11CmpXchg;
1281     break;
1282
1283   case AtomicExpr::AO__atomic_compare_exchange:
1284   case AtomicExpr::AO__atomic_compare_exchange_n:
1285     Form = GNUCmpXchg;
1286     break;
1287   }
1288
1289   // Check we have the right number of arguments.
1290   if (TheCall->getNumArgs() < NumArgs[Form]) {
1291     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1292       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1293       << TheCall->getCallee()->getSourceRange();
1294     return ExprError();
1295   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1296     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1297          diag::err_typecheck_call_too_many_args)
1298       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1299       << TheCall->getCallee()->getSourceRange();
1300     return ExprError();
1301   }
1302
1303   // Inspect the first argument of the atomic operation.
1304   Expr *Ptr = TheCall->getArg(0);
1305   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1306   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1307   if (!pointerType) {
1308     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1309       << Ptr->getType() << Ptr->getSourceRange();
1310     return ExprError();
1311   }
1312
1313   // For a __c11 builtin, this should be a pointer to an _Atomic type.
1314   QualType AtomTy = pointerType->getPointeeType(); // 'A'
1315   QualType ValType = AtomTy; // 'C'
1316   if (IsC11) {
1317     if (!AtomTy->isAtomicType()) {
1318       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1319         << Ptr->getType() << Ptr->getSourceRange();
1320       return ExprError();
1321     }
1322     if (AtomTy.isConstQualified()) {
1323       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1324         << Ptr->getType() << Ptr->getSourceRange();
1325       return ExprError();
1326     }
1327     ValType = AtomTy->getAs<AtomicType>()->getValueType();
1328   }
1329
1330   // For an arithmetic operation, the implied arithmetic must be well-formed.
1331   if (Form == Arithmetic) {
1332     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1333     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1334       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1335         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1336       return ExprError();
1337     }
1338     if (!IsAddSub && !ValType->isIntegerType()) {
1339       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1340         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1341       return ExprError();
1342     }
1343   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1344     // For __atomic_*_n operations, the value type must be a scalar integral or
1345     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1346     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1347       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1348     return ExprError();
1349   }
1350
1351   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1352       !AtomTy->isScalarType()) {
1353     // For GNU atomics, require a trivially-copyable type. This is not part of
1354     // the GNU atomics specification, but we enforce it for sanity.
1355     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1356       << Ptr->getType() << Ptr->getSourceRange();
1357     return ExprError();
1358   }
1359
1360   // FIXME: For any builtin other than a load, the ValType must not be
1361   // const-qualified.
1362
1363   switch (ValType.getObjCLifetime()) {
1364   case Qualifiers::OCL_None:
1365   case Qualifiers::OCL_ExplicitNone:
1366     // okay
1367     break;
1368
1369   case Qualifiers::OCL_Weak:
1370   case Qualifiers::OCL_Strong:
1371   case Qualifiers::OCL_Autoreleasing:
1372     // FIXME: Can this happen? By this point, ValType should be known
1373     // to be trivially copyable.
1374     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1375       << ValType << Ptr->getSourceRange();
1376     return ExprError();
1377   }
1378
1379   QualType ResultType = ValType;
1380   if (Form == Copy || Form == GNUXchg || Form == Init)
1381     ResultType = Context.VoidTy;
1382   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1383     ResultType = Context.BoolTy;
1384
1385   // The type of a parameter passed 'by value'. In the GNU atomics, such
1386   // arguments are actually passed as pointers.
1387   QualType ByValType = ValType; // 'CP'
1388   if (!IsC11 && !IsN)
1389     ByValType = Ptr->getType();
1390
1391   // The first argument --- the pointer --- has a fixed type; we
1392   // deduce the types of the rest of the arguments accordingly.  Walk
1393   // the remaining arguments, converting them to the deduced value type.
1394   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1395     QualType Ty;
1396     if (i < NumVals[Form] + 1) {
1397       switch (i) {
1398       case 1:
1399         // The second argument is the non-atomic operand. For arithmetic, this
1400         // is always passed by value, and for a compare_exchange it is always
1401         // passed by address. For the rest, GNU uses by-address and C11 uses
1402         // by-value.
1403         assert(Form != Load);
1404         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1405           Ty = ValType;
1406         else if (Form == Copy || Form == Xchg)
1407           Ty = ByValType;
1408         else if (Form == Arithmetic)
1409           Ty = Context.getPointerDiffType();
1410         else
1411           Ty = Context.getPointerType(ValType.getUnqualifiedType());
1412         break;
1413       case 2:
1414         // The third argument to compare_exchange / GNU exchange is a
1415         // (pointer to a) desired value.
1416         Ty = ByValType;
1417         break;
1418       case 3:
1419         // The fourth argument to GNU compare_exchange is a 'weak' flag.
1420         Ty = Context.BoolTy;
1421         break;
1422       }
1423     } else {
1424       // The order(s) are always converted to int.
1425       Ty = Context.IntTy;
1426     }
1427
1428     InitializedEntity Entity =
1429         InitializedEntity::InitializeParameter(Context, Ty, false);
1430     ExprResult Arg = TheCall->getArg(i);
1431     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1432     if (Arg.isInvalid())
1433       return true;
1434     TheCall->setArg(i, Arg.get());
1435   }
1436
1437   // Permute the arguments into a 'consistent' order.
1438   SmallVector<Expr*, 5> SubExprs;
1439   SubExprs.push_back(Ptr);
1440   switch (Form) {
1441   case Init:
1442     // Note, AtomicExpr::getVal1() has a special case for this atomic.
1443     SubExprs.push_back(TheCall->getArg(1)); // Val1
1444     break;
1445   case Load:
1446     SubExprs.push_back(TheCall->getArg(1)); // Order
1447     break;
1448   case Copy:
1449   case Arithmetic:
1450   case Xchg:
1451     SubExprs.push_back(TheCall->getArg(2)); // Order
1452     SubExprs.push_back(TheCall->getArg(1)); // Val1
1453     break;
1454   case GNUXchg:
1455     // Note, AtomicExpr::getVal2() has a special case for this atomic.
1456     SubExprs.push_back(TheCall->getArg(3)); // Order
1457     SubExprs.push_back(TheCall->getArg(1)); // Val1
1458     SubExprs.push_back(TheCall->getArg(2)); // Val2
1459     break;
1460   case C11CmpXchg:
1461     SubExprs.push_back(TheCall->getArg(3)); // Order
1462     SubExprs.push_back(TheCall->getArg(1)); // Val1
1463     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1464     SubExprs.push_back(TheCall->getArg(2)); // Val2
1465     break;
1466   case GNUCmpXchg:
1467     SubExprs.push_back(TheCall->getArg(4)); // Order
1468     SubExprs.push_back(TheCall->getArg(1)); // Val1
1469     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1470     SubExprs.push_back(TheCall->getArg(2)); // Val2
1471     SubExprs.push_back(TheCall->getArg(3)); // Weak
1472     break;
1473   }
1474
1475   if (SubExprs.size() >= 2 && Form != Init) {
1476     llvm::APSInt Result(32);
1477     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1478         !isValidOrderingForOp(Result.getSExtValue(), Op))
1479       Diag(SubExprs[1]->getLocStart(),
1480            diag::warn_atomic_op_has_invalid_memory_order)
1481           << SubExprs[1]->getSourceRange();
1482   }
1483
1484   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1485                                             SubExprs, ResultType, Op,
1486                                             TheCall->getRParenLoc());
1487   
1488   if ((Op == AtomicExpr::AO__c11_atomic_load ||
1489        (Op == AtomicExpr::AO__c11_atomic_store)) &&
1490       Context.AtomicUsesUnsupportedLibcall(AE))
1491     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1492     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1493
1494   return AE;
1495 }
1496
1497
1498 /// checkBuiltinArgument - Given a call to a builtin function, perform
1499 /// normal type-checking on the given argument, updating the call in
1500 /// place.  This is useful when a builtin function requires custom
1501 /// type-checking for some of its arguments but not necessarily all of
1502 /// them.
1503 ///
1504 /// Returns true on error.
1505 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1506   FunctionDecl *Fn = E->getDirectCallee();
1507   assert(Fn && "builtin call without direct callee!");
1508
1509   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1510   InitializedEntity Entity =
1511     InitializedEntity::InitializeParameter(S.Context, Param);
1512
1513   ExprResult Arg = E->getArg(0);
1514   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1515   if (Arg.isInvalid())
1516     return true;
1517
1518   E->setArg(ArgIndex, Arg.get());
1519   return false;
1520 }
1521
1522 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1523 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1524 /// type of its first argument.  The main ActOnCallExpr routines have already
1525 /// promoted the types of arguments because all of these calls are prototyped as
1526 /// void(...).
1527 ///
1528 /// This function goes through and does final semantic checking for these
1529 /// builtins,
1530 ExprResult
1531 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1532   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1533   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1534   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1535
1536   // Ensure that we have at least one argument to do type inference from.
1537   if (TheCall->getNumArgs() < 1) {
1538     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1539       << 0 << 1 << TheCall->getNumArgs()
1540       << TheCall->getCallee()->getSourceRange();
1541     return ExprError();
1542   }
1543
1544   // Inspect the first argument of the atomic builtin.  This should always be
1545   // a pointer type, whose element is an integral scalar or pointer type.
1546   // Because it is a pointer type, we don't have to worry about any implicit
1547   // casts here.
1548   // FIXME: We don't allow floating point scalars as input.
1549   Expr *FirstArg = TheCall->getArg(0);
1550   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1551   if (FirstArgResult.isInvalid())
1552     return ExprError();
1553   FirstArg = FirstArgResult.get();
1554   TheCall->setArg(0, FirstArg);
1555
1556   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1557   if (!pointerType) {
1558     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1559       << FirstArg->getType() << FirstArg->getSourceRange();
1560     return ExprError();
1561   }
1562
1563   QualType ValType = pointerType->getPointeeType();
1564   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1565       !ValType->isBlockPointerType()) {
1566     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1567       << FirstArg->getType() << FirstArg->getSourceRange();
1568     return ExprError();
1569   }
1570
1571   switch (ValType.getObjCLifetime()) {
1572   case Qualifiers::OCL_None:
1573   case Qualifiers::OCL_ExplicitNone:
1574     // okay
1575     break;
1576
1577   case Qualifiers::OCL_Weak:
1578   case Qualifiers::OCL_Strong:
1579   case Qualifiers::OCL_Autoreleasing:
1580     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1581       << ValType << FirstArg->getSourceRange();
1582     return ExprError();
1583   }
1584
1585   // Strip any qualifiers off ValType.
1586   ValType = ValType.getUnqualifiedType();
1587
1588   // The majority of builtins return a value, but a few have special return
1589   // types, so allow them to override appropriately below.
1590   QualType ResultType = ValType;
1591
1592   // We need to figure out which concrete builtin this maps onto.  For example,
1593   // __sync_fetch_and_add with a 2 byte object turns into
1594   // __sync_fetch_and_add_2.
1595 #define BUILTIN_ROW(x) \
1596   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1597     Builtin::BI##x##_8, Builtin::BI##x##_16 }
1598
1599   static const unsigned BuiltinIndices[][5] = {
1600     BUILTIN_ROW(__sync_fetch_and_add),
1601     BUILTIN_ROW(__sync_fetch_and_sub),
1602     BUILTIN_ROW(__sync_fetch_and_or),
1603     BUILTIN_ROW(__sync_fetch_and_and),
1604     BUILTIN_ROW(__sync_fetch_and_xor),
1605     BUILTIN_ROW(__sync_fetch_and_nand),
1606
1607     BUILTIN_ROW(__sync_add_and_fetch),
1608     BUILTIN_ROW(__sync_sub_and_fetch),
1609     BUILTIN_ROW(__sync_and_and_fetch),
1610     BUILTIN_ROW(__sync_or_and_fetch),
1611     BUILTIN_ROW(__sync_xor_and_fetch),
1612     BUILTIN_ROW(__sync_nand_and_fetch),
1613
1614     BUILTIN_ROW(__sync_val_compare_and_swap),
1615     BUILTIN_ROW(__sync_bool_compare_and_swap),
1616     BUILTIN_ROW(__sync_lock_test_and_set),
1617     BUILTIN_ROW(__sync_lock_release),
1618     BUILTIN_ROW(__sync_swap)
1619   };
1620 #undef BUILTIN_ROW
1621
1622   // Determine the index of the size.
1623   unsigned SizeIndex;
1624   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1625   case 1: SizeIndex = 0; break;
1626   case 2: SizeIndex = 1; break;
1627   case 4: SizeIndex = 2; break;
1628   case 8: SizeIndex = 3; break;
1629   case 16: SizeIndex = 4; break;
1630   default:
1631     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1632       << FirstArg->getType() << FirstArg->getSourceRange();
1633     return ExprError();
1634   }
1635
1636   // Each of these builtins has one pointer argument, followed by some number of
1637   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1638   // that we ignore.  Find out which row of BuiltinIndices to read from as well
1639   // as the number of fixed args.
1640   unsigned BuiltinID = FDecl->getBuiltinID();
1641   unsigned BuiltinIndex, NumFixed = 1;
1642   bool WarnAboutSemanticsChange = false;
1643   switch (BuiltinID) {
1644   default: llvm_unreachable("Unknown overloaded atomic builtin!");
1645   case Builtin::BI__sync_fetch_and_add: 
1646   case Builtin::BI__sync_fetch_and_add_1:
1647   case Builtin::BI__sync_fetch_and_add_2:
1648   case Builtin::BI__sync_fetch_and_add_4:
1649   case Builtin::BI__sync_fetch_and_add_8:
1650   case Builtin::BI__sync_fetch_and_add_16:
1651     BuiltinIndex = 0; 
1652     break;
1653       
1654   case Builtin::BI__sync_fetch_and_sub: 
1655   case Builtin::BI__sync_fetch_and_sub_1:
1656   case Builtin::BI__sync_fetch_and_sub_2:
1657   case Builtin::BI__sync_fetch_and_sub_4:
1658   case Builtin::BI__sync_fetch_and_sub_8:
1659   case Builtin::BI__sync_fetch_and_sub_16:
1660     BuiltinIndex = 1; 
1661     break;
1662       
1663   case Builtin::BI__sync_fetch_and_or:  
1664   case Builtin::BI__sync_fetch_and_or_1:
1665   case Builtin::BI__sync_fetch_and_or_2:
1666   case Builtin::BI__sync_fetch_and_or_4:
1667   case Builtin::BI__sync_fetch_and_or_8:
1668   case Builtin::BI__sync_fetch_and_or_16:
1669     BuiltinIndex = 2; 
1670     break;
1671       
1672   case Builtin::BI__sync_fetch_and_and: 
1673   case Builtin::BI__sync_fetch_and_and_1:
1674   case Builtin::BI__sync_fetch_and_and_2:
1675   case Builtin::BI__sync_fetch_and_and_4:
1676   case Builtin::BI__sync_fetch_and_and_8:
1677   case Builtin::BI__sync_fetch_and_and_16:
1678     BuiltinIndex = 3; 
1679     break;
1680
1681   case Builtin::BI__sync_fetch_and_xor: 
1682   case Builtin::BI__sync_fetch_and_xor_1:
1683   case Builtin::BI__sync_fetch_and_xor_2:
1684   case Builtin::BI__sync_fetch_and_xor_4:
1685   case Builtin::BI__sync_fetch_and_xor_8:
1686   case Builtin::BI__sync_fetch_and_xor_16:
1687     BuiltinIndex = 4; 
1688     break;
1689
1690   case Builtin::BI__sync_fetch_and_nand: 
1691   case Builtin::BI__sync_fetch_and_nand_1:
1692   case Builtin::BI__sync_fetch_and_nand_2:
1693   case Builtin::BI__sync_fetch_and_nand_4:
1694   case Builtin::BI__sync_fetch_and_nand_8:
1695   case Builtin::BI__sync_fetch_and_nand_16:
1696     BuiltinIndex = 5;
1697     WarnAboutSemanticsChange = true;
1698     break;
1699
1700   case Builtin::BI__sync_add_and_fetch: 
1701   case Builtin::BI__sync_add_and_fetch_1:
1702   case Builtin::BI__sync_add_and_fetch_2:
1703   case Builtin::BI__sync_add_and_fetch_4:
1704   case Builtin::BI__sync_add_and_fetch_8:
1705   case Builtin::BI__sync_add_and_fetch_16:
1706     BuiltinIndex = 6; 
1707     break;
1708       
1709   case Builtin::BI__sync_sub_and_fetch: 
1710   case Builtin::BI__sync_sub_and_fetch_1:
1711   case Builtin::BI__sync_sub_and_fetch_2:
1712   case Builtin::BI__sync_sub_and_fetch_4:
1713   case Builtin::BI__sync_sub_and_fetch_8:
1714   case Builtin::BI__sync_sub_and_fetch_16:
1715     BuiltinIndex = 7; 
1716     break;
1717       
1718   case Builtin::BI__sync_and_and_fetch: 
1719   case Builtin::BI__sync_and_and_fetch_1:
1720   case Builtin::BI__sync_and_and_fetch_2:
1721   case Builtin::BI__sync_and_and_fetch_4:
1722   case Builtin::BI__sync_and_and_fetch_8:
1723   case Builtin::BI__sync_and_and_fetch_16:
1724     BuiltinIndex = 8; 
1725     break;
1726       
1727   case Builtin::BI__sync_or_and_fetch:  
1728   case Builtin::BI__sync_or_and_fetch_1:
1729   case Builtin::BI__sync_or_and_fetch_2:
1730   case Builtin::BI__sync_or_and_fetch_4:
1731   case Builtin::BI__sync_or_and_fetch_8:
1732   case Builtin::BI__sync_or_and_fetch_16:
1733     BuiltinIndex = 9; 
1734     break;
1735       
1736   case Builtin::BI__sync_xor_and_fetch: 
1737   case Builtin::BI__sync_xor_and_fetch_1:
1738   case Builtin::BI__sync_xor_and_fetch_2:
1739   case Builtin::BI__sync_xor_and_fetch_4:
1740   case Builtin::BI__sync_xor_and_fetch_8:
1741   case Builtin::BI__sync_xor_and_fetch_16:
1742     BuiltinIndex = 10;
1743     break;
1744
1745   case Builtin::BI__sync_nand_and_fetch: 
1746   case Builtin::BI__sync_nand_and_fetch_1:
1747   case Builtin::BI__sync_nand_and_fetch_2:
1748   case Builtin::BI__sync_nand_and_fetch_4:
1749   case Builtin::BI__sync_nand_and_fetch_8:
1750   case Builtin::BI__sync_nand_and_fetch_16:
1751     BuiltinIndex = 11;
1752     WarnAboutSemanticsChange = true;
1753     break;
1754
1755   case Builtin::BI__sync_val_compare_and_swap:
1756   case Builtin::BI__sync_val_compare_and_swap_1:
1757   case Builtin::BI__sync_val_compare_and_swap_2:
1758   case Builtin::BI__sync_val_compare_and_swap_4:
1759   case Builtin::BI__sync_val_compare_and_swap_8:
1760   case Builtin::BI__sync_val_compare_and_swap_16:
1761     BuiltinIndex = 12;
1762     NumFixed = 2;
1763     break;
1764       
1765   case Builtin::BI__sync_bool_compare_and_swap:
1766   case Builtin::BI__sync_bool_compare_and_swap_1:
1767   case Builtin::BI__sync_bool_compare_and_swap_2:
1768   case Builtin::BI__sync_bool_compare_and_swap_4:
1769   case Builtin::BI__sync_bool_compare_and_swap_8:
1770   case Builtin::BI__sync_bool_compare_and_swap_16:
1771     BuiltinIndex = 13;
1772     NumFixed = 2;
1773     ResultType = Context.BoolTy;
1774     break;
1775       
1776   case Builtin::BI__sync_lock_test_and_set: 
1777   case Builtin::BI__sync_lock_test_and_set_1:
1778   case Builtin::BI__sync_lock_test_and_set_2:
1779   case Builtin::BI__sync_lock_test_and_set_4:
1780   case Builtin::BI__sync_lock_test_and_set_8:
1781   case Builtin::BI__sync_lock_test_and_set_16:
1782     BuiltinIndex = 14; 
1783     break;
1784       
1785   case Builtin::BI__sync_lock_release:
1786   case Builtin::BI__sync_lock_release_1:
1787   case Builtin::BI__sync_lock_release_2:
1788   case Builtin::BI__sync_lock_release_4:
1789   case Builtin::BI__sync_lock_release_8:
1790   case Builtin::BI__sync_lock_release_16:
1791     BuiltinIndex = 15;
1792     NumFixed = 0;
1793     ResultType = Context.VoidTy;
1794     break;
1795       
1796   case Builtin::BI__sync_swap: 
1797   case Builtin::BI__sync_swap_1:
1798   case Builtin::BI__sync_swap_2:
1799   case Builtin::BI__sync_swap_4:
1800   case Builtin::BI__sync_swap_8:
1801   case Builtin::BI__sync_swap_16:
1802     BuiltinIndex = 16; 
1803     break;
1804   }
1805
1806   // Now that we know how many fixed arguments we expect, first check that we
1807   // have at least that many.
1808   if (TheCall->getNumArgs() < 1+NumFixed) {
1809     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1810       << 0 << 1+NumFixed << TheCall->getNumArgs()
1811       << TheCall->getCallee()->getSourceRange();
1812     return ExprError();
1813   }
1814
1815   if (WarnAboutSemanticsChange) {
1816     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1817       << TheCall->getCallee()->getSourceRange();
1818   }
1819
1820   // Get the decl for the concrete builtin from this, we can tell what the
1821   // concrete integer type we should convert to is.
1822   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1823   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1824   FunctionDecl *NewBuiltinDecl;
1825   if (NewBuiltinID == BuiltinID)
1826     NewBuiltinDecl = FDecl;
1827   else {
1828     // Perform builtin lookup to avoid redeclaring it.
1829     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1830     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1831     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1832     assert(Res.getFoundDecl());
1833     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1834     if (!NewBuiltinDecl)
1835       return ExprError();
1836   }
1837
1838   // The first argument --- the pointer --- has a fixed type; we
1839   // deduce the types of the rest of the arguments accordingly.  Walk
1840   // the remaining arguments, converting them to the deduced value type.
1841   for (unsigned i = 0; i != NumFixed; ++i) {
1842     ExprResult Arg = TheCall->getArg(i+1);
1843
1844     // GCC does an implicit conversion to the pointer or integer ValType.  This
1845     // can fail in some cases (1i -> int**), check for this error case now.
1846     // Initialize the argument.
1847     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1848                                                    ValType, /*consume*/ false);
1849     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1850     if (Arg.isInvalid())
1851       return ExprError();
1852
1853     // Okay, we have something that *can* be converted to the right type.  Check
1854     // to see if there is a potentially weird extension going on here.  This can
1855     // happen when you do an atomic operation on something like an char* and
1856     // pass in 42.  The 42 gets converted to char.  This is even more strange
1857     // for things like 45.123 -> char, etc.
1858     // FIXME: Do this check.
1859     TheCall->setArg(i+1, Arg.get());
1860   }
1861
1862   ASTContext& Context = this->getASTContext();
1863
1864   // Create a new DeclRefExpr to refer to the new decl.
1865   DeclRefExpr* NewDRE = DeclRefExpr::Create(
1866       Context,
1867       DRE->getQualifierLoc(),
1868       SourceLocation(),
1869       NewBuiltinDecl,
1870       /*enclosing*/ false,
1871       DRE->getLocation(),
1872       Context.BuiltinFnTy,
1873       DRE->getValueKind());
1874
1875   // Set the callee in the CallExpr.
1876   // FIXME: This loses syntactic information.
1877   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1878   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1879                                               CK_BuiltinFnToFnPtr);
1880   TheCall->setCallee(PromotedCall.get());
1881
1882   // Change the result type of the call to match the original value type. This
1883   // is arbitrary, but the codegen for these builtins ins design to handle it
1884   // gracefully.
1885   TheCall->setType(ResultType);
1886
1887   return TheCallResult;
1888 }
1889
1890 /// CheckObjCString - Checks that the argument to the builtin
1891 /// CFString constructor is correct
1892 /// Note: It might also make sense to do the UTF-16 conversion here (would
1893 /// simplify the backend).
1894 bool Sema::CheckObjCString(Expr *Arg) {
1895   Arg = Arg->IgnoreParenCasts();
1896   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1897
1898   if (!Literal || !Literal->isAscii()) {
1899     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1900       << Arg->getSourceRange();
1901     return true;
1902   }
1903
1904   if (Literal->containsNonAsciiOrNull()) {
1905     StringRef String = Literal->getString();
1906     unsigned NumBytes = String.size();
1907     SmallVector<UTF16, 128> ToBuf(NumBytes);
1908     const UTF8 *FromPtr = (const UTF8 *)String.data();
1909     UTF16 *ToPtr = &ToBuf[0];
1910     
1911     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1912                                                  &ToPtr, ToPtr + NumBytes,
1913                                                  strictConversion);
1914     // Check for conversion failure.
1915     if (Result != conversionOK)
1916       Diag(Arg->getLocStart(),
1917            diag::warn_cfstring_truncated) << Arg->getSourceRange();
1918   }
1919   return false;
1920 }
1921
1922 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1923 /// Emit an error and return true on failure, return false on success.
1924 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1925   Expr *Fn = TheCall->getCallee();
1926   if (TheCall->getNumArgs() > 2) {
1927     Diag(TheCall->getArg(2)->getLocStart(),
1928          diag::err_typecheck_call_too_many_args)
1929       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1930       << Fn->getSourceRange()
1931       << SourceRange(TheCall->getArg(2)->getLocStart(),
1932                      (*(TheCall->arg_end()-1))->getLocEnd());
1933     return true;
1934   }
1935
1936   if (TheCall->getNumArgs() < 2) {
1937     return Diag(TheCall->getLocEnd(),
1938       diag::err_typecheck_call_too_few_args_at_least)
1939       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1940   }
1941
1942   // Type-check the first argument normally.
1943   if (checkBuiltinArgument(*this, TheCall, 0))
1944     return true;
1945
1946   // Determine whether the current function is variadic or not.
1947   BlockScopeInfo *CurBlock = getCurBlock();
1948   bool isVariadic;
1949   if (CurBlock)
1950     isVariadic = CurBlock->TheDecl->isVariadic();
1951   else if (FunctionDecl *FD = getCurFunctionDecl())
1952     isVariadic = FD->isVariadic();
1953   else
1954     isVariadic = getCurMethodDecl()->isVariadic();
1955
1956   if (!isVariadic) {
1957     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1958     return true;
1959   }
1960
1961   // Verify that the second argument to the builtin is the last argument of the
1962   // current function or method.
1963   bool SecondArgIsLastNamedArgument = false;
1964   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1965
1966   // These are valid if SecondArgIsLastNamedArgument is false after the next
1967   // block.
1968   QualType Type;
1969   SourceLocation ParamLoc;
1970
1971   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1972     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1973       // FIXME: This isn't correct for methods (results in bogus warning).
1974       // Get the last formal in the current function.
1975       const ParmVarDecl *LastArg;
1976       if (CurBlock)
1977         LastArg = *(CurBlock->TheDecl->param_end()-1);
1978       else if (FunctionDecl *FD = getCurFunctionDecl())
1979         LastArg = *(FD->param_end()-1);
1980       else
1981         LastArg = *(getCurMethodDecl()->param_end()-1);
1982       SecondArgIsLastNamedArgument = PV == LastArg;
1983
1984       Type = PV->getType();
1985       ParamLoc = PV->getLocation();
1986     }
1987   }
1988
1989   if (!SecondArgIsLastNamedArgument)
1990     Diag(TheCall->getArg(1)->getLocStart(),
1991          diag::warn_second_parameter_of_va_start_not_last_named_argument);
1992   else if (Type->isReferenceType()) {
1993     Diag(Arg->getLocStart(),
1994          diag::warn_va_start_of_reference_type_is_undefined);
1995     Diag(ParamLoc, diag::note_parameter_type) << Type;
1996   }
1997
1998   TheCall->setType(Context.VoidTy);
1999   return false;
2000 }
2001
2002 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2003   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2004   //                 const char *named_addr);
2005
2006   Expr *Func = Call->getCallee();
2007
2008   if (Call->getNumArgs() < 3)
2009     return Diag(Call->getLocEnd(),
2010                 diag::err_typecheck_call_too_few_args_at_least)
2011            << 0 /*function call*/ << 3 << Call->getNumArgs();
2012
2013   // Determine whether the current function is variadic or not.
2014   bool IsVariadic;
2015   if (BlockScopeInfo *CurBlock = getCurBlock())
2016     IsVariadic = CurBlock->TheDecl->isVariadic();
2017   else if (FunctionDecl *FD = getCurFunctionDecl())
2018     IsVariadic = FD->isVariadic();
2019   else if (ObjCMethodDecl *MD = getCurMethodDecl())
2020     IsVariadic = MD->isVariadic();
2021   else
2022     llvm_unreachable("unexpected statement type");
2023
2024   if (!IsVariadic) {
2025     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2026     return true;
2027   }
2028
2029   // Type-check the first argument normally.
2030   if (checkBuiltinArgument(*this, Call, 0))
2031     return true;
2032
2033   static const struct {
2034     unsigned ArgNo;
2035     QualType Type;
2036   } ArgumentTypes[] = {
2037     { 1, Context.getPointerType(Context.CharTy.withConst()) },
2038     { 2, Context.getSizeType() },
2039   };
2040
2041   for (const auto &AT : ArgumentTypes) {
2042     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2043     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2044       continue;
2045     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2046       << Arg->getType() << AT.Type << 1 /* different class */
2047       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2048       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2049   }
2050
2051   return false;
2052 }
2053
2054 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2055 /// friends.  This is declared to take (...), so we have to check everything.
2056 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2057   if (TheCall->getNumArgs() < 2)
2058     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2059       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2060   if (TheCall->getNumArgs() > 2)
2061     return Diag(TheCall->getArg(2)->getLocStart(),
2062                 diag::err_typecheck_call_too_many_args)
2063       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2064       << SourceRange(TheCall->getArg(2)->getLocStart(),
2065                      (*(TheCall->arg_end()-1))->getLocEnd());
2066
2067   ExprResult OrigArg0 = TheCall->getArg(0);
2068   ExprResult OrigArg1 = TheCall->getArg(1);
2069
2070   // Do standard promotions between the two arguments, returning their common
2071   // type.
2072   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2073   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2074     return true;
2075
2076   // Make sure any conversions are pushed back into the call; this is
2077   // type safe since unordered compare builtins are declared as "_Bool
2078   // foo(...)".
2079   TheCall->setArg(0, OrigArg0.get());
2080   TheCall->setArg(1, OrigArg1.get());
2081
2082   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2083     return false;
2084
2085   // If the common type isn't a real floating type, then the arguments were
2086   // invalid for this operation.
2087   if (Res.isNull() || !Res->isRealFloatingType())
2088     return Diag(OrigArg0.get()->getLocStart(),
2089                 diag::err_typecheck_call_invalid_ordered_compare)
2090       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2091       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2092
2093   return false;
2094 }
2095
2096 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2097 /// __builtin_isnan and friends.  This is declared to take (...), so we have
2098 /// to check everything. We expect the last argument to be a floating point
2099 /// value.
2100 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2101   if (TheCall->getNumArgs() < NumArgs)
2102     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2103       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2104   if (TheCall->getNumArgs() > NumArgs)
2105     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2106                 diag::err_typecheck_call_too_many_args)
2107       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2108       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2109                      (*(TheCall->arg_end()-1))->getLocEnd());
2110
2111   Expr *OrigArg = TheCall->getArg(NumArgs-1);
2112
2113   if (OrigArg->isTypeDependent())
2114     return false;
2115
2116   // This operation requires a non-_Complex floating-point number.
2117   if (!OrigArg->getType()->isRealFloatingType())
2118     return Diag(OrigArg->getLocStart(),
2119                 diag::err_typecheck_call_invalid_unary_fp)
2120       << OrigArg->getType() << OrigArg->getSourceRange();
2121
2122   // If this is an implicit conversion from float -> double, remove it.
2123   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2124     Expr *CastArg = Cast->getSubExpr();
2125     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2126       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2127              "promotion from float to double is the only expected cast here");
2128       Cast->setSubExpr(nullptr);
2129       TheCall->setArg(NumArgs-1, CastArg);
2130     }
2131   }
2132   
2133   return false;
2134 }
2135
2136 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2137 // This is declared to take (...), so we have to check everything.
2138 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2139   if (TheCall->getNumArgs() < 2)
2140     return ExprError(Diag(TheCall->getLocEnd(),
2141                           diag::err_typecheck_call_too_few_args_at_least)
2142                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2143                      << TheCall->getSourceRange());
2144
2145   // Determine which of the following types of shufflevector we're checking:
2146   // 1) unary, vector mask: (lhs, mask)
2147   // 2) binary, vector mask: (lhs, rhs, mask)
2148   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2149   QualType resType = TheCall->getArg(0)->getType();
2150   unsigned numElements = 0;
2151
2152   if (!TheCall->getArg(0)->isTypeDependent() &&
2153       !TheCall->getArg(1)->isTypeDependent()) {
2154     QualType LHSType = TheCall->getArg(0)->getType();
2155     QualType RHSType = TheCall->getArg(1)->getType();
2156
2157     if (!LHSType->isVectorType() || !RHSType->isVectorType())
2158       return ExprError(Diag(TheCall->getLocStart(),
2159                             diag::err_shufflevector_non_vector)
2160                        << SourceRange(TheCall->getArg(0)->getLocStart(),
2161                                       TheCall->getArg(1)->getLocEnd()));
2162
2163     numElements = LHSType->getAs<VectorType>()->getNumElements();
2164     unsigned numResElements = TheCall->getNumArgs() - 2;
2165
2166     // Check to see if we have a call with 2 vector arguments, the unary shuffle
2167     // with mask.  If so, verify that RHS is an integer vector type with the
2168     // same number of elts as lhs.
2169     if (TheCall->getNumArgs() == 2) {
2170       if (!RHSType->hasIntegerRepresentation() ||
2171           RHSType->getAs<VectorType>()->getNumElements() != numElements)
2172         return ExprError(Diag(TheCall->getLocStart(),
2173                               diag::err_shufflevector_incompatible_vector)
2174                          << SourceRange(TheCall->getArg(1)->getLocStart(),
2175                                         TheCall->getArg(1)->getLocEnd()));
2176     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2177       return ExprError(Diag(TheCall->getLocStart(),
2178                             diag::err_shufflevector_incompatible_vector)
2179                        << SourceRange(TheCall->getArg(0)->getLocStart(),
2180                                       TheCall->getArg(1)->getLocEnd()));
2181     } else if (numElements != numResElements) {
2182       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2183       resType = Context.getVectorType(eltType, numResElements,
2184                                       VectorType::GenericVector);
2185     }
2186   }
2187
2188   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2189     if (TheCall->getArg(i)->isTypeDependent() ||
2190         TheCall->getArg(i)->isValueDependent())
2191       continue;
2192
2193     llvm::APSInt Result(32);
2194     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2195       return ExprError(Diag(TheCall->getLocStart(),
2196                             diag::err_shufflevector_nonconstant_argument)
2197                        << TheCall->getArg(i)->getSourceRange());
2198
2199     // Allow -1 which will be translated to undef in the IR.
2200     if (Result.isSigned() && Result.isAllOnesValue())
2201       continue;
2202
2203     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2204       return ExprError(Diag(TheCall->getLocStart(),
2205                             diag::err_shufflevector_argument_too_large)
2206                        << TheCall->getArg(i)->getSourceRange());
2207   }
2208
2209   SmallVector<Expr*, 32> exprs;
2210
2211   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2212     exprs.push_back(TheCall->getArg(i));
2213     TheCall->setArg(i, nullptr);
2214   }
2215
2216   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2217                                          TheCall->getCallee()->getLocStart(),
2218                                          TheCall->getRParenLoc());
2219 }
2220
2221 /// SemaConvertVectorExpr - Handle __builtin_convertvector
2222 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2223                                        SourceLocation BuiltinLoc,
2224                                        SourceLocation RParenLoc) {
2225   ExprValueKind VK = VK_RValue;
2226   ExprObjectKind OK = OK_Ordinary;
2227   QualType DstTy = TInfo->getType();
2228   QualType SrcTy = E->getType();
2229
2230   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2231     return ExprError(Diag(BuiltinLoc,
2232                           diag::err_convertvector_non_vector)
2233                      << E->getSourceRange());
2234   if (!DstTy->isVectorType() && !DstTy->isDependentType())
2235     return ExprError(Diag(BuiltinLoc,
2236                           diag::err_convertvector_non_vector_type));
2237
2238   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2239     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2240     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2241     if (SrcElts != DstElts)
2242       return ExprError(Diag(BuiltinLoc,
2243                             diag::err_convertvector_incompatible_vector)
2244                        << E->getSourceRange());
2245   }
2246
2247   return new (Context)
2248       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
2249 }
2250
2251 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2252 // This is declared to take (const void*, ...) and can take two
2253 // optional constant int args.
2254 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
2255   unsigned NumArgs = TheCall->getNumArgs();
2256
2257   if (NumArgs > 3)
2258     return Diag(TheCall->getLocEnd(),
2259              diag::err_typecheck_call_too_many_args_at_most)
2260              << 0 /*function call*/ << 3 << NumArgs
2261              << TheCall->getSourceRange();
2262
2263   // Argument 0 is checked for us and the remaining arguments must be
2264   // constant integers.
2265   for (unsigned i = 1; i != NumArgs; ++i)
2266     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2267       return true;
2268
2269   return false;
2270 }
2271
2272 /// SemaBuiltinAssume - Handle __assume (MS Extension).
2273 // __assume does not evaluate its arguments, and should warn if its argument
2274 // has side effects.
2275 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2276   Expr *Arg = TheCall->getArg(0);
2277   if (Arg->isInstantiationDependent()) return false;
2278
2279   if (Arg->HasSideEffects(Context))
2280     return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2281       << Arg->getSourceRange()
2282       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2283
2284   return false;
2285 }
2286
2287 /// Handle __builtin_assume_aligned. This is declared
2288 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2289 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2290   unsigned NumArgs = TheCall->getNumArgs();
2291
2292   if (NumArgs > 3)
2293     return Diag(TheCall->getLocEnd(),
2294              diag::err_typecheck_call_too_many_args_at_most)
2295              << 0 /*function call*/ << 3 << NumArgs
2296              << TheCall->getSourceRange();
2297
2298   // The alignment must be a constant integer.
2299   Expr *Arg = TheCall->getArg(1);
2300
2301   // We can't check the value of a dependent argument.
2302   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2303     llvm::APSInt Result;
2304     if (SemaBuiltinConstantArg(TheCall, 1, Result))
2305       return true;
2306
2307     if (!Result.isPowerOf2())
2308       return Diag(TheCall->getLocStart(),
2309                   diag::err_alignment_not_power_of_two)
2310            << Arg->getSourceRange();
2311   }
2312
2313   if (NumArgs > 2) {
2314     ExprResult Arg(TheCall->getArg(2));
2315     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2316       Context.getSizeType(), false);
2317     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2318     if (Arg.isInvalid()) return true;
2319     TheCall->setArg(2, Arg.get());
2320   }
2321
2322   return false;
2323 }
2324
2325 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2326 /// TheCall is a constant expression.
2327 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2328                                   llvm::APSInt &Result) {
2329   Expr *Arg = TheCall->getArg(ArgNum);
2330   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2331   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2332   
2333   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2334   
2335   if (!Arg->isIntegerConstantExpr(Result, Context))
2336     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
2337                 << FDecl->getDeclName() <<  Arg->getSourceRange();
2338   
2339   return false;
2340 }
2341
2342 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2343 /// TheCall is a constant expression in the range [Low, High].
2344 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2345                                        int Low, int High) {
2346   llvm::APSInt Result;
2347
2348   // We can't check the value of a dependent argument.
2349   Expr *Arg = TheCall->getArg(ArgNum);
2350   if (Arg->isTypeDependent() || Arg->isValueDependent())
2351     return false;
2352
2353   // Check constant-ness first.
2354   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2355     return true;
2356
2357   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2358     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2359       << Low << High << Arg->getSourceRange();
2360
2361   return false;
2362 }
2363
2364 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2365 /// This checks that val is a constant 1.
2366 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2367   Expr *Arg = TheCall->getArg(1);
2368   llvm::APSInt Result;
2369
2370   // TODO: This is less than ideal. Overload this to take a value.
2371   if (SemaBuiltinConstantArg(TheCall, 1, Result))
2372     return true;
2373   
2374   if (Result != 1)
2375     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2376              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2377
2378   return false;
2379 }
2380
2381 namespace {
2382 enum StringLiteralCheckType {
2383   SLCT_NotALiteral,
2384   SLCT_UncheckedLiteral,
2385   SLCT_CheckedLiteral
2386 };
2387 }
2388
2389 // Determine if an expression is a string literal or constant string.
2390 // If this function returns false on the arguments to a function expecting a
2391 // format string, we will usually need to emit a warning.
2392 // True string literals are then checked by CheckFormatString.
2393 static StringLiteralCheckType
2394 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2395                       bool HasVAListArg, unsigned format_idx,
2396                       unsigned firstDataArg, Sema::FormatStringType Type,
2397                       Sema::VariadicCallType CallType, bool InFunctionCall,
2398                       llvm::SmallBitVector &CheckedVarArgs) {
2399  tryAgain:
2400   if (E->isTypeDependent() || E->isValueDependent())
2401     return SLCT_NotALiteral;
2402
2403   E = E->IgnoreParenCasts();
2404
2405   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2406     // Technically -Wformat-nonliteral does not warn about this case.
2407     // The behavior of printf and friends in this case is implementation
2408     // dependent.  Ideally if the format string cannot be null then
2409     // it should have a 'nonnull' attribute in the function prototype.
2410     return SLCT_UncheckedLiteral;
2411
2412   switch (E->getStmtClass()) {
2413   case Stmt::BinaryConditionalOperatorClass:
2414   case Stmt::ConditionalOperatorClass: {
2415     // The expression is a literal if both sub-expressions were, and it was
2416     // completely checked only if both sub-expressions were checked.
2417     const AbstractConditionalOperator *C =
2418         cast<AbstractConditionalOperator>(E);
2419     StringLiteralCheckType Left =
2420         checkFormatStringExpr(S, C->getTrueExpr(), Args,
2421                               HasVAListArg, format_idx, firstDataArg,
2422                               Type, CallType, InFunctionCall, CheckedVarArgs);
2423     if (Left == SLCT_NotALiteral)
2424       return SLCT_NotALiteral;
2425     StringLiteralCheckType Right =
2426         checkFormatStringExpr(S, C->getFalseExpr(), Args,
2427                               HasVAListArg, format_idx, firstDataArg,
2428                               Type, CallType, InFunctionCall, CheckedVarArgs);
2429     return Left < Right ? Left : Right;
2430   }
2431
2432   case Stmt::ImplicitCastExprClass: {
2433     E = cast<ImplicitCastExpr>(E)->getSubExpr();
2434     goto tryAgain;
2435   }
2436
2437   case Stmt::OpaqueValueExprClass:
2438     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2439       E = src;
2440       goto tryAgain;
2441     }
2442     return SLCT_NotALiteral;
2443
2444   case Stmt::PredefinedExprClass:
2445     // While __func__, etc., are technically not string literals, they
2446     // cannot contain format specifiers and thus are not a security
2447     // liability.
2448     return SLCT_UncheckedLiteral;
2449       
2450   case Stmt::DeclRefExprClass: {
2451     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2452
2453     // As an exception, do not flag errors for variables binding to
2454     // const string literals.
2455     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2456       bool isConstant = false;
2457       QualType T = DR->getType();
2458
2459       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2460         isConstant = AT->getElementType().isConstant(S.Context);
2461       } else if (const PointerType *PT = T->getAs<PointerType>()) {
2462         isConstant = T.isConstant(S.Context) &&
2463                      PT->getPointeeType().isConstant(S.Context);
2464       } else if (T->isObjCObjectPointerType()) {
2465         // In ObjC, there is usually no "const ObjectPointer" type,
2466         // so don't check if the pointee type is constant.
2467         isConstant = T.isConstant(S.Context);
2468       }
2469
2470       if (isConstant) {
2471         if (const Expr *Init = VD->getAnyInitializer()) {
2472           // Look through initializers like const char c[] = { "foo" }
2473           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2474             if (InitList->isStringLiteralInit())
2475               Init = InitList->getInit(0)->IgnoreParenImpCasts();
2476           }
2477           return checkFormatStringExpr(S, Init, Args,
2478                                        HasVAListArg, format_idx,
2479                                        firstDataArg, Type, CallType,
2480                                        /*InFunctionCall*/false, CheckedVarArgs);
2481         }
2482       }
2483
2484       // For vprintf* functions (i.e., HasVAListArg==true), we add a
2485       // special check to see if the format string is a function parameter
2486       // of the function calling the printf function.  If the function
2487       // has an attribute indicating it is a printf-like function, then we
2488       // should suppress warnings concerning non-literals being used in a call
2489       // to a vprintf function.  For example:
2490       //
2491       // void
2492       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2493       //      va_list ap;
2494       //      va_start(ap, fmt);
2495       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
2496       //      ...
2497       // }
2498       if (HasVAListArg) {
2499         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2500           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2501             int PVIndex = PV->getFunctionScopeIndex() + 1;
2502             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2503               // adjust for implicit parameter
2504               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2505                 if (MD->isInstance())
2506                   ++PVIndex;
2507               // We also check if the formats are compatible.
2508               // We can't pass a 'scanf' string to a 'printf' function.
2509               if (PVIndex == PVFormat->getFormatIdx() &&
2510                   Type == S.GetFormatStringType(PVFormat))
2511                 return SLCT_UncheckedLiteral;
2512             }
2513           }
2514         }
2515       }
2516     }
2517
2518     return SLCT_NotALiteral;
2519   }
2520
2521   case Stmt::CallExprClass:
2522   case Stmt::CXXMemberCallExprClass: {
2523     const CallExpr *CE = cast<CallExpr>(E);
2524     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2525       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2526         unsigned ArgIndex = FA->getFormatIdx();
2527         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2528           if (MD->isInstance())
2529             --ArgIndex;
2530         const Expr *Arg = CE->getArg(ArgIndex - 1);
2531
2532         return checkFormatStringExpr(S, Arg, Args,
2533                                      HasVAListArg, format_idx, firstDataArg,
2534                                      Type, CallType, InFunctionCall,
2535                                      CheckedVarArgs);
2536       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2537         unsigned BuiltinID = FD->getBuiltinID();
2538         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2539             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2540           const Expr *Arg = CE->getArg(0);
2541           return checkFormatStringExpr(S, Arg, Args,
2542                                        HasVAListArg, format_idx,
2543                                        firstDataArg, Type, CallType,
2544                                        InFunctionCall, CheckedVarArgs);
2545         }
2546       }
2547     }
2548
2549     return SLCT_NotALiteral;
2550   }
2551   case Stmt::ObjCStringLiteralClass:
2552   case Stmt::StringLiteralClass: {
2553     const StringLiteral *StrE = nullptr;
2554
2555     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2556       StrE = ObjCFExpr->getString();
2557     else
2558       StrE = cast<StringLiteral>(E);
2559
2560     if (StrE) {
2561       S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2562                           Type, InFunctionCall, CallType, CheckedVarArgs);
2563       return SLCT_CheckedLiteral;
2564     }
2565
2566     return SLCT_NotALiteral;
2567   }
2568
2569   default:
2570     return SLCT_NotALiteral;
2571   }
2572 }
2573
2574 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2575   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2576   .Case("scanf", FST_Scanf)
2577   .Cases("printf", "printf0", FST_Printf)
2578   .Cases("NSString", "CFString", FST_NSString)
2579   .Case("strftime", FST_Strftime)
2580   .Case("strfmon", FST_Strfmon)
2581   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2582   .Default(FST_Unknown);
2583 }
2584
2585 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2586 /// functions) for correct use of format strings.
2587 /// Returns true if a format string has been fully checked.
2588 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2589                                 ArrayRef<const Expr *> Args,
2590                                 bool IsCXXMember,
2591                                 VariadicCallType CallType,
2592                                 SourceLocation Loc, SourceRange Range,
2593                                 llvm::SmallBitVector &CheckedVarArgs) {
2594   FormatStringInfo FSI;
2595   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2596     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2597                                 FSI.FirstDataArg, GetFormatStringType(Format),
2598                                 CallType, Loc, Range, CheckedVarArgs);
2599   return false;
2600 }
2601
2602 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2603                                 bool HasVAListArg, unsigned format_idx,
2604                                 unsigned firstDataArg, FormatStringType Type,
2605                                 VariadicCallType CallType,
2606                                 SourceLocation Loc, SourceRange Range,
2607                                 llvm::SmallBitVector &CheckedVarArgs) {
2608   // CHECK: printf/scanf-like function is called with no format string.
2609   if (format_idx >= Args.size()) {
2610     Diag(Loc, diag::warn_missing_format_string) << Range;
2611     return false;
2612   }
2613
2614   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2615
2616   // CHECK: format string is not a string literal.
2617   //
2618   // Dynamically generated format strings are difficult to
2619   // automatically vet at compile time.  Requiring that format strings
2620   // are string literals: (1) permits the checking of format strings by
2621   // the compiler and thereby (2) can practically remove the source of
2622   // many format string exploits.
2623
2624   // Format string can be either ObjC string (e.g. @"%d") or
2625   // C string (e.g. "%d")
2626   // ObjC string uses the same format specifiers as C string, so we can use
2627   // the same format string checking logic for both ObjC and C strings.
2628   StringLiteralCheckType CT =
2629       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2630                             format_idx, firstDataArg, Type, CallType,
2631                             /*IsFunctionCall*/true, CheckedVarArgs);
2632   if (CT != SLCT_NotALiteral)
2633     // Literal format string found, check done!
2634     return CT == SLCT_CheckedLiteral;
2635
2636   // Strftime is particular as it always uses a single 'time' argument,
2637   // so it is safe to pass a non-literal string.
2638   if (Type == FST_Strftime)
2639     return false;
2640
2641   // Do not emit diag when the string param is a macro expansion and the
2642   // format is either NSString or CFString. This is a hack to prevent
2643   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2644   // which are usually used in place of NS and CF string literals.
2645   if (Type == FST_NSString &&
2646       SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2647     return false;
2648
2649   // If there are no arguments specified, warn with -Wformat-security, otherwise
2650   // warn only with -Wformat-nonliteral.
2651   if (Args.size() == firstDataArg)
2652     Diag(Args[format_idx]->getLocStart(),
2653          diag::warn_format_nonliteral_noargs)
2654       << OrigFormatExpr->getSourceRange();
2655   else
2656     Diag(Args[format_idx]->getLocStart(),
2657          diag::warn_format_nonliteral)
2658            << OrigFormatExpr->getSourceRange();
2659   return false;
2660 }
2661
2662 namespace {
2663 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2664 protected:
2665   Sema &S;
2666   const StringLiteral *FExpr;
2667   const Expr *OrigFormatExpr;
2668   const unsigned FirstDataArg;
2669   const unsigned NumDataArgs;
2670   const char *Beg; // Start of format string.
2671   const bool HasVAListArg;
2672   ArrayRef<const Expr *> Args;
2673   unsigned FormatIdx;
2674   llvm::SmallBitVector CoveredArgs;
2675   bool usesPositionalArgs;
2676   bool atFirstArg;
2677   bool inFunctionCall;
2678   Sema::VariadicCallType CallType;
2679   llvm::SmallBitVector &CheckedVarArgs;
2680 public:
2681   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2682                      const Expr *origFormatExpr, unsigned firstDataArg,
2683                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
2684                      ArrayRef<const Expr *> Args,
2685                      unsigned formatIdx, bool inFunctionCall,
2686                      Sema::VariadicCallType callType,
2687                      llvm::SmallBitVector &CheckedVarArgs)
2688     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2689       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2690       Beg(beg), HasVAListArg(hasVAListArg),
2691       Args(Args), FormatIdx(formatIdx),
2692       usesPositionalArgs(false), atFirstArg(true),
2693       inFunctionCall(inFunctionCall), CallType(callType),
2694       CheckedVarArgs(CheckedVarArgs) {
2695     CoveredArgs.resize(numDataArgs);
2696     CoveredArgs.reset();
2697   }
2698
2699   void DoneProcessing();
2700
2701   void HandleIncompleteSpecifier(const char *startSpecifier,
2702                                  unsigned specifierLen) override;
2703
2704   void HandleInvalidLengthModifier(
2705                            const analyze_format_string::FormatSpecifier &FS,
2706                            const analyze_format_string::ConversionSpecifier &CS,
2707                            const char *startSpecifier, unsigned specifierLen,
2708                            unsigned DiagID);
2709
2710   void HandleNonStandardLengthModifier(
2711                     const analyze_format_string::FormatSpecifier &FS,
2712                     const char *startSpecifier, unsigned specifierLen);
2713
2714   void HandleNonStandardConversionSpecifier(
2715                     const analyze_format_string::ConversionSpecifier &CS,
2716                     const char *startSpecifier, unsigned specifierLen);
2717
2718   void HandlePosition(const char *startPos, unsigned posLen) override;
2719
2720   void HandleInvalidPosition(const char *startSpecifier,
2721                              unsigned specifierLen,
2722                              analyze_format_string::PositionContext p) override;
2723
2724   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
2725
2726   void HandleNullChar(const char *nullCharacter) override;
2727
2728   template <typename Range>
2729   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2730                                    const Expr *ArgumentExpr,
2731                                    PartialDiagnostic PDiag,
2732                                    SourceLocation StringLoc,
2733                                    bool IsStringLocation, Range StringRange,
2734                                    ArrayRef<FixItHint> Fixit = None);
2735
2736 protected:
2737   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2738                                         const char *startSpec,
2739                                         unsigned specifierLen,
2740                                         const char *csStart, unsigned csLen);
2741
2742   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2743                                          const char *startSpec,
2744                                          unsigned specifierLen);
2745   
2746   SourceRange getFormatStringRange();
2747   CharSourceRange getSpecifierRange(const char *startSpecifier,
2748                                     unsigned specifierLen);
2749   SourceLocation getLocationOfByte(const char *x);
2750
2751   const Expr *getDataArg(unsigned i) const;
2752   
2753   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2754                     const analyze_format_string::ConversionSpecifier &CS,
2755                     const char *startSpecifier, unsigned specifierLen,
2756                     unsigned argIndex);
2757
2758   template <typename Range>
2759   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2760                             bool IsStringLocation, Range StringRange,
2761                             ArrayRef<FixItHint> Fixit = None);
2762 };
2763 }
2764
2765 SourceRange CheckFormatHandler::getFormatStringRange() {
2766   return OrigFormatExpr->getSourceRange();
2767 }
2768
2769 CharSourceRange CheckFormatHandler::
2770 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2771   SourceLocation Start = getLocationOfByte(startSpecifier);
2772   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2773
2774   // Advance the end SourceLocation by one due to half-open ranges.
2775   End = End.getLocWithOffset(1);
2776
2777   return CharSourceRange::getCharRange(Start, End);
2778 }
2779
2780 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2781   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2782 }
2783
2784 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2785                                                    unsigned specifierLen){
2786   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2787                        getLocationOfByte(startSpecifier),
2788                        /*IsStringLocation*/true,
2789                        getSpecifierRange(startSpecifier, specifierLen));
2790 }
2791
2792 void CheckFormatHandler::HandleInvalidLengthModifier(
2793     const analyze_format_string::FormatSpecifier &FS,
2794     const analyze_format_string::ConversionSpecifier &CS,
2795     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2796   using namespace analyze_format_string;
2797
2798   const LengthModifier &LM = FS.getLengthModifier();
2799   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2800
2801   // See if we know how to fix this length modifier.
2802   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2803   if (FixedLM) {
2804     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2805                          getLocationOfByte(LM.getStart()),
2806                          /*IsStringLocation*/true,
2807                          getSpecifierRange(startSpecifier, specifierLen));
2808
2809     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2810       << FixedLM->toString()
2811       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2812
2813   } else {
2814     FixItHint Hint;
2815     if (DiagID == diag::warn_format_nonsensical_length)
2816       Hint = FixItHint::CreateRemoval(LMRange);
2817
2818     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2819                          getLocationOfByte(LM.getStart()),
2820                          /*IsStringLocation*/true,
2821                          getSpecifierRange(startSpecifier, specifierLen),
2822                          Hint);
2823   }
2824 }
2825
2826 void CheckFormatHandler::HandleNonStandardLengthModifier(
2827     const analyze_format_string::FormatSpecifier &FS,
2828     const char *startSpecifier, unsigned specifierLen) {
2829   using namespace analyze_format_string;
2830
2831   const LengthModifier &LM = FS.getLengthModifier();
2832   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2833
2834   // See if we know how to fix this length modifier.
2835   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2836   if (FixedLM) {
2837     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2838                            << LM.toString() << 0,
2839                          getLocationOfByte(LM.getStart()),
2840                          /*IsStringLocation*/true,
2841                          getSpecifierRange(startSpecifier, specifierLen));
2842
2843     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2844       << FixedLM->toString()
2845       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2846
2847   } else {
2848     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2849                            << LM.toString() << 0,
2850                          getLocationOfByte(LM.getStart()),
2851                          /*IsStringLocation*/true,
2852                          getSpecifierRange(startSpecifier, specifierLen));
2853   }
2854 }
2855
2856 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2857     const analyze_format_string::ConversionSpecifier &CS,
2858     const char *startSpecifier, unsigned specifierLen) {
2859   using namespace analyze_format_string;
2860
2861   // See if we know how to fix this conversion specifier.
2862   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2863   if (FixedCS) {
2864     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2865                           << CS.toString() << /*conversion specifier*/1,
2866                          getLocationOfByte(CS.getStart()),
2867                          /*IsStringLocation*/true,
2868                          getSpecifierRange(startSpecifier, specifierLen));
2869
2870     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2871     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2872       << FixedCS->toString()
2873       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2874   } else {
2875     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2876                           << CS.toString() << /*conversion specifier*/1,
2877                          getLocationOfByte(CS.getStart()),
2878                          /*IsStringLocation*/true,
2879                          getSpecifierRange(startSpecifier, specifierLen));
2880   }
2881 }
2882
2883 void CheckFormatHandler::HandlePosition(const char *startPos,
2884                                         unsigned posLen) {
2885   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2886                                getLocationOfByte(startPos),
2887                                /*IsStringLocation*/true,
2888                                getSpecifierRange(startPos, posLen));
2889 }
2890
2891 void
2892 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2893                                      analyze_format_string::PositionContext p) {
2894   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2895                          << (unsigned) p,
2896                        getLocationOfByte(startPos), /*IsStringLocation*/true,
2897                        getSpecifierRange(startPos, posLen));
2898 }
2899
2900 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2901                                             unsigned posLen) {
2902   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2903                                getLocationOfByte(startPos),
2904                                /*IsStringLocation*/true,
2905                                getSpecifierRange(startPos, posLen));
2906 }
2907
2908 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2909   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2910     // The presence of a null character is likely an error.
2911     EmitFormatDiagnostic(
2912       S.PDiag(diag::warn_printf_format_string_contains_null_char),
2913       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2914       getFormatStringRange());
2915   }
2916 }
2917
2918 // Note that this may return NULL if there was an error parsing or building
2919 // one of the argument expressions.
2920 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2921   return Args[FirstDataArg + i];
2922 }
2923
2924 void CheckFormatHandler::DoneProcessing() {
2925     // Does the number of data arguments exceed the number of
2926     // format conversions in the format string?
2927   if (!HasVAListArg) {
2928       // Find any arguments that weren't covered.
2929     CoveredArgs.flip();
2930     signed notCoveredArg = CoveredArgs.find_first();
2931     if (notCoveredArg >= 0) {
2932       assert((unsigned)notCoveredArg < NumDataArgs);
2933       if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2934         SourceLocation Loc = E->getLocStart();
2935         if (!S.getSourceManager().isInSystemMacro(Loc)) {
2936           EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2937                                Loc, /*IsStringLocation*/false,
2938                                getFormatStringRange());
2939         }
2940       }
2941     }
2942   }
2943 }
2944
2945 bool
2946 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2947                                                      SourceLocation Loc,
2948                                                      const char *startSpec,
2949                                                      unsigned specifierLen,
2950                                                      const char *csStart,
2951                                                      unsigned csLen) {
2952   
2953   bool keepGoing = true;
2954   if (argIndex < NumDataArgs) {
2955     // Consider the argument coverered, even though the specifier doesn't
2956     // make sense.
2957     CoveredArgs.set(argIndex);
2958   }
2959   else {
2960     // If argIndex exceeds the number of data arguments we
2961     // don't issue a warning because that is just a cascade of warnings (and
2962     // they may have intended '%%' anyway). We don't want to continue processing
2963     // the format string after this point, however, as we will like just get
2964     // gibberish when trying to match arguments.
2965     keepGoing = false;
2966   }
2967   
2968   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2969                          << StringRef(csStart, csLen),
2970                        Loc, /*IsStringLocation*/true,
2971                        getSpecifierRange(startSpec, specifierLen));
2972   
2973   return keepGoing;
2974 }
2975
2976 void
2977 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2978                                                       const char *startSpec,
2979                                                       unsigned specifierLen) {
2980   EmitFormatDiagnostic(
2981     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2982     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2983 }
2984
2985 bool
2986 CheckFormatHandler::CheckNumArgs(
2987   const analyze_format_string::FormatSpecifier &FS,
2988   const analyze_format_string::ConversionSpecifier &CS,
2989   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2990
2991   if (argIndex >= NumDataArgs) {
2992     PartialDiagnostic PDiag = FS.usesPositionalArg()
2993       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2994            << (argIndex+1) << NumDataArgs)
2995       : S.PDiag(diag::warn_printf_insufficient_data_args);
2996     EmitFormatDiagnostic(
2997       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2998       getSpecifierRange(startSpecifier, specifierLen));
2999     return false;
3000   }
3001   return true;
3002 }
3003
3004 template<typename Range>
3005 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3006                                               SourceLocation Loc,
3007                                               bool IsStringLocation,
3008                                               Range StringRange,
3009                                               ArrayRef<FixItHint> FixIt) {
3010   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
3011                        Loc, IsStringLocation, StringRange, FixIt);
3012 }
3013
3014 /// \brief If the format string is not within the funcion call, emit a note
3015 /// so that the function call and string are in diagnostic messages.
3016 ///
3017 /// \param InFunctionCall if true, the format string is within the function
3018 /// call and only one diagnostic message will be produced.  Otherwise, an
3019 /// extra note will be emitted pointing to location of the format string.
3020 ///
3021 /// \param ArgumentExpr the expression that is passed as the format string
3022 /// argument in the function call.  Used for getting locations when two
3023 /// diagnostics are emitted.
3024 ///
3025 /// \param PDiag the callee should already have provided any strings for the
3026 /// diagnostic message.  This function only adds locations and fixits
3027 /// to diagnostics.
3028 ///
3029 /// \param Loc primary location for diagnostic.  If two diagnostics are
3030 /// required, one will be at Loc and a new SourceLocation will be created for
3031 /// the other one.
3032 ///
3033 /// \param IsStringLocation if true, Loc points to the format string should be
3034 /// used for the note.  Otherwise, Loc points to the argument list and will
3035 /// be used with PDiag.
3036 ///
3037 /// \param StringRange some or all of the string to highlight.  This is
3038 /// templated so it can accept either a CharSourceRange or a SourceRange.
3039 ///
3040 /// \param FixIt optional fix it hint for the format string.
3041 template<typename Range>
3042 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3043                                               const Expr *ArgumentExpr,
3044                                               PartialDiagnostic PDiag,
3045                                               SourceLocation Loc,
3046                                               bool IsStringLocation,
3047                                               Range StringRange,
3048                                               ArrayRef<FixItHint> FixIt) {
3049   if (InFunctionCall) {
3050     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3051     D << StringRange;
3052     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3053          I != E; ++I) {
3054       D << *I;
3055     }
3056   } else {
3057     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3058       << ArgumentExpr->getSourceRange();
3059
3060     const Sema::SemaDiagnosticBuilder &Note =
3061       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3062              diag::note_format_string_defined);
3063
3064     Note << StringRange;
3065     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3066          I != E; ++I) {
3067       Note << *I;
3068     }
3069   }
3070 }
3071
3072 //===--- CHECK: Printf format string checking ------------------------------===//
3073
3074 namespace {
3075 class CheckPrintfHandler : public CheckFormatHandler {
3076   bool ObjCContext;
3077 public:
3078   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3079                      const Expr *origFormatExpr, unsigned firstDataArg,
3080                      unsigned numDataArgs, bool isObjC,
3081                      const char *beg, bool hasVAListArg,
3082                      ArrayRef<const Expr *> Args,
3083                      unsigned formatIdx, bool inFunctionCall,
3084                      Sema::VariadicCallType CallType,
3085                      llvm::SmallBitVector &CheckedVarArgs)
3086     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3087                          numDataArgs, beg, hasVAListArg, Args,
3088                          formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3089       ObjCContext(isObjC)
3090   {}
3091
3092
3093   bool HandleInvalidPrintfConversionSpecifier(
3094                                       const analyze_printf::PrintfSpecifier &FS,
3095                                       const char *startSpecifier,
3096                                       unsigned specifierLen) override;
3097
3098   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3099                              const char *startSpecifier,
3100                              unsigned specifierLen) override;
3101   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3102                        const char *StartSpecifier,
3103                        unsigned SpecifierLen,
3104                        const Expr *E);
3105
3106   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3107                     const char *startSpecifier, unsigned specifierLen);
3108   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3109                            const analyze_printf::OptionalAmount &Amt,
3110                            unsigned type,
3111                            const char *startSpecifier, unsigned specifierLen);
3112   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3113                   const analyze_printf::OptionalFlag &flag,
3114                   const char *startSpecifier, unsigned specifierLen);
3115   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3116                          const analyze_printf::OptionalFlag &ignoredFlag,
3117                          const analyze_printf::OptionalFlag &flag,
3118                          const char *startSpecifier, unsigned specifierLen);
3119   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
3120                            const Expr *E);
3121
3122 };  
3123 }
3124
3125 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3126                                       const analyze_printf::PrintfSpecifier &FS,
3127                                       const char *startSpecifier,
3128                                       unsigned specifierLen) {
3129   const analyze_printf::PrintfConversionSpecifier &CS =
3130     FS.getConversionSpecifier();
3131   
3132   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3133                                           getLocationOfByte(CS.getStart()),
3134                                           startSpecifier, specifierLen,
3135                                           CS.getStart(), CS.getLength());
3136 }
3137
3138 bool CheckPrintfHandler::HandleAmount(
3139                                const analyze_format_string::OptionalAmount &Amt,
3140                                unsigned k, const char *startSpecifier,
3141                                unsigned specifierLen) {
3142
3143   if (Amt.hasDataArgument()) {
3144     if (!HasVAListArg) {
3145       unsigned argIndex = Amt.getArgIndex();
3146       if (argIndex >= NumDataArgs) {
3147         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3148                                << k,
3149                              getLocationOfByte(Amt.getStart()),
3150                              /*IsStringLocation*/true,
3151                              getSpecifierRange(startSpecifier, specifierLen));
3152         // Don't do any more checking.  We will just emit
3153         // spurious errors.
3154         return false;
3155       }
3156
3157       // Type check the data argument.  It should be an 'int'.
3158       // Although not in conformance with C99, we also allow the argument to be
3159       // an 'unsigned int' as that is a reasonably safe case.  GCC also
3160       // doesn't emit a warning for that case.
3161       CoveredArgs.set(argIndex);
3162       const Expr *Arg = getDataArg(argIndex);
3163       if (!Arg)
3164         return false;
3165
3166       QualType T = Arg->getType();
3167
3168       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3169       assert(AT.isValid());
3170
3171       if (!AT.matchesType(S.Context, T)) {
3172         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
3173                                << k << AT.getRepresentativeTypeName(S.Context)
3174                                << T << Arg->getSourceRange(),
3175                              getLocationOfByte(Amt.getStart()),
3176                              /*IsStringLocation*/true,
3177                              getSpecifierRange(startSpecifier, specifierLen));
3178         // Don't do any more checking.  We will just emit
3179         // spurious errors.
3180         return false;
3181       }
3182     }
3183   }
3184   return true;
3185 }
3186
3187 void CheckPrintfHandler::HandleInvalidAmount(
3188                                       const analyze_printf::PrintfSpecifier &FS,
3189                                       const analyze_printf::OptionalAmount &Amt,
3190                                       unsigned type,
3191                                       const char *startSpecifier,
3192                                       unsigned specifierLen) {
3193   const analyze_printf::PrintfConversionSpecifier &CS =
3194     FS.getConversionSpecifier();
3195
3196   FixItHint fixit =
3197     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3198       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3199                                  Amt.getConstantLength()))
3200       : FixItHint();
3201
3202   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3203                          << type << CS.toString(),
3204                        getLocationOfByte(Amt.getStart()),
3205                        /*IsStringLocation*/true,
3206                        getSpecifierRange(startSpecifier, specifierLen),
3207                        fixit);
3208 }
3209
3210 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3211                                     const analyze_printf::OptionalFlag &flag,
3212                                     const char *startSpecifier,
3213                                     unsigned specifierLen) {
3214   // Warn about pointless flag with a fixit removal.
3215   const analyze_printf::PrintfConversionSpecifier &CS =
3216     FS.getConversionSpecifier();
3217   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3218                          << flag.toString() << CS.toString(),
3219                        getLocationOfByte(flag.getPosition()),
3220                        /*IsStringLocation*/true,
3221                        getSpecifierRange(startSpecifier, specifierLen),
3222                        FixItHint::CreateRemoval(
3223                          getSpecifierRange(flag.getPosition(), 1)));
3224 }
3225
3226 void CheckPrintfHandler::HandleIgnoredFlag(
3227                                 const analyze_printf::PrintfSpecifier &FS,
3228                                 const analyze_printf::OptionalFlag &ignoredFlag,
3229                                 const analyze_printf::OptionalFlag &flag,
3230                                 const char *startSpecifier,
3231                                 unsigned specifierLen) {
3232   // Warn about ignored flag with a fixit removal.
3233   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3234                          << ignoredFlag.toString() << flag.toString(),
3235                        getLocationOfByte(ignoredFlag.getPosition()),
3236                        /*IsStringLocation*/true,
3237                        getSpecifierRange(startSpecifier, specifierLen),
3238                        FixItHint::CreateRemoval(
3239                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
3240 }
3241
3242 // Determines if the specified is a C++ class or struct containing
3243 // a member with the specified name and kind (e.g. a CXXMethodDecl named
3244 // "c_str()").
3245 template<typename MemberKind>
3246 static llvm::SmallPtrSet<MemberKind*, 1>
3247 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3248   const RecordType *RT = Ty->getAs<RecordType>();
3249   llvm::SmallPtrSet<MemberKind*, 1> Results;
3250
3251   if (!RT)
3252     return Results;
3253   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3254   if (!RD || !RD->getDefinition())
3255     return Results;
3256
3257   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
3258                  Sema::LookupMemberName);
3259   R.suppressDiagnostics();
3260
3261   // We just need to include all members of the right kind turned up by the
3262   // filter, at this point.
3263   if (S.LookupQualifiedName(R, RT->getDecl()))
3264     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3265       NamedDecl *decl = (*I)->getUnderlyingDecl();
3266       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3267         Results.insert(FK);
3268     }
3269   return Results;
3270 }
3271
3272 /// Check if we could call '.c_str()' on an object.
3273 ///
3274 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3275 /// allow the call, or if it would be ambiguous).
3276 bool Sema::hasCStrMethod(const Expr *E) {
3277   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3278   MethodSet Results =
3279       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3280   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3281        MI != ME; ++MI)
3282     if ((*MI)->getMinRequiredArguments() == 0)
3283       return true;
3284   return false;
3285 }
3286
3287 // Check if a (w)string was passed when a (w)char* was needed, and offer a
3288 // better diagnostic if so. AT is assumed to be valid.
3289 // Returns true when a c_str() conversion method is found.
3290 bool CheckPrintfHandler::checkForCStrMembers(
3291     const analyze_printf::ArgType &AT, const Expr *E) {
3292   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3293
3294   MethodSet Results =
3295       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3296
3297   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3298        MI != ME; ++MI) {
3299     const CXXMethodDecl *Method = *MI;
3300     if (Method->getMinRequiredArguments() == 0 &&
3301         AT.matchesType(S.Context, Method->getReturnType())) {
3302       // FIXME: Suggest parens if the expression needs them.
3303       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
3304       S.Diag(E->getLocStart(), diag::note_printf_c_str)
3305           << "c_str()"
3306           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3307       return true;
3308     }
3309   }
3310
3311   return false;
3312 }
3313
3314 bool
3315 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
3316                                             &FS,
3317                                           const char *startSpecifier,
3318                                           unsigned specifierLen) {
3319
3320   using namespace analyze_format_string;
3321   using namespace analyze_printf;  
3322   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
3323
3324   if (FS.consumesDataArgument()) {
3325     if (atFirstArg) {
3326         atFirstArg = false;
3327         usesPositionalArgs = FS.usesPositionalArg();
3328     }
3329     else if (usesPositionalArgs != FS.usesPositionalArg()) {
3330       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3331                                         startSpecifier, specifierLen);
3332       return false;
3333     }
3334   }
3335
3336   // First check if the field width, precision, and conversion specifier
3337   // have matching data arguments.
3338   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3339                     startSpecifier, specifierLen)) {
3340     return false;
3341   }
3342
3343   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3344                     startSpecifier, specifierLen)) {
3345     return false;
3346   }
3347
3348   if (!CS.consumesDataArgument()) {
3349     // FIXME: Technically specifying a precision or field width here
3350     // makes no sense.  Worth issuing a warning at some point.
3351     return true;
3352   }
3353
3354   // Consume the argument.
3355   unsigned argIndex = FS.getArgIndex();
3356   if (argIndex < NumDataArgs) {
3357     // The check to see if the argIndex is valid will come later.
3358     // We set the bit here because we may exit early from this
3359     // function if we encounter some other error.
3360     CoveredArgs.set(argIndex);
3361   }
3362
3363   // Check for using an Objective-C specific conversion specifier
3364   // in a non-ObjC literal.
3365   if (!ObjCContext && CS.isObjCArg()) {
3366     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3367                                                   specifierLen);
3368   }
3369
3370   // Check for invalid use of field width
3371   if (!FS.hasValidFieldWidth()) {
3372     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3373         startSpecifier, specifierLen);
3374   }
3375
3376   // Check for invalid use of precision
3377   if (!FS.hasValidPrecision()) {
3378     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3379         startSpecifier, specifierLen);
3380   }
3381
3382   // Check each flag does not conflict with any other component.
3383   if (!FS.hasValidThousandsGroupingPrefix())
3384     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3385   if (!FS.hasValidLeadingZeros())
3386     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3387   if (!FS.hasValidPlusPrefix())
3388     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3389   if (!FS.hasValidSpacePrefix())
3390     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3391   if (!FS.hasValidAlternativeForm())
3392     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3393   if (!FS.hasValidLeftJustified())
3394     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3395
3396   // Check that flags are not ignored by another flag
3397   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3398     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3399         startSpecifier, specifierLen);
3400   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3401     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3402             startSpecifier, specifierLen);
3403
3404   // Check the length modifier is valid with the given conversion specifier.
3405   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3406     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3407                                 diag::warn_format_nonsensical_length);
3408   else if (!FS.hasStandardLengthModifier())
3409     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3410   else if (!FS.hasStandardLengthConversionCombination())
3411     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3412                                 diag::warn_format_non_standard_conversion_spec);
3413
3414   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3415     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3416
3417   // The remaining checks depend on the data arguments.
3418   if (HasVAListArg)
3419     return true;
3420
3421   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3422     return false;
3423
3424   const Expr *Arg = getDataArg(argIndex);
3425   if (!Arg)
3426     return true;
3427
3428   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3429 }
3430
3431 static bool requiresParensToAddCast(const Expr *E) {
3432   // FIXME: We should have a general way to reason about operator
3433   // precedence and whether parens are actually needed here.
3434   // Take care of a few common cases where they aren't.
3435   const Expr *Inside = E->IgnoreImpCasts();
3436   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3437     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3438
3439   switch (Inside->getStmtClass()) {
3440   case Stmt::ArraySubscriptExprClass:
3441   case Stmt::CallExprClass:
3442   case Stmt::CharacterLiteralClass:
3443   case Stmt::CXXBoolLiteralExprClass:
3444   case Stmt::DeclRefExprClass:
3445   case Stmt::FloatingLiteralClass:
3446   case Stmt::IntegerLiteralClass:
3447   case Stmt::MemberExprClass:
3448   case Stmt::ObjCArrayLiteralClass:
3449   case Stmt::ObjCBoolLiteralExprClass:
3450   case Stmt::ObjCBoxedExprClass:
3451   case Stmt::ObjCDictionaryLiteralClass:
3452   case Stmt::ObjCEncodeExprClass:
3453   case Stmt::ObjCIvarRefExprClass:
3454   case Stmt::ObjCMessageExprClass:
3455   case Stmt::ObjCPropertyRefExprClass:
3456   case Stmt::ObjCStringLiteralClass:
3457   case Stmt::ObjCSubscriptRefExprClass:
3458   case Stmt::ParenExprClass:
3459   case Stmt::StringLiteralClass:
3460   case Stmt::UnaryOperatorClass:
3461     return false;
3462   default:
3463     return true;
3464   }
3465 }
3466
3467 static std::pair<QualType, StringRef>
3468 shouldNotPrintDirectly(const ASTContext &Context,
3469                        QualType IntendedTy,
3470                        const Expr *E) {
3471   // Use a 'while' to peel off layers of typedefs.
3472   QualType TyTy = IntendedTy;
3473   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3474     StringRef Name = UserTy->getDecl()->getName();
3475     QualType CastTy = llvm::StringSwitch<QualType>(Name)
3476       .Case("NSInteger", Context.LongTy)
3477       .Case("NSUInteger", Context.UnsignedLongTy)
3478       .Case("SInt32", Context.IntTy)
3479       .Case("UInt32", Context.UnsignedIntTy)
3480       .Default(QualType());
3481
3482     if (!CastTy.isNull())
3483       return std::make_pair(CastTy, Name);
3484
3485     TyTy = UserTy->desugar();
3486   }
3487
3488   // Strip parens if necessary.
3489   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3490     return shouldNotPrintDirectly(Context,
3491                                   PE->getSubExpr()->getType(),
3492                                   PE->getSubExpr());
3493
3494   // If this is a conditional expression, then its result type is constructed
3495   // via usual arithmetic conversions and thus there might be no necessary
3496   // typedef sugar there.  Recurse to operands to check for NSInteger &
3497   // Co. usage condition.
3498   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3499     QualType TrueTy, FalseTy;
3500     StringRef TrueName, FalseName;
3501
3502     std::tie(TrueTy, TrueName) =
3503       shouldNotPrintDirectly(Context,
3504                              CO->getTrueExpr()->getType(),
3505                              CO->getTrueExpr());
3506     std::tie(FalseTy, FalseName) =
3507       shouldNotPrintDirectly(Context,
3508                              CO->getFalseExpr()->getType(),
3509                              CO->getFalseExpr());
3510
3511     if (TrueTy == FalseTy)
3512       return std::make_pair(TrueTy, TrueName);
3513     else if (TrueTy.isNull())
3514       return std::make_pair(FalseTy, FalseName);
3515     else if (FalseTy.isNull())
3516       return std::make_pair(TrueTy, TrueName);
3517   }
3518
3519   return std::make_pair(QualType(), StringRef());
3520 }
3521
3522 bool
3523 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3524                                     const char *StartSpecifier,
3525                                     unsigned SpecifierLen,
3526                                     const Expr *E) {
3527   using namespace analyze_format_string;
3528   using namespace analyze_printf;
3529   // Now type check the data expression that matches the
3530   // format specifier.
3531   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3532                                                     ObjCContext);
3533   if (!AT.isValid())
3534     return true;
3535
3536   QualType ExprTy = E->getType();
3537   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3538     ExprTy = TET->getUnderlyingExpr()->getType();
3539   }
3540
3541   if (AT.matchesType(S.Context, ExprTy))
3542     return true;
3543
3544   // Look through argument promotions for our error message's reported type.
3545   // This includes the integral and floating promotions, but excludes array
3546   // and function pointer decay; seeing that an argument intended to be a
3547   // string has type 'char [6]' is probably more confusing than 'char *'.
3548   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3549     if (ICE->getCastKind() == CK_IntegralCast ||
3550         ICE->getCastKind() == CK_FloatingCast) {
3551       E = ICE->getSubExpr();
3552       ExprTy = E->getType();
3553
3554       // Check if we didn't match because of an implicit cast from a 'char'
3555       // or 'short' to an 'int'.  This is done because printf is a varargs
3556       // function.
3557       if (ICE->getType() == S.Context.IntTy ||
3558           ICE->getType() == S.Context.UnsignedIntTy) {
3559         // All further checking is done on the subexpression.
3560         if (AT.matchesType(S.Context, ExprTy))
3561           return true;
3562       }
3563     }
3564   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3565     // Special case for 'a', which has type 'int' in C.
3566     // Note, however, that we do /not/ want to treat multibyte constants like
3567     // 'MooV' as characters! This form is deprecated but still exists.
3568     if (ExprTy == S.Context.IntTy)
3569       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3570         ExprTy = S.Context.CharTy;
3571   }
3572
3573   // Look through enums to their underlying type.
3574   bool IsEnum = false;
3575   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3576     ExprTy = EnumTy->getDecl()->getIntegerType();
3577     IsEnum = true;
3578   }
3579
3580   // %C in an Objective-C context prints a unichar, not a wchar_t.
3581   // If the argument is an integer of some kind, believe the %C and suggest
3582   // a cast instead of changing the conversion specifier.
3583   QualType IntendedTy = ExprTy;
3584   if (ObjCContext &&
3585       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3586     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3587         !ExprTy->isCharType()) {
3588       // 'unichar' is defined as a typedef of unsigned short, but we should
3589       // prefer using the typedef if it is visible.
3590       IntendedTy = S.Context.UnsignedShortTy;
3591
3592       // While we are here, check if the value is an IntegerLiteral that happens
3593       // to be within the valid range.
3594       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3595         const llvm::APInt &V = IL->getValue();
3596         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3597           return true;
3598       }
3599
3600       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3601                           Sema::LookupOrdinaryName);
3602       if (S.LookupName(Result, S.getCurScope())) {
3603         NamedDecl *ND = Result.getFoundDecl();
3604         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3605           if (TD->getUnderlyingType() == IntendedTy)
3606             IntendedTy = S.Context.getTypedefType(TD);
3607       }
3608     }
3609   }
3610
3611   // Special-case some of Darwin's platform-independence types by suggesting
3612   // casts to primitive types that are known to be large enough.
3613   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
3614   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3615     QualType CastTy;
3616     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3617     if (!CastTy.isNull()) {
3618       IntendedTy = CastTy;
3619       ShouldNotPrintDirectly = true;
3620     }
3621   }
3622
3623   // We may be able to offer a FixItHint if it is a supported type.
3624   PrintfSpecifier fixedFS = FS;
3625   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3626                                  S.Context, ObjCContext);
3627
3628   if (success) {
3629     // Get the fix string from the fixed format specifier
3630     SmallString<16> buf;
3631     llvm::raw_svector_ostream os(buf);
3632     fixedFS.toString(os);
3633
3634     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3635
3636     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
3637       // In this case, the specifier is wrong and should be changed to match
3638       // the argument.
3639       EmitFormatDiagnostic(
3640         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3641           << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
3642           << E->getSourceRange(),
3643         E->getLocStart(),
3644         /*IsStringLocation*/false,
3645         SpecRange,
3646         FixItHint::CreateReplacement(SpecRange, os.str()));
3647
3648     } else {
3649       // The canonical type for formatting this value is different from the
3650       // actual type of the expression. (This occurs, for example, with Darwin's
3651       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3652       // should be printed as 'long' for 64-bit compatibility.)
3653       // Rather than emitting a normal format/argument mismatch, we want to
3654       // add a cast to the recommended type (and correct the format string
3655       // if necessary).
3656       SmallString<16> CastBuf;
3657       llvm::raw_svector_ostream CastFix(CastBuf);
3658       CastFix << "(";
3659       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3660       CastFix << ")";
3661
3662       SmallVector<FixItHint,4> Hints;
3663       if (!AT.matchesType(S.Context, IntendedTy))
3664         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3665
3666       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3667         // If there's already a cast present, just replace it.
3668         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3669         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3670
3671       } else if (!requiresParensToAddCast(E)) {
3672         // If the expression has high enough precedence,
3673         // just write the C-style cast.
3674         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3675                                                    CastFix.str()));
3676       } else {
3677         // Otherwise, add parens around the expression as well as the cast.
3678         CastFix << "(";
3679         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3680                                                    CastFix.str()));
3681
3682         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
3683         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3684       }
3685
3686       if (ShouldNotPrintDirectly) {
3687         // The expression has a type that should not be printed directly.
3688         // We extract the name from the typedef because we don't want to show
3689         // the underlying type in the diagnostic.
3690         StringRef Name;
3691         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3692           Name = TypedefTy->getDecl()->getName();
3693         else
3694           Name = CastTyName;
3695         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3696                                << Name << IntendedTy << IsEnum
3697                                << E->getSourceRange(),
3698                              E->getLocStart(), /*IsStringLocation=*/false,
3699                              SpecRange, Hints);
3700       } else {
3701         // In this case, the expression could be printed using a different
3702         // specifier, but we've decided that the specifier is probably correct 
3703         // and we should cast instead. Just use the normal warning message.
3704         EmitFormatDiagnostic(
3705           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3706             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3707             << E->getSourceRange(),
3708           E->getLocStart(), /*IsStringLocation*/false,
3709           SpecRange, Hints);
3710       }
3711     }
3712   } else {
3713     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3714                                                    SpecifierLen);
3715     // Since the warning for passing non-POD types to variadic functions
3716     // was deferred until now, we emit a warning for non-POD
3717     // arguments here.
3718     switch (S.isValidVarArgType(ExprTy)) {
3719     case Sema::VAK_Valid:
3720     case Sema::VAK_ValidInCXX11:
3721       EmitFormatDiagnostic(
3722         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3723           << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3724           << CSR
3725           << E->getSourceRange(),
3726         E->getLocStart(), /*IsStringLocation*/false, CSR);
3727       break;
3728
3729     case Sema::VAK_Undefined:
3730     case Sema::VAK_MSVCUndefined:
3731       EmitFormatDiagnostic(
3732         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3733           << S.getLangOpts().CPlusPlus11
3734           << ExprTy
3735           << CallType
3736           << AT.getRepresentativeTypeName(S.Context)
3737           << CSR
3738           << E->getSourceRange(),
3739         E->getLocStart(), /*IsStringLocation*/false, CSR);
3740       checkForCStrMembers(AT, E);
3741       break;
3742
3743     case Sema::VAK_Invalid:
3744       if (ExprTy->isObjCObjectType())
3745         EmitFormatDiagnostic(
3746           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3747             << S.getLangOpts().CPlusPlus11
3748             << ExprTy
3749             << CallType
3750             << AT.getRepresentativeTypeName(S.Context)
3751             << CSR
3752             << E->getSourceRange(),
3753           E->getLocStart(), /*IsStringLocation*/false, CSR);
3754       else
3755         // FIXME: If this is an initializer list, suggest removing the braces
3756         // or inserting a cast to the target type.
3757         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3758           << isa<InitListExpr>(E) << ExprTy << CallType
3759           << AT.getRepresentativeTypeName(S.Context)
3760           << E->getSourceRange();
3761       break;
3762     }
3763
3764     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3765            "format string specifier index out of range");
3766     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3767   }
3768
3769   return true;
3770 }
3771
3772 //===--- CHECK: Scanf format string checking ------------------------------===//
3773
3774 namespace {  
3775 class CheckScanfHandler : public CheckFormatHandler {
3776 public:
3777   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3778                     const Expr *origFormatExpr, unsigned firstDataArg,
3779                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
3780                     ArrayRef<const Expr *> Args,
3781                     unsigned formatIdx, bool inFunctionCall,
3782                     Sema::VariadicCallType CallType,
3783                     llvm::SmallBitVector &CheckedVarArgs)
3784     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3785                          numDataArgs, beg, hasVAListArg,
3786                          Args, formatIdx, inFunctionCall, CallType,
3787                          CheckedVarArgs)
3788   {}
3789   
3790   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3791                             const char *startSpecifier,
3792                             unsigned specifierLen) override;
3793   
3794   bool HandleInvalidScanfConversionSpecifier(
3795           const analyze_scanf::ScanfSpecifier &FS,
3796           const char *startSpecifier,
3797           unsigned specifierLen) override;
3798
3799   void HandleIncompleteScanList(const char *start, const char *end) override;
3800 };
3801 }
3802
3803 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3804                                                  const char *end) {
3805   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3806                        getLocationOfByte(end), /*IsStringLocation*/true,
3807                        getSpecifierRange(start, end - start));
3808 }
3809
3810 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3811                                         const analyze_scanf::ScanfSpecifier &FS,
3812                                         const char *startSpecifier,
3813                                         unsigned specifierLen) {
3814
3815   const analyze_scanf::ScanfConversionSpecifier &CS =
3816     FS.getConversionSpecifier();
3817
3818   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3819                                           getLocationOfByte(CS.getStart()),
3820                                           startSpecifier, specifierLen,
3821                                           CS.getStart(), CS.getLength());
3822 }
3823
3824 bool CheckScanfHandler::HandleScanfSpecifier(
3825                                        const analyze_scanf::ScanfSpecifier &FS,
3826                                        const char *startSpecifier,
3827                                        unsigned specifierLen) {
3828   
3829   using namespace analyze_scanf;
3830   using namespace analyze_format_string;  
3831
3832   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3833
3834   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3835   // be used to decide if we are using positional arguments consistently.
3836   if (FS.consumesDataArgument()) {
3837     if (atFirstArg) {
3838       atFirstArg = false;
3839       usesPositionalArgs = FS.usesPositionalArg();
3840     }
3841     else if (usesPositionalArgs != FS.usesPositionalArg()) {
3842       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3843                                         startSpecifier, specifierLen);
3844       return false;
3845     }
3846   }
3847   
3848   // Check if the field with is non-zero.
3849   const OptionalAmount &Amt = FS.getFieldWidth();
3850   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3851     if (Amt.getConstantAmount() == 0) {
3852       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3853                                                    Amt.getConstantLength());
3854       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3855                            getLocationOfByte(Amt.getStart()),
3856                            /*IsStringLocation*/true, R,
3857                            FixItHint::CreateRemoval(R));
3858     }
3859   }
3860   
3861   if (!FS.consumesDataArgument()) {
3862     // FIXME: Technically specifying a precision or field width here
3863     // makes no sense.  Worth issuing a warning at some point.
3864     return true;
3865   }
3866   
3867   // Consume the argument.
3868   unsigned argIndex = FS.getArgIndex();
3869   if (argIndex < NumDataArgs) {
3870       // The check to see if the argIndex is valid will come later.
3871       // We set the bit here because we may exit early from this
3872       // function if we encounter some other error.
3873     CoveredArgs.set(argIndex);
3874   }
3875   
3876   // Check the length modifier is valid with the given conversion specifier.
3877   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3878     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3879                                 diag::warn_format_nonsensical_length);
3880   else if (!FS.hasStandardLengthModifier())
3881     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3882   else if (!FS.hasStandardLengthConversionCombination())
3883     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3884                                 diag::warn_format_non_standard_conversion_spec);
3885
3886   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3887     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3888
3889   // The remaining checks depend on the data arguments.
3890   if (HasVAListArg)
3891     return true;
3892   
3893   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3894     return false;
3895   
3896   // Check that the argument type matches the format specifier.
3897   const Expr *Ex = getDataArg(argIndex);
3898   if (!Ex)
3899     return true;
3900
3901   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3902   if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3903     ScanfSpecifier fixedFS = FS;
3904     bool success = fixedFS.fixType(Ex->getType(),
3905                                    Ex->IgnoreImpCasts()->getType(),
3906                                    S.getLangOpts(), S.Context);
3907
3908     if (success) {
3909       // Get the fix string from the fixed format specifier.
3910       SmallString<128> buf;
3911       llvm::raw_svector_ostream os(buf);
3912       fixedFS.toString(os);
3913
3914       EmitFormatDiagnostic(
3915         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3916           << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
3917           << Ex->getSourceRange(),
3918         Ex->getLocStart(),
3919         /*IsStringLocation*/false,
3920         getSpecifierRange(startSpecifier, specifierLen),
3921         FixItHint::CreateReplacement(
3922           getSpecifierRange(startSpecifier, specifierLen),
3923           os.str()));
3924     } else {
3925       EmitFormatDiagnostic(
3926         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3927           << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
3928           << Ex->getSourceRange(),
3929         Ex->getLocStart(),
3930         /*IsStringLocation*/false,
3931         getSpecifierRange(startSpecifier, specifierLen));
3932     }
3933   }
3934
3935   return true;
3936 }
3937
3938 void Sema::CheckFormatString(const StringLiteral *FExpr,
3939                              const Expr *OrigFormatExpr,
3940                              ArrayRef<const Expr *> Args,
3941                              bool HasVAListArg, unsigned format_idx,
3942                              unsigned firstDataArg, FormatStringType Type,
3943                              bool inFunctionCall, VariadicCallType CallType,
3944                              llvm::SmallBitVector &CheckedVarArgs) {
3945   
3946   // CHECK: is the format string a wide literal?
3947   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3948     CheckFormatHandler::EmitFormatDiagnostic(
3949       *this, inFunctionCall, Args[format_idx],
3950       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3951       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3952     return;
3953   }
3954   
3955   // Str - The format string.  NOTE: this is NOT null-terminated!
3956   StringRef StrRef = FExpr->getString();
3957   const char *Str = StrRef.data();
3958   // Account for cases where the string literal is truncated in a declaration.
3959   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3960   assert(T && "String literal not of constant array type!");
3961   size_t TypeSize = T->getSize().getZExtValue();
3962   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3963   const unsigned numDataArgs = Args.size() - firstDataArg;
3964
3965   // Emit a warning if the string literal is truncated and does not contain an
3966   // embedded null character.
3967   if (TypeSize <= StrRef.size() &&
3968       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3969     CheckFormatHandler::EmitFormatDiagnostic(
3970         *this, inFunctionCall, Args[format_idx],
3971         PDiag(diag::warn_printf_format_string_not_null_terminated),
3972         FExpr->getLocStart(),
3973         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3974     return;
3975   }
3976
3977   // CHECK: empty format string?
3978   if (StrLen == 0 && numDataArgs > 0) {
3979     CheckFormatHandler::EmitFormatDiagnostic(
3980       *this, inFunctionCall, Args[format_idx],
3981       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3982       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3983     return;
3984   }
3985   
3986   if (Type == FST_Printf || Type == FST_NSString) {
3987     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3988                          numDataArgs, (Type == FST_NSString),
3989                          Str, HasVAListArg, Args, format_idx,
3990                          inFunctionCall, CallType, CheckedVarArgs);
3991   
3992     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3993                                                   getLangOpts(),
3994                                                   Context.getTargetInfo()))
3995       H.DoneProcessing();
3996   } else if (Type == FST_Scanf) {
3997     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3998                         Str, HasVAListArg, Args, format_idx,
3999                         inFunctionCall, CallType, CheckedVarArgs);
4000     
4001     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
4002                                                  getLangOpts(),
4003                                                  Context.getTargetInfo()))
4004       H.DoneProcessing();
4005   } // TODO: handle other formats
4006 }
4007
4008 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4009   // Str - The format string.  NOTE: this is NOT null-terminated!
4010   StringRef StrRef = FExpr->getString();
4011   const char *Str = StrRef.data();
4012   // Account for cases where the string literal is truncated in a declaration.
4013   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4014   assert(T && "String literal not of constant array type!");
4015   size_t TypeSize = T->getSize().getZExtValue();
4016   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4017   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4018                                                          getLangOpts(),
4019                                                          Context.getTargetInfo());
4020 }
4021
4022 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4023
4024 // Returns the related absolute value function that is larger, of 0 if one
4025 // does not exist.
4026 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4027   switch (AbsFunction) {
4028   default:
4029     return 0;
4030
4031   case Builtin::BI__builtin_abs:
4032     return Builtin::BI__builtin_labs;
4033   case Builtin::BI__builtin_labs:
4034     return Builtin::BI__builtin_llabs;
4035   case Builtin::BI__builtin_llabs:
4036     return 0;
4037
4038   case Builtin::BI__builtin_fabsf:
4039     return Builtin::BI__builtin_fabs;
4040   case Builtin::BI__builtin_fabs:
4041     return Builtin::BI__builtin_fabsl;
4042   case Builtin::BI__builtin_fabsl:
4043     return 0;
4044
4045   case Builtin::BI__builtin_cabsf:
4046     return Builtin::BI__builtin_cabs;
4047   case Builtin::BI__builtin_cabs:
4048     return Builtin::BI__builtin_cabsl;
4049   case Builtin::BI__builtin_cabsl:
4050     return 0;
4051
4052   case Builtin::BIabs:
4053     return Builtin::BIlabs;
4054   case Builtin::BIlabs:
4055     return Builtin::BIllabs;
4056   case Builtin::BIllabs:
4057     return 0;
4058
4059   case Builtin::BIfabsf:
4060     return Builtin::BIfabs;
4061   case Builtin::BIfabs:
4062     return Builtin::BIfabsl;
4063   case Builtin::BIfabsl:
4064     return 0;
4065
4066   case Builtin::BIcabsf:
4067    return Builtin::BIcabs;
4068   case Builtin::BIcabs:
4069     return Builtin::BIcabsl;
4070   case Builtin::BIcabsl:
4071     return 0;
4072   }
4073 }
4074
4075 // Returns the argument type of the absolute value function.
4076 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4077                                              unsigned AbsType) {
4078   if (AbsType == 0)
4079     return QualType();
4080
4081   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4082   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4083   if (Error != ASTContext::GE_None)
4084     return QualType();
4085
4086   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4087   if (!FT)
4088     return QualType();
4089
4090   if (FT->getNumParams() != 1)
4091     return QualType();
4092
4093   return FT->getParamType(0);
4094 }
4095
4096 // Returns the best absolute value function, or zero, based on type and
4097 // current absolute value function.
4098 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4099                                    unsigned AbsFunctionKind) {
4100   unsigned BestKind = 0;
4101   uint64_t ArgSize = Context.getTypeSize(ArgType);
4102   for (unsigned Kind = AbsFunctionKind; Kind != 0;
4103        Kind = getLargerAbsoluteValueFunction(Kind)) {
4104     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4105     if (Context.getTypeSize(ParamType) >= ArgSize) {
4106       if (BestKind == 0)
4107         BestKind = Kind;
4108       else if (Context.hasSameType(ParamType, ArgType)) {
4109         BestKind = Kind;
4110         break;
4111       }
4112     }
4113   }
4114   return BestKind;
4115 }
4116
4117 enum AbsoluteValueKind {
4118   AVK_Integer,
4119   AVK_Floating,
4120   AVK_Complex
4121 };
4122
4123 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4124   if (T->isIntegralOrEnumerationType())
4125     return AVK_Integer;
4126   if (T->isRealFloatingType())
4127     return AVK_Floating;
4128   if (T->isAnyComplexType())
4129     return AVK_Complex;
4130
4131   llvm_unreachable("Type not integer, floating, or complex");
4132 }
4133
4134 // Changes the absolute value function to a different type.  Preserves whether
4135 // the function is a builtin.
4136 static unsigned changeAbsFunction(unsigned AbsKind,
4137                                   AbsoluteValueKind ValueKind) {
4138   switch (ValueKind) {
4139   case AVK_Integer:
4140     switch (AbsKind) {
4141     default:
4142       return 0;
4143     case Builtin::BI__builtin_fabsf:
4144     case Builtin::BI__builtin_fabs:
4145     case Builtin::BI__builtin_fabsl:
4146     case Builtin::BI__builtin_cabsf:
4147     case Builtin::BI__builtin_cabs:
4148     case Builtin::BI__builtin_cabsl:
4149       return Builtin::BI__builtin_abs;
4150     case Builtin::BIfabsf:
4151     case Builtin::BIfabs:
4152     case Builtin::BIfabsl:
4153     case Builtin::BIcabsf:
4154     case Builtin::BIcabs:
4155     case Builtin::BIcabsl:
4156       return Builtin::BIabs;
4157     }
4158   case AVK_Floating:
4159     switch (AbsKind) {
4160     default:
4161       return 0;
4162     case Builtin::BI__builtin_abs:
4163     case Builtin::BI__builtin_labs:
4164     case Builtin::BI__builtin_llabs:
4165     case Builtin::BI__builtin_cabsf:
4166     case Builtin::BI__builtin_cabs:
4167     case Builtin::BI__builtin_cabsl:
4168       return Builtin::BI__builtin_fabsf;
4169     case Builtin::BIabs:
4170     case Builtin::BIlabs:
4171     case Builtin::BIllabs:
4172     case Builtin::BIcabsf:
4173     case Builtin::BIcabs:
4174     case Builtin::BIcabsl:
4175       return Builtin::BIfabsf;
4176     }
4177   case AVK_Complex:
4178     switch (AbsKind) {
4179     default:
4180       return 0;
4181     case Builtin::BI__builtin_abs:
4182     case Builtin::BI__builtin_labs:
4183     case Builtin::BI__builtin_llabs:
4184     case Builtin::BI__builtin_fabsf:
4185     case Builtin::BI__builtin_fabs:
4186     case Builtin::BI__builtin_fabsl:
4187       return Builtin::BI__builtin_cabsf;
4188     case Builtin::BIabs:
4189     case Builtin::BIlabs:
4190     case Builtin::BIllabs:
4191     case Builtin::BIfabsf:
4192     case Builtin::BIfabs:
4193     case Builtin::BIfabsl:
4194       return Builtin::BIcabsf;
4195     }
4196   }
4197   llvm_unreachable("Unable to convert function");
4198 }
4199
4200 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4201   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4202   if (!FnInfo)
4203     return 0;
4204
4205   switch (FDecl->getBuiltinID()) {
4206   default:
4207     return 0;
4208   case Builtin::BI__builtin_abs:
4209   case Builtin::BI__builtin_fabs:
4210   case Builtin::BI__builtin_fabsf:
4211   case Builtin::BI__builtin_fabsl:
4212   case Builtin::BI__builtin_labs:
4213   case Builtin::BI__builtin_llabs:
4214   case Builtin::BI__builtin_cabs:
4215   case Builtin::BI__builtin_cabsf:
4216   case Builtin::BI__builtin_cabsl:
4217   case Builtin::BIabs:
4218   case Builtin::BIlabs:
4219   case Builtin::BIllabs:
4220   case Builtin::BIfabs:
4221   case Builtin::BIfabsf:
4222   case Builtin::BIfabsl:
4223   case Builtin::BIcabs:
4224   case Builtin::BIcabsf:
4225   case Builtin::BIcabsl:
4226     return FDecl->getBuiltinID();
4227   }
4228   llvm_unreachable("Unknown Builtin type");
4229 }
4230
4231 // If the replacement is valid, emit a note with replacement function.
4232 // Additionally, suggest including the proper header if not already included.
4233 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
4234                             unsigned AbsKind, QualType ArgType) {
4235   bool EmitHeaderHint = true;
4236   const char *HeaderName = nullptr;
4237   const char *FunctionName = nullptr;
4238   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4239     FunctionName = "std::abs";
4240     if (ArgType->isIntegralOrEnumerationType()) {
4241       HeaderName = "cstdlib";
4242     } else if (ArgType->isRealFloatingType()) {
4243       HeaderName = "cmath";
4244     } else {
4245       llvm_unreachable("Invalid Type");
4246     }
4247
4248     // Lookup all std::abs
4249     if (NamespaceDecl *Std = S.getStdNamespace()) {
4250       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4251       R.suppressDiagnostics();
4252       S.LookupQualifiedName(R, Std);
4253
4254       for (const auto *I : R) {
4255         const FunctionDecl *FDecl = nullptr;
4256         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4257           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4258         } else {
4259           FDecl = dyn_cast<FunctionDecl>(I);
4260         }
4261         if (!FDecl)
4262           continue;
4263
4264         // Found std::abs(), check that they are the right ones.
4265         if (FDecl->getNumParams() != 1)
4266           continue;
4267
4268         // Check that the parameter type can handle the argument.
4269         QualType ParamType = FDecl->getParamDecl(0)->getType();
4270         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4271             S.Context.getTypeSize(ArgType) <=
4272                 S.Context.getTypeSize(ParamType)) {
4273           // Found a function, don't need the header hint.
4274           EmitHeaderHint = false;
4275           break;
4276         }
4277       }
4278     }
4279   } else {
4280     FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4281     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4282
4283     if (HeaderName) {
4284       DeclarationName DN(&S.Context.Idents.get(FunctionName));
4285       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4286       R.suppressDiagnostics();
4287       S.LookupName(R, S.getCurScope());
4288
4289       if (R.isSingleResult()) {
4290         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4291         if (FD && FD->getBuiltinID() == AbsKind) {
4292           EmitHeaderHint = false;
4293         } else {
4294           return;
4295         }
4296       } else if (!R.empty()) {
4297         return;
4298       }
4299     }
4300   }
4301
4302   S.Diag(Loc, diag::note_replace_abs_function)
4303       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
4304
4305   if (!HeaderName)
4306     return;
4307
4308   if (!EmitHeaderHint)
4309     return;
4310
4311   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4312                                                     << FunctionName;
4313 }
4314
4315 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4316   if (!FDecl)
4317     return false;
4318
4319   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4320     return false;
4321
4322   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4323
4324   while (ND && ND->isInlineNamespace()) {
4325     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
4326   }
4327
4328   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4329     return false;
4330
4331   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4332     return false;
4333
4334   return true;
4335 }
4336
4337 // Warn when using the wrong abs() function.
4338 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4339                                       const FunctionDecl *FDecl,
4340                                       IdentifierInfo *FnInfo) {
4341   if (Call->getNumArgs() != 1)
4342     return;
4343
4344   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
4345   bool IsStdAbs = IsFunctionStdAbs(FDecl);
4346   if (AbsKind == 0 && !IsStdAbs)
4347     return;
4348
4349   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4350   QualType ParamType = Call->getArg(0)->getType();
4351
4352   // Unsigned types cannot be negative.  Suggest removing the absolute value
4353   // function call.
4354   if (ArgType->isUnsignedIntegerType()) {
4355     const char *FunctionName =
4356         IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
4357     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4358     Diag(Call->getExprLoc(), diag::note_remove_abs)
4359         << FunctionName
4360         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4361     return;
4362   }
4363
4364   // std::abs has overloads which prevent most of the absolute value problems
4365   // from occurring.
4366   if (IsStdAbs)
4367     return;
4368
4369   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4370   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4371
4372   // The argument and parameter are the same kind.  Check if they are the right
4373   // size.
4374   if (ArgValueKind == ParamValueKind) {
4375     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4376       return;
4377
4378     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4379     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4380         << FDecl << ArgType << ParamType;
4381
4382     if (NewAbsKind == 0)
4383       return;
4384
4385     emitReplacement(*this, Call->getExprLoc(),
4386                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4387     return;
4388   }
4389
4390   // ArgValueKind != ParamValueKind
4391   // The wrong type of absolute value function was used.  Attempt to find the
4392   // proper one.
4393   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4394   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4395   if (NewAbsKind == 0)
4396     return;
4397
4398   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4399       << FDecl << ParamValueKind << ArgValueKind;
4400
4401   emitReplacement(*this, Call->getExprLoc(),
4402                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4403   return;
4404 }
4405
4406 //===--- CHECK: Standard memory functions ---------------------------------===//
4407
4408 /// \brief Takes the expression passed to the size_t parameter of functions
4409 /// such as memcmp, strncat, etc and warns if it's a comparison.
4410 ///
4411 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4412 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4413                                            IdentifierInfo *FnName,
4414                                            SourceLocation FnLoc,
4415                                            SourceLocation RParenLoc) {
4416   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4417   if (!Size)
4418     return false;
4419
4420   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4421   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4422     return false;
4423
4424   SourceRange SizeRange = Size->getSourceRange();
4425   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4426       << SizeRange << FnName;
4427   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4428       << FnName << FixItHint::CreateInsertion(
4429                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
4430       << FixItHint::CreateRemoval(RParenLoc);
4431   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
4432       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
4433       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4434                                     ")");
4435
4436   return true;
4437 }
4438
4439 /// \brief Determine whether the given type is or contains a dynamic class type
4440 /// (e.g., whether it has a vtable).
4441 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4442                                                      bool &IsContained) {
4443   // Look through array types while ignoring qualifiers.
4444   const Type *Ty = T->getBaseElementTypeUnsafe();
4445   IsContained = false;
4446
4447   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4448   RD = RD ? RD->getDefinition() : nullptr;
4449   if (!RD)
4450     return nullptr;
4451
4452   if (RD->isDynamicClass())
4453     return RD;
4454
4455   // Check all the fields.  If any bases were dynamic, the class is dynamic.
4456   // It's impossible for a class to transitively contain itself by value, so
4457   // infinite recursion is impossible.
4458   for (auto *FD : RD->fields()) {
4459     bool SubContained;
4460     if (const CXXRecordDecl *ContainedRD =
4461             getContainedDynamicClass(FD->getType(), SubContained)) {
4462       IsContained = true;
4463       return ContainedRD;
4464     }
4465   }
4466
4467   return nullptr;
4468 }
4469
4470 /// \brief If E is a sizeof expression, returns its argument expression,
4471 /// otherwise returns NULL.
4472 static const Expr *getSizeOfExprArg(const Expr* E) {
4473   if (const UnaryExprOrTypeTraitExpr *SizeOf =
4474       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4475     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4476       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
4477
4478   return nullptr;
4479 }
4480
4481 /// \brief If E is a sizeof expression, returns its argument type.
4482 static QualType getSizeOfArgType(const Expr* E) {
4483   if (const UnaryExprOrTypeTraitExpr *SizeOf =
4484       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4485     if (SizeOf->getKind() == clang::UETT_SizeOf)
4486       return SizeOf->getTypeOfArgument();
4487
4488   return QualType();
4489 }
4490
4491 /// \brief Check for dangerous or invalid arguments to memset().
4492 ///
4493 /// This issues warnings on known problematic, dangerous or unspecified
4494 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4495 /// function calls.
4496 ///
4497 /// \param Call The call expression to diagnose.
4498 void Sema::CheckMemaccessArguments(const CallExpr *Call,
4499                                    unsigned BId,
4500                                    IdentifierInfo *FnName) {
4501   assert(BId != 0);
4502
4503   // It is possible to have a non-standard definition of memset.  Validate
4504   // we have enough arguments, and if not, abort further checking.
4505   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4506   if (Call->getNumArgs() < ExpectedNumArgs)
4507     return;
4508
4509   unsigned LastArg = (BId == Builtin::BImemset ||
4510                       BId == Builtin::BIstrndup ? 1 : 2);
4511   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
4512   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4513
4514   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4515                                      Call->getLocStart(), Call->getRParenLoc()))
4516     return;
4517
4518   // We have special checking when the length is a sizeof expression.
4519   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4520   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4521   llvm::FoldingSetNodeID SizeOfArgID;
4522
4523   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4524     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4525     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4526
4527     QualType DestTy = Dest->getType();
4528     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4529       QualType PointeeTy = DestPtrTy->getPointeeType();
4530
4531       // Never warn about void type pointers. This can be used to suppress
4532       // false positives.
4533       if (PointeeTy->isVoidType())
4534         continue;
4535
4536       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4537       // actually comparing the expressions for equality. Because computing the
4538       // expression IDs can be expensive, we only do this if the diagnostic is
4539       // enabled.
4540       if (SizeOfArg &&
4541           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4542                            SizeOfArg->getExprLoc())) {
4543         // We only compute IDs for expressions if the warning is enabled, and
4544         // cache the sizeof arg's ID.
4545         if (SizeOfArgID == llvm::FoldingSetNodeID())
4546           SizeOfArg->Profile(SizeOfArgID, Context, true);
4547         llvm::FoldingSetNodeID DestID;
4548         Dest->Profile(DestID, Context, true);
4549         if (DestID == SizeOfArgID) {
4550           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4551           //       over sizeof(src) as well.
4552           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4553           StringRef ReadableName = FnName->getName();
4554
4555           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4556             if (UnaryOp->getOpcode() == UO_AddrOf)
4557               ActionIdx = 1; // If its an address-of operator, just remove it.
4558           if (!PointeeTy->isIncompleteType() &&
4559               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4560             ActionIdx = 2; // If the pointee's size is sizeof(char),
4561                            // suggest an explicit length.
4562
4563           // If the function is defined as a builtin macro, do not show macro
4564           // expansion.
4565           SourceLocation SL = SizeOfArg->getExprLoc();
4566           SourceRange DSR = Dest->getSourceRange();
4567           SourceRange SSR = SizeOfArg->getSourceRange();
4568           SourceManager &SM = getSourceManager();
4569
4570           if (SM.isMacroArgExpansion(SL)) {
4571             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4572             SL = SM.getSpellingLoc(SL);
4573             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4574                              SM.getSpellingLoc(DSR.getEnd()));
4575             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4576                              SM.getSpellingLoc(SSR.getEnd()));
4577           }
4578
4579           DiagRuntimeBehavior(SL, SizeOfArg,
4580                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4581                                 << ReadableName
4582                                 << PointeeTy
4583                                 << DestTy
4584                                 << DSR
4585                                 << SSR);
4586           DiagRuntimeBehavior(SL, SizeOfArg,
4587                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4588                                 << ActionIdx
4589                                 << SSR);
4590
4591           break;
4592         }
4593       }
4594
4595       // Also check for cases where the sizeof argument is the exact same
4596       // type as the memory argument, and where it points to a user-defined
4597       // record type.
4598       if (SizeOfArgTy != QualType()) {
4599         if (PointeeTy->isRecordType() &&
4600             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4601           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4602                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
4603                                 << FnName << SizeOfArgTy << ArgIdx
4604                                 << PointeeTy << Dest->getSourceRange()
4605                                 << LenExpr->getSourceRange());
4606           break;
4607         }
4608       }
4609
4610       // Always complain about dynamic classes.
4611       bool IsContained;
4612       if (const CXXRecordDecl *ContainedRD =
4613               getContainedDynamicClass(PointeeTy, IsContained)) {
4614
4615         unsigned OperationType = 0;
4616         // "overwritten" if we're warning about the destination for any call
4617         // but memcmp; otherwise a verb appropriate to the call.
4618         if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4619           if (BId == Builtin::BImemcpy)
4620             OperationType = 1;
4621           else if(BId == Builtin::BImemmove)
4622             OperationType = 2;
4623           else if (BId == Builtin::BImemcmp)
4624             OperationType = 3;
4625         }
4626           
4627         DiagRuntimeBehavior(
4628           Dest->getExprLoc(), Dest,
4629           PDiag(diag::warn_dyn_class_memaccess)
4630             << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4631             << FnName << IsContained << ContainedRD << OperationType
4632             << Call->getCallee()->getSourceRange());
4633       } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4634                BId != Builtin::BImemset)
4635         DiagRuntimeBehavior(
4636           Dest->getExprLoc(), Dest,
4637           PDiag(diag::warn_arc_object_memaccess)
4638             << ArgIdx << FnName << PointeeTy
4639             << Call->getCallee()->getSourceRange());
4640       else
4641         continue;
4642
4643       DiagRuntimeBehavior(
4644         Dest->getExprLoc(), Dest,
4645         PDiag(diag::note_bad_memaccess_silence)
4646           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4647       break;
4648     }
4649   }
4650 }
4651
4652 // A little helper routine: ignore addition and subtraction of integer literals.
4653 // This intentionally does not ignore all integer constant expressions because
4654 // we don't want to remove sizeof().
4655 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4656   Ex = Ex->IgnoreParenCasts();
4657
4658   for (;;) {
4659     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4660     if (!BO || !BO->isAdditiveOp())
4661       break;
4662
4663     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4664     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4665     
4666     if (isa<IntegerLiteral>(RHS))
4667       Ex = LHS;
4668     else if (isa<IntegerLiteral>(LHS))
4669       Ex = RHS;
4670     else
4671       break;
4672   }
4673
4674   return Ex;
4675 }
4676
4677 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4678                                                       ASTContext &Context) {
4679   // Only handle constant-sized or VLAs, but not flexible members.
4680   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4681     // Only issue the FIXIT for arrays of size > 1.
4682     if (CAT->getSize().getSExtValue() <= 1)
4683       return false;
4684   } else if (!Ty->isVariableArrayType()) {
4685     return false;
4686   }
4687   return true;
4688 }
4689
4690 // Warn if the user has made the 'size' argument to strlcpy or strlcat
4691 // be the size of the source, instead of the destination.
4692 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4693                                     IdentifierInfo *FnName) {
4694
4695   // Don't crash if the user has the wrong number of arguments
4696   unsigned NumArgs = Call->getNumArgs();
4697   if ((NumArgs != 3) && (NumArgs != 4))
4698     return;
4699
4700   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4701   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4702   const Expr *CompareWithSrc = nullptr;
4703
4704   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4705                                      Call->getLocStart(), Call->getRParenLoc()))
4706     return;
4707   
4708   // Look for 'strlcpy(dst, x, sizeof(x))'
4709   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4710     CompareWithSrc = Ex;
4711   else {
4712     // Look for 'strlcpy(dst, x, strlen(x))'
4713     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
4714       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4715           SizeCall->getNumArgs() == 1)
4716         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4717     }
4718   }
4719
4720   if (!CompareWithSrc)
4721     return;
4722
4723   // Determine if the argument to sizeof/strlen is equal to the source
4724   // argument.  In principle there's all kinds of things you could do
4725   // here, for instance creating an == expression and evaluating it with
4726   // EvaluateAsBooleanCondition, but this uses a more direct technique:
4727   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4728   if (!SrcArgDRE)
4729     return;
4730   
4731   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4732   if (!CompareWithSrcDRE || 
4733       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4734     return;
4735   
4736   const Expr *OriginalSizeArg = Call->getArg(2);
4737   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4738     << OriginalSizeArg->getSourceRange() << FnName;
4739   
4740   // Output a FIXIT hint if the destination is an array (rather than a
4741   // pointer to an array).  This could be enhanced to handle some
4742   // pointers if we know the actual size, like if DstArg is 'array+2'
4743   // we could say 'sizeof(array)-2'.
4744   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
4745   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
4746     return;
4747
4748   SmallString<128> sizeString;
4749   llvm::raw_svector_ostream OS(sizeString);
4750   OS << "sizeof(";
4751   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4752   OS << ")";
4753   
4754   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4755     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4756                                     OS.str());
4757 }
4758
4759 /// Check if two expressions refer to the same declaration.
4760 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4761   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4762     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4763       return D1->getDecl() == D2->getDecl();
4764   return false;
4765 }
4766
4767 static const Expr *getStrlenExprArg(const Expr *E) {
4768   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4769     const FunctionDecl *FD = CE->getDirectCallee();
4770     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4771       return nullptr;
4772     return CE->getArg(0)->IgnoreParenCasts();
4773   }
4774   return nullptr;
4775 }
4776
4777 // Warn on anti-patterns as the 'size' argument to strncat.
4778 // The correct size argument should look like following:
4779 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4780 void Sema::CheckStrncatArguments(const CallExpr *CE,
4781                                  IdentifierInfo *FnName) {
4782   // Don't crash if the user has the wrong number of arguments.
4783   if (CE->getNumArgs() < 3)
4784     return;
4785   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4786   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4787   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4788
4789   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4790                                      CE->getRParenLoc()))
4791     return;
4792
4793   // Identify common expressions, which are wrongly used as the size argument
4794   // to strncat and may lead to buffer overflows.
4795   unsigned PatternType = 0;
4796   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4797     // - sizeof(dst)
4798     if (referToTheSameDecl(SizeOfArg, DstArg))
4799       PatternType = 1;
4800     // - sizeof(src)
4801     else if (referToTheSameDecl(SizeOfArg, SrcArg))
4802       PatternType = 2;
4803   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4804     if (BE->getOpcode() == BO_Sub) {
4805       const Expr *L = BE->getLHS()->IgnoreParenCasts();
4806       const Expr *R = BE->getRHS()->IgnoreParenCasts();
4807       // - sizeof(dst) - strlen(dst)
4808       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4809           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4810         PatternType = 1;
4811       // - sizeof(src) - (anything)
4812       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4813         PatternType = 2;
4814     }
4815   }
4816
4817   if (PatternType == 0)
4818     return;
4819
4820   // Generate the diagnostic.
4821   SourceLocation SL = LenArg->getLocStart();
4822   SourceRange SR = LenArg->getSourceRange();
4823   SourceManager &SM = getSourceManager();
4824
4825   // If the function is defined as a builtin macro, do not show macro expansion.
4826   if (SM.isMacroArgExpansion(SL)) {
4827     SL = SM.getSpellingLoc(SL);
4828     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4829                      SM.getSpellingLoc(SR.getEnd()));
4830   }
4831
4832   // Check if the destination is an array (rather than a pointer to an array).
4833   QualType DstTy = DstArg->getType();
4834   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4835                                                                     Context);
4836   if (!isKnownSizeArray) {
4837     if (PatternType == 1)
4838       Diag(SL, diag::warn_strncat_wrong_size) << SR;
4839     else
4840       Diag(SL, diag::warn_strncat_src_size) << SR;
4841     return;
4842   }
4843
4844   if (PatternType == 1)
4845     Diag(SL, diag::warn_strncat_large_size) << SR;
4846   else
4847     Diag(SL, diag::warn_strncat_src_size) << SR;
4848
4849   SmallString<128> sizeString;
4850   llvm::raw_svector_ostream OS(sizeString);
4851   OS << "sizeof(";
4852   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4853   OS << ") - ";
4854   OS << "strlen(";
4855   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4856   OS << ") - 1";
4857
4858   Diag(SL, diag::note_strncat_wrong_size)
4859     << FixItHint::CreateReplacement(SR, OS.str());
4860 }
4861
4862 //===--- CHECK: Return Address of Stack Variable --------------------------===//
4863
4864 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4865                      Decl *ParentDecl);
4866 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4867                       Decl *ParentDecl);
4868
4869 /// CheckReturnStackAddr - Check if a return statement returns the address
4870 ///   of a stack variable.
4871 static void
4872 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4873                      SourceLocation ReturnLoc) {
4874
4875   Expr *stackE = nullptr;
4876   SmallVector<DeclRefExpr *, 8> refVars;
4877
4878   // Perform checking for returned stack addresses, local blocks,
4879   // label addresses or references to temporaries.
4880   if (lhsType->isPointerType() ||
4881       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4882     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
4883   } else if (lhsType->isReferenceType()) {
4884     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
4885   }
4886
4887   if (!stackE)
4888     return; // Nothing suspicious was found.
4889
4890   SourceLocation diagLoc;
4891   SourceRange diagRange;
4892   if (refVars.empty()) {
4893     diagLoc = stackE->getLocStart();
4894     diagRange = stackE->getSourceRange();
4895   } else {
4896     // We followed through a reference variable. 'stackE' contains the
4897     // problematic expression but we will warn at the return statement pointing
4898     // at the reference variable. We will later display the "trail" of
4899     // reference variables using notes.
4900     diagLoc = refVars[0]->getLocStart();
4901     diagRange = refVars[0]->getSourceRange();
4902   }
4903
4904   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4905     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4906                                              : diag::warn_ret_stack_addr)
4907      << DR->getDecl()->getDeclName() << diagRange;
4908   } else if (isa<BlockExpr>(stackE)) { // local block.
4909     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4910   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4911     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4912   } else { // local temporary.
4913     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4914                                                : diag::warn_ret_local_temp_addr)
4915      << diagRange;
4916   }
4917
4918   // Display the "trail" of reference variables that we followed until we
4919   // found the problematic expression using notes.
4920   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4921     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4922     // If this var binds to another reference var, show the range of the next
4923     // var, otherwise the var binds to the problematic expression, in which case
4924     // show the range of the expression.
4925     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4926                                   : stackE->getSourceRange();
4927     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4928         << VD->getDeclName() << range;
4929   }
4930 }
4931
4932 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4933 ///  check if the expression in a return statement evaluates to an address
4934 ///  to a location on the stack, a local block, an address of a label, or a
4935 ///  reference to local temporary. The recursion is used to traverse the
4936 ///  AST of the return expression, with recursion backtracking when we
4937 ///  encounter a subexpression that (1) clearly does not lead to one of the
4938 ///  above problematic expressions (2) is something we cannot determine leads to
4939 ///  a problematic expression based on such local checking.
4940 ///
4941 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
4942 ///  the expression that they point to. Such variables are added to the
4943 ///  'refVars' vector so that we know what the reference variable "trail" was.
4944 ///
4945 ///  EvalAddr processes expressions that are pointers that are used as
4946 ///  references (and not L-values).  EvalVal handles all other values.
4947 ///  At the base case of the recursion is a check for the above problematic
4948 ///  expressions.
4949 ///
4950 ///  This implementation handles:
4951 ///
4952 ///   * pointer-to-pointer casts
4953 ///   * implicit conversions from array references to pointers
4954 ///   * taking the address of fields
4955 ///   * arbitrary interplay between "&" and "*" operators
4956 ///   * pointer arithmetic from an address of a stack variable
4957 ///   * taking the address of an array element where the array is on the stack
4958 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4959                       Decl *ParentDecl) {
4960   if (E->isTypeDependent())
4961     return nullptr;
4962
4963   // We should only be called for evaluating pointer expressions.
4964   assert((E->getType()->isAnyPointerType() ||
4965           E->getType()->isBlockPointerType() ||
4966           E->getType()->isObjCQualifiedIdType()) &&
4967          "EvalAddr only works on pointers");
4968
4969   E = E->IgnoreParens();
4970
4971   // Our "symbolic interpreter" is just a dispatch off the currently
4972   // viewed AST node.  We then recursively traverse the AST by calling
4973   // EvalAddr and EvalVal appropriately.
4974   switch (E->getStmtClass()) {
4975   case Stmt::DeclRefExprClass: {
4976     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4977
4978     // If we leave the immediate function, the lifetime isn't about to end.
4979     if (DR->refersToEnclosingVariableOrCapture())
4980       return nullptr;
4981
4982     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4983       // If this is a reference variable, follow through to the expression that
4984       // it points to.
4985       if (V->hasLocalStorage() &&
4986           V->getType()->isReferenceType() && V->hasInit()) {
4987         // Add the reference variable to the "trail".
4988         refVars.push_back(DR);
4989         return EvalAddr(V->getInit(), refVars, ParentDecl);
4990       }
4991
4992     return nullptr;
4993   }
4994
4995   case Stmt::UnaryOperatorClass: {
4996     // The only unary operator that make sense to handle here
4997     // is AddrOf.  All others don't make sense as pointers.
4998     UnaryOperator *U = cast<UnaryOperator>(E);
4999
5000     if (U->getOpcode() == UO_AddrOf)
5001       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
5002     else
5003       return nullptr;
5004   }
5005
5006   case Stmt::BinaryOperatorClass: {
5007     // Handle pointer arithmetic.  All other binary operators are not valid
5008     // in this context.
5009     BinaryOperator *B = cast<BinaryOperator>(E);
5010     BinaryOperatorKind op = B->getOpcode();
5011
5012     if (op != BO_Add && op != BO_Sub)
5013       return nullptr;
5014
5015     Expr *Base = B->getLHS();
5016
5017     // Determine which argument is the real pointer base.  It could be
5018     // the RHS argument instead of the LHS.
5019     if (!Base->getType()->isPointerType()) Base = B->getRHS();
5020
5021     assert (Base->getType()->isPointerType());
5022     return EvalAddr(Base, refVars, ParentDecl);
5023   }
5024
5025   // For conditional operators we need to see if either the LHS or RHS are
5026   // valid DeclRefExpr*s.  If one of them is valid, we return it.
5027   case Stmt::ConditionalOperatorClass: {
5028     ConditionalOperator *C = cast<ConditionalOperator>(E);
5029
5030     // Handle the GNU extension for missing LHS.
5031     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5032     if (Expr *LHSExpr = C->getLHS()) {
5033       // In C++, we can have a throw-expression, which has 'void' type.
5034       if (!LHSExpr->getType()->isVoidType())
5035         if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
5036           return LHS;
5037     }
5038
5039     // In C++, we can have a throw-expression, which has 'void' type.
5040     if (C->getRHS()->getType()->isVoidType())
5041       return nullptr;
5042
5043     return EvalAddr(C->getRHS(), refVars, ParentDecl);
5044   }
5045
5046   case Stmt::BlockExprClass:
5047     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5048       return E; // local block.
5049     return nullptr;
5050
5051   case Stmt::AddrLabelExprClass:
5052     return E; // address of label.
5053
5054   case Stmt::ExprWithCleanupsClass:
5055     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5056                     ParentDecl);
5057
5058   // For casts, we need to handle conversions from arrays to
5059   // pointer values, and pointer-to-pointer conversions.
5060   case Stmt::ImplicitCastExprClass:
5061   case Stmt::CStyleCastExprClass:
5062   case Stmt::CXXFunctionalCastExprClass:
5063   case Stmt::ObjCBridgedCastExprClass:
5064   case Stmt::CXXStaticCastExprClass:
5065   case Stmt::CXXDynamicCastExprClass:
5066   case Stmt::CXXConstCastExprClass:
5067   case Stmt::CXXReinterpretCastExprClass: {
5068     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5069     switch (cast<CastExpr>(E)->getCastKind()) {
5070     case CK_LValueToRValue:
5071     case CK_NoOp:
5072     case CK_BaseToDerived:
5073     case CK_DerivedToBase:
5074     case CK_UncheckedDerivedToBase:
5075     case CK_Dynamic:
5076     case CK_CPointerToObjCPointerCast:
5077     case CK_BlockPointerToObjCPointerCast:
5078     case CK_AnyPointerToBlockPointerCast:
5079       return EvalAddr(SubExpr, refVars, ParentDecl);
5080
5081     case CK_ArrayToPointerDecay:
5082       return EvalVal(SubExpr, refVars, ParentDecl);
5083
5084     case CK_BitCast:
5085       if (SubExpr->getType()->isAnyPointerType() ||
5086           SubExpr->getType()->isBlockPointerType() ||
5087           SubExpr->getType()->isObjCQualifiedIdType())
5088         return EvalAddr(SubExpr, refVars, ParentDecl);
5089       else
5090         return nullptr;
5091
5092     default:
5093       return nullptr;
5094     }
5095   }
5096
5097   case Stmt::MaterializeTemporaryExprClass:
5098     if (Expr *Result = EvalAddr(
5099                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5100                                 refVars, ParentDecl))
5101       return Result;
5102       
5103     return E;
5104       
5105   // Everything else: we simply don't reason about them.
5106   default:
5107     return nullptr;
5108   }
5109 }
5110
5111
5112 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
5113 ///   See the comments for EvalAddr for more details.
5114 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5115                      Decl *ParentDecl) {
5116 do {
5117   // We should only be called for evaluating non-pointer expressions, or
5118   // expressions with a pointer type that are not used as references but instead
5119   // are l-values (e.g., DeclRefExpr with a pointer type).
5120
5121   // Our "symbolic interpreter" is just a dispatch off the currently
5122   // viewed AST node.  We then recursively traverse the AST by calling
5123   // EvalAddr and EvalVal appropriately.
5124
5125   E = E->IgnoreParens();
5126   switch (E->getStmtClass()) {
5127   case Stmt::ImplicitCastExprClass: {
5128     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
5129     if (IE->getValueKind() == VK_LValue) {
5130       E = IE->getSubExpr();
5131       continue;
5132     }
5133     return nullptr;
5134   }
5135
5136   case Stmt::ExprWithCleanupsClass:
5137     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5138
5139   case Stmt::DeclRefExprClass: {
5140     // When we hit a DeclRefExpr we are looking at code that refers to a
5141     // variable's name. If it's not a reference variable we check if it has
5142     // local storage within the function, and if so, return the expression.
5143     DeclRefExpr *DR = cast<DeclRefExpr>(E);
5144
5145     // If we leave the immediate function, the lifetime isn't about to end.
5146     if (DR->refersToEnclosingVariableOrCapture())
5147       return nullptr;
5148
5149     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5150       // Check if it refers to itself, e.g. "int& i = i;".
5151       if (V == ParentDecl)
5152         return DR;
5153
5154       if (V->hasLocalStorage()) {
5155         if (!V->getType()->isReferenceType())
5156           return DR;
5157
5158         // Reference variable, follow through to the expression that
5159         // it points to.
5160         if (V->hasInit()) {
5161           // Add the reference variable to the "trail".
5162           refVars.push_back(DR);
5163           return EvalVal(V->getInit(), refVars, V);
5164         }
5165       }
5166     }
5167
5168     return nullptr;
5169   }
5170
5171   case Stmt::UnaryOperatorClass: {
5172     // The only unary operator that make sense to handle here
5173     // is Deref.  All others don't resolve to a "name."  This includes
5174     // handling all sorts of rvalues passed to a unary operator.
5175     UnaryOperator *U = cast<UnaryOperator>(E);
5176
5177     if (U->getOpcode() == UO_Deref)
5178       return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
5179
5180     return nullptr;
5181   }
5182
5183   case Stmt::ArraySubscriptExprClass: {
5184     // Array subscripts are potential references to data on the stack.  We
5185     // retrieve the DeclRefExpr* for the array variable if it indeed
5186     // has local storage.
5187     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5188   }
5189
5190   case Stmt::ConditionalOperatorClass: {
5191     // For conditional operators we need to see if either the LHS or RHS are
5192     // non-NULL Expr's.  If one is non-NULL, we return it.
5193     ConditionalOperator *C = cast<ConditionalOperator>(E);
5194
5195     // Handle the GNU extension for missing LHS.
5196     if (Expr *LHSExpr = C->getLHS()) {
5197       // In C++, we can have a throw-expression, which has 'void' type.
5198       if (!LHSExpr->getType()->isVoidType())
5199         if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5200           return LHS;
5201     }
5202
5203     // In C++, we can have a throw-expression, which has 'void' type.
5204     if (C->getRHS()->getType()->isVoidType())
5205       return nullptr;
5206
5207     return EvalVal(C->getRHS(), refVars, ParentDecl);
5208   }
5209
5210   // Accesses to members are potential references to data on the stack.
5211   case Stmt::MemberExprClass: {
5212     MemberExpr *M = cast<MemberExpr>(E);
5213
5214     // Check for indirect access.  We only want direct field accesses.
5215     if (M->isArrow())
5216       return nullptr;
5217
5218     // Check whether the member type is itself a reference, in which case
5219     // we're not going to refer to the member, but to what the member refers to.
5220     if (M->getMemberDecl()->getType()->isReferenceType())
5221       return nullptr;
5222
5223     return EvalVal(M->getBase(), refVars, ParentDecl);
5224   }
5225
5226   case Stmt::MaterializeTemporaryExprClass:
5227     if (Expr *Result = EvalVal(
5228                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5229                                refVars, ParentDecl))
5230       return Result;
5231       
5232     return E;
5233
5234   default:
5235     // Check that we don't return or take the address of a reference to a
5236     // temporary. This is only useful in C++.
5237     if (!E->isTypeDependent() && E->isRValue())
5238       return E;
5239
5240     // Everything else: we simply don't reason about them.
5241     return nullptr;
5242   }
5243 } while (true);
5244 }
5245
5246 void
5247 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5248                          SourceLocation ReturnLoc,
5249                          bool isObjCMethod,
5250                          const AttrVec *Attrs,
5251                          const FunctionDecl *FD) {
5252   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5253
5254   // Check if the return value is null but should not be.
5255   if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5256       CheckNonNullExpr(*this, RetValExp))
5257     Diag(ReturnLoc, diag::warn_null_ret)
5258       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5259
5260   // C++11 [basic.stc.dynamic.allocation]p4:
5261   //   If an allocation function declared with a non-throwing
5262   //   exception-specification fails to allocate storage, it shall return
5263   //   a null pointer. Any other allocation function that fails to allocate
5264   //   storage shall indicate failure only by throwing an exception [...]
5265   if (FD) {
5266     OverloadedOperatorKind Op = FD->getOverloadedOperator();
5267     if (Op == OO_New || Op == OO_Array_New) {
5268       const FunctionProtoType *Proto
5269         = FD->getType()->castAs<FunctionProtoType>();
5270       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5271           CheckNonNullExpr(*this, RetValExp))
5272         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5273           << FD << getLangOpts().CPlusPlus11;
5274     }
5275   }
5276 }
5277
5278 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5279
5280 /// Check for comparisons of floating point operands using != and ==.
5281 /// Issue a warning if these are no self-comparisons, as they are not likely
5282 /// to do what the programmer intended.
5283 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
5284   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5285   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
5286
5287   // Special case: check for x == x (which is OK).
5288   // Do not emit warnings for such cases.
5289   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5290     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5291       if (DRL->getDecl() == DRR->getDecl())
5292         return;
5293
5294
5295   // Special case: check for comparisons against literals that can be exactly
5296   //  represented by APFloat.  In such cases, do not emit a warning.  This
5297   //  is a heuristic: often comparison against such literals are used to
5298   //  detect if a value in a variable has not changed.  This clearly can
5299   //  lead to false negatives.
5300   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5301     if (FLL->isExact())
5302       return;
5303   } else
5304     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5305       if (FLR->isExact())
5306         return;
5307
5308   // Check for comparisons with builtin types.
5309   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
5310     if (CL->getBuiltinCallee())
5311       return;
5312
5313   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
5314     if (CR->getBuiltinCallee())
5315       return;
5316
5317   // Emit the diagnostic.
5318   Diag(Loc, diag::warn_floatingpoint_eq)
5319     << LHS->getSourceRange() << RHS->getSourceRange();
5320 }
5321
5322 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5323 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
5324
5325 namespace {
5326
5327 /// Structure recording the 'active' range of an integer-valued
5328 /// expression.
5329 struct IntRange {
5330   /// The number of bits active in the int.
5331   unsigned Width;
5332
5333   /// True if the int is known not to have negative values.
5334   bool NonNegative;
5335
5336   IntRange(unsigned Width, bool NonNegative)
5337     : Width(Width), NonNegative(NonNegative)
5338   {}
5339
5340   /// Returns the range of the bool type.
5341   static IntRange forBoolType() {
5342     return IntRange(1, true);
5343   }
5344
5345   /// Returns the range of an opaque value of the given integral type.
5346   static IntRange forValueOfType(ASTContext &C, QualType T) {
5347     return forValueOfCanonicalType(C,
5348                           T->getCanonicalTypeInternal().getTypePtr());
5349   }
5350
5351   /// Returns the range of an opaque value of a canonical integral type.
5352   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
5353     assert(T->isCanonicalUnqualified());
5354
5355     if (const VectorType *VT = dyn_cast<VectorType>(T))
5356       T = VT->getElementType().getTypePtr();
5357     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5358       T = CT->getElementType().getTypePtr();
5359     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5360       T = AT->getValueType().getTypePtr();
5361
5362     // For enum types, use the known bit width of the enumerators.
5363     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
5364       EnumDecl *Enum = ET->getDecl();
5365       if (!Enum->isCompleteDefinition())
5366         return IntRange(C.getIntWidth(QualType(T, 0)), false);
5367
5368       unsigned NumPositive = Enum->getNumPositiveBits();
5369       unsigned NumNegative = Enum->getNumNegativeBits();
5370
5371       if (NumNegative == 0)
5372         return IntRange(NumPositive, true/*NonNegative*/);
5373       else
5374         return IntRange(std::max(NumPositive + 1, NumNegative),
5375                         false/*NonNegative*/);
5376     }
5377
5378     const BuiltinType *BT = cast<BuiltinType>(T);
5379     assert(BT->isInteger());
5380
5381     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5382   }
5383
5384   /// Returns the "target" range of a canonical integral type, i.e.
5385   /// the range of values expressible in the type.
5386   ///
5387   /// This matches forValueOfCanonicalType except that enums have the
5388   /// full range of their type, not the range of their enumerators.
5389   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5390     assert(T->isCanonicalUnqualified());
5391
5392     if (const VectorType *VT = dyn_cast<VectorType>(T))
5393       T = VT->getElementType().getTypePtr();
5394     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5395       T = CT->getElementType().getTypePtr();
5396     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5397       T = AT->getValueType().getTypePtr();
5398     if (const EnumType *ET = dyn_cast<EnumType>(T))
5399       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
5400
5401     const BuiltinType *BT = cast<BuiltinType>(T);
5402     assert(BT->isInteger());
5403
5404     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5405   }
5406
5407   /// Returns the supremum of two ranges: i.e. their conservative merge.
5408   static IntRange join(IntRange L, IntRange R) {
5409     return IntRange(std::max(L.Width, R.Width),
5410                     L.NonNegative && R.NonNegative);
5411   }
5412
5413   /// Returns the infinum of two ranges: i.e. their aggressive merge.
5414   static IntRange meet(IntRange L, IntRange R) {
5415     return IntRange(std::min(L.Width, R.Width),
5416                     L.NonNegative || R.NonNegative);
5417   }
5418 };
5419
5420 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5421                               unsigned MaxWidth) {
5422   if (value.isSigned() && value.isNegative())
5423     return IntRange(value.getMinSignedBits(), false);
5424
5425   if (value.getBitWidth() > MaxWidth)
5426     value = value.trunc(MaxWidth);
5427
5428   // isNonNegative() just checks the sign bit without considering
5429   // signedness.
5430   return IntRange(value.getActiveBits(), true);
5431 }
5432
5433 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5434                               unsigned MaxWidth) {
5435   if (result.isInt())
5436     return GetValueRange(C, result.getInt(), MaxWidth);
5437
5438   if (result.isVector()) {
5439     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5440     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5441       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5442       R = IntRange::join(R, El);
5443     }
5444     return R;
5445   }
5446
5447   if (result.isComplexInt()) {
5448     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5449     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5450     return IntRange::join(R, I);
5451   }
5452
5453   // This can happen with lossless casts to intptr_t of "based" lvalues.
5454   // Assume it might use arbitrary bits.
5455   // FIXME: The only reason we need to pass the type in here is to get
5456   // the sign right on this one case.  It would be nice if APValue
5457   // preserved this.
5458   assert(result.isLValue() || result.isAddrLabelDiff());
5459   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
5460 }
5461
5462 static QualType GetExprType(Expr *E) {
5463   QualType Ty = E->getType();
5464   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5465     Ty = AtomicRHS->getValueType();
5466   return Ty;
5467 }
5468
5469 /// Pseudo-evaluate the given integer expression, estimating the
5470 /// range of values it might take.
5471 ///
5472 /// \param MaxWidth - the width to which the value will be truncated
5473 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
5474   E = E->IgnoreParens();
5475
5476   // Try a full evaluation first.
5477   Expr::EvalResult result;
5478   if (E->EvaluateAsRValue(result, C))
5479     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
5480
5481   // I think we only want to look through implicit casts here; if the
5482   // user has an explicit widening cast, we should treat the value as
5483   // being of the new, wider type.
5484   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
5485     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
5486       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5487
5488     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
5489
5490     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
5491
5492     // Assume that non-integer casts can span the full range of the type.
5493     if (!isIntegerCast)
5494       return OutputTypeRange;
5495
5496     IntRange SubRange
5497       = GetExprRange(C, CE->getSubExpr(),
5498                      std::min(MaxWidth, OutputTypeRange.Width));
5499
5500     // Bail out if the subexpr's range is as wide as the cast type.
5501     if (SubRange.Width >= OutputTypeRange.Width)
5502       return OutputTypeRange;
5503
5504     // Otherwise, we take the smaller width, and we're non-negative if
5505     // either the output type or the subexpr is.
5506     return IntRange(SubRange.Width,
5507                     SubRange.NonNegative || OutputTypeRange.NonNegative);
5508   }
5509
5510   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5511     // If we can fold the condition, just take that operand.
5512     bool CondResult;
5513     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5514       return GetExprRange(C, CondResult ? CO->getTrueExpr()
5515                                         : CO->getFalseExpr(),
5516                           MaxWidth);
5517
5518     // Otherwise, conservatively merge.
5519     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5520     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5521     return IntRange::join(L, R);
5522   }
5523
5524   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5525     switch (BO->getOpcode()) {
5526
5527     // Boolean-valued operations are single-bit and positive.
5528     case BO_LAnd:
5529     case BO_LOr:
5530     case BO_LT:
5531     case BO_GT:
5532     case BO_LE:
5533     case BO_GE:
5534     case BO_EQ:
5535     case BO_NE:
5536       return IntRange::forBoolType();
5537
5538     // The type of the assignments is the type of the LHS, so the RHS
5539     // is not necessarily the same type.
5540     case BO_MulAssign:
5541     case BO_DivAssign:
5542     case BO_RemAssign:
5543     case BO_AddAssign:
5544     case BO_SubAssign:
5545     case BO_XorAssign:
5546     case BO_OrAssign:
5547       // TODO: bitfields?
5548       return IntRange::forValueOfType(C, GetExprType(E));
5549
5550     // Simple assignments just pass through the RHS, which will have
5551     // been coerced to the LHS type.
5552     case BO_Assign:
5553       // TODO: bitfields?
5554       return GetExprRange(C, BO->getRHS(), MaxWidth);
5555
5556     // Operations with opaque sources are black-listed.
5557     case BO_PtrMemD:
5558     case BO_PtrMemI:
5559       return IntRange::forValueOfType(C, GetExprType(E));
5560
5561     // Bitwise-and uses the *infinum* of the two source ranges.
5562     case BO_And:
5563     case BO_AndAssign:
5564       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5565                             GetExprRange(C, BO->getRHS(), MaxWidth));
5566
5567     // Left shift gets black-listed based on a judgement call.
5568     case BO_Shl:
5569       // ...except that we want to treat '1 << (blah)' as logically
5570       // positive.  It's an important idiom.
5571       if (IntegerLiteral *I
5572             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5573         if (I->getValue() == 1) {
5574           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5575           return IntRange(R.Width, /*NonNegative*/ true);
5576         }
5577       }
5578       // fallthrough
5579
5580     case BO_ShlAssign:
5581       return IntRange::forValueOfType(C, GetExprType(E));
5582
5583     // Right shift by a constant can narrow its left argument.
5584     case BO_Shr:
5585     case BO_ShrAssign: {
5586       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5587
5588       // If the shift amount is a positive constant, drop the width by
5589       // that much.
5590       llvm::APSInt shift;
5591       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5592           shift.isNonNegative()) {
5593         unsigned zext = shift.getZExtValue();
5594         if (zext >= L.Width)
5595           L.Width = (L.NonNegative ? 0 : 1);
5596         else
5597           L.Width -= zext;
5598       }
5599
5600       return L;
5601     }
5602
5603     // Comma acts as its right operand.
5604     case BO_Comma:
5605       return GetExprRange(C, BO->getRHS(), MaxWidth);
5606
5607     // Black-list pointer subtractions.
5608     case BO_Sub:
5609       if (BO->getLHS()->getType()->isPointerType())
5610         return IntRange::forValueOfType(C, GetExprType(E));
5611       break;
5612
5613     // The width of a division result is mostly determined by the size
5614     // of the LHS.
5615     case BO_Div: {
5616       // Don't 'pre-truncate' the operands.
5617       unsigned opWidth = C.getIntWidth(GetExprType(E));
5618       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5619
5620       // If the divisor is constant, use that.
5621       llvm::APSInt divisor;
5622       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5623         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5624         if (log2 >= L.Width)
5625           L.Width = (L.NonNegative ? 0 : 1);
5626         else
5627           L.Width = std::min(L.Width - log2, MaxWidth);
5628         return L;
5629       }
5630
5631       // Otherwise, just use the LHS's width.
5632       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5633       return IntRange(L.Width, L.NonNegative && R.NonNegative);
5634     }
5635
5636     // The result of a remainder can't be larger than the result of
5637     // either side.
5638     case BO_Rem: {
5639       // Don't 'pre-truncate' the operands.
5640       unsigned opWidth = C.getIntWidth(GetExprType(E));
5641       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5642       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5643
5644       IntRange meet = IntRange::meet(L, R);
5645       meet.Width = std::min(meet.Width, MaxWidth);
5646       return meet;
5647     }
5648
5649     // The default behavior is okay for these.
5650     case BO_Mul:
5651     case BO_Add:
5652     case BO_Xor:
5653     case BO_Or:
5654       break;
5655     }
5656
5657     // The default case is to treat the operation as if it were closed
5658     // on the narrowest type that encompasses both operands.
5659     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5660     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5661     return IntRange::join(L, R);
5662   }
5663
5664   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5665     switch (UO->getOpcode()) {
5666     // Boolean-valued operations are white-listed.
5667     case UO_LNot:
5668       return IntRange::forBoolType();
5669
5670     // Operations with opaque sources are black-listed.
5671     case UO_Deref:
5672     case UO_AddrOf: // should be impossible
5673       return IntRange::forValueOfType(C, GetExprType(E));
5674
5675     default:
5676       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5677     }
5678   }
5679
5680   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5681     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5682
5683   if (FieldDecl *BitField = E->getSourceBitField())
5684     return IntRange(BitField->getBitWidthValue(C),
5685                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
5686
5687   return IntRange::forValueOfType(C, GetExprType(E));
5688 }
5689
5690 static IntRange GetExprRange(ASTContext &C, Expr *E) {
5691   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5692 }
5693
5694 /// Checks whether the given value, which currently has the given
5695 /// source semantics, has the same value when coerced through the
5696 /// target semantics.
5697 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5698                                  const llvm::fltSemantics &Src,
5699                                  const llvm::fltSemantics &Tgt) {
5700   llvm::APFloat truncated = value;
5701
5702   bool ignored;
5703   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5704   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5705
5706   return truncated.bitwiseIsEqual(value);
5707 }
5708
5709 /// Checks whether the given value, which currently has the given
5710 /// source semantics, has the same value when coerced through the
5711 /// target semantics.
5712 ///
5713 /// The value might be a vector of floats (or a complex number).
5714 static bool IsSameFloatAfterCast(const APValue &value,
5715                                  const llvm::fltSemantics &Src,
5716                                  const llvm::fltSemantics &Tgt) {
5717   if (value.isFloat())
5718     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5719
5720   if (value.isVector()) {
5721     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5722       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5723         return false;
5724     return true;
5725   }
5726
5727   assert(value.isComplexFloat());
5728   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5729           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5730 }
5731
5732 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
5733
5734 static bool IsZero(Sema &S, Expr *E) {
5735   // Suppress cases where we are comparing against an enum constant.
5736   if (const DeclRefExpr *DR =
5737       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5738     if (isa<EnumConstantDecl>(DR->getDecl()))
5739       return false;
5740
5741   // Suppress cases where the '0' value is expanded from a macro.
5742   if (E->getLocStart().isMacroID())
5743     return false;
5744
5745   llvm::APSInt Value;
5746   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5747 }
5748
5749 static bool HasEnumType(Expr *E) {
5750   // Strip off implicit integral promotions.
5751   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5752     if (ICE->getCastKind() != CK_IntegralCast &&
5753         ICE->getCastKind() != CK_NoOp)
5754       break;
5755     E = ICE->getSubExpr();
5756   }
5757
5758   return E->getType()->isEnumeralType();
5759 }
5760
5761 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
5762   // Disable warning in template instantiations.
5763   if (!S.ActiveTemplateInstantiations.empty())
5764     return;
5765
5766   BinaryOperatorKind op = E->getOpcode();
5767   if (E->isValueDependent())
5768     return;
5769
5770   if (op == BO_LT && IsZero(S, E->getRHS())) {
5771     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5772       << "< 0" << "false" << HasEnumType(E->getLHS())
5773       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5774   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
5775     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5776       << ">= 0" << "true" << HasEnumType(E->getLHS())
5777       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5778   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
5779     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5780       << "0 >" << "false" << HasEnumType(E->getRHS())
5781       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5782   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
5783     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5784       << "0 <=" << "true" << HasEnumType(E->getRHS())
5785       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5786   }
5787 }
5788
5789 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
5790                                          Expr *Constant, Expr *Other,
5791                                          llvm::APSInt Value,
5792                                          bool RhsConstant) {
5793   // Disable warning in template instantiations.
5794   if (!S.ActiveTemplateInstantiations.empty())
5795     return;
5796
5797   // TODO: Investigate using GetExprRange() to get tighter bounds
5798   // on the bit ranges.
5799   QualType OtherT = Other->getType();
5800   if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5801     OtherT = AT->getValueType();
5802   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5803   unsigned OtherWidth = OtherRange.Width;
5804
5805   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5806
5807   // 0 values are handled later by CheckTrivialUnsignedComparison().
5808   if ((Value == 0) && (!OtherIsBooleanType))
5809     return;
5810
5811   BinaryOperatorKind op = E->getOpcode();
5812   bool IsTrue = true;
5813
5814   // Used for diagnostic printout.
5815   enum {
5816     LiteralConstant = 0,
5817     CXXBoolLiteralTrue,
5818     CXXBoolLiteralFalse
5819   } LiteralOrBoolConstant = LiteralConstant;
5820
5821   if (!OtherIsBooleanType) {
5822     QualType ConstantT = Constant->getType();
5823     QualType CommonT = E->getLHS()->getType();
5824
5825     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5826       return;
5827     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5828            "comparison with non-integer type");
5829
5830     bool ConstantSigned = ConstantT->isSignedIntegerType();
5831     bool CommonSigned = CommonT->isSignedIntegerType();
5832
5833     bool EqualityOnly = false;
5834
5835     if (CommonSigned) {
5836       // The common type is signed, therefore no signed to unsigned conversion.
5837       if (!OtherRange.NonNegative) {
5838         // Check that the constant is representable in type OtherT.
5839         if (ConstantSigned) {
5840           if (OtherWidth >= Value.getMinSignedBits())
5841             return;
5842         } else { // !ConstantSigned
5843           if (OtherWidth >= Value.getActiveBits() + 1)
5844             return;
5845         }
5846       } else { // !OtherSigned
5847                // Check that the constant is representable in type OtherT.
5848         // Negative values are out of range.
5849         if (ConstantSigned) {
5850           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5851             return;
5852         } else { // !ConstantSigned
5853           if (OtherWidth >= Value.getActiveBits())
5854             return;
5855         }
5856       }
5857     } else { // !CommonSigned
5858       if (OtherRange.NonNegative) {
5859         if (OtherWidth >= Value.getActiveBits())
5860           return;
5861       } else { // OtherSigned
5862         assert(!ConstantSigned &&
5863                "Two signed types converted to unsigned types.");
5864         // Check to see if the constant is representable in OtherT.
5865         if (OtherWidth > Value.getActiveBits())
5866           return;
5867         // Check to see if the constant is equivalent to a negative value
5868         // cast to CommonT.
5869         if (S.Context.getIntWidth(ConstantT) ==
5870                 S.Context.getIntWidth(CommonT) &&
5871             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5872           return;
5873         // The constant value rests between values that OtherT can represent
5874         // after conversion.  Relational comparison still works, but equality
5875         // comparisons will be tautological.
5876         EqualityOnly = true;
5877       }
5878     }
5879
5880     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5881
5882     if (op == BO_EQ || op == BO_NE) {
5883       IsTrue = op == BO_NE;
5884     } else if (EqualityOnly) {
5885       return;
5886     } else if (RhsConstant) {
5887       if (op == BO_GT || op == BO_GE)
5888         IsTrue = !PositiveConstant;
5889       else // op == BO_LT || op == BO_LE
5890         IsTrue = PositiveConstant;
5891     } else {
5892       if (op == BO_LT || op == BO_LE)
5893         IsTrue = !PositiveConstant;
5894       else // op == BO_GT || op == BO_GE
5895         IsTrue = PositiveConstant;
5896     }
5897   } else {
5898     // Other isKnownToHaveBooleanValue
5899     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5900     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5901     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5902
5903     static const struct LinkedConditions {
5904       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5905       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5906       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5907       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5908       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5909       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5910
5911     } TruthTable = {
5912         // Constant on LHS.              | Constant on RHS.              |
5913         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
5914         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5915         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5916         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5917         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5918         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5919         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5920       };
5921
5922     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5923
5924     enum ConstantValue ConstVal = Zero;
5925     if (Value.isUnsigned() || Value.isNonNegative()) {
5926       if (Value == 0) {
5927         LiteralOrBoolConstant =
5928             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5929         ConstVal = Zero;
5930       } else if (Value == 1) {
5931         LiteralOrBoolConstant =
5932             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5933         ConstVal = One;
5934       } else {
5935         LiteralOrBoolConstant = LiteralConstant;
5936         ConstVal = GT_One;
5937       }
5938     } else {
5939       ConstVal = LT_Zero;
5940     }
5941
5942     CompareBoolWithConstantResult CmpRes;
5943
5944     switch (op) {
5945     case BO_LT:
5946       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5947       break;
5948     case BO_GT:
5949       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5950       break;
5951     case BO_LE:
5952       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5953       break;
5954     case BO_GE:
5955       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5956       break;
5957     case BO_EQ:
5958       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5959       break;
5960     case BO_NE:
5961       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5962       break;
5963     default:
5964       CmpRes = Unkwn;
5965       break;
5966     }
5967
5968     if (CmpRes == AFals) {
5969       IsTrue = false;
5970     } else if (CmpRes == ATrue) {
5971       IsTrue = true;
5972     } else {
5973       return;
5974     }
5975   }
5976
5977   // If this is a comparison to an enum constant, include that
5978   // constant in the diagnostic.
5979   const EnumConstantDecl *ED = nullptr;
5980   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5981     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5982
5983   SmallString<64> PrettySourceValue;
5984   llvm::raw_svector_ostream OS(PrettySourceValue);
5985   if (ED)
5986     OS << '\'' << *ED << "' (" << Value << ")";
5987   else
5988     OS << Value;
5989
5990   S.DiagRuntimeBehavior(
5991     E->getOperatorLoc(), E,
5992     S.PDiag(diag::warn_out_of_range_compare)
5993         << OS.str() << LiteralOrBoolConstant
5994         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5995         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
5996 }
5997
5998 /// Analyze the operands of the given comparison.  Implements the
5999 /// fallback case from AnalyzeComparison.
6000 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
6001   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6002   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6003 }
6004
6005 /// \brief Implements -Wsign-compare.
6006 ///
6007 /// \param E the binary operator to check for warnings
6008 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
6009   // The type the comparison is being performed in.
6010   QualType T = E->getLHS()->getType();
6011
6012   // Only analyze comparison operators where both sides have been converted to
6013   // the same type.
6014   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6015     return AnalyzeImpConvsInComparison(S, E);
6016
6017   // Don't analyze value-dependent comparisons directly.
6018   if (E->isValueDependent())
6019     return AnalyzeImpConvsInComparison(S, E);
6020
6021   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6022   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
6023   
6024   bool IsComparisonConstant = false;
6025   
6026   // Check whether an integer constant comparison results in a value
6027   // of 'true' or 'false'.
6028   if (T->isIntegralType(S.Context)) {
6029     llvm::APSInt RHSValue;
6030     bool IsRHSIntegralLiteral = 
6031       RHS->isIntegerConstantExpr(RHSValue, S.Context);
6032     llvm::APSInt LHSValue;
6033     bool IsLHSIntegralLiteral = 
6034       LHS->isIntegerConstantExpr(LHSValue, S.Context);
6035     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6036         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6037     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6038       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6039     else
6040       IsComparisonConstant = 
6041         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6042   } else if (!T->hasUnsignedIntegerRepresentation())
6043       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
6044   
6045   // We don't do anything special if this isn't an unsigned integral
6046   // comparison:  we're only interested in integral comparisons, and
6047   // signed comparisons only happen in cases we don't care to warn about.
6048   //
6049   // We also don't care about value-dependent expressions or expressions
6050   // whose result is a constant.
6051   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
6052     return AnalyzeImpConvsInComparison(S, E);
6053   
6054   // Check to see if one of the (unmodified) operands is of different
6055   // signedness.
6056   Expr *signedOperand, *unsignedOperand;
6057   if (LHS->getType()->hasSignedIntegerRepresentation()) {
6058     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
6059            "unsigned comparison between two signed integer expressions?");
6060     signedOperand = LHS;
6061     unsignedOperand = RHS;
6062   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6063     signedOperand = RHS;
6064     unsignedOperand = LHS;
6065   } else {
6066     CheckTrivialUnsignedComparison(S, E);
6067     return AnalyzeImpConvsInComparison(S, E);
6068   }
6069
6070   // Otherwise, calculate the effective range of the signed operand.
6071   IntRange signedRange = GetExprRange(S.Context, signedOperand);
6072
6073   // Go ahead and analyze implicit conversions in the operands.  Note
6074   // that we skip the implicit conversions on both sides.
6075   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6076   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
6077
6078   // If the signed range is non-negative, -Wsign-compare won't fire,
6079   // but we should still check for comparisons which are always true
6080   // or false.
6081   if (signedRange.NonNegative)
6082     return CheckTrivialUnsignedComparison(S, E);
6083
6084   // For (in)equality comparisons, if the unsigned operand is a
6085   // constant which cannot collide with a overflowed signed operand,
6086   // then reinterpreting the signed operand as unsigned will not
6087   // change the result of the comparison.
6088   if (E->isEqualityOp()) {
6089     unsigned comparisonWidth = S.Context.getIntWidth(T);
6090     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
6091
6092     // We should never be unable to prove that the unsigned operand is
6093     // non-negative.
6094     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6095
6096     if (unsignedRange.Width < comparisonWidth)
6097       return;
6098   }
6099
6100   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6101     S.PDiag(diag::warn_mixed_sign_comparison)
6102       << LHS->getType() << RHS->getType()
6103       << LHS->getSourceRange() << RHS->getSourceRange());
6104 }
6105
6106 /// Analyzes an attempt to assign the given value to a bitfield.
6107 ///
6108 /// Returns true if there was something fishy about the attempt.
6109 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6110                                       SourceLocation InitLoc) {
6111   assert(Bitfield->isBitField());
6112   if (Bitfield->isInvalidDecl())
6113     return false;
6114
6115   // White-list bool bitfields.
6116   if (Bitfield->getType()->isBooleanType())
6117     return false;
6118
6119   // Ignore value- or type-dependent expressions.
6120   if (Bitfield->getBitWidth()->isValueDependent() ||
6121       Bitfield->getBitWidth()->isTypeDependent() ||
6122       Init->isValueDependent() ||
6123       Init->isTypeDependent())
6124     return false;
6125
6126   Expr *OriginalInit = Init->IgnoreParenImpCasts();
6127
6128   llvm::APSInt Value;
6129   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
6130     return false;
6131
6132   unsigned OriginalWidth = Value.getBitWidth();
6133   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
6134
6135   if (OriginalWidth <= FieldWidth)
6136     return false;
6137
6138   // Compute the value which the bitfield will contain.
6139   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6140   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
6141
6142   // Check whether the stored value is equal to the original value.
6143   TruncatedValue = TruncatedValue.extend(OriginalWidth);
6144   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6145     return false;
6146
6147   // Special-case bitfields of width 1: booleans are naturally 0/1, and
6148   // therefore don't strictly fit into a signed bitfield of width 1.
6149   if (FieldWidth == 1 && Value == 1)
6150     return false;
6151
6152   std::string PrettyValue = Value.toString(10);
6153   std::string PrettyTrunc = TruncatedValue.toString(10);
6154
6155   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6156     << PrettyValue << PrettyTrunc << OriginalInit->getType()
6157     << Init->getSourceRange();
6158
6159   return true;
6160 }
6161
6162 /// Analyze the given simple or compound assignment for warning-worthy
6163 /// operations.
6164 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
6165   // Just recurse on the LHS.
6166   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6167
6168   // We want to recurse on the RHS as normal unless we're assigning to
6169   // a bitfield.
6170   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
6171     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
6172                                   E->getOperatorLoc())) {
6173       // Recurse, ignoring any implicit conversions on the RHS.
6174       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6175                                         E->getOperatorLoc());
6176     }
6177   }
6178
6179   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6180 }
6181
6182 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
6183 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 
6184                             SourceLocation CContext, unsigned diag,
6185                             bool pruneControlFlow = false) {
6186   if (pruneControlFlow) {
6187     S.DiagRuntimeBehavior(E->getExprLoc(), E,
6188                           S.PDiag(diag)
6189                             << SourceType << T << E->getSourceRange()
6190                             << SourceRange(CContext));
6191     return;
6192   }
6193   S.Diag(E->getExprLoc(), diag)
6194     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6195 }
6196
6197 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
6198 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
6199                             SourceLocation CContext, unsigned diag,
6200                             bool pruneControlFlow = false) {
6201   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
6202 }
6203
6204 /// Diagnose an implicit cast from a literal expression. Does not warn when the
6205 /// cast wouldn't lose information.
6206 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6207                                     SourceLocation CContext) {
6208   // Try to convert the literal exactly to an integer. If we can, don't warn.
6209   bool isExact = false;
6210   const llvm::APFloat &Value = FL->getValue();
6211   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6212                             T->hasUnsignedIntegerRepresentation());
6213   if (Value.convertToInteger(IntegerValue,
6214                              llvm::APFloat::rmTowardZero, &isExact)
6215       == llvm::APFloat::opOK && isExact)
6216     return;
6217
6218   // FIXME: Force the precision of the source value down so we don't print
6219   // digits which are usually useless (we don't really care here if we
6220   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
6221   // would automatically print the shortest representation, but it's a bit
6222   // tricky to implement.
6223   SmallString<16> PrettySourceValue;
6224   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6225   precision = (precision * 59 + 195) / 196;
6226   Value.toString(PrettySourceValue, precision);
6227
6228   SmallString<16> PrettyTargetValue;
6229   if (T->isSpecificBuiltinType(BuiltinType::Bool))
6230     PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6231   else
6232     IntegerValue.toString(PrettyTargetValue);
6233
6234   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6235     << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6236     << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
6237 }
6238
6239 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6240   if (!Range.Width) return "0";
6241
6242   llvm::APSInt ValueInRange = Value;
6243   ValueInRange.setIsSigned(!Range.NonNegative);
6244   ValueInRange = ValueInRange.trunc(Range.Width);
6245   return ValueInRange.toString(10);
6246 }
6247
6248 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6249   if (!isa<ImplicitCastExpr>(Ex))
6250     return false;
6251
6252   Expr *InnerE = Ex->IgnoreParenImpCasts();
6253   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6254   const Type *Source =
6255     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6256   if (Target->isDependentType())
6257     return false;
6258
6259   const BuiltinType *FloatCandidateBT =
6260     dyn_cast<BuiltinType>(ToBool ? Source : Target);
6261   const Type *BoolCandidateType = ToBool ? Target : Source;
6262
6263   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6264           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6265 }
6266
6267 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6268                                       SourceLocation CC) {
6269   unsigned NumArgs = TheCall->getNumArgs();
6270   for (unsigned i = 0; i < NumArgs; ++i) {
6271     Expr *CurrA = TheCall->getArg(i);
6272     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6273       continue;
6274
6275     bool IsSwapped = ((i > 0) &&
6276         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6277     IsSwapped |= ((i < (NumArgs - 1)) &&
6278         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6279     if (IsSwapped) {
6280       // Warn on this floating-point to bool conversion.
6281       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6282                       CurrA->getType(), CC,
6283                       diag::warn_impcast_floating_point_to_bool);
6284     }
6285   }
6286 }
6287
6288 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6289                                    SourceLocation CC) {
6290   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6291                         E->getExprLoc()))
6292     return;
6293
6294   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6295   const Expr::NullPointerConstantKind NullKind =
6296       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6297   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6298     return;
6299
6300   // Return if target type is a safe conversion.
6301   if (T->isAnyPointerType() || T->isBlockPointerType() ||
6302       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6303     return;
6304
6305   SourceLocation Loc = E->getSourceRange().getBegin();
6306
6307   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
6308   if (NullKind == Expr::NPCK_GNUNull) {
6309     if (Loc.isMacroID())
6310       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6311   }
6312
6313   // Only warn if the null and context location are in the same macro expansion.
6314   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6315     return;
6316
6317   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6318       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6319       << FixItHint::CreateReplacement(Loc,
6320                                       S.getFixItZeroLiteralForType(T, Loc));
6321 }
6322
6323 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
6324                              SourceLocation CC, bool *ICContext = nullptr) {
6325   if (E->isTypeDependent() || E->isValueDependent()) return;
6326
6327   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6328   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6329   if (Source == Target) return;
6330   if (Target->isDependentType()) return;
6331
6332   // If the conversion context location is invalid don't complain. We also
6333   // don't want to emit a warning if the issue occurs from the expansion of
6334   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6335   // delay this check as long as possible. Once we detect we are in that
6336   // scenario, we just return.
6337   if (CC.isInvalid())
6338     return;
6339
6340   // Diagnose implicit casts to bool.
6341   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6342     if (isa<StringLiteral>(E))
6343       // Warn on string literal to bool.  Checks for string literals in logical
6344       // and expressions, for instance, assert(0 && "error here"), are
6345       // prevented by a check in AnalyzeImplicitConversions().
6346       return DiagnoseImpCast(S, E, T, CC,
6347                              diag::warn_impcast_string_literal_to_bool);
6348     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6349         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6350       // This covers the literal expressions that evaluate to Objective-C
6351       // objects.
6352       return DiagnoseImpCast(S, E, T, CC,
6353                              diag::warn_impcast_objective_c_literal_to_bool);
6354     }
6355     if (Source->isPointerType() || Source->canDecayToPointerType()) {
6356       // Warn on pointer to bool conversion that is always true.
6357       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6358                                      SourceRange(CC));
6359     }
6360   }
6361
6362   // Strip vector types.
6363   if (isa<VectorType>(Source)) {
6364     if (!isa<VectorType>(Target)) {
6365       if (S.SourceMgr.isInSystemMacro(CC))
6366         return;
6367       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
6368     }
6369     
6370     // If the vector cast is cast between two vectors of the same size, it is
6371     // a bitcast, not a conversion.
6372     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6373       return;
6374
6375     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6376     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6377   }
6378   if (auto VecTy = dyn_cast<VectorType>(Target))
6379     Target = VecTy->getElementType().getTypePtr();
6380
6381   // Strip complex types.
6382   if (isa<ComplexType>(Source)) {
6383     if (!isa<ComplexType>(Target)) {
6384       if (S.SourceMgr.isInSystemMacro(CC))
6385         return;
6386
6387       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
6388     }
6389
6390     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6391     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6392   }
6393
6394   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6395   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6396
6397   // If the source is floating point...
6398   if (SourceBT && SourceBT->isFloatingPoint()) {
6399     // ...and the target is floating point...
6400     if (TargetBT && TargetBT->isFloatingPoint()) {
6401       // ...then warn if we're dropping FP rank.
6402
6403       // Builtin FP kinds are ordered by increasing FP rank.
6404       if (SourceBT->getKind() > TargetBT->getKind()) {
6405         // Don't warn about float constants that are precisely
6406         // representable in the target type.
6407         Expr::EvalResult result;
6408         if (E->EvaluateAsRValue(result, S.Context)) {
6409           // Value might be a float, a float vector, or a float complex.
6410           if (IsSameFloatAfterCast(result.Val,
6411                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6412                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
6413             return;
6414         }
6415
6416         if (S.SourceMgr.isInSystemMacro(CC))
6417           return;
6418
6419         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
6420       }
6421       return;
6422     }
6423
6424     // If the target is integral, always warn.    
6425     if (TargetBT && TargetBT->isInteger()) {
6426       if (S.SourceMgr.isInSystemMacro(CC))
6427         return;
6428       
6429       Expr *InnerE = E->IgnoreParenImpCasts();
6430       // We also want to warn on, e.g., "int i = -1.234"
6431       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6432         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6433           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6434
6435       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6436         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
6437       } else {
6438         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6439       }
6440     }
6441
6442     // If the target is bool, warn if expr is a function or method call.
6443     if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6444         isa<CallExpr>(E)) {
6445       // Check last argument of function call to see if it is an
6446       // implicit cast from a type matching the type the result
6447       // is being cast to.
6448       CallExpr *CEx = cast<CallExpr>(E);
6449       unsigned NumArgs = CEx->getNumArgs();
6450       if (NumArgs > 0) {
6451         Expr *LastA = CEx->getArg(NumArgs - 1);
6452         Expr *InnerE = LastA->IgnoreParenImpCasts();
6453         const Type *InnerType =
6454           S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6455         if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6456           // Warn on this floating-point to bool conversion
6457           DiagnoseImpCast(S, E, T, CC,
6458                           diag::warn_impcast_floating_point_to_bool);
6459         }
6460       }
6461     }
6462     return;
6463   }
6464
6465   DiagnoseNullConversion(S, E, T, CC);
6466
6467   if (!Source->isIntegerType() || !Target->isIntegerType())
6468     return;
6469
6470   // TODO: remove this early return once the false positives for constant->bool
6471   // in templates, macros, etc, are reduced or removed.
6472   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6473     return;
6474
6475   IntRange SourceRange = GetExprRange(S.Context, E);
6476   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
6477
6478   if (SourceRange.Width > TargetRange.Width) {
6479     // If the source is a constant, use a default-on diagnostic.
6480     // TODO: this should happen for bitfield stores, too.
6481     llvm::APSInt Value(32);
6482     if (E->isIntegerConstantExpr(Value, S.Context)) {
6483       if (S.SourceMgr.isInSystemMacro(CC))
6484         return;
6485
6486       std::string PrettySourceValue = Value.toString(10);
6487       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
6488
6489       S.DiagRuntimeBehavior(E->getExprLoc(), E,
6490         S.PDiag(diag::warn_impcast_integer_precision_constant)
6491             << PrettySourceValue << PrettyTargetValue
6492             << E->getType() << T << E->getSourceRange()
6493             << clang::SourceRange(CC));
6494       return;
6495     }
6496
6497     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6498     if (S.SourceMgr.isInSystemMacro(CC))
6499       return;
6500
6501     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
6502       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6503                              /* pruneControlFlow */ true);
6504     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
6505   }
6506
6507   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6508       (!TargetRange.NonNegative && SourceRange.NonNegative &&
6509        SourceRange.Width == TargetRange.Width)) {
6510         
6511     if (S.SourceMgr.isInSystemMacro(CC))
6512       return;
6513
6514     unsigned DiagID = diag::warn_impcast_integer_sign;
6515
6516     // Traditionally, gcc has warned about this under -Wsign-compare.
6517     // We also want to warn about it in -Wconversion.
6518     // So if -Wconversion is off, use a completely identical diagnostic
6519     // in the sign-compare group.
6520     // The conditional-checking code will 
6521     if (ICContext) {
6522       DiagID = diag::warn_impcast_integer_sign_conditional;
6523       *ICContext = true;
6524     }
6525
6526     return DiagnoseImpCast(S, E, T, CC, DiagID);
6527   }
6528
6529   // Diagnose conversions between different enumeration types.
6530   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6531   // type, to give us better diagnostics.
6532   QualType SourceType = E->getType();
6533   if (!S.getLangOpts().CPlusPlus) {
6534     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6535       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6536         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6537         SourceType = S.Context.getTypeDeclType(Enum);
6538         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6539       }
6540   }
6541   
6542   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6543     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
6544       if (SourceEnum->getDecl()->hasNameForLinkage() &&
6545           TargetEnum->getDecl()->hasNameForLinkage() &&
6546           SourceEnum != TargetEnum) {
6547         if (S.SourceMgr.isInSystemMacro(CC))
6548           return;
6549
6550         return DiagnoseImpCast(S, E, SourceType, T, CC, 
6551                                diag::warn_impcast_different_enum_types);
6552       }
6553   
6554   return;
6555 }
6556
6557 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6558                               SourceLocation CC, QualType T);
6559
6560 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
6561                              SourceLocation CC, bool &ICContext) {
6562   E = E->IgnoreParenImpCasts();
6563
6564   if (isa<ConditionalOperator>(E))
6565     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
6566
6567   AnalyzeImplicitConversions(S, E, CC);
6568   if (E->getType() != T)
6569     return CheckImplicitConversion(S, E, T, CC, &ICContext);
6570   return;
6571 }
6572
6573 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6574                               SourceLocation CC, QualType T) {
6575   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
6576
6577   bool Suspicious = false;
6578   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6579   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
6580
6581   // If -Wconversion would have warned about either of the candidates
6582   // for a signedness conversion to the context type...
6583   if (!Suspicious) return;
6584
6585   // ...but it's currently ignored...
6586   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
6587     return;
6588
6589   // ...then check whether it would have warned about either of the
6590   // candidates for a signedness conversion to the condition type.
6591   if (E->getType() == T) return;
6592  
6593   Suspicious = false;
6594   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6595                           E->getType(), CC, &Suspicious);
6596   if (!Suspicious)
6597     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
6598                             E->getType(), CC, &Suspicious);
6599 }
6600
6601 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6602 /// Input argument E is a logical expression.
6603 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6604   if (S.getLangOpts().Bool)
6605     return;
6606   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6607 }
6608
6609 /// AnalyzeImplicitConversions - Find and report any interesting
6610 /// implicit conversions in the given expression.  There are a couple
6611 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
6612 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
6613   QualType T = OrigE->getType();
6614   Expr *E = OrigE->IgnoreParenImpCasts();
6615
6616   if (E->isTypeDependent() || E->isValueDependent())
6617     return;
6618   
6619   // For conditional operators, we analyze the arguments as if they
6620   // were being fed directly into the output.
6621   if (isa<ConditionalOperator>(E)) {
6622     ConditionalOperator *CO = cast<ConditionalOperator>(E);
6623     CheckConditionalOperator(S, CO, CC, T);
6624     return;
6625   }
6626
6627   // Check implicit argument conversions for function calls.
6628   if (CallExpr *Call = dyn_cast<CallExpr>(E))
6629     CheckImplicitArgumentConversions(S, Call, CC);
6630
6631   // Go ahead and check any implicit conversions we might have skipped.
6632   // The non-canonical typecheck is just an optimization;
6633   // CheckImplicitConversion will filter out dead implicit conversions.
6634   if (E->getType() != T)
6635     CheckImplicitConversion(S, E, T, CC);
6636
6637   // Now continue drilling into this expression.
6638   
6639   if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
6640     if (POE->getResultExpr())
6641       E = POE->getResultExpr();
6642   }
6643   
6644   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6645     return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6646   
6647   // Skip past explicit casts.
6648   if (isa<ExplicitCastExpr>(E)) {
6649     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
6650     return AnalyzeImplicitConversions(S, E, CC);
6651   }
6652
6653   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6654     // Do a somewhat different check with comparison operators.
6655     if (BO->isComparisonOp())
6656       return AnalyzeComparison(S, BO);
6657
6658     // And with simple assignments.
6659     if (BO->getOpcode() == BO_Assign)
6660       return AnalyzeAssignment(S, BO);
6661   }
6662
6663   // These break the otherwise-useful invariant below.  Fortunately,
6664   // we don't really need to recurse into them, because any internal
6665   // expressions should have been analyzed already when they were
6666   // built into statements.
6667   if (isa<StmtExpr>(E)) return;
6668
6669   // Don't descend into unevaluated contexts.
6670   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6671
6672   // Now just recurse over the expression's children.
6673   CC = E->getExprLoc();
6674   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6675   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6676   for (Stmt::child_range I = E->children(); I; ++I) {
6677     Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6678     if (!ChildExpr)
6679       continue;
6680
6681     if (IsLogicalAndOperator &&
6682         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6683       // Ignore checking string literals that are in logical and operators.
6684       // This is a common pattern for asserts.
6685       continue;
6686     AnalyzeImplicitConversions(S, ChildExpr, CC);
6687   }
6688
6689   if (BO && BO->isLogicalOp()) {
6690     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6691     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6692       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
6693
6694     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6695     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6696       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
6697   }
6698
6699   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6700     if (U->getOpcode() == UO_LNot)
6701       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
6702 }
6703
6704 } // end anonymous namespace
6705
6706 enum {
6707   AddressOf,
6708   FunctionPointer,
6709   ArrayPointer
6710 };
6711
6712 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6713 // Returns true when emitting a warning about taking the address of a reference.
6714 static bool CheckForReference(Sema &SemaRef, const Expr *E,
6715                               PartialDiagnostic PD) {
6716   E = E->IgnoreParenImpCasts();
6717
6718   const FunctionDecl *FD = nullptr;
6719
6720   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6721     if (!DRE->getDecl()->getType()->isReferenceType())
6722       return false;
6723   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6724     if (!M->getMemberDecl()->getType()->isReferenceType())
6725       return false;
6726   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6727     if (!Call->getCallReturnType()->isReferenceType())
6728       return false;
6729     FD = Call->getDirectCallee();
6730   } else {
6731     return false;
6732   }
6733
6734   SemaRef.Diag(E->getExprLoc(), PD);
6735
6736   // If possible, point to location of function.
6737   if (FD) {
6738     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6739   }
6740
6741   return true;
6742 }
6743
6744 // Returns true if the SourceLocation is expanded from any macro body.
6745 // Returns false if the SourceLocation is invalid, is from not in a macro
6746 // expansion, or is from expanded from a top-level macro argument.
6747 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6748   if (Loc.isInvalid())
6749     return false;
6750
6751   while (Loc.isMacroID()) {
6752     if (SM.isMacroBodyExpansion(Loc))
6753       return true;
6754     Loc = SM.getImmediateMacroCallerLoc(Loc);
6755   }
6756
6757   return false;
6758 }
6759
6760 /// \brief Diagnose pointers that are always non-null.
6761 /// \param E the expression containing the pointer
6762 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6763 /// compared to a null pointer
6764 /// \param IsEqual True when the comparison is equal to a null pointer
6765 /// \param Range Extra SourceRange to highlight in the diagnostic
6766 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6767                                         Expr::NullPointerConstantKind NullKind,
6768                                         bool IsEqual, SourceRange Range) {
6769   if (!E)
6770     return;
6771
6772   // Don't warn inside macros.
6773   if (E->getExprLoc().isMacroID()) {
6774     const SourceManager &SM = getSourceManager();
6775     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6776         IsInAnyMacroBody(SM, Range.getBegin()))
6777       return;
6778   }
6779   E = E->IgnoreImpCasts();
6780
6781   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6782
6783   if (isa<CXXThisExpr>(E)) {
6784     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6785                                 : diag::warn_this_bool_conversion;
6786     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6787     return;
6788   }
6789
6790   bool IsAddressOf = false;
6791
6792   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6793     if (UO->getOpcode() != UO_AddrOf)
6794       return;
6795     IsAddressOf = true;
6796     E = UO->getSubExpr();
6797   }
6798
6799   if (IsAddressOf) {
6800     unsigned DiagID = IsCompare
6801                           ? diag::warn_address_of_reference_null_compare
6802                           : diag::warn_address_of_reference_bool_conversion;
6803     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6804                                          << IsEqual;
6805     if (CheckForReference(*this, E, PD)) {
6806       return;
6807     }
6808   }
6809
6810   // Expect to find a single Decl.  Skip anything more complicated.
6811   ValueDecl *D = nullptr;
6812   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6813     D = R->getDecl();
6814   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6815     D = M->getMemberDecl();
6816   }
6817
6818   // Weak Decls can be null.
6819   if (!D || D->isWeak())
6820     return;
6821   
6822   // Check for parameter decl with nonnull attribute
6823   if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6824     if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6825       if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6826         unsigned NumArgs = FD->getNumParams();
6827         llvm::SmallBitVector AttrNonNull(NumArgs);
6828         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6829           if (!NonNull->args_size()) {
6830             AttrNonNull.set(0, NumArgs);
6831             break;
6832           }
6833           for (unsigned Val : NonNull->args()) {
6834             if (Val >= NumArgs)
6835               continue;
6836             AttrNonNull.set(Val);
6837           }
6838         }
6839         if (!AttrNonNull.empty())
6840           for (unsigned i = 0; i < NumArgs; ++i)
6841             if (FD->getParamDecl(i) == PV &&
6842                 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
6843               std::string Str;
6844               llvm::raw_string_ostream S(Str);
6845               E->printPretty(S, nullptr, getPrintingPolicy());
6846               unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6847                                           : diag::warn_cast_nonnull_to_bool;
6848               Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6849                 << Range << IsEqual;
6850               return;
6851             }
6852       }
6853     }
6854   
6855   QualType T = D->getType();
6856   const bool IsArray = T->isArrayType();
6857   const bool IsFunction = T->isFunctionType();
6858
6859   // Address of function is used to silence the function warning.
6860   if (IsAddressOf && IsFunction) {
6861     return;
6862   }
6863
6864   // Found nothing.
6865   if (!IsAddressOf && !IsFunction && !IsArray)
6866     return;
6867
6868   // Pretty print the expression for the diagnostic.
6869   std::string Str;
6870   llvm::raw_string_ostream S(Str);
6871   E->printPretty(S, nullptr, getPrintingPolicy());
6872
6873   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6874                               : diag::warn_impcast_pointer_to_bool;
6875   unsigned DiagType;
6876   if (IsAddressOf)
6877     DiagType = AddressOf;
6878   else if (IsFunction)
6879     DiagType = FunctionPointer;
6880   else if (IsArray)
6881     DiagType = ArrayPointer;
6882   else
6883     llvm_unreachable("Could not determine diagnostic.");
6884   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6885                                 << Range << IsEqual;
6886
6887   if (!IsFunction)
6888     return;
6889
6890   // Suggest '&' to silence the function warning.
6891   Diag(E->getExprLoc(), diag::note_function_warning_silence)
6892       << FixItHint::CreateInsertion(E->getLocStart(), "&");
6893
6894   // Check to see if '()' fixit should be emitted.
6895   QualType ReturnType;
6896   UnresolvedSet<4> NonTemplateOverloads;
6897   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6898   if (ReturnType.isNull())
6899     return;
6900
6901   if (IsCompare) {
6902     // There are two cases here.  If there is null constant, the only suggest
6903     // for a pointer return type.  If the null is 0, then suggest if the return
6904     // type is a pointer or an integer type.
6905     if (!ReturnType->isPointerType()) {
6906       if (NullKind == Expr::NPCK_ZeroExpression ||
6907           NullKind == Expr::NPCK_ZeroLiteral) {
6908         if (!ReturnType->isIntegerType())
6909           return;
6910       } else {
6911         return;
6912       }
6913     }
6914   } else { // !IsCompare
6915     // For function to bool, only suggest if the function pointer has bool
6916     // return type.
6917     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6918       return;
6919   }
6920   Diag(E->getExprLoc(), diag::note_function_to_function_call)
6921       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
6922 }
6923
6924
6925 /// Diagnoses "dangerous" implicit conversions within the given
6926 /// expression (which is a full expression).  Implements -Wconversion
6927 /// and -Wsign-compare.
6928 ///
6929 /// \param CC the "context" location of the implicit conversion, i.e.
6930 ///   the most location of the syntactic entity requiring the implicit
6931 ///   conversion
6932 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
6933   // Don't diagnose in unevaluated contexts.
6934   if (isUnevaluatedContext())
6935     return;
6936
6937   // Don't diagnose for value- or type-dependent expressions.
6938   if (E->isTypeDependent() || E->isValueDependent())
6939     return;
6940
6941   // Check for array bounds violations in cases where the check isn't triggered
6942   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6943   // ArraySubscriptExpr is on the RHS of a variable initialization.
6944   CheckArrayAccess(E);
6945
6946   // This is not the right CC for (e.g.) a variable initialization.
6947   AnalyzeImplicitConversions(*this, E, CC);
6948 }
6949
6950 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6951 /// Input argument E is a logical expression.
6952 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
6953   ::CheckBoolLikeConversion(*this, E, CC);
6954 }
6955
6956 /// Diagnose when expression is an integer constant expression and its evaluation
6957 /// results in integer overflow
6958 void Sema::CheckForIntOverflow (Expr *E) {
6959   if (isa<BinaryOperator>(E->IgnoreParenCasts()))
6960     E->IgnoreParenCasts()->EvaluateForOverflow(Context);
6961 }
6962
6963 namespace {
6964 /// \brief Visitor for expressions which looks for unsequenced operations on the
6965 /// same object.
6966 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
6967   typedef EvaluatedExprVisitor<SequenceChecker> Base;
6968
6969   /// \brief A tree of sequenced regions within an expression. Two regions are
6970   /// unsequenced if one is an ancestor or a descendent of the other. When we
6971   /// finish processing an expression with sequencing, such as a comma
6972   /// expression, we fold its tree nodes into its parent, since they are
6973   /// unsequenced with respect to nodes we will visit later.
6974   class SequenceTree {
6975     struct Value {
6976       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6977       unsigned Parent : 31;
6978       bool Merged : 1;
6979     };
6980     SmallVector<Value, 8> Values;
6981
6982   public:
6983     /// \brief A region within an expression which may be sequenced with respect
6984     /// to some other region.
6985     class Seq {
6986       explicit Seq(unsigned N) : Index(N) {}
6987       unsigned Index;
6988       friend class SequenceTree;
6989     public:
6990       Seq() : Index(0) {}
6991     };
6992
6993     SequenceTree() { Values.push_back(Value(0)); }
6994     Seq root() const { return Seq(0); }
6995
6996     /// \brief Create a new sequence of operations, which is an unsequenced
6997     /// subset of \p Parent. This sequence of operations is sequenced with
6998     /// respect to other children of \p Parent.
6999     Seq allocate(Seq Parent) {
7000       Values.push_back(Value(Parent.Index));
7001       return Seq(Values.size() - 1);
7002     }
7003
7004     /// \brief Merge a sequence of operations into its parent.
7005     void merge(Seq S) {
7006       Values[S.Index].Merged = true;
7007     }
7008
7009     /// \brief Determine whether two operations are unsequenced. This operation
7010     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7011     /// should have been merged into its parent as appropriate.
7012     bool isUnsequenced(Seq Cur, Seq Old) {
7013       unsigned C = representative(Cur.Index);
7014       unsigned Target = representative(Old.Index);
7015       while (C >= Target) {
7016         if (C == Target)
7017           return true;
7018         C = Values[C].Parent;
7019       }
7020       return false;
7021     }
7022
7023   private:
7024     /// \brief Pick a representative for a sequence.
7025     unsigned representative(unsigned K) {
7026       if (Values[K].Merged)
7027         // Perform path compression as we go.
7028         return Values[K].Parent = representative(Values[K].Parent);
7029       return K;
7030     }
7031   };
7032
7033   /// An object for which we can track unsequenced uses.
7034   typedef NamedDecl *Object;
7035
7036   /// Different flavors of object usage which we track. We only track the
7037   /// least-sequenced usage of each kind.
7038   enum UsageKind {
7039     /// A read of an object. Multiple unsequenced reads are OK.
7040     UK_Use,
7041     /// A modification of an object which is sequenced before the value
7042     /// computation of the expression, such as ++n in C++.
7043     UK_ModAsValue,
7044     /// A modification of an object which is not sequenced before the value
7045     /// computation of the expression, such as n++.
7046     UK_ModAsSideEffect,
7047
7048     UK_Count = UK_ModAsSideEffect + 1
7049   };
7050
7051   struct Usage {
7052     Usage() : Use(nullptr), Seq() {}
7053     Expr *Use;
7054     SequenceTree::Seq Seq;
7055   };
7056
7057   struct UsageInfo {
7058     UsageInfo() : Diagnosed(false) {}
7059     Usage Uses[UK_Count];
7060     /// Have we issued a diagnostic for this variable already?
7061     bool Diagnosed;
7062   };
7063   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7064
7065   Sema &SemaRef;
7066   /// Sequenced regions within the expression.
7067   SequenceTree Tree;
7068   /// Declaration modifications and references which we have seen.
7069   UsageInfoMap UsageMap;
7070   /// The region we are currently within.
7071   SequenceTree::Seq Region;
7072   /// Filled in with declarations which were modified as a side-effect
7073   /// (that is, post-increment operations).
7074   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7075   /// Expressions to check later. We defer checking these to reduce
7076   /// stack usage.
7077   SmallVectorImpl<Expr *> &WorkList;
7078
7079   /// RAII object wrapping the visitation of a sequenced subexpression of an
7080   /// expression. At the end of this process, the side-effects of the evaluation
7081   /// become sequenced with respect to the value computation of the result, so
7082   /// we downgrade any UK_ModAsSideEffect within the evaluation to
7083   /// UK_ModAsValue.
7084   struct SequencedSubexpression {
7085     SequencedSubexpression(SequenceChecker &Self)
7086       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7087       Self.ModAsSideEffect = &ModAsSideEffect;
7088     }
7089     ~SequencedSubexpression() {
7090       for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7091            MI != ME; ++MI) {
7092         UsageInfo &U = Self.UsageMap[MI->first];
7093         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7094         Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7095         SideEffectUsage = MI->second;
7096       }
7097       Self.ModAsSideEffect = OldModAsSideEffect;
7098     }
7099
7100     SequenceChecker &Self;
7101     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7102     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
7103   };
7104
7105   /// RAII object wrapping the visitation of a subexpression which we might
7106   /// choose to evaluate as a constant. If any subexpression is evaluated and
7107   /// found to be non-constant, this allows us to suppress the evaluation of
7108   /// the outer expression.
7109   class EvaluationTracker {
7110   public:
7111     EvaluationTracker(SequenceChecker &Self)
7112         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7113       Self.EvalTracker = this;
7114     }
7115     ~EvaluationTracker() {
7116       Self.EvalTracker = Prev;
7117       if (Prev)
7118         Prev->EvalOK &= EvalOK;
7119     }
7120
7121     bool evaluate(const Expr *E, bool &Result) {
7122       if (!EvalOK || E->isValueDependent())
7123         return false;
7124       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7125       return EvalOK;
7126     }
7127
7128   private:
7129     SequenceChecker &Self;
7130     EvaluationTracker *Prev;
7131     bool EvalOK;
7132   } *EvalTracker;
7133
7134   /// \brief Find the object which is produced by the specified expression,
7135   /// if any.
7136   Object getObject(Expr *E, bool Mod) const {
7137     E = E->IgnoreParenCasts();
7138     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7139       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7140         return getObject(UO->getSubExpr(), Mod);
7141     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7142       if (BO->getOpcode() == BO_Comma)
7143         return getObject(BO->getRHS(), Mod);
7144       if (Mod && BO->isAssignmentOp())
7145         return getObject(BO->getLHS(), Mod);
7146     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7147       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7148       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7149         return ME->getMemberDecl();
7150     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7151       // FIXME: If this is a reference, map through to its value.
7152       return DRE->getDecl();
7153     return nullptr;
7154   }
7155
7156   /// \brief Note that an object was modified or used by an expression.
7157   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7158     Usage &U = UI.Uses[UK];
7159     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7160       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7161         ModAsSideEffect->push_back(std::make_pair(O, U));
7162       U.Use = Ref;
7163       U.Seq = Region;
7164     }
7165   }
7166   /// \brief Check whether a modification or use conflicts with a prior usage.
7167   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7168                   bool IsModMod) {
7169     if (UI.Diagnosed)
7170       return;
7171
7172     const Usage &U = UI.Uses[OtherKind];
7173     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7174       return;
7175
7176     Expr *Mod = U.Use;
7177     Expr *ModOrUse = Ref;
7178     if (OtherKind == UK_Use)
7179       std::swap(Mod, ModOrUse);
7180
7181     SemaRef.Diag(Mod->getExprLoc(),
7182                  IsModMod ? diag::warn_unsequenced_mod_mod
7183                           : diag::warn_unsequenced_mod_use)
7184       << O << SourceRange(ModOrUse->getExprLoc());
7185     UI.Diagnosed = true;
7186   }
7187
7188   void notePreUse(Object O, Expr *Use) {
7189     UsageInfo &U = UsageMap[O];
7190     // Uses conflict with other modifications.
7191     checkUsage(O, U, Use, UK_ModAsValue, false);
7192   }
7193   void notePostUse(Object O, Expr *Use) {
7194     UsageInfo &U = UsageMap[O];
7195     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7196     addUsage(U, O, Use, UK_Use);
7197   }
7198
7199   void notePreMod(Object O, Expr *Mod) {
7200     UsageInfo &U = UsageMap[O];
7201     // Modifications conflict with other modifications and with uses.
7202     checkUsage(O, U, Mod, UK_ModAsValue, true);
7203     checkUsage(O, U, Mod, UK_Use, false);
7204   }
7205   void notePostMod(Object O, Expr *Use, UsageKind UK) {
7206     UsageInfo &U = UsageMap[O];
7207     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7208     addUsage(U, O, Use, UK);
7209   }
7210
7211 public:
7212   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
7213       : Base(S.Context), SemaRef(S), Region(Tree.root()),
7214         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
7215     Visit(E);
7216   }
7217
7218   void VisitStmt(Stmt *S) {
7219     // Skip all statements which aren't expressions for now.
7220   }
7221
7222   void VisitExpr(Expr *E) {
7223     // By default, just recurse to evaluated subexpressions.
7224     Base::VisitStmt(E);
7225   }
7226
7227   void VisitCastExpr(CastExpr *E) {
7228     Object O = Object();
7229     if (E->getCastKind() == CK_LValueToRValue)
7230       O = getObject(E->getSubExpr(), false);
7231
7232     if (O)
7233       notePreUse(O, E);
7234     VisitExpr(E);
7235     if (O)
7236       notePostUse(O, E);
7237   }
7238
7239   void VisitBinComma(BinaryOperator *BO) {
7240     // C++11 [expr.comma]p1:
7241     //   Every value computation and side effect associated with the left
7242     //   expression is sequenced before every value computation and side
7243     //   effect associated with the right expression.
7244     SequenceTree::Seq LHS = Tree.allocate(Region);
7245     SequenceTree::Seq RHS = Tree.allocate(Region);
7246     SequenceTree::Seq OldRegion = Region;
7247
7248     {
7249       SequencedSubexpression SeqLHS(*this);
7250       Region = LHS;
7251       Visit(BO->getLHS());
7252     }
7253
7254     Region = RHS;
7255     Visit(BO->getRHS());
7256
7257     Region = OldRegion;
7258
7259     // Forget that LHS and RHS are sequenced. They are both unsequenced
7260     // with respect to other stuff.
7261     Tree.merge(LHS);
7262     Tree.merge(RHS);
7263   }
7264
7265   void VisitBinAssign(BinaryOperator *BO) {
7266     // The modification is sequenced after the value computation of the LHS
7267     // and RHS, so check it before inspecting the operands and update the
7268     // map afterwards.
7269     Object O = getObject(BO->getLHS(), true);
7270     if (!O)
7271       return VisitExpr(BO);
7272
7273     notePreMod(O, BO);
7274
7275     // C++11 [expr.ass]p7:
7276     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7277     //   only once.
7278     //
7279     // Therefore, for a compound assignment operator, O is considered used
7280     // everywhere except within the evaluation of E1 itself.
7281     if (isa<CompoundAssignOperator>(BO))
7282       notePreUse(O, BO);
7283
7284     Visit(BO->getLHS());
7285
7286     if (isa<CompoundAssignOperator>(BO))
7287       notePostUse(O, BO);
7288
7289     Visit(BO->getRHS());
7290
7291     // C++11 [expr.ass]p1:
7292     //   the assignment is sequenced [...] before the value computation of the
7293     //   assignment expression.
7294     // C11 6.5.16/3 has no such rule.
7295     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7296                                                        : UK_ModAsSideEffect);
7297   }
7298   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7299     VisitBinAssign(CAO);
7300   }
7301
7302   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7303   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7304   void VisitUnaryPreIncDec(UnaryOperator *UO) {
7305     Object O = getObject(UO->getSubExpr(), true);
7306     if (!O)
7307       return VisitExpr(UO);
7308
7309     notePreMod(O, UO);
7310     Visit(UO->getSubExpr());
7311     // C++11 [expr.pre.incr]p1:
7312     //   the expression ++x is equivalent to x+=1
7313     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7314                                                        : UK_ModAsSideEffect);
7315   }
7316
7317   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7318   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7319   void VisitUnaryPostIncDec(UnaryOperator *UO) {
7320     Object O = getObject(UO->getSubExpr(), true);
7321     if (!O)
7322       return VisitExpr(UO);
7323
7324     notePreMod(O, UO);
7325     Visit(UO->getSubExpr());
7326     notePostMod(O, UO, UK_ModAsSideEffect);
7327   }
7328
7329   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7330   void VisitBinLOr(BinaryOperator *BO) {
7331     // The side-effects of the LHS of an '&&' are sequenced before the
7332     // value computation of the RHS, and hence before the value computation
7333     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7334     // as if they were unconditionally sequenced.
7335     EvaluationTracker Eval(*this);
7336     {
7337       SequencedSubexpression Sequenced(*this);
7338       Visit(BO->getLHS());
7339     }
7340
7341     bool Result;
7342     if (Eval.evaluate(BO->getLHS(), Result)) {
7343       if (!Result)
7344         Visit(BO->getRHS());
7345     } else {
7346       // Check for unsequenced operations in the RHS, treating it as an
7347       // entirely separate evaluation.
7348       //
7349       // FIXME: If there are operations in the RHS which are unsequenced
7350       // with respect to operations outside the RHS, and those operations
7351       // are unconditionally evaluated, diagnose them.
7352       WorkList.push_back(BO->getRHS());
7353     }
7354   }
7355   void VisitBinLAnd(BinaryOperator *BO) {
7356     EvaluationTracker Eval(*this);
7357     {
7358       SequencedSubexpression Sequenced(*this);
7359       Visit(BO->getLHS());
7360     }
7361
7362     bool Result;
7363     if (Eval.evaluate(BO->getLHS(), Result)) {
7364       if (Result)
7365         Visit(BO->getRHS());
7366     } else {
7367       WorkList.push_back(BO->getRHS());
7368     }
7369   }
7370
7371   // Only visit the condition, unless we can be sure which subexpression will
7372   // be chosen.
7373   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
7374     EvaluationTracker Eval(*this);
7375     {
7376       SequencedSubexpression Sequenced(*this);
7377       Visit(CO->getCond());
7378     }
7379
7380     bool Result;
7381     if (Eval.evaluate(CO->getCond(), Result))
7382       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
7383     else {
7384       WorkList.push_back(CO->getTrueExpr());
7385       WorkList.push_back(CO->getFalseExpr());
7386     }
7387   }
7388
7389   void VisitCallExpr(CallExpr *CE) {
7390     // C++11 [intro.execution]p15:
7391     //   When calling a function [...], every value computation and side effect
7392     //   associated with any argument expression, or with the postfix expression
7393     //   designating the called function, is sequenced before execution of every
7394     //   expression or statement in the body of the function [and thus before
7395     //   the value computation of its result].
7396     SequencedSubexpression Sequenced(*this);
7397     Base::VisitCallExpr(CE);
7398
7399     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7400   }
7401
7402   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
7403     // This is a call, so all subexpressions are sequenced before the result.
7404     SequencedSubexpression Sequenced(*this);
7405
7406     if (!CCE->isListInitialization())
7407       return VisitExpr(CCE);
7408
7409     // In C++11, list initializations are sequenced.
7410     SmallVector<SequenceTree::Seq, 32> Elts;
7411     SequenceTree::Seq Parent = Region;
7412     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7413                                         E = CCE->arg_end();
7414          I != E; ++I) {
7415       Region = Tree.allocate(Parent);
7416       Elts.push_back(Region);
7417       Visit(*I);
7418     }
7419
7420     // Forget that the initializers are sequenced.
7421     Region = Parent;
7422     for (unsigned I = 0; I < Elts.size(); ++I)
7423       Tree.merge(Elts[I]);
7424   }
7425
7426   void VisitInitListExpr(InitListExpr *ILE) {
7427     if (!SemaRef.getLangOpts().CPlusPlus11)
7428       return VisitExpr(ILE);
7429
7430     // In C++11, list initializations are sequenced.
7431     SmallVector<SequenceTree::Seq, 32> Elts;
7432     SequenceTree::Seq Parent = Region;
7433     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7434       Expr *E = ILE->getInit(I);
7435       if (!E) continue;
7436       Region = Tree.allocate(Parent);
7437       Elts.push_back(Region);
7438       Visit(E);
7439     }
7440
7441     // Forget that the initializers are sequenced.
7442     Region = Parent;
7443     for (unsigned I = 0; I < Elts.size(); ++I)
7444       Tree.merge(Elts[I]);
7445   }
7446 };
7447 }
7448
7449 void Sema::CheckUnsequencedOperations(Expr *E) {
7450   SmallVector<Expr *, 8> WorkList;
7451   WorkList.push_back(E);
7452   while (!WorkList.empty()) {
7453     Expr *Item = WorkList.pop_back_val();
7454     SequenceChecker(*this, Item, WorkList);
7455   }
7456 }
7457
7458 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7459                               bool IsConstexpr) {
7460   CheckImplicitConversions(E, CheckLoc);
7461   CheckUnsequencedOperations(E);
7462   if (!IsConstexpr && !E->isValueDependent())
7463     CheckForIntOverflow(E);
7464 }
7465
7466 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7467                                        FieldDecl *BitField,
7468                                        Expr *Init) {
7469   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7470 }
7471
7472 /// CheckParmsForFunctionDef - Check that the parameters of the given
7473 /// function are appropriate for the definition of a function. This
7474 /// takes care of any checks that cannot be performed on the
7475 /// declaration itself, e.g., that the types of each of the function
7476 /// parameters are complete.
7477 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7478                                     ParmVarDecl *const *PEnd,
7479                                     bool CheckParameterNames) {
7480   bool HasInvalidParm = false;
7481   for (; P != PEnd; ++P) {
7482     ParmVarDecl *Param = *P;
7483     
7484     // C99 6.7.5.3p4: the parameters in a parameter type list in a
7485     // function declarator that is part of a function definition of
7486     // that function shall not have incomplete type.
7487     //
7488     // This is also C++ [dcl.fct]p6.
7489     if (!Param->isInvalidDecl() &&
7490         RequireCompleteType(Param->getLocation(), Param->getType(),
7491                             diag::err_typecheck_decl_incomplete_type)) {
7492       Param->setInvalidDecl();
7493       HasInvalidParm = true;
7494     }
7495
7496     // C99 6.9.1p5: If the declarator includes a parameter type list, the
7497     // declaration of each parameter shall include an identifier.
7498     if (CheckParameterNames &&
7499         Param->getIdentifier() == nullptr &&
7500         !Param->isImplicit() &&
7501         !getLangOpts().CPlusPlus)
7502       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
7503
7504     // C99 6.7.5.3p12:
7505     //   If the function declarator is not part of a definition of that
7506     //   function, parameters may have incomplete type and may use the [*]
7507     //   notation in their sequences of declarator specifiers to specify
7508     //   variable length array types.
7509     QualType PType = Param->getOriginalType();
7510     while (const ArrayType *AT = Context.getAsArrayType(PType)) {
7511       if (AT->getSizeModifier() == ArrayType::Star) {
7512         // FIXME: This diagnostic should point the '[*]' if source-location
7513         // information is added for it.
7514         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
7515         break;
7516       }
7517       PType= AT->getElementType();
7518     }
7519
7520     // MSVC destroys objects passed by value in the callee.  Therefore a
7521     // function definition which takes such a parameter must be able to call the
7522     // object's destructor.  However, we don't perform any direct access check
7523     // on the dtor.
7524     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7525                                        .getCXXABI()
7526                                        .areArgsDestroyedLeftToRightInCallee()) {
7527       if (!Param->isInvalidDecl()) {
7528         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7529           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7530           if (!ClassDecl->isInvalidDecl() &&
7531               !ClassDecl->hasIrrelevantDestructor() &&
7532               !ClassDecl->isDependentContext()) {
7533             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7534             MarkFunctionReferenced(Param->getLocation(), Destructor);
7535             DiagnoseUseOfDecl(Destructor, Param->getLocation());
7536           }
7537         }
7538       }
7539     }
7540   }
7541
7542   return HasInvalidParm;
7543 }
7544
7545 /// CheckCastAlign - Implements -Wcast-align, which warns when a
7546 /// pointer cast increases the alignment requirements.
7547 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7548   // This is actually a lot of work to potentially be doing on every
7549   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
7550   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
7551     return;
7552
7553   // Ignore dependent types.
7554   if (T->isDependentType() || Op->getType()->isDependentType())
7555     return;
7556
7557   // Require that the destination be a pointer type.
7558   const PointerType *DestPtr = T->getAs<PointerType>();
7559   if (!DestPtr) return;
7560
7561   // If the destination has alignment 1, we're done.
7562   QualType DestPointee = DestPtr->getPointeeType();
7563   if (DestPointee->isIncompleteType()) return;
7564   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7565   if (DestAlign.isOne()) return;
7566
7567   // Require that the source be a pointer type.
7568   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7569   if (!SrcPtr) return;
7570   QualType SrcPointee = SrcPtr->getPointeeType();
7571
7572   // Whitelist casts from cv void*.  We already implicitly
7573   // whitelisted casts to cv void*, since they have alignment 1.
7574   // Also whitelist casts involving incomplete types, which implicitly
7575   // includes 'void'.
7576   if (SrcPointee->isIncompleteType()) return;
7577
7578   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7579   if (SrcAlign >= DestAlign) return;
7580
7581   Diag(TRange.getBegin(), diag::warn_cast_align)
7582     << Op->getType() << T
7583     << static_cast<unsigned>(SrcAlign.getQuantity())
7584     << static_cast<unsigned>(DestAlign.getQuantity())
7585     << TRange << Op->getSourceRange();
7586 }
7587
7588 static const Type* getElementType(const Expr *BaseExpr) {
7589   const Type* EltType = BaseExpr->getType().getTypePtr();
7590   if (EltType->isAnyPointerType())
7591     return EltType->getPointeeType().getTypePtr();
7592   else if (EltType->isArrayType())
7593     return EltType->getBaseElementTypeUnsafe();
7594   return EltType;
7595 }
7596
7597 /// \brief Check whether this array fits the idiom of a size-one tail padded
7598 /// array member of a struct.
7599 ///
7600 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
7601 /// commonly used to emulate flexible arrays in C89 code.
7602 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7603                                     const NamedDecl *ND) {
7604   if (Size != 1 || !ND) return false;
7605
7606   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7607   if (!FD) return false;
7608
7609   // Don't consider sizes resulting from macro expansions or template argument
7610   // substitution to form C89 tail-padded arrays.
7611
7612   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
7613   while (TInfo) {
7614     TypeLoc TL = TInfo->getTypeLoc();
7615     // Look through typedefs.
7616     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7617       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
7618       TInfo = TDL->getTypeSourceInfo();
7619       continue;
7620     }
7621     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7622       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
7623       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7624         return false;
7625     }
7626     break;
7627   }
7628
7629   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
7630   if (!RD) return false;
7631   if (RD->isUnion()) return false;
7632   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7633     if (!CRD->isStandardLayout()) return false;
7634   }
7635
7636   // See if this is the last field decl in the record.
7637   const Decl *D = FD;
7638   while ((D = D->getNextDeclInContext()))
7639     if (isa<FieldDecl>(D))
7640       return false;
7641   return true;
7642 }
7643
7644 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7645                             const ArraySubscriptExpr *ASE,
7646                             bool AllowOnePastEnd, bool IndexNegated) {
7647   IndexExpr = IndexExpr->IgnoreParenImpCasts();
7648   if (IndexExpr->isValueDependent())
7649     return;
7650
7651   const Type *EffectiveType = getElementType(BaseExpr);
7652   BaseExpr = BaseExpr->IgnoreParenCasts();
7653   const ConstantArrayType *ArrayTy =
7654     Context.getAsConstantArrayType(BaseExpr->getType());
7655   if (!ArrayTy)
7656     return;
7657
7658   llvm::APSInt index;
7659   if (!IndexExpr->EvaluateAsInt(index, Context))
7660     return;
7661   if (IndexNegated)
7662     index = -index;
7663
7664   const NamedDecl *ND = nullptr;
7665   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7666     ND = dyn_cast<NamedDecl>(DRE->getDecl());
7667   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7668     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7669
7670   if (index.isUnsigned() || !index.isNegative()) {
7671     llvm::APInt size = ArrayTy->getSize();
7672     if (!size.isStrictlyPositive())
7673       return;
7674
7675     const Type* BaseType = getElementType(BaseExpr);
7676     if (BaseType != EffectiveType) {
7677       // Make sure we're comparing apples to apples when comparing index to size
7678       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7679       uint64_t array_typesize = Context.getTypeSize(BaseType);
7680       // Handle ptrarith_typesize being zero, such as when casting to void*
7681       if (!ptrarith_typesize) ptrarith_typesize = 1;
7682       if (ptrarith_typesize != array_typesize) {
7683         // There's a cast to a different size type involved
7684         uint64_t ratio = array_typesize / ptrarith_typesize;
7685         // TODO: Be smarter about handling cases where array_typesize is not a
7686         // multiple of ptrarith_typesize
7687         if (ptrarith_typesize * ratio == array_typesize)
7688           size *= llvm::APInt(size.getBitWidth(), ratio);
7689       }
7690     }
7691
7692     if (size.getBitWidth() > index.getBitWidth())
7693       index = index.zext(size.getBitWidth());
7694     else if (size.getBitWidth() < index.getBitWidth())
7695       size = size.zext(index.getBitWidth());
7696
7697     // For array subscripting the index must be less than size, but for pointer
7698     // arithmetic also allow the index (offset) to be equal to size since
7699     // computing the next address after the end of the array is legal and
7700     // commonly done e.g. in C++ iterators and range-based for loops.
7701     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
7702       return;
7703
7704     // Also don't warn for arrays of size 1 which are members of some
7705     // structure. These are often used to approximate flexible arrays in C89
7706     // code.
7707     if (IsTailPaddedMemberArray(*this, size, ND))
7708       return;
7709
7710     // Suppress the warning if the subscript expression (as identified by the
7711     // ']' location) and the index expression are both from macro expansions
7712     // within a system header.
7713     if (ASE) {
7714       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7715           ASE->getRBracketLoc());
7716       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7717         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7718             IndexExpr->getLocStart());
7719         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
7720           return;
7721       }
7722     }
7723
7724     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
7725     if (ASE)
7726       DiagID = diag::warn_array_index_exceeds_bounds;
7727
7728     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7729                         PDiag(DiagID) << index.toString(10, true)
7730                           << size.toString(10, true)
7731                           << (unsigned)size.getLimitedValue(~0U)
7732                           << IndexExpr->getSourceRange());
7733   } else {
7734     unsigned DiagID = diag::warn_array_index_precedes_bounds;
7735     if (!ASE) {
7736       DiagID = diag::warn_ptr_arith_precedes_bounds;
7737       if (index.isNegative()) index = -index;
7738     }
7739
7740     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7741                         PDiag(DiagID) << index.toString(10, true)
7742                           << IndexExpr->getSourceRange());
7743   }
7744
7745   if (!ND) {
7746     // Try harder to find a NamedDecl to point at in the note.
7747     while (const ArraySubscriptExpr *ASE =
7748            dyn_cast<ArraySubscriptExpr>(BaseExpr))
7749       BaseExpr = ASE->getBase()->IgnoreParenCasts();
7750     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7751       ND = dyn_cast<NamedDecl>(DRE->getDecl());
7752     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7753       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7754   }
7755
7756   if (ND)
7757     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7758                         PDiag(diag::note_array_index_out_of_bounds)
7759                           << ND->getDeclName());
7760 }
7761
7762 void Sema::CheckArrayAccess(const Expr *expr) {
7763   int AllowOnePastEnd = 0;
7764   while (expr) {
7765     expr = expr->IgnoreParenImpCasts();
7766     switch (expr->getStmtClass()) {
7767       case Stmt::ArraySubscriptExprClass: {
7768         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
7769         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
7770                          AllowOnePastEnd > 0);
7771         return;
7772       }
7773       case Stmt::UnaryOperatorClass: {
7774         // Only unwrap the * and & unary operators
7775         const UnaryOperator *UO = cast<UnaryOperator>(expr);
7776         expr = UO->getSubExpr();
7777         switch (UO->getOpcode()) {
7778           case UO_AddrOf:
7779             AllowOnePastEnd++;
7780             break;
7781           case UO_Deref:
7782             AllowOnePastEnd--;
7783             break;
7784           default:
7785             return;
7786         }
7787         break;
7788       }
7789       case Stmt::ConditionalOperatorClass: {
7790         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7791         if (const Expr *lhs = cond->getLHS())
7792           CheckArrayAccess(lhs);
7793         if (const Expr *rhs = cond->getRHS())
7794           CheckArrayAccess(rhs);
7795         return;
7796       }
7797       default:
7798         return;
7799     }
7800   }
7801 }
7802
7803 //===--- CHECK: Objective-C retain cycles ----------------------------------//
7804
7805 namespace {
7806   struct RetainCycleOwner {
7807     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
7808     VarDecl *Variable;
7809     SourceRange Range;
7810     SourceLocation Loc;
7811     bool Indirect;
7812
7813     void setLocsFrom(Expr *e) {
7814       Loc = e->getExprLoc();
7815       Range = e->getSourceRange();
7816     }
7817   };
7818 }
7819
7820 /// Consider whether capturing the given variable can possibly lead to
7821 /// a retain cycle.
7822 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
7823   // In ARC, it's captured strongly iff the variable has __strong
7824   // lifetime.  In MRR, it's captured strongly if the variable is
7825   // __block and has an appropriate type.
7826   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7827     return false;
7828
7829   owner.Variable = var;
7830   if (ref)
7831     owner.setLocsFrom(ref);
7832   return true;
7833 }
7834
7835 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
7836   while (true) {
7837     e = e->IgnoreParens();
7838     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7839       switch (cast->getCastKind()) {
7840       case CK_BitCast:
7841       case CK_LValueBitCast:
7842       case CK_LValueToRValue:
7843       case CK_ARCReclaimReturnedObject:
7844         e = cast->getSubExpr();
7845         continue;
7846
7847       default:
7848         return false;
7849       }
7850     }
7851
7852     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7853       ObjCIvarDecl *ivar = ref->getDecl();
7854       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7855         return false;
7856
7857       // Try to find a retain cycle in the base.
7858       if (!findRetainCycleOwner(S, ref->getBase(), owner))
7859         return false;
7860
7861       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7862       owner.Indirect = true;
7863       return true;
7864     }
7865
7866     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7867       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7868       if (!var) return false;
7869       return considerVariable(var, ref, owner);
7870     }
7871
7872     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7873       if (member->isArrow()) return false;
7874
7875       // Don't count this as an indirect ownership.
7876       e = member->getBase();
7877       continue;
7878     }
7879
7880     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7881       // Only pay attention to pseudo-objects on property references.
7882       ObjCPropertyRefExpr *pre
7883         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7884                                               ->IgnoreParens());
7885       if (!pre) return false;
7886       if (pre->isImplicitProperty()) return false;
7887       ObjCPropertyDecl *property = pre->getExplicitProperty();
7888       if (!property->isRetaining() &&
7889           !(property->getPropertyIvarDecl() &&
7890             property->getPropertyIvarDecl()->getType()
7891               .getObjCLifetime() == Qualifiers::OCL_Strong))
7892           return false;
7893
7894       owner.Indirect = true;
7895       if (pre->isSuperReceiver()) {
7896         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7897         if (!owner.Variable)
7898           return false;
7899         owner.Loc = pre->getLocation();
7900         owner.Range = pre->getSourceRange();
7901         return true;
7902       }
7903       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7904                               ->getSourceExpr());
7905       continue;
7906     }
7907
7908     // Array ivars?
7909
7910     return false;
7911   }
7912 }
7913
7914 namespace {
7915   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7916     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7917       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7918         Context(Context), Variable(variable), Capturer(nullptr),
7919         VarWillBeReased(false) {}
7920     ASTContext &Context;
7921     VarDecl *Variable;
7922     Expr *Capturer;
7923     bool VarWillBeReased;
7924
7925     void VisitDeclRefExpr(DeclRefExpr *ref) {
7926       if (ref->getDecl() == Variable && !Capturer)
7927         Capturer = ref;
7928     }
7929
7930     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7931       if (Capturer) return;
7932       Visit(ref->getBase());
7933       if (Capturer && ref->isFreeIvar())
7934         Capturer = ref;
7935     }
7936
7937     void VisitBlockExpr(BlockExpr *block) {
7938       // Look inside nested blocks 
7939       if (block->getBlockDecl()->capturesVariable(Variable))
7940         Visit(block->getBlockDecl()->getBody());
7941     }
7942     
7943     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7944       if (Capturer) return;
7945       if (OVE->getSourceExpr())
7946         Visit(OVE->getSourceExpr());
7947     }
7948     void VisitBinaryOperator(BinaryOperator *BinOp) {
7949       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7950         return;
7951       Expr *LHS = BinOp->getLHS();
7952       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7953         if (DRE->getDecl() != Variable)
7954           return;
7955         if (Expr *RHS = BinOp->getRHS()) {
7956           RHS = RHS->IgnoreParenCasts();
7957           llvm::APSInt Value;
7958           VarWillBeReased =
7959             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7960         }
7961       }
7962     }
7963   };
7964 }
7965
7966 /// Check whether the given argument is a block which captures a
7967 /// variable.
7968 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7969   assert(owner.Variable && owner.Loc.isValid());
7970
7971   e = e->IgnoreParenCasts();
7972
7973   // Look through [^{...} copy] and Block_copy(^{...}).
7974   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7975     Selector Cmd = ME->getSelector();
7976     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7977       e = ME->getInstanceReceiver();
7978       if (!e)
7979         return nullptr;
7980       e = e->IgnoreParenCasts();
7981     }
7982   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7983     if (CE->getNumArgs() == 1) {
7984       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
7985       if (Fn) {
7986         const IdentifierInfo *FnI = Fn->getIdentifier();
7987         if (FnI && FnI->isStr("_Block_copy")) {
7988           e = CE->getArg(0)->IgnoreParenCasts();
7989         }
7990       }
7991     }
7992   }
7993   
7994   BlockExpr *block = dyn_cast<BlockExpr>(e);
7995   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7996     return nullptr;
7997
7998   FindCaptureVisitor visitor(S.Context, owner.Variable);
7999   visitor.Visit(block->getBlockDecl()->getBody());
8000   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
8001 }
8002
8003 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8004                                 RetainCycleOwner &owner) {
8005   assert(capturer);
8006   assert(owner.Variable && owner.Loc.isValid());
8007
8008   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8009     << owner.Variable << capturer->getSourceRange();
8010   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8011     << owner.Indirect << owner.Range;
8012 }
8013
8014 /// Check for a keyword selector that starts with the word 'add' or
8015 /// 'set'.
8016 static bool isSetterLikeSelector(Selector sel) {
8017   if (sel.isUnarySelector()) return false;
8018
8019   StringRef str = sel.getNameForSlot(0);
8020   while (!str.empty() && str.front() == '_') str = str.substr(1);
8021   if (str.startswith("set"))
8022     str = str.substr(3);
8023   else if (str.startswith("add")) {
8024     // Specially whitelist 'addOperationWithBlock:'.
8025     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8026       return false;
8027     str = str.substr(3);
8028   }
8029   else
8030     return false;
8031
8032   if (str.empty()) return true;
8033   return !isLowercase(str.front());
8034 }
8035
8036 /// Check a message send to see if it's likely to cause a retain cycle.
8037 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8038   // Only check instance methods whose selector looks like a setter.
8039   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8040     return;
8041
8042   // Try to find a variable that the receiver is strongly owned by.
8043   RetainCycleOwner owner;
8044   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
8045     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
8046       return;
8047   } else {
8048     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8049     owner.Variable = getCurMethodDecl()->getSelfDecl();
8050     owner.Loc = msg->getSuperLoc();
8051     owner.Range = msg->getSuperLoc();
8052   }
8053
8054   // Check whether the receiver is captured by any of the arguments.
8055   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8056     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8057       return diagnoseRetainCycle(*this, capturer, owner);
8058 }
8059
8060 /// Check a property assign to see if it's likely to cause a retain cycle.
8061 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8062   RetainCycleOwner owner;
8063   if (!findRetainCycleOwner(*this, receiver, owner))
8064     return;
8065
8066   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8067     diagnoseRetainCycle(*this, capturer, owner);
8068 }
8069
8070 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8071   RetainCycleOwner Owner;
8072   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
8073     return;
8074   
8075   // Because we don't have an expression for the variable, we have to set the
8076   // location explicitly here.
8077   Owner.Loc = Var->getLocation();
8078   Owner.Range = Var->getSourceRange();
8079   
8080   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8081     diagnoseRetainCycle(*this, Capturer, Owner);
8082 }
8083
8084 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8085                                      Expr *RHS, bool isProperty) {
8086   // Check if RHS is an Objective-C object literal, which also can get
8087   // immediately zapped in a weak reference.  Note that we explicitly
8088   // allow ObjCStringLiterals, since those are designed to never really die.
8089   RHS = RHS->IgnoreParenImpCasts();
8090
8091   // This enum needs to match with the 'select' in
8092   // warn_objc_arc_literal_assign (off-by-1).
8093   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8094   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8095     return false;
8096
8097   S.Diag(Loc, diag::warn_arc_literal_assign)
8098     << (unsigned) Kind
8099     << (isProperty ? 0 : 1)
8100     << RHS->getSourceRange();
8101
8102   return true;
8103 }
8104
8105 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8106                                     Qualifiers::ObjCLifetime LT,
8107                                     Expr *RHS, bool isProperty) {
8108   // Strip off any implicit cast added to get to the one ARC-specific.
8109   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8110     if (cast->getCastKind() == CK_ARCConsumeObject) {
8111       S.Diag(Loc, diag::warn_arc_retained_assign)
8112         << (LT == Qualifiers::OCL_ExplicitNone)
8113         << (isProperty ? 0 : 1)
8114         << RHS->getSourceRange();
8115       return true;
8116     }
8117     RHS = cast->getSubExpr();
8118   }
8119
8120   if (LT == Qualifiers::OCL_Weak &&
8121       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8122     return true;
8123
8124   return false;
8125 }
8126
8127 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8128                               QualType LHS, Expr *RHS) {
8129   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8130
8131   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8132     return false;
8133
8134   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8135     return true;
8136
8137   return false;
8138 }
8139
8140 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8141                               Expr *LHS, Expr *RHS) {
8142   QualType LHSType;
8143   // PropertyRef on LHS type need be directly obtained from
8144   // its declaration as it has a PseudoType.
8145   ObjCPropertyRefExpr *PRE
8146     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8147   if (PRE && !PRE->isImplicitProperty()) {
8148     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8149     if (PD)
8150       LHSType = PD->getType();
8151   }
8152   
8153   if (LHSType.isNull())
8154     LHSType = LHS->getType();
8155
8156   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8157
8158   if (LT == Qualifiers::OCL_Weak) {
8159     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
8160       getCurFunction()->markSafeWeakUse(LHS);
8161   }
8162
8163   if (checkUnsafeAssigns(Loc, LHSType, RHS))
8164     return;
8165
8166   // FIXME. Check for other life times.
8167   if (LT != Qualifiers::OCL_None)
8168     return;
8169   
8170   if (PRE) {
8171     if (PRE->isImplicitProperty())
8172       return;
8173     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8174     if (!PD)
8175       return;
8176     
8177     unsigned Attributes = PD->getPropertyAttributes();
8178     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
8179       // when 'assign' attribute was not explicitly specified
8180       // by user, ignore it and rely on property type itself
8181       // for lifetime info.
8182       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8183       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8184           LHSType->isObjCRetainableType())
8185         return;
8186         
8187       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8188         if (cast->getCastKind() == CK_ARCConsumeObject) {
8189           Diag(Loc, diag::warn_arc_retained_property_assign)
8190           << RHS->getSourceRange();
8191           return;
8192         }
8193         RHS = cast->getSubExpr();
8194       }
8195     }
8196     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
8197       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8198         return;
8199     }
8200   }
8201 }
8202
8203 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8204
8205 namespace {
8206 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8207                                  SourceLocation StmtLoc,
8208                                  const NullStmt *Body) {
8209   // Do not warn if the body is a macro that expands to nothing, e.g:
8210   //
8211   // #define CALL(x)
8212   // if (condition)
8213   //   CALL(0);
8214   //
8215   if (Body->hasLeadingEmptyMacro())
8216     return false;
8217
8218   // Get line numbers of statement and body.
8219   bool StmtLineInvalid;
8220   unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8221                                                       &StmtLineInvalid);
8222   if (StmtLineInvalid)
8223     return false;
8224
8225   bool BodyLineInvalid;
8226   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8227                                                       &BodyLineInvalid);
8228   if (BodyLineInvalid)
8229     return false;
8230
8231   // Warn if null statement and body are on the same line.
8232   if (StmtLine != BodyLine)
8233     return false;
8234
8235   return true;
8236 }
8237 } // Unnamed namespace
8238
8239 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8240                                  const Stmt *Body,
8241                                  unsigned DiagID) {
8242   // Since this is a syntactic check, don't emit diagnostic for template
8243   // instantiations, this just adds noise.
8244   if (CurrentInstantiationScope)
8245     return;
8246
8247   // The body should be a null statement.
8248   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8249   if (!NBody)
8250     return;
8251
8252   // Do the usual checks.
8253   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8254     return;
8255
8256   Diag(NBody->getSemiLoc(), DiagID);
8257   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8258 }
8259
8260 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8261                                  const Stmt *PossibleBody) {
8262   assert(!CurrentInstantiationScope); // Ensured by caller
8263
8264   SourceLocation StmtLoc;
8265   const Stmt *Body;
8266   unsigned DiagID;
8267   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8268     StmtLoc = FS->getRParenLoc();
8269     Body = FS->getBody();
8270     DiagID = diag::warn_empty_for_body;
8271   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8272     StmtLoc = WS->getCond()->getSourceRange().getEnd();
8273     Body = WS->getBody();
8274     DiagID = diag::warn_empty_while_body;
8275   } else
8276     return; // Neither `for' nor `while'.
8277
8278   // The body should be a null statement.
8279   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8280   if (!NBody)
8281     return;
8282
8283   // Skip expensive checks if diagnostic is disabled.
8284   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
8285     return;
8286
8287   // Do the usual checks.
8288   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8289     return;
8290
8291   // `for(...);' and `while(...);' are popular idioms, so in order to keep
8292   // noise level low, emit diagnostics only if for/while is followed by a
8293   // CompoundStmt, e.g.:
8294   //    for (int i = 0; i < n; i++);
8295   //    {
8296   //      a(i);
8297   //    }
8298   // or if for/while is followed by a statement with more indentation
8299   // than for/while itself:
8300   //    for (int i = 0; i < n; i++);
8301   //      a(i);
8302   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8303   if (!ProbableTypo) {
8304     bool BodyColInvalid;
8305     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8306                              PossibleBody->getLocStart(),
8307                              &BodyColInvalid);
8308     if (BodyColInvalid)
8309       return;
8310
8311     bool StmtColInvalid;
8312     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8313                              S->getLocStart(),
8314                              &StmtColInvalid);
8315     if (StmtColInvalid)
8316       return;
8317
8318     if (BodyCol > StmtCol)
8319       ProbableTypo = true;
8320   }
8321
8322   if (ProbableTypo) {
8323     Diag(NBody->getSemiLoc(), DiagID);
8324     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8325   }
8326 }
8327
8328 //===--- CHECK: Warn on self move with std::move. -------------------------===//
8329
8330 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8331 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8332                              SourceLocation OpLoc) {
8333
8334   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8335     return;
8336
8337   if (!ActiveTemplateInstantiations.empty())
8338     return;
8339
8340   // Strip parens and casts away.
8341   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8342   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8343
8344   // Check for a call expression
8345   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8346   if (!CE || CE->getNumArgs() != 1)
8347     return;
8348
8349   // Check for a call to std::move
8350   const FunctionDecl *FD = CE->getDirectCallee();
8351   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8352       !FD->getIdentifier()->isStr("move"))
8353     return;
8354
8355   // Get argument from std::move
8356   RHSExpr = CE->getArg(0);
8357
8358   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8359   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8360
8361   // Two DeclRefExpr's, check that the decls are the same.
8362   if (LHSDeclRef && RHSDeclRef) {
8363     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8364       return;
8365     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8366         RHSDeclRef->getDecl()->getCanonicalDecl())
8367       return;
8368
8369     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8370                                         << LHSExpr->getSourceRange()
8371                                         << RHSExpr->getSourceRange();
8372     return;
8373   }
8374
8375   // Member variables require a different approach to check for self moves.
8376   // MemberExpr's are the same if every nested MemberExpr refers to the same
8377   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8378   // the base Expr's are CXXThisExpr's.
8379   const Expr *LHSBase = LHSExpr;
8380   const Expr *RHSBase = RHSExpr;
8381   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8382   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8383   if (!LHSME || !RHSME)
8384     return;
8385
8386   while (LHSME && RHSME) {
8387     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8388         RHSME->getMemberDecl()->getCanonicalDecl())
8389       return;
8390
8391     LHSBase = LHSME->getBase();
8392     RHSBase = RHSME->getBase();
8393     LHSME = dyn_cast<MemberExpr>(LHSBase);
8394     RHSME = dyn_cast<MemberExpr>(RHSBase);
8395   }
8396
8397   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8398   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8399   if (LHSDeclRef && RHSDeclRef) {
8400     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8401       return;
8402     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8403         RHSDeclRef->getDecl()->getCanonicalDecl())
8404       return;
8405
8406     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8407                                         << LHSExpr->getSourceRange()
8408                                         << RHSExpr->getSourceRange();
8409     return;
8410   }
8411
8412   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8413     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8414                                         << LHSExpr->getSourceRange()
8415                                         << RHSExpr->getSourceRange();
8416 }
8417
8418 //===--- Layout compatibility ----------------------------------------------//
8419
8420 namespace {
8421
8422 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8423
8424 /// \brief Check if two enumeration types are layout-compatible.
8425 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8426   // C++11 [dcl.enum] p8:
8427   // Two enumeration types are layout-compatible if they have the same
8428   // underlying type.
8429   return ED1->isComplete() && ED2->isComplete() &&
8430          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8431 }
8432
8433 /// \brief Check if two fields are layout-compatible.
8434 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8435   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8436     return false;
8437
8438   if (Field1->isBitField() != Field2->isBitField())
8439     return false;
8440
8441   if (Field1->isBitField()) {
8442     // Make sure that the bit-fields are the same length.
8443     unsigned Bits1 = Field1->getBitWidthValue(C);
8444     unsigned Bits2 = Field2->getBitWidthValue(C);
8445
8446     if (Bits1 != Bits2)
8447       return false;
8448   }
8449
8450   return true;
8451 }
8452
8453 /// \brief Check if two standard-layout structs are layout-compatible.
8454 /// (C++11 [class.mem] p17)
8455 bool isLayoutCompatibleStruct(ASTContext &C,
8456                               RecordDecl *RD1,
8457                               RecordDecl *RD2) {
8458   // If both records are C++ classes, check that base classes match.
8459   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8460     // If one of records is a CXXRecordDecl we are in C++ mode,
8461     // thus the other one is a CXXRecordDecl, too.
8462     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8463     // Check number of base classes.
8464     if (D1CXX->getNumBases() != D2CXX->getNumBases())
8465       return false;
8466
8467     // Check the base classes.
8468     for (CXXRecordDecl::base_class_const_iterator
8469                Base1 = D1CXX->bases_begin(),
8470            BaseEnd1 = D1CXX->bases_end(),
8471               Base2 = D2CXX->bases_begin();
8472          Base1 != BaseEnd1;
8473          ++Base1, ++Base2) {
8474       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8475         return false;
8476     }
8477   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8478     // If only RD2 is a C++ class, it should have zero base classes.
8479     if (D2CXX->getNumBases() > 0)
8480       return false;
8481   }
8482
8483   // Check the fields.
8484   RecordDecl::field_iterator Field2 = RD2->field_begin(),
8485                              Field2End = RD2->field_end(),
8486                              Field1 = RD1->field_begin(),
8487                              Field1End = RD1->field_end();
8488   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8489     if (!isLayoutCompatible(C, *Field1, *Field2))
8490       return false;
8491   }
8492   if (Field1 != Field1End || Field2 != Field2End)
8493     return false;
8494
8495   return true;
8496 }
8497
8498 /// \brief Check if two standard-layout unions are layout-compatible.
8499 /// (C++11 [class.mem] p18)
8500 bool isLayoutCompatibleUnion(ASTContext &C,
8501                              RecordDecl *RD1,
8502                              RecordDecl *RD2) {
8503   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
8504   for (auto *Field2 : RD2->fields())
8505     UnmatchedFields.insert(Field2);
8506
8507   for (auto *Field1 : RD1->fields()) {
8508     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8509         I = UnmatchedFields.begin(),
8510         E = UnmatchedFields.end();
8511
8512     for ( ; I != E; ++I) {
8513       if (isLayoutCompatible(C, Field1, *I)) {
8514         bool Result = UnmatchedFields.erase(*I);
8515         (void) Result;
8516         assert(Result);
8517         break;
8518       }
8519     }
8520     if (I == E)
8521       return false;
8522   }
8523
8524   return UnmatchedFields.empty();
8525 }
8526
8527 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8528   if (RD1->isUnion() != RD2->isUnion())
8529     return false;
8530
8531   if (RD1->isUnion())
8532     return isLayoutCompatibleUnion(C, RD1, RD2);
8533   else
8534     return isLayoutCompatibleStruct(C, RD1, RD2);
8535 }
8536
8537 /// \brief Check if two types are layout-compatible in C++11 sense.
8538 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8539   if (T1.isNull() || T2.isNull())
8540     return false;
8541
8542   // C++11 [basic.types] p11:
8543   // If two types T1 and T2 are the same type, then T1 and T2 are
8544   // layout-compatible types.
8545   if (C.hasSameType(T1, T2))
8546     return true;
8547
8548   T1 = T1.getCanonicalType().getUnqualifiedType();
8549   T2 = T2.getCanonicalType().getUnqualifiedType();
8550
8551   const Type::TypeClass TC1 = T1->getTypeClass();
8552   const Type::TypeClass TC2 = T2->getTypeClass();
8553
8554   if (TC1 != TC2)
8555     return false;
8556
8557   if (TC1 == Type::Enum) {
8558     return isLayoutCompatible(C,
8559                               cast<EnumType>(T1)->getDecl(),
8560                               cast<EnumType>(T2)->getDecl());
8561   } else if (TC1 == Type::Record) {
8562     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8563       return false;
8564
8565     return isLayoutCompatible(C,
8566                               cast<RecordType>(T1)->getDecl(),
8567                               cast<RecordType>(T2)->getDecl());
8568   }
8569
8570   return false;
8571 }
8572 }
8573
8574 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8575
8576 namespace {
8577 /// \brief Given a type tag expression find the type tag itself.
8578 ///
8579 /// \param TypeExpr Type tag expression, as it appears in user's code.
8580 ///
8581 /// \param VD Declaration of an identifier that appears in a type tag.
8582 ///
8583 /// \param MagicValue Type tag magic value.
8584 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8585                      const ValueDecl **VD, uint64_t *MagicValue) {
8586   while(true) {
8587     if (!TypeExpr)
8588       return false;
8589
8590     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8591
8592     switch (TypeExpr->getStmtClass()) {
8593     case Stmt::UnaryOperatorClass: {
8594       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8595       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8596         TypeExpr = UO->getSubExpr();
8597         continue;
8598       }
8599       return false;
8600     }
8601
8602     case Stmt::DeclRefExprClass: {
8603       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8604       *VD = DRE->getDecl();
8605       return true;
8606     }
8607
8608     case Stmt::IntegerLiteralClass: {
8609       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8610       llvm::APInt MagicValueAPInt = IL->getValue();
8611       if (MagicValueAPInt.getActiveBits() <= 64) {
8612         *MagicValue = MagicValueAPInt.getZExtValue();
8613         return true;
8614       } else
8615         return false;
8616     }
8617
8618     case Stmt::BinaryConditionalOperatorClass:
8619     case Stmt::ConditionalOperatorClass: {
8620       const AbstractConditionalOperator *ACO =
8621           cast<AbstractConditionalOperator>(TypeExpr);
8622       bool Result;
8623       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8624         if (Result)
8625           TypeExpr = ACO->getTrueExpr();
8626         else
8627           TypeExpr = ACO->getFalseExpr();
8628         continue;
8629       }
8630       return false;
8631     }
8632
8633     case Stmt::BinaryOperatorClass: {
8634       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8635       if (BO->getOpcode() == BO_Comma) {
8636         TypeExpr = BO->getRHS();
8637         continue;
8638       }
8639       return false;
8640     }
8641
8642     default:
8643       return false;
8644     }
8645   }
8646 }
8647
8648 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
8649 ///
8650 /// \param TypeExpr Expression that specifies a type tag.
8651 ///
8652 /// \param MagicValues Registered magic values.
8653 ///
8654 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8655 ///        kind.
8656 ///
8657 /// \param TypeInfo Information about the corresponding C type.
8658 ///
8659 /// \returns true if the corresponding C type was found.
8660 bool GetMatchingCType(
8661         const IdentifierInfo *ArgumentKind,
8662         const Expr *TypeExpr, const ASTContext &Ctx,
8663         const llvm::DenseMap<Sema::TypeTagMagicValue,
8664                              Sema::TypeTagData> *MagicValues,
8665         bool &FoundWrongKind,
8666         Sema::TypeTagData &TypeInfo) {
8667   FoundWrongKind = false;
8668
8669   // Variable declaration that has type_tag_for_datatype attribute.
8670   const ValueDecl *VD = nullptr;
8671
8672   uint64_t MagicValue;
8673
8674   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8675     return false;
8676
8677   if (VD) {
8678     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
8679       if (I->getArgumentKind() != ArgumentKind) {
8680         FoundWrongKind = true;
8681         return false;
8682       }
8683       TypeInfo.Type = I->getMatchingCType();
8684       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8685       TypeInfo.MustBeNull = I->getMustBeNull();
8686       return true;
8687     }
8688     return false;
8689   }
8690
8691   if (!MagicValues)
8692     return false;
8693
8694   llvm::DenseMap<Sema::TypeTagMagicValue,
8695                  Sema::TypeTagData>::const_iterator I =
8696       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8697   if (I == MagicValues->end())
8698     return false;
8699
8700   TypeInfo = I->second;
8701   return true;
8702 }
8703 } // unnamed namespace
8704
8705 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8706                                       uint64_t MagicValue, QualType Type,
8707                                       bool LayoutCompatible,
8708                                       bool MustBeNull) {
8709   if (!TypeTagForDatatypeMagicValues)
8710     TypeTagForDatatypeMagicValues.reset(
8711         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8712
8713   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8714   (*TypeTagForDatatypeMagicValues)[Magic] =
8715       TypeTagData(Type, LayoutCompatible, MustBeNull);
8716 }
8717
8718 namespace {
8719 bool IsSameCharType(QualType T1, QualType T2) {
8720   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8721   if (!BT1)
8722     return false;
8723
8724   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8725   if (!BT2)
8726     return false;
8727
8728   BuiltinType::Kind T1Kind = BT1->getKind();
8729   BuiltinType::Kind T2Kind = BT2->getKind();
8730
8731   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
8732          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
8733          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8734          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8735 }
8736 } // unnamed namespace
8737
8738 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8739                                     const Expr * const *ExprArgs) {
8740   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8741   bool IsPointerAttr = Attr->getIsPointer();
8742
8743   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8744   bool FoundWrongKind;
8745   TypeTagData TypeInfo;
8746   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8747                         TypeTagForDatatypeMagicValues.get(),
8748                         FoundWrongKind, TypeInfo)) {
8749     if (FoundWrongKind)
8750       Diag(TypeTagExpr->getExprLoc(),
8751            diag::warn_type_tag_for_datatype_wrong_kind)
8752         << TypeTagExpr->getSourceRange();
8753     return;
8754   }
8755
8756   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8757   if (IsPointerAttr) {
8758     // Skip implicit cast of pointer to `void *' (as a function argument).
8759     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
8760       if (ICE->getType()->isVoidPointerType() &&
8761           ICE->getCastKind() == CK_BitCast)
8762         ArgumentExpr = ICE->getSubExpr();
8763   }
8764   QualType ArgumentType = ArgumentExpr->getType();
8765
8766   // Passing a `void*' pointer shouldn't trigger a warning.
8767   if (IsPointerAttr && ArgumentType->isVoidPointerType())
8768     return;
8769
8770   if (TypeInfo.MustBeNull) {
8771     // Type tag with matching void type requires a null pointer.
8772     if (!ArgumentExpr->isNullPointerConstant(Context,
8773                                              Expr::NPC_ValueDependentIsNotNull)) {
8774       Diag(ArgumentExpr->getExprLoc(),
8775            diag::warn_type_safety_null_pointer_required)
8776           << ArgumentKind->getName()
8777           << ArgumentExpr->getSourceRange()
8778           << TypeTagExpr->getSourceRange();
8779     }
8780     return;
8781   }
8782
8783   QualType RequiredType = TypeInfo.Type;
8784   if (IsPointerAttr)
8785     RequiredType = Context.getPointerType(RequiredType);
8786
8787   bool mismatch = false;
8788   if (!TypeInfo.LayoutCompatible) {
8789     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8790
8791     // C++11 [basic.fundamental] p1:
8792     // Plain char, signed char, and unsigned char are three distinct types.
8793     //
8794     // But we treat plain `char' as equivalent to `signed char' or `unsigned
8795     // char' depending on the current char signedness mode.
8796     if (mismatch)
8797       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8798                                            RequiredType->getPointeeType())) ||
8799           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8800         mismatch = false;
8801   } else
8802     if (IsPointerAttr)
8803       mismatch = !isLayoutCompatible(Context,
8804                                      ArgumentType->getPointeeType(),
8805                                      RequiredType->getPointeeType());
8806     else
8807       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8808
8809   if (mismatch)
8810     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
8811         << ArgumentType << ArgumentKind
8812         << TypeInfo.LayoutCompatible << RequiredType
8813         << ArgumentExpr->getSourceRange()
8814         << TypeTagExpr->getSourceRange();
8815 }
8816