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