clang  6.0.0svn
SemaChecking.cpp
Go to the documentation of this file.
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/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.h"
30 #include "clang/AST/NSAPI.h"
32 #include "clang/AST/Stmt.h"
33 #include "clang/AST/TemplateBase.h"
34 #include "clang/AST/Type.h"
35 #include "clang/AST/TypeLoc.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/LLVM.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstddef>
91 #include <cstdint>
92 #include <functional>
93 #include <limits>
94 #include <string>
95 #include <tuple>
96 #include <utility>
97 
98 using namespace clang;
99 using namespace sema;
100 
102  unsigned ByteNo) const {
103  return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104  Context.getTargetInfo());
105 }
106 
107 /// Checks that a call expression's argument count is the desired number.
108 /// This is useful when doing custom type-checking. Returns true on error.
109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110  unsigned argCount = call->getNumArgs();
111  if (argCount == desiredArgCount) return false;
112 
113  if (argCount < desiredArgCount)
114  return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
115  << 0 /*function call*/ << desiredArgCount << argCount
116  << call->getSourceRange();
117 
118  // Highlight all the excess arguments.
119  SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
120  call->getArg(argCount - 1)->getLocEnd());
121 
122  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123  << 0 /*function call*/ << desiredArgCount << argCount
124  << call->getArg(1)->getSourceRange();
125 }
126 
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130  if (checkArgCount(S, TheCall, 2))
131  return true;
132 
133  // First argument should be an integer.
134  Expr *ValArg = TheCall->getArg(0);
135  QualType Ty = ValArg->getType();
136  if (!Ty->isIntegerType()) {
137  S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
138  << ValArg->getSourceRange();
139  return true;
140  }
141 
142  // Second argument should be a constant string.
143  Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144  StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145  if (!Literal || !Literal->isAscii()) {
146  S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
147  << StrArg->getSourceRange();
148  return true;
149  }
150 
151  TheCall->setType(Ty);
152  return false;
153 }
154 
155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156  // We need at least one argument.
157  if (TheCall->getNumArgs() < 1) {
158  S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
159  << 0 << 1 << TheCall->getNumArgs()
160  << TheCall->getCallee()->getSourceRange();
161  return true;
162  }
163 
164  // All arguments should be wide string literals.
165  for (Expr *Arg : TheCall->arguments()) {
166  auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167  if (!Literal || !Literal->isWide()) {
168  S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169  << Arg->getSourceRange();
170  return true;
171  }
172  }
173 
174  return false;
175 }
176 
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180  if (checkArgCount(S, TheCall, 1))
181  return true;
182 
183  ExprResult Arg(TheCall->getArg(0));
184  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185  if (ResultType.isNull())
186  return true;
187 
188  TheCall->setArg(0, Arg.get());
189  TheCall->setType(ResultType);
190  return false;
191 }
192 
193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194  if (checkArgCount(S, TheCall, 3))
195  return true;
196 
197  // First two arguments should be integers.
198  for (unsigned I = 0; I < 2; ++I) {
199  Expr *Arg = TheCall->getArg(I);
200  QualType Ty = Arg->getType();
201  if (!Ty->isIntegerType()) {
202  S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203  << Ty << Arg->getSourceRange();
204  return true;
205  }
206  }
207 
208  // Third argument should be a pointer to a non-const integer.
209  // IRGen correctly handles volatile, restrict, and address spaces, and
210  // the other qualifiers aren't possible.
211  {
212  Expr *Arg = TheCall->getArg(2);
213  QualType Ty = Arg->getType();
214  const auto *PtrTy = Ty->getAs<PointerType>();
215  if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216  !PtrTy->getPointeeType().isConstQualified())) {
217  S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218  << Ty << Arg->getSourceRange();
219  return true;
220  }
221  }
222 
223  return false;
224 }
225 
226 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
227  CallExpr *TheCall, unsigned SizeIdx,
228  unsigned DstSizeIdx) {
229  if (TheCall->getNumArgs() <= SizeIdx ||
230  TheCall->getNumArgs() <= DstSizeIdx)
231  return;
232 
233  const Expr *SizeArg = TheCall->getArg(SizeIdx);
234  const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
235 
236  llvm::APSInt Size, DstSize;
237 
238  // find out if both sizes are known at compile time
239  if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240  !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
241  return;
242 
243  if (Size.ule(DstSize))
244  return;
245 
246  // confirmed overflow so generate the diagnostic.
247  IdentifierInfo *FnName = FDecl->getIdentifier();
248  SourceLocation SL = TheCall->getLocStart();
249  SourceRange SR = TheCall->getSourceRange();
250 
251  S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
252 }
253 
254 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255  if (checkArgCount(S, BuiltinCall, 2))
256  return true;
257 
258  SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259  Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260  Expr *Call = BuiltinCall->getArg(0);
261  Expr *Chain = BuiltinCall->getArg(1);
262 
263  if (Call->getStmtClass() != Stmt::CallExprClass) {
264  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265  << Call->getSourceRange();
266  return true;
267  }
268 
269  auto CE = cast<CallExpr>(Call);
270  if (CE->getCallee()->getType()->isBlockPointerType()) {
271  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272  << Call->getSourceRange();
273  return true;
274  }
275 
276  const Decl *TargetDecl = CE->getCalleeDecl();
277  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278  if (FD->getBuiltinID()) {
279  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280  << Call->getSourceRange();
281  return true;
282  }
283 
284  if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286  << Call->getSourceRange();
287  return true;
288  }
289 
290  ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291  if (ChainResult.isInvalid())
292  return true;
293  if (!ChainResult.get()->getType()->isPointerType()) {
294  S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295  << Chain->getSourceRange();
296  return true;
297  }
298 
299  QualType ReturnTy = CE->getCallReturnType(S.Context);
300  QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301  QualType BuiltinTy = S.Context.getFunctionType(
302  ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303  QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
304 
305  Builtin =
306  S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
307 
308  BuiltinCall->setType(CE->getType());
309  BuiltinCall->setValueKind(CE->getValueKind());
310  BuiltinCall->setObjectKind(CE->getObjectKind());
311  BuiltinCall->setCallee(Builtin);
312  BuiltinCall->setArg(1, ChainResult.get());
313 
314  return false;
315 }
316 
317 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318  Scope::ScopeFlags NeededScopeFlags,
319  unsigned DiagID) {
320  // Scopes aren't available during instantiation. Fortunately, builtin
321  // functions cannot be template args so they cannot be formed through template
322  // instantiation. Therefore checking once during the parse is sufficient.
323  if (SemaRef.inTemplateInstantiation())
324  return false;
325 
326  Scope *S = SemaRef.getCurScope();
327  while (S && !S->isSEHExceptScope())
328  S = S->getParent();
329  if (!S || !(S->getFlags() & NeededScopeFlags)) {
330  auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331  SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332  << DRE->getDecl()->getIdentifier();
333  return true;
334  }
335 
336  return false;
337 }
338 
339 static inline bool isBlockPointer(Expr *Arg) {
340  return Arg->getType()->isBlockPointerType();
341 }
342 
343 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344 /// void*, which is a requirement of device side enqueue.
345 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346  const BlockPointerType *BPT =
347  cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348  ArrayRef<QualType> Params =
349  BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350  unsigned ArgCounter = 0;
351  bool IllegalParams = false;
352  // Iterate through the block parameters until either one is found that is not
353  // a local void*, or the block is valid.
354  for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355  I != E; ++I, ++ArgCounter) {
356  if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357  (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
359  // Get the location of the error. If a block literal has been passed
360  // (BlockExpr) then we can point straight to the offending argument,
361  // else we just point to the variable reference.
362  SourceLocation ErrorLoc;
363  if (isa<BlockExpr>(BlockArg)) {
364  BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365  ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366  } else if (isa<DeclRefExpr>(BlockArg)) {
367  ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
368  }
369  S.Diag(ErrorLoc,
370  diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371  IllegalParams = true;
372  }
373  }
374 
375  return IllegalParams;
376 }
377 
378 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379  if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380  S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381  << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
382  return true;
383  }
384  return false;
385 }
386 
387 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388  if (checkArgCount(S, TheCall, 2))
389  return true;
390 
391  if (checkOpenCLSubgroupExt(S, TheCall))
392  return true;
393 
394  // First argument is an ndrange_t type.
395  Expr *NDRangeArg = TheCall->getArg(0);
396  if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
397  S.Diag(NDRangeArg->getLocStart(),
398  diag::err_opencl_builtin_expected_type)
399  << TheCall->getDirectCallee() << "'ndrange_t'";
400  return true;
401  }
402 
403  Expr *BlockArg = TheCall->getArg(1);
404  if (!isBlockPointer(BlockArg)) {
405  S.Diag(BlockArg->getLocStart(),
406  diag::err_opencl_builtin_expected_type)
407  << TheCall->getDirectCallee() << "block";
408  return true;
409  }
410  return checkOpenCLBlockArgs(S, BlockArg);
411 }
412 
413 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414 /// get_kernel_work_group_size
415 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
417  if (checkArgCount(S, TheCall, 1))
418  return true;
419 
420  Expr *BlockArg = TheCall->getArg(0);
421  if (!isBlockPointer(BlockArg)) {
422  S.Diag(BlockArg->getLocStart(),
423  diag::err_opencl_builtin_expected_type)
424  << TheCall->getDirectCallee() << "block";
425  return true;
426  }
427  return checkOpenCLBlockArgs(S, BlockArg);
428 }
429 
430 /// Diagnose integer type and any valid implicit conversion to it.
431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432  const QualType &IntType);
433 
435  unsigned Start, unsigned End) {
436  bool IllegalParams = false;
437  for (unsigned I = Start; I <= End; ++I)
438  IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439  S.Context.getSizeType());
440  return IllegalParams;
441 }
442 
443 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444 /// 'local void*' parameter of passed block.
446  Expr *BlockArg,
447  unsigned NumNonVarArgs) {
448  const BlockPointerType *BPT =
449  cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450  unsigned NumBlockParams =
451  BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452  unsigned TotalNumArgs = TheCall->getNumArgs();
453 
454  // For each argument passed to the block, a corresponding uint needs to
455  // be passed to describe the size of the local memory.
456  if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457  S.Diag(TheCall->getLocStart(),
458  diag::err_opencl_enqueue_kernel_local_size_args);
459  return true;
460  }
461 
462  // Check that the sizes of the local memory are specified by integers.
463  return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
464  TotalNumArgs - 1);
465 }
466 
467 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468 /// overload formats specified in Table 6.13.17.1.
469 /// int enqueue_kernel(queue_t queue,
470 /// kernel_enqueue_flags_t flags,
471 /// const ndrange_t ndrange,
472 /// void (^block)(void))
473 /// int enqueue_kernel(queue_t queue,
474 /// kernel_enqueue_flags_t flags,
475 /// const ndrange_t ndrange,
476 /// uint num_events_in_wait_list,
477 /// clk_event_t *event_wait_list,
478 /// clk_event_t *event_ret,
479 /// void (^block)(void))
480 /// int enqueue_kernel(queue_t queue,
481 /// kernel_enqueue_flags_t flags,
482 /// const ndrange_t ndrange,
483 /// void (^block)(local void*, ...),
484 /// uint size0, ...)
485 /// int enqueue_kernel(queue_t queue,
486 /// kernel_enqueue_flags_t flags,
487 /// const ndrange_t ndrange,
488 /// uint num_events_in_wait_list,
489 /// clk_event_t *event_wait_list,
490 /// clk_event_t *event_ret,
491 /// void (^block)(local void*, ...),
492 /// uint size0, ...)
493 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494  unsigned NumArgs = TheCall->getNumArgs();
495 
496  if (NumArgs < 4) {
497  S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
498  return true;
499  }
500 
501  Expr *Arg0 = TheCall->getArg(0);
502  Expr *Arg1 = TheCall->getArg(1);
503  Expr *Arg2 = TheCall->getArg(2);
504  Expr *Arg3 = TheCall->getArg(3);
505 
506  // First argument always needs to be a queue_t type.
507  if (!Arg0->getType()->isQueueT()) {
508  S.Diag(TheCall->getArg(0)->getLocStart(),
509  diag::err_opencl_builtin_expected_type)
510  << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
511  return true;
512  }
513 
514  // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515  if (!Arg1->getType()->isIntegerType()) {
516  S.Diag(TheCall->getArg(1)->getLocStart(),
517  diag::err_opencl_builtin_expected_type)
518  << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
519  return true;
520  }
521 
522  // Third argument is always an ndrange_t type.
523  if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
524  S.Diag(TheCall->getArg(2)->getLocStart(),
525  diag::err_opencl_builtin_expected_type)
526  << TheCall->getDirectCallee() << "'ndrange_t'";
527  return true;
528  }
529 
530  // With four arguments, there is only one form that the function could be
531  // called in: no events and no variable arguments.
532  if (NumArgs == 4) {
533  // check that the last argument is the right block type.
534  if (!isBlockPointer(Arg3)) {
535  S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536  << TheCall->getDirectCallee() << "block";
537  return true;
538  }
539  // we have a block type, check the prototype
540  const BlockPointerType *BPT =
541  cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542  if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543  S.Diag(Arg3->getLocStart(),
544  diag::err_opencl_enqueue_kernel_blocks_no_args);
545  return true;
546  }
547  return false;
548  }
549  // we can have block + varargs.
550  if (isBlockPointer(Arg3))
551  return (checkOpenCLBlockArgs(S, Arg3) ||
552  checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553  // last two cases with either exactly 7 args or 7 args and varargs.
554  if (NumArgs >= 7) {
555  // check common block argument.
556  Expr *Arg6 = TheCall->getArg(6);
557  if (!isBlockPointer(Arg6)) {
558  S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559  << TheCall->getDirectCallee() << "block";
560  return true;
561  }
562  if (checkOpenCLBlockArgs(S, Arg6))
563  return true;
564 
565  // Forth argument has to be any integer type.
566  if (!Arg3->getType()->isIntegerType()) {
567  S.Diag(TheCall->getArg(3)->getLocStart(),
568  diag::err_opencl_builtin_expected_type)
569  << TheCall->getDirectCallee() << "integer";
570  return true;
571  }
572  // check remaining common arguments.
573  Expr *Arg4 = TheCall->getArg(4);
574  Expr *Arg5 = TheCall->getArg(5);
575 
576  // Fifth argument is always passed as a pointer to clk_event_t.
577  if (!Arg4->isNullPointerConstant(S.Context,
580  S.Diag(TheCall->getArg(4)->getLocStart(),
581  diag::err_opencl_builtin_expected_type)
582  << TheCall->getDirectCallee()
584  return true;
585  }
586 
587  // Sixth argument is always passed as a pointer to clk_event_t.
588  if (!Arg5->isNullPointerConstant(S.Context,
590  !(Arg5->getType()->isPointerType() &&
591  Arg5->getType()->getPointeeType()->isClkEventT())) {
592  S.Diag(TheCall->getArg(5)->getLocStart(),
593  diag::err_opencl_builtin_expected_type)
594  << TheCall->getDirectCallee()
596  return true;
597  }
598 
599  if (NumArgs == 7)
600  return false;
601 
602  return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
603  }
604 
605  // None of the specific case has been detected, give generic error
606  S.Diag(TheCall->getLocStart(),
607  diag::err_opencl_enqueue_kernel_incorrect_args);
608  return true;
609 }
610 
611 /// Returns OpenCL access qual.
612 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
613  return D->getAttr<OpenCLAccessAttr>();
614 }
615 
616 /// Returns true if pipe element type is different from the pointer.
617 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618  const Expr *Arg0 = Call->getArg(0);
619  // First argument type should always be pipe.
620  if (!Arg0->getType()->isPipeType()) {
621  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
622  << Call->getDirectCallee() << Arg0->getSourceRange();
623  return true;
624  }
625  OpenCLAccessAttr *AccessQual =
626  getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627  // Validates the access qualifier is compatible with the call.
628  // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629  // read_only and write_only, and assumed to be read_only if no qualifier is
630  // specified.
631  switch (Call->getDirectCallee()->getBuiltinID()) {
632  case Builtin::BIread_pipe:
633  case Builtin::BIreserve_read_pipe:
634  case Builtin::BIcommit_read_pipe:
635  case Builtin::BIwork_group_reserve_read_pipe:
636  case Builtin::BIsub_group_reserve_read_pipe:
637  case Builtin::BIwork_group_commit_read_pipe:
638  case Builtin::BIsub_group_commit_read_pipe:
639  if (!(!AccessQual || AccessQual->isReadOnly())) {
640  S.Diag(Arg0->getLocStart(),
641  diag::err_opencl_builtin_pipe_invalid_access_modifier)
642  << "read_only" << Arg0->getSourceRange();
643  return true;
644  }
645  break;
646  case Builtin::BIwrite_pipe:
647  case Builtin::BIreserve_write_pipe:
648  case Builtin::BIcommit_write_pipe:
649  case Builtin::BIwork_group_reserve_write_pipe:
650  case Builtin::BIsub_group_reserve_write_pipe:
651  case Builtin::BIwork_group_commit_write_pipe:
652  case Builtin::BIsub_group_commit_write_pipe:
653  if (!(AccessQual && AccessQual->isWriteOnly())) {
654  S.Diag(Arg0->getLocStart(),
655  diag::err_opencl_builtin_pipe_invalid_access_modifier)
656  << "write_only" << Arg0->getSourceRange();
657  return true;
658  }
659  break;
660  default:
661  break;
662  }
663  return false;
664 }
665 
666 /// Returns true if pipe element type is different from the pointer.
667 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668  const Expr *Arg0 = Call->getArg(0);
669  const Expr *ArgIdx = Call->getArg(Idx);
670  const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
671  const QualType EltTy = PipeTy->getElementType();
672  const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
673  // The Idx argument should be a pointer and the type of the pointer and
674  // the type of pipe element should also be the same.
675  if (!ArgTy ||
676  !S.Context.hasSameType(
677  EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
678  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
679  << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
680  << ArgIdx->getType() << ArgIdx->getSourceRange();
681  return true;
682  }
683  return false;
684 }
685 
686 // \brief Performs semantic analysis for the read/write_pipe call.
687 // \param S Reference to the semantic analyzer.
688 // \param Call A pointer to the builtin call.
689 // \return True if a semantic error has been found, false otherwise.
690 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
691  // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692  // functions have two forms.
693  switch (Call->getNumArgs()) {
694  case 2:
695  if (checkOpenCLPipeArg(S, Call))
696  return true;
697  // The call with 2 arguments should be
698  // read/write_pipe(pipe T, T*).
699  // Check packet type T.
700  if (checkOpenCLPipePacketType(S, Call, 1))
701  return true;
702  break;
703 
704  case 4: {
705  if (checkOpenCLPipeArg(S, Call))
706  return true;
707  // The call with 4 arguments should be
708  // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709  // Check reserve_id_t.
710  if (!Call->getArg(1)->getType()->isReserveIDT()) {
711  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
712  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
713  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
714  return true;
715  }
716 
717  // Check the index.
718  const Expr *Arg2 = Call->getArg(2);
719  if (!Arg2->getType()->isIntegerType() &&
720  !Arg2->getType()->isUnsignedIntegerType()) {
721  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
722  << Call->getDirectCallee() << S.Context.UnsignedIntTy
723  << Arg2->getType() << Arg2->getSourceRange();
724  return true;
725  }
726 
727  // Check packet type T.
728  if (checkOpenCLPipePacketType(S, Call, 3))
729  return true;
730  } break;
731  default:
732  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
733  << Call->getDirectCallee() << Call->getSourceRange();
734  return true;
735  }
736 
737  return false;
738 }
739 
740 // \brief Performs a semantic analysis on the {work_group_/sub_group_
741 // /_}reserve_{read/write}_pipe
742 // \param S Reference to the semantic analyzer.
743 // \param Call The call to the builtin function to be analyzed.
744 // \return True if a semantic error was found, false otherwise.
745 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746  if (checkArgCount(S, Call, 2))
747  return true;
748 
749  if (checkOpenCLPipeArg(S, Call))
750  return true;
751 
752  // Check the reserve size.
753  if (!Call->getArg(1)->getType()->isIntegerType() &&
754  !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
756  << Call->getDirectCallee() << S.Context.UnsignedIntTy
757  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
758  return true;
759  }
760 
761  // Since return type of reserve_read/write_pipe built-in function is
762  // reserve_id_t, which is not defined in the builtin def file , we used int
763  // as return type and need to override the return type of these functions.
764  Call->setType(S.Context.OCLReserveIDTy);
765 
766  return false;
767 }
768 
769 // \brief Performs a semantic analysis on {work_group_/sub_group_
770 // /_}commit_{read/write}_pipe
771 // \param S Reference to the semantic analyzer.
772 // \param Call The call to the builtin function to be analyzed.
773 // \return True if a semantic error was found, false otherwise.
774 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775  if (checkArgCount(S, Call, 2))
776  return true;
777 
778  if (checkOpenCLPipeArg(S, Call))
779  return true;
780 
781  // Check reserve_id_t.
782  if (!Call->getArg(1)->getType()->isReserveIDT()) {
783  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
784  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
785  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
786  return true;
787  }
788 
789  return false;
790 }
791 
792 // \brief Performs a semantic analysis on the call to built-in Pipe
793 // Query Functions.
794 // \param S Reference to the semantic analyzer.
795 // \param Call The call to the builtin function to be analyzed.
796 // \return True if a semantic error was found, false otherwise.
797 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798  if (checkArgCount(S, Call, 1))
799  return true;
800 
801  if (!Call->getArg(0)->getType()->isPipeType()) {
802  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
803  << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
804  return true;
805  }
806 
807  return false;
808 }
809 
810 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
811 // \brief Performs semantic analysis for the to_global/local/private call.
812 // \param S Reference to the semantic analyzer.
813 // \param BuiltinID ID of the builtin function.
814 // \param Call A pointer to the builtin call.
815 // \return True if a semantic error has been found, false otherwise.
816 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817  CallExpr *Call) {
818  if (Call->getNumArgs() != 1) {
819  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820  << Call->getDirectCallee() << Call->getSourceRange();
821  return true;
822  }
823 
824  auto RT = Call->getArg(0)->getType();
825  if (!RT->isPointerType() || RT->getPointeeType()
826  .getAddressSpace() == LangAS::opencl_constant) {
827  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828  << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
829  return true;
830  }
831 
832  RT = RT->getPointeeType();
833  auto Qual = RT.getQualifiers();
834  switch (BuiltinID) {
835  case Builtin::BIto_global:
836  Qual.setAddressSpace(LangAS::opencl_global);
837  break;
838  case Builtin::BIto_local:
839  Qual.setAddressSpace(LangAS::opencl_local);
840  break;
841  case Builtin::BIto_private:
842  Qual.setAddressSpace(LangAS::opencl_private);
843  break;
844  default:
845  llvm_unreachable("Invalid builtin function");
846  }
848  RT.getUnqualifiedType(), Qual)));
849 
850  return false;
851 }
852 
854 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855  CallExpr *TheCall) {
856  ExprResult TheCallResult(TheCall);
857 
858  // Find out if any arguments are required to be integer constant expressions.
859  unsigned ICEArguments = 0;
861  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862  if (Error != ASTContext::GE_None)
863  ICEArguments = 0; // Don't diagnose previously diagnosed errors.
864 
865  // If any arguments are required to be ICE's, check and diagnose.
866  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867  // Skip arguments not required to be ICE's.
868  if ((ICEArguments & (1 << ArgNo)) == 0) continue;
869 
870  llvm::APSInt Result;
871  if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
872  return true;
873  ICEArguments &= ~(1 << ArgNo);
874  }
875 
876  switch (BuiltinID) {
877  case Builtin::BI__builtin___CFStringMakeConstantString:
878  assert(TheCall->getNumArgs() == 1 &&
879  "Wrong # arguments to builtin CFStringMakeConstantString");
880  if (CheckObjCString(TheCall->getArg(0)))
881  return ExprError();
882  break;
883  case Builtin::BI__builtin_ms_va_start:
884  case Builtin::BI__builtin_stdarg_start:
885  case Builtin::BI__builtin_va_start:
886  if (SemaBuiltinVAStart(BuiltinID, TheCall))
887  return ExprError();
888  break;
889  case Builtin::BI__va_start: {
890  switch (Context.getTargetInfo().getTriple().getArch()) {
891  case llvm::Triple::arm:
892  case llvm::Triple::thumb:
893  if (SemaBuiltinVAStartARMMicrosoft(TheCall))
894  return ExprError();
895  break;
896  default:
897  if (SemaBuiltinVAStart(BuiltinID, TheCall))
898  return ExprError();
899  break;
900  }
901  break;
902  }
903  case Builtin::BI__builtin_isgreater:
904  case Builtin::BI__builtin_isgreaterequal:
905  case Builtin::BI__builtin_isless:
906  case Builtin::BI__builtin_islessequal:
907  case Builtin::BI__builtin_islessgreater:
908  case Builtin::BI__builtin_isunordered:
909  if (SemaBuiltinUnorderedCompare(TheCall))
910  return ExprError();
911  break;
912  case Builtin::BI__builtin_fpclassify:
913  if (SemaBuiltinFPClassification(TheCall, 6))
914  return ExprError();
915  break;
916  case Builtin::BI__builtin_isfinite:
917  case Builtin::BI__builtin_isinf:
918  case Builtin::BI__builtin_isinf_sign:
919  case Builtin::BI__builtin_isnan:
920  case Builtin::BI__builtin_isnormal:
921  if (SemaBuiltinFPClassification(TheCall, 1))
922  return ExprError();
923  break;
924  case Builtin::BI__builtin_shufflevector:
925  return SemaBuiltinShuffleVector(TheCall);
926  // TheCall will be freed by the smart pointer here, but that's fine, since
927  // SemaBuiltinShuffleVector guts it, but then doesn't release it.
928  case Builtin::BI__builtin_prefetch:
929  if (SemaBuiltinPrefetch(TheCall))
930  return ExprError();
931  break;
932  case Builtin::BI__builtin_alloca_with_align:
933  if (SemaBuiltinAllocaWithAlign(TheCall))
934  return ExprError();
935  break;
936  case Builtin::BI__assume:
937  case Builtin::BI__builtin_assume:
938  if (SemaBuiltinAssume(TheCall))
939  return ExprError();
940  break;
941  case Builtin::BI__builtin_assume_aligned:
942  if (SemaBuiltinAssumeAligned(TheCall))
943  return ExprError();
944  break;
945  case Builtin::BI__builtin_object_size:
946  if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
947  return ExprError();
948  break;
949  case Builtin::BI__builtin_longjmp:
950  if (SemaBuiltinLongjmp(TheCall))
951  return ExprError();
952  break;
953  case Builtin::BI__builtin_setjmp:
954  if (SemaBuiltinSetjmp(TheCall))
955  return ExprError();
956  break;
957  case Builtin::BI_setjmp:
958  case Builtin::BI_setjmpex:
959  if (checkArgCount(*this, TheCall, 1))
960  return true;
961  break;
962  case Builtin::BI__builtin_classify_type:
963  if (checkArgCount(*this, TheCall, 1)) return true;
964  TheCall->setType(Context.IntTy);
965  break;
966  case Builtin::BI__builtin_constant_p:
967  if (checkArgCount(*this, TheCall, 1)) return true;
968  TheCall->setType(Context.IntTy);
969  break;
970  case Builtin::BI__sync_fetch_and_add:
971  case Builtin::BI__sync_fetch_and_add_1:
972  case Builtin::BI__sync_fetch_and_add_2:
973  case Builtin::BI__sync_fetch_and_add_4:
974  case Builtin::BI__sync_fetch_and_add_8:
975  case Builtin::BI__sync_fetch_and_add_16:
976  case Builtin::BI__sync_fetch_and_sub:
977  case Builtin::BI__sync_fetch_and_sub_1:
978  case Builtin::BI__sync_fetch_and_sub_2:
979  case Builtin::BI__sync_fetch_and_sub_4:
980  case Builtin::BI__sync_fetch_and_sub_8:
981  case Builtin::BI__sync_fetch_and_sub_16:
982  case Builtin::BI__sync_fetch_and_or:
983  case Builtin::BI__sync_fetch_and_or_1:
984  case Builtin::BI__sync_fetch_and_or_2:
985  case Builtin::BI__sync_fetch_and_or_4:
986  case Builtin::BI__sync_fetch_and_or_8:
987  case Builtin::BI__sync_fetch_and_or_16:
988  case Builtin::BI__sync_fetch_and_and:
989  case Builtin::BI__sync_fetch_and_and_1:
990  case Builtin::BI__sync_fetch_and_and_2:
991  case Builtin::BI__sync_fetch_and_and_4:
992  case Builtin::BI__sync_fetch_and_and_8:
993  case Builtin::BI__sync_fetch_and_and_16:
994  case Builtin::BI__sync_fetch_and_xor:
995  case Builtin::BI__sync_fetch_and_xor_1:
996  case Builtin::BI__sync_fetch_and_xor_2:
997  case Builtin::BI__sync_fetch_and_xor_4:
998  case Builtin::BI__sync_fetch_and_xor_8:
999  case Builtin::BI__sync_fetch_and_xor_16:
1000  case Builtin::BI__sync_fetch_and_nand:
1001  case Builtin::BI__sync_fetch_and_nand_1:
1002  case Builtin::BI__sync_fetch_and_nand_2:
1003  case Builtin::BI__sync_fetch_and_nand_4:
1004  case Builtin::BI__sync_fetch_and_nand_8:
1005  case Builtin::BI__sync_fetch_and_nand_16:
1006  case Builtin::BI__sync_add_and_fetch:
1007  case Builtin::BI__sync_add_and_fetch_1:
1008  case Builtin::BI__sync_add_and_fetch_2:
1009  case Builtin::BI__sync_add_and_fetch_4:
1010  case Builtin::BI__sync_add_and_fetch_8:
1011  case Builtin::BI__sync_add_and_fetch_16:
1012  case Builtin::BI__sync_sub_and_fetch:
1013  case Builtin::BI__sync_sub_and_fetch_1:
1014  case Builtin::BI__sync_sub_and_fetch_2:
1015  case Builtin::BI__sync_sub_and_fetch_4:
1016  case Builtin::BI__sync_sub_and_fetch_8:
1017  case Builtin::BI__sync_sub_and_fetch_16:
1018  case Builtin::BI__sync_and_and_fetch:
1019  case Builtin::BI__sync_and_and_fetch_1:
1020  case Builtin::BI__sync_and_and_fetch_2:
1021  case Builtin::BI__sync_and_and_fetch_4:
1022  case Builtin::BI__sync_and_and_fetch_8:
1023  case Builtin::BI__sync_and_and_fetch_16:
1024  case Builtin::BI__sync_or_and_fetch:
1025  case Builtin::BI__sync_or_and_fetch_1:
1026  case Builtin::BI__sync_or_and_fetch_2:
1027  case Builtin::BI__sync_or_and_fetch_4:
1028  case Builtin::BI__sync_or_and_fetch_8:
1029  case Builtin::BI__sync_or_and_fetch_16:
1030  case Builtin::BI__sync_xor_and_fetch:
1031  case Builtin::BI__sync_xor_and_fetch_1:
1032  case Builtin::BI__sync_xor_and_fetch_2:
1033  case Builtin::BI__sync_xor_and_fetch_4:
1034  case Builtin::BI__sync_xor_and_fetch_8:
1035  case Builtin::BI__sync_xor_and_fetch_16:
1036  case Builtin::BI__sync_nand_and_fetch:
1037  case Builtin::BI__sync_nand_and_fetch_1:
1038  case Builtin::BI__sync_nand_and_fetch_2:
1039  case Builtin::BI__sync_nand_and_fetch_4:
1040  case Builtin::BI__sync_nand_and_fetch_8:
1041  case Builtin::BI__sync_nand_and_fetch_16:
1042  case Builtin::BI__sync_val_compare_and_swap:
1043  case Builtin::BI__sync_val_compare_and_swap_1:
1044  case Builtin::BI__sync_val_compare_and_swap_2:
1045  case Builtin::BI__sync_val_compare_and_swap_4:
1046  case Builtin::BI__sync_val_compare_and_swap_8:
1047  case Builtin::BI__sync_val_compare_and_swap_16:
1048  case Builtin::BI__sync_bool_compare_and_swap:
1049  case Builtin::BI__sync_bool_compare_and_swap_1:
1050  case Builtin::BI__sync_bool_compare_and_swap_2:
1051  case Builtin::BI__sync_bool_compare_and_swap_4:
1052  case Builtin::BI__sync_bool_compare_and_swap_8:
1053  case Builtin::BI__sync_bool_compare_and_swap_16:
1054  case Builtin::BI__sync_lock_test_and_set:
1055  case Builtin::BI__sync_lock_test_and_set_1:
1056  case Builtin::BI__sync_lock_test_and_set_2:
1057  case Builtin::BI__sync_lock_test_and_set_4:
1058  case Builtin::BI__sync_lock_test_and_set_8:
1059  case Builtin::BI__sync_lock_test_and_set_16:
1060  case Builtin::BI__sync_lock_release:
1061  case Builtin::BI__sync_lock_release_1:
1062  case Builtin::BI__sync_lock_release_2:
1063  case Builtin::BI__sync_lock_release_4:
1064  case Builtin::BI__sync_lock_release_8:
1065  case Builtin::BI__sync_lock_release_16:
1066  case Builtin::BI__sync_swap:
1067  case Builtin::BI__sync_swap_1:
1068  case Builtin::BI__sync_swap_2:
1069  case Builtin::BI__sync_swap_4:
1070  case Builtin::BI__sync_swap_8:
1071  case Builtin::BI__sync_swap_16:
1072  return SemaBuiltinAtomicOverloaded(TheCallResult);
1073  case Builtin::BI__builtin_nontemporal_load:
1074  case Builtin::BI__builtin_nontemporal_store:
1075  return SemaBuiltinNontemporalOverloaded(TheCallResult);
1076 #define BUILTIN(ID, TYPE, ATTRS)
1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078  case Builtin::BI##ID: \
1079  return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1080 #include "clang/Basic/Builtins.def"
1081  case Builtin::BI__annotation:
1082  if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083  return ExprError();
1084  break;
1085  case Builtin::BI__builtin_annotation:
1086  if (SemaBuiltinAnnotation(*this, TheCall))
1087  return ExprError();
1088  break;
1089  case Builtin::BI__builtin_addressof:
1090  if (SemaBuiltinAddressof(*this, TheCall))
1091  return ExprError();
1092  break;
1093  case Builtin::BI__builtin_add_overflow:
1094  case Builtin::BI__builtin_sub_overflow:
1095  case Builtin::BI__builtin_mul_overflow:
1096  if (SemaBuiltinOverflow(*this, TheCall))
1097  return ExprError();
1098  break;
1099  case Builtin::BI__builtin_operator_new:
1100  case Builtin::BI__builtin_operator_delete:
1101  if (!getLangOpts().CPlusPlus) {
1102  Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1103  << (BuiltinID == Builtin::BI__builtin_operator_new
1104  ? "__builtin_operator_new"
1105  : "__builtin_operator_delete")
1106  << "C++";
1107  return ExprError();
1108  }
1109  // CodeGen assumes it can find the global new and delete to call,
1110  // so ensure that they are declared.
1111  DeclareGlobalNewDelete();
1112  break;
1113 
1114  // check secure string manipulation functions where overflows
1115  // are detectable at compile time
1116  case Builtin::BI__builtin___memcpy_chk:
1117  case Builtin::BI__builtin___memmove_chk:
1118  case Builtin::BI__builtin___memset_chk:
1119  case Builtin::BI__builtin___strlcat_chk:
1120  case Builtin::BI__builtin___strlcpy_chk:
1121  case Builtin::BI__builtin___strncat_chk:
1122  case Builtin::BI__builtin___strncpy_chk:
1123  case Builtin::BI__builtin___stpncpy_chk:
1124  SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1125  break;
1126  case Builtin::BI__builtin___memccpy_chk:
1127  SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1128  break;
1129  case Builtin::BI__builtin___snprintf_chk:
1130  case Builtin::BI__builtin___vsnprintf_chk:
1131  SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1132  break;
1133  case Builtin::BI__builtin_call_with_static_chain:
1134  if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1135  return ExprError();
1136  break;
1137  case Builtin::BI__exception_code:
1138  case Builtin::BI_exception_code:
1139  if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1140  diag::err_seh___except_block))
1141  return ExprError();
1142  break;
1143  case Builtin::BI__exception_info:
1144  case Builtin::BI_exception_info:
1145  if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1146  diag::err_seh___except_filter))
1147  return ExprError();
1148  break;
1149  case Builtin::BI__GetExceptionInfo:
1150  if (checkArgCount(*this, TheCall, 1))
1151  return ExprError();
1152 
1153  if (CheckCXXThrowOperand(
1154  TheCall->getLocStart(),
1155  Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1156  TheCall))
1157  return ExprError();
1158 
1159  TheCall->setType(Context.VoidPtrTy);
1160  break;
1161  // OpenCL v2.0, s6.13.16 - Pipe functions
1162  case Builtin::BIread_pipe:
1163  case Builtin::BIwrite_pipe:
1164  // Since those two functions are declared with var args, we need a semantic
1165  // check for the argument.
1166  if (SemaBuiltinRWPipe(*this, TheCall))
1167  return ExprError();
1168  TheCall->setType(Context.IntTy);
1169  break;
1170  case Builtin::BIreserve_read_pipe:
1171  case Builtin::BIreserve_write_pipe:
1172  case Builtin::BIwork_group_reserve_read_pipe:
1173  case Builtin::BIwork_group_reserve_write_pipe:
1174  if (SemaBuiltinReserveRWPipe(*this, TheCall))
1175  return ExprError();
1176  break;
1177  case Builtin::BIsub_group_reserve_read_pipe:
1178  case Builtin::BIsub_group_reserve_write_pipe:
1179  if (checkOpenCLSubgroupExt(*this, TheCall) ||
1180  SemaBuiltinReserveRWPipe(*this, TheCall))
1181  return ExprError();
1182  break;
1183  case Builtin::BIcommit_read_pipe:
1184  case Builtin::BIcommit_write_pipe:
1185  case Builtin::BIwork_group_commit_read_pipe:
1186  case Builtin::BIwork_group_commit_write_pipe:
1187  if (SemaBuiltinCommitRWPipe(*this, TheCall))
1188  return ExprError();
1189  break;
1190  case Builtin::BIsub_group_commit_read_pipe:
1191  case Builtin::BIsub_group_commit_write_pipe:
1192  if (checkOpenCLSubgroupExt(*this, TheCall) ||
1193  SemaBuiltinCommitRWPipe(*this, TheCall))
1194  return ExprError();
1195  break;
1196  case Builtin::BIget_pipe_num_packets:
1197  case Builtin::BIget_pipe_max_packets:
1198  if (SemaBuiltinPipePackets(*this, TheCall))
1199  return ExprError();
1200  TheCall->setType(Context.UnsignedIntTy);
1201  break;
1202  case Builtin::BIto_global:
1203  case Builtin::BIto_local:
1204  case Builtin::BIto_private:
1205  if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1206  return ExprError();
1207  break;
1208  // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1209  case Builtin::BIenqueue_kernel:
1210  if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1211  return ExprError();
1212  break;
1213  case Builtin::BIget_kernel_work_group_size:
1214  case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1215  if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1216  return ExprError();
1217  break;
1218  break;
1219  case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1220  case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1221  if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1222  return ExprError();
1223  break;
1224  case Builtin::BI__builtin_os_log_format:
1225  case Builtin::BI__builtin_os_log_format_buffer_size:
1226  if (SemaBuiltinOSLogFormat(TheCall))
1227  return ExprError();
1228  break;
1229  }
1230 
1231  // Since the target specific builtins for each arch overlap, only check those
1232  // of the arch we are compiling for.
1233  if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1234  switch (Context.getTargetInfo().getTriple().getArch()) {
1235  case llvm::Triple::arm:
1236  case llvm::Triple::armeb:
1237  case llvm::Triple::thumb:
1238  case llvm::Triple::thumbeb:
1239  if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1240  return ExprError();
1241  break;
1242  case llvm::Triple::aarch64:
1243  case llvm::Triple::aarch64_be:
1244  if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1245  return ExprError();
1246  break;
1247  case llvm::Triple::mips:
1248  case llvm::Triple::mipsel:
1249  case llvm::Triple::mips64:
1250  case llvm::Triple::mips64el:
1251  if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1252  return ExprError();
1253  break;
1254  case llvm::Triple::systemz:
1255  if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1256  return ExprError();
1257  break;
1258  case llvm::Triple::x86:
1259  case llvm::Triple::x86_64:
1260  if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1261  return ExprError();
1262  break;
1263  case llvm::Triple::ppc:
1264  case llvm::Triple::ppc64:
1265  case llvm::Triple::ppc64le:
1266  if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1267  return ExprError();
1268  break;
1269  default:
1270  break;
1271  }
1272  }
1273 
1274  return TheCallResult;
1275 }
1276 
1277 // Get the valid immediate range for the specified NEON type code.
1278 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1279  NeonTypeFlags Type(t);
1280  int IsQuad = ForceQuad ? true : Type.isQuad();
1281  switch (Type.getEltType()) {
1282  case NeonTypeFlags::Int8:
1283  case NeonTypeFlags::Poly8:
1284  return shift ? 7 : (8 << IsQuad) - 1;
1285  case NeonTypeFlags::Int16:
1286  case NeonTypeFlags::Poly16:
1287  return shift ? 15 : (4 << IsQuad) - 1;
1288  case NeonTypeFlags::Int32:
1289  return shift ? 31 : (2 << IsQuad) - 1;
1290  case NeonTypeFlags::Int64:
1291  case NeonTypeFlags::Poly64:
1292  return shift ? 63 : (1 << IsQuad) - 1;
1294  return shift ? 127 : (1 << IsQuad) - 1;
1296  assert(!shift && "cannot shift float types!");
1297  return (4 << IsQuad) - 1;
1299  assert(!shift && "cannot shift float types!");
1300  return (2 << IsQuad) - 1;
1302  assert(!shift && "cannot shift float types!");
1303  return (1 << IsQuad) - 1;
1304  }
1305  llvm_unreachable("Invalid NeonTypeFlag!");
1306 }
1307 
1308 /// getNeonEltType - Return the QualType corresponding to the elements of
1309 /// the vector type specified by the NeonTypeFlags. This is used to check
1310 /// the pointer arguments for Neon load/store intrinsics.
1312  bool IsPolyUnsigned, bool IsInt64Long) {
1313  switch (Flags.getEltType()) {
1314  case NeonTypeFlags::Int8:
1315  return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1316  case NeonTypeFlags::Int16:
1317  return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1318  case NeonTypeFlags::Int32:
1319  return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1320  case NeonTypeFlags::Int64:
1321  if (IsInt64Long)
1322  return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1323  else
1324  return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1325  : Context.LongLongTy;
1326  case NeonTypeFlags::Poly8:
1327  return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1328  case NeonTypeFlags::Poly16:
1329  return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1330  case NeonTypeFlags::Poly64:
1331  if (IsInt64Long)
1332  return Context.UnsignedLongTy;
1333  else
1334  return Context.UnsignedLongLongTy;
1336  break;
1338  return Context.HalfTy;
1340  return Context.FloatTy;
1342  return Context.DoubleTy;
1343  }
1344  llvm_unreachable("Invalid NeonTypeFlag!");
1345 }
1346 
1347 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1348  llvm::APSInt Result;
1349  uint64_t mask = 0;
1350  unsigned TV = 0;
1351  int PtrArgNum = -1;
1352  bool HasConstPtr = false;
1353  switch (BuiltinID) {
1354 #define GET_NEON_OVERLOAD_CHECK
1355 #include "clang/Basic/arm_neon.inc"
1356 #undef GET_NEON_OVERLOAD_CHECK
1357  }
1358 
1359  // For NEON intrinsics which are overloaded on vector element type, validate
1360  // the immediate which specifies which variant to emit.
1361  unsigned ImmArg = TheCall->getNumArgs()-1;
1362  if (mask) {
1363  if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1364  return true;
1365 
1366  TV = Result.getLimitedValue(64);
1367  if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1368  return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1369  << TheCall->getArg(ImmArg)->getSourceRange();
1370  }
1371 
1372  if (PtrArgNum >= 0) {
1373  // Check that pointer arguments have the specified type.
1374  Expr *Arg = TheCall->getArg(PtrArgNum);
1375  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1376  Arg = ICE->getSubExpr();
1377  ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1378  QualType RHSTy = RHS.get()->getType();
1379 
1380  llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1381  bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1382  Arch == llvm::Triple::aarch64_be;
1383  bool IsInt64Long =
1385  QualType EltTy =
1386  getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1387  if (HasConstPtr)
1388  EltTy = EltTy.withConst();
1389  QualType LHSTy = Context.getPointerType(EltTy);
1390  AssignConvertType ConvTy;
1391  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1392  if (RHS.isInvalid())
1393  return true;
1394  if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1395  RHS.get(), AA_Assigning))
1396  return true;
1397  }
1398 
1399  // For NEON intrinsics which take an immediate value as part of the
1400  // instruction, range check them here.
1401  unsigned i = 0, l = 0, u = 0;
1402  switch (BuiltinID) {
1403  default:
1404  return false;
1405 #define GET_NEON_IMMEDIATE_CHECK
1406 #include "clang/Basic/arm_neon.inc"
1407 #undef GET_NEON_IMMEDIATE_CHECK
1408  }
1409 
1410  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1411 }
1412 
1413 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1414  unsigned MaxWidth) {
1415  assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1416  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1417  BuiltinID == ARM::BI__builtin_arm_strex ||
1418  BuiltinID == ARM::BI__builtin_arm_stlex ||
1419  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1420  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1421  BuiltinID == AArch64::BI__builtin_arm_strex ||
1422  BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1423  "unexpected ARM builtin");
1424  bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1425  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1426  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1427  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1428 
1429  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1430 
1431  // Ensure that we have the proper number of arguments.
1432  if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1433  return true;
1434 
1435  // Inspect the pointer argument of the atomic builtin. This should always be
1436  // a pointer type, whose element is an integral scalar or pointer type.
1437  // Because it is a pointer type, we don't have to worry about any implicit
1438  // casts here.
1439  Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1440  ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1441  if (PointerArgRes.isInvalid())
1442  return true;
1443  PointerArg = PointerArgRes.get();
1444 
1445  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1446  if (!pointerType) {
1447  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1448  << PointerArg->getType() << PointerArg->getSourceRange();
1449  return true;
1450  }
1451 
1452  // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1453  // task is to insert the appropriate casts into the AST. First work out just
1454  // what the appropriate type is.
1455  QualType ValType = pointerType->getPointeeType();
1456  QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1457  if (IsLdrex)
1458  AddrType.addConst();
1459 
1460  // Issue a warning if the cast is dodgy.
1461  CastKind CastNeeded = CK_NoOp;
1462  if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1463  CastNeeded = CK_BitCast;
1464  Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1465  << PointerArg->getType()
1466  << Context.getPointerType(AddrType)
1467  << AA_Passing << PointerArg->getSourceRange();
1468  }
1469 
1470  // Finally, do the cast and replace the argument with the corrected version.
1471  AddrType = Context.getPointerType(AddrType);
1472  PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1473  if (PointerArgRes.isInvalid())
1474  return true;
1475  PointerArg = PointerArgRes.get();
1476 
1477  TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1478 
1479  // In general, we allow ints, floats and pointers to be loaded and stored.
1480  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1481  !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1482  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1483  << PointerArg->getType() << PointerArg->getSourceRange();
1484  return true;
1485  }
1486 
1487  // But ARM doesn't have instructions to deal with 128-bit versions.
1488  if (Context.getTypeSize(ValType) > MaxWidth) {
1489  assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1490  Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1491  << PointerArg->getType() << PointerArg->getSourceRange();
1492  return true;
1493  }
1494 
1495  switch (ValType.getObjCLifetime()) {
1496  case Qualifiers::OCL_None:
1498  // okay
1499  break;
1500 
1501  case Qualifiers::OCL_Weak:
1504  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1505  << ValType << PointerArg->getSourceRange();
1506  return true;
1507  }
1508 
1509  if (IsLdrex) {
1510  TheCall->setType(ValType);
1511  return false;
1512  }
1513 
1514  // Initialize the argument to be stored.
1515  ExprResult ValArg = TheCall->getArg(0);
1517  Context, ValType, /*consume*/ false);
1518  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1519  if (ValArg.isInvalid())
1520  return true;
1521  TheCall->setArg(0, ValArg.get());
1522 
1523  // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1524  // but the custom checker bypasses all default analysis.
1525  TheCall->setType(Context.IntTy);
1526  return false;
1527 }
1528 
1529 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1530  if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1531  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1532  BuiltinID == ARM::BI__builtin_arm_strex ||
1533  BuiltinID == ARM::BI__builtin_arm_stlex) {
1534  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1535  }
1536 
1537  if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1538  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1539  SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1540  }
1541 
1542  if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1543  BuiltinID == ARM::BI__builtin_arm_wsr64)
1544  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1545 
1546  if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1547  BuiltinID == ARM::BI__builtin_arm_rsrp ||
1548  BuiltinID == ARM::BI__builtin_arm_wsr ||
1549  BuiltinID == ARM::BI__builtin_arm_wsrp)
1550  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1551 
1552  if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1553  return true;
1554 
1555  // For intrinsics which take an immediate value as part of the instruction,
1556  // range check them here.
1557  // FIXME: VFP Intrinsics should error if VFP not present.
1558  switch (BuiltinID) {
1559  default: return false;
1560  case ARM::BI__builtin_arm_ssat:
1561  return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1562  case ARM::BI__builtin_arm_usat:
1563  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1564  case ARM::BI__builtin_arm_ssat16:
1565  return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1566  case ARM::BI__builtin_arm_usat16:
1567  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1568  case ARM::BI__builtin_arm_vcvtr_f:
1569  case ARM::BI__builtin_arm_vcvtr_d:
1570  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1571  case ARM::BI__builtin_arm_dmb:
1572  case ARM::BI__builtin_arm_dsb:
1573  case ARM::BI__builtin_arm_isb:
1574  case ARM::BI__builtin_arm_dbg:
1575  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1576  }
1577 }
1578 
1579 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1580  CallExpr *TheCall) {
1581  if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1582  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1583  BuiltinID == AArch64::BI__builtin_arm_strex ||
1584  BuiltinID == AArch64::BI__builtin_arm_stlex) {
1585  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1586  }
1587 
1588  if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1589  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1590  SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1591  SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1592  SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1593  }
1594 
1595  if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1596  BuiltinID == AArch64::BI__builtin_arm_wsr64)
1597  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1598 
1599  if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1600  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1601  BuiltinID == AArch64::BI__builtin_arm_wsr ||
1602  BuiltinID == AArch64::BI__builtin_arm_wsrp)
1603  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1604 
1605  if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1606  return true;
1607 
1608  // For intrinsics which take an immediate value as part of the instruction,
1609  // range check them here.
1610  unsigned i = 0, l = 0, u = 0;
1611  switch (BuiltinID) {
1612  default: return false;
1613  case AArch64::BI__builtin_arm_dmb:
1614  case AArch64::BI__builtin_arm_dsb:
1615  case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1616  }
1617 
1618  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1619 }
1620 
1621 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1622 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1623 // ordering for DSP is unspecified. MSA is ordered by the data format used
1624 // by the underlying instruction i.e., df/m, df/n and then by size.
1625 //
1626 // FIXME: The size tests here should instead be tablegen'd along with the
1627 // definitions from include/clang/Basic/BuiltinsMips.def.
1628 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1629 // be too.
1630 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1631  unsigned i = 0, l = 0, u = 0, m = 0;
1632  switch (BuiltinID) {
1633  default: return false;
1634  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1635  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1636  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1637  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1638  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1639  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1640  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1641  // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1642  // df/m field.
1643  // These intrinsics take an unsigned 3 bit immediate.
1644  case Mips::BI__builtin_msa_bclri_b:
1645  case Mips::BI__builtin_msa_bnegi_b:
1646  case Mips::BI__builtin_msa_bseti_b:
1647  case Mips::BI__builtin_msa_sat_s_b:
1648  case Mips::BI__builtin_msa_sat_u_b:
1649  case Mips::BI__builtin_msa_slli_b:
1650  case Mips::BI__builtin_msa_srai_b:
1651  case Mips::BI__builtin_msa_srari_b:
1652  case Mips::BI__builtin_msa_srli_b:
1653  case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1654  case Mips::BI__builtin_msa_binsli_b:
1655  case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1656  // These intrinsics take an unsigned 4 bit immediate.
1657  case Mips::BI__builtin_msa_bclri_h:
1658  case Mips::BI__builtin_msa_bnegi_h:
1659  case Mips::BI__builtin_msa_bseti_h:
1660  case Mips::BI__builtin_msa_sat_s_h:
1661  case Mips::BI__builtin_msa_sat_u_h:
1662  case Mips::BI__builtin_msa_slli_h:
1663  case Mips::BI__builtin_msa_srai_h:
1664  case Mips::BI__builtin_msa_srari_h:
1665  case Mips::BI__builtin_msa_srli_h:
1666  case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1667  case Mips::BI__builtin_msa_binsli_h:
1668  case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1669  // These intrinsics take an unsigned 5 bit immedate.
1670  // The first block of intrinsics actually have an unsigned 5 bit field,
1671  // not a df/n field.
1672  case Mips::BI__builtin_msa_clei_u_b:
1673  case Mips::BI__builtin_msa_clei_u_h:
1674  case Mips::BI__builtin_msa_clei_u_w:
1675  case Mips::BI__builtin_msa_clei_u_d:
1676  case Mips::BI__builtin_msa_clti_u_b:
1677  case Mips::BI__builtin_msa_clti_u_h:
1678  case Mips::BI__builtin_msa_clti_u_w:
1679  case Mips::BI__builtin_msa_clti_u_d:
1680  case Mips::BI__builtin_msa_maxi_u_b:
1681  case Mips::BI__builtin_msa_maxi_u_h:
1682  case Mips::BI__builtin_msa_maxi_u_w:
1683  case Mips::BI__builtin_msa_maxi_u_d:
1684  case Mips::BI__builtin_msa_mini_u_b:
1685  case Mips::BI__builtin_msa_mini_u_h:
1686  case Mips::BI__builtin_msa_mini_u_w:
1687  case Mips::BI__builtin_msa_mini_u_d:
1688  case Mips::BI__builtin_msa_addvi_b:
1689  case Mips::BI__builtin_msa_addvi_h:
1690  case Mips::BI__builtin_msa_addvi_w:
1691  case Mips::BI__builtin_msa_addvi_d:
1692  case Mips::BI__builtin_msa_bclri_w:
1693  case Mips::BI__builtin_msa_bnegi_w:
1694  case Mips::BI__builtin_msa_bseti_w:
1695  case Mips::BI__builtin_msa_sat_s_w:
1696  case Mips::BI__builtin_msa_sat_u_w:
1697  case Mips::BI__builtin_msa_slli_w:
1698  case Mips::BI__builtin_msa_srai_w:
1699  case Mips::BI__builtin_msa_srari_w:
1700  case Mips::BI__builtin_msa_srli_w:
1701  case Mips::BI__builtin_msa_srlri_w:
1702  case Mips::BI__builtin_msa_subvi_b:
1703  case Mips::BI__builtin_msa_subvi_h:
1704  case Mips::BI__builtin_msa_subvi_w:
1705  case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1706  case Mips::BI__builtin_msa_binsli_w:
1707  case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1708  // These intrinsics take an unsigned 6 bit immediate.
1709  case Mips::BI__builtin_msa_bclri_d:
1710  case Mips::BI__builtin_msa_bnegi_d:
1711  case Mips::BI__builtin_msa_bseti_d:
1712  case Mips::BI__builtin_msa_sat_s_d:
1713  case Mips::BI__builtin_msa_sat_u_d:
1714  case Mips::BI__builtin_msa_slli_d:
1715  case Mips::BI__builtin_msa_srai_d:
1716  case Mips::BI__builtin_msa_srari_d:
1717  case Mips::BI__builtin_msa_srli_d:
1718  case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1719  case Mips::BI__builtin_msa_binsli_d:
1720  case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1721  // These intrinsics take a signed 5 bit immediate.
1722  case Mips::BI__builtin_msa_ceqi_b:
1723  case Mips::BI__builtin_msa_ceqi_h:
1724  case Mips::BI__builtin_msa_ceqi_w:
1725  case Mips::BI__builtin_msa_ceqi_d:
1726  case Mips::BI__builtin_msa_clti_s_b:
1727  case Mips::BI__builtin_msa_clti_s_h:
1728  case Mips::BI__builtin_msa_clti_s_w:
1729  case Mips::BI__builtin_msa_clti_s_d:
1730  case Mips::BI__builtin_msa_clei_s_b:
1731  case Mips::BI__builtin_msa_clei_s_h:
1732  case Mips::BI__builtin_msa_clei_s_w:
1733  case Mips::BI__builtin_msa_clei_s_d:
1734  case Mips::BI__builtin_msa_maxi_s_b:
1735  case Mips::BI__builtin_msa_maxi_s_h:
1736  case Mips::BI__builtin_msa_maxi_s_w:
1737  case Mips::BI__builtin_msa_maxi_s_d:
1738  case Mips::BI__builtin_msa_mini_s_b:
1739  case Mips::BI__builtin_msa_mini_s_h:
1740  case Mips::BI__builtin_msa_mini_s_w:
1741  case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1742  // These intrinsics take an unsigned 8 bit immediate.
1743  case Mips::BI__builtin_msa_andi_b:
1744  case Mips::BI__builtin_msa_nori_b:
1745  case Mips::BI__builtin_msa_ori_b:
1746  case Mips::BI__builtin_msa_shf_b:
1747  case Mips::BI__builtin_msa_shf_h:
1748  case Mips::BI__builtin_msa_shf_w:
1749  case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1750  case Mips::BI__builtin_msa_bseli_b:
1751  case Mips::BI__builtin_msa_bmnzi_b:
1752  case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1753  // df/n format
1754  // These intrinsics take an unsigned 4 bit immediate.
1755  case Mips::BI__builtin_msa_copy_s_b:
1756  case Mips::BI__builtin_msa_copy_u_b:
1757  case Mips::BI__builtin_msa_insve_b:
1758  case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1759  case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1760  // These intrinsics take an unsigned 3 bit immediate.
1761  case Mips::BI__builtin_msa_copy_s_h:
1762  case Mips::BI__builtin_msa_copy_u_h:
1763  case Mips::BI__builtin_msa_insve_h:
1764  case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1765  case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1766  // These intrinsics take an unsigned 2 bit immediate.
1767  case Mips::BI__builtin_msa_copy_s_w:
1768  case Mips::BI__builtin_msa_copy_u_w:
1769  case Mips::BI__builtin_msa_insve_w:
1770  case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1771  case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1772  // These intrinsics take an unsigned 1 bit immediate.
1773  case Mips::BI__builtin_msa_copy_s_d:
1774  case Mips::BI__builtin_msa_copy_u_d:
1775  case Mips::BI__builtin_msa_insve_d:
1776  case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1777  case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1778  // Memory offsets and immediate loads.
1779  // These intrinsics take a signed 10 bit immediate.
1780  case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1781  case Mips::BI__builtin_msa_ldi_h:
1782  case Mips::BI__builtin_msa_ldi_w:
1783  case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1784  case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1785  case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1786  case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1787  case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1788  case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1789  case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1790  case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1791  case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1792  }
1793 
1794  if (!m)
1795  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1796 
1797  return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1798  SemaBuiltinConstantArgMultiple(TheCall, i, m);
1799 }
1800 
1801 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1802  unsigned i = 0, l = 0, u = 0;
1803  bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1804  BuiltinID == PPC::BI__builtin_divdeu ||
1805  BuiltinID == PPC::BI__builtin_bpermd;
1806  bool IsTarget64Bit = Context.getTargetInfo()
1807  .getTypeWidth(Context
1808  .getTargetInfo()
1809  .getIntPtrType()) == 64;
1810  bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1811  BuiltinID == PPC::BI__builtin_divweu ||
1812  BuiltinID == PPC::BI__builtin_divde ||
1813  BuiltinID == PPC::BI__builtin_divdeu;
1814 
1815  if (Is64BitBltin && !IsTarget64Bit)
1816  return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1817  << TheCall->getSourceRange();
1818 
1819  if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1820  (BuiltinID == PPC::BI__builtin_bpermd &&
1821  !Context.getTargetInfo().hasFeature("bpermd")))
1822  return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1823  << TheCall->getSourceRange();
1824 
1825  switch (BuiltinID) {
1826  default: return false;
1827  case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1828  case PPC::BI__builtin_altivec_crypto_vshasigmad:
1829  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1830  SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1831  case PPC::BI__builtin_tbegin:
1832  case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1833  case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1834  case PPC::BI__builtin_tabortwc:
1835  case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1836  case PPC::BI__builtin_tabortwci:
1837  case PPC::BI__builtin_tabortdci:
1838  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1839  SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1840  case PPC::BI__builtin_vsx_xxpermdi:
1841  case PPC::BI__builtin_vsx_xxsldwi:
1842  return SemaBuiltinVSX(TheCall);
1843  }
1844  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1845 }
1846 
1847 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1848  CallExpr *TheCall) {
1849  if (BuiltinID == SystemZ::BI__builtin_tabort) {
1850  Expr *Arg = TheCall->getArg(0);
1851  llvm::APSInt AbortCode(32);
1852  if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1853  AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1854  return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1855  << Arg->getSourceRange();
1856  }
1857 
1858  // For intrinsics which take an immediate value as part of the instruction,
1859  // range check them here.
1860  unsigned i = 0, l = 0, u = 0;
1861  switch (BuiltinID) {
1862  default: return false;
1863  case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1864  case SystemZ::BI__builtin_s390_verimb:
1865  case SystemZ::BI__builtin_s390_verimh:
1866  case SystemZ::BI__builtin_s390_verimf:
1867  case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1868  case SystemZ::BI__builtin_s390_vfaeb:
1869  case SystemZ::BI__builtin_s390_vfaeh:
1870  case SystemZ::BI__builtin_s390_vfaef:
1871  case SystemZ::BI__builtin_s390_vfaebs:
1872  case SystemZ::BI__builtin_s390_vfaehs:
1873  case SystemZ::BI__builtin_s390_vfaefs:
1874  case SystemZ::BI__builtin_s390_vfaezb:
1875  case SystemZ::BI__builtin_s390_vfaezh:
1876  case SystemZ::BI__builtin_s390_vfaezf:
1877  case SystemZ::BI__builtin_s390_vfaezbs:
1878  case SystemZ::BI__builtin_s390_vfaezhs:
1879  case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1880  case SystemZ::BI__builtin_s390_vfisb:
1881  case SystemZ::BI__builtin_s390_vfidb:
1882  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1883  SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1884  case SystemZ::BI__builtin_s390_vftcisb:
1885  case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1886  case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1887  case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1888  case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1889  case SystemZ::BI__builtin_s390_vstrcb:
1890  case SystemZ::BI__builtin_s390_vstrch:
1891  case SystemZ::BI__builtin_s390_vstrcf:
1892  case SystemZ::BI__builtin_s390_vstrczb:
1893  case SystemZ::BI__builtin_s390_vstrczh:
1894  case SystemZ::BI__builtin_s390_vstrczf:
1895  case SystemZ::BI__builtin_s390_vstrcbs:
1896  case SystemZ::BI__builtin_s390_vstrchs:
1897  case SystemZ::BI__builtin_s390_vstrcfs:
1898  case SystemZ::BI__builtin_s390_vstrczbs:
1899  case SystemZ::BI__builtin_s390_vstrczhs:
1900  case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1901  case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1902  case SystemZ::BI__builtin_s390_vfminsb:
1903  case SystemZ::BI__builtin_s390_vfmaxsb:
1904  case SystemZ::BI__builtin_s390_vfmindb:
1905  case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1906  }
1907  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1908 }
1909 
1910 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1911 /// This checks that the target supports __builtin_cpu_supports and
1912 /// that the string argument is constant and valid.
1913 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1914  Expr *Arg = TheCall->getArg(0);
1915 
1916  // Check if the argument is a string literal.
1917  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1918  return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1919  << Arg->getSourceRange();
1920 
1921  // Check the contents of the string.
1922  StringRef Feature =
1923  cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1924  if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1925  return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1926  << Arg->getSourceRange();
1927  return false;
1928 }
1929 
1930 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1931 /// This checks that the target supports __builtin_cpu_is and
1932 /// that the string argument is constant and valid.
1933 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1934  Expr *Arg = TheCall->getArg(0);
1935 
1936  // Check if the argument is a string literal.
1937  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1938  return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1939  << Arg->getSourceRange();
1940 
1941  // Check the contents of the string.
1942  StringRef Feature =
1943  cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1944  if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1945  return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1946  << Arg->getSourceRange();
1947  return false;
1948 }
1949 
1950 // Check if the rounding mode is legal.
1951 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1952  // Indicates if this instruction has rounding control or just SAE.
1953  bool HasRC = false;
1954 
1955  unsigned ArgNum = 0;
1956  switch (BuiltinID) {
1957  default:
1958  return false;
1959  case X86::BI__builtin_ia32_vcvttsd2si32:
1960  case X86::BI__builtin_ia32_vcvttsd2si64:
1961  case X86::BI__builtin_ia32_vcvttsd2usi32:
1962  case X86::BI__builtin_ia32_vcvttsd2usi64:
1963  case X86::BI__builtin_ia32_vcvttss2si32:
1964  case X86::BI__builtin_ia32_vcvttss2si64:
1965  case X86::BI__builtin_ia32_vcvttss2usi32:
1966  case X86::BI__builtin_ia32_vcvttss2usi64:
1967  ArgNum = 1;
1968  break;
1969  case X86::BI__builtin_ia32_cvtps2pd512_mask:
1970  case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1971  case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1972  case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1973  case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1974  case X86::BI__builtin_ia32_cvttps2dq512_mask:
1975  case X86::BI__builtin_ia32_cvttps2qq512_mask:
1976  case X86::BI__builtin_ia32_cvttps2udq512_mask:
1977  case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1978  case X86::BI__builtin_ia32_exp2pd_mask:
1979  case X86::BI__builtin_ia32_exp2ps_mask:
1980  case X86::BI__builtin_ia32_getexppd512_mask:
1981  case X86::BI__builtin_ia32_getexpps512_mask:
1982  case X86::BI__builtin_ia32_rcp28pd_mask:
1983  case X86::BI__builtin_ia32_rcp28ps_mask:
1984  case X86::BI__builtin_ia32_rsqrt28pd_mask:
1985  case X86::BI__builtin_ia32_rsqrt28ps_mask:
1986  case X86::BI__builtin_ia32_vcomisd:
1987  case X86::BI__builtin_ia32_vcomiss:
1988  case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1989  ArgNum = 3;
1990  break;
1991  case X86::BI__builtin_ia32_cmppd512_mask:
1992  case X86::BI__builtin_ia32_cmpps512_mask:
1993  case X86::BI__builtin_ia32_cmpsd_mask:
1994  case X86::BI__builtin_ia32_cmpss_mask:
1995  case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1996  case X86::BI__builtin_ia32_getexpsd128_round_mask:
1997  case X86::BI__builtin_ia32_getexpss128_round_mask:
1998  case X86::BI__builtin_ia32_maxpd512_mask:
1999  case X86::BI__builtin_ia32_maxps512_mask:
2000  case X86::BI__builtin_ia32_maxsd_round_mask:
2001  case X86::BI__builtin_ia32_maxss_round_mask:
2002  case X86::BI__builtin_ia32_minpd512_mask:
2003  case X86::BI__builtin_ia32_minps512_mask:
2004  case X86::BI__builtin_ia32_minsd_round_mask:
2005  case X86::BI__builtin_ia32_minss_round_mask:
2006  case X86::BI__builtin_ia32_rcp28sd_round_mask:
2007  case X86::BI__builtin_ia32_rcp28ss_round_mask:
2008  case X86::BI__builtin_ia32_reducepd512_mask:
2009  case X86::BI__builtin_ia32_reduceps512_mask:
2010  case X86::BI__builtin_ia32_rndscalepd_mask:
2011  case X86::BI__builtin_ia32_rndscaleps_mask:
2012  case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2013  case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2014  ArgNum = 4;
2015  break;
2016  case X86::BI__builtin_ia32_fixupimmpd512_mask:
2017  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2018  case X86::BI__builtin_ia32_fixupimmps512_mask:
2019  case X86::BI__builtin_ia32_fixupimmps512_maskz:
2020  case X86::BI__builtin_ia32_fixupimmsd_mask:
2021  case X86::BI__builtin_ia32_fixupimmsd_maskz:
2022  case X86::BI__builtin_ia32_fixupimmss_mask:
2023  case X86::BI__builtin_ia32_fixupimmss_maskz:
2024  case X86::BI__builtin_ia32_rangepd512_mask:
2025  case X86::BI__builtin_ia32_rangeps512_mask:
2026  case X86::BI__builtin_ia32_rangesd128_round_mask:
2027  case X86::BI__builtin_ia32_rangess128_round_mask:
2028  case X86::BI__builtin_ia32_reducesd_mask:
2029  case X86::BI__builtin_ia32_reducess_mask:
2030  case X86::BI__builtin_ia32_rndscalesd_round_mask:
2031  case X86::BI__builtin_ia32_rndscaless_round_mask:
2032  ArgNum = 5;
2033  break;
2034  case X86::BI__builtin_ia32_vcvtsd2si64:
2035  case X86::BI__builtin_ia32_vcvtsd2si32:
2036  case X86::BI__builtin_ia32_vcvtsd2usi32:
2037  case X86::BI__builtin_ia32_vcvtsd2usi64:
2038  case X86::BI__builtin_ia32_vcvtss2si32:
2039  case X86::BI__builtin_ia32_vcvtss2si64:
2040  case X86::BI__builtin_ia32_vcvtss2usi32:
2041  case X86::BI__builtin_ia32_vcvtss2usi64:
2042  ArgNum = 1;
2043  HasRC = true;
2044  break;
2045  case X86::BI__builtin_ia32_cvtsi2sd64:
2046  case X86::BI__builtin_ia32_cvtsi2ss32:
2047  case X86::BI__builtin_ia32_cvtsi2ss64:
2048  case X86::BI__builtin_ia32_cvtusi2sd64:
2049  case X86::BI__builtin_ia32_cvtusi2ss32:
2050  case X86::BI__builtin_ia32_cvtusi2ss64:
2051  ArgNum = 2;
2052  HasRC = true;
2053  break;
2054  case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2055  case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2056  case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2057  case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2058  case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2059  case X86::BI__builtin_ia32_cvtps2qq512_mask:
2060  case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2061  case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2062  case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2063  case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2064  case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2065  case X86::BI__builtin_ia32_sqrtpd512_mask:
2066  case X86::BI__builtin_ia32_sqrtps512_mask:
2067  ArgNum = 3;
2068  HasRC = true;
2069  break;
2070  case X86::BI__builtin_ia32_addpd512_mask:
2071  case X86::BI__builtin_ia32_addps512_mask:
2072  case X86::BI__builtin_ia32_divpd512_mask:
2073  case X86::BI__builtin_ia32_divps512_mask:
2074  case X86::BI__builtin_ia32_mulpd512_mask:
2075  case X86::BI__builtin_ia32_mulps512_mask:
2076  case X86::BI__builtin_ia32_subpd512_mask:
2077  case X86::BI__builtin_ia32_subps512_mask:
2078  case X86::BI__builtin_ia32_addss_round_mask:
2079  case X86::BI__builtin_ia32_addsd_round_mask:
2080  case X86::BI__builtin_ia32_divss_round_mask:
2081  case X86::BI__builtin_ia32_divsd_round_mask:
2082  case X86::BI__builtin_ia32_mulss_round_mask:
2083  case X86::BI__builtin_ia32_mulsd_round_mask:
2084  case X86::BI__builtin_ia32_subss_round_mask:
2085  case X86::BI__builtin_ia32_subsd_round_mask:
2086  case X86::BI__builtin_ia32_scalefpd512_mask:
2087  case X86::BI__builtin_ia32_scalefps512_mask:
2088  case X86::BI__builtin_ia32_scalefsd_round_mask:
2089  case X86::BI__builtin_ia32_scalefss_round_mask:
2090  case X86::BI__builtin_ia32_getmantpd512_mask:
2091  case X86::BI__builtin_ia32_getmantps512_mask:
2092  case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2093  case X86::BI__builtin_ia32_sqrtsd_round_mask:
2094  case X86::BI__builtin_ia32_sqrtss_round_mask:
2095  case X86::BI__builtin_ia32_vfmaddpd512_mask:
2096  case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2097  case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2098  case X86::BI__builtin_ia32_vfmaddps512_mask:
2099  case X86::BI__builtin_ia32_vfmaddps512_mask3:
2100  case X86::BI__builtin_ia32_vfmaddps512_maskz:
2101  case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2102  case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2103  case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2104  case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2105  case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2106  case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2107  case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2108  case X86::BI__builtin_ia32_vfmsubps512_mask3:
2109  case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2110  case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2111  case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2112  case X86::BI__builtin_ia32_vfnmaddps512_mask:
2113  case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2114  case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2115  case X86::BI__builtin_ia32_vfnmsubps512_mask:
2116  case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2117  case X86::BI__builtin_ia32_vfmaddsd3_mask:
2118  case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2119  case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2120  case X86::BI__builtin_ia32_vfmaddss3_mask:
2121  case X86::BI__builtin_ia32_vfmaddss3_maskz:
2122  case X86::BI__builtin_ia32_vfmaddss3_mask3:
2123  ArgNum = 4;
2124  HasRC = true;
2125  break;
2126  case X86::BI__builtin_ia32_getmantsd_round_mask:
2127  case X86::BI__builtin_ia32_getmantss_round_mask:
2128  ArgNum = 5;
2129  HasRC = true;
2130  break;
2131  }
2132 
2133  llvm::APSInt Result;
2134 
2135  // We can't check the value of a dependent argument.
2136  Expr *Arg = TheCall->getArg(ArgNum);
2137  if (Arg->isTypeDependent() || Arg->isValueDependent())
2138  return false;
2139 
2140  // Check constant-ness first.
2141  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2142  return true;
2143 
2144  // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2145  // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2146  // combined with ROUND_NO_EXC.
2147  if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2148  Result == 8/*ROUND_NO_EXC*/ ||
2149  (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2150  return false;
2151 
2152  return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2153  << Arg->getSourceRange();
2154 }
2155 
2156 // Check if the gather/scatter scale is legal.
2157 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2158  CallExpr *TheCall) {
2159  unsigned ArgNum = 0;
2160  switch (BuiltinID) {
2161  default:
2162  return false;
2163  case X86::BI__builtin_ia32_gatherpfdpd:
2164  case X86::BI__builtin_ia32_gatherpfdps:
2165  case X86::BI__builtin_ia32_gatherpfqpd:
2166  case X86::BI__builtin_ia32_gatherpfqps:
2167  case X86::BI__builtin_ia32_scatterpfdpd:
2168  case X86::BI__builtin_ia32_scatterpfdps:
2169  case X86::BI__builtin_ia32_scatterpfqpd:
2170  case X86::BI__builtin_ia32_scatterpfqps:
2171  ArgNum = 3;
2172  break;
2173  case X86::BI__builtin_ia32_gatherd_pd:
2174  case X86::BI__builtin_ia32_gatherd_pd256:
2175  case X86::BI__builtin_ia32_gatherq_pd:
2176  case X86::BI__builtin_ia32_gatherq_pd256:
2177  case X86::BI__builtin_ia32_gatherd_ps:
2178  case X86::BI__builtin_ia32_gatherd_ps256:
2179  case X86::BI__builtin_ia32_gatherq_ps:
2180  case X86::BI__builtin_ia32_gatherq_ps256:
2181  case X86::BI__builtin_ia32_gatherd_q:
2182  case X86::BI__builtin_ia32_gatherd_q256:
2183  case X86::BI__builtin_ia32_gatherq_q:
2184  case X86::BI__builtin_ia32_gatherq_q256:
2185  case X86::BI__builtin_ia32_gatherd_d:
2186  case X86::BI__builtin_ia32_gatherd_d256:
2187  case X86::BI__builtin_ia32_gatherq_d:
2188  case X86::BI__builtin_ia32_gatherq_d256:
2189  case X86::BI__builtin_ia32_gather3div2df:
2190  case X86::BI__builtin_ia32_gather3div2di:
2191  case X86::BI__builtin_ia32_gather3div4df:
2192  case X86::BI__builtin_ia32_gather3div4di:
2193  case X86::BI__builtin_ia32_gather3div4sf:
2194  case X86::BI__builtin_ia32_gather3div4si:
2195  case X86::BI__builtin_ia32_gather3div8sf:
2196  case X86::BI__builtin_ia32_gather3div8si:
2197  case X86::BI__builtin_ia32_gather3siv2df:
2198  case X86::BI__builtin_ia32_gather3siv2di:
2199  case X86::BI__builtin_ia32_gather3siv4df:
2200  case X86::BI__builtin_ia32_gather3siv4di:
2201  case X86::BI__builtin_ia32_gather3siv4sf:
2202  case X86::BI__builtin_ia32_gather3siv4si:
2203  case X86::BI__builtin_ia32_gather3siv8sf:
2204  case X86::BI__builtin_ia32_gather3siv8si:
2205  case X86::BI__builtin_ia32_gathersiv8df:
2206  case X86::BI__builtin_ia32_gathersiv16sf:
2207  case X86::BI__builtin_ia32_gatherdiv8df:
2208  case X86::BI__builtin_ia32_gatherdiv16sf:
2209  case X86::BI__builtin_ia32_gathersiv8di:
2210  case X86::BI__builtin_ia32_gathersiv16si:
2211  case X86::BI__builtin_ia32_gatherdiv8di:
2212  case X86::BI__builtin_ia32_gatherdiv16si:
2213  case X86::BI__builtin_ia32_scatterdiv2df:
2214  case X86::BI__builtin_ia32_scatterdiv2di:
2215  case X86::BI__builtin_ia32_scatterdiv4df:
2216  case X86::BI__builtin_ia32_scatterdiv4di:
2217  case X86::BI__builtin_ia32_scatterdiv4sf:
2218  case X86::BI__builtin_ia32_scatterdiv4si:
2219  case X86::BI__builtin_ia32_scatterdiv8sf:
2220  case X86::BI__builtin_ia32_scatterdiv8si:
2221  case X86::BI__builtin_ia32_scattersiv2df:
2222  case X86::BI__builtin_ia32_scattersiv2di:
2223  case X86::BI__builtin_ia32_scattersiv4df:
2224  case X86::BI__builtin_ia32_scattersiv4di:
2225  case X86::BI__builtin_ia32_scattersiv4sf:
2226  case X86::BI__builtin_ia32_scattersiv4si:
2227  case X86::BI__builtin_ia32_scattersiv8sf:
2228  case X86::BI__builtin_ia32_scattersiv8si:
2229  case X86::BI__builtin_ia32_scattersiv8df:
2230  case X86::BI__builtin_ia32_scattersiv16sf:
2231  case X86::BI__builtin_ia32_scatterdiv8df:
2232  case X86::BI__builtin_ia32_scatterdiv16sf:
2233  case X86::BI__builtin_ia32_scattersiv8di:
2234  case X86::BI__builtin_ia32_scattersiv16si:
2235  case X86::BI__builtin_ia32_scatterdiv8di:
2236  case X86::BI__builtin_ia32_scatterdiv16si:
2237  ArgNum = 4;
2238  break;
2239  }
2240 
2241  llvm::APSInt Result;
2242 
2243  // We can't check the value of a dependent argument.
2244  Expr *Arg = TheCall->getArg(ArgNum);
2245  if (Arg->isTypeDependent() || Arg->isValueDependent())
2246  return false;
2247 
2248  // Check constant-ness first.
2249  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2250  return true;
2251 
2252  if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2253  return false;
2254 
2255  return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2256  << Arg->getSourceRange();
2257 }
2258 
2259 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2260  if (BuiltinID == X86::BI__builtin_cpu_supports)
2261  return SemaBuiltinCpuSupports(*this, TheCall);
2262 
2263  if (BuiltinID == X86::BI__builtin_cpu_is)
2264  return SemaBuiltinCpuIs(*this, TheCall);
2265 
2266  // If the intrinsic has rounding or SAE make sure its valid.
2267  if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2268  return true;
2269 
2270  // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2271  if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2272  return true;
2273 
2274  // For intrinsics which take an immediate value as part of the instruction,
2275  // range check them here.
2276  int i = 0, l = 0, u = 0;
2277  switch (BuiltinID) {
2278  default:
2279  return false;
2280  case X86::BI_mm_prefetch:
2281  i = 1; l = 0; u = 3;
2282  break;
2283  case X86::BI__builtin_ia32_sha1rnds4:
2284  case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2285  case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2286  case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2287  case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2288  i = 2; l = 0; u = 3;
2289  break;
2290  case X86::BI__builtin_ia32_vpermil2pd:
2291  case X86::BI__builtin_ia32_vpermil2pd256:
2292  case X86::BI__builtin_ia32_vpermil2ps:
2293  case X86::BI__builtin_ia32_vpermil2ps256:
2294  i = 3; l = 0; u = 3;
2295  break;
2296  case X86::BI__builtin_ia32_cmpb128_mask:
2297  case X86::BI__builtin_ia32_cmpw128_mask:
2298  case X86::BI__builtin_ia32_cmpd128_mask:
2299  case X86::BI__builtin_ia32_cmpq128_mask:
2300  case X86::BI__builtin_ia32_cmpb256_mask:
2301  case X86::BI__builtin_ia32_cmpw256_mask:
2302  case X86::BI__builtin_ia32_cmpd256_mask:
2303  case X86::BI__builtin_ia32_cmpq256_mask:
2304  case X86::BI__builtin_ia32_cmpb512_mask:
2305  case X86::BI__builtin_ia32_cmpw512_mask:
2306  case X86::BI__builtin_ia32_cmpd512_mask:
2307  case X86::BI__builtin_ia32_cmpq512_mask:
2308  case X86::BI__builtin_ia32_ucmpb128_mask:
2309  case X86::BI__builtin_ia32_ucmpw128_mask:
2310  case X86::BI__builtin_ia32_ucmpd128_mask:
2311  case X86::BI__builtin_ia32_ucmpq128_mask:
2312  case X86::BI__builtin_ia32_ucmpb256_mask:
2313  case X86::BI__builtin_ia32_ucmpw256_mask:
2314  case X86::BI__builtin_ia32_ucmpd256_mask:
2315  case X86::BI__builtin_ia32_ucmpq256_mask:
2316  case X86::BI__builtin_ia32_ucmpb512_mask:
2317  case X86::BI__builtin_ia32_ucmpw512_mask:
2318  case X86::BI__builtin_ia32_ucmpd512_mask:
2319  case X86::BI__builtin_ia32_ucmpq512_mask:
2320  case X86::BI__builtin_ia32_vpcomub:
2321  case X86::BI__builtin_ia32_vpcomuw:
2322  case X86::BI__builtin_ia32_vpcomud:
2323  case X86::BI__builtin_ia32_vpcomuq:
2324  case X86::BI__builtin_ia32_vpcomb:
2325  case X86::BI__builtin_ia32_vpcomw:
2326  case X86::BI__builtin_ia32_vpcomd:
2327  case X86::BI__builtin_ia32_vpcomq:
2328  i = 2; l = 0; u = 7;
2329  break;
2330  case X86::BI__builtin_ia32_roundps:
2331  case X86::BI__builtin_ia32_roundpd:
2332  case X86::BI__builtin_ia32_roundps256:
2333  case X86::BI__builtin_ia32_roundpd256:
2334  i = 1; l = 0; u = 15;
2335  break;
2336  case X86::BI__builtin_ia32_roundss:
2337  case X86::BI__builtin_ia32_roundsd:
2338  case X86::BI__builtin_ia32_rangepd128_mask:
2339  case X86::BI__builtin_ia32_rangepd256_mask:
2340  case X86::BI__builtin_ia32_rangepd512_mask:
2341  case X86::BI__builtin_ia32_rangeps128_mask:
2342  case X86::BI__builtin_ia32_rangeps256_mask:
2343  case X86::BI__builtin_ia32_rangeps512_mask:
2344  case X86::BI__builtin_ia32_getmantsd_round_mask:
2345  case X86::BI__builtin_ia32_getmantss_round_mask:
2346  i = 2; l = 0; u = 15;
2347  break;
2348  case X86::BI__builtin_ia32_cmpps:
2349  case X86::BI__builtin_ia32_cmpss:
2350  case X86::BI__builtin_ia32_cmppd:
2351  case X86::BI__builtin_ia32_cmpsd:
2352  case X86::BI__builtin_ia32_cmpps256:
2353  case X86::BI__builtin_ia32_cmppd256:
2354  case X86::BI__builtin_ia32_cmpps128_mask:
2355  case X86::BI__builtin_ia32_cmppd128_mask:
2356  case X86::BI__builtin_ia32_cmpps256_mask:
2357  case X86::BI__builtin_ia32_cmppd256_mask:
2358  case X86::BI__builtin_ia32_cmpps512_mask:
2359  case X86::BI__builtin_ia32_cmppd512_mask:
2360  case X86::BI__builtin_ia32_cmpsd_mask:
2361  case X86::BI__builtin_ia32_cmpss_mask:
2362  i = 2; l = 0; u = 31;
2363  break;
2364  case X86::BI__builtin_ia32_xabort:
2365  i = 0; l = -128; u = 255;
2366  break;
2367  case X86::BI__builtin_ia32_pshufw:
2368  case X86::BI__builtin_ia32_aeskeygenassist128:
2369  i = 1; l = -128; u = 255;
2370  break;
2371  case X86::BI__builtin_ia32_vcvtps2ph:
2372  case X86::BI__builtin_ia32_vcvtps2ph_mask:
2373  case X86::BI__builtin_ia32_vcvtps2ph256:
2374  case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2375  case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2376  case X86::BI__builtin_ia32_rndscaleps_128_mask:
2377  case X86::BI__builtin_ia32_rndscalepd_128_mask:
2378  case X86::BI__builtin_ia32_rndscaleps_256_mask:
2379  case X86::BI__builtin_ia32_rndscalepd_256_mask:
2380  case X86::BI__builtin_ia32_rndscaleps_mask:
2381  case X86::BI__builtin_ia32_rndscalepd_mask:
2382  case X86::BI__builtin_ia32_reducepd128_mask:
2383  case X86::BI__builtin_ia32_reducepd256_mask:
2384  case X86::BI__builtin_ia32_reducepd512_mask:
2385  case X86::BI__builtin_ia32_reduceps128_mask:
2386  case X86::BI__builtin_ia32_reduceps256_mask:
2387  case X86::BI__builtin_ia32_reduceps512_mask:
2388  case X86::BI__builtin_ia32_prold512_mask:
2389  case X86::BI__builtin_ia32_prolq512_mask:
2390  case X86::BI__builtin_ia32_prold128_mask:
2391  case X86::BI__builtin_ia32_prold256_mask:
2392  case X86::BI__builtin_ia32_prolq128_mask:
2393  case X86::BI__builtin_ia32_prolq256_mask:
2394  case X86::BI__builtin_ia32_prord128_mask:
2395  case X86::BI__builtin_ia32_prord256_mask:
2396  case X86::BI__builtin_ia32_prorq128_mask:
2397  case X86::BI__builtin_ia32_prorq256_mask:
2398  case X86::BI__builtin_ia32_fpclasspd128_mask:
2399  case X86::BI__builtin_ia32_fpclasspd256_mask:
2400  case X86::BI__builtin_ia32_fpclassps128_mask:
2401  case X86::BI__builtin_ia32_fpclassps256_mask:
2402  case X86::BI__builtin_ia32_fpclassps512_mask:
2403  case X86::BI__builtin_ia32_fpclasspd512_mask:
2404  case X86::BI__builtin_ia32_fpclasssd_mask:
2405  case X86::BI__builtin_ia32_fpclassss_mask:
2406  i = 1; l = 0; u = 255;
2407  break;
2408  case X86::BI__builtin_ia32_palignr:
2409  case X86::BI__builtin_ia32_insertps128:
2410  case X86::BI__builtin_ia32_dpps:
2411  case X86::BI__builtin_ia32_dppd:
2412  case X86::BI__builtin_ia32_dpps256:
2413  case X86::BI__builtin_ia32_mpsadbw128:
2414  case X86::BI__builtin_ia32_mpsadbw256:
2415  case X86::BI__builtin_ia32_pcmpistrm128:
2416  case X86::BI__builtin_ia32_pcmpistri128:
2417  case X86::BI__builtin_ia32_pcmpistria128:
2418  case X86::BI__builtin_ia32_pcmpistric128:
2419  case X86::BI__builtin_ia32_pcmpistrio128:
2420  case X86::BI__builtin_ia32_pcmpistris128:
2421  case X86::BI__builtin_ia32_pcmpistriz128:
2422  case X86::BI__builtin_ia32_pclmulqdq128:
2423  case X86::BI__builtin_ia32_vperm2f128_pd256:
2424  case X86::BI__builtin_ia32_vperm2f128_ps256:
2425  case X86::BI__builtin_ia32_vperm2f128_si256:
2426  case X86::BI__builtin_ia32_permti256:
2427  i = 2; l = -128; u = 255;
2428  break;
2429  case X86::BI__builtin_ia32_palignr128:
2430  case X86::BI__builtin_ia32_palignr256:
2431  case X86::BI__builtin_ia32_palignr512_mask:
2432  case X86::BI__builtin_ia32_vcomisd:
2433  case X86::BI__builtin_ia32_vcomiss:
2434  case X86::BI__builtin_ia32_shuf_f32x4_mask:
2435  case X86::BI__builtin_ia32_shuf_f64x2_mask:
2436  case X86::BI__builtin_ia32_shuf_i32x4_mask:
2437  case X86::BI__builtin_ia32_shuf_i64x2_mask:
2438  case X86::BI__builtin_ia32_dbpsadbw128_mask:
2439  case X86::BI__builtin_ia32_dbpsadbw256_mask:
2440  case X86::BI__builtin_ia32_dbpsadbw512_mask:
2441  i = 2; l = 0; u = 255;
2442  break;
2443  case X86::BI__builtin_ia32_fixupimmpd512_mask:
2444  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2445  case X86::BI__builtin_ia32_fixupimmps512_mask:
2446  case X86::BI__builtin_ia32_fixupimmps512_maskz:
2447  case X86::BI__builtin_ia32_fixupimmsd_mask:
2448  case X86::BI__builtin_ia32_fixupimmsd_maskz:
2449  case X86::BI__builtin_ia32_fixupimmss_mask:
2450  case X86::BI__builtin_ia32_fixupimmss_maskz:
2451  case X86::BI__builtin_ia32_fixupimmpd128_mask:
2452  case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2453  case X86::BI__builtin_ia32_fixupimmpd256_mask:
2454  case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2455  case X86::BI__builtin_ia32_fixupimmps128_mask:
2456  case X86::BI__builtin_ia32_fixupimmps128_maskz:
2457  case X86::BI__builtin_ia32_fixupimmps256_mask:
2458  case X86::BI__builtin_ia32_fixupimmps256_maskz:
2459  case X86::BI__builtin_ia32_pternlogd512_mask:
2460  case X86::BI__builtin_ia32_pternlogd512_maskz:
2461  case X86::BI__builtin_ia32_pternlogq512_mask:
2462  case X86::BI__builtin_ia32_pternlogq512_maskz:
2463  case X86::BI__builtin_ia32_pternlogd128_mask:
2464  case X86::BI__builtin_ia32_pternlogd128_maskz:
2465  case X86::BI__builtin_ia32_pternlogd256_mask:
2466  case X86::BI__builtin_ia32_pternlogd256_maskz:
2467  case X86::BI__builtin_ia32_pternlogq128_mask:
2468  case X86::BI__builtin_ia32_pternlogq128_maskz:
2469  case X86::BI__builtin_ia32_pternlogq256_mask:
2470  case X86::BI__builtin_ia32_pternlogq256_maskz:
2471  i = 3; l = 0; u = 255;
2472  break;
2473  case X86::BI__builtin_ia32_gatherpfdpd:
2474  case X86::BI__builtin_ia32_gatherpfdps:
2475  case X86::BI__builtin_ia32_gatherpfqpd:
2476  case X86::BI__builtin_ia32_gatherpfqps:
2477  case X86::BI__builtin_ia32_scatterpfdpd:
2478  case X86::BI__builtin_ia32_scatterpfdps:
2479  case X86::BI__builtin_ia32_scatterpfqpd:
2480  case X86::BI__builtin_ia32_scatterpfqps:
2481  i = 4; l = 2; u = 3;
2482  break;
2483  case X86::BI__builtin_ia32_pcmpestrm128:
2484  case X86::BI__builtin_ia32_pcmpestri128:
2485  case X86::BI__builtin_ia32_pcmpestria128:
2486  case X86::BI__builtin_ia32_pcmpestric128:
2487  case X86::BI__builtin_ia32_pcmpestrio128:
2488  case X86::BI__builtin_ia32_pcmpestris128:
2489  case X86::BI__builtin_ia32_pcmpestriz128:
2490  i = 4; l = -128; u = 255;
2491  break;
2492  case X86::BI__builtin_ia32_rndscalesd_round_mask:
2493  case X86::BI__builtin_ia32_rndscaless_round_mask:
2494  i = 4; l = 0; u = 255;
2495  break;
2496  }
2497  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2498 }
2499 
2500 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2501 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2502 /// Returns true when the format fits the function and the FormatStringInfo has
2503 /// been populated.
2504 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2505  FormatStringInfo *FSI) {
2506  FSI->HasVAListArg = Format->getFirstArg() == 0;
2507  FSI->FormatIdx = Format->getFormatIdx() - 1;
2508  FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2509 
2510  // The way the format attribute works in GCC, the implicit this argument
2511  // of member functions is counted. However, it doesn't appear in our own
2512  // lists, so decrement format_idx in that case.
2513  if (IsCXXMember) {
2514  if(FSI->FormatIdx == 0)
2515  return false;
2516  --FSI->FormatIdx;
2517  if (FSI->FirstDataArg != 0)
2518  --FSI->FirstDataArg;
2519  }
2520  return true;
2521 }
2522 
2523 /// Checks if a the given expression evaluates to null.
2524 ///
2525 /// \brief Returns true if the value evaluates to null.
2526 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2527  // If the expression has non-null type, it doesn't evaluate to null.
2528  if (auto nullability
2529  = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2530  if (*nullability == NullabilityKind::NonNull)
2531  return false;
2532  }
2533 
2534  // As a special case, transparent unions initialized with zero are
2535  // considered null for the purposes of the nonnull attribute.
2536  if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2537  if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2538  if (const CompoundLiteralExpr *CLE =
2539  dyn_cast<CompoundLiteralExpr>(Expr))
2540  if (const InitListExpr *ILE =
2541  dyn_cast<InitListExpr>(CLE->getInitializer()))
2542  Expr = ILE->getInit(0);
2543  }
2544 
2545  bool Result;
2546  return (!Expr->isValueDependent() &&
2547  Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2548  !Result);
2549 }
2550 
2552  const Expr *ArgExpr,
2553  SourceLocation CallSiteLoc) {
2554  if (CheckNonNullExpr(S, ArgExpr))
2555  S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2556  S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2557 }
2558 
2559 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2560  FormatStringInfo FSI;
2561  if ((GetFormatStringType(Format) == FST_NSString) &&
2562  getFormatStringInfo(Format, false, &FSI)) {
2563  Idx = FSI.FormatIdx;
2564  return true;
2565  }
2566  return false;
2567 }
2568 
2569 /// \brief Diagnose use of %s directive in an NSString which is being passed
2570 /// as formatting string to formatting method.
2571 static void
2573  const NamedDecl *FDecl,
2574  Expr **Args,
2575  unsigned NumArgs) {
2576  unsigned Idx = 0;
2577  bool Format = false;
2579  if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2580  Idx = 2;
2581  Format = true;
2582  }
2583  else
2584  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2585  if (S.GetFormatNSStringIdx(I, Idx)) {
2586  Format = true;
2587  break;
2588  }
2589  }
2590  if (!Format || NumArgs <= Idx)
2591  return;
2592  const Expr *FormatExpr = Args[Idx];
2593  if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2594  FormatExpr = CSCE->getSubExpr();
2595  const StringLiteral *FormatString;
2596  if (const ObjCStringLiteral *OSL =
2597  dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2598  FormatString = OSL->getString();
2599  else
2600  FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2601  if (!FormatString)
2602  return;
2603  if (S.FormatStringHasSArg(FormatString)) {
2604  S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2605  << "%s" << 1 << 1;
2606  S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2607  << FDecl->getDeclName();
2608  }
2609 }
2610 
2611 /// Determine whether the given type has a non-null nullability annotation.
2613  if (auto nullability = type->getNullability(ctx))
2614  return *nullability == NullabilityKind::NonNull;
2615 
2616  return false;
2617 }
2618 
2620  const NamedDecl *FDecl,
2621  const FunctionProtoType *Proto,
2622  ArrayRef<const Expr *> Args,
2623  SourceLocation CallSiteLoc) {
2624  assert((FDecl || Proto) && "Need a function declaration or prototype");
2625 
2626  // Check the attributes attached to the method/function itself.
2627  llvm::SmallBitVector NonNullArgs;
2628  if (FDecl) {
2629  // Handle the nonnull attribute on the function/method declaration itself.
2630  for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2631  if (!NonNull->args_size()) {
2632  // Easy case: all pointer arguments are nonnull.
2633  for (const auto *Arg : Args)
2634  if (S.isValidPointerAttrType(Arg->getType()))
2635  CheckNonNullArgument(S, Arg, CallSiteLoc);
2636  return;
2637  }
2638 
2639  for (unsigned Val : NonNull->args()) {
2640  if (Val >= Args.size())
2641  continue;
2642  if (NonNullArgs.empty())
2643  NonNullArgs.resize(Args.size());
2644  NonNullArgs.set(Val);
2645  }
2646  }
2647  }
2648 
2649  if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2650  // Handle the nonnull attribute on the parameters of the
2651  // function/method.
2652  ArrayRef<ParmVarDecl*> parms;
2653  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2654  parms = FD->parameters();
2655  else
2656  parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2657 
2658  unsigned ParamIndex = 0;
2659  for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2660  I != E; ++I, ++ParamIndex) {
2661  const ParmVarDecl *PVD = *I;
2662  if (PVD->hasAttr<NonNullAttr>() ||
2663  isNonNullType(S.Context, PVD->getType())) {
2664  if (NonNullArgs.empty())
2665  NonNullArgs.resize(Args.size());
2666 
2667  NonNullArgs.set(ParamIndex);
2668  }
2669  }
2670  } else {
2671  // If we have a non-function, non-method declaration but no
2672  // function prototype, try to dig out the function prototype.
2673  if (!Proto) {
2674  if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2675  QualType type = VD->getType().getNonReferenceType();
2676  if (auto pointerType = type->getAs<PointerType>())
2677  type = pointerType->getPointeeType();
2678  else if (auto blockType = type->getAs<BlockPointerType>())
2679  type = blockType->getPointeeType();
2680  // FIXME: data member pointers?
2681 
2682  // Dig out the function prototype, if there is one.
2683  Proto = type->getAs<FunctionProtoType>();
2684  }
2685  }
2686 
2687  // Fill in non-null argument information from the nullability
2688  // information on the parameter types (if we have them).
2689  if (Proto) {
2690  unsigned Index = 0;
2691  for (auto paramType : Proto->getParamTypes()) {
2692  if (isNonNullType(S.Context, paramType)) {
2693  if (NonNullArgs.empty())
2694  NonNullArgs.resize(Args.size());
2695 
2696  NonNullArgs.set(Index);
2697  }
2698 
2699  ++Index;
2700  }
2701  }
2702  }
2703 
2704  // Check for non-null arguments.
2705  for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2706  ArgIndex != ArgIndexEnd; ++ArgIndex) {
2707  if (NonNullArgs[ArgIndex])
2708  CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2709  }
2710 }
2711 
2712 /// Handles the checks for format strings, non-POD arguments to vararg
2713 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2714 /// attributes.
2715 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2716  const Expr *ThisArg, ArrayRef<const Expr *> Args,
2717  bool IsMemberFunction, SourceLocation Loc,
2718  SourceRange Range, VariadicCallType CallType) {
2719  // FIXME: We should check as much as we can in the template definition.
2720  if (CurContext->isDependentContext())
2721  return;
2722 
2723  // Printf and scanf checking.
2724  llvm::SmallBitVector CheckedVarArgs;
2725  if (FDecl) {
2726  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2727  // Only create vector if there are format attributes.
2728  CheckedVarArgs.resize(Args.size());
2729 
2730  CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2731  CheckedVarArgs);
2732  }
2733  }
2734 
2735  // Refuse POD arguments that weren't caught by the format string
2736  // checks above.
2737  auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2738  if (CallType != VariadicDoesNotApply &&
2739  (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2740  unsigned NumParams = Proto ? Proto->getNumParams()
2741  : FDecl && isa<FunctionDecl>(FDecl)
2742  ? cast<FunctionDecl>(FDecl)->getNumParams()
2743  : FDecl && isa<ObjCMethodDecl>(FDecl)
2744  ? cast<ObjCMethodDecl>(FDecl)->param_size()
2745  : 0;
2746 
2747  for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2748  // Args[ArgIdx] can be null in malformed code.
2749  if (const Expr *Arg = Args[ArgIdx]) {
2750  if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2751  checkVariadicArgument(Arg, CallType);
2752  }
2753  }
2754  }
2755 
2756  if (FDecl || Proto) {
2757  CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2758 
2759  // Type safety checking.
2760  if (FDecl) {
2761  for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2762  CheckArgumentWithTypeTag(I, Args, Loc);
2763  }
2764  }
2765 
2766  if (FD)
2767  diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2768 }
2769 
2770 /// CheckConstructorCall - Check a constructor call for correctness and safety
2771 /// properties not enforced by the C type system.
2772 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2773  ArrayRef<const Expr *> Args,
2774  const FunctionProtoType *Proto,
2775  SourceLocation Loc) {
2776  VariadicCallType CallType =
2777  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2778  checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2779  Loc, SourceRange(), CallType);
2780 }
2781 
2782 /// CheckFunctionCall - Check a direct function call for various correctness
2783 /// and safety properties not strictly enforced by the C type system.
2784 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2785  const FunctionProtoType *Proto) {
2786  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2787  isa<CXXMethodDecl>(FDecl);
2788  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2789  IsMemberOperatorCall;
2790  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2791  TheCall->getCallee());
2792  Expr** Args = TheCall->getArgs();
2793  unsigned NumArgs = TheCall->getNumArgs();
2794 
2795  Expr *ImplicitThis = nullptr;
2796  if (IsMemberOperatorCall) {
2797  // If this is a call to a member operator, hide the first argument
2798  // from checkCall.
2799  // FIXME: Our choice of AST representation here is less than ideal.
2800  ImplicitThis = Args[0];
2801  ++Args;
2802  --NumArgs;
2803  } else if (IsMemberFunction)
2804  ImplicitThis =
2805  cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2806 
2807  checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2808  IsMemberFunction, TheCall->getRParenLoc(),
2809  TheCall->getCallee()->getSourceRange(), CallType);
2810 
2811  IdentifierInfo *FnInfo = FDecl->getIdentifier();
2812  // None of the checks below are needed for functions that don't have
2813  // simple names (e.g., C++ conversion functions).
2814  if (!FnInfo)
2815  return false;
2816 
2817  CheckAbsoluteValueFunction(TheCall, FDecl);
2818  CheckMaxUnsignedZero(TheCall, FDecl);
2819 
2820  if (getLangOpts().ObjC1)
2821  DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2822 
2823  unsigned CMId = FDecl->getMemoryFunctionKind();
2824  if (CMId == 0)
2825  return false;
2826 
2827  // Handle memory setting and copying functions.
2828  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2829  CheckStrlcpycatArguments(TheCall, FnInfo);
2830  else if (CMId == Builtin::BIstrncat)
2831  CheckStrncatArguments(TheCall, FnInfo);
2832  else
2833  CheckMemaccessArguments(TheCall, CMId, FnInfo);
2834 
2835  return false;
2836 }
2837 
2838 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2839  ArrayRef<const Expr *> Args) {
2840  VariadicCallType CallType =
2841  Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2842 
2843  checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2844  /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2845  CallType);
2846 
2847  return false;
2848 }
2849 
2850 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2851  const FunctionProtoType *Proto) {
2852  QualType Ty;
2853  if (const auto *V = dyn_cast<VarDecl>(NDecl))
2854  Ty = V->getType().getNonReferenceType();
2855  else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2856  Ty = F->getType().getNonReferenceType();
2857  else
2858  return false;
2859 
2860  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2861  !Ty->isFunctionProtoType())
2862  return false;
2863 
2864  VariadicCallType CallType;
2865  if (!Proto || !Proto->isVariadic()) {
2866  CallType = VariadicDoesNotApply;
2867  } else if (Ty->isBlockPointerType()) {
2868  CallType = VariadicBlock;
2869  } else { // Ty->isFunctionPointerType()
2870  CallType = VariadicFunction;
2871  }
2872 
2873  checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2874  llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2875  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2876  TheCall->getCallee()->getSourceRange(), CallType);
2877 
2878  return false;
2879 }
2880 
2881 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2882 /// such as function pointers returned from functions.
2883 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2884  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2885  TheCall->getCallee());
2886  checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2887  llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2888  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2889  TheCall->getCallee()->getSourceRange(), CallType);
2890 
2891  return false;
2892 }
2893 
2894 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2895  if (!llvm::isValidAtomicOrderingCABI(Ordering))
2896  return false;
2897 
2898  auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2899  switch (Op) {
2900  case AtomicExpr::AO__c11_atomic_init:
2901  case AtomicExpr::AO__opencl_atomic_init:
2902  llvm_unreachable("There is no ordering argument for an init");
2903 
2904  case AtomicExpr::AO__c11_atomic_load:
2905  case AtomicExpr::AO__opencl_atomic_load:
2906  case AtomicExpr::AO__atomic_load_n:
2907  case AtomicExpr::AO__atomic_load:
2908  return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2909  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2910 
2911  case AtomicExpr::AO__c11_atomic_store:
2912  case AtomicExpr::AO__opencl_atomic_store:
2913  case AtomicExpr::AO__atomic_store:
2914  case AtomicExpr::AO__atomic_store_n:
2915  return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2916  OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2917  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2918 
2919  default:
2920  return true;
2921  }
2922 }
2923 
2924 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2925  AtomicExpr::AtomicOp Op) {
2926  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2927  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2928 
2929  // All the non-OpenCL operations take one of the following forms.
2930  // The OpenCL operations take the __c11 forms with one extra argument for
2931  // synchronization scope.
2932  enum {
2933  // C __c11_atomic_init(A *, C)
2934  Init,
2935 
2936  // C __c11_atomic_load(A *, int)
2937  Load,
2938 
2939  // void __atomic_load(A *, CP, int)
2940  LoadCopy,
2941 
2942  // void __atomic_store(A *, CP, int)
2943  Copy,
2944 
2945  // C __c11_atomic_add(A *, M, int)
2946  Arithmetic,
2947 
2948  // C __atomic_exchange_n(A *, CP, int)
2949  Xchg,
2950 
2951  // void __atomic_exchange(A *, C *, CP, int)
2952  GNUXchg,
2953 
2954  // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2955  C11CmpXchg,
2956 
2957  // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2958  GNUCmpXchg
2959  } Form = Init;
2960 
2961  const unsigned NumForm = GNUCmpXchg + 1;
2962  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2963  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2964  // where:
2965  // C is an appropriate type,
2966  // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2967  // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2968  // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2969  // the int parameters are for orderings.
2970 
2971  static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2972  && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2973  "need to update code for modified forms");
2974  static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2975  AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2976  AtomicExpr::AO__atomic_load,
2977  "need to update code for modified C11 atomics");
2978  bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2979  Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2980  bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2981  Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2982  IsOpenCL;
2983  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2984  Op == AtomicExpr::AO__atomic_store_n ||
2985  Op == AtomicExpr::AO__atomic_exchange_n ||
2986  Op == AtomicExpr::AO__atomic_compare_exchange_n;
2987  bool IsAddSub = false;
2988 
2989  switch (Op) {
2990  case AtomicExpr::AO__c11_atomic_init:
2991  case AtomicExpr::AO__opencl_atomic_init:
2992  Form = Init;
2993  break;
2994 
2995  case AtomicExpr::AO__c11_atomic_load:
2996  case AtomicExpr::AO__opencl_atomic_load:
2997  case AtomicExpr::AO__atomic_load_n:
2998  Form = Load;
2999  break;
3000 
3001  case AtomicExpr::AO__atomic_load:
3002  Form = LoadCopy;
3003  break;
3004 
3005  case AtomicExpr::AO__c11_atomic_store:
3006  case AtomicExpr::AO__opencl_atomic_store:
3007  case AtomicExpr::AO__atomic_store:
3008  case AtomicExpr::AO__atomic_store_n:
3009  Form = Copy;
3010  break;
3011 
3012  case AtomicExpr::AO__c11_atomic_fetch_add:
3013  case AtomicExpr::AO__c11_atomic_fetch_sub:
3014  case AtomicExpr::AO__opencl_atomic_fetch_add:
3015  case AtomicExpr::AO__opencl_atomic_fetch_sub:
3016  case AtomicExpr::AO__opencl_atomic_fetch_min:
3017  case AtomicExpr::AO__opencl_atomic_fetch_max:
3018  case AtomicExpr::AO__atomic_fetch_add:
3019  case AtomicExpr::AO__atomic_fetch_sub:
3020  case AtomicExpr::AO__atomic_add_fetch:
3021  case AtomicExpr::AO__atomic_sub_fetch:
3022  IsAddSub = true;
3023  // Fall through.
3024  case AtomicExpr::AO__c11_atomic_fetch_and:
3025  case AtomicExpr::AO__c11_atomic_fetch_or:
3026  case AtomicExpr::AO__c11_atomic_fetch_xor:
3027  case AtomicExpr::AO__opencl_atomic_fetch_and:
3028  case AtomicExpr::AO__opencl_atomic_fetch_or:
3029  case AtomicExpr::AO__opencl_atomic_fetch_xor:
3030  case AtomicExpr::AO__atomic_fetch_and:
3031  case AtomicExpr::AO__atomic_fetch_or:
3032  case AtomicExpr::AO__atomic_fetch_xor:
3033  case AtomicExpr::AO__atomic_fetch_nand:
3034  case AtomicExpr::AO__atomic_and_fetch:
3035  case AtomicExpr::AO__atomic_or_fetch:
3036  case AtomicExpr::AO__atomic_xor_fetch:
3037  case AtomicExpr::AO__atomic_nand_fetch:
3038  Form = Arithmetic;
3039  break;
3040 
3041  case AtomicExpr::AO__c11_atomic_exchange:
3042  case AtomicExpr::AO__opencl_atomic_exchange:
3043  case AtomicExpr::AO__atomic_exchange_n:
3044  Form = Xchg;
3045  break;
3046 
3047  case AtomicExpr::AO__atomic_exchange:
3048  Form = GNUXchg;
3049  break;
3050 
3051  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3052  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3053  case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3054  case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3055  Form = C11CmpXchg;
3056  break;
3057 
3058  case AtomicExpr::AO__atomic_compare_exchange:
3059  case AtomicExpr::AO__atomic_compare_exchange_n:
3060  Form = GNUCmpXchg;
3061  break;
3062  }
3063 
3064  unsigned AdjustedNumArgs = NumArgs[Form];
3065  if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3066  ++AdjustedNumArgs;
3067  // Check we have the right number of arguments.
3068  if (TheCall->getNumArgs() < AdjustedNumArgs) {
3069  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3070  << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3071  << TheCall->getCallee()->getSourceRange();
3072  return ExprError();
3073  } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3074  Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3075  diag::err_typecheck_call_too_many_args)
3076  << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3077  << TheCall->getCallee()->getSourceRange();
3078  return ExprError();
3079  }
3080 
3081  // Inspect the first argument of the atomic operation.
3082  Expr *Ptr = TheCall->getArg(0);
3083  ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3084  if (ConvertedPtr.isInvalid())
3085  return ExprError();
3086 
3087  Ptr = ConvertedPtr.get();
3088  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3089  if (!pointerType) {
3090  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3091  << Ptr->getType() << Ptr->getSourceRange();
3092  return ExprError();
3093  }
3094 
3095  // For a __c11 builtin, this should be a pointer to an _Atomic type.
3096  QualType AtomTy = pointerType->getPointeeType(); // 'A'
3097  QualType ValType = AtomTy; // 'C'
3098  if (IsC11) {
3099  if (!AtomTy->isAtomicType()) {
3100  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3101  << Ptr->getType() << Ptr->getSourceRange();
3102  return ExprError();
3103  }
3104  if (AtomTy.isConstQualified() ||
3106  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3107  << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3108  << Ptr->getSourceRange();
3109  return ExprError();
3110  }
3111  ValType = AtomTy->getAs<AtomicType>()->getValueType();
3112  } else if (Form != Load && Form != LoadCopy) {
3113  if (ValType.isConstQualified()) {
3114  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3115  << Ptr->getType() << Ptr->getSourceRange();
3116  return ExprError();
3117  }
3118  }
3119 
3120  // For an arithmetic operation, the implied arithmetic must be well-formed.
3121  if (Form == Arithmetic) {
3122  // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3123  if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3124  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3125  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3126  return ExprError();
3127  }
3128  if (!IsAddSub && !ValType->isIntegerType()) {
3129  Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3130  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3131  return ExprError();
3132  }
3133  if (IsC11 && ValType->isPointerType() &&
3134  RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3135  diag::err_incomplete_type)) {
3136  return ExprError();
3137  }
3138  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3139  // For __atomic_*_n operations, the value type must be a scalar integral or
3140  // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3141  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3142  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3143  return ExprError();
3144  }
3145 
3146  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3147  !AtomTy->isScalarType()) {
3148  // For GNU atomics, require a trivially-copyable type. This is not part of
3149  // the GNU atomics specification, but we enforce it for sanity.
3150  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3151  << Ptr->getType() << Ptr->getSourceRange();
3152  return ExprError();
3153  }
3154 
3155  switch (ValType.getObjCLifetime()) {
3156  case Qualifiers::OCL_None:
3158  // okay
3159  break;
3160 
3161  case Qualifiers::OCL_Weak:
3164  // FIXME: Can this happen? By this point, ValType should be known
3165  // to be trivially copyable.
3166  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3167  << ValType << Ptr->getSourceRange();
3168  return ExprError();
3169  }
3170 
3171  // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3172  // volatile-ness of the pointee-type inject itself into the result or the
3173  // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3174  ValType.removeLocalVolatile();
3175  ValType.removeLocalConst();
3176  QualType ResultType = ValType;
3177  if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3178  Form == Init)
3179  ResultType = Context.VoidTy;
3180  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3181  ResultType = Context.BoolTy;
3182 
3183  // The type of a parameter passed 'by value'. In the GNU atomics, such
3184  // arguments are actually passed as pointers.
3185  QualType ByValType = ValType; // 'CP'
3186  if (!IsC11 && !IsN)
3187  ByValType = Ptr->getType();
3188 
3189  // The first argument --- the pointer --- has a fixed type; we
3190  // deduce the types of the rest of the arguments accordingly. Walk
3191  // the remaining arguments, converting them to the deduced value type.
3192  for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3193  QualType Ty;
3194  if (i < NumVals[Form] + 1) {
3195  switch (i) {
3196  case 1:
3197  // The second argument is the non-atomic operand. For arithmetic, this
3198  // is always passed by value, and for a compare_exchange it is always
3199  // passed by address. For the rest, GNU uses by-address and C11 uses
3200  // by-value.
3201  assert(Form != Load);
3202  if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3203  Ty = ValType;
3204  else if (Form == Copy || Form == Xchg)
3205  Ty = ByValType;
3206  else if (Form == Arithmetic)
3207  Ty = Context.getPointerDiffType();
3208  else {
3209  Expr *ValArg = TheCall->getArg(i);
3210  // Treat this argument as _Nonnull as we want to show a warning if
3211  // NULL is passed into it.
3212  CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3213  LangAS AS = LangAS::Default;
3214  // Keep address space of non-atomic pointer type.
3215  if (const PointerType *PtrTy =
3216  ValArg->getType()->getAs<PointerType>()) {
3217  AS = PtrTy->getPointeeType().getAddressSpace();
3218  }
3219  Ty = Context.getPointerType(
3220  Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3221  }
3222  break;
3223  case 2:
3224  // The third argument to compare_exchange / GNU exchange is a
3225  // (pointer to a) desired value.
3226  Ty = ByValType;
3227  break;
3228  case 3:
3229  // The fourth argument to GNU compare_exchange is a 'weak' flag.
3230  Ty = Context.BoolTy;
3231  break;
3232  }
3233  } else {
3234  // The order(s) and scope are always converted to int.
3235  Ty = Context.IntTy;
3236  }
3237 
3238  InitializedEntity Entity =
3239  InitializedEntity::InitializeParameter(Context, Ty, false);
3240  ExprResult Arg = TheCall->getArg(i);
3241  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3242  if (Arg.isInvalid())
3243  return true;
3244  TheCall->setArg(i, Arg.get());
3245  }
3246 
3247  // Permute the arguments into a 'consistent' order.
3248  SmallVector<Expr*, 5> SubExprs;
3249  SubExprs.push_back(Ptr);
3250  switch (Form) {
3251  case Init:
3252  // Note, AtomicExpr::getVal1() has a special case for this atomic.
3253  SubExprs.push_back(TheCall->getArg(1)); // Val1
3254  break;
3255  case Load:
3256  SubExprs.push_back(TheCall->getArg(1)); // Order
3257  break;
3258  case LoadCopy:
3259  case Copy:
3260  case Arithmetic:
3261  case Xchg:
3262  SubExprs.push_back(TheCall->getArg(2)); // Order
3263  SubExprs.push_back(TheCall->getArg(1)); // Val1
3264  break;
3265  case GNUXchg:
3266  // Note, AtomicExpr::getVal2() has a special case for this atomic.
3267  SubExprs.push_back(TheCall->getArg(3)); // Order
3268  SubExprs.push_back(TheCall->getArg(1)); // Val1
3269  SubExprs.push_back(TheCall->getArg(2)); // Val2
3270  break;
3271  case C11CmpXchg:
3272  SubExprs.push_back(TheCall->getArg(3)); // Order
3273  SubExprs.push_back(TheCall->getArg(1)); // Val1
3274  SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3275  SubExprs.push_back(TheCall->getArg(2)); // Val2
3276  break;
3277  case GNUCmpXchg:
3278  SubExprs.push_back(TheCall->getArg(4)); // Order
3279  SubExprs.push_back(TheCall->getArg(1)); // Val1
3280  SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3281  SubExprs.push_back(TheCall->getArg(2)); // Val2
3282  SubExprs.push_back(TheCall->getArg(3)); // Weak
3283  break;
3284  }
3285 
3286  if (SubExprs.size() >= 2 && Form != Init) {
3287  llvm::APSInt Result(32);
3288  if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3289  !isValidOrderingForOp(Result.getSExtValue(), Op))
3290  Diag(SubExprs[1]->getLocStart(),
3291  diag::warn_atomic_op_has_invalid_memory_order)
3292  << SubExprs[1]->getSourceRange();
3293  }
3294 
3295  if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3296  auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3297  llvm::APSInt Result(32);
3298  if (Scope->isIntegerConstantExpr(Result, Context) &&
3299  !ScopeModel->isValid(Result.getZExtValue())) {
3300  Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3301  << Scope->getSourceRange();
3302  }
3303  SubExprs.push_back(Scope);
3304  }
3305 
3306  AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3307  SubExprs, ResultType, Op,
3308  TheCall->getRParenLoc());
3309 
3310  if ((Op == AtomicExpr::AO__c11_atomic_load ||
3311  Op == AtomicExpr::AO__c11_atomic_store ||
3312  Op == AtomicExpr::AO__opencl_atomic_load ||
3313  Op == AtomicExpr::AO__opencl_atomic_store ) &&
3314  Context.AtomicUsesUnsupportedLibcall(AE))
3315  Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3316  << ((Op == AtomicExpr::AO__c11_atomic_load ||
3317  Op == AtomicExpr::AO__opencl_atomic_load)
3318  ? 0 : 1);
3319 
3320  return AE;
3321 }
3322 
3323 /// checkBuiltinArgument - Given a call to a builtin function, perform
3324 /// normal type-checking on the given argument, updating the call in
3325 /// place. This is useful when a builtin function requires custom
3326 /// type-checking for some of its arguments but not necessarily all of
3327 /// them.
3328 ///
3329 /// Returns true on error.
3330 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3331  FunctionDecl *Fn = E->getDirectCallee();
3332  assert(Fn && "builtin call without direct callee!");
3333 
3334  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3335  InitializedEntity Entity =
3337 
3338  ExprResult Arg = E->getArg(0);
3339  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3340  if (Arg.isInvalid())
3341  return true;
3342 
3343  E->setArg(ArgIndex, Arg.get());
3344  return false;
3345 }
3346 
3347 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3348 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3349 /// type of its first argument. The main ActOnCallExpr routines have already
3350 /// promoted the types of arguments because all of these calls are prototyped as
3351 /// void(...).
3352 ///
3353 /// This function goes through and does final semantic checking for these
3354 /// builtins,
3355 ExprResult
3356 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3357  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3358  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3359  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3360 
3361  // Ensure that we have at least one argument to do type inference from.
3362  if (TheCall->getNumArgs() < 1) {
3363  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3364  << 0 << 1 << TheCall->getNumArgs()
3365  << TheCall->getCallee()->getSourceRange();
3366  return ExprError();
3367  }
3368 
3369  // Inspect the first argument of the atomic builtin. This should always be
3370  // a pointer type, whose element is an integral scalar or pointer type.
3371  // Because it is a pointer type, we don't have to worry about any implicit
3372  // casts here.
3373  // FIXME: We don't allow floating point scalars as input.
3374  Expr *FirstArg = TheCall->getArg(0);
3375  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3376  if (FirstArgResult.isInvalid())
3377  return ExprError();
3378  FirstArg = FirstArgResult.get();
3379  TheCall->setArg(0, FirstArg);
3380 
3381  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3382  if (!pointerType) {
3383  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3384  << FirstArg->getType() << FirstArg->getSourceRange();
3385  return ExprError();
3386  }
3387 
3388  QualType ValType = pointerType->getPointeeType();
3389  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3390  !ValType->isBlockPointerType()) {
3391  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3392  << FirstArg->getType() << FirstArg->getSourceRange();
3393  return ExprError();
3394  }
3395 
3396  switch (ValType.getObjCLifetime()) {
3397  case Qualifiers::OCL_None:
3399  // okay
3400  break;
3401 
3402  case Qualifiers::OCL_Weak:
3405  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3406  << ValType << FirstArg->getSourceRange();
3407  return ExprError();
3408  }
3409 
3410  // Strip any qualifiers off ValType.
3411  ValType = ValType.getUnqualifiedType();
3412 
3413  // The majority of builtins return a value, but a few have special return
3414  // types, so allow them to override appropriately below.
3415  QualType ResultType = ValType;
3416 
3417  // We need to figure out which concrete builtin this maps onto. For example,
3418  // __sync_fetch_and_add with a 2 byte object turns into
3419  // __sync_fetch_and_add_2.
3420 #define BUILTIN_ROW(x) \
3421  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3422  Builtin::BI##x##_8, Builtin::BI##x##_16 }
3423 
3424  static const unsigned BuiltinIndices[][5] = {
3425  BUILTIN_ROW(__sync_fetch_and_add),
3426  BUILTIN_ROW(__sync_fetch_and_sub),
3427  BUILTIN_ROW(__sync_fetch_and_or),
3428  BUILTIN_ROW(__sync_fetch_and_and),
3429  BUILTIN_ROW(__sync_fetch_and_xor),
3430  BUILTIN_ROW(__sync_fetch_and_nand),
3431 
3432  BUILTIN_ROW(__sync_add_and_fetch),
3433  BUILTIN_ROW(__sync_sub_and_fetch),
3434  BUILTIN_ROW(__sync_and_and_fetch),
3435  BUILTIN_ROW(__sync_or_and_fetch),
3436  BUILTIN_ROW(__sync_xor_and_fetch),
3437  BUILTIN_ROW(__sync_nand_and_fetch),
3438 
3439  BUILTIN_ROW(__sync_val_compare_and_swap),
3440  BUILTIN_ROW(__sync_bool_compare_and_swap),
3441  BUILTIN_ROW(__sync_lock_test_and_set),
3442  BUILTIN_ROW(__sync_lock_release),
3443  BUILTIN_ROW(__sync_swap)
3444  };
3445 #undef BUILTIN_ROW
3446 
3447  // Determine the index of the size.
3448  unsigned SizeIndex;
3449  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3450  case 1: SizeIndex = 0; break;
3451  case 2: SizeIndex = 1; break;
3452  case 4: SizeIndex = 2; break;
3453  case 8: SizeIndex = 3; break;
3454  case 16: SizeIndex = 4; break;
3455  default:
3456  Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3457  << FirstArg->getType() << FirstArg->getSourceRange();
3458  return ExprError();
3459  }
3460 
3461  // Each of these builtins has one pointer argument, followed by some number of
3462  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3463  // that we ignore. Find out which row of BuiltinIndices to read from as well
3464  // as the number of fixed args.
3465  unsigned BuiltinID = FDecl->getBuiltinID();
3466  unsigned BuiltinIndex, NumFixed = 1;
3467  bool WarnAboutSemanticsChange = false;
3468  switch (BuiltinID) {
3469  default: llvm_unreachable("Unknown overloaded atomic builtin!");
3470  case Builtin::BI__sync_fetch_and_add:
3471  case Builtin::BI__sync_fetch_and_add_1:
3472  case Builtin::BI__sync_fetch_and_add_2:
3473  case Builtin::BI__sync_fetch_and_add_4:
3474  case Builtin::BI__sync_fetch_and_add_8:
3475  case Builtin::BI__sync_fetch_and_add_16:
3476  BuiltinIndex = 0;
3477  break;
3478 
3479  case Builtin::BI__sync_fetch_and_sub:
3480  case Builtin::BI__sync_fetch_and_sub_1:
3481  case Builtin::BI__sync_fetch_and_sub_2:
3482  case Builtin::BI__sync_fetch_and_sub_4:
3483  case Builtin::BI__sync_fetch_and_sub_8:
3484  case Builtin::BI__sync_fetch_and_sub_16:
3485  BuiltinIndex = 1;
3486  break;
3487 
3488  case Builtin::BI__sync_fetch_and_or:
3489  case Builtin::BI__sync_fetch_and_or_1:
3490  case Builtin::BI__sync_fetch_and_or_2:
3491  case Builtin::BI__sync_fetch_and_or_4:
3492  case Builtin::BI__sync_fetch_and_or_8:
3493  case Builtin::BI__sync_fetch_and_or_16:
3494  BuiltinIndex = 2;
3495  break;
3496 
3497  case Builtin::BI__sync_fetch_and_and:
3498  case Builtin::BI__sync_fetch_and_and_1:
3499  case Builtin::BI__sync_fetch_and_and_2:
3500  case Builtin::BI__sync_fetch_and_and_4:
3501  case Builtin::BI__sync_fetch_and_and_8:
3502  case Builtin::BI__sync_fetch_and_and_16:
3503  BuiltinIndex = 3;
3504  break;
3505 
3506  case Builtin::BI__sync_fetch_and_xor:
3507  case Builtin::BI__sync_fetch_and_xor_1:
3508  case Builtin::BI__sync_fetch_and_xor_2:
3509  case Builtin::BI__sync_fetch_and_xor_4:
3510  case Builtin::BI__sync_fetch_and_xor_8:
3511  case Builtin::BI__sync_fetch_and_xor_16:
3512  BuiltinIndex = 4;
3513  break;
3514 
3515  case Builtin::BI__sync_fetch_and_nand:
3516  case Builtin::BI__sync_fetch_and_nand_1:
3517  case Builtin::BI__sync_fetch_and_nand_2:
3518  case Builtin::BI__sync_fetch_and_nand_4:
3519  case Builtin::BI__sync_fetch_and_nand_8:
3520  case Builtin::BI__sync_fetch_and_nand_16:
3521  BuiltinIndex = 5;
3522  WarnAboutSemanticsChange = true;
3523  break;
3524 
3525  case Builtin::BI__sync_add_and_fetch:
3526  case Builtin::BI__sync_add_and_fetch_1:
3527  case Builtin::BI__sync_add_and_fetch_2:
3528  case Builtin::BI__sync_add_and_fetch_4:
3529  case Builtin::BI__sync_add_and_fetch_8:
3530  case Builtin::BI__sync_add_and_fetch_16:
3531  BuiltinIndex = 6;
3532  break;
3533 
3534  case Builtin::BI__sync_sub_and_fetch:
3535  case Builtin::BI__sync_sub_and_fetch_1:
3536  case Builtin::BI__sync_sub_and_fetch_2:
3537  case Builtin::BI__sync_sub_and_fetch_4:
3538  case Builtin::BI__sync_sub_and_fetch_8:
3539  case Builtin::BI__sync_sub_and_fetch_16:
3540  BuiltinIndex = 7;
3541  break;
3542 
3543  case Builtin::BI__sync_and_and_fetch:
3544  case Builtin::BI__sync_and_and_fetch_1:
3545  case Builtin::BI__sync_and_and_fetch_2:
3546  case Builtin::BI__sync_and_and_fetch_4:
3547  case Builtin::BI__sync_and_and_fetch_8:
3548  case Builtin::BI__sync_and_and_fetch_16:
3549  BuiltinIndex = 8;
3550  break;
3551 
3552  case Builtin::BI__sync_or_and_fetch:
3553  case Builtin::BI__sync_or_and_fetch_1:
3554  case Builtin::BI__sync_or_and_fetch_2:
3555  case Builtin::BI__sync_or_and_fetch_4:
3556  case Builtin::BI__sync_or_and_fetch_8:
3557  case Builtin::BI__sync_or_and_fetch_16:
3558  BuiltinIndex = 9;
3559  break;
3560 
3561  case Builtin::BI__sync_xor_and_fetch:
3562  case Builtin::BI__sync_xor_and_fetch_1:
3563  case Builtin::BI__sync_xor_and_fetch_2:
3564  case Builtin::BI__sync_xor_and_fetch_4:
3565  case Builtin::BI__sync_xor_and_fetch_8:
3566  case Builtin::BI__sync_xor_and_fetch_16:
3567  BuiltinIndex = 10;
3568  break;
3569 
3570  case Builtin::BI__sync_nand_and_fetch:
3571  case Builtin::BI__sync_nand_and_fetch_1:
3572  case Builtin::BI__sync_nand_and_fetch_2:
3573  case Builtin::BI__sync_nand_and_fetch_4:
3574  case Builtin::BI__sync_nand_and_fetch_8:
3575  case Builtin::BI__sync_nand_and_fetch_16:
3576  BuiltinIndex = 11;
3577  WarnAboutSemanticsChange = true;
3578  break;
3579 
3580  case Builtin::BI__sync_val_compare_and_swap:
3581  case Builtin::BI__sync_val_compare_and_swap_1:
3582  case Builtin::BI__sync_val_compare_and_swap_2:
3583  case Builtin::BI__sync_val_compare_and_swap_4:
3584  case Builtin::BI__sync_val_compare_and_swap_8:
3585  case Builtin::BI__sync_val_compare_and_swap_16:
3586  BuiltinIndex = 12;
3587  NumFixed = 2;
3588  break;
3589 
3590  case Builtin::BI__sync_bool_compare_and_swap:
3591  case Builtin::BI__sync_bool_compare_and_swap_1:
3592  case Builtin::BI__sync_bool_compare_and_swap_2:
3593  case Builtin::BI__sync_bool_compare_and_swap_4:
3594  case Builtin::BI__sync_bool_compare_and_swap_8:
3595  case Builtin::BI__sync_bool_compare_and_swap_16:
3596  BuiltinIndex = 13;
3597  NumFixed = 2;
3598  ResultType = Context.BoolTy;
3599  break;
3600 
3601  case Builtin::BI__sync_lock_test_and_set:
3602  case Builtin::BI__sync_lock_test_and_set_1:
3603  case Builtin::BI__sync_lock_test_and_set_2:
3604  case Builtin::BI__sync_lock_test_and_set_4:
3605  case Builtin::BI__sync_lock_test_and_set_8:
3606  case Builtin::BI__sync_lock_test_and_set_16:
3607  BuiltinIndex = 14;
3608  break;
3609 
3610  case Builtin::BI__sync_lock_release:
3611  case Builtin::BI__sync_lock_release_1:
3612  case Builtin::BI__sync_lock_release_2:
3613  case Builtin::BI__sync_lock_release_4:
3614  case Builtin::BI__sync_lock_release_8:
3615  case Builtin::BI__sync_lock_release_16:
3616  BuiltinIndex = 15;
3617  NumFixed = 0;
3618  ResultType = Context.VoidTy;
3619  break;
3620 
3621  case Builtin::BI__sync_swap:
3622  case Builtin::BI__sync_swap_1:
3623  case Builtin::BI__sync_swap_2:
3624  case Builtin::BI__sync_swap_4:
3625  case Builtin::BI__sync_swap_8:
3626  case Builtin::BI__sync_swap_16:
3627  BuiltinIndex = 16;
3628  break;
3629  }
3630 
3631  // Now that we know how many fixed arguments we expect, first check that we
3632  // have at least that many.
3633  if (TheCall->getNumArgs() < 1+NumFixed) {
3634  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3635  << 0 << 1+NumFixed << TheCall->getNumArgs()
3636  << TheCall->getCallee()->getSourceRange();
3637  return ExprError();
3638  }
3639 
3640  if (WarnAboutSemanticsChange) {
3641  Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3642  << TheCall->getCallee()->getSourceRange();
3643  }
3644 
3645  // Get the decl for the concrete builtin from this, we can tell what the
3646  // concrete integer type we should convert to is.
3647  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3648  const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3649  FunctionDecl *NewBuiltinDecl;
3650  if (NewBuiltinID == BuiltinID)
3651  NewBuiltinDecl = FDecl;
3652  else {
3653  // Perform builtin lookup to avoid redeclaring it.
3654  DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3655  LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3656  LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3657  assert(Res.getFoundDecl());
3658  NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3659  if (!NewBuiltinDecl)
3660  return ExprError();
3661  }
3662 
3663  // The first argument --- the pointer --- has a fixed type; we
3664  // deduce the types of the rest of the arguments accordingly. Walk
3665  // the remaining arguments, converting them to the deduced value type.
3666  for (unsigned i = 0; i != NumFixed; ++i) {
3667  ExprResult Arg = TheCall->getArg(i+1);
3668 
3669  // GCC does an implicit conversion to the pointer or integer ValType. This
3670  // can fail in some cases (1i -> int**), check for this error case now.
3671  // Initialize the argument.
3673  ValType, /*consume*/ false);
3674  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3675  if (Arg.isInvalid())
3676  return ExprError();
3677 
3678  // Okay, we have something that *can* be converted to the right type. Check
3679  // to see if there is a potentially weird extension going on here. This can
3680  // happen when you do an atomic operation on something like an char* and
3681  // pass in 42. The 42 gets converted to char. This is even more strange
3682  // for things like 45.123 -> char, etc.
3683  // FIXME: Do this check.
3684  TheCall->setArg(i+1, Arg.get());
3685  }
3686 
3687  ASTContext& Context = this->getASTContext();
3688 
3689  // Create a new DeclRefExpr to refer to the new decl.
3690  DeclRefExpr* NewDRE = DeclRefExpr::Create(
3691  Context,
3692  DRE->getQualifierLoc(),
3693  SourceLocation(),
3694  NewBuiltinDecl,
3695  /*enclosing*/ false,
3696  DRE->getLocation(),
3697  Context.BuiltinFnTy,
3698  DRE->getValueKind());
3699 
3700  // Set the callee in the CallExpr.
3701  // FIXME: This loses syntactic information.
3702  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3703  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3704  CK_BuiltinFnToFnPtr);
3705  TheCall->setCallee(PromotedCall.get());
3706 
3707  // Change the result type of the call to match the original value type. This
3708  // is arbitrary, but the codegen for these builtins ins design to handle it
3709  // gracefully.
3710  TheCall->setType(ResultType);
3711 
3712  return TheCallResult;
3713 }
3714 
3715 /// SemaBuiltinNontemporalOverloaded - We have a call to
3716 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3717 /// overloaded function based on the pointer type of its last argument.
3718 ///
3719 /// This function goes through and does final semantic checking for these
3720 /// builtins.
3721 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3722  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3723  DeclRefExpr *DRE =
3724  cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3725  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3726  unsigned BuiltinID = FDecl->getBuiltinID();
3727  assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3728  BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3729  "Unexpected nontemporal load/store builtin!");
3730  bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3731  unsigned numArgs = isStore ? 2 : 1;
3732 
3733  // Ensure that we have the proper number of arguments.
3734  if (checkArgCount(*this, TheCall, numArgs))
3735  return ExprError();
3736 
3737  // Inspect the last argument of the nontemporal builtin. This should always
3738  // be a pointer type, from which we imply the type of the memory access.
3739  // Because it is a pointer type, we don't have to worry about any implicit
3740  // casts here.
3741  Expr *PointerArg = TheCall->getArg(numArgs - 1);
3742  ExprResult PointerArgResult =
3743  DefaultFunctionArrayLvalueConversion(PointerArg);
3744 
3745  if (PointerArgResult.isInvalid())
3746  return ExprError();
3747  PointerArg = PointerArgResult.get();
3748  TheCall->setArg(numArgs - 1, PointerArg);
3749 
3750  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3751  if (!pointerType) {
3752  Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3753  << PointerArg->getType() << PointerArg->getSourceRange();
3754  return ExprError();
3755  }
3756 
3757  QualType ValType = pointerType->getPointeeType();
3758 
3759  // Strip any qualifiers off ValType.
3760  ValType = ValType.getUnqualifiedType();
3761  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3762  !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3763  !ValType->isVectorType()) {
3764  Diag(DRE->getLocStart(),
3765  diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3766  << PointerArg->getType() << PointerArg->getSourceRange();
3767  return ExprError();
3768  }
3769 
3770  if (!isStore) {
3771  TheCall->setType(ValType);
3772  return TheCallResult;
3773  }
3774 
3775  ExprResult ValArg = TheCall->getArg(0);
3777  Context, ValType, /*consume*/ false);
3778  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3779  if (ValArg.isInvalid())
3780  return ExprError();
3781 
3782  TheCall->setArg(0, ValArg.get());
3783  TheCall->setType(Context.VoidTy);
3784  return TheCallResult;
3785 }
3786 
3787 /// CheckObjCString - Checks that the argument to the builtin
3788 /// CFString constructor is correct
3789 /// Note: It might also make sense to do the UTF-16 conversion here (would
3790 /// simplify the backend).
3791 bool Sema::CheckObjCString(Expr *Arg) {
3792  Arg = Arg->IgnoreParenCasts();
3793  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3794 
3795  if (!Literal || !Literal->isAscii()) {
3796  Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3797  << Arg->getSourceRange();
3798  return true;
3799  }
3800 
3801  if (Literal->containsNonAsciiOrNull()) {
3802  StringRef String = Literal->getString();
3803  unsigned NumBytes = String.size();
3804  SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3805  const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3806  llvm::UTF16 *ToPtr = &ToBuf[0];
3807 
3808  llvm::ConversionResult Result =
3809  llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3810  ToPtr + NumBytes, llvm::strictConversion);
3811  // Check for conversion failure.
3812  if (Result != llvm::conversionOK)
3813  Diag(Arg->getLocStart(),
3814  diag::warn_cfstring_truncated) << Arg->getSourceRange();
3815  }
3816  return false;
3817 }
3818 
3819 /// CheckObjCString - Checks that the format string argument to the os_log()
3820 /// and os_trace() functions is correct, and converts it to const char *.
3821 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3822  Arg = Arg->IgnoreParenCasts();
3823  auto *Literal = dyn_cast<StringLiteral>(Arg);
3824  if (!Literal) {
3825  if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3826  Literal = ObjcLiteral->getString();
3827  }
3828  }
3829 
3830  if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3831  return ExprError(
3832  Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3833  << Arg->getSourceRange());
3834  }
3835 
3836  ExprResult Result(Literal);
3837  QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3838  InitializedEntity Entity =
3839  InitializedEntity::InitializeParameter(Context, ResultTy, false);
3840  Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3841  return Result;
3842 }
3843 
3844 /// Check that the user is calling the appropriate va_start builtin for the
3845 /// target and calling convention.
3846 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3847  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3848  bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3849  bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3850  bool IsWindows = TT.isOSWindows();
3851  bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3852  if (IsX64 || IsAArch64) {
3853  CallingConv CC = CC_C;
3854  if (const FunctionDecl *FD = S.getCurFunctionDecl())
3855  CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3856  if (IsMSVAStart) {
3857  // Don't allow this in System V ABI functions.
3858  if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3859  return S.Diag(Fn->getLocStart(),
3860  diag::err_ms_va_start_used_in_sysv_function);
3861  } else {
3862  // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3863  // On x64 Windows, don't allow this in System V ABI functions.
3864  // (Yes, that means there's no corresponding way to support variadic
3865  // System V ABI functions on Windows.)
3866  if ((IsWindows && CC == CC_X86_64SysV) ||
3867  (!IsWindows && CC == CC_Win64))
3868  return S.Diag(Fn->getLocStart(),
3869  diag::err_va_start_used_in_wrong_abi_function)
3870  << !IsWindows;
3871  }
3872  return false;
3873  }
3874 
3875  if (IsMSVAStart)
3876  return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3877  return false;
3878 }
3879 
3881  ParmVarDecl **LastParam = nullptr) {
3882  // Determine whether the current function, block, or obj-c method is variadic
3883  // and get its parameter list.
3884  bool IsVariadic = false;
3885  ArrayRef<ParmVarDecl *> Params;
3886  DeclContext *Caller = S.CurContext;
3887  if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3888  IsVariadic = Block->isVariadic();
3889  Params = Block->parameters();
3890  } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3891  IsVariadic = FD->isVariadic();
3892  Params = FD->parameters();
3893  } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3894  IsVariadic = MD->isVariadic();
3895  // FIXME: This isn't correct for methods (results in bogus warning).
3896  Params = MD->parameters();
3897  } else if (isa<CapturedDecl>(Caller)) {
3898  // We don't support va_start in a CapturedDecl.
3899  S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3900  return true;
3901  } else {
3902  // This must be some other declcontext that parses exprs.
3903  S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3904  return true;
3905  }
3906 
3907  if (!IsVariadic) {
3908  S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3909  return true;
3910  }
3911 
3912  if (LastParam)
3913  *LastParam = Params.empty() ? nullptr : Params.back();
3914 
3915  return false;
3916 }
3917 
3918 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3919 /// for validity. Emit an error and return true on failure; return false
3920 /// on success.
3921 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3922  Expr *Fn = TheCall->getCallee();
3923 
3924  if (checkVAStartABI(*this, BuiltinID, Fn))
3925  return true;
3926 
3927  if (TheCall->getNumArgs() > 2) {
3928  Diag(TheCall->getArg(2)->getLocStart(),
3929  diag::err_typecheck_call_too_many_args)
3930  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3931  << Fn->getSourceRange()
3932  << SourceRange(TheCall->getArg(2)->getLocStart(),
3933  (*(TheCall->arg_end()-1))->getLocEnd());
3934  return true;
3935  }
3936 
3937  if (TheCall->getNumArgs() < 2) {
3938  return Diag(TheCall->getLocEnd(),
3939  diag::err_typecheck_call_too_few_args_at_least)
3940  << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3941  }
3942 
3943  // Type-check the first argument normally.
3944  if (checkBuiltinArgument(*this, TheCall, 0))
3945  return true;
3946 
3947  // Check that the current function is variadic, and get its last parameter.
3948  ParmVarDecl *LastParam;
3949  if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3950  return true;
3951 
3952  // Verify that the second argument to the builtin is the last argument of the
3953  // current function or method.
3954  bool SecondArgIsLastNamedArgument = false;
3955  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3956 
3957  // These are valid if SecondArgIsLastNamedArgument is false after the next
3958  // block.
3959  QualType Type;
3960  SourceLocation ParamLoc;
3961  bool IsCRegister = false;
3962 
3963  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3964  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3965  SecondArgIsLastNamedArgument = PV == LastParam;
3966 
3967  Type = PV->getType();
3968  ParamLoc = PV->getLocation();
3969  IsCRegister =
3970  PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3971  }
3972  }
3973 
3974  if (!SecondArgIsLastNamedArgument)
3975  Diag(TheCall->getArg(1)->getLocStart(),
3976  diag::warn_second_arg_of_va_start_not_last_named_param);
3977  else if (IsCRegister || Type->isReferenceType() ||
3978  Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3979  // Promotable integers are UB, but enumerations need a bit of
3980  // extra checking to see what their promotable type actually is.
3981  if (!Type->isPromotableIntegerType())
3982  return false;
3983  if (!Type->isEnumeralType())
3984  return true;
3985  const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3986  return !(ED &&
3987  Context.typesAreCompatible(ED->getPromotionType(), Type));
3988  }()) {
3989  unsigned Reason = 0;
3990  if (Type->isReferenceType()) Reason = 1;
3991  else if (IsCRegister) Reason = 2;
3992  Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3993  Diag(ParamLoc, diag::note_parameter_type) << Type;
3994  }
3995 
3996  TheCall->setType(Context.VoidTy);
3997  return false;
3998 }
3999 
4000 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4001  // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4002  // const char *named_addr);
4003 
4004  Expr *Func = Call->getCallee();
4005 
4006  if (Call->getNumArgs() < 3)
4007  return Diag(Call->getLocEnd(),
4008  diag::err_typecheck_call_too_few_args_at_least)
4009  << 0 /*function call*/ << 3 << Call->getNumArgs();
4010 
4011  // Type-check the first argument normally.
4012  if (checkBuiltinArgument(*this, Call, 0))
4013  return true;
4014 
4015  // Check that the current function is variadic.
4016  if (checkVAStartIsInVariadicFunction(*this, Func))
4017  return true;
4018 
4019  // __va_start on Windows does not validate the parameter qualifiers
4020 
4021  const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4022  const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4023 
4024  const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4025  const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4026 
4027  const QualType &ConstCharPtrTy =
4028  Context.getPointerType(Context.CharTy.withConst());
4029  if (!Arg1Ty->isPointerType() ||
4030  Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4031  Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4032  << Arg1->getType() << ConstCharPtrTy
4033  << 1 /* different class */
4034  << 0 /* qualifier difference */
4035  << 3 /* parameter mismatch */
4036  << 2 << Arg1->getType() << ConstCharPtrTy;
4037 
4038  const QualType SizeTy = Context.getSizeType();
4039  if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4040  Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4041  << Arg2->getType() << SizeTy
4042  << 1 /* different class */
4043  << 0 /* qualifier difference */
4044  << 3 /* parameter mismatch */
4045  << 3 << Arg2->getType() << SizeTy;
4046 
4047  return false;
4048 }
4049 
4050 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4051 /// friends. This is declared to take (...), so we have to check everything.
4052 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4053  if (TheCall->getNumArgs() < 2)
4054  return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4055  << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4056  if (TheCall->getNumArgs() > 2)
4057  return Diag(TheCall->getArg(2)->getLocStart(),
4058  diag::err_typecheck_call_too_many_args)
4059  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4060  << SourceRange(TheCall->getArg(2)->getLocStart(),
4061  (*(TheCall->arg_end()-1))->getLocEnd());
4062 
4063  ExprResult OrigArg0 = TheCall->getArg(0);
4064  ExprResult OrigArg1 = TheCall->getArg(1);
4065 
4066  // Do standard promotions between the two arguments, returning their common
4067  // type.
4068  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4069  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4070  return true;
4071 
4072  // Make sure any conversions are pushed back into the call; this is
4073  // type safe since unordered compare builtins are declared as "_Bool
4074  // foo(...)".
4075  TheCall->setArg(0, OrigArg0.get());
4076  TheCall->setArg(1, OrigArg1.get());
4077 
4078  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4079  return false;
4080 
4081  // If the common type isn't a real floating type, then the arguments were
4082  // invalid for this operation.
4083  if (Res.isNull() || !Res->isRealFloatingType())
4084  return Diag(OrigArg0.get()->getLocStart(),
4085  diag::err_typecheck_call_invalid_ordered_compare)
4086  << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4087  << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4088 
4089  return false;
4090 }
4091 
4092 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4093 /// __builtin_isnan and friends. This is declared to take (...), so we have
4094 /// to check everything. We expect the last argument to be a floating point
4095 /// value.
4096 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4097  if (TheCall->getNumArgs() < NumArgs)
4098  return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4099  << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4100  if (TheCall->getNumArgs() > NumArgs)
4101  return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4102  diag::err_typecheck_call_too_many_args)
4103  << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4104  << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4105  (*(TheCall->arg_end()-1))->getLocEnd());
4106 
4107  Expr *OrigArg = TheCall->getArg(NumArgs-1);
4108 
4109  if (OrigArg->isTypeDependent())
4110  return false;
4111 
4112  // This operation requires a non-_Complex floating-point number.
4113  if (!OrigArg->getType()->isRealFloatingType())
4114  return Diag(OrigArg->getLocStart(),
4115  diag::err_typecheck_call_invalid_unary_fp)
4116  << OrigArg->getType() << OrigArg->getSourceRange();
4117 
4118  // If this is an implicit conversion from float -> float or double, remove it.
4119  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4120  // Only remove standard FloatCasts, leaving other casts inplace
4121  if (Cast->getCastKind() == CK_FloatingCast) {
4122  Expr *CastArg = Cast->getSubExpr();
4123  if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4124  assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4125  Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4126  "promotion from float to either float or double is the only expected cast here");
4127  Cast->setSubExpr(nullptr);
4128  TheCall->setArg(NumArgs-1, CastArg);
4129  }
4130  }
4131  }
4132 
4133  return false;
4134 }
4135 
4136 // Customized Sema Checking for VSX builtins that have the following signature:
4137 // vector [...] builtinName(vector [...], vector [...], const int);
4138 // Which takes the same type of vectors (any legal vector type) for the first
4139 // two arguments and takes compile time constant for the third argument.
4140 // Example builtins are :
4141 // vector double vec_xxpermdi(vector double, vector double, int);
4142 // vector short vec_xxsldwi(vector short, vector short, int);
4143 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4144  unsigned ExpectedNumArgs = 3;
4145  if (TheCall->getNumArgs() < ExpectedNumArgs)
4146  return Diag(TheCall->getLocEnd(),
4147  diag::err_typecheck_call_too_few_args_at_least)
4148  << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4149  << TheCall->getSourceRange();
4150 
4151  if (TheCall->getNumArgs() > ExpectedNumArgs)
4152  return Diag(TheCall->getLocEnd(),
4153  diag::err_typecheck_call_too_many_args_at_most)
4154  << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4155  << TheCall->getSourceRange();
4156 
4157  // Check the third argument is a compile time constant
4158  llvm::APSInt Value;
4159  if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4160  return Diag(TheCall->getLocStart(),
4161  diag::err_vsx_builtin_nonconstant_argument)
4162  << 3 /* argument index */ << TheCall->getDirectCallee()
4163  << SourceRange(TheCall->getArg(2)->getLocStart(),
4164  TheCall->getArg(2)->getLocEnd());
4165 
4166  QualType Arg1Ty = TheCall->getArg(0)->getType();
4167  QualType Arg2Ty = TheCall->getArg(1)->getType();
4168 
4169  // Check the type of argument 1 and argument 2 are vectors.
4170  SourceLocation BuiltinLoc = TheCall->getLocStart();
4171  if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4172  (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4173  return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4174  << TheCall->getDirectCallee()
4175  << SourceRange(TheCall->getArg(0)->getLocStart(),
4176  TheCall->getArg(1)->getLocEnd());
4177  }
4178 
4179  // Check the first two arguments are the same type.
4180  if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4181  return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4182  << TheCall->getDirectCallee()
4183  << SourceRange(TheCall->getArg(0)->getLocStart(),
4184  TheCall->getArg(1)->getLocEnd());
4185  }
4186 
4187  // When default clang type checking is turned off and the customized type
4188  // checking is used, the returning type of the function must be explicitly
4189  // set. Otherwise it is _Bool by default.
4190  TheCall->setType(Arg1Ty);
4191 
4192  return false;
4193 }
4194 
4195 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4196 // This is declared to take (...), so we have to check everything.
4198  if (TheCall->getNumArgs() < 2)
4199  return ExprError(Diag(TheCall->getLocEnd(),
4200  diag::err_typecheck_call_too_few_args_at_least)
4201  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4202  << TheCall->getSourceRange());
4203 
4204  // Determine which of the following types of shufflevector we're checking:
4205  // 1) unary, vector mask: (lhs, mask)
4206  // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4207  QualType resType = TheCall->getArg(0)->getType();
4208  unsigned numElements = 0;
4209 
4210  if (!TheCall->getArg(0)->isTypeDependent() &&
4211  !TheCall->getArg(1)->isTypeDependent()) {
4212  QualType LHSType = TheCall->getArg(0)->getType();
4213  QualType RHSType = TheCall->getArg(1)->getType();
4214 
4215  if (!LHSType->isVectorType() || !RHSType->isVectorType())
4216  return ExprError(Diag(TheCall->getLocStart(),
4217  diag::err_vec_builtin_non_vector)
4218  << TheCall->getDirectCallee()
4219  << SourceRange(TheCall->getArg(0)->getLocStart(),
4220  TheCall->getArg(1)->getLocEnd()));
4221 
4222  numElements = LHSType->getAs<VectorType>()->getNumElements();
4223  unsigned numResElements = TheCall->getNumArgs() - 2;
4224 
4225  // Check to see if we have a call with 2 vector arguments, the unary shuffle
4226  // with mask. If so, verify that RHS is an integer vector type with the
4227  // same number of elts as lhs.
4228  if (TheCall->getNumArgs() == 2) {
4229  if (!RHSType->hasIntegerRepresentation() ||
4230  RHSType->getAs<VectorType>()->getNumElements() != numElements)
4231  return ExprError(Diag(TheCall->getLocStart(),
4232  diag::err_vec_builtin_incompatible_vector)
4233  << TheCall->getDirectCallee()
4234  << SourceRange(TheCall->getArg(1)->getLocStart(),
4235  TheCall->getArg(1)->getLocEnd()));
4236  } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4237  return ExprError(Diag(TheCall->getLocStart(),
4238  diag::err_vec_builtin_incompatible_vector)
4239  << TheCall->getDirectCallee()
4240  << SourceRange(TheCall->getArg(0)->getLocStart(),
4241  TheCall->getArg(1)->getLocEnd()));
4242  } else if (numElements != numResElements) {
4243  QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4244  resType = Context.getVectorType(eltType, numResElements,
4246  }
4247  }
4248 
4249  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4250  if (TheCall->getArg(i)->isTypeDependent() ||
4251  TheCall->getArg(i)->isValueDependent())
4252  continue;
4253 
4254  llvm::APSInt Result(32);
4255  if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4256  return ExprError(Diag(TheCall->getLocStart(),
4257  diag::err_shufflevector_nonconstant_argument)
4258  << TheCall->getArg(i)->getSourceRange());
4259 
4260  // Allow -1 which will be translated to undef in the IR.
4261  if (Result.isSigned() && Result.isAllOnesValue())
4262  continue;
4263 
4264  if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4265  return ExprError(Diag(TheCall->getLocStart(),
4266  diag::err_shufflevector_argument_too_large)
4267  << TheCall->getArg(i)->getSourceRange());
4268  }
4269 
4270  SmallVector<Expr*, 32> exprs;
4271 
4272  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4273  exprs.push_back(TheCall->getArg(i));
4274  TheCall->setArg(i, nullptr);
4275  }
4276 
4277  return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4278  TheCall->getCallee()->getLocStart(),
4279  TheCall->getRParenLoc());
4280 }
4281 
4282 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4284  SourceLocation BuiltinLoc,
4285  SourceLocation RParenLoc) {
4286  ExprValueKind VK = VK_RValue;
4288  QualType DstTy = TInfo->getType();
4289  QualType SrcTy = E->getType();
4290 
4291  if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4292  return ExprError(Diag(BuiltinLoc,
4293  diag::err_convertvector_non_vector)
4294  << E->getSourceRange());
4295  if (!DstTy->isVectorType() && !DstTy->isDependentType())
4296  return ExprError(Diag(BuiltinLoc,
4297  diag::err_convertvector_non_vector_type));
4298 
4299  if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4300  unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4301  unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4302  if (SrcElts != DstElts)
4303  return ExprError(Diag(BuiltinLoc,
4304  diag::err_convertvector_incompatible_vector)
4305  << E->getSourceRange());
4306  }
4307 
4308  return new (Context)
4309  ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4310 }
4311 
4312 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4313 // This is declared to take (const void*, ...) and can take two
4314 // optional constant int args.
4315 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4316  unsigned NumArgs = TheCall->getNumArgs();
4317 
4318  if (NumArgs > 3)
4319  return Diag(TheCall->getLocEnd(),
4320  diag::err_typecheck_call_too_many_args_at_most)
4321  << 0 /*function call*/ << 3 << NumArgs
4322  << TheCall->getSourceRange();
4323 
4324  // Argument 0 is checked for us and the remaining arguments must be
4325  // constant integers.
4326  for (unsigned i = 1; i != NumArgs; ++i)
4327  if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4328  return true;
4329 
4330  return false;
4331 }
4332 
4333 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4334 // __assume does not evaluate its arguments, and should warn if its argument
4335 // has side effects.
4336 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4337  Expr *Arg = TheCall->getArg(0);
4338  if (Arg->isInstantiationDependent()) return false;
4339 
4340  if (Arg->HasSideEffects(Context))
4341  Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4342  << Arg->getSourceRange()
4343  << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4344 
4345  return false;
4346 }
4347 
4348 /// Handle __builtin_alloca_with_align. This is declared
4349 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4350 /// than 8.
4351 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4352  // The alignment must be a constant integer.
4353  Expr *Arg = TheCall->getArg(1);
4354 
4355  // We can't check the value of a dependent argument.
4356  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4357  if (const auto *UE =
4358  dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4359  if (UE->getKind() == UETT_AlignOf)
4360  Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4361  << Arg->getSourceRange();
4362 
4363  llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4364 
4365  if (!Result.isPowerOf2())
4366  return Diag(TheCall->getLocStart(),
4367  diag::err_alignment_not_power_of_two)
4368  << Arg->getSourceRange();
4369 
4370  if (Result < Context.getCharWidth())
4371  return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4372  << (unsigned)Context.getCharWidth()
4373  << Arg->getSourceRange();
4374 
4375  if (Result > std::numeric_limits<int32_t>::max())
4376  return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4378  << Arg->getSourceRange();
4379  }
4380 
4381  return false;
4382 }
4383 
4384 /// Handle __builtin_assume_aligned. This is declared
4385 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4386 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4387  unsigned NumArgs = TheCall->getNumArgs();
4388 
4389  if (NumArgs > 3)
4390  return Diag(TheCall->getLocEnd(),
4391  diag::err_typecheck_call_too_many_args_at_most)
4392  << 0 /*function call*/ << 3 << NumArgs
4393  << TheCall->getSourceRange();
4394 
4395  // The alignment must be a constant integer.
4396  Expr *Arg = TheCall->getArg(1);
4397 
4398  // We can't check the value of a dependent argument.
4399  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4400  llvm::APSInt Result;
4401  if (SemaBuiltinConstantArg(TheCall, 1, Result))
4402  return true;
4403 
4404  if (!Result.isPowerOf2())
4405  return Diag(TheCall->getLocStart(),
4406  diag::err_alignment_not_power_of_two)
4407  << Arg->getSourceRange();
4408  }
4409 
4410  if (NumArgs > 2) {
4411  ExprResult Arg(TheCall->getArg(2));
4413  Context.getSizeType(), false);
4414  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4415  if (Arg.isInvalid()) return true;
4416  TheCall->setArg(2, Arg.get());
4417  }
4418 
4419  return false;
4420 }
4421 
4422 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4423  unsigned BuiltinID =
4424  cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4425  bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4426 
4427  unsigned NumArgs = TheCall->getNumArgs();
4428  unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4429  if (NumArgs < NumRequiredArgs) {
4430  return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4431  << 0 /* function call */ << NumRequiredArgs << NumArgs
4432  << TheCall->getSourceRange();
4433  }
4434  if (NumArgs >= NumRequiredArgs + 0x100) {
4435  return Diag(TheCall->getLocEnd(),
4436  diag::err_typecheck_call_too_many_args_at_most)
4437  << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4438  << TheCall->getSourceRange();
4439  }
4440  unsigned i = 0;
4441 
4442  // For formatting call, check buffer arg.
4443  if (!IsSizeCall) {
4444  ExprResult Arg(TheCall->getArg(i));
4446  Context, Context.VoidPtrTy, false);
4447  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4448  if (Arg.isInvalid())
4449  return true;
4450  TheCall->setArg(i, Arg.get());
4451  i++;
4452  }
4453 
4454  // Check string literal arg.
4455  unsigned FormatIdx = i;
4456  {
4457  ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4458  if (Arg.isInvalid())
4459  return true;
4460  TheCall->setArg(i, Arg.get());
4461  i++;
4462  }
4463 
4464  // Make sure variadic args are scalar.
4465  unsigned FirstDataArg = i;
4466  while (i < NumArgs) {
4467  ExprResult Arg = DefaultVariadicArgumentPromotion(
4468  TheCall->getArg(i), VariadicFunction, nullptr);
4469  if (Arg.isInvalid())
4470  return true;
4471  CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4472  if (ArgSize.getQuantity() >= 0x100) {
4473  return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4474  << i << (int)ArgSize.getQuantity() << 0xff
4475  << TheCall->getSourceRange();
4476  }
4477  TheCall->setArg(i, Arg.get());
4478  i++;
4479  }
4480 
4481  // Check formatting specifiers. NOTE: We're only doing this for the non-size
4482  // call to avoid duplicate diagnostics.
4483  if (!IsSizeCall) {
4484  llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4485  ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4486  bool Success = CheckFormatArguments(
4487  Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4488  VariadicFunction, TheCall->getLocStart(), SourceRange(),
4489  CheckedVarArgs);
4490  if (!Success)
4491  return true;
4492  }
4493 
4494  if (IsSizeCall) {
4495  TheCall->setType(Context.getSizeType());
4496  } else {
4497  TheCall->setType(Context.VoidPtrTy);
4498  }
4499  return false;
4500 }
4501 
4502 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4503 /// TheCall is a constant expression.
4504 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4505  llvm::APSInt &Result) {
4506  Expr *Arg = TheCall->getArg(ArgNum);
4507  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4508  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4509 
4510  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4511 
4512  if (!Arg->isIntegerConstantExpr(Result, Context))
4513  return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4514  << FDecl->getDeclName() << Arg->getSourceRange();
4515 
4516  return false;
4517 }
4518 
4519 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4520 /// TheCall is a constant expression in the range [Low, High].
4521 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4522  int Low, int High) {
4523  llvm::APSInt Result;
4524 
4525  // We can't check the value of a dependent argument.
4526  Expr *Arg = TheCall->getArg(ArgNum);
4527  if (Arg->isTypeDependent() || Arg->isValueDependent())
4528  return false;
4529 
4530  // Check constant-ness first.
4531  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4532  return true;
4533 
4534  if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4535  return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4536  << Low << High << Arg->getSourceRange();
4537 
4538  return false;
4539 }
4540 
4541 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4542 /// TheCall is a constant expression is a multiple of Num..
4543 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4544  unsigned Num) {
4545  llvm::APSInt Result;
4546 
4547  // We can't check the value of a dependent argument.
4548  Expr *Arg = TheCall->getArg(ArgNum);
4549  if (Arg->isTypeDependent() || Arg->isValueDependent())
4550  return false;
4551 
4552  // Check constant-ness first.
4553  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4554  return true;
4555 
4556  if (Result.getSExtValue() % Num != 0)
4557  return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4558  << Num << Arg->getSourceRange();
4559 
4560  return false;
4561 }
4562 
4563 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4564 /// TheCall is an ARM/AArch64 special register string literal.
4565 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4566  int ArgNum, unsigned ExpectedFieldNum,
4567  bool AllowName) {
4568  bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4569  BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4570  BuiltinID == ARM::BI__builtin_arm_rsr ||
4571  BuiltinID == ARM::BI__builtin_arm_rsrp ||
4572  BuiltinID == ARM::BI__builtin_arm_wsr ||
4573  BuiltinID == ARM::BI__builtin_arm_wsrp;
4574  bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4575  BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4576  BuiltinID == AArch64::BI__builtin_arm_rsr ||
4577  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4578  BuiltinID == AArch64::BI__builtin_arm_wsr ||
4579  BuiltinID == AArch64::BI__builtin_arm_wsrp;
4580  assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4581 
4582  // We can't check the value of a dependent argument.
4583  Expr *Arg = TheCall->getArg(ArgNum);
4584  if (Arg->isTypeDependent() || Arg->isValueDependent())
4585  return false;
4586 
4587  // Check if the argument is a string literal.
4588  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4589  return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4590  << Arg->getSourceRange();
4591 
4592  // Check the type of special register given.
4593  StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4595  Reg.split(Fields, ":");
4596 
4597  if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4598  return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4599  << Arg->getSourceRange();
4600 
4601  // If the string is the name of a register then we cannot check that it is
4602  // valid here but if the string is of one the forms described in ACLE then we
4603  // can check that the supplied fields are integers and within the valid
4604  // ranges.
4605  if (Fields.size() > 1) {
4606  bool FiveFields = Fields.size() == 5;
4607 
4608  bool ValidString = true;
4609  if (IsARMBuiltin) {
4610  ValidString &= Fields[0].startswith_lower("cp") ||
4611  Fields[0].startswith_lower("p");
4612  if (ValidString)
4613  Fields[0] =
4614  Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4615 
4616  ValidString &= Fields[2].startswith_lower("c");
4617  if (ValidString)
4618  Fields[2] = Fields[2].drop_front(1);
4619 
4620  if (FiveFields) {
4621  ValidString &= Fields[3].startswith_lower("c");
4622  if (ValidString)
4623  Fields[3] = Fields[3].drop_front(1);
4624  }
4625  }
4626 
4627  SmallVector<int, 5> Ranges;
4628  if (FiveFields)
4629  Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4630  else
4631  Ranges.append({15, 7, 15});
4632 
4633  for (unsigned i=0; i<Fields.size(); ++i) {
4634  int IntField;
4635  ValidString &= !Fields[i].getAsInteger(10, IntField);
4636  ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4637  }
4638 
4639  if (!ValidString)
4640  return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4641  << Arg->getSourceRange();
4642  } else if (IsAArch64Builtin && Fields.size() == 1) {
4643  // If the register name is one of those that appear in the condition below
4644  // and the special register builtin being used is one of the write builtins,
4645  // then we require that the argument provided for writing to the register
4646  // is an integer constant expression. This is because it will be lowered to
4647  // an MSR (immediate) instruction, so we need to know the immediate at
4648  // compile time.
4649  if (TheCall->getNumArgs() != 2)
4650  return false;
4651 
4652  std::string RegLower = Reg.lower();
4653  if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4654  RegLower != "pan" && RegLower != "uao")
4655  return false;
4656 
4657  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4658  }
4659 
4660  return false;
4661 }
4662 
4663 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4664 /// This checks that the target supports __builtin_longjmp and
4665 /// that val is a constant 1.
4666 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4667  if (!Context.getTargetInfo().hasSjLjLowering())
4668  return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4669  << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4670 
4671  Expr *Arg = TheCall->getArg(1);
4672  llvm::APSInt Result;
4673 
4674  // TODO: This is less than ideal. Overload this to take a value.
4675  if (SemaBuiltinConstantArg(TheCall, 1, Result))
4676  return true;
4677 
4678  if (Result != 1)
4679  return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4680  << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4681 
4682  return false;
4683 }
4684 
4685 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4686 /// This checks that the target supports __builtin_setjmp.
4687 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4688  if (!Context.getTargetInfo().hasSjLjLowering())
4689  return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4690  << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4691  return false;
4692 }
4693 
4694 namespace {
4695 
4696 class UncoveredArgHandler {
4697  enum { Unknown = -1, AllCovered = -2 };
4698 
4699  signed FirstUncoveredArg = Unknown;
4700  SmallVector<const Expr *, 4> DiagnosticExprs;
4701 
4702 public:
4703  UncoveredArgHandler() = default;
4704 
4705  bool hasUncoveredArg() const {
4706  return (FirstUncoveredArg >= 0);
4707  }
4708 
4709  unsigned getUncoveredArg() const {
4710  assert(hasUncoveredArg() && "no uncovered argument");
4711  return FirstUncoveredArg;
4712  }
4713 
4714  void setAllCovered() {
4715  // A string has been found with all arguments covered, so clear out
4716  // the diagnostics.
4717  DiagnosticExprs.clear();
4718  FirstUncoveredArg = AllCovered;
4719  }
4720 
4721  void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4722  assert(NewFirstUncoveredArg >= 0 && "Outside range");
4723 
4724  // Don't update if a previous string covers all arguments.
4725  if (FirstUncoveredArg == AllCovered)
4726  return;
4727 
4728  // UncoveredArgHandler tracks the highest uncovered argument index
4729  // and with it all the strings that match this index.
4730  if (NewFirstUncoveredArg == FirstUncoveredArg)
4731  DiagnosticExprs.push_back(StrExpr);
4732  else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4733  DiagnosticExprs.clear();
4734  DiagnosticExprs.push_back(StrExpr);
4735  FirstUncoveredArg = NewFirstUncoveredArg;
4736  }
4737  }
4738 
4739  void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4740 };
4741 
4743  SLCT_NotALiteral,
4744  SLCT_UncheckedLiteral,
4745  SLCT_CheckedLiteral
4746 };
4747 
4748 } // namespace
4749 
4750 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4751  BinaryOperatorKind BinOpKind,
4752  bool AddendIsRight) {
4753  unsigned BitWidth = Offset.getBitWidth();
4754  unsigned AddendBitWidth = Addend.getBitWidth();
4755  // There might be negative interim results.
4756  if (Addend.isUnsigned()) {
4757  Addend = Addend.zext(++AddendBitWidth);
4758  Addend.setIsSigned(true);
4759  }
4760  // Adjust the bit width of the APSInts.
4761  if (AddendBitWidth > BitWidth) {
4762  Offset = Offset.sext(AddendBitWidth);
4763  BitWidth = AddendBitWidth;
4764  } else if (BitWidth > AddendBitWidth) {
4765  Addend = Addend.sext(BitWidth);
4766  }
4767 
4768  bool Ov = false;
4769  llvm::APSInt ResOffset = Offset;
4770  if (BinOpKind == BO_Add)
4771  ResOffset = Offset.sadd_ov(Addend, Ov);
4772  else {
4773  assert(AddendIsRight && BinOpKind == BO_Sub &&
4774  "operator must be add or sub with addend on the right");
4775  ResOffset = Offset.ssub_ov(Addend, Ov);
4776  }
4777 
4778  // We add an offset to a pointer here so we should support an offset as big as
4779  // possible.
4780  if (Ov) {
4781  assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4782  "index (intermediate) result too big");
4783  Offset = Offset.sext(2 * BitWidth);
4784  sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4785  return;
4786  }
4787 
4788  Offset = ResOffset;
4789 }
4790 
4791 namespace {
4792 
4793 // This is a wrapper class around StringLiteral to support offsetted string
4794 // literals as format strings. It takes the offset into account when returning
4795 // the string and its length or the source locations to display notes correctly.
4796 class FormatStringLiteral {
4797  const StringLiteral *FExpr;
4798  int64_t Offset;
4799 
4800  public:
4801  FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4802  : FExpr(fexpr), Offset(Offset) {}
4803 
4804  StringRef getString() const {
4805  return FExpr->getString().drop_front(Offset);
4806  }
4807 
4808  unsigned getByteLength() const {
4809  return FExpr->getByteLength() - getCharByteWidth() * Offset;
4810  }
4811 
4812  unsigned getLength() const { return FExpr->getLength() - Offset; }
4813  unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4814 
4815  StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4816 
4817  QualType getType() const { return FExpr->getType(); }
4818 
4819  bool isAscii() const { return FExpr->isAscii(); }
4820  bool isWide() const { return FExpr->isWide(); }
4821  bool isUTF8() const { return FExpr->isUTF8(); }
4822  bool isUTF16() const { return FExpr->isUTF16(); }
4823  bool isUTF32() const { return FExpr->isUTF32(); }
4824  bool isPascal() const { return FExpr->isPascal(); }
4825 
4826  SourceLocation getLocationOfByte(
4827  unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4828  const TargetInfo &Target, unsigned *StartToken = nullptr,
4829  unsigned *StartTokenByteOffset = nullptr) const {
4830  return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4831  StartToken, StartTokenByteOffset);
4832  }
4833 
4834  SourceLocation getLocStart() const LLVM_READONLY {
4835  return FExpr->getLocStart().getLocWithOffset(Offset);
4836  }
4837 
4838  SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4839 };
4840 
4841 } // namespace
4842 
4843 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4844  const Expr *OrigFormatExpr,
4845  ArrayRef<const Expr *> Args,
4846  bool HasVAListArg, unsigned format_idx,
4847  unsigned firstDataArg,
4849  bool inFunctionCall,
4850  Sema::VariadicCallType CallType,
4851  llvm::SmallBitVector &CheckedVarArgs,
4852  UncoveredArgHandler &UncoveredArg);
4853 
4854 // Determine if an expression is a string literal or constant string.
4855 // If this function returns false on the arguments to a function expecting a
4856 // format string, we will usually need to emit a warning.
4857 // True string literals are then checked by CheckFormatString.
4859 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4860  bool HasVAListArg, unsigned format_idx,
4861  unsigned firstDataArg, Sema::FormatStringType Type,
4862  Sema::VariadicCallType CallType, bool InFunctionCall,
4863  llvm::SmallBitVector &CheckedVarArgs,
4864  UncoveredArgHandler &UncoveredArg,
4865  llvm::APSInt Offset) {
4866  tryAgain:
4867  assert(Offset.isSigned() && "invalid offset");
4868 
4869  if (E->isTypeDependent() || E->isValueDependent())
4870  return SLCT_NotALiteral;
4871 
4872  E = E->IgnoreParenCasts();
4873 
4875  // Technically -Wformat-nonliteral does not warn about this case.
4876  // The behavior of printf and friends in this case is implementation
4877  // dependent. Ideally if the format string cannot be null then
4878  // it should have a 'nonnull' attribute in the function prototype.
4879  return SLCT_UncheckedLiteral;
4880 
4881  switch (E->getStmtClass()) {
4882  case Stmt::BinaryConditionalOperatorClass:
4883  case Stmt::ConditionalOperatorClass: {
4884  // The expression is a literal if both sub-expressions were, and it was
4885  // completely checked only if both sub-expressions were checked.
4886  const AbstractConditionalOperator *C =
4887  cast<AbstractConditionalOperator>(E);
4888 
4889  // Determine whether it is necessary to check both sub-expressions, for
4890  // example, because the condition expression is a constant that can be
4891  // evaluated at compile time.
4892  bool CheckLeft = true, CheckRight = true;
4893 
4894  bool Cond;
4895  if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4896  if (Cond)
4897  CheckRight = false;
4898  else
4899  CheckLeft = false;
4900  }
4901 
4902  // We need to maintain the offsets for the right and the left hand side
4903  // separately to check if every possible indexed expression is a valid
4904  // string literal. They might have different offsets for different string
4905  // literals in the end.
4907  if (!CheckLeft)
4908  Left = SLCT_UncheckedLiteral;
4909  else {
4910  Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4911  HasVAListArg, format_idx, firstDataArg,
4912  Type, CallType, InFunctionCall,
4913  CheckedVarArgs, UncoveredArg, Offset);
4914  if (Left == SLCT_NotALiteral || !CheckRight) {
4915  return Left;
4916  }
4917  }
4918 
4919  StringLiteralCheckType Right =
4920  checkFormatStringExpr(S, C->getFalseExpr(), Args,
4921  HasVAListArg, format_idx, firstDataArg,
4922  Type, CallType, InFunctionCall, CheckedVarArgs,
4923  UncoveredArg, Offset);
4924 
4925  return (CheckLeft && Left < Right) ? Left : Right;
4926  }
4927 
4928  case Stmt::ImplicitCastExprClass:
4929  E = cast<ImplicitCastExpr>(E)->getSubExpr();
4930  goto tryAgain;
4931 
4932  case Stmt::OpaqueValueExprClass:
4933  if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4934  E = src;
4935  goto tryAgain;
4936  }
4937  return SLCT_NotALiteral;
4938 
4939  case Stmt::PredefinedExprClass:
4940  // While __func__, etc., are technically not string literals, they
4941  // cannot contain format specifiers and thus are not a security
4942  // liability.
4943  return SLCT_UncheckedLiteral;
4944 
4945  case Stmt::DeclRefExprClass: {
4946  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4947 
4948  // As an exception, do not flag errors for variables binding to
4949  // const string literals.
4950  if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4951  bool isConstant = false;
4952  QualType T = DR->getType();
4953 
4954  if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4955  isConstant = AT->getElementType().isConstant(S.Context);
4956  } else if (const PointerType *PT = T->getAs<PointerType>()) {
4957  isConstant = T.isConstant(S.Context) &&
4958  PT->getPointeeType().isConstant(S.Context);
4959  } else if (T->isObjCObjectPointerType()) {
4960  // In ObjC, there is usually no "const ObjectPointer" type,
4961  // so don't check if the pointee type is constant.
4962  isConstant = T.isConstant(S.Context);
4963  }
4964 
4965  if (isConstant) {
4966  if (const Expr *Init = VD->getAnyInitializer()) {
4967  // Look through initializers like const char c[] = { "foo" }
4968  if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4969  if (InitList->isStringLiteralInit())
4970  Init = InitList->getInit(0)->IgnoreParenImpCasts();
4971  }
4972  return checkFormatStringExpr(S, Init, Args,
4973  HasVAListArg, format_idx,
4974  firstDataArg, Type, CallType,
4975  /*InFunctionCall*/ false, CheckedVarArgs,
4976  UncoveredArg, Offset);
4977  }
4978  }
4979 
4980  // For vprintf* functions (i.e., HasVAListArg==true), we add a
4981  // special check to see if the format string is a function parameter
4982  // of the function calling the printf function. If the function
4983  // has an attribute indicating it is a printf-like function, then we
4984  // should suppress warnings concerning non-literals being used in a call
4985  // to a vprintf function. For example:
4986  //
4987  // void
4988  // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4989  // va_list ap;
4990  // va_start(ap, fmt);
4991  // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4992  // ...
4993  // }
4994  if (HasVAListArg) {
4995  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4996  if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4997  int PVIndex = PV->getFunctionScopeIndex() + 1;
4998  for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4999  // adjust for implicit parameter
5000  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5001  if (MD->isInstance())
5002  ++PVIndex;
5003  // We also check if the formats are compatible.
5004  // We can't pass a 'scanf' string to a 'printf' function.
5005  if (PVIndex == PVFormat->getFormatIdx() &&
5006  Type == S.GetFormatStringType(PVFormat))
5007  return SLCT_UncheckedLiteral;
5008  }
5009  }
5010  }
5011  }
5012  }
5013 
5014  return SLCT_NotALiteral;
5015  }
5016 
5017  case Stmt::CallExprClass:
5018  case Stmt::CXXMemberCallExprClass: {
5019  const CallExpr *CE = cast<CallExpr>(E);
5020  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5021  if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5022  unsigned ArgIndex = FA->getFormatIdx();
5023  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5024  if (MD->isInstance())
5025  --ArgIndex;
5026  const Expr *Arg = CE->getArg(ArgIndex - 1);
5027 
5028  return checkFormatStringExpr(S, Arg, Args,
5029  HasVAListArg, format_idx, firstDataArg,
5030  Type, CallType, InFunctionCall,
5031  CheckedVarArgs, UncoveredArg, Offset);
5032  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5033  unsigned BuiltinID = FD->getBuiltinID();
5034  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5035  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5036  const Expr *Arg = CE->getArg(0);
5037  return checkFormatStringExpr(S, Arg, Args,
5038  HasVAListArg, format_idx,
5039  firstDataArg, Type, CallType,
5040  InFunctionCall, CheckedVarArgs,
5041  UncoveredArg, Offset);
5042  }
5043  }
5044  }
5045 
5046  return SLCT_NotALiteral;
5047  }
5048  case Stmt::ObjCMessageExprClass: {
5049  const auto *ME = cast<ObjCMessageExpr>(E);
5050  if (const auto *ND = ME->getMethodDecl()) {
5051  if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5052  unsigned ArgIndex = FA->getFormatIdx();
5053  const Expr *Arg = ME->getArg(ArgIndex - 1);
5054  return checkFormatStringExpr(
5055  S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5056  CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5057  }
5058  }
5059 
5060  return SLCT_NotALiteral;
5061  }
5062  case Stmt::ObjCStringLiteralClass:
5063  case Stmt::StringLiteralClass: {
5064  const StringLiteral *StrE = nullptr;
5065 
5066  if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5067  StrE = ObjCFExpr->getString();
5068  else
5069  StrE = cast<StringLiteral>(E);
5070 
5071  if (StrE) {
5072  if (Offset.isNegative() || Offset > StrE->getLength()) {
5073  // TODO: It would be better to have an explicit warning for out of
5074  // bounds literals.
5075  return SLCT_NotALiteral;
5076  }
5077  FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5078  CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5079  firstDataArg, Type, InFunctionCall, CallType,
5080  CheckedVarArgs, UncoveredArg);
5081  return SLCT_CheckedLiteral;
5082  }
5083 
5084  return SLCT_NotALiteral;
5085  }
5086  case Stmt::BinaryOperatorClass: {
5087  llvm::APSInt LResult;
5088  llvm::APSInt RResult;
5089 
5090  const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5091 
5092  // A string literal + an int offset is still a string literal.
5093  if (BinOp->isAdditiveOp()) {
5094  bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5095  bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5096 
5097  if (LIsInt != RIsInt) {
5098  BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5099 
5100  if (LIsInt) {
5101  if (BinOpKind == BO_Add) {
5102  sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5103  E = BinOp->getRHS();
5104  goto tryAgain;
5105  }
5106  } else {
5107  sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5108  E = BinOp->getLHS();
5109  goto tryAgain;
5110  }
5111  }
5112  }
5113 
5114  return SLCT_NotALiteral;
5115  }
5116  case Stmt::UnaryOperatorClass: {
5117  const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5118  auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5119  if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5120  llvm::APSInt IndexResult;
5121  if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5122  sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5123  E = ASE->getBase();
5124  goto tryAgain;
5125  }
5126  }
5127 
5128  return SLCT_NotALiteral;
5129  }
5130 
5131  default:
5132  return SLCT_NotALiteral;
5133  }
5134 }
5135 
5137  return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5138  .Case("scanf", FST_Scanf)
5139  .Cases("printf", "printf0", FST_Printf)
5140  .Cases("NSString", "CFString", FST_NSString)
5141  .Case("strftime", FST_Strftime)
5142  .Case("strfmon", FST_Strfmon)
5143  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5144  .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5145  .Case("os_trace", FST_OSLog)
5146  .Case("os_log", FST_OSLog)
5147  .Default(FST_Unknown);
5148 }
5149 
5150 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5151 /// functions) for correct use of format strings.
5152 /// Returns true if a format string has been fully checked.
5153 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5155  bool IsCXXMember,
5156  VariadicCallType CallType,
5157  SourceLocation Loc, SourceRange Range,
5158  llvm::SmallBitVector &CheckedVarArgs) {
5159  FormatStringInfo FSI;
5160  if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5161  return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5162  FSI.FirstDataArg, GetFormatStringType(Format),
5163  CallType, Loc, Range, CheckedVarArgs);
5164  return false;
5165 }
5166 
5167 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5168  bool HasVAListArg, unsigned format_idx,
5169  unsigned firstDataArg, FormatStringType Type,
5170  VariadicCallType CallType,
5171  SourceLocation Loc, SourceRange Range,
5172  llvm::SmallBitVector &CheckedVarArgs) {
5173  // CHECK: printf/scanf-like function is called with no format string.
5174  if (format_idx >= Args.size()) {
5175  Diag(Loc, diag::warn_missing_format_string) << Range;
5176  return false;
5177  }
5178 
5179  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5180 
5181  // CHECK: format string is not a string literal.
5182  //
5183  // Dynamically generated format strings are difficult to
5184  // automatically vet at compile time. Requiring that format strings
5185  // are string literals: (1) permits the checking of format strings by
5186  // the compiler and thereby (2) can practically remove the source of
5187  // many format string exploits.
5188 
5189  // Format string can be either ObjC string (e.g. @"%d") or
5190  // C string (e.g. "%d")
5191  // ObjC string uses the same format specifiers as C string, so we can use
5192  // the same format string checking logic for both ObjC and C strings.
5193  UncoveredArgHandler UncoveredArg;
5195  checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5196  format_idx, firstDataArg, Type, CallType,
5197  /*IsFunctionCall*/ true, CheckedVarArgs,
5198  UncoveredArg,
5199  /*no string offset*/ llvm::APSInt(64, false) = 0);
5200 
5201  // Generate a diagnostic where an uncovered argument is detected.
5202  if (UncoveredArg.hasUncoveredArg()) {
5203  unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5204  assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5205  UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5206  }
5207 
5208  if (CT != SLCT_NotALiteral)
5209  // Literal format string found, check done!
5210  return CT == SLCT_CheckedLiteral;
5211 
5212  // Strftime is particular as it always uses a single 'time' argument,
5213  // so it is safe to pass a non-literal string.
5214  if (Type == FST_Strftime)
5215  return false;
5216 
5217  // Do not emit diag when the string param is a macro expansion and the
5218  // format is either NSString or CFString. This is a hack to prevent
5219  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5220  // which are usually used in place of NS and CF string literals.
5221  SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5222  if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5223  return false;
5224 
5225  // If there are no arguments specified, warn with -Wformat-security, otherwise
5226  // warn only with -Wformat-nonliteral.
5227  if (Args.size() == firstDataArg) {
5228  Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5229  << OrigFormatExpr->getSourceRange();
5230  switch (Type) {
5231  default:
5232  break;
5233  case FST_Kprintf:
5234  case FST_FreeBSDKPrintf:
5235  case FST_Printf:
5236  Diag(FormatLoc, diag::note_format_security_fixit)
5237  << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5238  break;
5239  case FST_NSString:
5240  Diag(FormatLoc, diag::note_format_security_fixit)
5241  << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5242  break;
5243  }
5244  } else {
5245  Diag(FormatLoc, diag::warn_format_nonliteral)
5246  << OrigFormatExpr->getSourceRange();
5247  }
5248  return false;
5249 }
5250 
5251 namespace {
5252 
5253 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5254 protected:
5255  Sema &S;
5256  const FormatStringLiteral *FExpr;
5257  const Expr *OrigFormatExpr;
5258  const Sema::FormatStringType FSType;
5259  const unsigned FirstDataArg;
5260  const unsigned NumDataArgs;
5261  const char *Beg; // Start of format string.
5262  const bool HasVAListArg;
5264  unsigned FormatIdx;
5265  llvm::SmallBitVector CoveredArgs;
5266  bool usesPositionalArgs = false;
5267  bool atFirstArg = true;
5268  bool inFunctionCall;
5269  Sema::VariadicCallType CallType;
5270  llvm::SmallBitVector &CheckedVarArgs;
5271  UncoveredArgHandler &UncoveredArg;
5272 
5273 public:
5274  CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5275  const Expr *origFormatExpr,
5276  const Sema::FormatStringType type, unsigned firstDataArg,
5277  unsigned numDataArgs, const char *beg, bool hasVAListArg,
5278  ArrayRef<const Expr *> Args, unsigned formatIdx,
5279  bool inFunctionCall, Sema::VariadicCallType callType,
5280  llvm::SmallBitVector &CheckedVarArgs,
5281  UncoveredArgHandler &UncoveredArg)
5282  : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5283  FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5284  HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5285  inFunctionCall(inFunctionCall), CallType(callType),
5286  CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5287  CoveredArgs.resize(numDataArgs);
5288  CoveredArgs.reset();
5289  }
5290 
5291  void DoneProcessing();
5292 
5293  void HandleIncompleteSpecifier(const char *startSpecifier,
5294  unsigned specifierLen) override;
5295 
5296  void HandleInvalidLengthModifier(
5299  const char *startSpecifier, unsigned specifierLen,
5300  unsigned DiagID);
5301 
5302  void HandleNonStandardLengthModifier(
5304  const char *startSpecifier, unsigned specifierLen);
5305 
5306  void HandleNonStandardConversionSpecifier(
5308  const char *startSpecifier, unsigned specifierLen);
5309 
5310  void HandlePosition(const char *startPos, unsigned posLen) override;
5311 
5312  void HandleInvalidPosition(const char *startSpecifier,
5313  unsigned specifierLen,
5315 
5316  void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5317 
5318  void HandleNullChar(const char *nullCharacter) override;
5319 
5320  template <typename Range>
5321  static void
5322  EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5323  const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5324  bool IsStringLocation, Range StringRange,
5325  ArrayRef<FixItHint> Fixit = None);
5326 
5327 protected:
5328  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5329  const char *startSpec,
5330  unsigned specifierLen,
5331  const char *csStart, unsigned csLen);
5332 
5333  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5334  const char *startSpec,
5335  unsigned specifierLen);
5336 
5337  SourceRange getFormatStringRange();
5338  CharSourceRange getSpecifierRange(const char *startSpecifier,
5339  unsigned specifierLen);
5340  SourceLocation getLocationOfByte(const char *x);
5341 
5342  const Expr *getDataArg(unsigned i) const;
5343 
5344  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5346  const char *startSpecifier, unsigned specifierLen,
5347  unsigned argIndex);
5348 
5349  template <typename Range>
5350  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5351  bool IsStringLocation, Range StringRange,
5352  ArrayRef<FixItHint> Fixit = None);
5353 };
5354 
5355 } // namespace
5356 
5357 SourceRange CheckFormatHandler::getFormatStringRange() {
5358  return OrigFormatExpr->getSourceRange();
5359 }
5360 
5361 CharSourceRange CheckFormatHandler::
5362 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5363  SourceLocation Start = getLocationOfByte(startSpecifier);
5364  SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5365 
5366  // Advance the end SourceLocation by one due to half-open ranges.
5367  End = End.getLocWithOffset(1);
5368 
5369  return CharSourceRange::getCharRange(Start, End);
5370 }
5371 
5372 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5373  return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5374  S.getLangOpts(), S.Context.getTargetInfo());
5375 }
5376 
5377 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5378  unsigned specifierLen){
5379  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5380  getLocationOfByte(startSpecifier),
5381  /*IsStringLocation*/true,
5382  getSpecifierRange(startSpecifier, specifierLen));
5383 }
5384 
5385 void CheckFormatHandler::HandleInvalidLengthModifier(
5388  const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5389  using namespace analyze_format_string;
5390 
5391  const LengthModifier &LM = FS.getLengthModifier();
5392  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5393 
5394  // See if we know how to fix this length modifier.
5396  if (FixedLM) {
5397  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5398  getLocationOfByte(LM.getStart()),
5399  /*IsStringLocation*/true,
5400  getSpecifierRange(startSpecifier, specifierLen));
5401 
5402  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5403  << FixedLM->toString()
5404  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5405 
5406  } else {
5407  FixItHint Hint;
5408  if (DiagID == diag::warn_format_nonsensical_length)
5409  Hint = FixItHint::CreateRemoval(LMRange);
5410 
5411  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5412  getLocationOfByte(LM.getStart()),
5413  /*IsStringLocation*/true,
5414  getSpecifierRange(startSpecifier, specifierLen),
5415  Hint);
5416  }
5417 }
5418 
5419 void CheckFormatHandler::HandleNonStandardLengthModifier(
5421  const char *startSpecifier, unsigned specifierLen) {
5422  using namespace analyze_format_string;
5423 
5424  const LengthModifier &LM = FS.getLengthModifier();
5425  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5426 
5427  // See if we know how to fix this length modifier.
5429  if (FixedLM) {
5430  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5431  << LM.toString() << 0,
5432  getLocationOfByte(LM.getStart()),
5433  /*IsStringLocation*/true,
5434  getSpecifierRange(startSpecifier, specifierLen));
5435 
5436  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5437  << FixedLM->toString()
5438  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5439 
5440  } else {
5441  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5442  << LM.toString() << 0,
5443  getLocationOfByte(LM.getStart()),
5444  /*IsStringLocation*/true,
5445  getSpecifierRange(startSpecifier, specifierLen));
5446  }
5447 }
5448 
5449 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5451  const char *startSpecifier, unsigned specifierLen) {
5452  using namespace analyze_format_string;
5453 
5454  // See if we know how to fix this conversion specifier.
5456  if (FixedCS) {
5457  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5458  << CS.toString() << /*conversion specifier*/1,
5459  getLocationOfByte(CS.getStart()),
5460  /*IsStringLocation*/true,
5461  getSpecifierRange(startSpecifier, specifierLen));
5462 
5463  CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5464  S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5465  << FixedCS->toString()
5466  << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5467  } else {
5468  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5469  << CS.toString() << /*conversion specifier*/1,
5470  getLocationOfByte(CS.getStart()),
5471  /*IsStringLocation*/true,
5472  getSpecifierRange(startSpecifier, specifierLen));
5473  }
5474 }
5475 
5476 void CheckFormatHandler::HandlePosition(const char *startPos,
5477  unsigned posLen) {
5478  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5479  getLocationOfByte(startPos),
5480  /*IsStringLocation*/true,
5481  getSpecifierRange(startPos, posLen));
5482 }
5483 
5484 void
5485 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5487  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5488  << (unsigned) p,
5489  getLocationOfByte(startPos), /*IsStringLocation*/true,
5490  getSpecifierRange(startPos, posLen));
5491 }
5492 
5493 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5494  unsigned posLen) {
5495  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5496  getLocationOfByte(startPos),
5497  /*IsStringLocation*/true,
5498  getSpecifierRange(startPos, posLen));
5499 }
5500 
5501 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5502  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5503  // The presence of a null character is likely an error.
5504  EmitFormatDiagnostic(
5505  S.PDiag(diag::warn_printf_format_string_contains_null_char),
5506  getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5507  getFormatStringRange());
5508  }
5509 }
5510 
5511 // Note that this may return NULL if there was an error parsing or building
5512 // one of the argument expressions.
5513 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5514  return Args[FirstDataArg + i];
5515 }
5516 
5517 void CheckFormatHandler::DoneProcessing() {
5518  // Does the number of data arguments exceed the number of
5519  // format conversions in the format string?
5520  if (!HasVAListArg) {
5521  // Find any arguments that weren't covered.
5522  CoveredArgs.flip();
5523  signed notCoveredArg = CoveredArgs.find_first();
5524  if (notCoveredArg >= 0) {
5525  assert((unsigned)notCoveredArg < NumDataArgs);
5526  UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5527  } else {
5528  UncoveredArg.setAllCovered();
5529  }
5530  }
5531 }
5532 
5533 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5534  const Expr *ArgExpr) {
5535  assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5536  "Invalid state");
5537 
5538  if (!ArgExpr)
5539  return;
5540 
5541  SourceLocation Loc = ArgExpr->getLocStart();
5542 
5543  if (S.getSourceManager().isInSystemMacro(Loc))
5544  return;
5545 
5546  PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5547  for (auto E : DiagnosticExprs)
5548  PDiag << E->getSourceRange();
5549 
5550  CheckFormatHandler::EmitFormatDiagnostic(
5551  S, IsFunctionCall, DiagnosticExprs[0],
5552  PDiag, Loc, /*IsStringLocation*/false,
5553  DiagnosticExprs[0]->getSourceRange());
5554 }
5555 
5556 bool
5557 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5558  SourceLocation Loc,
5559  const char *startSpec,
5560  unsigned specifierLen,
5561  const char *csStart,
5562  unsigned csLen) {
5563  bool keepGoing = true;
5564  if (argIndex < NumDataArgs) {
5565  // Consider the argument coverered, even though the specifier doesn't
5566  // make sense.
5567  CoveredArgs.set(argIndex);
5568  }
5569  else {
5570  // If argIndex exceeds the number of data arguments we
5571  // don't issue a warning because that is just a cascade of warnings (and
5572  // they may have intended '%%' anyway). We don't want to continue processing
5573  // the format string after this point, however, as we will like just get
5574  // gibberish when trying to match arguments.
5575  keepGoing = false;
5576  }
5577 
5578  StringRef Specifier(csStart, csLen);
5579 
5580  // If the specifier in non-printable, it could be the first byte of a UTF-8
5581  // sequence. In that case, print the UTF-8 code point. If not, print the byte
5582  // hex value.
5583  std::string CodePointStr;
5584  if (!llvm::sys::locale::isPrint(*csStart)) {
5585  llvm::UTF32 CodePoint;
5586  const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5587  const llvm::UTF8 *E =
5588  reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5589  llvm::ConversionResult Result =
5590  llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5591 
5592  if (Result != llvm::conversionOK) {
5593  unsigned char FirstChar = *csStart;
5594  CodePoint = (llvm::UTF32)FirstChar;
5595  }
5596 
5597  llvm::raw_string_ostream OS(CodePointStr);
5598  if (CodePoint < 256)
5599  OS << "\\x" << llvm::format("%02x", CodePoint);
5600  else if (CodePoint <= 0xFFFF)
5601  OS << "\\u" << llvm::format("%04x", CodePoint);
5602  else
5603  OS << "\\U" << llvm::format("%08x", CodePoint);
5604  OS.flush();
5605  Specifier = CodePointStr;
5606  }
5607 
5608  EmitFormatDiagnostic(
5609  S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5610  /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5611 
5612  return keepGoing;
5613 }
5614 
5615 void
5616 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5617  const char *startSpec,
5618  unsigned specifierLen) {
5619  EmitFormatDiagnostic(
5620  S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5621  Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5622 }
5623 
5624 bool
5625 CheckFormatHandler::CheckNumArgs(
5628  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5629 
5630  if (argIndex >= NumDataArgs) {
5632  ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5633  << (argIndex+1) << NumDataArgs)
5634  : S.PDiag(diag::warn_printf_insufficient_data_args);
5635  EmitFormatDiagnostic(
5636  PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5637  getSpecifierRange(startSpecifier, specifierLen));
5638 
5639  // Since more arguments than conversion tokens are given, by extension
5640  // all arguments are covered, so mark this as so.
5641  UncoveredArg.setAllCovered();
5642  return false;
5643  }
5644  return true;
5645 }
5646 
5647 template<typename Range>
5648 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5649  SourceLocation Loc,
5650  bool IsStringLocation,
5651  Range StringRange,
5653  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5654  Loc, IsStringLocation, StringRange, FixIt);
5655 }
5656 
5657 /// \brief If the format string is not within the funcion call, emit a note
5658 /// so that the function call and string are in diagnostic messages.
5659 ///
5660 /// \param InFunctionCall if true, the format string is within the function
5661 /// call and only one diagnostic message will be produced. Otherwise, an
5662 /// extra note will be emitted pointing to location of the format string.
5663 ///
5664 /// \param ArgumentExpr the expression that is passed as the format string
5665 /// argument in the function call. Used for getting locations when two
5666 /// diagnostics are emitted.
5667 ///
5668 /// \param PDiag the callee should already have provided any strings for the
5669 /// diagnostic message. This function only adds locations and fixits
5670 /// to diagnostics.
5671 ///
5672 /// \param Loc primary location for diagnostic. If two diagnostics are
5673 /// required, one will be at Loc and a new SourceLocation will be created for
5674 /// the other one.
5675 ///
5676 /// \param IsStringLocation if true, Loc points to the format string should be
5677 /// used for the note. Otherwise, Loc points to the argument list and will
5678 /// be used with PDiag.
5679 ///
5680 /// \param StringRange some or all of the string to highlight. This is
5681 /// templated so it can accept either a CharSourceRange or a SourceRange.
5682 ///
5683 /// \param FixIt optional fix it hint for the format string.
5684 template <typename Range>
5685 void CheckFormatHandler::EmitFormatDiagnostic(
5686  Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5687  const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5688  Range StringRange, ArrayRef<FixItHint> FixIt) {
5689  if (InFunctionCall) {
5690  const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5691  D << StringRange;
5692  D << FixIt;
5693  } else {
5694  S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5695  << ArgumentExpr->getSourceRange();
5696 
5697  const Sema::SemaDiagnosticBuilder &Note =
5698  S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5699  diag::note_format_string_defined);
5700 
5701  Note << StringRange;
5702  Note << FixIt;
5703  }
5704 }
5705 
5706 //===--- CHECK: Printf format string checking ------------------------------===//
5707 
5708 namespace {
5709 
5710 class CheckPrintfHandler : public CheckFormatHandler {
5711 public:
5712  CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5713  const Expr *origFormatExpr,
5714  const Sema::FormatStringType type, unsigned firstDataArg,
5715  unsigned numDataArgs, bool isObjC, const char *beg,
5716  bool hasVAListArg, ArrayRef<const Expr *> Args,
5717  unsigned formatIdx, bool inFunctionCall,
5718  Sema::VariadicCallType CallType,
5719  llvm::SmallBitVector &CheckedVarArgs,
5720  UncoveredArgHandler &UncoveredArg)
5721  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5722  numDataArgs, beg, hasVAListArg, Args, formatIdx,
5723  inFunctionCall, CallType, CheckedVarArgs,
5724  UncoveredArg) {}
5725 
5726  bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5727 
5728  /// Returns true if '%@' specifiers are allowed in the format string.
5729  bool allowsObjCArg() const {
5730  return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5731  FSType == Sema::FST_OSTrace;
5732  }
5733 
5734  bool HandleInvalidPrintfConversionSpecifier(
5736  const char *startSpecifier,
5737  unsigned specifierLen) override;
5738 
5739  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5740  const char *startSpecifier,
5741  unsigned specifierLen) override;
5742  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5743  const char *StartSpecifier,
5744  unsigned SpecifierLen,
5745  const Expr *E);
5746 
5747  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5748  const char *startSpecifier, unsigned specifierLen);
5749  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5750  const analyze_printf::OptionalAmount &Amt,
5751  unsigned type,
5752  const char *startSpecifier, unsigned specifierLen);
5753  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5754  const analyze_printf::OptionalFlag &flag,
5755  const char *startSpecifier, unsigned specifierLen);
5756  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5757  const analyze_printf::OptionalFlag &ignoredFlag,
5758  const analyze_printf::OptionalFlag &flag,
5759  const char *startSpecifier, unsigned specifierLen);
5760  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5761  const Expr *E);
5762 
5763  void HandleEmptyObjCModifierFlag(const char *startFlag,
5764  unsigned flagLen) override;
5765 
5766  void HandleInvalidObjCModifierFlag(const char *startFlag,
5767  unsigned flagLen) override;
5768 
5769  void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5770  const char *flagsEnd,
5771  const char *conversionPosition)
5772  override;
5773 };
5774 
5775 } // namespace
5776 
5777 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5779  const char *startSpecifier,
5780  unsigned specifierLen) {
5783 
5784  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5785  getLocationOfByte(CS.getStart()),
5786  startSpecifier, specifierLen,
5787  CS.getStart(), CS.getLength());
5788 }
5789 
5790 bool CheckPrintfHandler::HandleAmount(
5792  unsigned k, const char *startSpecifier,
5793  unsigned specifierLen) {
5794  if (Amt.hasDataArgument()) {
5795  if (!HasVAListArg) {
5796  unsigned argIndex = Amt.getArgIndex();
5797  if (argIndex >= NumDataArgs) {
5798  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5799  << k,
5800  getLocationOfByte(Amt.getStart()),
5801  /*IsStringLocation*/true,
5802  getSpecifierRange(startSpecifier, specifierLen));
5803  // Don't do any more checking. We will just emit
5804  // spurious errors.
5805  return false;
5806  }
5807 
5808  // Type check the data argument. It should be an 'int'.
5809  // Although not in conformance with C99, we also allow the argument to be
5810  // an 'unsigned int' as that is a reasonably safe case. GCC also
5811  // doesn't emit a warning for that case.
5812  CoveredArgs.set(argIn