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 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1074   unsigned i = 0, l = 0, u = 0;
1075   switch (BuiltinID) {
1076   default: return false;
1077   case X86::BI__builtin_cpu_supports:
1078     return SemaBuiltinCpuSupports(TheCall);
1079   case X86::BI__builtin_ms_va_start:
1080     return SemaBuiltinMSVAStart(TheCall);
1081   case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
1082   case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
1083   case X86::BI__builtin_ia32_vpermil2pd:
1084   case X86::BI__builtin_ia32_vpermil2pd256:
1085   case X86::BI__builtin_ia32_vpermil2ps:
1086   case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
1087   case X86::BI__builtin_ia32_cmpb128_mask:
1088   case X86::BI__builtin_ia32_cmpw128_mask:
1089   case X86::BI__builtin_ia32_cmpd128_mask:
1090   case X86::BI__builtin_ia32_cmpq128_mask:
1091   case X86::BI__builtin_ia32_cmpb256_mask:
1092   case X86::BI__builtin_ia32_cmpw256_mask:
1093   case X86::BI__builtin_ia32_cmpd256_mask:
1094   case X86::BI__builtin_ia32_cmpq256_mask:
1095   case X86::BI__builtin_ia32_cmpb512_mask:
1096   case X86::BI__builtin_ia32_cmpw512_mask:
1097   case X86::BI__builtin_ia32_cmpd512_mask:
1098   case X86::BI__builtin_ia32_cmpq512_mask:
1099   case X86::BI__builtin_ia32_ucmpb128_mask:
1100   case X86::BI__builtin_ia32_ucmpw128_mask:
1101   case X86::BI__builtin_ia32_ucmpd128_mask:
1102   case X86::BI__builtin_ia32_ucmpq128_mask:
1103   case X86::BI__builtin_ia32_ucmpb256_mask:
1104   case X86::BI__builtin_ia32_ucmpw256_mask:
1105   case X86::BI__builtin_ia32_ucmpd256_mask:
1106   case X86::BI__builtin_ia32_ucmpq256_mask:
1107   case X86::BI__builtin_ia32_ucmpb512_mask:
1108   case X86::BI__builtin_ia32_ucmpw512_mask:
1109   case X86::BI__builtin_ia32_ucmpd512_mask:
1110   case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
1111   case X86::BI__builtin_ia32_roundps:
1112   case X86::BI__builtin_ia32_roundpd:
1113   case X86::BI__builtin_ia32_roundps256:
1114   case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1115   case X86::BI__builtin_ia32_roundss:
1116   case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1117   case X86::BI__builtin_ia32_cmpps:
1118   case X86::BI__builtin_ia32_cmpss:
1119   case X86::BI__builtin_ia32_cmppd:
1120   case X86::BI__builtin_ia32_cmpsd:
1121   case X86::BI__builtin_ia32_cmpps256:
1122   case X86::BI__builtin_ia32_cmppd256:
1123   case X86::BI__builtin_ia32_cmpps512_mask:
1124   case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
1125   case X86::BI__builtin_ia32_vpcomub:
1126   case X86::BI__builtin_ia32_vpcomuw:
1127   case X86::BI__builtin_ia32_vpcomud:
1128   case X86::BI__builtin_ia32_vpcomuq:
1129   case X86::BI__builtin_ia32_vpcomb:
1130   case X86::BI__builtin_ia32_vpcomw:
1131   case X86::BI__builtin_ia32_vpcomd:
1132   case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
1133   }
1134   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1135 }
1136 
1137 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1138 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
1139 /// Returns true when the format fits the function and the FormatStringInfo has
1140 /// been populated.
1141 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1142                                FormatStringInfo *FSI) {
1143   FSI->HasVAListArg = Format->getFirstArg() == 0;
1144   FSI->FormatIdx = Format->getFormatIdx() - 1;
1145   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1146 
1147   // The way the format attribute works in GCC, the implicit this argument
1148   // of member functions is counted. However, it doesn't appear in our own
1149   // lists, so decrement format_idx in that case.
1150   if (IsCXXMember) {
1151     if(FSI->FormatIdx == 0)
1152       return false;
1153     --FSI->FormatIdx;
1154     if (FSI->FirstDataArg != 0)
1155       --FSI->FirstDataArg;
1156   }
1157   return true;
1158 }
1159 
1160 /// Checks if a the given expression evaluates to null.
1161 ///
1162 /// \brief Returns true if the value evaluates to null.
1163 static bool CheckNonNullExpr(Sema &S,
1164                              const Expr *Expr) {
1165   // If the expression has non-null type, it doesn't evaluate to null.
1166   if (auto nullability
1167         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1168     if (*nullability == NullabilityKind::NonNull)
1169       return false;
1170   }
1171 
1172   // As a special case, transparent unions initialized with zero are
1173   // considered null for the purposes of the nonnull attribute.
1174   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
1175     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1176       if (const CompoundLiteralExpr *CLE =
1177           dyn_cast<CompoundLiteralExpr>(Expr))
1178         if (const InitListExpr *ILE =
1179             dyn_cast<InitListExpr>(CLE->getInitializer()))
1180           Expr = ILE->getInit(0);
1181   }
1182 
1183   bool Result;
1184   return (!Expr->isValueDependent() &&
1185           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1186           !Result);
1187 }
1188 
1189 static void CheckNonNullArgument(Sema &S,
1190                                  const Expr *ArgExpr,
1191                                  SourceLocation CallSiteLoc) {
1192   if (CheckNonNullExpr(S, ArgExpr))
1193     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1194            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
1195 }
1196 
1197 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1198   FormatStringInfo FSI;
1199   if ((GetFormatStringType(Format) == FST_NSString) &&
1200       getFormatStringInfo(Format, false, &FSI)) {
1201     Idx = FSI.FormatIdx;
1202     return true;
1203   }
1204   return false;
1205 }
1206 /// \brief Diagnose use of %s directive in an NSString which is being passed
1207 /// as formatting string to formatting method.
1208 static void
1209 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1210                                         const NamedDecl *FDecl,
1211                                         Expr **Args,
1212                                         unsigned NumArgs) {
1213   unsigned Idx = 0;
1214   bool Format = false;
1215   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1216   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1217     Idx = 2;
1218     Format = true;
1219   }
1220   else
1221     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1222       if (S.GetFormatNSStringIdx(I, Idx)) {
1223         Format = true;
1224         break;
1225       }
1226     }
1227   if (!Format || NumArgs <= Idx)
1228     return;
1229   const Expr *FormatExpr = Args[Idx];
1230   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1231     FormatExpr = CSCE->getSubExpr();
1232   const StringLiteral *FormatString;
1233   if (const ObjCStringLiteral *OSL =
1234       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1235     FormatString = OSL->getString();
1236   else
1237     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1238   if (!FormatString)
1239     return;
1240   if (S.FormatStringHasSArg(FormatString)) {
1241     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1242       << "%s" << 1 << 1;
1243     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1244       << FDecl->getDeclName();
1245   }
1246 }
1247 
1248 /// Determine whether the given type has a non-null nullability annotation.
1249 static bool isNonNullType(ASTContext &ctx, QualType type) {
1250   if (auto nullability = type->getNullability(ctx))
1251     return *nullability == NullabilityKind::NonNull;
1252 
1253   return false;
1254 }
1255 
1256 static void CheckNonNullArguments(Sema &S,
1257                                   const NamedDecl *FDecl,
1258                                   const FunctionProtoType *Proto,
1259                                   ArrayRef<const Expr *> Args,
1260                                   SourceLocation CallSiteLoc) {
1261   assert((FDecl || Proto) && "Need a function declaration or prototype");
1262 
1263   // Check the attributes attached to the method/function itself.
1264   llvm::SmallBitVector NonNullArgs;
1265   if (FDecl) {
1266     // Handle the nonnull attribute on the function/method declaration itself.
1267     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1268       if (!NonNull->args_size()) {
1269         // Easy case: all pointer arguments are nonnull.
1270         for (const auto *Arg : Args)
1271           if (S.isValidPointerAttrType(Arg->getType()))
1272             CheckNonNullArgument(S, Arg, CallSiteLoc);
1273         return;
1274       }
1275 
1276       for (unsigned Val : NonNull->args()) {
1277         if (Val >= Args.size())
1278           continue;
1279         if (NonNullArgs.empty())
1280           NonNullArgs.resize(Args.size());
1281         NonNullArgs.set(Val);
1282       }
1283     }
1284   }
1285 
1286   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1287     // Handle the nonnull attribute on the parameters of the
1288     // function/method.
1289     ArrayRef<ParmVarDecl*> parms;
1290     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1291       parms = FD->parameters();
1292     else
1293       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1294 
1295     unsigned ParamIndex = 0;
1296     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1297          I != E; ++I, ++ParamIndex) {
1298       const ParmVarDecl *PVD = *I;
1299       if (PVD->hasAttr<NonNullAttr>() ||
1300           isNonNullType(S.Context, PVD->getType())) {
1301         if (NonNullArgs.empty())
1302           NonNullArgs.resize(Args.size());
1303 
1304         NonNullArgs.set(ParamIndex);
1305       }
1306     }
1307   } else {
1308     // If we have a non-function, non-method declaration but no
1309     // function prototype, try to dig out the function prototype.
1310     if (!Proto) {
1311       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1312         QualType type = VD->getType().getNonReferenceType();
1313         if (auto pointerType = type->getAs<PointerType>())
1314           type = pointerType->getPointeeType();
1315         else if (auto blockType = type->getAs<BlockPointerType>())
1316           type = blockType->getPointeeType();
1317         // FIXME: data member pointers?
1318 
1319         // Dig out the function prototype, if there is one.
1320         Proto = type->getAs<FunctionProtoType>();
1321       }
1322     }
1323 
1324     // Fill in non-null argument information from the nullability
1325     // information on the parameter types (if we have them).
1326     if (Proto) {
1327       unsigned Index = 0;
1328       for (auto paramType : Proto->getParamTypes()) {
1329         if (isNonNullType(S.Context, paramType)) {
1330           if (NonNullArgs.empty())
1331             NonNullArgs.resize(Args.size());
1332 
1333           NonNullArgs.set(Index);
1334         }
1335 
1336         ++Index;
1337       }
1338     }
1339   }
1340 
1341   // Check for non-null arguments.
1342   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1343        ArgIndex != ArgIndexEnd; ++ArgIndex) {
1344     if (NonNullArgs[ArgIndex])
1345       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1346   }
1347 }
1348 
1349 /// Handles the checks for format strings, non-POD arguments to vararg
1350 /// functions, and NULL arguments passed to non-NULL parameters.
1351 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1352                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
1353                      SourceLocation Loc, SourceRange Range,
1354                      VariadicCallType CallType) {
1355   // FIXME: We should check as much as we can in the template definition.
1356   if (CurContext->isDependentContext())
1357     return;
1358 
1359   // Printf and scanf checking.
1360   llvm::SmallBitVector CheckedVarArgs;
1361   if (FDecl) {
1362     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1363       // Only create vector if there are format attributes.
1364       CheckedVarArgs.resize(Args.size());
1365 
1366       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1367                            CheckedVarArgs);
1368     }
1369   }
1370 
1371   // Refuse POD arguments that weren't caught by the format string
1372   // checks above.
1373   if (CallType != VariadicDoesNotApply) {
1374     unsigned NumParams = Proto ? Proto->getNumParams()
1375                        : FDecl && isa<FunctionDecl>(FDecl)
1376                            ? cast<FunctionDecl>(FDecl)->getNumParams()
1377                        : FDecl && isa<ObjCMethodDecl>(FDecl)
1378                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
1379                        : 0;
1380 
1381     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1382       // Args[ArgIdx] can be null in malformed code.
1383       if (const Expr *Arg = Args[ArgIdx]) {
1384         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1385           checkVariadicArgument(Arg, CallType);
1386       }
1387     }
1388   }
1389 
1390   if (FDecl || Proto) {
1391     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
1392 
1393     // Type safety checking.
1394     if (FDecl) {
1395       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1396         CheckArgumentWithTypeTag(I, Args.data());
1397     }
1398   }
1399 }
1400 
1401 /// CheckConstructorCall - Check a constructor call for correctness and safety
1402 /// properties not enforced by the C type system.
1403 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1404                                 ArrayRef<const Expr *> Args,
1405                                 const FunctionProtoType *Proto,
1406                                 SourceLocation Loc) {
1407   VariadicCallType CallType =
1408     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1409   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1410             CallType);
1411 }
1412 
1413 /// CheckFunctionCall - Check a direct function call for various correctness
1414 /// and safety properties not strictly enforced by the C type system.
1415 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1416                              const FunctionProtoType *Proto) {
1417   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1418                               isa<CXXMethodDecl>(FDecl);
1419   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1420                           IsMemberOperatorCall;
1421   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1422                                                   TheCall->getCallee());
1423   Expr** Args = TheCall->getArgs();
1424   unsigned NumArgs = TheCall->getNumArgs();
1425   if (IsMemberOperatorCall) {
1426     // If this is a call to a member operator, hide the first argument
1427     // from checkCall.
1428     // FIXME: Our choice of AST representation here is less than ideal.
1429     ++Args;
1430     --NumArgs;
1431   }
1432   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
1433             IsMemberFunction, TheCall->getRParenLoc(),
1434             TheCall->getCallee()->getSourceRange(), CallType);
1435 
1436   IdentifierInfo *FnInfo = FDecl->getIdentifier();
1437   // None of the checks below are needed for functions that don't have
1438   // simple names (e.g., C++ conversion functions).
1439   if (!FnInfo)
1440     return false;
1441 
1442   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1443   if (getLangOpts().ObjC1)
1444     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1445 
1446   unsigned CMId = FDecl->getMemoryFunctionKind();
1447   if (CMId == 0)
1448     return false;
1449 
1450   // Handle memory setting and copying functions.
1451   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1452     CheckStrlcpycatArguments(TheCall, FnInfo);
1453   else if (CMId == Builtin::BIstrncat)
1454     CheckStrncatArguments(TheCall, FnInfo);
1455   else
1456     CheckMemaccessArguments(TheCall, CMId, FnInfo);
1457 
1458   return false;
1459 }
1460 
1461 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1462                                ArrayRef<const Expr *> Args) {
1463   VariadicCallType CallType =
1464       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1465 
1466   checkCall(Method, nullptr, Args,
1467             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1468             CallType);
1469 
1470   return false;
1471 }
1472 
1473 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1474                             const FunctionProtoType *Proto) {
1475   QualType Ty;
1476   if (const auto *V = dyn_cast<VarDecl>(NDecl))
1477     Ty = V->getType().getNonReferenceType();
1478   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
1479     Ty = F->getType().getNonReferenceType();
1480   else
1481     return false;
1482 
1483   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1484       !Ty->isFunctionProtoType())
1485     return false;
1486 
1487   VariadicCallType CallType;
1488   if (!Proto || !Proto->isVariadic()) {
1489     CallType = VariadicDoesNotApply;
1490   } else if (Ty->isBlockPointerType()) {
1491     CallType = VariadicBlock;
1492   } else { // Ty->isFunctionPointerType()
1493     CallType = VariadicFunction;
1494   }
1495 
1496   checkCall(NDecl, Proto,
1497             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1498             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1499             TheCall->getCallee()->getSourceRange(), CallType);
1500 
1501   return false;
1502 }
1503 
1504 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1505 /// such as function pointers returned from functions.
1506 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1507   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1508                                                   TheCall->getCallee());
1509   checkCall(/*FDecl=*/nullptr, Proto,
1510             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1511             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1512             TheCall->getCallee()->getSourceRange(), CallType);
1513 
1514   return false;
1515 }
1516 
1517 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1518   if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1519       Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1520     return false;
1521 
1522   switch (Op) {
1523   case AtomicExpr::AO__c11_atomic_init:
1524     llvm_unreachable("There is no ordering argument for an init");
1525 
1526   case AtomicExpr::AO__c11_atomic_load:
1527   case AtomicExpr::AO__atomic_load_n:
1528   case AtomicExpr::AO__atomic_load:
1529     return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1530            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1531 
1532   case AtomicExpr::AO__c11_atomic_store:
1533   case AtomicExpr::AO__atomic_store:
1534   case AtomicExpr::AO__atomic_store_n:
1535     return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1536            Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1537            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1538 
1539   default:
1540     return true;
1541   }
1542 }
1543 
1544 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1545                                          AtomicExpr::AtomicOp Op) {
1546   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1547   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1548 
1549   // All these operations take one of the following forms:
1550   enum {
1551     // C    __c11_atomic_init(A *, C)
1552     Init,
1553     // C    __c11_atomic_load(A *, int)
1554     Load,
1555     // void __atomic_load(A *, CP, int)
1556     Copy,
1557     // C    __c11_atomic_add(A *, M, int)
1558     Arithmetic,
1559     // C    __atomic_exchange_n(A *, CP, int)
1560     Xchg,
1561     // void __atomic_exchange(A *, C *, CP, int)
1562     GNUXchg,
1563     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1564     C11CmpXchg,
1565     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1566     GNUCmpXchg
1567   } Form = Init;
1568   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1569   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1570   // where:
1571   //   C is an appropriate type,
1572   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1573   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1574   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1575   //   the int parameters are for orderings.
1576 
1577   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1578                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1579                         AtomicExpr::AO__atomic_load,
1580                 "need to update code for modified C11 atomics");
1581   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1582                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1583   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1584              Op == AtomicExpr::AO__atomic_store_n ||
1585              Op == AtomicExpr::AO__atomic_exchange_n ||
1586              Op == AtomicExpr::AO__atomic_compare_exchange_n;
1587   bool IsAddSub = false;
1588 
1589   switch (Op) {
1590   case AtomicExpr::AO__c11_atomic_init:
1591     Form = Init;
1592     break;
1593 
1594   case AtomicExpr::AO__c11_atomic_load:
1595   case AtomicExpr::AO__atomic_load_n:
1596     Form = Load;
1597     break;
1598 
1599   case AtomicExpr::AO__c11_atomic_store:
1600   case AtomicExpr::AO__atomic_load:
1601   case AtomicExpr::AO__atomic_store:
1602   case AtomicExpr::AO__atomic_store_n:
1603     Form = Copy;
1604     break;
1605 
1606   case AtomicExpr::AO__c11_atomic_fetch_add:
1607   case AtomicExpr::AO__c11_atomic_fetch_sub:
1608   case AtomicExpr::AO__atomic_fetch_add:
1609   case AtomicExpr::AO__atomic_fetch_sub:
1610   case AtomicExpr::AO__atomic_add_fetch:
1611   case AtomicExpr::AO__atomic_sub_fetch:
1612     IsAddSub = true;
1613     // Fall through.
1614   case AtomicExpr::AO__c11_atomic_fetch_and:
1615   case AtomicExpr::AO__c11_atomic_fetch_or:
1616   case AtomicExpr::AO__c11_atomic_fetch_xor:
1617   case AtomicExpr::AO__atomic_fetch_and:
1618   case AtomicExpr::AO__atomic_fetch_or:
1619   case AtomicExpr::AO__atomic_fetch_xor:
1620   case AtomicExpr::AO__atomic_fetch_nand:
1621   case AtomicExpr::AO__atomic_and_fetch:
1622   case AtomicExpr::AO__atomic_or_fetch:
1623   case AtomicExpr::AO__atomic_xor_fetch:
1624   case AtomicExpr::AO__atomic_nand_fetch:
1625     Form = Arithmetic;
1626     break;
1627 
1628   case AtomicExpr::AO__c11_atomic_exchange:
1629   case AtomicExpr::AO__atomic_exchange_n:
1630     Form = Xchg;
1631     break;
1632 
1633   case AtomicExpr::AO__atomic_exchange:
1634     Form = GNUXchg;
1635     break;
1636 
1637   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1638   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1639     Form = C11CmpXchg;
1640     break;
1641 
1642   case AtomicExpr::AO__atomic_compare_exchange:
1643   case AtomicExpr::AO__atomic_compare_exchange_n:
1644     Form = GNUCmpXchg;
1645     break;
1646   }
1647 
1648   // Check we have the right number of arguments.
1649   if (TheCall->getNumArgs() < NumArgs[Form]) {
1650     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1651       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1652       << TheCall->getCallee()->getSourceRange();
1653     return ExprError();
1654   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1655     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1656          diag::err_typecheck_call_too_many_args)
1657       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1658       << TheCall->getCallee()->getSourceRange();
1659     return ExprError();
1660   }
1661 
1662   // Inspect the first argument of the atomic operation.
1663   Expr *Ptr = TheCall->getArg(0);
1664   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1665   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1666   if (!pointerType) {
1667     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1668       << Ptr->getType() << Ptr->getSourceRange();
1669     return ExprError();
1670   }
1671 
1672   // For a __c11 builtin, this should be a pointer to an _Atomic type.
1673   QualType AtomTy = pointerType->getPointeeType(); // 'A'
1674   QualType ValType = AtomTy; // 'C'
1675   if (IsC11) {
1676     if (!AtomTy->isAtomicType()) {
1677       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1678         << Ptr->getType() << Ptr->getSourceRange();
1679       return ExprError();
1680     }
1681     if (AtomTy.isConstQualified()) {
1682       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1683         << Ptr->getType() << Ptr->getSourceRange();
1684       return ExprError();
1685     }
1686     ValType = AtomTy->getAs<AtomicType>()->getValueType();
1687   } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1688     if (ValType.isConstQualified()) {
1689       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1690         << Ptr->getType() << Ptr->getSourceRange();
1691       return ExprError();
1692     }
1693   }
1694 
1695   // For an arithmetic operation, the implied arithmetic must be well-formed.
1696   if (Form == Arithmetic) {
1697     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1698     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1699       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1700         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1701       return ExprError();
1702     }
1703     if (!IsAddSub && !ValType->isIntegerType()) {
1704       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1705         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1706       return ExprError();
1707     }
1708     if (IsC11 && ValType->isPointerType() &&
1709         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1710                             diag::err_incomplete_type)) {
1711       return ExprError();
1712     }
1713   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1714     // For __atomic_*_n operations, the value type must be a scalar integral or
1715     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1716     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1717       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1718     return ExprError();
1719   }
1720 
1721   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1722       !AtomTy->isScalarType()) {
1723     // For GNU atomics, require a trivially-copyable type. This is not part of
1724     // the GNU atomics specification, but we enforce it for sanity.
1725     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1726       << Ptr->getType() << Ptr->getSourceRange();
1727     return ExprError();
1728   }
1729 
1730   switch (ValType.getObjCLifetime()) {
1731   case Qualifiers::OCL_None:
1732   case Qualifiers::OCL_ExplicitNone:
1733     // okay
1734     break;
1735 
1736   case Qualifiers::OCL_Weak:
1737   case Qualifiers::OCL_Strong:
1738   case Qualifiers::OCL_Autoreleasing:
1739     // FIXME: Can this happen? By this point, ValType should be known
1740     // to be trivially copyable.
1741     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1742       << ValType << Ptr->getSourceRange();
1743     return ExprError();
1744   }
1745 
1746   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
1747   // volatile-ness of the pointee-type inject itself into the result or the
1748   // other operands.
1749   ValType.removeLocalVolatile();
1750   QualType ResultType = ValType;
1751   if (Form == Copy || Form == GNUXchg || Form == Init)
1752     ResultType = Context.VoidTy;
1753   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1754     ResultType = Context.BoolTy;
1755 
1756   // The type of a parameter passed 'by value'. In the GNU atomics, such
1757   // arguments are actually passed as pointers.
1758   QualType ByValType = ValType; // 'CP'
1759   if (!IsC11 && !IsN)
1760     ByValType = Ptr->getType();
1761 
1762   // FIXME: __atomic_load allows the first argument to be a a pointer to const
1763   // but not the second argument. We need to manually remove possible const
1764   // qualifiers.
1765 
1766   // The first argument --- the pointer --- has a fixed type; we
1767   // deduce the types of the rest of the arguments accordingly.  Walk
1768   // the remaining arguments, converting them to the deduced value type.
1769   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1770     QualType Ty;
1771     if (i < NumVals[Form] + 1) {
1772       switch (i) {
1773       case 1:
1774         // The second argument is the non-atomic operand. For arithmetic, this
1775         // is always passed by value, and for a compare_exchange it is always
1776         // passed by address. For the rest, GNU uses by-address and C11 uses
1777         // by-value.
1778         assert(Form != Load);
1779         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1780           Ty = ValType;
1781         else if (Form == Copy || Form == Xchg)
1782           Ty = ByValType;
1783         else if (Form == Arithmetic)
1784           Ty = Context.getPointerDiffType();
1785         else
1786           Ty = Context.getPointerType(ValType.getUnqualifiedType());
1787         break;
1788       case 2:
1789         // The third argument to compare_exchange / GNU exchange is a
1790         // (pointer to a) desired value.
1791         Ty = ByValType;
1792         break;
1793       case 3:
1794         // The fourth argument to GNU compare_exchange is a 'weak' flag.
1795         Ty = Context.BoolTy;
1796         break;
1797       }
1798     } else {
1799       // The order(s) are always converted to int.
1800       Ty = Context.IntTy;
1801     }
1802 
1803     InitializedEntity Entity =
1804         InitializedEntity::InitializeParameter(Context, Ty, false);
1805     ExprResult Arg = TheCall->getArg(i);
1806     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1807     if (Arg.isInvalid())
1808       return true;
1809     TheCall->setArg(i, Arg.get());
1810   }
1811 
1812   // Permute the arguments into a 'consistent' order.
1813   SmallVector<Expr*, 5> SubExprs;
1814   SubExprs.push_back(Ptr);
1815   switch (Form) {
1816   case Init:
1817     // Note, AtomicExpr::getVal1() has a special case for this atomic.
1818     SubExprs.push_back(TheCall->getArg(1)); // Val1
1819     break;
1820   case Load:
1821     SubExprs.push_back(TheCall->getArg(1)); // Order
1822     break;
1823   case Copy:
1824   case Arithmetic:
1825   case Xchg:
1826     SubExprs.push_back(TheCall->getArg(2)); // Order
1827     SubExprs.push_back(TheCall->getArg(1)); // Val1
1828     break;
1829   case GNUXchg:
1830     // Note, AtomicExpr::getVal2() has a special case for this atomic.
1831     SubExprs.push_back(TheCall->getArg(3)); // Order
1832     SubExprs.push_back(TheCall->getArg(1)); // Val1
1833     SubExprs.push_back(TheCall->getArg(2)); // Val2
1834     break;
1835   case C11CmpXchg:
1836     SubExprs.push_back(TheCall->getArg(3)); // Order
1837     SubExprs.push_back(TheCall->getArg(1)); // Val1
1838     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1839     SubExprs.push_back(TheCall->getArg(2)); // Val2
1840     break;
1841   case GNUCmpXchg:
1842     SubExprs.push_back(TheCall->getArg(4)); // Order
1843     SubExprs.push_back(TheCall->getArg(1)); // Val1
1844     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1845     SubExprs.push_back(TheCall->getArg(2)); // Val2
1846     SubExprs.push_back(TheCall->getArg(3)); // Weak
1847     break;
1848   }
1849 
1850   if (SubExprs.size() >= 2 && Form != Init) {
1851     llvm::APSInt Result(32);
1852     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1853         !isValidOrderingForOp(Result.getSExtValue(), Op))
1854       Diag(SubExprs[1]->getLocStart(),
1855            diag::warn_atomic_op_has_invalid_memory_order)
1856           << SubExprs[1]->getSourceRange();
1857   }
1858 
1859   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1860                                             SubExprs, ResultType, Op,
1861                                             TheCall->getRParenLoc());
1862 
1863   if ((Op == AtomicExpr::AO__c11_atomic_load ||
1864        (Op == AtomicExpr::AO__c11_atomic_store)) &&
1865       Context.AtomicUsesUnsupportedLibcall(AE))
1866     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1867     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1868 
1869   return AE;
1870 }
1871 
1872 
1873 /// checkBuiltinArgument - Given a call to a builtin function, perform
1874 /// normal type-checking on the given argument, updating the call in
1875 /// place.  This is useful when a builtin function requires custom
1876 /// type-checking for some of its arguments but not necessarily all of
1877 /// them.
1878 ///
1879 /// Returns true on error.
1880 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1881   FunctionDecl *Fn = E->getDirectCallee();
1882   assert(Fn && "builtin call without direct callee!");
1883 
1884   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1885   InitializedEntity Entity =
1886     InitializedEntity::InitializeParameter(S.Context, Param);
1887 
1888   ExprResult Arg = E->getArg(0);
1889   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1890   if (Arg.isInvalid())
1891     return true;
1892 
1893   E->setArg(ArgIndex, Arg.get());
1894   return false;
1895 }
1896 
1897 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1898 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1899 /// type of its first argument.  The main ActOnCallExpr routines have already
1900 /// promoted the types of arguments because all of these calls are prototyped as
1901 /// void(...).
1902 ///
1903 /// This function goes through and does final semantic checking for these
1904 /// builtins,
1905 ExprResult
1906 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1907   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1908   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1909   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1910 
1911   // Ensure that we have at least one argument to do type inference from.
1912   if (TheCall->getNumArgs() < 1) {
1913     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1914       << 0 << 1 << TheCall->getNumArgs()
1915       << TheCall->getCallee()->getSourceRange();
1916     return ExprError();
1917   }
1918 
1919   // Inspect the first argument of the atomic builtin.  This should always be
1920   // a pointer type, whose element is an integral scalar or pointer type.
1921   // Because it is a pointer type, we don't have to worry about any implicit
1922   // casts here.
1923   // FIXME: We don't allow floating point scalars as input.
1924   Expr *FirstArg = TheCall->getArg(0);
1925   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1926   if (FirstArgResult.isInvalid())
1927     return ExprError();
1928   FirstArg = FirstArgResult.get();
1929   TheCall->setArg(0, FirstArg);
1930 
1931   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1932   if (!pointerType) {
1933     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1934       << FirstArg->getType() << FirstArg->getSourceRange();
1935     return ExprError();
1936   }
1937 
1938   QualType ValType = pointerType->getPointeeType();
1939   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1940       !ValType->isBlockPointerType()) {
1941     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1942       << FirstArg->getType() << FirstArg->getSourceRange();
1943     return ExprError();
1944   }
1945 
1946   switch (ValType.getObjCLifetime()) {
1947   case Qualifiers::OCL_None:
1948   case Qualifiers::OCL_ExplicitNone:
1949     // okay
1950     break;
1951 
1952   case Qualifiers::OCL_Weak:
1953   case Qualifiers::OCL_Strong:
1954   case Qualifiers::OCL_Autoreleasing:
1955     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1956       << ValType << FirstArg->getSourceRange();
1957     return ExprError();
1958   }
1959 
1960   // Strip any qualifiers off ValType.
1961   ValType = ValType.getUnqualifiedType();
1962 
1963   // The majority of builtins return a value, but a few have special return
1964   // types, so allow them to override appropriately below.
1965   QualType ResultType = ValType;
1966 
1967   // We need to figure out which concrete builtin this maps onto.  For example,
1968   // __sync_fetch_and_add with a 2 byte object turns into
1969   // __sync_fetch_and_add_2.
1970 #define BUILTIN_ROW(x) \
1971   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1972     Builtin::BI##x##_8, Builtin::BI##x##_16 }
1973 
1974   static const unsigned BuiltinIndices[][5] = {
1975     BUILTIN_ROW(__sync_fetch_and_add),
1976     BUILTIN_ROW(__sync_fetch_and_sub),
1977     BUILTIN_ROW(__sync_fetch_and_or),
1978     BUILTIN_ROW(__sync_fetch_and_and),
1979     BUILTIN_ROW(__sync_fetch_and_xor),
1980     BUILTIN_ROW(__sync_fetch_and_nand),
1981 
1982     BUILTIN_ROW(__sync_add_and_fetch),
1983     BUILTIN_ROW(__sync_sub_and_fetch),
1984     BUILTIN_ROW(__sync_and_and_fetch),
1985     BUILTIN_ROW(__sync_or_and_fetch),
1986     BUILTIN_ROW(__sync_xor_and_fetch),
1987     BUILTIN_ROW(__sync_nand_and_fetch),
1988 
1989     BUILTIN_ROW(__sync_val_compare_and_swap),
1990     BUILTIN_ROW(__sync_bool_compare_and_swap),
1991     BUILTIN_ROW(__sync_lock_test_and_set),
1992     BUILTIN_ROW(__sync_lock_release),
1993     BUILTIN_ROW(__sync_swap)
1994   };
1995 #undef BUILTIN_ROW
1996 
1997   // Determine the index of the size.
1998   unsigned SizeIndex;
1999   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
2000   case 1: SizeIndex = 0; break;
2001   case 2: SizeIndex = 1; break;
2002   case 4: SizeIndex = 2; break;
2003   case 8: SizeIndex = 3; break;
2004   case 16: SizeIndex = 4; break;
2005   default:
2006     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2007       << FirstArg->getType() << FirstArg->getSourceRange();
2008     return ExprError();
2009   }
2010 
2011   // Each of these builtins has one pointer argument, followed by some number of
2012   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2013   // that we ignore.  Find out which row of BuiltinIndices to read from as well
2014   // as the number of fixed args.
2015   unsigned BuiltinID = FDecl->getBuiltinID();
2016   unsigned BuiltinIndex, NumFixed = 1;
2017   bool WarnAboutSemanticsChange = false;
2018   switch (BuiltinID) {
2019   default: llvm_unreachable("Unknown overloaded atomic builtin!");
2020   case Builtin::BI__sync_fetch_and_add:
2021   case Builtin::BI__sync_fetch_and_add_1:
2022   case Builtin::BI__sync_fetch_and_add_2:
2023   case Builtin::BI__sync_fetch_and_add_4:
2024   case Builtin::BI__sync_fetch_and_add_8:
2025   case Builtin::BI__sync_fetch_and_add_16:
2026     BuiltinIndex = 0;
2027     break;
2028 
2029   case Builtin::BI__sync_fetch_and_sub:
2030   case Builtin::BI__sync_fetch_and_sub_1:
2031   case Builtin::BI__sync_fetch_and_sub_2:
2032   case Builtin::BI__sync_fetch_and_sub_4:
2033   case Builtin::BI__sync_fetch_and_sub_8:
2034   case Builtin::BI__sync_fetch_and_sub_16:
2035     BuiltinIndex = 1;
2036     break;
2037 
2038   case Builtin::BI__sync_fetch_and_or:
2039   case Builtin::BI__sync_fetch_and_or_1:
2040   case Builtin::BI__sync_fetch_and_or_2:
2041   case Builtin::BI__sync_fetch_and_or_4:
2042   case Builtin::BI__sync_fetch_and_or_8:
2043   case Builtin::BI__sync_fetch_and_or_16:
2044     BuiltinIndex = 2;
2045     break;
2046 
2047   case Builtin::BI__sync_fetch_and_and:
2048   case Builtin::BI__sync_fetch_and_and_1:
2049   case Builtin::BI__sync_fetch_and_and_2:
2050   case Builtin::BI__sync_fetch_and_and_4:
2051   case Builtin::BI__sync_fetch_and_and_8:
2052   case Builtin::BI__sync_fetch_and_and_16:
2053     BuiltinIndex = 3;
2054     break;
2055 
2056   case Builtin::BI__sync_fetch_and_xor:
2057   case Builtin::BI__sync_fetch_and_xor_1:
2058   case Builtin::BI__sync_fetch_and_xor_2:
2059   case Builtin::BI__sync_fetch_and_xor_4:
2060   case Builtin::BI__sync_fetch_and_xor_8:
2061   case Builtin::BI__sync_fetch_and_xor_16:
2062     BuiltinIndex = 4;
2063     break;
2064 
2065   case Builtin::BI__sync_fetch_and_nand:
2066   case Builtin::BI__sync_fetch_and_nand_1:
2067   case Builtin::BI__sync_fetch_and_nand_2:
2068   case Builtin::BI__sync_fetch_and_nand_4:
2069   case Builtin::BI__sync_fetch_and_nand_8:
2070   case Builtin::BI__sync_fetch_and_nand_16:
2071     BuiltinIndex = 5;
2072     WarnAboutSemanticsChange = true;
2073     break;
2074 
2075   case Builtin::BI__sync_add_and_fetch:
2076   case Builtin::BI__sync_add_and_fetch_1:
2077   case Builtin::BI__sync_add_and_fetch_2:
2078   case Builtin::BI__sync_add_and_fetch_4:
2079   case Builtin::BI__sync_add_and_fetch_8:
2080   case Builtin::BI__sync_add_and_fetch_16:
2081     BuiltinIndex = 6;
2082     break;
2083 
2084   case Builtin::BI__sync_sub_and_fetch:
2085   case Builtin::BI__sync_sub_and_fetch_1:
2086   case Builtin::BI__sync_sub_and_fetch_2:
2087   case Builtin::BI__sync_sub_and_fetch_4:
2088   case Builtin::BI__sync_sub_and_fetch_8:
2089   case Builtin::BI__sync_sub_and_fetch_16:
2090     BuiltinIndex = 7;
2091     break;
2092 
2093   case Builtin::BI__sync_and_and_fetch:
2094   case Builtin::BI__sync_and_and_fetch_1:
2095   case Builtin::BI__sync_and_and_fetch_2:
2096   case Builtin::BI__sync_and_and_fetch_4:
2097   case Builtin::BI__sync_and_and_fetch_8:
2098   case Builtin::BI__sync_and_and_fetch_16:
2099     BuiltinIndex = 8;
2100     break;
2101 
2102   case Builtin::BI__sync_or_and_fetch:
2103   case Builtin::BI__sync_or_and_fetch_1:
2104   case Builtin::BI__sync_or_and_fetch_2:
2105   case Builtin::BI__sync_or_and_fetch_4:
2106   case Builtin::BI__sync_or_and_fetch_8:
2107   case Builtin::BI__sync_or_and_fetch_16:
2108     BuiltinIndex = 9;
2109     break;
2110 
2111   case Builtin::BI__sync_xor_and_fetch:
2112   case Builtin::BI__sync_xor_and_fetch_1:
2113   case Builtin::BI__sync_xor_and_fetch_2:
2114   case Builtin::BI__sync_xor_and_fetch_4:
2115   case Builtin::BI__sync_xor_and_fetch_8:
2116   case Builtin::BI__sync_xor_and_fetch_16:
2117     BuiltinIndex = 10;
2118     break;
2119 
2120   case Builtin::BI__sync_nand_and_fetch:
2121   case Builtin::BI__sync_nand_and_fetch_1:
2122   case Builtin::BI__sync_nand_and_fetch_2:
2123   case Builtin::BI__sync_nand_and_fetch_4:
2124   case Builtin::BI__sync_nand_and_fetch_8:
2125   case Builtin::BI__sync_nand_and_fetch_16:
2126     BuiltinIndex = 11;
2127     WarnAboutSemanticsChange = true;
2128     break;
2129 
2130   case Builtin::BI__sync_val_compare_and_swap:
2131   case Builtin::BI__sync_val_compare_and_swap_1:
2132   case Builtin::BI__sync_val_compare_and_swap_2:
2133   case Builtin::BI__sync_val_compare_and_swap_4:
2134   case Builtin::BI__sync_val_compare_and_swap_8:
2135   case Builtin::BI__sync_val_compare_and_swap_16:
2136     BuiltinIndex = 12;
2137     NumFixed = 2;
2138     break;
2139 
2140   case Builtin::BI__sync_bool_compare_and_swap:
2141   case Builtin::BI__sync_bool_compare_and_swap_1:
2142   case Builtin::BI__sync_bool_compare_and_swap_2:
2143   case Builtin::BI__sync_bool_compare_and_swap_4:
2144   case Builtin::BI__sync_bool_compare_and_swap_8:
2145   case Builtin::BI__sync_bool_compare_and_swap_16:
2146     BuiltinIndex = 13;
2147     NumFixed = 2;
2148     ResultType = Context.BoolTy;
2149     break;
2150 
2151   case Builtin::BI__sync_lock_test_and_set:
2152   case Builtin::BI__sync_lock_test_and_set_1:
2153   case Builtin::BI__sync_lock_test_and_set_2:
2154   case Builtin::BI__sync_lock_test_and_set_4:
2155   case Builtin::BI__sync_lock_test_and_set_8:
2156   case Builtin::BI__sync_lock_test_and_set_16:
2157     BuiltinIndex = 14;
2158     break;
2159 
2160   case Builtin::BI__sync_lock_release:
2161   case Builtin::BI__sync_lock_release_1:
2162   case Builtin::BI__sync_lock_release_2:
2163   case Builtin::BI__sync_lock_release_4:
2164   case Builtin::BI__sync_lock_release_8:
2165   case Builtin::BI__sync_lock_release_16:
2166     BuiltinIndex = 15;
2167     NumFixed = 0;
2168     ResultType = Context.VoidTy;
2169     break;
2170 
2171   case Builtin::BI__sync_swap:
2172   case Builtin::BI__sync_swap_1:
2173   case Builtin::BI__sync_swap_2:
2174   case Builtin::BI__sync_swap_4:
2175   case Builtin::BI__sync_swap_8:
2176   case Builtin::BI__sync_swap_16:
2177     BuiltinIndex = 16;
2178     break;
2179   }
2180 
2181   // Now that we know how many fixed arguments we expect, first check that we
2182   // have at least that many.
2183   if (TheCall->getNumArgs() < 1+NumFixed) {
2184     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2185       << 0 << 1+NumFixed << TheCall->getNumArgs()
2186       << TheCall->getCallee()->getSourceRange();
2187     return ExprError();
2188   }
2189 
2190   if (WarnAboutSemanticsChange) {
2191     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2192       << TheCall->getCallee()->getSourceRange();
2193   }
2194 
2195   // Get the decl for the concrete builtin from this, we can tell what the
2196   // concrete integer type we should convert to is.
2197   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2198   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
2199   FunctionDecl *NewBuiltinDecl;
2200   if (NewBuiltinID == BuiltinID)
2201     NewBuiltinDecl = FDecl;
2202   else {
2203     // Perform builtin lookup to avoid redeclaring it.
2204     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2205     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2206     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2207     assert(Res.getFoundDecl());
2208     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
2209     if (!NewBuiltinDecl)
2210       return ExprError();
2211   }
2212 
2213   // The first argument --- the pointer --- has a fixed type; we
2214   // deduce the types of the rest of the arguments accordingly.  Walk
2215   // the remaining arguments, converting them to the deduced value type.
2216   for (unsigned i = 0; i != NumFixed; ++i) {
2217     ExprResult Arg = TheCall->getArg(i+1);
2218 
2219     // GCC does an implicit conversion to the pointer or integer ValType.  This
2220     // can fail in some cases (1i -> int**), check for this error case now.
2221     // Initialize the argument.
2222     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2223                                                    ValType, /*consume*/ false);
2224     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2225     if (Arg.isInvalid())
2226       return ExprError();
2227 
2228     // Okay, we have something that *can* be converted to the right type.  Check
2229     // to see if there is a potentially weird extension going on here.  This can
2230     // happen when you do an atomic operation on something like an char* and
2231     // pass in 42.  The 42 gets converted to char.  This is even more strange
2232     // for things like 45.123 -> char, etc.
2233     // FIXME: Do this check.
2234     TheCall->setArg(i+1, Arg.get());
2235   }
2236 
2237   ASTContext& Context = this->getASTContext();
2238 
2239   // Create a new DeclRefExpr to refer to the new decl.
2240   DeclRefExpr* NewDRE = DeclRefExpr::Create(
2241       Context,
2242       DRE->getQualifierLoc(),
2243       SourceLocation(),
2244       NewBuiltinDecl,
2245       /*enclosing*/ false,
2246       DRE->getLocation(),
2247       Context.BuiltinFnTy,
2248       DRE->getValueKind());
2249 
2250   // Set the callee in the CallExpr.
2251   // FIXME: This loses syntactic information.
2252   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2253   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2254                                               CK_BuiltinFnToFnPtr);
2255   TheCall->setCallee(PromotedCall.get());
2256 
2257   // Change the result type of the call to match the original value type. This
2258   // is arbitrary, but the codegen for these builtins ins design to handle it
2259   // gracefully.
2260   TheCall->setType(ResultType);
2261 
2262   return TheCallResult;
2263 }
2264 
2265 /// SemaBuiltinNontemporalOverloaded - We have a call to
2266 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2267 /// overloaded function based on the pointer type of its last argument.
2268 ///
2269 /// This function goes through and does final semantic checking for these
2270 /// builtins.
2271 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2272   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2273   DeclRefExpr *DRE =
2274       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2275   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2276   unsigned BuiltinID = FDecl->getBuiltinID();
2277   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2278           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2279          "Unexpected nontemporal load/store builtin!");
2280   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2281   unsigned numArgs = isStore ? 2 : 1;
2282 
2283   // Ensure that we have the proper number of arguments.
2284   if (checkArgCount(*this, TheCall, numArgs))
2285     return ExprError();
2286 
2287   // Inspect the last argument of the nontemporal builtin.  This should always
2288   // be a pointer type, from which we imply the type of the memory access.
2289   // Because it is a pointer type, we don't have to worry about any implicit
2290   // casts here.
2291   Expr *PointerArg = TheCall->getArg(numArgs - 1);
2292   ExprResult PointerArgResult =
2293       DefaultFunctionArrayLvalueConversion(PointerArg);
2294 
2295   if (PointerArgResult.isInvalid())
2296     return ExprError();
2297   PointerArg = PointerArgResult.get();
2298   TheCall->setArg(numArgs - 1, PointerArg);
2299 
2300   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2301   if (!pointerType) {
2302     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2303         << PointerArg->getType() << PointerArg->getSourceRange();
2304     return ExprError();
2305   }
2306 
2307   QualType ValType = pointerType->getPointeeType();
2308 
2309   // Strip any qualifiers off ValType.
2310   ValType = ValType.getUnqualifiedType();
2311   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2312       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2313       !ValType->isVectorType()) {
2314     Diag(DRE->getLocStart(),
2315          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2316         << PointerArg->getType() << PointerArg->getSourceRange();
2317     return ExprError();
2318   }
2319 
2320   if (!isStore) {
2321     TheCall->setType(ValType);
2322     return TheCallResult;
2323   }
2324 
2325   ExprResult ValArg = TheCall->getArg(0);
2326   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2327       Context, ValType, /*consume*/ false);
2328   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2329   if (ValArg.isInvalid())
2330     return ExprError();
2331 
2332   TheCall->setArg(0, ValArg.get());
2333   TheCall->setType(Context.VoidTy);
2334   return TheCallResult;
2335 }
2336 
2337 /// CheckObjCString - Checks that the argument to the builtin
2338 /// CFString constructor is correct
2339 /// Note: It might also make sense to do the UTF-16 conversion here (would
2340 /// simplify the backend).
2341 bool Sema::CheckObjCString(Expr *Arg) {
2342   Arg = Arg->IgnoreParenCasts();
2343   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2344 
2345   if (!Literal || !Literal->isAscii()) {
2346     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2347       << Arg->getSourceRange();
2348     return true;
2349   }
2350 
2351   if (Literal->containsNonAsciiOrNull()) {
2352     StringRef String = Literal->getString();
2353     unsigned NumBytes = String.size();
2354     SmallVector<UTF16, 128> ToBuf(NumBytes);
2355     const UTF8 *FromPtr = (const UTF8 *)String.data();
2356     UTF16 *ToPtr = &ToBuf[0];
2357 
2358     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2359                                                  &ToPtr, ToPtr + NumBytes,
2360                                                  strictConversion);
2361     // Check for conversion failure.
2362     if (Result != conversionOK)
2363       Diag(Arg->getLocStart(),
2364            diag::warn_cfstring_truncated) << Arg->getSourceRange();
2365   }
2366   return false;
2367 }
2368 
2369 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2370 /// for validity.  Emit an error and return true on failure; return false
2371 /// on success.
2372 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
2373   Expr *Fn = TheCall->getCallee();
2374   if (TheCall->getNumArgs() > 2) {
2375     Diag(TheCall->getArg(2)->getLocStart(),
2376          diag::err_typecheck_call_too_many_args)
2377       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2378       << Fn->getSourceRange()
2379       << SourceRange(TheCall->getArg(2)->getLocStart(),
2380                      (*(TheCall->arg_end()-1))->getLocEnd());
2381     return true;
2382   }
2383 
2384   if (TheCall->getNumArgs() < 2) {
2385     return Diag(TheCall->getLocEnd(),
2386       diag::err_typecheck_call_too_few_args_at_least)
2387       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
2388   }
2389 
2390   // Type-check the first argument normally.
2391   if (checkBuiltinArgument(*this, TheCall, 0))
2392     return true;
2393 
2394   // Determine whether the current function is variadic or not.
2395   BlockScopeInfo *CurBlock = getCurBlock();
2396   bool isVariadic;
2397   if (CurBlock)
2398     isVariadic = CurBlock->TheDecl->isVariadic();
2399   else if (FunctionDecl *FD = getCurFunctionDecl())
2400     isVariadic = FD->isVariadic();
2401   else
2402     isVariadic = getCurMethodDecl()->isVariadic();
2403 
2404   if (!isVariadic) {
2405     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2406     return true;
2407   }
2408 
2409   // Verify that the second argument to the builtin is the last argument of the
2410   // current function or method.
2411   bool SecondArgIsLastNamedArgument = false;
2412   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
2413 
2414   // These are valid if SecondArgIsLastNamedArgument is false after the next
2415   // block.
2416   QualType Type;
2417   SourceLocation ParamLoc;
2418 
2419   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2420     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2421       // FIXME: This isn't correct for methods (results in bogus warning).
2422       // Get the last formal in the current function.
2423       const ParmVarDecl *LastArg;
2424       if (CurBlock)
2425         LastArg = *(CurBlock->TheDecl->param_end()-1);
2426       else if (FunctionDecl *FD = getCurFunctionDecl())
2427         LastArg = *(FD->param_end()-1);
2428       else
2429         LastArg = *(getCurMethodDecl()->param_end()-1);
2430       SecondArgIsLastNamedArgument = PV == LastArg;
2431 
2432       Type = PV->getType();
2433       ParamLoc = PV->getLocation();
2434     }
2435   }
2436 
2437   if (!SecondArgIsLastNamedArgument)
2438     Diag(TheCall->getArg(1)->getLocStart(),
2439          diag::warn_second_parameter_of_va_start_not_last_named_argument);
2440   else if (Type->isReferenceType()) {
2441     Diag(Arg->getLocStart(),
2442          diag::warn_va_start_of_reference_type_is_undefined);
2443     Diag(ParamLoc, diag::note_parameter_type) << Type;
2444   }
2445 
2446   TheCall->setType(Context.VoidTy);
2447   return false;
2448 }
2449 
2450 /// Check the arguments to '__builtin_va_start' for validity, and that
2451 /// it was called from a function of the native ABI.
2452 /// Emit an error and return true on failure; return false on success.
2453 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2454   // On x86-64 Unix, don't allow this in Win64 ABI functions.
2455   // On x64 Windows, don't allow this in System V ABI functions.
2456   // (Yes, that means there's no corresponding way to support variadic
2457   // System V ABI functions on Windows.)
2458   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2459     unsigned OS = Context.getTargetInfo().getTriple().getOS();
2460     clang::CallingConv CC = CC_C;
2461     if (const FunctionDecl *FD = getCurFunctionDecl())
2462       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2463     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2464         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2465       return Diag(TheCall->getCallee()->getLocStart(),
2466                   diag::err_va_start_used_in_wrong_abi_function)
2467              << (OS != llvm::Triple::Win32);
2468   }
2469   return SemaBuiltinVAStartImpl(TheCall);
2470 }
2471 
2472 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
2473 /// it was called from a Win64 ABI function.
2474 /// Emit an error and return true on failure; return false on success.
2475 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2476   // This only makes sense for x86-64.
2477   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2478   Expr *Callee = TheCall->getCallee();
2479   if (TT.getArch() != llvm::Triple::x86_64)
2480     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2481   // Don't allow this in System V ABI functions.
2482   clang::CallingConv CC = CC_C;
2483   if (const FunctionDecl *FD = getCurFunctionDecl())
2484     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2485   if (CC == CC_X86_64SysV ||
2486       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2487     return Diag(Callee->getLocStart(),
2488                 diag::err_ms_va_start_used_in_sysv_function);
2489   return SemaBuiltinVAStartImpl(TheCall);
2490 }
2491 
2492 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2493   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2494   //                 const char *named_addr);
2495 
2496   Expr *Func = Call->getCallee();
2497 
2498   if (Call->getNumArgs() < 3)
2499     return Diag(Call->getLocEnd(),
2500                 diag::err_typecheck_call_too_few_args_at_least)
2501            << 0 /*function call*/ << 3 << Call->getNumArgs();
2502 
2503   // Determine whether the current function is variadic or not.
2504   bool IsVariadic;
2505   if (BlockScopeInfo *CurBlock = getCurBlock())
2506     IsVariadic = CurBlock->TheDecl->isVariadic();
2507   else if (FunctionDecl *FD = getCurFunctionDecl())
2508     IsVariadic = FD->isVariadic();
2509   else if (ObjCMethodDecl *MD = getCurMethodDecl())
2510     IsVariadic = MD->isVariadic();
2511   else
2512     llvm_unreachable("unexpected statement type");
2513 
2514   if (!IsVariadic) {
2515     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2516     return true;
2517   }
2518 
2519   // Type-check the first argument normally.
2520   if (checkBuiltinArgument(*this, Call, 0))
2521     return true;
2522 
2523   const struct {
2524     unsigned ArgNo;
2525     QualType Type;
2526   } ArgumentTypes[] = {
2527     { 1, Context.getPointerType(Context.CharTy.withConst()) },
2528     { 2, Context.getSizeType() },
2529   };
2530 
2531   for (const auto &AT : ArgumentTypes) {
2532     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2533     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2534       continue;
2535     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2536       << Arg->getType() << AT.Type << 1 /* different class */
2537       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2538       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2539   }
2540 
2541   return false;
2542 }
2543 
2544 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2545 /// friends.  This is declared to take (...), so we have to check everything.
2546 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2547   if (TheCall->getNumArgs() < 2)
2548     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2549       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2550   if (TheCall->getNumArgs() > 2)
2551     return Diag(TheCall->getArg(2)->getLocStart(),
2552                 diag::err_typecheck_call_too_many_args)
2553       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2554       << SourceRange(TheCall->getArg(2)->getLocStart(),
2555                      (*(TheCall->arg_end()-1))->getLocEnd());
2556 
2557   ExprResult OrigArg0 = TheCall->getArg(0);
2558   ExprResult OrigArg1 = TheCall->getArg(1);
2559 
2560   // Do standard promotions between the two arguments, returning their common
2561   // type.
2562   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2563   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2564     return true;
2565 
2566   // Make sure any conversions are pushed back into the call; this is
2567   // type safe since unordered compare builtins are declared as "_Bool
2568   // foo(...)".
2569   TheCall->setArg(0, OrigArg0.get());
2570   TheCall->setArg(1, OrigArg1.get());
2571 
2572   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2573     return false;
2574 
2575   // If the common type isn't a real floating type, then the arguments were
2576   // invalid for this operation.
2577   if (Res.isNull() || !Res->isRealFloatingType())
2578     return Diag(OrigArg0.get()->getLocStart(),
2579                 diag::err_typecheck_call_invalid_ordered_compare)
2580       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2581       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2582 
2583   return false;
2584 }
2585 
2586 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2587 /// __builtin_isnan and friends.  This is declared to take (...), so we have
2588 /// to check everything. We expect the last argument to be a floating point
2589 /// value.
2590 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2591   if (TheCall->getNumArgs() < NumArgs)
2592     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2593       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2594   if (TheCall->getNumArgs() > NumArgs)
2595     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2596                 diag::err_typecheck_call_too_many_args)
2597       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2598       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2599                      (*(TheCall->arg_end()-1))->getLocEnd());
2600 
2601   Expr *OrigArg = TheCall->getArg(NumArgs-1);
2602 
2603   if (OrigArg->isTypeDependent())
2604     return false;
2605 
2606   // This operation requires a non-_Complex floating-point number.
2607   if (!OrigArg->getType()->isRealFloatingType())
2608     return Diag(OrigArg->getLocStart(),
2609                 diag::err_typecheck_call_invalid_unary_fp)
2610       << OrigArg->getType() << OrigArg->getSourceRange();
2611 
2612   // If this is an implicit conversion from float -> double, remove it.
2613   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2614     Expr *CastArg = Cast->getSubExpr();
2615     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2616       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2617              "promotion from float to double is the only expected cast here");
2618       Cast->setSubExpr(nullptr);
2619       TheCall->setArg(NumArgs-1, CastArg);
2620     }
2621   }
2622 
2623   return false;
2624 }
2625 
2626 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2627 // This is declared to take (...), so we have to check everything.
2628 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2629   if (TheCall->getNumArgs() < 2)
2630     return ExprError(Diag(TheCall->getLocEnd(),
2631                           diag::err_typecheck_call_too_few_args_at_least)
2632                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2633                      << TheCall->getSourceRange());
2634 
2635   // Determine which of the following types of shufflevector we're checking:
2636   // 1) unary, vector mask: (lhs, mask)
2637   // 2) binary, vector mask: (lhs, rhs, mask)
2638   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2639   QualType resType = TheCall->getArg(0)->getType();
2640   unsigned numElements = 0;
2641 
2642   if (!TheCall->getArg(0)->isTypeDependent() &&
2643       !TheCall->getArg(1)->isTypeDependent()) {
2644     QualType LHSType = TheCall->getArg(0)->getType();
2645     QualType RHSType = TheCall->getArg(1)->getType();
2646 
2647     if (!LHSType->isVectorType() || !RHSType->isVectorType())
2648       return ExprError(Diag(TheCall->getLocStart(),
2649                             diag::err_shufflevector_non_vector)
2650                        << SourceRange(TheCall->getArg(0)->getLocStart(),
2651                                       TheCall->getArg(1)->getLocEnd()));
2652 
2653     numElements = LHSType->getAs<VectorType>()->getNumElements();
2654     unsigned numResElements = TheCall->getNumArgs() - 2;
2655 
2656     // Check to see if we have a call with 2 vector arguments, the unary shuffle
2657     // with mask.  If so, verify that RHS is an integer vector type with the
2658     // same number of elts as lhs.
2659     if (TheCall->getNumArgs() == 2) {
2660       if (!RHSType->hasIntegerRepresentation() ||
2661           RHSType->getAs<VectorType>()->getNumElements() != numElements)
2662         return ExprError(Diag(TheCall->getLocStart(),
2663                               diag::err_shufflevector_incompatible_vector)
2664                          << SourceRange(TheCall->getArg(1)->getLocStart(),
2665                                         TheCall->getArg(1)->getLocEnd()));
2666     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2667       return ExprError(Diag(TheCall->getLocStart(),
2668                             diag::err_shufflevector_incompatible_vector)
2669                        << SourceRange(TheCall->getArg(0)->getLocStart(),
2670                                       TheCall->getArg(1)->getLocEnd()));
2671     } else if (numElements != numResElements) {
2672       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2673       resType = Context.getVectorType(eltType, numResElements,
2674                                       VectorType::GenericVector);
2675     }
2676   }
2677 
2678   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2679     if (TheCall->getArg(i)->isTypeDependent() ||
2680         TheCall->getArg(i)->isValueDependent())
2681       continue;
2682 
2683     llvm::APSInt Result(32);
2684     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2685       return ExprError(Diag(TheCall->getLocStart(),
2686                             diag::err_shufflevector_nonconstant_argument)
2687                        << TheCall->getArg(i)->getSourceRange());
2688 
2689     // Allow -1 which will be translated to undef in the IR.
2690     if (Result.isSigned() && Result.isAllOnesValue())
2691       continue;
2692 
2693     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2694       return ExprError(Diag(TheCall->getLocStart(),
2695                             diag::err_shufflevector_argument_too_large)
2696                        << TheCall->getArg(i)->getSourceRange());
2697   }
2698 
2699   SmallVector<Expr*, 32> exprs;
2700 
2701   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2702     exprs.push_back(TheCall->getArg(i));
2703     TheCall->setArg(i, nullptr);
2704   }
2705 
2706   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2707                                          TheCall->getCallee()->getLocStart(),
2708                                          TheCall->getRParenLoc());
2709 }
2710 
2711 /// SemaConvertVectorExpr - Handle __builtin_convertvector
2712 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2713                                        SourceLocation BuiltinLoc,
2714                                        SourceLocation RParenLoc) {
2715   ExprValueKind VK = VK_RValue;
2716   ExprObjectKind OK = OK_Ordinary;
2717   QualType DstTy = TInfo->getType();
2718   QualType SrcTy = E->getType();
2719 
2720   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2721     return ExprError(Diag(BuiltinLoc,
2722                           diag::err_convertvector_non_vector)
2723                      << E->getSourceRange());
2724   if (!DstTy->isVectorType() && !DstTy->isDependentType())
2725     return ExprError(Diag(BuiltinLoc,
2726                           diag::err_convertvector_non_vector_type));
2727 
2728   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2729     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2730     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2731     if (SrcElts != DstElts)
2732       return ExprError(Diag(BuiltinLoc,
2733                             diag::err_convertvector_incompatible_vector)
2734                        << E->getSourceRange());
2735   }
2736 
2737   return new (Context)
2738       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
2739 }
2740 
2741 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2742 // This is declared to take (const void*, ...) and can take two
2743 // optional constant int args.
2744 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
2745   unsigned NumArgs = TheCall->getNumArgs();
2746 
2747   if (NumArgs > 3)
2748     return Diag(TheCall->getLocEnd(),
2749              diag::err_typecheck_call_too_many_args_at_most)
2750              << 0 /*function call*/ << 3 << NumArgs
2751              << TheCall->getSourceRange();
2752 
2753   // Argument 0 is checked for us and the remaining arguments must be
2754   // constant integers.
2755   for (unsigned i = 1; i != NumArgs; ++i)
2756     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2757       return true;
2758 
2759   return false;
2760 }
2761 
2762 /// SemaBuiltinAssume - Handle __assume (MS Extension).
2763 // __assume does not evaluate its arguments, and should warn if its argument
2764 // has side effects.
2765 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2766   Expr *Arg = TheCall->getArg(0);
2767   if (Arg->isInstantiationDependent()) return false;
2768 
2769   if (Arg->HasSideEffects(Context))
2770     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2771       << Arg->getSourceRange()
2772       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2773 
2774   return false;
2775 }
2776 
2777 /// Handle __builtin_assume_aligned. This is declared
2778 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2779 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2780   unsigned NumArgs = TheCall->getNumArgs();
2781 
2782   if (NumArgs > 3)
2783     return Diag(TheCall->getLocEnd(),
2784              diag::err_typecheck_call_too_many_args_at_most)
2785              << 0 /*function call*/ << 3 << NumArgs
2786              << TheCall->getSourceRange();
2787 
2788   // The alignment must be a constant integer.
2789   Expr *Arg = TheCall->getArg(1);
2790 
2791   // We can't check the value of a dependent argument.
2792   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2793     llvm::APSInt Result;
2794     if (SemaBuiltinConstantArg(TheCall, 1, Result))
2795       return true;
2796 
2797     if (!Result.isPowerOf2())
2798       return Diag(TheCall->getLocStart(),
2799                   diag::err_alignment_not_power_of_two)
2800            << Arg->getSourceRange();
2801   }
2802 
2803   if (NumArgs > 2) {
2804     ExprResult Arg(TheCall->getArg(2));
2805     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2806       Context.getSizeType(), false);
2807     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2808     if (Arg.isInvalid()) return true;
2809     TheCall->setArg(2, Arg.get());
2810   }
2811 
2812   return false;
2813 }
2814 
2815 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2816 /// TheCall is a constant expression.
2817 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2818                                   llvm::APSInt &Result) {
2819   Expr *Arg = TheCall->getArg(ArgNum);
2820   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2821   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2822 
2823   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2824 
2825   if (!Arg->isIntegerConstantExpr(Result, Context))
2826     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
2827                 << FDecl->getDeclName() <<  Arg->getSourceRange();
2828 
2829   return false;
2830 }
2831 
2832 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2833 /// TheCall is a constant expression in the range [Low, High].
2834 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2835                                        int Low, int High) {
2836   llvm::APSInt Result;
2837 
2838   // We can't check the value of a dependent argument.
2839   Expr *Arg = TheCall->getArg(ArgNum);
2840   if (Arg->isTypeDependent() || Arg->isValueDependent())
2841     return false;
2842 
2843   // Check constant-ness first.
2844   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2845     return true;
2846 
2847   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2848     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2849       << Low << High << Arg->getSourceRange();
2850 
2851   return false;
2852 }
2853 
2854 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2855 /// TheCall is an ARM/AArch64 special register string literal.
2856 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2857                                     int ArgNum, unsigned ExpectedFieldNum,
2858                                     bool AllowName) {
2859   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2860                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2861                       BuiltinID == ARM::BI__builtin_arm_rsr ||
2862                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2863                       BuiltinID == ARM::BI__builtin_arm_wsr ||
2864                       BuiltinID == ARM::BI__builtin_arm_wsrp;
2865   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2866                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2867                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
2868                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2869                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
2870                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
2871   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2872 
2873   // We can't check the value of a dependent argument.
2874   Expr *Arg = TheCall->getArg(ArgNum);
2875   if (Arg->isTypeDependent() || Arg->isValueDependent())
2876     return false;
2877 
2878   // Check if the argument is a string literal.
2879   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2880     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2881            << Arg->getSourceRange();
2882 
2883   // Check the type of special register given.
2884   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2885   SmallVector<StringRef, 6> Fields;
2886   Reg.split(Fields, ":");
2887 
2888   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2889     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2890            << Arg->getSourceRange();
2891 
2892   // If the string is the name of a register then we cannot check that it is
2893   // valid here but if the string is of one the forms described in ACLE then we
2894   // can check that the supplied fields are integers and within the valid
2895   // ranges.
2896   if (Fields.size() > 1) {
2897     bool FiveFields = Fields.size() == 5;
2898 
2899     bool ValidString = true;
2900     if (IsARMBuiltin) {
2901       ValidString &= Fields[0].startswith_lower("cp") ||
2902                      Fields[0].startswith_lower("p");
2903       if (ValidString)
2904         Fields[0] =
2905           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2906 
2907       ValidString &= Fields[2].startswith_lower("c");
2908       if (ValidString)
2909         Fields[2] = Fields[2].drop_front(1);
2910 
2911       if (FiveFields) {
2912         ValidString &= Fields[3].startswith_lower("c");
2913         if (ValidString)
2914           Fields[3] = Fields[3].drop_front(1);
2915       }
2916     }
2917 
2918     SmallVector<int, 5> Ranges;
2919     if (FiveFields)
2920       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2921     else
2922       Ranges.append({15, 7, 15});
2923 
2924     for (unsigned i=0; i<Fields.size(); ++i) {
2925       int IntField;
2926       ValidString &= !Fields[i].getAsInteger(10, IntField);
2927       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2928     }
2929 
2930     if (!ValidString)
2931       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2932              << Arg->getSourceRange();
2933 
2934   } else if (IsAArch64Builtin && Fields.size() == 1) {
2935     // If the register name is one of those that appear in the condition below
2936     // and the special register builtin being used is one of the write builtins,
2937     // then we require that the argument provided for writing to the register
2938     // is an integer constant expression. This is because it will be lowered to
2939     // an MSR (immediate) instruction, so we need to know the immediate at
2940     // compile time.
2941     if (TheCall->getNumArgs() != 2)
2942       return false;
2943 
2944     std::string RegLower = Reg.lower();
2945     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2946         RegLower != "pan" && RegLower != "uao")
2947       return false;
2948 
2949     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2950   }
2951 
2952   return false;
2953 }
2954 
2955 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2956 /// This checks that the target supports __builtin_cpu_supports and
2957 /// that the string argument is constant and valid.
2958 bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
2959   Expr *Arg = TheCall->getArg(0);
2960 
2961   // Check if the argument is a string literal.
2962   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2963     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2964            << Arg->getSourceRange();
2965 
2966   // Check the contents of the string.
2967   StringRef Feature =
2968       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2969   if (!Context.getTargetInfo().validateCpuSupports(Feature))
2970     return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2971            << Arg->getSourceRange();
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   // std::abs has overloads which prevent most of the absolute value problems
5089   // from occurring.
5090   if (IsStdAbs)
5091     return;
5092 
5093   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5094   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5095 
5096   // The argument and parameter are the same kind.  Check if they are the right
5097   // size.
5098   if (ArgValueKind == ParamValueKind) {
5099     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5100       return;
5101 
5102     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5103     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5104         << FDecl << ArgType << ParamType;
5105 
5106     if (NewAbsKind == 0)
5107       return;
5108 
5109     emitReplacement(*this, Call->getExprLoc(),
5110                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
5111     return;
5112   }
5113 
5114   // ArgValueKind != ParamValueKind
5115   // The wrong type of absolute value function was used.  Attempt to find the
5116   // proper one.
5117   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5118   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5119   if (NewAbsKind == 0)
5120     return;
5121 
5122   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5123       << FDecl << ParamValueKind << ArgValueKind;
5124 
5125   emitReplacement(*this, Call->getExprLoc(),
5126                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
5127   return;
5128 }
5129 
5130 //===--- CHECK: Standard memory functions ---------------------------------===//
5131 
5132 /// \brief Takes the expression passed to the size_t parameter of functions
5133 /// such as memcmp, strncat, etc and warns if it's a comparison.
5134 ///
5135 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5136 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5137                                            IdentifierInfo *FnName,
5138                                            SourceLocation FnLoc,
5139                                            SourceLocation RParenLoc) {
5140   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5141   if (!Size)
5142     return false;
5143 
5144   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5145   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5146     return false;
5147 
5148   SourceRange SizeRange = Size->getSourceRange();
5149   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5150       << SizeRange << FnName;
5151   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
5152       << FnName << FixItHint::CreateInsertion(
5153                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
5154       << FixItHint::CreateRemoval(RParenLoc);
5155   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
5156       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
5157       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5158                                     ")");
5159 
5160   return true;
5161 }
5162 
5163 /// \brief Determine whether the given type is or contains a dynamic class type
5164 /// (e.g., whether it has a vtable).
5165 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5166                                                      bool &IsContained) {
5167   // Look through array types while ignoring qualifiers.
5168   const Type *Ty = T->getBaseElementTypeUnsafe();
5169   IsContained = false;
5170 
5171   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5172   RD = RD ? RD->getDefinition() : nullptr;
5173   if (!RD)
5174     return nullptr;
5175 
5176   if (RD->isDynamicClass())
5177     return RD;
5178 
5179   // Check all the fields.  If any bases were dynamic, the class is dynamic.
5180   // It's impossible for a class to transitively contain itself by value, so
5181   // infinite recursion is impossible.
5182   for (auto *FD : RD->fields()) {
5183     bool SubContained;
5184     if (const CXXRecordDecl *ContainedRD =
5185             getContainedDynamicClass(FD->getType(), SubContained)) {
5186       IsContained = true;
5187       return ContainedRD;
5188     }
5189   }
5190 
5191   return nullptr;
5192 }
5193 
5194 /// \brief If E is a sizeof expression, returns its argument expression,
5195 /// otherwise returns NULL.
5196 static const Expr *getSizeOfExprArg(const Expr *E) {
5197   if (const UnaryExprOrTypeTraitExpr *SizeOf =
5198       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5199     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5200       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
5201 
5202   return nullptr;
5203 }
5204 
5205 /// \brief If E is a sizeof expression, returns its argument type.
5206 static QualType getSizeOfArgType(const Expr *E) {
5207   if (const UnaryExprOrTypeTraitExpr *SizeOf =
5208       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5209     if (SizeOf->getKind() == clang::UETT_SizeOf)
5210       return SizeOf->getTypeOfArgument();
5211 
5212   return QualType();
5213 }
5214 
5215 /// \brief Check for dangerous or invalid arguments to memset().
5216 ///
5217 /// This issues warnings on known problematic, dangerous or unspecified
5218 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5219 /// function calls.
5220 ///
5221 /// \param Call The call expression to diagnose.
5222 void Sema::CheckMemaccessArguments(const CallExpr *Call,
5223                                    unsigned BId,
5224                                    IdentifierInfo *FnName) {
5225   assert(BId != 0);
5226 
5227   // It is possible to have a non-standard definition of memset.  Validate
5228   // we have enough arguments, and if not, abort further checking.
5229   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
5230   if (Call->getNumArgs() < ExpectedNumArgs)
5231     return;
5232 
5233   unsigned LastArg = (BId == Builtin::BImemset ||
5234                       BId == Builtin::BIstrndup ? 1 : 2);
5235   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
5236   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
5237 
5238   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5239                                      Call->getLocStart(), Call->getRParenLoc()))
5240     return;
5241 
5242   // We have special checking when the length is a sizeof expression.
5243   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5244   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5245   llvm::FoldingSetNodeID SizeOfArgID;
5246 
5247   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5248     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
5249     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
5250 
5251     QualType DestTy = Dest->getType();
5252     QualType PointeeTy;
5253     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
5254       PointeeTy = DestPtrTy->getPointeeType();
5255 
5256       // Never warn about void type pointers. This can be used to suppress
5257       // false positives.
5258       if (PointeeTy->isVoidType())
5259         continue;
5260 
5261       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5262       // actually comparing the expressions for equality. Because computing the
5263       // expression IDs can be expensive, we only do this if the diagnostic is
5264       // enabled.
5265       if (SizeOfArg &&
5266           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5267                            SizeOfArg->getExprLoc())) {
5268         // We only compute IDs for expressions if the warning is enabled, and
5269         // cache the sizeof arg's ID.
5270         if (SizeOfArgID == llvm::FoldingSetNodeID())
5271           SizeOfArg->Profile(SizeOfArgID, Context, true);
5272         llvm::FoldingSetNodeID DestID;
5273         Dest->Profile(DestID, Context, true);
5274         if (DestID == SizeOfArgID) {
5275           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5276           //       over sizeof(src) as well.
5277           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
5278           StringRef ReadableName = FnName->getName();
5279 
5280           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
5281             if (UnaryOp->getOpcode() == UO_AddrOf)
5282               ActionIdx = 1; // If its an address-of operator, just remove it.
5283           if (!PointeeTy->isIncompleteType() &&
5284               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
5285             ActionIdx = 2; // If the pointee's size is sizeof(char),
5286                            // suggest an explicit length.
5287 
5288           // If the function is defined as a builtin macro, do not show macro
5289           // expansion.
5290           SourceLocation SL = SizeOfArg->getExprLoc();
5291           SourceRange DSR = Dest->getSourceRange();
5292           SourceRange SSR = SizeOfArg->getSourceRange();
5293           SourceManager &SM = getSourceManager();
5294 
5295           if (SM.isMacroArgExpansion(SL)) {
5296             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5297             SL = SM.getSpellingLoc(SL);
5298             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5299                              SM.getSpellingLoc(DSR.getEnd()));
5300             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5301                              SM.getSpellingLoc(SSR.getEnd()));
5302           }
5303 
5304           DiagRuntimeBehavior(SL, SizeOfArg,
5305                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
5306                                 << ReadableName
5307                                 << PointeeTy
5308                                 << DestTy
5309                                 << DSR
5310                                 << SSR);
5311           DiagRuntimeBehavior(SL, SizeOfArg,
5312                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5313                                 << ActionIdx
5314                                 << SSR);
5315 
5316           break;
5317         }
5318       }
5319 
5320       // Also check for cases where the sizeof argument is the exact same
5321       // type as the memory argument, and where it points to a user-defined
5322       // record type.
5323       if (SizeOfArgTy != QualType()) {
5324         if (PointeeTy->isRecordType() &&
5325             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5326           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5327                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
5328                                 << FnName << SizeOfArgTy << ArgIdx
5329                                 << PointeeTy << Dest->getSourceRange()
5330                                 << LenExpr->getSourceRange());
5331           break;
5332         }
5333       }
5334     } else if (DestTy->isArrayType()) {
5335       PointeeTy = DestTy;
5336     }
5337 
5338     if (PointeeTy == QualType())
5339       continue;
5340 
5341     // Always complain about dynamic classes.
5342     bool IsContained;
5343     if (const CXXRecordDecl *ContainedRD =
5344             getContainedDynamicClass(PointeeTy, IsContained)) {
5345 
5346       unsigned OperationType = 0;
5347       // "overwritten" if we're warning about the destination for any call
5348       // but memcmp; otherwise a verb appropriate to the call.
5349       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5350         if (BId == Builtin::BImemcpy)
5351           OperationType = 1;
5352         else if(BId == Builtin::BImemmove)
5353           OperationType = 2;
5354         else if (BId == Builtin::BImemcmp)
5355           OperationType = 3;
5356       }
5357 
5358       DiagRuntimeBehavior(
5359         Dest->getExprLoc(), Dest,
5360         PDiag(diag::warn_dyn_class_memaccess)
5361           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5362           << FnName << IsContained << ContainedRD << OperationType
5363           << Call->getCallee()->getSourceRange());
5364     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5365              BId != Builtin::BImemset)
5366       DiagRuntimeBehavior(
5367         Dest->getExprLoc(), Dest,
5368         PDiag(diag::warn_arc_object_memaccess)
5369           << ArgIdx << FnName << PointeeTy
5370           << Call->getCallee()->getSourceRange());
5371     else
5372       continue;
5373 
5374     DiagRuntimeBehavior(
5375       Dest->getExprLoc(), Dest,
5376       PDiag(diag::note_bad_memaccess_silence)
5377         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5378     break;
5379   }
5380 
5381 }
5382 
5383 // A little helper routine: ignore addition and subtraction of integer literals.
5384 // This intentionally does not ignore all integer constant expressions because
5385 // we don't want to remove sizeof().
5386 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5387   Ex = Ex->IgnoreParenCasts();
5388 
5389   for (;;) {
5390     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5391     if (!BO || !BO->isAdditiveOp())
5392       break;
5393 
5394     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5395     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5396 
5397     if (isa<IntegerLiteral>(RHS))
5398       Ex = LHS;
5399     else if (isa<IntegerLiteral>(LHS))
5400       Ex = RHS;
5401     else
5402       break;
5403   }
5404 
5405   return Ex;
5406 }
5407 
5408 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5409                                                       ASTContext &Context) {
5410   // Only handle constant-sized or VLAs, but not flexible members.
5411   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5412     // Only issue the FIXIT for arrays of size > 1.
5413     if (CAT->getSize().getSExtValue() <= 1)
5414       return false;
5415   } else if (!Ty->isVariableArrayType()) {
5416     return false;
5417   }
5418   return true;
5419 }
5420 
5421 // Warn if the user has made the 'size' argument to strlcpy or strlcat
5422 // be the size of the source, instead of the destination.
5423 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5424                                     IdentifierInfo *FnName) {
5425 
5426   // Don't crash if the user has the wrong number of arguments
5427   unsigned NumArgs = Call->getNumArgs();
5428   if ((NumArgs != 3) && (NumArgs != 4))
5429     return;
5430 
5431   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5432   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
5433   const Expr *CompareWithSrc = nullptr;
5434 
5435   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5436                                      Call->getLocStart(), Call->getRParenLoc()))
5437     return;
5438 
5439   // Look for 'strlcpy(dst, x, sizeof(x))'
5440   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5441     CompareWithSrc = Ex;
5442   else {
5443     // Look for 'strlcpy(dst, x, strlen(x))'
5444     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
5445       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5446           SizeCall->getNumArgs() == 1)
5447         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5448     }
5449   }
5450 
5451   if (!CompareWithSrc)
5452     return;
5453 
5454   // Determine if the argument to sizeof/strlen is equal to the source
5455   // argument.  In principle there's all kinds of things you could do
5456   // here, for instance creating an == expression and evaluating it with
5457   // EvaluateAsBooleanCondition, but this uses a more direct technique:
5458   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5459   if (!SrcArgDRE)
5460     return;
5461 
5462   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5463   if (!CompareWithSrcDRE ||
5464       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5465     return;
5466 
5467   const Expr *OriginalSizeArg = Call->getArg(2);
5468   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5469     << OriginalSizeArg->getSourceRange() << FnName;
5470 
5471   // Output a FIXIT hint if the destination is an array (rather than a
5472   // pointer to an array).  This could be enhanced to handle some
5473   // pointers if we know the actual size, like if DstArg is 'array+2'
5474   // we could say 'sizeof(array)-2'.
5475   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
5476   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
5477     return;
5478 
5479   SmallString<128> sizeString;
5480   llvm::raw_svector_ostream OS(sizeString);
5481   OS << "sizeof(";
5482   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5483   OS << ")";
5484 
5485   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5486     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5487                                     OS.str());
5488 }
5489 
5490 /// Check if two expressions refer to the same declaration.
5491 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5492   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5493     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5494       return D1->getDecl() == D2->getDecl();
5495   return false;
5496 }
5497 
5498 static const Expr *getStrlenExprArg(const Expr *E) {
5499   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5500     const FunctionDecl *FD = CE->getDirectCallee();
5501     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
5502       return nullptr;
5503     return CE->getArg(0)->IgnoreParenCasts();
5504   }
5505   return nullptr;
5506 }
5507 
5508 // Warn on anti-patterns as the 'size' argument to strncat.
5509 // The correct size argument should look like following:
5510 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5511 void Sema::CheckStrncatArguments(const CallExpr *CE,
5512                                  IdentifierInfo *FnName) {
5513   // Don't crash if the user has the wrong number of arguments.
5514   if (CE->getNumArgs() < 3)
5515     return;
5516   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5517   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5518   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5519 
5520   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5521                                      CE->getRParenLoc()))
5522     return;
5523 
5524   // Identify common expressions, which are wrongly used as the size argument
5525   // to strncat and may lead to buffer overflows.
5526   unsigned PatternType = 0;
5527   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5528     // - sizeof(dst)
5529     if (referToTheSameDecl(SizeOfArg, DstArg))
5530       PatternType = 1;
5531     // - sizeof(src)
5532     else if (referToTheSameDecl(SizeOfArg, SrcArg))
5533       PatternType = 2;
5534   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5535     if (BE->getOpcode() == BO_Sub) {
5536       const Expr *L = BE->getLHS()->IgnoreParenCasts();
5537       const Expr *R = BE->getRHS()->IgnoreParenCasts();
5538       // - sizeof(dst) - strlen(dst)
5539       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5540           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5541         PatternType = 1;
5542       // - sizeof(src) - (anything)
5543       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5544         PatternType = 2;
5545     }
5546   }
5547 
5548   if (PatternType == 0)
5549     return;
5550 
5551   // Generate the diagnostic.
5552   SourceLocation SL = LenArg->getLocStart();
5553   SourceRange SR = LenArg->getSourceRange();
5554   SourceManager &SM = getSourceManager();
5555 
5556   // If the function is defined as a builtin macro, do not show macro expansion.
5557   if (SM.isMacroArgExpansion(SL)) {
5558     SL = SM.getSpellingLoc(SL);
5559     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5560                      SM.getSpellingLoc(SR.getEnd()));
5561   }
5562 
5563   // Check if the destination is an array (rather than a pointer to an array).
5564   QualType DstTy = DstArg->getType();
5565   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5566                                                                     Context);
5567   if (!isKnownSizeArray) {
5568     if (PatternType == 1)
5569       Diag(SL, diag::warn_strncat_wrong_size) << SR;
5570     else
5571       Diag(SL, diag::warn_strncat_src_size) << SR;
5572     return;
5573   }
5574 
5575   if (PatternType == 1)
5576     Diag(SL, diag::warn_strncat_large_size) << SR;
5577   else
5578     Diag(SL, diag::warn_strncat_src_size) << SR;
5579 
5580   SmallString<128> sizeString;
5581   llvm::raw_svector_ostream OS(sizeString);
5582   OS << "sizeof(";
5583   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5584   OS << ") - ";
5585   OS << "strlen(";
5586   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5587   OS << ") - 1";
5588 
5589   Diag(SL, diag::note_strncat_wrong_size)
5590     << FixItHint::CreateReplacement(SR, OS.str());
5591 }
5592 
5593 //===--- CHECK: Return Address of Stack Variable --------------------------===//
5594 
5595 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5596                      Decl *ParentDecl);
5597 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5598                       Decl *ParentDecl);
5599 
5600 /// CheckReturnStackAddr - Check if a return statement returns the address
5601 ///   of a stack variable.
5602 static void
5603 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5604                      SourceLocation ReturnLoc) {
5605 
5606   Expr *stackE = nullptr;
5607   SmallVector<DeclRefExpr *, 8> refVars;
5608 
5609   // Perform checking for returned stack addresses, local blocks,
5610   // label addresses or references to temporaries.
5611   if (lhsType->isPointerType() ||
5612       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
5613     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
5614   } else if (lhsType->isReferenceType()) {
5615     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
5616   }
5617 
5618   if (!stackE)
5619     return; // Nothing suspicious was found.
5620 
5621   SourceLocation diagLoc;
5622   SourceRange diagRange;
5623   if (refVars.empty()) {
5624     diagLoc = stackE->getLocStart();
5625     diagRange = stackE->getSourceRange();
5626   } else {
5627     // We followed through a reference variable. 'stackE' contains the
5628     // problematic expression but we will warn at the return statement pointing
5629     // at the reference variable. We will later display the "trail" of
5630     // reference variables using notes.
5631     diagLoc = refVars[0]->getLocStart();
5632     diagRange = refVars[0]->getSourceRange();
5633   }
5634 
5635   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
5636     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
5637                                              : diag::warn_ret_stack_addr)
5638      << DR->getDecl()->getDeclName() << diagRange;
5639   } else if (isa<BlockExpr>(stackE)) { // local block.
5640     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
5641   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
5642     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
5643   } else { // local temporary.
5644     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5645                                                : diag::warn_ret_local_temp_addr)
5646      << diagRange;
5647   }
5648 
5649   // Display the "trail" of reference variables that we followed until we
5650   // found the problematic expression using notes.
5651   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5652     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5653     // If this var binds to another reference var, show the range of the next
5654     // var, otherwise the var binds to the problematic expression, in which case
5655     // show the range of the expression.
5656     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5657                                   : stackE->getSourceRange();
5658     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5659         << VD->getDeclName() << range;
5660   }
5661 }
5662 
5663 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5664 ///  check if the expression in a return statement evaluates to an address
5665 ///  to a location on the stack, a local block, an address of a label, or a
5666 ///  reference to local temporary. The recursion is used to traverse the
5667 ///  AST of the return expression, with recursion backtracking when we
5668 ///  encounter a subexpression that (1) clearly does not lead to one of the
5669 ///  above problematic expressions (2) is something we cannot determine leads to
5670 ///  a problematic expression based on such local checking.
5671 ///
5672 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
5673 ///  the expression that they point to. Such variables are added to the
5674 ///  'refVars' vector so that we know what the reference variable "trail" was.
5675 ///
5676 ///  EvalAddr processes expressions that are pointers that are used as
5677 ///  references (and not L-values).  EvalVal handles all other values.
5678 ///  At the base case of the recursion is a check for the above problematic
5679 ///  expressions.
5680 ///
5681 ///  This implementation handles:
5682 ///
5683 ///   * pointer-to-pointer casts
5684 ///   * implicit conversions from array references to pointers
5685 ///   * taking the address of fields
5686 ///   * arbitrary interplay between "&" and "*" operators
5687 ///   * pointer arithmetic from an address of a stack variable
5688 ///   * taking the address of an array element where the array is on the stack
5689 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5690                       Decl *ParentDecl) {
5691   if (E->isTypeDependent())
5692     return nullptr;
5693 
5694   // We should only be called for evaluating pointer expressions.
5695   assert((E->getType()->isAnyPointerType() ||
5696           E->getType()->isBlockPointerType() ||
5697           E->getType()->isObjCQualifiedIdType()) &&
5698          "EvalAddr only works on pointers");
5699 
5700   E = E->IgnoreParens();
5701 
5702   // Our "symbolic interpreter" is just a dispatch off the currently
5703   // viewed AST node.  We then recursively traverse the AST by calling
5704   // EvalAddr and EvalVal appropriately.
5705   switch (E->getStmtClass()) {
5706   case Stmt::DeclRefExprClass: {
5707     DeclRefExpr *DR = cast<DeclRefExpr>(E);
5708 
5709     // If we leave the immediate function, the lifetime isn't about to end.
5710     if (DR->refersToEnclosingVariableOrCapture())
5711       return nullptr;
5712 
5713     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5714       // If this is a reference variable, follow through to the expression that
5715       // it points to.
5716       if (V->hasLocalStorage() &&
5717           V->getType()->isReferenceType() && V->hasInit()) {
5718         // Add the reference variable to the "trail".
5719         refVars.push_back(DR);
5720         return EvalAddr(V->getInit(), refVars, ParentDecl);
5721       }
5722 
5723     return nullptr;
5724   }
5725 
5726   case Stmt::UnaryOperatorClass: {
5727     // The only unary operator that make sense to handle here
5728     // is AddrOf.  All others don't make sense as pointers.
5729     UnaryOperator *U = cast<UnaryOperator>(E);
5730 
5731     if (U->getOpcode() == UO_AddrOf)
5732       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
5733     else
5734       return nullptr;
5735   }
5736 
5737   case Stmt::BinaryOperatorClass: {
5738     // Handle pointer arithmetic.  All other binary operators are not valid
5739     // in this context.
5740     BinaryOperator *B = cast<BinaryOperator>(E);
5741     BinaryOperatorKind op = B->getOpcode();
5742 
5743     if (op != BO_Add && op != BO_Sub)
5744       return nullptr;
5745 
5746     Expr *Base = B->getLHS();
5747 
5748     // Determine which argument is the real pointer base.  It could be
5749     // the RHS argument instead of the LHS.
5750     if (!Base->getType()->isPointerType()) Base = B->getRHS();
5751 
5752     assert (Base->getType()->isPointerType());
5753     return EvalAddr(Base, refVars, ParentDecl);
5754   }
5755 
5756   // For conditional operators we need to see if either the LHS or RHS are
5757   // valid DeclRefExpr*s.  If one of them is valid, we return it.
5758   case Stmt::ConditionalOperatorClass: {
5759     ConditionalOperator *C = cast<ConditionalOperator>(E);
5760 
5761     // Handle the GNU extension for missing LHS.
5762     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5763     if (Expr *LHSExpr = C->getLHS()) {
5764       // In C++, we can have a throw-expression, which has 'void' type.
5765       if (!LHSExpr->getType()->isVoidType())
5766         if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
5767           return LHS;
5768     }
5769 
5770     // In C++, we can have a throw-expression, which has 'void' type.
5771     if (C->getRHS()->getType()->isVoidType())
5772       return nullptr;
5773 
5774     return EvalAddr(C->getRHS(), refVars, ParentDecl);
5775   }
5776 
5777   case Stmt::BlockExprClass:
5778     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5779       return E; // local block.
5780     return nullptr;
5781 
5782   case Stmt::AddrLabelExprClass:
5783     return E; // address of label.
5784 
5785   case Stmt::ExprWithCleanupsClass:
5786     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5787                     ParentDecl);
5788 
5789   // For casts, we need to handle conversions from arrays to
5790   // pointer values, and pointer-to-pointer conversions.
5791   case Stmt::ImplicitCastExprClass:
5792   case Stmt::CStyleCastExprClass:
5793   case Stmt::CXXFunctionalCastExprClass:
5794   case Stmt::ObjCBridgedCastExprClass:
5795   case Stmt::CXXStaticCastExprClass:
5796   case Stmt::CXXDynamicCastExprClass:
5797   case Stmt::CXXConstCastExprClass:
5798   case Stmt::CXXReinterpretCastExprClass: {
5799     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5800     switch (cast<CastExpr>(E)->getCastKind()) {
5801     case CK_LValueToRValue:
5802     case CK_NoOp:
5803     case CK_BaseToDerived:
5804     case CK_DerivedToBase:
5805     case CK_UncheckedDerivedToBase:
5806     case CK_Dynamic:
5807     case CK_CPointerToObjCPointerCast:
5808     case CK_BlockPointerToObjCPointerCast:
5809     case CK_AnyPointerToBlockPointerCast:
5810       return EvalAddr(SubExpr, refVars, ParentDecl);
5811 
5812     case CK_ArrayToPointerDecay:
5813       return EvalVal(SubExpr, refVars, ParentDecl);
5814 
5815     case CK_BitCast:
5816       if (SubExpr->getType()->isAnyPointerType() ||
5817           SubExpr->getType()->isBlockPointerType() ||
5818           SubExpr->getType()->isObjCQualifiedIdType())
5819         return EvalAddr(SubExpr, refVars, ParentDecl);
5820       else
5821         return nullptr;
5822 
5823     default:
5824       return nullptr;
5825     }
5826   }
5827 
5828   case Stmt::MaterializeTemporaryExprClass:
5829     if (Expr *Result = EvalAddr(
5830                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5831                                 refVars, ParentDecl))
5832       return Result;
5833 
5834     return E;
5835 
5836   // Everything else: we simply don't reason about them.
5837   default:
5838     return nullptr;
5839   }
5840 }
5841 
5842 
5843 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
5844 ///   See the comments for EvalAddr for more details.
5845 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5846                      Decl *ParentDecl) {
5847 do {
5848   // We should only be called for evaluating non-pointer expressions, or
5849   // expressions with a pointer type that are not used as references but instead
5850   // are l-values (e.g., DeclRefExpr with a pointer type).
5851 
5852   // Our "symbolic interpreter" is just a dispatch off the currently
5853   // viewed AST node.  We then recursively traverse the AST by calling
5854   // EvalAddr and EvalVal appropriately.
5855 
5856   E = E->IgnoreParens();
5857   switch (E->getStmtClass()) {
5858   case Stmt::ImplicitCastExprClass: {
5859     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
5860     if (IE->getValueKind() == VK_LValue) {
5861       E = IE->getSubExpr();
5862       continue;
5863     }
5864     return nullptr;
5865   }
5866 
5867   case Stmt::ExprWithCleanupsClass:
5868     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5869 
5870   case Stmt::DeclRefExprClass: {
5871     // When we hit a DeclRefExpr we are looking at code that refers to a
5872     // variable's name. If it's not a reference variable we check if it has
5873     // local storage within the function, and if so, return the expression.
5874     DeclRefExpr *DR = cast<DeclRefExpr>(E);
5875 
5876     // If we leave the immediate function, the lifetime isn't about to end.
5877     if (DR->refersToEnclosingVariableOrCapture())
5878       return nullptr;
5879 
5880     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5881       // Check if it refers to itself, e.g. "int& i = i;".
5882       if (V == ParentDecl)
5883         return DR;
5884 
5885       if (V->hasLocalStorage()) {
5886         if (!V->getType()->isReferenceType())
5887           return DR;
5888 
5889         // Reference variable, follow through to the expression that
5890         // it points to.
5891         if (V->hasInit()) {
5892           // Add the reference variable to the "trail".
5893           refVars.push_back(DR);
5894           return EvalVal(V->getInit(), refVars, V);
5895         }
5896       }
5897     }
5898 
5899     return nullptr;
5900   }
5901 
5902   case Stmt::UnaryOperatorClass: {
5903     // The only unary operator that make sense to handle here
5904     // is Deref.  All others don't resolve to a "name."  This includes
5905     // handling all sorts of rvalues passed to a unary operator.
5906     UnaryOperator *U = cast<UnaryOperator>(E);
5907 
5908     if (U->getOpcode() == UO_Deref)
5909       return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
5910 
5911     return nullptr;
5912   }
5913 
5914   case Stmt::ArraySubscriptExprClass: {
5915     // Array subscripts are potential references to data on the stack.  We
5916     // retrieve the DeclRefExpr* for the array variable if it indeed
5917     // has local storage.
5918     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5919   }
5920 
5921   case Stmt::OMPArraySectionExprClass: {
5922     return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5923                     ParentDecl);
5924   }
5925 
5926   case Stmt::ConditionalOperatorClass: {
5927     // For conditional operators we need to see if either the LHS or RHS are
5928     // non-NULL Expr's.  If one is non-NULL, we return it.
5929     ConditionalOperator *C = cast<ConditionalOperator>(E);
5930 
5931     // Handle the GNU extension for missing LHS.
5932     if (Expr *LHSExpr = C->getLHS()) {
5933       // In C++, we can have a throw-expression, which has 'void' type.
5934       if (!LHSExpr->getType()->isVoidType())
5935         if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5936           return LHS;
5937     }
5938 
5939     // In C++, we can have a throw-expression, which has 'void' type.
5940     if (C->getRHS()->getType()->isVoidType())
5941       return nullptr;
5942 
5943     return EvalVal(C->getRHS(), refVars, ParentDecl);
5944   }
5945 
5946   // Accesses to members are potential references to data on the stack.
5947   case Stmt::MemberExprClass: {
5948     MemberExpr *M = cast<MemberExpr>(E);
5949 
5950     // Check for indirect access.  We only want direct field accesses.
5951     if (M->isArrow())
5952       return nullptr;
5953 
5954     // Check whether the member type is itself a reference, in which case
5955     // we're not going to refer to the member, but to what the member refers to.
5956     if (M->getMemberDecl()->getType()->isReferenceType())
5957       return nullptr;
5958 
5959     return EvalVal(M->getBase(), refVars, ParentDecl);
5960   }
5961 
5962   case Stmt::MaterializeTemporaryExprClass:
5963     if (Expr *Result = EvalVal(
5964                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5965                                refVars, ParentDecl))
5966       return Result;
5967 
5968     return E;
5969 
5970   default:
5971     // Check that we don't return or take the address of a reference to a
5972     // temporary. This is only useful in C++.
5973     if (!E->isTypeDependent() && E->isRValue())
5974       return E;
5975 
5976     // Everything else: we simply don't reason about them.
5977     return nullptr;
5978   }
5979 } while (true);
5980 }
5981 
5982 void
5983 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5984                          SourceLocation ReturnLoc,
5985                          bool isObjCMethod,
5986                          const AttrVec *Attrs,
5987                          const FunctionDecl *FD) {
5988   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5989 
5990   // Check if the return value is null but should not be.
5991   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5992        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
5993       CheckNonNullExpr(*this, RetValExp))
5994     Diag(ReturnLoc, diag::warn_null_ret)
5995       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5996 
5997   // C++11 [basic.stc.dynamic.allocation]p4:
5998   //   If an allocation function declared with a non-throwing
5999   //   exception-specification fails to allocate storage, it shall return
6000   //   a null pointer. Any other allocation function that fails to allocate
6001   //   storage shall indicate failure only by throwing an exception [...]
6002   if (FD) {
6003     OverloadedOperatorKind Op = FD->getOverloadedOperator();
6004     if (Op == OO_New || Op == OO_Array_New) {
6005       const FunctionProtoType *Proto
6006         = FD->getType()->castAs<FunctionProtoType>();
6007       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6008           CheckNonNullExpr(*this, RetValExp))
6009         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6010           << FD << getLangOpts().CPlusPlus11;
6011     }
6012   }
6013 }
6014 
6015 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6016 
6017 /// Check for comparisons of floating point operands using != and ==.
6018 /// Issue a warning if these are no self-comparisons, as they are not likely
6019 /// to do what the programmer intended.
6020 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
6021   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6022   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
6023 
6024   // Special case: check for x == x (which is OK).
6025   // Do not emit warnings for such cases.
6026   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6027     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6028       if (DRL->getDecl() == DRR->getDecl())
6029         return;
6030 
6031 
6032   // Special case: check for comparisons against literals that can be exactly
6033   //  represented by APFloat.  In such cases, do not emit a warning.  This
6034   //  is a heuristic: often comparison against such literals are used to
6035   //  detect if a value in a variable has not changed.  This clearly can
6036   //  lead to false negatives.
6037   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6038     if (FLL->isExact())
6039       return;
6040   } else
6041     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6042       if (FLR->isExact())
6043         return;
6044 
6045   // Check for comparisons with builtin types.
6046   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
6047     if (CL->getBuiltinCallee())
6048       return;
6049 
6050   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
6051     if (CR->getBuiltinCallee())
6052       return;
6053 
6054   // Emit the diagnostic.
6055   Diag(Loc, diag::warn_floatingpoint_eq)
6056     << LHS->getSourceRange() << RHS->getSourceRange();
6057 }
6058 
6059 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6060 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
6061 
6062 namespace {
6063 
6064 /// Structure recording the 'active' range of an integer-valued
6065 /// expression.
6066 struct IntRange {
6067   /// The number of bits active in the int.
6068   unsigned Width;
6069 
6070   /// True if the int is known not to have negative values.
6071   bool NonNegative;
6072 
6073   IntRange(unsigned Width, bool NonNegative)
6074     : Width(Width), NonNegative(NonNegative)
6075   {}
6076 
6077   /// Returns the range of the bool type.
6078   static IntRange forBoolType() {
6079     return IntRange(1, true);
6080   }
6081 
6082   /// Returns the range of an opaque value of the given integral type.
6083   static IntRange forValueOfType(ASTContext &C, QualType T) {
6084     return forValueOfCanonicalType(C,
6085                           T->getCanonicalTypeInternal().getTypePtr());
6086   }
6087 
6088   /// Returns the range of an opaque value of a canonical integral type.
6089   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
6090     assert(T->isCanonicalUnqualified());
6091 
6092     if (const VectorType *VT = dyn_cast<VectorType>(T))
6093       T = VT->getElementType().getTypePtr();
6094     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6095       T = CT->getElementType().getTypePtr();
6096     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6097       T = AT->getValueType().getTypePtr();
6098 
6099     // For enum types, use the known bit width of the enumerators.
6100     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
6101       EnumDecl *Enum = ET->getDecl();
6102       if (!Enum->isCompleteDefinition())
6103         return IntRange(C.getIntWidth(QualType(T, 0)), false);
6104 
6105       unsigned NumPositive = Enum->getNumPositiveBits();
6106       unsigned NumNegative = Enum->getNumNegativeBits();
6107 
6108       if (NumNegative == 0)
6109         return IntRange(NumPositive, true/*NonNegative*/);
6110       else
6111         return IntRange(std::max(NumPositive + 1, NumNegative),
6112                         false/*NonNegative*/);
6113     }
6114 
6115     const BuiltinType *BT = cast<BuiltinType>(T);
6116     assert(BT->isInteger());
6117 
6118     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6119   }
6120 
6121   /// Returns the "target" range of a canonical integral type, i.e.
6122   /// the range of values expressible in the type.
6123   ///
6124   /// This matches forValueOfCanonicalType except that enums have the
6125   /// full range of their type, not the range of their enumerators.
6126   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6127     assert(T->isCanonicalUnqualified());
6128 
6129     if (const VectorType *VT = dyn_cast<VectorType>(T))
6130       T = VT->getElementType().getTypePtr();
6131     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6132       T = CT->getElementType().getTypePtr();
6133     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6134       T = AT->getValueType().getTypePtr();
6135     if (const EnumType *ET = dyn_cast<EnumType>(T))
6136       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
6137 
6138     const BuiltinType *BT = cast<BuiltinType>(T);
6139     assert(BT->isInteger());
6140 
6141     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6142   }
6143 
6144   /// Returns the supremum of two ranges: i.e. their conservative merge.
6145   static IntRange join(IntRange L, IntRange R) {
6146     return IntRange(std::max(L.Width, R.Width),
6147                     L.NonNegative && R.NonNegative);
6148   }
6149 
6150   /// Returns the infinum of two ranges: i.e. their aggressive merge.
6151   static IntRange meet(IntRange L, IntRange R) {
6152     return IntRange(std::min(L.Width, R.Width),
6153                     L.NonNegative || R.NonNegative);
6154   }
6155 };
6156 
6157 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6158                               unsigned MaxWidth) {
6159   if (value.isSigned() && value.isNegative())
6160     return IntRange(value.getMinSignedBits(), false);
6161 
6162   if (value.getBitWidth() > MaxWidth)
6163     value = value.trunc(MaxWidth);
6164 
6165   // isNonNegative() just checks the sign bit without considering
6166   // signedness.
6167   return IntRange(value.getActiveBits(), true);
6168 }
6169 
6170 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6171                               unsigned MaxWidth) {
6172   if (result.isInt())
6173     return GetValueRange(C, result.getInt(), MaxWidth);
6174 
6175   if (result.isVector()) {
6176     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6177     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6178       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6179       R = IntRange::join(R, El);
6180     }
6181     return R;
6182   }
6183 
6184   if (result.isComplexInt()) {
6185     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6186     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6187     return IntRange::join(R, I);
6188   }
6189 
6190   // This can happen with lossless casts to intptr_t of "based" lvalues.
6191   // Assume it might use arbitrary bits.
6192   // FIXME: The only reason we need to pass the type in here is to get
6193   // the sign right on this one case.  It would be nice if APValue
6194   // preserved this.
6195   assert(result.isLValue() || result.isAddrLabelDiff());
6196   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
6197 }
6198 
6199 static QualType GetExprType(Expr *E) {
6200   QualType Ty = E->getType();
6201   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6202     Ty = AtomicRHS->getValueType();
6203   return Ty;
6204 }
6205 
6206 /// Pseudo-evaluate the given integer expression, estimating the
6207 /// range of values it might take.
6208 ///
6209 /// \param MaxWidth - the width to which the value will be truncated
6210 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
6211   E = E->IgnoreParens();
6212 
6213   // Try a full evaluation first.
6214   Expr::EvalResult result;
6215   if (E->EvaluateAsRValue(result, C))
6216     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
6217 
6218   // I think we only want to look through implicit casts here; if the
6219   // user has an explicit widening cast, we should treat the value as
6220   // being of the new, wider type.
6221   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
6222     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
6223       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6224 
6225     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
6226 
6227     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
6228 
6229     // Assume that non-integer casts can span the full range of the type.
6230     if (!isIntegerCast)
6231       return OutputTypeRange;
6232 
6233     IntRange SubRange
6234       = GetExprRange(C, CE->getSubExpr(),
6235                      std::min(MaxWidth, OutputTypeRange.Width));
6236 
6237     // Bail out if the subexpr's range is as wide as the cast type.
6238     if (SubRange.Width >= OutputTypeRange.Width)
6239       return OutputTypeRange;
6240 
6241     // Otherwise, we take the smaller width, and we're non-negative if
6242     // either the output type or the subexpr is.
6243     return IntRange(SubRange.Width,
6244                     SubRange.NonNegative || OutputTypeRange.NonNegative);
6245   }
6246 
6247   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6248     // If we can fold the condition, just take that operand.
6249     bool CondResult;
6250     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6251       return GetExprRange(C, CondResult ? CO->getTrueExpr()
6252                                         : CO->getFalseExpr(),
6253                           MaxWidth);
6254 
6255     // Otherwise, conservatively merge.
6256     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6257     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6258     return IntRange::join(L, R);
6259   }
6260 
6261   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6262     switch (BO->getOpcode()) {
6263 
6264     // Boolean-valued operations are single-bit and positive.
6265     case BO_LAnd:
6266     case BO_LOr:
6267     case BO_LT:
6268     case BO_GT:
6269     case BO_LE:
6270     case BO_GE:
6271     case BO_EQ:
6272     case BO_NE:
6273       return IntRange::forBoolType();
6274 
6275     // The type of the assignments is the type of the LHS, so the RHS
6276     // is not necessarily the same type.
6277     case BO_MulAssign:
6278     case BO_DivAssign:
6279     case BO_RemAssign:
6280     case BO_AddAssign:
6281     case BO_SubAssign:
6282     case BO_XorAssign:
6283     case BO_OrAssign:
6284       // TODO: bitfields?
6285       return IntRange::forValueOfType(C, GetExprType(E));
6286 
6287     // Simple assignments just pass through the RHS, which will have
6288     // been coerced to the LHS type.
6289     case BO_Assign:
6290       // TODO: bitfields?
6291       return GetExprRange(C, BO->getRHS(), MaxWidth);
6292 
6293     // Operations with opaque sources are black-listed.
6294     case BO_PtrMemD:
6295     case BO_PtrMemI:
6296       return IntRange::forValueOfType(C, GetExprType(E));
6297 
6298     // Bitwise-and uses the *infinum* of the two source ranges.
6299     case BO_And:
6300     case BO_AndAssign:
6301       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6302                             GetExprRange(C, BO->getRHS(), MaxWidth));
6303 
6304     // Left shift gets black-listed based on a judgement call.
6305     case BO_Shl:
6306       // ...except that we want to treat '1 << (blah)' as logically
6307       // positive.  It's an important idiom.
6308       if (IntegerLiteral *I
6309             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6310         if (I->getValue() == 1) {
6311           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
6312           return IntRange(R.Width, /*NonNegative*/ true);
6313         }
6314       }
6315       // fallthrough
6316 
6317     case BO_ShlAssign:
6318       return IntRange::forValueOfType(C, GetExprType(E));
6319 
6320     // Right shift by a constant can narrow its left argument.
6321     case BO_Shr:
6322     case BO_ShrAssign: {
6323       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6324 
6325       // If the shift amount is a positive constant, drop the width by
6326       // that much.
6327       llvm::APSInt shift;
6328       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6329           shift.isNonNegative()) {
6330         unsigned zext = shift.getZExtValue();
6331         if (zext >= L.Width)
6332           L.Width = (L.NonNegative ? 0 : 1);
6333         else
6334           L.Width -= zext;
6335       }
6336 
6337       return L;
6338     }
6339 
6340     // Comma acts as its right operand.
6341     case BO_Comma:
6342       return GetExprRange(C, BO->getRHS(), MaxWidth);
6343 
6344     // Black-list pointer subtractions.
6345     case BO_Sub:
6346       if (BO->getLHS()->getType()->isPointerType())
6347         return IntRange::forValueOfType(C, GetExprType(E));
6348       break;
6349 
6350     // The width of a division result is mostly determined by the size
6351     // of the LHS.
6352     case BO_Div: {
6353       // Don't 'pre-truncate' the operands.
6354       unsigned opWidth = C.getIntWidth(GetExprType(E));
6355       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6356 
6357       // If the divisor is constant, use that.
6358       llvm::APSInt divisor;
6359       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6360         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6361         if (log2 >= L.Width)
6362           L.Width = (L.NonNegative ? 0 : 1);
6363         else
6364           L.Width = std::min(L.Width - log2, MaxWidth);
6365         return L;
6366       }
6367 
6368       // Otherwise, just use the LHS's width.
6369       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6370       return IntRange(L.Width, L.NonNegative && R.NonNegative);
6371     }
6372 
6373     // The result of a remainder can't be larger than the result of
6374     // either side.
6375     case BO_Rem: {
6376       // Don't 'pre-truncate' the operands.
6377       unsigned opWidth = C.getIntWidth(GetExprType(E));
6378       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6379       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6380 
6381       IntRange meet = IntRange::meet(L, R);
6382       meet.Width = std::min(meet.Width, MaxWidth);
6383       return meet;
6384     }
6385 
6386     // The default behavior is okay for these.
6387     case BO_Mul:
6388     case BO_Add:
6389     case BO_Xor:
6390     case BO_Or:
6391       break;
6392     }
6393 
6394     // The default case is to treat the operation as if it were closed
6395     // on the narrowest type that encompasses both operands.
6396     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6397     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6398     return IntRange::join(L, R);
6399   }
6400 
6401   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6402     switch (UO->getOpcode()) {
6403     // Boolean-valued operations are white-listed.
6404     case UO_LNot:
6405       return IntRange::forBoolType();
6406 
6407     // Operations with opaque sources are black-listed.
6408     case UO_Deref:
6409     case UO_AddrOf: // should be impossible
6410       return IntRange::forValueOfType(C, GetExprType(E));
6411 
6412     default:
6413       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6414     }
6415   }
6416 
6417   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6418     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6419 
6420   if (FieldDecl *BitField = E->getSourceBitField())
6421     return IntRange(BitField->getBitWidthValue(C),
6422                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
6423 
6424   return IntRange::forValueOfType(C, GetExprType(E));
6425 }
6426 
6427 static IntRange GetExprRange(ASTContext &C, Expr *E) {
6428   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
6429 }
6430 
6431 /// Checks whether the given value, which currently has the given
6432 /// source semantics, has the same value when coerced through the
6433 /// target semantics.
6434 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6435                                  const llvm::fltSemantics &Src,
6436                                  const llvm::fltSemantics &Tgt) {
6437   llvm::APFloat truncated = value;
6438 
6439   bool ignored;
6440   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6441   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6442 
6443   return truncated.bitwiseIsEqual(value);
6444 }
6445 
6446 /// Checks whether the given value, which currently has the given
6447 /// source semantics, has the same value when coerced through the
6448 /// target semantics.
6449 ///
6450 /// The value might be a vector of floats (or a complex number).
6451 static bool IsSameFloatAfterCast(const APValue &value,
6452                                  const llvm::fltSemantics &Src,
6453                                  const llvm::fltSemantics &Tgt) {
6454   if (value.isFloat())
6455     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6456 
6457   if (value.isVector()) {
6458     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6459       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6460         return false;
6461     return true;
6462   }
6463 
6464   assert(value.isComplexFloat());
6465   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6466           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6467 }
6468 
6469 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
6470 
6471 static bool IsZero(Sema &S, Expr *E) {
6472   // Suppress cases where we are comparing against an enum constant.
6473   if (const DeclRefExpr *DR =
6474       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6475     if (isa<EnumConstantDecl>(DR->getDecl()))
6476       return false;
6477 
6478   // Suppress cases where the '0' value is expanded from a macro.
6479   if (E->getLocStart().isMacroID())
6480     return false;
6481 
6482   llvm::APSInt Value;
6483   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6484 }
6485 
6486 static bool HasEnumType(Expr *E) {
6487   // Strip off implicit integral promotions.
6488   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6489     if (ICE->getCastKind() != CK_IntegralCast &&
6490         ICE->getCastKind() != CK_NoOp)
6491       break;
6492     E = ICE->getSubExpr();
6493   }
6494 
6495   return E->getType()->isEnumeralType();
6496 }
6497 
6498 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
6499   // Disable warning in template instantiations.
6500   if (!S.ActiveTemplateInstantiations.empty())
6501     return;
6502 
6503   BinaryOperatorKind op = E->getOpcode();
6504   if (E->isValueDependent())
6505     return;
6506 
6507   if (op == BO_LT && IsZero(S, E->getRHS())) {
6508     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6509       << "< 0" << "false" << HasEnumType(E->getLHS())
6510       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6511   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
6512     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6513       << ">= 0" << "true" << HasEnumType(E->getLHS())
6514       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6515   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
6516     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6517       << "0 >" << "false" << HasEnumType(E->getRHS())
6518       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6519   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
6520     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6521       << "0 <=" << "true" << HasEnumType(E->getRHS())
6522       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6523   }
6524 }
6525 
6526 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6527                                          Expr *Constant, Expr *Other,
6528                                          llvm::APSInt Value,
6529                                          bool RhsConstant) {
6530   // Disable warning in template instantiations.
6531   if (!S.ActiveTemplateInstantiations.empty())
6532     return;
6533 
6534   // TODO: Investigate using GetExprRange() to get tighter bounds
6535   // on the bit ranges.
6536   QualType OtherT = Other->getType();
6537   if (const auto *AT = OtherT->getAs<AtomicType>())
6538     OtherT = AT->getValueType();
6539   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6540   unsigned OtherWidth = OtherRange.Width;
6541 
6542   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6543 
6544   // 0 values are handled later by CheckTrivialUnsignedComparison().
6545   if ((Value == 0) && (!OtherIsBooleanType))
6546     return;
6547 
6548   BinaryOperatorKind op = E->getOpcode();
6549   bool IsTrue = true;
6550 
6551   // Used for diagnostic printout.
6552   enum {
6553     LiteralConstant = 0,
6554     CXXBoolLiteralTrue,
6555     CXXBoolLiteralFalse
6556   } LiteralOrBoolConstant = LiteralConstant;
6557 
6558   if (!OtherIsBooleanType) {
6559     QualType ConstantT = Constant->getType();
6560     QualType CommonT = E->getLHS()->getType();
6561 
6562     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6563       return;
6564     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6565            "comparison with non-integer type");
6566 
6567     bool ConstantSigned = ConstantT->isSignedIntegerType();
6568     bool CommonSigned = CommonT->isSignedIntegerType();
6569 
6570     bool EqualityOnly = false;
6571 
6572     if (CommonSigned) {
6573       // The common type is signed, therefore no signed to unsigned conversion.
6574       if (!OtherRange.NonNegative) {
6575         // Check that the constant is representable in type OtherT.
6576         if (ConstantSigned) {
6577           if (OtherWidth >= Value.getMinSignedBits())
6578             return;
6579         } else { // !ConstantSigned
6580           if (OtherWidth >= Value.getActiveBits() + 1)
6581             return;
6582         }
6583       } else { // !OtherSigned
6584                // Check that the constant is representable in type OtherT.
6585         // Negative values are out of range.
6586         if (ConstantSigned) {
6587           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6588             return;
6589         } else { // !ConstantSigned
6590           if (OtherWidth >= Value.getActiveBits())
6591             return;
6592         }
6593       }
6594     } else { // !CommonSigned
6595       if (OtherRange.NonNegative) {
6596         if (OtherWidth >= Value.getActiveBits())
6597           return;
6598       } else { // OtherSigned
6599         assert(!ConstantSigned &&
6600                "Two signed types converted to unsigned types.");
6601         // Check to see if the constant is representable in OtherT.
6602         if (OtherWidth > Value.getActiveBits())
6603           return;
6604         // Check to see if the constant is equivalent to a negative value
6605         // cast to CommonT.
6606         if (S.Context.getIntWidth(ConstantT) ==
6607                 S.Context.getIntWidth(CommonT) &&
6608             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6609           return;
6610         // The constant value rests between values that OtherT can represent
6611         // after conversion.  Relational comparison still works, but equality
6612         // comparisons will be tautological.
6613         EqualityOnly = true;
6614       }
6615     }
6616 
6617     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6618 
6619     if (op == BO_EQ || op == BO_NE) {
6620       IsTrue = op == BO_NE;
6621     } else if (EqualityOnly) {
6622       return;
6623     } else if (RhsConstant) {
6624       if (op == BO_GT || op == BO_GE)
6625         IsTrue = !PositiveConstant;
6626       else // op == BO_LT || op == BO_LE
6627         IsTrue = PositiveConstant;
6628     } else {
6629       if (op == BO_LT || op == BO_LE)
6630         IsTrue = !PositiveConstant;
6631       else // op == BO_GT || op == BO_GE
6632         IsTrue = PositiveConstant;
6633     }
6634   } else {
6635     // Other isKnownToHaveBooleanValue
6636     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6637     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6638     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6639 
6640     static const struct LinkedConditions {
6641       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6642       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6643       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6644       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6645       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6646       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6647 
6648     } TruthTable = {
6649         // Constant on LHS.              | Constant on RHS.              |
6650         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
6651         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6652         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6653         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6654         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6655         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6656         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6657       };
6658 
6659     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6660 
6661     enum ConstantValue ConstVal = Zero;
6662     if (Value.isUnsigned() || Value.isNonNegative()) {
6663       if (Value == 0) {
6664         LiteralOrBoolConstant =
6665             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6666         ConstVal = Zero;
6667       } else if (Value == 1) {
6668         LiteralOrBoolConstant =
6669             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6670         ConstVal = One;
6671       } else {
6672         LiteralOrBoolConstant = LiteralConstant;
6673         ConstVal = GT_One;
6674       }
6675     } else {
6676       ConstVal = LT_Zero;
6677     }
6678 
6679     CompareBoolWithConstantResult CmpRes;
6680 
6681     switch (op) {
6682     case BO_LT:
6683       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6684       break;
6685     case BO_GT:
6686       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6687       break;
6688     case BO_LE:
6689       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6690       break;
6691     case BO_GE:
6692       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6693       break;
6694     case BO_EQ:
6695       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6696       break;
6697     case BO_NE:
6698       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6699       break;
6700     default:
6701       CmpRes = Unkwn;
6702       break;
6703     }
6704 
6705     if (CmpRes == AFals) {
6706       IsTrue = false;
6707     } else if (CmpRes == ATrue) {
6708       IsTrue = true;
6709     } else {
6710       return;
6711     }
6712   }
6713 
6714   // If this is a comparison to an enum constant, include that
6715   // constant in the diagnostic.
6716   const EnumConstantDecl *ED = nullptr;
6717   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6718     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6719 
6720   SmallString<64> PrettySourceValue;
6721   llvm::raw_svector_ostream OS(PrettySourceValue);
6722   if (ED)
6723     OS << '\'' << *ED << "' (" << Value << ")";
6724   else
6725     OS << Value;
6726 
6727   S.DiagRuntimeBehavior(
6728     E->getOperatorLoc(), E,
6729     S.PDiag(diag::warn_out_of_range_compare)
6730         << OS.str() << LiteralOrBoolConstant
6731         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6732         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
6733 }
6734 
6735 /// Analyze the operands of the given comparison.  Implements the
6736 /// fallback case from AnalyzeComparison.
6737 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
6738   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6739   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6740 }
6741 
6742 /// \brief Implements -Wsign-compare.
6743 ///
6744 /// \param E the binary operator to check for warnings
6745 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
6746   // The type the comparison is being performed in.
6747   QualType T = E->getLHS()->getType();
6748 
6749   // Only analyze comparison operators where both sides have been converted to
6750   // the same type.
6751   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6752     return AnalyzeImpConvsInComparison(S, E);
6753 
6754   // Don't analyze value-dependent comparisons directly.
6755   if (E->isValueDependent())
6756     return AnalyzeImpConvsInComparison(S, E);
6757 
6758   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6759   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
6760 
6761   bool IsComparisonConstant = false;
6762 
6763   // Check whether an integer constant comparison results in a value
6764   // of 'true' or 'false'.
6765   if (T->isIntegralType(S.Context)) {
6766     llvm::APSInt RHSValue;
6767     bool IsRHSIntegralLiteral =
6768       RHS->isIntegerConstantExpr(RHSValue, S.Context);
6769     llvm::APSInt LHSValue;
6770     bool IsLHSIntegralLiteral =
6771       LHS->isIntegerConstantExpr(LHSValue, S.Context);
6772     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6773         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6774     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6775       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6776     else
6777       IsComparisonConstant =
6778         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6779   } else if (!T->hasUnsignedIntegerRepresentation())
6780       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
6781 
6782   // We don't do anything special if this isn't an unsigned integral
6783   // comparison:  we're only interested in integral comparisons, and
6784   // signed comparisons only happen in cases we don't care to warn about.
6785   //
6786   // We also don't care about value-dependent expressions or expressions
6787   // whose result is a constant.
6788   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
6789     return AnalyzeImpConvsInComparison(S, E);
6790 
6791   // Check to see if one of the (unmodified) operands is of different
6792   // signedness.
6793   Expr *signedOperand, *unsignedOperand;
6794   if (LHS->getType()->hasSignedIntegerRepresentation()) {
6795     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
6796            "unsigned comparison between two signed integer expressions?");
6797     signedOperand = LHS;
6798     unsignedOperand = RHS;
6799   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6800     signedOperand = RHS;
6801     unsignedOperand = LHS;
6802   } else {
6803     CheckTrivialUnsignedComparison(S, E);
6804     return AnalyzeImpConvsInComparison(S, E);
6805   }
6806 
6807   // Otherwise, calculate the effective range of the signed operand.
6808   IntRange signedRange = GetExprRange(S.Context, signedOperand);
6809 
6810   // Go ahead and analyze implicit conversions in the operands.  Note
6811   // that we skip the implicit conversions on both sides.
6812   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6813   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
6814 
6815   // If the signed range is non-negative, -Wsign-compare won't fire,
6816   // but we should still check for comparisons which are always true
6817   // or false.
6818   if (signedRange.NonNegative)
6819     return CheckTrivialUnsignedComparison(S, E);
6820 
6821   // For (in)equality comparisons, if the unsigned operand is a
6822   // constant which cannot collide with a overflowed signed operand,
6823   // then reinterpreting the signed operand as unsigned will not
6824   // change the result of the comparison.
6825   if (E->isEqualityOp()) {
6826     unsigned comparisonWidth = S.Context.getIntWidth(T);
6827     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
6828 
6829     // We should never be unable to prove that the unsigned operand is
6830     // non-negative.
6831     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6832 
6833     if (unsignedRange.Width < comparisonWidth)
6834       return;
6835   }
6836 
6837   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6838     S.PDiag(diag::warn_mixed_sign_comparison)
6839       << LHS->getType() << RHS->getType()
6840       << LHS->getSourceRange() << RHS->getSourceRange());
6841 }
6842 
6843 /// Analyzes an attempt to assign the given value to a bitfield.
6844 ///
6845 /// Returns true if there was something fishy about the attempt.
6846 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6847                                       SourceLocation InitLoc) {
6848   assert(Bitfield->isBitField());
6849   if (Bitfield->isInvalidDecl())
6850     return false;
6851 
6852   // White-list bool bitfields.
6853   if (Bitfield->getType()->isBooleanType())
6854     return false;
6855 
6856   // Ignore value- or type-dependent expressions.
6857   if (Bitfield->getBitWidth()->isValueDependent() ||
6858       Bitfield->getBitWidth()->isTypeDependent() ||
6859       Init->isValueDependent() ||
6860       Init->isTypeDependent())
6861     return false;
6862 
6863   Expr *OriginalInit = Init->IgnoreParenImpCasts();
6864 
6865   llvm::APSInt Value;
6866   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
6867     return false;
6868 
6869   unsigned OriginalWidth = Value.getBitWidth();
6870   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
6871 
6872   if (OriginalWidth <= FieldWidth)
6873     return false;
6874 
6875   // Compute the value which the bitfield will contain.
6876   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6877   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
6878 
6879   // Check whether the stored value is equal to the original value.
6880   TruncatedValue = TruncatedValue.extend(OriginalWidth);
6881   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6882     return false;
6883 
6884   // Special-case bitfields of width 1: booleans are naturally 0/1, and
6885   // therefore don't strictly fit into a signed bitfield of width 1.
6886   if (FieldWidth == 1 && Value == 1)
6887     return false;
6888 
6889   std::string PrettyValue = Value.toString(10);
6890   std::string PrettyTrunc = TruncatedValue.toString(10);
6891 
6892   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6893     << PrettyValue << PrettyTrunc << OriginalInit->getType()
6894     << Init->getSourceRange();
6895 
6896   return true;
6897 }
6898 
6899 /// Analyze the given simple or compound assignment for warning-worthy
6900 /// operations.
6901 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
6902   // Just recurse on the LHS.
6903   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6904 
6905   // We want to recurse on the RHS as normal unless we're assigning to
6906   // a bitfield.
6907   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
6908     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
6909                                   E->getOperatorLoc())) {
6910       // Recurse, ignoring any implicit conversions on the RHS.
6911       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6912                                         E->getOperatorLoc());
6913     }
6914   }
6915 
6916   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6917 }
6918 
6919 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
6920 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
6921                             SourceLocation CContext, unsigned diag,
6922                             bool pruneControlFlow = false) {
6923   if (pruneControlFlow) {
6924     S.DiagRuntimeBehavior(E->getExprLoc(), E,
6925                           S.PDiag(diag)
6926                             << SourceType << T << E->getSourceRange()
6927                             << SourceRange(CContext));
6928     return;
6929   }
6930   S.Diag(E->getExprLoc(), diag)
6931     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6932 }
6933 
6934 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
6935 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
6936                             SourceLocation CContext, unsigned diag,
6937                             bool pruneControlFlow = false) {
6938   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
6939 }
6940 
6941 /// Diagnose an implicit cast from a literal expression. Does not warn when the
6942 /// cast wouldn't lose information.
6943 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6944                                     SourceLocation CContext) {
6945   // Try to convert the literal exactly to an integer. If we can, don't warn.
6946   bool isExact = false;
6947   const llvm::APFloat &Value = FL->getValue();
6948   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6949                             T->hasUnsignedIntegerRepresentation());
6950   if (Value.convertToInteger(IntegerValue,
6951                              llvm::APFloat::rmTowardZero, &isExact)
6952       == llvm::APFloat::opOK && isExact)
6953     return;
6954 
6955   // FIXME: Force the precision of the source value down so we don't print
6956   // digits which are usually useless (we don't really care here if we
6957   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
6958   // would automatically print the shortest representation, but it's a bit
6959   // tricky to implement.
6960   SmallString<16> PrettySourceValue;
6961   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6962   precision = (precision * 59 + 195) / 196;
6963   Value.toString(PrettySourceValue, precision);
6964 
6965   SmallString<16> PrettyTargetValue;
6966   if (T->isSpecificBuiltinType(BuiltinType::Bool))
6967     PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6968   else
6969     IntegerValue.toString(PrettyTargetValue);
6970 
6971   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6972     << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6973     << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
6974 }
6975 
6976 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6977   if (!Range.Width) return "0";
6978 
6979   llvm::APSInt ValueInRange = Value;
6980   ValueInRange.setIsSigned(!Range.NonNegative);
6981   ValueInRange = ValueInRange.trunc(Range.Width);
6982   return ValueInRange.toString(10);
6983 }
6984 
6985 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6986   if (!isa<ImplicitCastExpr>(Ex))
6987     return false;
6988 
6989   Expr *InnerE = Ex->IgnoreParenImpCasts();
6990   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6991   const Type *Source =
6992     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6993   if (Target->isDependentType())
6994     return false;
6995 
6996   const BuiltinType *FloatCandidateBT =
6997     dyn_cast<BuiltinType>(ToBool ? Source : Target);
6998   const Type *BoolCandidateType = ToBool ? Target : Source;
6999 
7000   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7001           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7002 }
7003 
7004 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7005                                       SourceLocation CC) {
7006   unsigned NumArgs = TheCall->getNumArgs();
7007   for (unsigned i = 0; i < NumArgs; ++i) {
7008     Expr *CurrA = TheCall->getArg(i);
7009     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7010       continue;
7011 
7012     bool IsSwapped = ((i > 0) &&
7013         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7014     IsSwapped |= ((i < (NumArgs - 1)) &&
7015         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7016     if (IsSwapped) {
7017       // Warn on this floating-point to bool conversion.
7018       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7019                       CurrA->getType(), CC,
7020                       diag::warn_impcast_floating_point_to_bool);
7021     }
7022   }
7023 }
7024 
7025 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
7026                                    SourceLocation CC) {
7027   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7028                         E->getExprLoc()))
7029     return;
7030 
7031   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7032   const Expr::NullPointerConstantKind NullKind =
7033       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7034   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7035     return;
7036 
7037   // Return if target type is a safe conversion.
7038   if (T->isAnyPointerType() || T->isBlockPointerType() ||
7039       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7040     return;
7041 
7042   SourceLocation Loc = E->getSourceRange().getBegin();
7043 
7044   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
7045   if (NullKind == Expr::NPCK_GNUNull) {
7046     if (Loc.isMacroID())
7047       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7048   }
7049 
7050   // Only warn if the null and context location are in the same macro expansion.
7051   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7052     return;
7053 
7054   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7055       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7056       << FixItHint::CreateReplacement(Loc,
7057                                       S.getFixItZeroLiteralForType(T, Loc));
7058 }
7059 
7060 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7061                                   ObjCArrayLiteral *ArrayLiteral);
7062 static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7063                                        ObjCDictionaryLiteral *DictionaryLiteral);
7064 
7065 /// Check a single element within a collection literal against the
7066 /// target element type.
7067 static void checkObjCCollectionLiteralElement(Sema &S,
7068                                               QualType TargetElementType,
7069                                               Expr *Element,
7070                                               unsigned ElementKind) {
7071   // Skip a bitcast to 'id' or qualified 'id'.
7072   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7073     if (ICE->getCastKind() == CK_BitCast &&
7074         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7075       Element = ICE->getSubExpr();
7076   }
7077 
7078   QualType ElementType = Element->getType();
7079   ExprResult ElementResult(Element);
7080   if (ElementType->getAs<ObjCObjectPointerType>() &&
7081       S.CheckSingleAssignmentConstraints(TargetElementType,
7082                                          ElementResult,
7083                                          false, false)
7084         != Sema::Compatible) {
7085     S.Diag(Element->getLocStart(),
7086            diag::warn_objc_collection_literal_element)
7087       << ElementType << ElementKind << TargetElementType
7088       << Element->getSourceRange();
7089   }
7090 
7091   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7092     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7093   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7094     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7095 }
7096 
7097 /// Check an Objective-C array literal being converted to the given
7098 /// target type.
7099 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7100                                   ObjCArrayLiteral *ArrayLiteral) {
7101   if (!S.NSArrayDecl)
7102     return;
7103 
7104   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7105   if (!TargetObjCPtr)
7106     return;
7107 
7108   if (TargetObjCPtr->isUnspecialized() ||
7109       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7110         != S.NSArrayDecl->getCanonicalDecl())
7111     return;
7112 
7113   auto TypeArgs = TargetObjCPtr->getTypeArgs();
7114   if (TypeArgs.size() != 1)
7115     return;
7116 
7117   QualType TargetElementType = TypeArgs[0];
7118   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7119     checkObjCCollectionLiteralElement(S, TargetElementType,
7120                                       ArrayLiteral->getElement(I),
7121                                       0);
7122   }
7123 }
7124 
7125 /// Check an Objective-C dictionary literal being converted to the given
7126 /// target type.
7127 static void checkObjCDictionaryLiteral(
7128               Sema &S, QualType TargetType,
7129               ObjCDictionaryLiteral *DictionaryLiteral) {
7130   if (!S.NSDictionaryDecl)
7131     return;
7132 
7133   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7134   if (!TargetObjCPtr)
7135     return;
7136 
7137   if (TargetObjCPtr->isUnspecialized() ||
7138       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7139         != S.NSDictionaryDecl->getCanonicalDecl())
7140     return;
7141 
7142   auto TypeArgs = TargetObjCPtr->getTypeArgs();
7143   if (TypeArgs.size() != 2)
7144     return;
7145 
7146   QualType TargetKeyType = TypeArgs[0];
7147   QualType TargetObjectType = TypeArgs[1];
7148   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7149     auto Element = DictionaryLiteral->getKeyValueElement(I);
7150     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7151     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7152   }
7153 }
7154 
7155 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
7156                              SourceLocation CC, bool *ICContext = nullptr) {
7157   if (E->isTypeDependent() || E->isValueDependent()) return;
7158 
7159   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7160   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7161   if (Source == Target) return;
7162   if (Target->isDependentType()) return;
7163 
7164   // If the conversion context location is invalid don't complain. We also
7165   // don't want to emit a warning if the issue occurs from the expansion of
7166   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7167   // delay this check as long as possible. Once we detect we are in that
7168   // scenario, we just return.
7169   if (CC.isInvalid())
7170     return;
7171 
7172   // Diagnose implicit casts to bool.
7173   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7174     if (isa<StringLiteral>(E))
7175       // Warn on string literal to bool.  Checks for string literals in logical
7176       // and expressions, for instance, assert(0 && "error here"), are
7177       // prevented by a check in AnalyzeImplicitConversions().
7178       return DiagnoseImpCast(S, E, T, CC,
7179                              diag::warn_impcast_string_literal_to_bool);
7180     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7181         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7182       // This covers the literal expressions that evaluate to Objective-C
7183       // objects.
7184       return DiagnoseImpCast(S, E, T, CC,
7185                              diag::warn_impcast_objective_c_literal_to_bool);
7186     }
7187     if (Source->isPointerType() || Source->canDecayToPointerType()) {
7188       // Warn on pointer to bool conversion that is always true.
7189       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7190                                      SourceRange(CC));
7191     }
7192   }
7193 
7194   // Check implicit casts from Objective-C collection literals to specialized
7195   // collection types, e.g., NSArray<NSString *> *.
7196   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7197     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7198   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7199     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7200 
7201   // Strip vector types.
7202   if (isa<VectorType>(Source)) {
7203     if (!isa<VectorType>(Target)) {
7204       if (S.SourceMgr.isInSystemMacro(CC))
7205         return;
7206       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
7207     }
7208 
7209     // If the vector cast is cast between two vectors of the same size, it is
7210     // a bitcast, not a conversion.
7211     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7212       return;
7213 
7214     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7215     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7216   }
7217   if (auto VecTy = dyn_cast<VectorType>(Target))
7218     Target = VecTy->getElementType().getTypePtr();
7219 
7220   // Strip complex types.
7221   if (isa<ComplexType>(Source)) {
7222     if (!isa<ComplexType>(Target)) {
7223       if (S.SourceMgr.isInSystemMacro(CC))
7224         return;
7225 
7226       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
7227     }
7228 
7229     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7230     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7231   }
7232 
7233   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7234   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7235 
7236   // If the source is floating point...
7237   if (SourceBT && SourceBT->isFloatingPoint()) {
7238     // ...and the target is floating point...
7239     if (TargetBT && TargetBT->isFloatingPoint()) {
7240       // ...then warn if we're dropping FP rank.
7241 
7242       // Builtin FP kinds are ordered by increasing FP rank.
7243       if (SourceBT->getKind() > TargetBT->getKind()) {
7244         // Don't warn about float constants that are precisely
7245         // representable in the target type.
7246         Expr::EvalResult result;
7247         if (E->EvaluateAsRValue(result, S.Context)) {
7248           // Value might be a float, a float vector, or a float complex.
7249           if (IsSameFloatAfterCast(result.Val,
7250                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7251                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
7252             return;
7253         }
7254 
7255         if (S.SourceMgr.isInSystemMacro(CC))
7256           return;
7257 
7258         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
7259 
7260       }
7261       // ... or possibly if we're increasing rank, too
7262       else if (TargetBT->getKind() > SourceBT->getKind()) {
7263         if (S.SourceMgr.isInSystemMacro(CC))
7264           return;
7265 
7266         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
7267       }
7268       return;
7269     }
7270 
7271     // If the target is integral, always warn.
7272     if (TargetBT && TargetBT->isInteger()) {
7273       if (S.SourceMgr.isInSystemMacro(CC))
7274         return;
7275 
7276       Expr *InnerE = E->IgnoreParenImpCasts();
7277       // We also want to warn on, e.g., "int i = -1.234"
7278       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7279         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7280           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7281 
7282       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7283         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
7284       } else {
7285         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7286       }
7287     }
7288 
7289     // If the target is bool, warn if expr is a function or method call.
7290     if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7291         isa<CallExpr>(E)) {
7292       // Check last argument of function call to see if it is an
7293       // implicit cast from a type matching the type the result
7294       // is being cast to.
7295       CallExpr *CEx = cast<CallExpr>(E);
7296       unsigned NumArgs = CEx->getNumArgs();
7297       if (NumArgs > 0) {
7298         Expr *LastA = CEx->getArg(NumArgs - 1);
7299         Expr *InnerE = LastA->IgnoreParenImpCasts();
7300         const Type *InnerType =
7301           S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7302         if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7303           // Warn on this floating-point to bool conversion
7304           DiagnoseImpCast(S, E, T, CC,
7305                           diag::warn_impcast_floating_point_to_bool);
7306         }
7307       }
7308     }
7309     return;
7310   }
7311 
7312   DiagnoseNullConversion(S, E, T, CC);
7313 
7314   if (!Source->isIntegerType() || !Target->isIntegerType())
7315     return;
7316 
7317   // TODO: remove this early return once the false positives for constant->bool
7318   // in templates, macros, etc, are reduced or removed.
7319   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7320     return;
7321 
7322   IntRange SourceRange = GetExprRange(S.Context, E);
7323   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
7324 
7325   if (SourceRange.Width > TargetRange.Width) {
7326     // If the source is a constant, use a default-on diagnostic.
7327     // TODO: this should happen for bitfield stores, too.
7328     llvm::APSInt Value(32);
7329     if (E->isIntegerConstantExpr(Value, S.Context)) {
7330       if (S.SourceMgr.isInSystemMacro(CC))
7331         return;
7332 
7333       std::string PrettySourceValue = Value.toString(10);
7334       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
7335 
7336       S.DiagRuntimeBehavior(E->getExprLoc(), E,
7337         S.PDiag(diag::warn_impcast_integer_precision_constant)
7338             << PrettySourceValue << PrettyTargetValue
7339             << E->getType() << T << E->getSourceRange()
7340             << clang::SourceRange(CC));
7341       return;
7342     }
7343 
7344     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7345     if (S.SourceMgr.isInSystemMacro(CC))
7346       return;
7347 
7348     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
7349       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7350                              /* pruneControlFlow */ true);
7351     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
7352   }
7353 
7354   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7355       (!TargetRange.NonNegative && SourceRange.NonNegative &&
7356        SourceRange.Width == TargetRange.Width)) {
7357 
7358     if (S.SourceMgr.isInSystemMacro(CC))
7359       return;
7360 
7361     unsigned DiagID = diag::warn_impcast_integer_sign;
7362 
7363     // Traditionally, gcc has warned about this under -Wsign-compare.
7364     // We also want to warn about it in -Wconversion.
7365     // So if -Wconversion is off, use a completely identical diagnostic
7366     // in the sign-compare group.
7367     // The conditional-checking code will
7368     if (ICContext) {
7369       DiagID = diag::warn_impcast_integer_sign_conditional;
7370       *ICContext = true;
7371     }
7372 
7373     return DiagnoseImpCast(S, E, T, CC, DiagID);
7374   }
7375 
7376   // Diagnose conversions between different enumeration types.
7377   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7378   // type, to give us better diagnostics.
7379   QualType SourceType = E->getType();
7380   if (!S.getLangOpts().CPlusPlus) {
7381     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7382       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7383         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7384         SourceType = S.Context.getTypeDeclType(Enum);
7385         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7386       }
7387   }
7388 
7389   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7390     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
7391       if (SourceEnum->getDecl()->hasNameForLinkage() &&
7392           TargetEnum->getDecl()->hasNameForLinkage() &&
7393           SourceEnum != TargetEnum) {
7394         if (S.SourceMgr.isInSystemMacro(CC))
7395           return;
7396 
7397         return DiagnoseImpCast(S, E, SourceType, T, CC,
7398                                diag::warn_impcast_different_enum_types);
7399       }
7400 
7401   return;
7402 }
7403 
7404 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7405                               SourceLocation CC, QualType T);
7406 
7407 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
7408                              SourceLocation CC, bool &ICContext) {
7409   E = E->IgnoreParenImpCasts();
7410 
7411   if (isa<ConditionalOperator>(E))
7412     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
7413 
7414   AnalyzeImplicitConversions(S, E, CC);
7415   if (E->getType() != T)
7416     return CheckImplicitConversion(S, E, T, CC, &ICContext);
7417   return;
7418 }
7419 
7420 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7421                               SourceLocation CC, QualType T) {
7422   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
7423 
7424   bool Suspicious = false;
7425   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7426   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
7427 
7428   // If -Wconversion would have warned about either of the candidates
7429   // for a signedness conversion to the context type...
7430   if (!Suspicious) return;
7431 
7432   // ...but it's currently ignored...
7433   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
7434     return;
7435 
7436   // ...then check whether it would have warned about either of the
7437   // candidates for a signedness conversion to the condition type.
7438   if (E->getType() == T) return;
7439 
7440   Suspicious = false;
7441   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7442                           E->getType(), CC, &Suspicious);
7443   if (!Suspicious)
7444     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
7445                             E->getType(), CC, &Suspicious);
7446 }
7447 
7448 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7449 /// Input argument E is a logical expression.
7450 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7451   if (S.getLangOpts().Bool)
7452     return;
7453   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7454 }
7455 
7456 /// AnalyzeImplicitConversions - Find and report any interesting
7457 /// implicit conversions in the given expression.  There are a couple
7458 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
7459 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
7460   QualType T = OrigE->getType();
7461   Expr *E = OrigE->IgnoreParenImpCasts();
7462 
7463   if (E->isTypeDependent() || E->isValueDependent())
7464     return;
7465 
7466   // For conditional operators, we analyze the arguments as if they
7467   // were being fed directly into the output.
7468   if (isa<ConditionalOperator>(E)) {
7469     ConditionalOperator *CO = cast<ConditionalOperator>(E);
7470     CheckConditionalOperator(S, CO, CC, T);
7471     return;
7472   }
7473 
7474   // Check implicit argument conversions for function calls.
7475   if (CallExpr *Call = dyn_cast<CallExpr>(E))
7476     CheckImplicitArgumentConversions(S, Call, CC);
7477 
7478   // Go ahead and check any implicit conversions we might have skipped.
7479   // The non-canonical typecheck is just an optimization;
7480   // CheckImplicitConversion will filter out dead implicit conversions.
7481   if (E->getType() != T)
7482     CheckImplicitConversion(S, E, T, CC);
7483 
7484   // Now continue drilling into this expression.
7485 
7486   if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
7487     if (POE->getResultExpr())
7488       E = POE->getResultExpr();
7489   }
7490 
7491   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7492     if (OVE->getSourceExpr())
7493       AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7494     return;
7495   }
7496 
7497   // Skip past explicit casts.
7498   if (isa<ExplicitCastExpr>(E)) {
7499     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
7500     return AnalyzeImplicitConversions(S, E, CC);
7501   }
7502 
7503   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7504     // Do a somewhat different check with comparison operators.
7505     if (BO->isComparisonOp())
7506       return AnalyzeComparison(S, BO);
7507 
7508     // And with simple assignments.
7509     if (BO->getOpcode() == BO_Assign)
7510       return AnalyzeAssignment(S, BO);
7511   }
7512 
7513   // These break the otherwise-useful invariant below.  Fortunately,
7514   // we don't really need to recurse into them, because any internal
7515   // expressions should have been analyzed already when they were
7516   // built into statements.
7517   if (isa<StmtExpr>(E)) return;
7518 
7519   // Don't descend into unevaluated contexts.
7520   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
7521 
7522   // Now just recurse over the expression's children.
7523   CC = E->getExprLoc();
7524   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
7525   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
7526   for (Stmt *SubStmt : E->children()) {
7527     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
7528     if (!ChildExpr)
7529       continue;
7530 
7531     if (IsLogicalAndOperator &&
7532         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
7533       // Ignore checking string literals that are in logical and operators.
7534       // This is a common pattern for asserts.
7535       continue;
7536     AnalyzeImplicitConversions(S, ChildExpr, CC);
7537   }
7538 
7539   if (BO && BO->isLogicalOp()) {
7540     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7541     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7542       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
7543 
7544     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7545     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7546       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
7547   }
7548 
7549   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7550     if (U->getOpcode() == UO_LNot)
7551       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
7552 }
7553 
7554 } // end anonymous namespace
7555 
7556 enum {
7557   AddressOf,
7558   FunctionPointer,
7559   ArrayPointer
7560 };
7561 
7562 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7563 // Returns true when emitting a warning about taking the address of a reference.
7564 static bool CheckForReference(Sema &SemaRef, const Expr *E,
7565                               PartialDiagnostic PD) {
7566   E = E->IgnoreParenImpCasts();
7567 
7568   const FunctionDecl *FD = nullptr;
7569 
7570   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7571     if (!DRE->getDecl()->getType()->isReferenceType())
7572       return false;
7573   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7574     if (!M->getMemberDecl()->getType()->isReferenceType())
7575       return false;
7576   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
7577     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
7578       return false;
7579     FD = Call->getDirectCallee();
7580   } else {
7581     return false;
7582   }
7583 
7584   SemaRef.Diag(E->getExprLoc(), PD);
7585 
7586   // If possible, point to location of function.
7587   if (FD) {
7588     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7589   }
7590 
7591   return true;
7592 }
7593 
7594 // Returns true if the SourceLocation is expanded from any macro body.
7595 // Returns false if the SourceLocation is invalid, is from not in a macro
7596 // expansion, or is from expanded from a top-level macro argument.
7597 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7598   if (Loc.isInvalid())
7599     return false;
7600 
7601   while (Loc.isMacroID()) {
7602     if (SM.isMacroBodyExpansion(Loc))
7603       return true;
7604     Loc = SM.getImmediateMacroCallerLoc(Loc);
7605   }
7606 
7607   return false;
7608 }
7609 
7610 /// \brief Diagnose pointers that are always non-null.
7611 /// \param E the expression containing the pointer
7612 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7613 /// compared to a null pointer
7614 /// \param IsEqual True when the comparison is equal to a null pointer
7615 /// \param Range Extra SourceRange to highlight in the diagnostic
7616 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7617                                         Expr::NullPointerConstantKind NullKind,
7618                                         bool IsEqual, SourceRange Range) {
7619   if (!E)
7620     return;
7621 
7622   // Don't warn inside macros.
7623   if (E->getExprLoc().isMacroID()) {
7624     const SourceManager &SM = getSourceManager();
7625     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7626         IsInAnyMacroBody(SM, Range.getBegin()))
7627       return;
7628   }
7629   E = E->IgnoreImpCasts();
7630 
7631   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7632 
7633   if (isa<CXXThisExpr>(E)) {
7634     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7635                                 : diag::warn_this_bool_conversion;
7636     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7637     return;
7638   }
7639 
7640   bool IsAddressOf = false;
7641 
7642   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7643     if (UO->getOpcode() != UO_AddrOf)
7644       return;
7645     IsAddressOf = true;
7646     E = UO->getSubExpr();
7647   }
7648 
7649   if (IsAddressOf) {
7650     unsigned DiagID = IsCompare
7651                           ? diag::warn_address_of_reference_null_compare
7652                           : diag::warn_address_of_reference_bool_conversion;
7653     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7654                                          << IsEqual;
7655     if (CheckForReference(*this, E, PD)) {
7656       return;
7657     }
7658   }
7659 
7660   // Expect to find a single Decl.  Skip anything more complicated.
7661   ValueDecl *D = nullptr;
7662   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7663     D = R->getDecl();
7664   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7665     D = M->getMemberDecl();
7666   }
7667 
7668   // Weak Decls can be null.
7669   if (!D || D->isWeak())
7670     return;
7671 
7672   // Check for parameter decl with nonnull attribute
7673   if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7674     if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7675       if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7676         unsigned NumArgs = FD->getNumParams();
7677         llvm::SmallBitVector AttrNonNull(NumArgs);
7678         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7679           if (!NonNull->args_size()) {
7680             AttrNonNull.set(0, NumArgs);
7681             break;
7682           }
7683           for (unsigned Val : NonNull->args()) {
7684             if (Val >= NumArgs)
7685               continue;
7686             AttrNonNull.set(Val);
7687           }
7688         }
7689         if (!AttrNonNull.empty())
7690           for (unsigned i = 0; i < NumArgs; ++i)
7691             if (FD->getParamDecl(i) == PV &&
7692                 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
7693               std::string Str;
7694               llvm::raw_string_ostream S(Str);
7695               E->printPretty(S, nullptr, getPrintingPolicy());
7696               unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7697                                           : diag::warn_cast_nonnull_to_bool;
7698               Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7699                 << Range << IsEqual;
7700               return;
7701             }
7702       }
7703     }
7704 
7705   QualType T = D->getType();
7706   const bool IsArray = T->isArrayType();
7707   const bool IsFunction = T->isFunctionType();
7708 
7709   // Address of function is used to silence the function warning.
7710   if (IsAddressOf && IsFunction) {
7711     return;
7712   }
7713 
7714   // Found nothing.
7715   if (!IsAddressOf && !IsFunction && !IsArray)
7716     return;
7717 
7718   // Pretty print the expression for the diagnostic.
7719   std::string Str;
7720   llvm::raw_string_ostream S(Str);
7721   E->printPretty(S, nullptr, getPrintingPolicy());
7722 
7723   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7724                               : diag::warn_impcast_pointer_to_bool;
7725   unsigned DiagType;
7726   if (IsAddressOf)
7727     DiagType = AddressOf;
7728   else if (IsFunction)
7729     DiagType = FunctionPointer;
7730   else if (IsArray)
7731     DiagType = ArrayPointer;
7732   else
7733     llvm_unreachable("Could not determine diagnostic.");
7734   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7735                                 << Range << IsEqual;
7736 
7737   if (!IsFunction)
7738     return;
7739 
7740   // Suggest '&' to silence the function warning.
7741   Diag(E->getExprLoc(), diag::note_function_warning_silence)
7742       << FixItHint::CreateInsertion(E->getLocStart(), "&");
7743 
7744   // Check to see if '()' fixit should be emitted.
7745   QualType ReturnType;
7746   UnresolvedSet<4> NonTemplateOverloads;
7747   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7748   if (ReturnType.isNull())
7749     return;
7750 
7751   if (IsCompare) {
7752     // There are two cases here.  If there is null constant, the only suggest
7753     // for a pointer return type.  If the null is 0, then suggest if the return
7754     // type is a pointer or an integer type.
7755     if (!ReturnType->isPointerType()) {
7756       if (NullKind == Expr::NPCK_ZeroExpression ||
7757           NullKind == Expr::NPCK_ZeroLiteral) {
7758         if (!ReturnType->isIntegerType())
7759           return;
7760       } else {
7761         return;
7762       }
7763     }
7764   } else { // !IsCompare
7765     // For function to bool, only suggest if the function pointer has bool
7766     // return type.
7767     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7768       return;
7769   }
7770   Diag(E->getExprLoc(), diag::note_function_to_function_call)
7771       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
7772 }
7773 
7774 
7775 /// Diagnoses "dangerous" implicit conversions within the given
7776 /// expression (which is a full expression).  Implements -Wconversion
7777 /// and -Wsign-compare.
7778 ///
7779 /// \param CC the "context" location of the implicit conversion, i.e.
7780 ///   the most location of the syntactic entity requiring the implicit
7781 ///   conversion
7782 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
7783   // Don't diagnose in unevaluated contexts.
7784   if (isUnevaluatedContext())
7785     return;
7786 
7787   // Don't diagnose for value- or type-dependent expressions.
7788   if (E->isTypeDependent() || E->isValueDependent())
7789     return;
7790 
7791   // Check for array bounds violations in cases where the check isn't triggered
7792   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7793   // ArraySubscriptExpr is on the RHS of a variable initialization.
7794   CheckArrayAccess(E);
7795 
7796   // This is not the right CC for (e.g.) a variable initialization.
7797   AnalyzeImplicitConversions(*this, E, CC);
7798 }
7799 
7800 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7801 /// Input argument E is a logical expression.
7802 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7803   ::CheckBoolLikeConversion(*this, E, CC);
7804 }
7805 
7806 /// Diagnose when expression is an integer constant expression and its evaluation
7807 /// results in integer overflow
7808 void Sema::CheckForIntOverflow (Expr *E) {
7809   if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7810     E->IgnoreParenCasts()->EvaluateForOverflow(Context);
7811 }
7812 
7813 namespace {
7814 /// \brief Visitor for expressions which looks for unsequenced operations on the
7815 /// same object.
7816 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
7817   typedef EvaluatedExprVisitor<SequenceChecker> Base;
7818 
7819   /// \brief A tree of sequenced regions within an expression. Two regions are
7820   /// unsequenced if one is an ancestor or a descendent of the other. When we
7821   /// finish processing an expression with sequencing, such as a comma
7822   /// expression, we fold its tree nodes into its parent, since they are
7823   /// unsequenced with respect to nodes we will visit later.
7824   class SequenceTree {
7825     struct Value {
7826       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7827       unsigned Parent : 31;
7828       bool Merged : 1;
7829     };
7830     SmallVector<Value, 8> Values;
7831 
7832   public:
7833     /// \brief A region within an expression which may be sequenced with respect
7834     /// to some other region.
7835     class Seq {
7836       explicit Seq(unsigned N) : Index(N) {}
7837       unsigned Index;
7838       friend class SequenceTree;
7839     public:
7840       Seq() : Index(0) {}
7841     };
7842 
7843     SequenceTree() { Values.push_back(Value(0)); }
7844     Seq root() const { return Seq(0); }
7845 
7846     /// \brief Create a new sequence of operations, which is an unsequenced
7847     /// subset of \p Parent. This sequence of operations is sequenced with
7848     /// respect to other children of \p Parent.
7849     Seq allocate(Seq Parent) {
7850       Values.push_back(Value(Parent.Index));
7851       return Seq(Values.size() - 1);
7852     }
7853 
7854     /// \brief Merge a sequence of operations into its parent.
7855     void merge(Seq S) {
7856       Values[S.Index].Merged = true;
7857     }
7858 
7859     /// \brief Determine whether two operations are unsequenced. This operation
7860     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7861     /// should have been merged into its parent as appropriate.
7862     bool isUnsequenced(Seq Cur, Seq Old) {
7863       unsigned C = representative(Cur.Index);
7864       unsigned Target = representative(Old.Index);
7865       while (C >= Target) {
7866         if (C == Target)
7867           return true;
7868         C = Values[C].Parent;
7869       }
7870       return false;
7871     }
7872 
7873   private:
7874     /// \brief Pick a representative for a sequence.
7875     unsigned representative(unsigned K) {
7876       if (Values[K].Merged)
7877         // Perform path compression as we go.
7878         return Values[K].Parent = representative(Values[K].Parent);
7879       return K;
7880     }
7881   };
7882 
7883   /// An object for which we can track unsequenced uses.
7884   typedef NamedDecl *Object;
7885 
7886   /// Different flavors of object usage which we track. We only track the
7887   /// least-sequenced usage of each kind.
7888   enum UsageKind {
7889     /// A read of an object. Multiple unsequenced reads are OK.
7890     UK_Use,
7891     /// A modification of an object which is sequenced before the value
7892     /// computation of the expression, such as ++n in C++.
7893     UK_ModAsValue,
7894     /// A modification of an object which is not sequenced before the value
7895     /// computation of the expression, such as n++.
7896     UK_ModAsSideEffect,
7897 
7898     UK_Count = UK_ModAsSideEffect + 1
7899   };
7900 
7901   struct Usage {
7902     Usage() : Use(nullptr), Seq() {}
7903     Expr *Use;
7904     SequenceTree::Seq Seq;
7905   };
7906 
7907   struct UsageInfo {
7908     UsageInfo() : Diagnosed(false) {}
7909     Usage Uses[UK_Count];
7910     /// Have we issued a diagnostic for this variable already?
7911     bool Diagnosed;
7912   };
7913   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7914 
7915   Sema &SemaRef;
7916   /// Sequenced regions within the expression.
7917   SequenceTree Tree;
7918   /// Declaration modifications and references which we have seen.
7919   UsageInfoMap UsageMap;
7920   /// The region we are currently within.
7921   SequenceTree::Seq Region;
7922   /// Filled in with declarations which were modified as a side-effect
7923   /// (that is, post-increment operations).
7924   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7925   /// Expressions to check later. We defer checking these to reduce
7926   /// stack usage.
7927   SmallVectorImpl<Expr *> &WorkList;
7928 
7929   /// RAII object wrapping the visitation of a sequenced subexpression of an
7930   /// expression. At the end of this process, the side-effects of the evaluation
7931   /// become sequenced with respect to the value computation of the result, so
7932   /// we downgrade any UK_ModAsSideEffect within the evaluation to
7933   /// UK_ModAsValue.
7934   struct SequencedSubexpression {
7935     SequencedSubexpression(SequenceChecker &Self)
7936       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7937       Self.ModAsSideEffect = &ModAsSideEffect;
7938     }
7939     ~SequencedSubexpression() {
7940       for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7941            MI != ME; ++MI) {
7942         UsageInfo &U = Self.UsageMap[MI->first];
7943         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7944         Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7945         SideEffectUsage = MI->second;
7946       }
7947       Self.ModAsSideEffect = OldModAsSideEffect;
7948     }
7949 
7950     SequenceChecker &Self;
7951     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7952     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
7953   };
7954 
7955   /// RAII object wrapping the visitation of a subexpression which we might
7956   /// choose to evaluate as a constant. If any subexpression is evaluated and
7957   /// found to be non-constant, this allows us to suppress the evaluation of
7958   /// the outer expression.
7959   class EvaluationTracker {
7960   public:
7961     EvaluationTracker(SequenceChecker &Self)
7962         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7963       Self.EvalTracker = this;
7964     }
7965     ~EvaluationTracker() {
7966       Self.EvalTracker = Prev;
7967       if (Prev)
7968         Prev->EvalOK &= EvalOK;
7969     }
7970 
7971     bool evaluate(const Expr *E, bool &Result) {
7972       if (!EvalOK || E->isValueDependent())
7973         return false;
7974       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7975       return EvalOK;
7976     }
7977 
7978   private:
7979     SequenceChecker &Self;
7980     EvaluationTracker *Prev;
7981     bool EvalOK;
7982   } *EvalTracker;
7983 
7984   /// \brief Find the object which is produced by the specified expression,
7985   /// if any.
7986   Object getObject(Expr *E, bool Mod) const {
7987     E = E->IgnoreParenCasts();
7988     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7989       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7990         return getObject(UO->getSubExpr(), Mod);
7991     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7992       if (BO->getOpcode() == BO_Comma)
7993         return getObject(BO->getRHS(), Mod);
7994       if (Mod && BO->isAssignmentOp())
7995         return getObject(BO->getLHS(), Mod);
7996     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7997       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7998       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7999         return ME->getMemberDecl();
8000     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8001       // FIXME: If this is a reference, map through to its value.
8002       return DRE->getDecl();
8003     return nullptr;
8004   }
8005 
8006   /// \brief Note that an object was modified or used by an expression.
8007   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8008     Usage &U = UI.Uses[UK];
8009     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8010       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8011         ModAsSideEffect->push_back(std::make_pair(O, U));
8012       U.Use = Ref;
8013       U.Seq = Region;
8014     }
8015   }
8016   /// \brief Check whether a modification or use conflicts with a prior usage.
8017   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8018                   bool IsModMod) {
8019     if (UI.Diagnosed)
8020       return;
8021 
8022     const Usage &U = UI.Uses[OtherKind];
8023     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8024       return;
8025 
8026     Expr *Mod = U.Use;
8027     Expr *ModOrUse = Ref;
8028     if (OtherKind == UK_Use)
8029       std::swap(Mod, ModOrUse);
8030 
8031     SemaRef.Diag(Mod->getExprLoc(),
8032                  IsModMod ? diag::warn_unsequenced_mod_mod
8033                           : diag::warn_unsequenced_mod_use)
8034       << O << SourceRange(ModOrUse->getExprLoc());
8035     UI.Diagnosed = true;
8036   }
8037 
8038   void notePreUse(Object O, Expr *Use) {
8039     UsageInfo &U = UsageMap[O];
8040     // Uses conflict with other modifications.
8041     checkUsage(O, U, Use, UK_ModAsValue, false);
8042   }
8043   void notePostUse(Object O, Expr *Use) {
8044     UsageInfo &U = UsageMap[O];
8045     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8046     addUsage(U, O, Use, UK_Use);
8047   }
8048 
8049   void notePreMod(Object O, Expr *Mod) {
8050     UsageInfo &U = UsageMap[O];
8051     // Modifications conflict with other modifications and with uses.
8052     checkUsage(O, U, Mod, UK_ModAsValue, true);
8053     checkUsage(O, U, Mod, UK_Use, false);
8054   }
8055   void notePostMod(Object O, Expr *Use, UsageKind UK) {
8056     UsageInfo &U = UsageMap[O];
8057     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8058     addUsage(U, O, Use, UK);
8059   }
8060 
8061 public:
8062   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
8063       : Base(S.Context), SemaRef(S), Region(Tree.root()),
8064         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
8065     Visit(E);
8066   }
8067 
8068   void VisitStmt(Stmt *S) {
8069     // Skip all statements which aren't expressions for now.
8070   }
8071 
8072   void VisitExpr(Expr *E) {
8073     // By default, just recurse to evaluated subexpressions.
8074     Base::VisitStmt(E);
8075   }
8076 
8077   void VisitCastExpr(CastExpr *E) {
8078     Object O = Object();
8079     if (E->getCastKind() == CK_LValueToRValue)
8080       O = getObject(E->getSubExpr(), false);
8081 
8082     if (O)
8083       notePreUse(O, E);
8084     VisitExpr(E);
8085     if (O)
8086       notePostUse(O, E);
8087   }
8088 
8089   void VisitBinComma(BinaryOperator *BO) {
8090     // C++11 [expr.comma]p1:
8091     //   Every value computation and side effect associated with the left
8092     //   expression is sequenced before every value computation and side
8093     //   effect associated with the right expression.
8094     SequenceTree::Seq LHS = Tree.allocate(Region);
8095     SequenceTree::Seq RHS = Tree.allocate(Region);
8096     SequenceTree::Seq OldRegion = Region;
8097 
8098     {
8099       SequencedSubexpression SeqLHS(*this);
8100       Region = LHS;
8101       Visit(BO->getLHS());
8102     }
8103 
8104     Region = RHS;
8105     Visit(BO->getRHS());
8106 
8107     Region = OldRegion;
8108 
8109     // Forget that LHS and RHS are sequenced. They are both unsequenced
8110     // with respect to other stuff.
8111     Tree.merge(LHS);
8112     Tree.merge(RHS);
8113   }
8114 
8115   void VisitBinAssign(BinaryOperator *BO) {
8116     // The modification is sequenced after the value computation of the LHS
8117     // and RHS, so check it before inspecting the operands and update the
8118     // map afterwards.
8119     Object O = getObject(BO->getLHS(), true);
8120     if (!O)
8121       return VisitExpr(BO);
8122 
8123     notePreMod(O, BO);
8124 
8125     // C++11 [expr.ass]p7:
8126     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8127     //   only once.
8128     //
8129     // Therefore, for a compound assignment operator, O is considered used
8130     // everywhere except within the evaluation of E1 itself.
8131     if (isa<CompoundAssignOperator>(BO))
8132       notePreUse(O, BO);
8133 
8134     Visit(BO->getLHS());
8135 
8136     if (isa<CompoundAssignOperator>(BO))
8137       notePostUse(O, BO);
8138 
8139     Visit(BO->getRHS());
8140 
8141     // C++11 [expr.ass]p1:
8142     //   the assignment is sequenced [...] before the value computation of the
8143     //   assignment expression.
8144     // C11 6.5.16/3 has no such rule.
8145     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8146                                                        : UK_ModAsSideEffect);
8147   }
8148   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8149     VisitBinAssign(CAO);
8150   }
8151 
8152   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8153   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8154   void VisitUnaryPreIncDec(UnaryOperator *UO) {
8155     Object O = getObject(UO->getSubExpr(), true);
8156     if (!O)
8157       return VisitExpr(UO);
8158 
8159     notePreMod(O, UO);
8160     Visit(UO->getSubExpr());
8161     // C++11 [expr.pre.incr]p1:
8162     //   the expression ++x is equivalent to x+=1
8163     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8164                                                        : UK_ModAsSideEffect);
8165   }
8166 
8167   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8168   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8169   void VisitUnaryPostIncDec(UnaryOperator *UO) {
8170     Object O = getObject(UO->getSubExpr(), true);
8171     if (!O)
8172       return VisitExpr(UO);
8173 
8174     notePreMod(O, UO);
8175     Visit(UO->getSubExpr());
8176     notePostMod(O, UO, UK_ModAsSideEffect);
8177   }
8178 
8179   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8180   void VisitBinLOr(BinaryOperator *BO) {
8181     // The side-effects of the LHS of an '&&' are sequenced before the
8182     // value computation of the RHS, and hence before the value computation
8183     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8184     // as if they were unconditionally sequenced.
8185     EvaluationTracker Eval(*this);
8186     {
8187       SequencedSubexpression Sequenced(*this);
8188       Visit(BO->getLHS());
8189     }
8190 
8191     bool Result;
8192     if (Eval.evaluate(BO->getLHS(), Result)) {
8193       if (!Result)
8194         Visit(BO->getRHS());
8195     } else {
8196       // Check for unsequenced operations in the RHS, treating it as an
8197       // entirely separate evaluation.
8198       //
8199       // FIXME: If there are operations in the RHS which are unsequenced
8200       // with respect to operations outside the RHS, and those operations
8201       // are unconditionally evaluated, diagnose them.
8202       WorkList.push_back(BO->getRHS());
8203     }
8204   }
8205   void VisitBinLAnd(BinaryOperator *BO) {
8206     EvaluationTracker Eval(*this);
8207     {
8208       SequencedSubexpression Sequenced(*this);
8209       Visit(BO->getLHS());
8210     }
8211 
8212     bool Result;
8213     if (Eval.evaluate(BO->getLHS(), Result)) {
8214       if (Result)
8215         Visit(BO->getRHS());
8216     } else {
8217       WorkList.push_back(BO->getRHS());
8218     }
8219   }
8220 
8221   // Only visit the condition, unless we can be sure which subexpression will
8222   // be chosen.
8223   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
8224     EvaluationTracker Eval(*this);
8225     {
8226       SequencedSubexpression Sequenced(*this);
8227       Visit(CO->getCond());
8228     }
8229 
8230     bool Result;
8231     if (Eval.evaluate(CO->getCond(), Result))
8232       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
8233     else {
8234       WorkList.push_back(CO->getTrueExpr());
8235       WorkList.push_back(CO->getFalseExpr());
8236     }
8237   }
8238 
8239   void VisitCallExpr(CallExpr *CE) {
8240     // C++11 [intro.execution]p15:
8241     //   When calling a function [...], every value computation and side effect
8242     //   associated with any argument expression, or with the postfix expression
8243     //   designating the called function, is sequenced before execution of every
8244     //   expression or statement in the body of the function [and thus before
8245     //   the value computation of its result].
8246     SequencedSubexpression Sequenced(*this);
8247     Base::VisitCallExpr(CE);
8248 
8249     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8250   }
8251 
8252   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
8253     // This is a call, so all subexpressions are sequenced before the result.
8254     SequencedSubexpression Sequenced(*this);
8255 
8256     if (!CCE->isListInitialization())
8257       return VisitExpr(CCE);
8258 
8259     // In C++11, list initializations are sequenced.
8260     SmallVector<SequenceTree::Seq, 32> Elts;
8261     SequenceTree::Seq Parent = Region;
8262     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8263                                         E = CCE->arg_end();
8264          I != E; ++I) {
8265       Region = Tree.allocate(Parent);
8266       Elts.push_back(Region);
8267       Visit(*I);
8268     }
8269 
8270     // Forget that the initializers are sequenced.
8271     Region = Parent;
8272     for (unsigned I = 0; I < Elts.size(); ++I)
8273       Tree.merge(Elts[I]);
8274   }
8275 
8276   void VisitInitListExpr(InitListExpr *ILE) {
8277     if (!SemaRef.getLangOpts().CPlusPlus11)
8278       return VisitExpr(ILE);
8279 
8280     // In C++11, list initializations are sequenced.
8281     SmallVector<SequenceTree::Seq, 32> Elts;
8282     SequenceTree::Seq Parent = Region;
8283     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8284       Expr *E = ILE->getInit(I);
8285       if (!E) continue;
8286       Region = Tree.allocate(Parent);
8287       Elts.push_back(Region);
8288       Visit(E);
8289     }
8290 
8291     // Forget that the initializers are sequenced.
8292     Region = Parent;
8293     for (unsigned I = 0; I < Elts.size(); ++I)
8294       Tree.merge(Elts[I]);
8295   }
8296 };
8297 }
8298 
8299 void Sema::CheckUnsequencedOperations(Expr *E) {
8300   SmallVector<Expr *, 8> WorkList;
8301   WorkList.push_back(E);
8302   while (!WorkList.empty()) {
8303     Expr *Item = WorkList.pop_back_val();
8304     SequenceChecker(*this, Item, WorkList);
8305   }
8306 }
8307 
8308 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8309                               bool IsConstexpr) {
8310   CheckImplicitConversions(E, CheckLoc);
8311   CheckUnsequencedOperations(E);
8312   if (!IsConstexpr && !E->isValueDependent())
8313     CheckForIntOverflow(E);
8314 }
8315 
8316 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8317                                        FieldDecl *BitField,
8318                                        Expr *Init) {
8319   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8320 }
8321 
8322 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8323                                          SourceLocation Loc) {
8324   if (!PType->isVariablyModifiedType())
8325     return;
8326   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8327     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8328     return;
8329   }
8330   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8331     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8332     return;
8333   }
8334   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8335     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8336     return;
8337   }
8338 
8339   const ArrayType *AT = S.Context.getAsArrayType(PType);
8340   if (!AT)
8341     return;
8342 
8343   if (AT->getSizeModifier() != ArrayType::Star) {
8344     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8345     return;
8346   }
8347 
8348   S.Diag(Loc, diag::err_array_star_in_function_definition);
8349 }
8350 
8351 /// CheckParmsForFunctionDef - Check that the parameters of the given
8352 /// function are appropriate for the definition of a function. This
8353 /// takes care of any checks that cannot be performed on the
8354 /// declaration itself, e.g., that the types of each of the function
8355 /// parameters are complete.
8356 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8357                                     ParmVarDecl *const *PEnd,
8358                                     bool CheckParameterNames) {
8359   bool HasInvalidParm = false;
8360   for (; P != PEnd; ++P) {
8361     ParmVarDecl *Param = *P;
8362 
8363     // C99 6.7.5.3p4: the parameters in a parameter type list in a
8364     // function declarator that is part of a function definition of
8365     // that function shall not have incomplete type.
8366     //
8367     // This is also C++ [dcl.fct]p6.
8368     if (!Param->isInvalidDecl() &&
8369         RequireCompleteType(Param->getLocation(), Param->getType(),
8370                             diag::err_typecheck_decl_incomplete_type)) {
8371       Param->setInvalidDecl();
8372       HasInvalidParm = true;
8373     }
8374 
8375     // C99 6.9.1p5: If the declarator includes a parameter type list, the
8376     // declaration of each parameter shall include an identifier.
8377     if (CheckParameterNames &&
8378         Param->getIdentifier() == nullptr &&
8379         !Param->isImplicit() &&
8380         !getLangOpts().CPlusPlus)
8381       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8382 
8383     // C99 6.7.5.3p12:
8384     //   If the function declarator is not part of a definition of that
8385     //   function, parameters may have incomplete type and may use the [*]
8386     //   notation in their sequences of declarator specifiers to specify
8387     //   variable length array types.
8388     QualType PType = Param->getOriginalType();
8389     // FIXME: This diagnostic should point the '[*]' if source-location
8390     // information is added for it.
8391     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
8392 
8393     // MSVC destroys objects passed by value in the callee.  Therefore a
8394     // function definition which takes such a parameter must be able to call the
8395     // object's destructor.  However, we don't perform any direct access check
8396     // on the dtor.
8397     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8398                                        .getCXXABI()
8399                                        .areArgsDestroyedLeftToRightInCallee()) {
8400       if (!Param->isInvalidDecl()) {
8401         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8402           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8403           if (!ClassDecl->isInvalidDecl() &&
8404               !ClassDecl->hasIrrelevantDestructor() &&
8405               !ClassDecl->isDependentContext()) {
8406             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8407             MarkFunctionReferenced(Param->getLocation(), Destructor);
8408             DiagnoseUseOfDecl(Destructor, Param->getLocation());
8409           }
8410         }
8411       }
8412     }
8413   }
8414 
8415   return HasInvalidParm;
8416 }
8417 
8418 /// CheckCastAlign - Implements -Wcast-align, which warns when a
8419 /// pointer cast increases the alignment requirements.
8420 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8421   // This is actually a lot of work to potentially be doing on every
8422   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
8423   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
8424     return;
8425 
8426   // Ignore dependent types.
8427   if (T->isDependentType() || Op->getType()->isDependentType())
8428     return;
8429 
8430   // Require that the destination be a pointer type.
8431   const PointerType *DestPtr = T->getAs<PointerType>();
8432   if (!DestPtr) return;
8433 
8434   // If the destination has alignment 1, we're done.
8435   QualType DestPointee = DestPtr->getPointeeType();
8436   if (DestPointee->isIncompleteType()) return;
8437   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8438   if (DestAlign.isOne()) return;
8439 
8440   // Require that the source be a pointer type.
8441   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8442   if (!SrcPtr) return;
8443   QualType SrcPointee = SrcPtr->getPointeeType();
8444 
8445   // Whitelist casts from cv void*.  We already implicitly
8446   // whitelisted casts to cv void*, since they have alignment 1.
8447   // Also whitelist casts involving incomplete types, which implicitly
8448   // includes 'void'.
8449   if (SrcPointee->isIncompleteType()) return;
8450 
8451   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8452   if (SrcAlign >= DestAlign) return;
8453 
8454   Diag(TRange.getBegin(), diag::warn_cast_align)
8455     << Op->getType() << T
8456     << static_cast<unsigned>(SrcAlign.getQuantity())
8457     << static_cast<unsigned>(DestAlign.getQuantity())
8458     << TRange << Op->getSourceRange();
8459 }
8460 
8461 static const Type* getElementType(const Expr *BaseExpr) {
8462   const Type* EltType = BaseExpr->getType().getTypePtr();
8463   if (EltType->isAnyPointerType())
8464     return EltType->getPointeeType().getTypePtr();
8465   else if (EltType->isArrayType())
8466     return EltType->getBaseElementTypeUnsafe();
8467   return EltType;
8468 }
8469 
8470 /// \brief Check whether this array fits the idiom of a size-one tail padded
8471 /// array member of a struct.
8472 ///
8473 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
8474 /// commonly used to emulate flexible arrays in C89 code.
8475 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8476                                     const NamedDecl *ND) {
8477   if (Size != 1 || !ND) return false;
8478 
8479   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8480   if (!FD) return false;
8481 
8482   // Don't consider sizes resulting from macro expansions or template argument
8483   // substitution to form C89 tail-padded arrays.
8484 
8485   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
8486   while (TInfo) {
8487     TypeLoc TL = TInfo->getTypeLoc();
8488     // Look through typedefs.
8489     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8490       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
8491       TInfo = TDL->getTypeSourceInfo();
8492       continue;
8493     }
8494     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8495       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
8496       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8497         return false;
8498     }
8499     break;
8500   }
8501 
8502   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
8503   if (!RD) return false;
8504   if (RD->isUnion()) return false;
8505   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8506     if (!CRD->isStandardLayout()) return false;
8507   }
8508 
8509   // See if this is the last field decl in the record.
8510   const Decl *D = FD;
8511   while ((D = D->getNextDeclInContext()))
8512     if (isa<FieldDecl>(D))
8513       return false;
8514   return true;
8515 }
8516 
8517 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8518                             const ArraySubscriptExpr *ASE,
8519                             bool AllowOnePastEnd, bool IndexNegated) {
8520   IndexExpr = IndexExpr->IgnoreParenImpCasts();
8521   if (IndexExpr->isValueDependent())
8522     return;
8523 
8524   const Type *EffectiveType = getElementType(BaseExpr);
8525   BaseExpr = BaseExpr->IgnoreParenCasts();
8526   const ConstantArrayType *ArrayTy =
8527     Context.getAsConstantArrayType(BaseExpr->getType());
8528   if (!ArrayTy)
8529     return;
8530 
8531   llvm::APSInt index;
8532   if (!IndexExpr->EvaluateAsInt(index, Context))
8533     return;
8534   if (IndexNegated)
8535     index = -index;
8536 
8537   const NamedDecl *ND = nullptr;
8538   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8539     ND = dyn_cast<NamedDecl>(DRE->getDecl());
8540   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8541     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8542 
8543   if (index.isUnsigned() || !index.isNegative()) {
8544     llvm::APInt size = ArrayTy->getSize();
8545     if (!size.isStrictlyPositive())
8546       return;
8547 
8548     const Type* BaseType = getElementType(BaseExpr);
8549     if (BaseType != EffectiveType) {
8550       // Make sure we're comparing apples to apples when comparing index to size
8551       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8552       uint64_t array_typesize = Context.getTypeSize(BaseType);
8553       // Handle ptrarith_typesize being zero, such as when casting to void*
8554       if (!ptrarith_typesize) ptrarith_typesize = 1;
8555       if (ptrarith_typesize != array_typesize) {
8556         // There's a cast to a different size type involved
8557         uint64_t ratio = array_typesize / ptrarith_typesize;
8558         // TODO: Be smarter about handling cases where array_typesize is not a
8559         // multiple of ptrarith_typesize
8560         if (ptrarith_typesize * ratio == array_typesize)
8561           size *= llvm::APInt(size.getBitWidth(), ratio);
8562       }
8563     }
8564 
8565     if (size.getBitWidth() > index.getBitWidth())
8566       index = index.zext(size.getBitWidth());
8567     else if (size.getBitWidth() < index.getBitWidth())
8568       size = size.zext(index.getBitWidth());
8569 
8570     // For array subscripting the index must be less than size, but for pointer
8571     // arithmetic also allow the index (offset) to be equal to size since
8572     // computing the next address after the end of the array is legal and
8573     // commonly done e.g. in C++ iterators and range-based for loops.
8574     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
8575       return;
8576 
8577     // Also don't warn for arrays of size 1 which are members of some
8578     // structure. These are often used to approximate flexible arrays in C89
8579     // code.
8580     if (IsTailPaddedMemberArray(*this, size, ND))
8581       return;
8582 
8583     // Suppress the warning if the subscript expression (as identified by the
8584     // ']' location) and the index expression are both from macro expansions
8585     // within a system header.
8586     if (ASE) {
8587       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8588           ASE->getRBracketLoc());
8589       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8590         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8591             IndexExpr->getLocStart());
8592         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
8593           return;
8594       }
8595     }
8596 
8597     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
8598     if (ASE)
8599       DiagID = diag::warn_array_index_exceeds_bounds;
8600 
8601     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8602                         PDiag(DiagID) << index.toString(10, true)
8603                           << size.toString(10, true)
8604                           << (unsigned)size.getLimitedValue(~0U)
8605                           << IndexExpr->getSourceRange());
8606   } else {
8607     unsigned DiagID = diag::warn_array_index_precedes_bounds;
8608     if (!ASE) {
8609       DiagID = diag::warn_ptr_arith_precedes_bounds;
8610       if (index.isNegative()) index = -index;
8611     }
8612 
8613     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8614                         PDiag(DiagID) << index.toString(10, true)
8615                           << IndexExpr->getSourceRange());
8616   }
8617 
8618   if (!ND) {
8619     // Try harder to find a NamedDecl to point at in the note.
8620     while (const ArraySubscriptExpr *ASE =
8621            dyn_cast<ArraySubscriptExpr>(BaseExpr))
8622       BaseExpr = ASE->getBase()->IgnoreParenCasts();
8623     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8624       ND = dyn_cast<NamedDecl>(DRE->getDecl());
8625     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8626       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8627   }
8628 
8629   if (ND)
8630     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8631                         PDiag(diag::note_array_index_out_of_bounds)
8632                           << ND->getDeclName());
8633 }
8634 
8635 void Sema::CheckArrayAccess(const Expr *expr) {
8636   int AllowOnePastEnd = 0;
8637   while (expr) {
8638     expr = expr->IgnoreParenImpCasts();
8639     switch (expr->getStmtClass()) {
8640       case Stmt::ArraySubscriptExprClass: {
8641         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
8642         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
8643                          AllowOnePastEnd > 0);
8644         return;
8645       }
8646       case Stmt::OMPArraySectionExprClass: {
8647         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8648         if (ASE->getLowerBound())
8649           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8650                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
8651         return;
8652       }
8653       case Stmt::UnaryOperatorClass: {
8654         // Only unwrap the * and & unary operators
8655         const UnaryOperator *UO = cast<UnaryOperator>(expr);
8656         expr = UO->getSubExpr();
8657         switch (UO->getOpcode()) {
8658           case UO_AddrOf:
8659             AllowOnePastEnd++;
8660             break;
8661           case UO_Deref:
8662             AllowOnePastEnd--;
8663             break;
8664           default:
8665             return;
8666         }
8667         break;
8668       }
8669       case Stmt::ConditionalOperatorClass: {
8670         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8671         if (const Expr *lhs = cond->getLHS())
8672           CheckArrayAccess(lhs);
8673         if (const Expr *rhs = cond->getRHS())
8674           CheckArrayAccess(rhs);
8675         return;
8676       }
8677       default:
8678         return;
8679     }
8680   }
8681 }
8682 
8683 //===--- CHECK: Objective-C retain cycles ----------------------------------//
8684 
8685 namespace {
8686   struct RetainCycleOwner {
8687     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
8688     VarDecl *Variable;
8689     SourceRange Range;
8690     SourceLocation Loc;
8691     bool Indirect;
8692 
8693     void setLocsFrom(Expr *e) {
8694       Loc = e->getExprLoc();
8695       Range = e->getSourceRange();
8696     }
8697   };
8698 }
8699 
8700 /// Consider whether capturing the given variable can possibly lead to
8701 /// a retain cycle.
8702 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
8703   // In ARC, it's captured strongly iff the variable has __strong
8704   // lifetime.  In MRR, it's captured strongly if the variable is
8705   // __block and has an appropriate type.
8706   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8707     return false;
8708 
8709   owner.Variable = var;
8710   if (ref)
8711     owner.setLocsFrom(ref);
8712   return true;
8713 }
8714 
8715 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
8716   while (true) {
8717     e = e->IgnoreParens();
8718     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8719       switch (cast->getCastKind()) {
8720       case CK_BitCast:
8721       case CK_LValueBitCast:
8722       case CK_LValueToRValue:
8723       case CK_ARCReclaimReturnedObject:
8724         e = cast->getSubExpr();
8725         continue;
8726 
8727       default:
8728         return false;
8729       }
8730     }
8731 
8732     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8733       ObjCIvarDecl *ivar = ref->getDecl();
8734       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8735         return false;
8736 
8737       // Try to find a retain cycle in the base.
8738       if (!findRetainCycleOwner(S, ref->getBase(), owner))
8739         return false;
8740 
8741       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8742       owner.Indirect = true;
8743       return true;
8744     }
8745 
8746     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8747       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8748       if (!var) return false;
8749       return considerVariable(var, ref, owner);
8750     }
8751 
8752     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8753       if (member->isArrow()) return false;
8754 
8755       // Don't count this as an indirect ownership.
8756       e = member->getBase();
8757       continue;
8758     }
8759 
8760     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8761       // Only pay attention to pseudo-objects on property references.
8762       ObjCPropertyRefExpr *pre
8763         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8764                                               ->IgnoreParens());
8765       if (!pre) return false;
8766       if (pre->isImplicitProperty()) return false;
8767       ObjCPropertyDecl *property = pre->getExplicitProperty();
8768       if (!property->isRetaining() &&
8769           !(property->getPropertyIvarDecl() &&
8770             property->getPropertyIvarDecl()->getType()
8771               .getObjCLifetime() == Qualifiers::OCL_Strong))
8772           return false;
8773 
8774       owner.Indirect = true;
8775       if (pre->isSuperReceiver()) {
8776         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8777         if (!owner.Variable)
8778           return false;
8779         owner.Loc = pre->getLocation();
8780         owner.Range = pre->getSourceRange();
8781         return true;
8782       }
8783       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8784                               ->getSourceExpr());
8785       continue;
8786     }
8787 
8788     // Array ivars?
8789 
8790     return false;
8791   }
8792 }
8793 
8794 namespace {
8795   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8796     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8797       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
8798         Context(Context), Variable(variable), Capturer(nullptr),
8799         VarWillBeReased(false) {}
8800     ASTContext &Context;
8801     VarDecl *Variable;
8802     Expr *Capturer;
8803     bool VarWillBeReased;
8804 
8805     void VisitDeclRefExpr(DeclRefExpr *ref) {
8806       if (ref->getDecl() == Variable && !Capturer)
8807         Capturer = ref;
8808     }
8809 
8810     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8811       if (Capturer) return;
8812       Visit(ref->getBase());
8813       if (Capturer && ref->isFreeIvar())
8814         Capturer = ref;
8815     }
8816 
8817     void VisitBlockExpr(BlockExpr *block) {
8818       // Look inside nested blocks
8819       if (block->getBlockDecl()->capturesVariable(Variable))
8820         Visit(block->getBlockDecl()->getBody());
8821     }
8822 
8823     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8824       if (Capturer) return;
8825       if (OVE->getSourceExpr())
8826         Visit(OVE->getSourceExpr());
8827     }
8828     void VisitBinaryOperator(BinaryOperator *BinOp) {
8829       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8830         return;
8831       Expr *LHS = BinOp->getLHS();
8832       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8833         if (DRE->getDecl() != Variable)
8834           return;
8835         if (Expr *RHS = BinOp->getRHS()) {
8836           RHS = RHS->IgnoreParenCasts();
8837           llvm::APSInt Value;
8838           VarWillBeReased =
8839             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8840         }
8841       }
8842     }
8843   };
8844 }
8845 
8846 /// Check whether the given argument is a block which captures a
8847 /// variable.
8848 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8849   assert(owner.Variable && owner.Loc.isValid());
8850 
8851   e = e->IgnoreParenCasts();
8852 
8853   // Look through [^{...} copy] and Block_copy(^{...}).
8854   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8855     Selector Cmd = ME->getSelector();
8856     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8857       e = ME->getInstanceReceiver();
8858       if (!e)
8859         return nullptr;
8860       e = e->IgnoreParenCasts();
8861     }
8862   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8863     if (CE->getNumArgs() == 1) {
8864       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
8865       if (Fn) {
8866         const IdentifierInfo *FnI = Fn->getIdentifier();
8867         if (FnI && FnI->isStr("_Block_copy")) {
8868           e = CE->getArg(0)->IgnoreParenCasts();
8869         }
8870       }
8871     }
8872   }
8873 
8874   BlockExpr *block = dyn_cast<BlockExpr>(e);
8875   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
8876     return nullptr;
8877 
8878   FindCaptureVisitor visitor(S.Context, owner.Variable);
8879   visitor.Visit(block->getBlockDecl()->getBody());
8880   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
8881 }
8882 
8883 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8884                                 RetainCycleOwner &owner) {
8885   assert(capturer);
8886   assert(owner.Variable && owner.Loc.isValid());
8887 
8888   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8889     << owner.Variable << capturer->getSourceRange();
8890   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8891     << owner.Indirect << owner.Range;
8892 }
8893 
8894 /// Check for a keyword selector that starts with the word 'add' or
8895 /// 'set'.
8896 static bool isSetterLikeSelector(Selector sel) {
8897   if (sel.isUnarySelector()) return false;
8898 
8899   StringRef str = sel.getNameForSlot(0);
8900   while (!str.empty() && str.front() == '_') str = str.substr(1);
8901   if (str.startswith("set"))
8902     str = str.substr(3);
8903   else if (str.startswith("add")) {
8904     // Specially whitelist 'addOperationWithBlock:'.
8905     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8906       return false;
8907     str = str.substr(3);
8908   }
8909   else
8910     return false;
8911 
8912   if (str.empty()) return true;
8913   return !isLowercase(str.front());
8914 }
8915 
8916 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8917                                                     ObjCMessageExpr *Message) {
8918   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8919                                                 Message->getReceiverInterface(),
8920                                                 NSAPI::ClassId_NSMutableArray);
8921   if (!IsMutableArray) {
8922     return None;
8923   }
8924 
8925   Selector Sel = Message->getSelector();
8926 
8927   Optional<NSAPI::NSArrayMethodKind> MKOpt =
8928     S.NSAPIObj->getNSArrayMethodKind(Sel);
8929   if (!MKOpt) {
8930     return None;
8931   }
8932 
8933   NSAPI::NSArrayMethodKind MK = *MKOpt;
8934 
8935   switch (MK) {
8936     case NSAPI::NSMutableArr_addObject:
8937     case NSAPI::NSMutableArr_insertObjectAtIndex:
8938     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8939       return 0;
8940     case NSAPI::NSMutableArr_replaceObjectAtIndex:
8941       return 1;
8942 
8943     default:
8944       return None;
8945   }
8946 
8947   return None;
8948 }
8949 
8950 static
8951 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8952                                                   ObjCMessageExpr *Message) {
8953   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
8954                                             Message->getReceiverInterface(),
8955                                             NSAPI::ClassId_NSMutableDictionary);
8956   if (!IsMutableDictionary) {
8957     return None;
8958   }
8959 
8960   Selector Sel = Message->getSelector();
8961 
8962   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8963     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8964   if (!MKOpt) {
8965     return None;
8966   }
8967 
8968   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8969 
8970   switch (MK) {
8971     case NSAPI::NSMutableDict_setObjectForKey:
8972     case NSAPI::NSMutableDict_setValueForKey:
8973     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8974       return 0;
8975 
8976     default:
8977       return None;
8978   }
8979 
8980   return None;
8981 }
8982 
8983 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8984   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
8985                                                 Message->getReceiverInterface(),
8986                                                 NSAPI::ClassId_NSMutableSet);
8987 
8988   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
8989                                             Message->getReceiverInterface(),
8990                                             NSAPI::ClassId_NSMutableOrderedSet);
8991   if (!IsMutableSet && !IsMutableOrderedSet) {
8992     return None;
8993   }
8994 
8995   Selector Sel = Message->getSelector();
8996 
8997   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8998   if (!MKOpt) {
8999     return None;
9000   }
9001 
9002   NSAPI::NSSetMethodKind MK = *MKOpt;
9003 
9004   switch (MK) {
9005     case NSAPI::NSMutableSet_addObject:
9006     case NSAPI::NSOrderedSet_setObjectAtIndex:
9007     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9008     case NSAPI::NSOrderedSet_insertObjectAtIndex:
9009       return 0;
9010     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9011       return 1;
9012   }
9013 
9014   return None;
9015 }
9016 
9017 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9018   if (!Message->isInstanceMessage()) {
9019     return;
9020   }
9021 
9022   Optional<int> ArgOpt;
9023 
9024   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9025       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9026       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9027     return;
9028   }
9029 
9030   int ArgIndex = *ArgOpt;
9031 
9032   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9033   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9034     Arg = OE->getSourceExpr()->IgnoreImpCasts();
9035   }
9036 
9037   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
9038     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9039       if (ArgRE->isObjCSelfExpr()) {
9040         Diag(Message->getSourceRange().getBegin(),
9041              diag::warn_objc_circular_container)
9042           << ArgRE->getDecl()->getName() << StringRef("super");
9043       }
9044     }
9045   } else {
9046     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9047 
9048     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9049       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9050     }
9051 
9052     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9053       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9054         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9055           ValueDecl *Decl = ReceiverRE->getDecl();
9056           Diag(Message->getSourceRange().getBegin(),
9057                diag::warn_objc_circular_container)
9058             << Decl->getName() << Decl->getName();
9059           if (!ArgRE->isObjCSelfExpr()) {
9060             Diag(Decl->getLocation(),
9061                  diag::note_objc_circular_container_declared_here)
9062               << Decl->getName();
9063           }
9064         }
9065       }
9066     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9067       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9068         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9069           ObjCIvarDecl *Decl = IvarRE->getDecl();
9070           Diag(Message->getSourceRange().getBegin(),
9071                diag::warn_objc_circular_container)
9072             << Decl->getName() << Decl->getName();
9073           Diag(Decl->getLocation(),
9074                diag::note_objc_circular_container_declared_here)
9075             << Decl->getName();
9076         }
9077       }
9078     }
9079   }
9080 
9081 }
9082 
9083 /// Check a message send to see if it's likely to cause a retain cycle.
9084 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9085   // Only check instance methods whose selector looks like a setter.
9086   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9087     return;
9088 
9089   // Try to find a variable that the receiver is strongly owned by.
9090   RetainCycleOwner owner;
9091   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
9092     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
9093       return;
9094   } else {
9095     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9096     owner.Variable = getCurMethodDecl()->getSelfDecl();
9097     owner.Loc = msg->getSuperLoc();
9098     owner.Range = msg->getSuperLoc();
9099   }
9100 
9101   // Check whether the receiver is captured by any of the arguments.
9102   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9103     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9104       return diagnoseRetainCycle(*this, capturer, owner);
9105 }
9106 
9107 /// Check a property assign to see if it's likely to cause a retain cycle.
9108 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9109   RetainCycleOwner owner;
9110   if (!findRetainCycleOwner(*this, receiver, owner))
9111     return;
9112 
9113   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9114     diagnoseRetainCycle(*this, capturer, owner);
9115 }
9116 
9117 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9118   RetainCycleOwner Owner;
9119   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
9120     return;
9121 
9122   // Because we don't have an expression for the variable, we have to set the
9123   // location explicitly here.
9124   Owner.Loc = Var->getLocation();
9125   Owner.Range = Var->getSourceRange();
9126 
9127   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9128     diagnoseRetainCycle(*this, Capturer, Owner);
9129 }
9130 
9131 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9132                                      Expr *RHS, bool isProperty) {
9133   // Check if RHS is an Objective-C object literal, which also can get
9134   // immediately zapped in a weak reference.  Note that we explicitly
9135   // allow ObjCStringLiterals, since those are designed to never really die.
9136   RHS = RHS->IgnoreParenImpCasts();
9137 
9138   // This enum needs to match with the 'select' in
9139   // warn_objc_arc_literal_assign (off-by-1).
9140   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9141   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9142     return false;
9143 
9144   S.Diag(Loc, diag::warn_arc_literal_assign)
9145     << (unsigned) Kind
9146     << (isProperty ? 0 : 1)
9147     << RHS->getSourceRange();
9148 
9149   return true;
9150 }
9151 
9152 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9153                                     Qualifiers::ObjCLifetime LT,
9154                                     Expr *RHS, bool isProperty) {
9155   // Strip off any implicit cast added to get to the one ARC-specific.
9156   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9157     if (cast->getCastKind() == CK_ARCConsumeObject) {
9158       S.Diag(Loc, diag::warn_arc_retained_assign)
9159         << (LT == Qualifiers::OCL_ExplicitNone)
9160         << (isProperty ? 0 : 1)
9161         << RHS->getSourceRange();
9162       return true;
9163     }
9164     RHS = cast->getSubExpr();
9165   }
9166 
9167   if (LT == Qualifiers::OCL_Weak &&
9168       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9169     return true;
9170 
9171   return false;
9172 }
9173 
9174 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9175                               QualType LHS, Expr *RHS) {
9176   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9177 
9178   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9179     return false;
9180 
9181   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9182     return true;
9183 
9184   return false;
9185 }
9186 
9187 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9188                               Expr *LHS, Expr *RHS) {
9189   QualType LHSType;
9190   // PropertyRef on LHS type need be directly obtained from
9191   // its declaration as it has a PseudoType.
9192   ObjCPropertyRefExpr *PRE
9193     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9194   if (PRE && !PRE->isImplicitProperty()) {
9195     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9196     if (PD)
9197       LHSType = PD->getType();
9198   }
9199 
9200   if (LHSType.isNull())
9201     LHSType = LHS->getType();
9202 
9203   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9204 
9205   if (LT == Qualifiers::OCL_Weak) {
9206     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
9207       getCurFunction()->markSafeWeakUse(LHS);
9208   }
9209 
9210   if (checkUnsafeAssigns(Loc, LHSType, RHS))
9211     return;
9212 
9213   // FIXME. Check for other life times.
9214   if (LT != Qualifiers::OCL_None)
9215     return;
9216 
9217   if (PRE) {
9218     if (PRE->isImplicitProperty())
9219       return;
9220     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9221     if (!PD)
9222       return;
9223 
9224     unsigned Attributes = PD->getPropertyAttributes();
9225     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
9226       // when 'assign' attribute was not explicitly specified
9227       // by user, ignore it and rely on property type itself
9228       // for lifetime info.
9229       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9230       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9231           LHSType->isObjCRetainableType())
9232         return;
9233 
9234       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9235         if (cast->getCastKind() == CK_ARCConsumeObject) {
9236           Diag(Loc, diag::warn_arc_retained_property_assign)
9237           << RHS->getSourceRange();
9238           return;
9239         }
9240         RHS = cast->getSubExpr();
9241       }
9242     }
9243     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
9244       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9245         return;
9246     }
9247   }
9248 }
9249 
9250 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9251 
9252 namespace {
9253 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9254                                  SourceLocation StmtLoc,
9255                                  const NullStmt *Body) {
9256   // Do not warn if the body is a macro that expands to nothing, e.g:
9257   //
9258   // #define CALL(x)
9259   // if (condition)
9260   //   CALL(0);
9261   //
9262   if (Body->hasLeadingEmptyMacro())
9263     return false;
9264 
9265   // Get line numbers of statement and body.
9266   bool StmtLineInvalid;
9267   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
9268                                                       &StmtLineInvalid);
9269   if (StmtLineInvalid)
9270     return false;
9271 
9272   bool BodyLineInvalid;
9273   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9274                                                       &BodyLineInvalid);
9275   if (BodyLineInvalid)
9276     return false;
9277 
9278   // Warn if null statement and body are on the same line.
9279   if (StmtLine != BodyLine)
9280     return false;
9281 
9282   return true;
9283 }
9284 } // Unnamed namespace
9285 
9286 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9287                                  const Stmt *Body,
9288                                  unsigned DiagID) {
9289   // Since this is a syntactic check, don't emit diagnostic for template
9290   // instantiations, this just adds noise.
9291   if (CurrentInstantiationScope)
9292     return;
9293 
9294   // The body should be a null statement.
9295   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9296   if (!NBody)
9297     return;
9298 
9299   // Do the usual checks.
9300   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9301     return;
9302 
9303   Diag(NBody->getSemiLoc(), DiagID);
9304   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9305 }
9306 
9307 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9308                                  const Stmt *PossibleBody) {
9309   assert(!CurrentInstantiationScope); // Ensured by caller
9310 
9311   SourceLocation StmtLoc;
9312   const Stmt *Body;
9313   unsigned DiagID;
9314   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9315     StmtLoc = FS->getRParenLoc();
9316     Body = FS->getBody();
9317     DiagID = diag::warn_empty_for_body;
9318   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9319     StmtLoc = WS->getCond()->getSourceRange().getEnd();
9320     Body = WS->getBody();
9321     DiagID = diag::warn_empty_while_body;
9322   } else
9323     return; // Neither `for' nor `while'.
9324 
9325   // The body should be a null statement.
9326   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9327   if (!NBody)
9328     return;
9329 
9330   // Skip expensive checks if diagnostic is disabled.
9331   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
9332     return;
9333 
9334   // Do the usual checks.
9335   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9336     return;
9337 
9338   // `for(...);' and `while(...);' are popular idioms, so in order to keep
9339   // noise level low, emit diagnostics only if for/while is followed by a
9340   // CompoundStmt, e.g.:
9341   //    for (int i = 0; i < n; i++);
9342   //    {
9343   //      a(i);
9344   //    }
9345   // or if for/while is followed by a statement with more indentation
9346   // than for/while itself:
9347   //    for (int i = 0; i < n; i++);
9348   //      a(i);
9349   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9350   if (!ProbableTypo) {
9351     bool BodyColInvalid;
9352     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9353                              PossibleBody->getLocStart(),
9354                              &BodyColInvalid);
9355     if (BodyColInvalid)
9356       return;
9357 
9358     bool StmtColInvalid;
9359     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9360                              S->getLocStart(),
9361                              &StmtColInvalid);
9362     if (StmtColInvalid)
9363       return;
9364 
9365     if (BodyCol > StmtCol)
9366       ProbableTypo = true;
9367   }
9368 
9369   if (ProbableTypo) {
9370     Diag(NBody->getSemiLoc(), DiagID);
9371     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9372   }
9373 }
9374 
9375 //===--- CHECK: Warn on self move with std::move. -------------------------===//
9376 
9377 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9378 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9379                              SourceLocation OpLoc) {
9380 
9381   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9382     return;
9383 
9384   if (!ActiveTemplateInstantiations.empty())
9385     return;
9386 
9387   // Strip parens and casts away.
9388   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9389   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9390 
9391   // Check for a call expression
9392   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9393   if (!CE || CE->getNumArgs() != 1)
9394     return;
9395 
9396   // Check for a call to std::move
9397   const FunctionDecl *FD = CE->getDirectCallee();
9398   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9399       !FD->getIdentifier()->isStr("move"))
9400     return;
9401 
9402   // Get argument from std::move
9403   RHSExpr = CE->getArg(0);
9404 
9405   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9406   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9407 
9408   // Two DeclRefExpr's, check that the decls are the same.
9409   if (LHSDeclRef && RHSDeclRef) {
9410     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9411       return;
9412     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9413         RHSDeclRef->getDecl()->getCanonicalDecl())
9414       return;
9415 
9416     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9417                                         << LHSExpr->getSourceRange()
9418                                         << RHSExpr->getSourceRange();
9419     return;
9420   }
9421 
9422   // Member variables require a different approach to check for self moves.
9423   // MemberExpr's are the same if every nested MemberExpr refers to the same
9424   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9425   // the base Expr's are CXXThisExpr's.
9426   const Expr *LHSBase = LHSExpr;
9427   const Expr *RHSBase = RHSExpr;
9428   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9429   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9430   if (!LHSME || !RHSME)
9431     return;
9432 
9433   while (LHSME && RHSME) {
9434     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9435         RHSME->getMemberDecl()->getCanonicalDecl())
9436       return;
9437 
9438     LHSBase = LHSME->getBase();
9439     RHSBase = RHSME->getBase();
9440     LHSME = dyn_cast<MemberExpr>(LHSBase);
9441     RHSME = dyn_cast<MemberExpr>(RHSBase);
9442   }
9443 
9444   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9445   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9446   if (LHSDeclRef && RHSDeclRef) {
9447     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9448       return;
9449     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9450         RHSDeclRef->getDecl()->getCanonicalDecl())
9451       return;
9452 
9453     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9454                                         << LHSExpr->getSourceRange()
9455                                         << RHSExpr->getSourceRange();
9456     return;
9457   }
9458 
9459   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9460     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9461                                         << LHSExpr->getSourceRange()
9462                                         << RHSExpr->getSourceRange();
9463 }
9464 
9465 //===--- Layout compatibility ----------------------------------------------//
9466 
9467 namespace {
9468 
9469 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9470 
9471 /// \brief Check if two enumeration types are layout-compatible.
9472 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9473   // C++11 [dcl.enum] p8:
9474   // Two enumeration types are layout-compatible if they have the same
9475   // underlying type.
9476   return ED1->isComplete() && ED2->isComplete() &&
9477          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9478 }
9479 
9480 /// \brief Check if two fields are layout-compatible.
9481 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9482   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9483     return false;
9484 
9485   if (Field1->isBitField() != Field2->isBitField())
9486     return false;
9487 
9488   if (Field1->isBitField()) {
9489     // Make sure that the bit-fields are the same length.
9490     unsigned Bits1 = Field1->getBitWidthValue(C);
9491     unsigned Bits2 = Field2->getBitWidthValue(C);
9492 
9493     if (Bits1 != Bits2)
9494       return false;
9495   }
9496 
9497   return true;
9498 }
9499 
9500 /// \brief Check if two standard-layout structs are layout-compatible.
9501 /// (C++11 [class.mem] p17)
9502 bool isLayoutCompatibleStruct(ASTContext &C,
9503                               RecordDecl *RD1,
9504                               RecordDecl *RD2) {
9505   // If both records are C++ classes, check that base classes match.
9506   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9507     // If one of records is a CXXRecordDecl we are in C++ mode,
9508     // thus the other one is a CXXRecordDecl, too.
9509     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9510     // Check number of base classes.
9511     if (D1CXX->getNumBases() != D2CXX->getNumBases())
9512       return false;
9513 
9514     // Check the base classes.
9515     for (CXXRecordDecl::base_class_const_iterator
9516                Base1 = D1CXX->bases_begin(),
9517            BaseEnd1 = D1CXX->bases_end(),
9518               Base2 = D2CXX->bases_begin();
9519          Base1 != BaseEnd1;
9520          ++Base1, ++Base2) {
9521       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9522         return false;
9523     }
9524   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9525     // If only RD2 is a C++ class, it should have zero base classes.
9526     if (D2CXX->getNumBases() > 0)
9527       return false;
9528   }
9529 
9530   // Check the fields.
9531   RecordDecl::field_iterator Field2 = RD2->field_begin(),
9532                              Field2End = RD2->field_end(),
9533                              Field1 = RD1->field_begin(),
9534                              Field1End = RD1->field_end();
9535   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9536     if (!isLayoutCompatible(C, *Field1, *Field2))
9537       return false;
9538   }
9539   if (Field1 != Field1End || Field2 != Field2End)
9540     return false;
9541 
9542   return true;
9543 }
9544 
9545 /// \brief Check if two standard-layout unions are layout-compatible.
9546 /// (C++11 [class.mem] p18)
9547 bool isLayoutCompatibleUnion(ASTContext &C,
9548                              RecordDecl *RD1,
9549                              RecordDecl *RD2) {
9550   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
9551   for (auto *Field2 : RD2->fields())
9552     UnmatchedFields.insert(Field2);
9553 
9554   for (auto *Field1 : RD1->fields()) {
9555     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9556         I = UnmatchedFields.begin(),
9557         E = UnmatchedFields.end();
9558 
9559     for ( ; I != E; ++I) {
9560       if (isLayoutCompatible(C, Field1, *I)) {
9561         bool Result = UnmatchedFields.erase(*I);
9562         (void) Result;
9563         assert(Result);
9564         break;
9565       }
9566     }
9567     if (I == E)
9568       return false;
9569   }
9570 
9571   return UnmatchedFields.empty();
9572 }
9573 
9574 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9575   if (RD1->isUnion() != RD2->isUnion())
9576     return false;
9577 
9578   if (RD1->isUnion())
9579     return isLayoutCompatibleUnion(C, RD1, RD2);
9580   else
9581     return isLayoutCompatibleStruct(C, RD1, RD2);
9582 }
9583 
9584 /// \brief Check if two types are layout-compatible in C++11 sense.
9585 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9586   if (T1.isNull() || T2.isNull())
9587     return false;
9588 
9589   // C++11 [basic.types] p11:
9590   // If two types T1 and T2 are the same type, then T1 and T2 are
9591   // layout-compatible types.
9592   if (C.hasSameType(T1, T2))
9593     return true;
9594 
9595   T1 = T1.getCanonicalType().getUnqualifiedType();
9596   T2 = T2.getCanonicalType().getUnqualifiedType();
9597 
9598   const Type::TypeClass TC1 = T1->getTypeClass();
9599   const Type::TypeClass TC2 = T2->getTypeClass();
9600 
9601   if (TC1 != TC2)
9602     return false;
9603 
9604   if (TC1 == Type::Enum) {
9605     return isLayoutCompatible(C,
9606                               cast<EnumType>(T1)->getDecl(),
9607                               cast<EnumType>(T2)->getDecl());
9608   } else if (TC1 == Type::Record) {
9609     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9610       return false;
9611 
9612     return isLayoutCompatible(C,
9613                               cast<RecordType>(T1)->getDecl(),
9614                               cast<RecordType>(T2)->getDecl());
9615   }
9616 
9617   return false;
9618 }
9619 }
9620 
9621 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9622 
9623 namespace {
9624 /// \brief Given a type tag expression find the type tag itself.
9625 ///
9626 /// \param TypeExpr Type tag expression, as it appears in user's code.
9627 ///
9628 /// \param VD Declaration of an identifier that appears in a type tag.
9629 ///
9630 /// \param MagicValue Type tag magic value.
9631 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9632                      const ValueDecl **VD, uint64_t *MagicValue) {
9633   while(true) {
9634     if (!TypeExpr)
9635       return false;
9636 
9637     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9638 
9639     switch (TypeExpr->getStmtClass()) {
9640     case Stmt::UnaryOperatorClass: {
9641       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9642       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9643         TypeExpr = UO->getSubExpr();
9644         continue;
9645       }
9646       return false;
9647     }
9648 
9649     case Stmt::DeclRefExprClass: {
9650       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9651       *VD = DRE->getDecl();
9652       return true;
9653     }
9654 
9655     case Stmt::IntegerLiteralClass: {
9656       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9657       llvm::APInt MagicValueAPInt = IL->getValue();
9658       if (MagicValueAPInt.getActiveBits() <= 64) {
9659         *MagicValue = MagicValueAPInt.getZExtValue();
9660         return true;
9661       } else
9662         return false;
9663     }
9664 
9665     case Stmt::BinaryConditionalOperatorClass:
9666     case Stmt::ConditionalOperatorClass: {
9667       const AbstractConditionalOperator *ACO =
9668           cast<AbstractConditionalOperator>(TypeExpr);
9669       bool Result;
9670       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9671         if (Result)
9672           TypeExpr = ACO->getTrueExpr();
9673         else
9674           TypeExpr = ACO->getFalseExpr();
9675         continue;
9676       }
9677       return false;
9678     }
9679 
9680     case Stmt::BinaryOperatorClass: {
9681       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9682       if (BO->getOpcode() == BO_Comma) {
9683         TypeExpr = BO->getRHS();
9684         continue;
9685       }
9686       return false;
9687     }
9688 
9689     default:
9690       return false;
9691     }
9692   }
9693 }
9694 
9695 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
9696 ///
9697 /// \param TypeExpr Expression that specifies a type tag.
9698 ///
9699 /// \param MagicValues Registered magic values.
9700 ///
9701 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9702 ///        kind.
9703 ///
9704 /// \param TypeInfo Information about the corresponding C type.
9705 ///
9706 /// \returns true if the corresponding C type was found.
9707 bool GetMatchingCType(
9708         const IdentifierInfo *ArgumentKind,
9709         const Expr *TypeExpr, const ASTContext &Ctx,
9710         const llvm::DenseMap<Sema::TypeTagMagicValue,
9711                              Sema::TypeTagData> *MagicValues,
9712         bool &FoundWrongKind,
9713         Sema::TypeTagData &TypeInfo) {
9714   FoundWrongKind = false;
9715 
9716   // Variable declaration that has type_tag_for_datatype attribute.
9717   const ValueDecl *VD = nullptr;
9718 
9719   uint64_t MagicValue;
9720 
9721   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9722     return false;
9723 
9724   if (VD) {
9725     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
9726       if (I->getArgumentKind() != ArgumentKind) {
9727         FoundWrongKind = true;
9728         return false;
9729       }
9730       TypeInfo.Type = I->getMatchingCType();
9731       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9732       TypeInfo.MustBeNull = I->getMustBeNull();
9733       return true;
9734     }
9735     return false;
9736   }
9737 
9738   if (!MagicValues)
9739     return false;
9740 
9741   llvm::DenseMap<Sema::TypeTagMagicValue,
9742                  Sema::TypeTagData>::const_iterator I =
9743       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9744   if (I == MagicValues->end())
9745     return false;
9746 
9747   TypeInfo = I->second;
9748   return true;
9749 }
9750 } // unnamed namespace
9751 
9752 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9753                                       uint64_t MagicValue, QualType Type,
9754                                       bool LayoutCompatible,
9755                                       bool MustBeNull) {
9756   if (!TypeTagForDatatypeMagicValues)
9757     TypeTagForDatatypeMagicValues.reset(
9758         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9759 
9760   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9761   (*TypeTagForDatatypeMagicValues)[Magic] =
9762       TypeTagData(Type, LayoutCompatible, MustBeNull);
9763 }
9764 
9765 namespace {
9766 bool IsSameCharType(QualType T1, QualType T2) {
9767   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9768   if (!BT1)
9769     return false;
9770 
9771   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9772   if (!BT2)
9773     return false;
9774 
9775   BuiltinType::Kind T1Kind = BT1->getKind();
9776   BuiltinType::Kind T2Kind = BT2->getKind();
9777 
9778   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
9779          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
9780          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9781          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9782 }
9783 } // unnamed namespace
9784 
9785 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9786                                     const Expr * const *ExprArgs) {
9787   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9788   bool IsPointerAttr = Attr->getIsPointer();
9789 
9790   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9791   bool FoundWrongKind;
9792   TypeTagData TypeInfo;
9793   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9794                         TypeTagForDatatypeMagicValues.get(),
9795                         FoundWrongKind, TypeInfo)) {
9796     if (FoundWrongKind)
9797       Diag(TypeTagExpr->getExprLoc(),
9798            diag::warn_type_tag_for_datatype_wrong_kind)
9799         << TypeTagExpr->getSourceRange();
9800     return;
9801   }
9802 
9803   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9804   if (IsPointerAttr) {
9805     // Skip implicit cast of pointer to `void *' (as a function argument).
9806     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
9807       if (ICE->getType()->isVoidPointerType() &&
9808           ICE->getCastKind() == CK_BitCast)
9809         ArgumentExpr = ICE->getSubExpr();
9810   }
9811   QualType ArgumentType = ArgumentExpr->getType();
9812 
9813   // Passing a `void*' pointer shouldn't trigger a warning.
9814   if (IsPointerAttr && ArgumentType->isVoidPointerType())
9815     return;
9816 
9817   if (TypeInfo.MustBeNull) {
9818     // Type tag with matching void type requires a null pointer.
9819     if (!ArgumentExpr->isNullPointerConstant(Context,
9820                                              Expr::NPC_ValueDependentIsNotNull)) {
9821       Diag(ArgumentExpr->getExprLoc(),
9822            diag::warn_type_safety_null_pointer_required)
9823           << ArgumentKind->getName()
9824           << ArgumentExpr->getSourceRange()
9825           << TypeTagExpr->getSourceRange();
9826     }
9827     return;
9828   }
9829 
9830   QualType RequiredType = TypeInfo.Type;
9831   if (IsPointerAttr)
9832     RequiredType = Context.getPointerType(RequiredType);
9833 
9834   bool mismatch = false;
9835   if (!TypeInfo.LayoutCompatible) {
9836     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9837 
9838     // C++11 [basic.fundamental] p1:
9839     // Plain char, signed char, and unsigned char are three distinct types.
9840     //
9841     // But we treat plain `char' as equivalent to `signed char' or `unsigned
9842     // char' depending on the current char signedness mode.
9843     if (mismatch)
9844       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9845                                            RequiredType->getPointeeType())) ||
9846           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9847         mismatch = false;
9848   } else
9849     if (IsPointerAttr)
9850       mismatch = !isLayoutCompatible(Context,
9851                                      ArgumentType->getPointeeType(),
9852                                      RequiredType->getPointeeType());
9853     else
9854       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9855 
9856   if (mismatch)
9857     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
9858         << ArgumentType << ArgumentKind
9859         << TypeInfo.LayoutCompatible << RequiredType
9860         << ArgumentExpr->getSourceRange()
9861         << TypeTagExpr->getSourceRange();
9862 }
9863 
9864