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