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