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