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