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