Bug Summary

File:tools/clang/lib/Sema/SemaChecking.cpp
Warning:line 112, column 5
Potential memory leak

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp

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"
19#include "clang/AST/EvaluatedExprVisitor.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"
26#include "clang/Analysis/Analyses/FormatString.h"
27#include "clang/Basic/CharInfo.h"
28#include "clang/Basic/SyncScope.h"
29#include "clang/Basic/TargetBuiltins.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
36#include "clang/Sema/SemaInternal.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
45using namespace clang;
46using namespace sema;
47
48SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
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.
56static 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.
76static 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
102static 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.
126static 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
140static 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
173static 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
201static 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
264static 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
286static 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.
292static 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() !=
305 LangAS::opencl_local) {
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
325static 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
334static 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.
363static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
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.
378static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
379 const QualType &IntType);
380
381static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
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.
392static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
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, ...)
440static 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,
525 Expr::NPC_ValueDependentIsNotNull) &&
526 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
527 S.Diag(TheCall->getArg(4)->getLocStart(),
528 diag::err_opencl_builtin_expected_type)
529 << TheCall->getDirectCallee()
530 << S.Context.getPointerType(S.Context.OCLClkEventTy);
531 return true;
532 }
533
534 // Sixth argument is always passed as a pointer to clk_event_t.
535 if (!Arg5->isNullPointerConstant(S.Context,
536 Expr::NPC_ValueDependentIsNotNull) &&
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()
542 << S.Context.getPointerType(S.Context.OCLClkEventTy);
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.
559static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
560 return D->getAttr<OpenCLAccessAttr>();
561}
562
563/// Returns true if pipe element type is different from the pointer.
564static 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.
614static 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.
637static 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.
692static 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.
721static 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.
744static 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.
762static 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")::llvm::llvm_unreachable_internal("Invalid builtin function",
"/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 791)
;
792 }
793 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
794 RT.getUnqualifiedType(), Qual)));
795
796 return false;
797}
798
799ExprResult
800Sema::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;
806 ASTContext::GetBuiltinTypeError Error;
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 &&((TheCall->getNumArgs() == 1 && "Wrong # arguments to builtin CFStringMakeConstantString"
) ? static_cast<void> (0) : __assert_fail ("TheCall->getNumArgs() == 1 && \"Wrong # arguments to builtin CFStringMakeConstantString\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 825, __PRETTY_FUNCTION__))
825 "Wrong # arguments to builtin CFStringMakeConstantString")((TheCall->getNumArgs() == 1 && "Wrong # arguments to builtin CFStringMakeConstantString"
) ? static_cast<void> (0) : __assert_fail ("TheCall->getNumArgs() == 1 && \"Wrong # arguments to builtin CFStringMakeConstantString\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 825, __PRETTY_FUNCTION__))
;
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.
1226static 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;
1241 case NeonTypeFlags::Poly128:
1242 return shift ? 127 : (1 << IsQuad) - 1;
1243 case NeonTypeFlags::Float16:
1244 assert(!shift && "cannot shift float types!")((!shift && "cannot shift float types!") ? static_cast
<void> (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1244, __PRETTY_FUNCTION__))
;
1245 return (4 << IsQuad) - 1;
1246 case NeonTypeFlags::Float32:
1247 assert(!shift && "cannot shift float types!")((!shift && "cannot shift float types!") ? static_cast
<void> (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1247, __PRETTY_FUNCTION__))
;
1248 return (2 << IsQuad) - 1;
1249 case NeonTypeFlags::Float64:
1250 assert(!shift && "cannot shift float types!")((!shift && "cannot shift float types!") ? static_cast
<void> (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1250, __PRETTY_FUNCTION__))
;
1251 return (1 << IsQuad) - 1;
1252 }
1253 llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1253)
;
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.
1259static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
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;
1283 case NeonTypeFlags::Poly128:
1284 break;
1285 case NeonTypeFlags::Float16:
1286 return Context.HalfTy;
1287 case NeonTypeFlags::Float32:
1288 return Context.FloatTy;
1289 case NeonTypeFlags::Float64:
1290 return Context.DoubleTy;
1291 }
1292 llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1292)
;
1293}
1294
1295bool 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 =
1332 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
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
1361bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1362 unsigned MaxWidth) {
1363 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
1364 BuiltinID == ARM::BI__builtin_arm_ldaex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
1365 BuiltinID == ARM::BI__builtin_arm_strex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
1366 BuiltinID == ARM::BI__builtin_arm_stlex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
1367 BuiltinID == AArch64::BI__builtin_arm_ldrex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
1368 BuiltinID == AArch64::BI__builtin_arm_ldaex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
1369 BuiltinID == AArch64::BI__builtin_arm_strex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
1370 BuiltinID == AArch64::BI__builtin_arm_stlex) &&(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
1371 "unexpected ARM builtin")(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1371, __PRETTY_FUNCTION__))
;
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")((MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"
) ? static_cast<void> (0) : __assert_fail ("MaxWidth == 64 && \"Diagnostic unexpectedly inaccurate\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 1437, __PRETTY_FUNCTION__))
;
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:
1445 case Qualifiers::OCL_ExplicitNone:
1446 // okay
1447 break;
1448
1449 case Qualifiers::OCL_Weak:
1450 case Qualifiers::OCL_Strong:
1451 case Qualifiers::OCL_Autoreleasing:
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);
1464 InitializedEntity Entity = InitializedEntity::InitializeParameter(
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
1477bool 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
1522bool 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.
1573bool 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
1744bool 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
1790bool 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.
1856static 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.
1876static 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.
1894bool 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.
2100bool 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
2202bool 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_vcvtps2ph_mask:
2316 case X86::BI__builtin_ia32_vcvtps2ph256:
2317 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2318 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2319 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2320 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2321 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2322 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2323 case X86::BI__builtin_ia32_rndscaleps_mask:
2324 case X86::BI__builtin_ia32_rndscalepd_mask:
2325 case X86::BI__builtin_ia32_reducepd128_mask:
2326 case X86::BI__builtin_ia32_reducepd256_mask:
2327 case X86::BI__builtin_ia32_reducepd512_mask:
2328 case X86::BI__builtin_ia32_reduceps128_mask:
2329 case X86::BI__builtin_ia32_reduceps256_mask:
2330 case X86::BI__builtin_ia32_reduceps512_mask:
2331 case X86::BI__builtin_ia32_prold512_mask:
2332 case X86::BI__builtin_ia32_prolq512_mask:
2333 case X86::BI__builtin_ia32_prold128_mask:
2334 case X86::BI__builtin_ia32_prold256_mask:
2335 case X86::BI__builtin_ia32_prolq128_mask:
2336 case X86::BI__builtin_ia32_prolq256_mask:
2337 case X86::BI__builtin_ia32_prord128_mask:
2338 case X86::BI__builtin_ia32_prord256_mask:
2339 case X86::BI__builtin_ia32_prorq128_mask:
2340 case X86::BI__builtin_ia32_prorq256_mask:
2341 case X86::BI__builtin_ia32_fpclasspd128_mask:
2342 case X86::BI__builtin_ia32_fpclasspd256_mask:
2343 case X86::BI__builtin_ia32_fpclassps128_mask:
2344 case X86::BI__builtin_ia32_fpclassps256_mask:
2345 case X86::BI__builtin_ia32_fpclassps512_mask:
2346 case X86::BI__builtin_ia32_fpclasspd512_mask:
2347 case X86::BI__builtin_ia32_fpclasssd_mask:
2348 case X86::BI__builtin_ia32_fpclassss_mask:
2349 i = 1; l = 0; u = 255;
2350 break;
2351 case X86::BI__builtin_ia32_palignr:
2352 case X86::BI__builtin_ia32_insertps128:
2353 case X86::BI__builtin_ia32_dpps:
2354 case X86::BI__builtin_ia32_dppd:
2355 case X86::BI__builtin_ia32_dpps256:
2356 case X86::BI__builtin_ia32_mpsadbw128:
2357 case X86::BI__builtin_ia32_mpsadbw256:
2358 case X86::BI__builtin_ia32_pcmpistrm128:
2359 case X86::BI__builtin_ia32_pcmpistri128:
2360 case X86::BI__builtin_ia32_pcmpistria128:
2361 case X86::BI__builtin_ia32_pcmpistric128:
2362 case X86::BI__builtin_ia32_pcmpistrio128:
2363 case X86::BI__builtin_ia32_pcmpistris128:
2364 case X86::BI__builtin_ia32_pcmpistriz128:
2365 case X86::BI__builtin_ia32_pclmulqdq128:
2366 case X86::BI__builtin_ia32_vperm2f128_pd256:
2367 case X86::BI__builtin_ia32_vperm2f128_ps256:
2368 case X86::BI__builtin_ia32_vperm2f128_si256:
2369 case X86::BI__builtin_ia32_permti256:
2370 i = 2; l = -128; u = 255;
2371 break;
2372 case X86::BI__builtin_ia32_palignr128:
2373 case X86::BI__builtin_ia32_palignr256:
2374 case X86::BI__builtin_ia32_palignr512_mask:
2375 case X86::BI__builtin_ia32_vcomisd:
2376 case X86::BI__builtin_ia32_vcomiss:
2377 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2378 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2379 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2380 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2381 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2382 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2383 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2384 i = 2; l = 0; u = 255;
2385 break;
2386 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2387 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2388 case X86::BI__builtin_ia32_fixupimmps512_mask:
2389 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2390 case X86::BI__builtin_ia32_fixupimmsd_mask:
2391 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2392 case X86::BI__builtin_ia32_fixupimmss_mask:
2393 case X86::BI__builtin_ia32_fixupimmss_maskz:
2394 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2395 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2396 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2397 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2398 case X86::BI__builtin_ia32_fixupimmps128_mask:
2399 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2400 case X86::BI__builtin_ia32_fixupimmps256_mask:
2401 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2402 case X86::BI__builtin_ia32_pternlogd512_mask:
2403 case X86::BI__builtin_ia32_pternlogd512_maskz:
2404 case X86::BI__builtin_ia32_pternlogq512_mask:
2405 case X86::BI__builtin_ia32_pternlogq512_maskz:
2406 case X86::BI__builtin_ia32_pternlogd128_mask:
2407 case X86::BI__builtin_ia32_pternlogd128_maskz:
2408 case X86::BI__builtin_ia32_pternlogd256_mask:
2409 case X86::BI__builtin_ia32_pternlogd256_maskz:
2410 case X86::BI__builtin_ia32_pternlogq128_mask:
2411 case X86::BI__builtin_ia32_pternlogq128_maskz:
2412 case X86::BI__builtin_ia32_pternlogq256_mask:
2413 case X86::BI__builtin_ia32_pternlogq256_maskz:
2414 i = 3; l = 0; u = 255;
2415 break;
2416 case X86::BI__builtin_ia32_gatherpfdpd:
2417 case X86::BI__builtin_ia32_gatherpfdps:
2418 case X86::BI__builtin_ia32_gatherpfqpd:
2419 case X86::BI__builtin_ia32_gatherpfqps:
2420 case X86::BI__builtin_ia32_scatterpfdpd:
2421 case X86::BI__builtin_ia32_scatterpfdps:
2422 case X86::BI__builtin_ia32_scatterpfqpd:
2423 case X86::BI__builtin_ia32_scatterpfqps:
2424 i = 4; l = 2; u = 3;
2425 break;
2426 case X86::BI__builtin_ia32_pcmpestrm128:
2427 case X86::BI__builtin_ia32_pcmpestri128:
2428 case X86::BI__builtin_ia32_pcmpestria128:
2429 case X86::BI__builtin_ia32_pcmpestric128:
2430 case X86::BI__builtin_ia32_pcmpestrio128:
2431 case X86::BI__builtin_ia32_pcmpestris128:
2432 case X86::BI__builtin_ia32_pcmpestriz128:
2433 i = 4; l = -128; u = 255;
2434 break;
2435 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2436 case X86::BI__builtin_ia32_rndscaless_round_mask:
2437 i = 4; l = 0; u = 255;
2438 break;
2439 }
2440 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2441}
2442
2443/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2444/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2445/// Returns true when the format fits the function and the FormatStringInfo has
2446/// been populated.
2447bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2448 FormatStringInfo *FSI) {
2449 FSI->HasVAListArg = Format->getFirstArg() == 0;
2450 FSI->FormatIdx = Format->getFormatIdx() - 1;
2451 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2452
2453 // The way the format attribute works in GCC, the implicit this argument
2454 // of member functions is counted. However, it doesn't appear in our own
2455 // lists, so decrement format_idx in that case.
2456 if (IsCXXMember) {
2457 if(FSI->FormatIdx == 0)
2458 return false;
2459 --FSI->FormatIdx;
2460 if (FSI->FirstDataArg != 0)
2461 --FSI->FirstDataArg;
2462 }
2463 return true;
2464}
2465
2466/// Checks if a the given expression evaluates to null.
2467///
2468/// \brief Returns true if the value evaluates to null.
2469static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2470 // If the expression has non-null type, it doesn't evaluate to null.
2471 if (auto nullability
2472 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2473 if (*nullability == NullabilityKind::NonNull)
2474 return false;
2475 }
2476
2477 // As a special case, transparent unions initialized with zero are
2478 // considered null for the purposes of the nonnull attribute.
2479 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2480 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2481 if (const CompoundLiteralExpr *CLE =
2482 dyn_cast<CompoundLiteralExpr>(Expr))
2483 if (const InitListExpr *ILE =
2484 dyn_cast<InitListExpr>(CLE->getInitializer()))
2485 Expr = ILE->getInit(0);
2486 }
2487
2488 bool Result;
2489 return (!Expr->isValueDependent() &&
2490 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2491 !Result);
2492}
2493
2494static void CheckNonNullArgument(Sema &S,
2495 const Expr *ArgExpr,
2496 SourceLocation CallSiteLoc) {
2497 if (CheckNonNullExpr(S, ArgExpr))
2498 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2499 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2500}
2501
2502bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2503 FormatStringInfo FSI;
2504 if ((GetFormatStringType(Format) == FST_NSString) &&
2505 getFormatStringInfo(Format, false, &FSI)) {
2506 Idx = FSI.FormatIdx;
2507 return true;
2508 }
2509 return false;
2510}
2511/// \brief Diagnose use of %s directive in an NSString which is being passed
2512/// as formatting string to formatting method.
2513static void
2514DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2515 const NamedDecl *FDecl,
2516 Expr **Args,
2517 unsigned NumArgs) {
2518 unsigned Idx = 0;
2519 bool Format = false;
2520 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2521 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2522 Idx = 2;
2523 Format = true;
2524 }
2525 else
2526 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2527 if (S.GetFormatNSStringIdx(I, Idx)) {
2528 Format = true;
2529 break;
2530 }
2531 }
2532 if (!Format || NumArgs <= Idx)
2533 return;
2534 const Expr *FormatExpr = Args[Idx];
2535 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2536 FormatExpr = CSCE->getSubExpr();
2537 const StringLiteral *FormatString;
2538 if (const ObjCStringLiteral *OSL =
2539 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2540 FormatString = OSL->getString();
2541 else
2542 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2543 if (!FormatString)
2544 return;
2545 if (S.FormatStringHasSArg(FormatString)) {
2546 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2547 << "%s" << 1 << 1;
2548 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2549 << FDecl->getDeclName();
2550 }
2551}
2552
2553/// Determine whether the given type has a non-null nullability annotation.
2554static bool isNonNullType(ASTContext &ctx, QualType type) {
2555 if (auto nullability = type->getNullability(ctx))
2556 return *nullability == NullabilityKind::NonNull;
2557
2558 return false;
2559}
2560
2561static void CheckNonNullArguments(Sema &S,
2562 const NamedDecl *FDecl,
2563 const FunctionProtoType *Proto,
2564 ArrayRef<const Expr *> Args,
2565 SourceLocation CallSiteLoc) {
2566 assert((FDecl || Proto) && "Need a function declaration or prototype")(((FDecl || Proto) && "Need a function declaration or prototype"
) ? static_cast<void> (0) : __assert_fail ("(FDecl || Proto) && \"Need a function declaration or prototype\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 2566, __PRETTY_FUNCTION__))
;
2567
2568 // Check the attributes attached to the method/function itself.
2569 llvm::SmallBitVector NonNullArgs;
2570 if (FDecl) {
2571 // Handle the nonnull attribute on the function/method declaration itself.
2572 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2573 if (!NonNull->args_size()) {
2574 // Easy case: all pointer arguments are nonnull.
2575 for (const auto *Arg : Args)
2576 if (S.isValidPointerAttrType(Arg->getType()))
2577 CheckNonNullArgument(S, Arg, CallSiteLoc);
2578 return;
2579 }
2580
2581 for (unsigned Val : NonNull->args()) {
2582 if (Val >= Args.size())
2583 continue;
2584 if (NonNullArgs.empty())
2585 NonNullArgs.resize(Args.size());
2586 NonNullArgs.set(Val);
2587 }
2588 }
2589 }
2590
2591 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2592 // Handle the nonnull attribute on the parameters of the
2593 // function/method.
2594 ArrayRef<ParmVarDecl*> parms;
2595 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2596 parms = FD->parameters();
2597 else
2598 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2599
2600 unsigned ParamIndex = 0;
2601 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2602 I != E; ++I, ++ParamIndex) {
2603 const ParmVarDecl *PVD = *I;
2604 if (PVD->hasAttr<NonNullAttr>() ||
2605 isNonNullType(S.Context, PVD->getType())) {
2606 if (NonNullArgs.empty())
2607 NonNullArgs.resize(Args.size());
2608
2609 NonNullArgs.set(ParamIndex);
2610 }
2611 }
2612 } else {
2613 // If we have a non-function, non-method declaration but no
2614 // function prototype, try to dig out the function prototype.
2615 if (!Proto) {
2616 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2617 QualType type = VD->getType().getNonReferenceType();
2618 if (auto pointerType = type->getAs<PointerType>())
2619 type = pointerType->getPointeeType();
2620 else if (auto blockType = type->getAs<BlockPointerType>())
2621 type = blockType->getPointeeType();
2622 // FIXME: data member pointers?
2623
2624 // Dig out the function prototype, if there is one.
2625 Proto = type->getAs<FunctionProtoType>();
2626 }
2627 }
2628
2629 // Fill in non-null argument information from the nullability
2630 // information on the parameter types (if we have them).
2631 if (Proto) {
2632 unsigned Index = 0;
2633 for (auto paramType : Proto->getParamTypes()) {
2634 if (isNonNullType(S.Context, paramType)) {
2635 if (NonNullArgs.empty())
2636 NonNullArgs.resize(Args.size());
2637
2638 NonNullArgs.set(Index);
2639 }
2640
2641 ++Index;
2642 }
2643 }
2644 }
2645
2646 // Check for non-null arguments.
2647 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2648 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2649 if (NonNullArgs[ArgIndex])
2650 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2651 }
2652}
2653
2654/// Handles the checks for format strings, non-POD arguments to vararg
2655/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2656/// attributes.
2657void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2658 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2659 bool IsMemberFunction, SourceLocation Loc,
2660 SourceRange Range, VariadicCallType CallType) {
2661 // FIXME: We should check as much as we can in the template definition.
2662 if (CurContext->isDependentContext())
4
Assuming the condition is false
5
Taking false branch
2663 return;
2664
2665 // Printf and scanf checking.
2666 llvm::SmallBitVector CheckedVarArgs;
2667 if (FDecl) {
6
Taking true branch
2668 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2669 // Only create vector if there are format attributes.
2670 CheckedVarArgs.resize(Args.size());
7
Calling 'SmallBitVector::resize'
13
Returned allocated memory
14
Calling 'SmallBitVector::resize'
2671
2672 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2673 CheckedVarArgs);
2674 }
2675 }
2676
2677 // Refuse POD arguments that weren't caught by the format string
2678 // checks above.
2679 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2680 if (CallType != VariadicDoesNotApply &&
2681 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2682 unsigned NumParams = Proto ? Proto->getNumParams()
2683 : FDecl && isa<FunctionDecl>(FDecl)
2684 ? cast<FunctionDecl>(FDecl)->getNumParams()
2685 : FDecl && isa<ObjCMethodDecl>(FDecl)
2686 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2687 : 0;
2688
2689 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2690 // Args[ArgIdx] can be null in malformed code.
2691 if (const Expr *Arg = Args[ArgIdx]) {
2692 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2693 checkVariadicArgument(Arg, CallType);
2694 }
2695 }
2696 }
2697
2698 if (FDecl || Proto) {
2699 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2700
2701 // Type safety checking.
2702 if (FDecl) {
2703 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2704 CheckArgumentWithTypeTag(I, Args.data());
2705 }
2706 }
2707
2708 if (FD)
2709 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2710}
2711
2712/// CheckConstructorCall - Check a constructor call for correctness and safety
2713/// properties not enforced by the C type system.
2714void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2715 ArrayRef<const Expr *> Args,
2716 const FunctionProtoType *Proto,
2717 SourceLocation Loc) {
2718 VariadicCallType CallType =
2719 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2720 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2721 Loc, SourceRange(), CallType);
2722}
2723
2724/// CheckFunctionCall - Check a direct function call for various correctness
2725/// and safety properties not strictly enforced by the C type system.
2726bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2727 const FunctionProtoType *Proto) {
2728 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2729 isa<CXXMethodDecl>(FDecl);
2730 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2731 IsMemberOperatorCall;
2732 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2733 TheCall->getCallee());
2734 Expr** Args = TheCall->getArgs();
2735 unsigned NumArgs = TheCall->getNumArgs();
2736
2737 Expr *ImplicitThis = nullptr;
2738 if (IsMemberOperatorCall) {
2739 // If this is a call to a member operator, hide the first argument
2740 // from checkCall.
2741 // FIXME: Our choice of AST representation here is less than ideal.
2742 ImplicitThis = Args[0];
2743 ++Args;
2744 --NumArgs;
2745 } else if (IsMemberFunction)
2746 ImplicitThis =
2747 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2748
2749 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2750 IsMemberFunction, TheCall->getRParenLoc(),
2751 TheCall->getCallee()->getSourceRange(), CallType);
2752
2753 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2754 // None of the checks below are needed for functions that don't have
2755 // simple names (e.g., C++ conversion functions).
2756 if (!FnInfo)
2757 return false;
2758
2759 CheckAbsoluteValueFunction(TheCall, FDecl);
2760 CheckMaxUnsignedZero(TheCall, FDecl);
2761
2762 if (getLangOpts().ObjC1)
2763 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2764
2765 unsigned CMId = FDecl->getMemoryFunctionKind();
2766 if (CMId == 0)
2767 return false;
2768
2769 // Handle memory setting and copying functions.
2770// if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2771// CheckStrlcpycatArguments(TheCall, FnInfo);
2772// else
2773 if (CMId == Builtin::BIstrncat)
2774 CheckStrncatArguments(TheCall, FnInfo);
2775 else
2776 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2777
2778 return false;
2779}
2780
2781bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2782 ArrayRef<const Expr *> Args) {
2783 VariadicCallType CallType =
2784 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1
Assuming the condition is false
2
'?' condition is false
2785
2786 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3
Calling 'Sema::checkCall'
2787 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2788 CallType);
2789
2790 return false;
2791}
2792
2793bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2794 const FunctionProtoType *Proto) {
2795 QualType Ty;
2796 if (const auto *V = dyn_cast<VarDecl>(NDecl))
2797 Ty = V->getType().getNonReferenceType();
2798 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2799 Ty = F->getType().getNonReferenceType();
2800 else
2801 return false;
2802
2803 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2804 !Ty->isFunctionProtoType())
2805 return false;
2806
2807 VariadicCallType CallType;
2808 if (!Proto || !Proto->isVariadic()) {
2809 CallType = VariadicDoesNotApply;
2810 } else if (Ty->isBlockPointerType()) {
2811 CallType = VariadicBlock;
2812 } else { // Ty->isFunctionPointerType()
2813 CallType = VariadicFunction;
2814 }
2815
2816 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2817 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2818 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2819 TheCall->getCallee()->getSourceRange(), CallType);
2820
2821 return false;
2822}
2823
2824/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2825/// such as function pointers returned from functions.
2826bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2827 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2828 TheCall->getCallee());
2829 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2830 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2831 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2832 TheCall->getCallee()->getSourceRange(), CallType);
2833
2834 return false;
2835}
2836
2837static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2838 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2839 return false;
2840
2841 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2842 switch (Op) {
2843 case AtomicExpr::AO__c11_atomic_init:
2844 case AtomicExpr::AO__opencl_atomic_init:
2845 llvm_unreachable("There is no ordering argument for an init")::llvm::llvm_unreachable_internal("There is no ordering argument for an init"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 2845)
;
2846
2847 case AtomicExpr::AO__c11_atomic_load:
2848 case AtomicExpr::AO__opencl_atomic_load:
2849 case AtomicExpr::AO__atomic_load_n:
2850 case AtomicExpr::AO__atomic_load:
2851 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2852 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2853
2854 case AtomicExpr::AO__c11_atomic_store:
2855 case AtomicExpr::AO__opencl_atomic_store:
2856 case AtomicExpr::AO__atomic_store:
2857 case AtomicExpr::AO__atomic_store_n:
2858 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2859 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2860 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2861
2862 default:
2863 return true;
2864 }
2865}
2866
2867ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2868 AtomicExpr::AtomicOp Op) {
2869 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2870 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2871
2872 // All the non-OpenCL operations take one of the following forms.
2873 // The OpenCL operations take the __c11 forms with one extra argument for
2874 // synchronization scope.
2875 enum {
2876 // C __c11_atomic_init(A *, C)
2877 Init,
2878 // C __c11_atomic_load(A *, int)
2879 Load,
2880 // void __atomic_load(A *, CP, int)
2881 LoadCopy,
2882 // void __atomic_store(A *, CP, int)
2883 Copy,
2884 // C __c11_atomic_add(A *, M, int)
2885 Arithmetic,
2886 // C __atomic_exchange_n(A *, CP, int)
2887 Xchg,
2888 // void __atomic_exchange(A *, C *, CP, int)
2889 GNUXchg,
2890 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2891 C11CmpXchg,
2892 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2893 GNUCmpXchg
2894 } Form = Init;
2895 const unsigned NumForm = GNUCmpXchg + 1;
2896 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2897 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2898 // where:
2899 // C is an appropriate type,
2900 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2901 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2902 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2903 // the int parameters are for orderings.
2904
2905 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2906 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2907 "need to update code for modified forms");
2908 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2909 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2910 AtomicExpr::AO__atomic_load,
2911 "need to update code for modified C11 atomics");
2912 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2913 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2914 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2915 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2916 IsOpenCL;
2917 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2918 Op == AtomicExpr::AO__atomic_store_n ||
2919 Op == AtomicExpr::AO__atomic_exchange_n ||
2920 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2921 bool IsAddSub = false;
2922
2923 switch (Op) {
2924 case AtomicExpr::AO__c11_atomic_init:
2925 case AtomicExpr::AO__opencl_atomic_init:
2926 Form = Init;
2927 break;
2928
2929 case AtomicExpr::AO__c11_atomic_load:
2930 case AtomicExpr::AO__opencl_atomic_load:
2931 case AtomicExpr::AO__atomic_load_n:
2932 Form = Load;
2933 break;
2934
2935 case AtomicExpr::AO__atomic_load:
2936 Form = LoadCopy;
2937 break;
2938
2939 case AtomicExpr::AO__c11_atomic_store:
2940 case AtomicExpr::AO__opencl_atomic_store:
2941 case AtomicExpr::AO__atomic_store:
2942 case AtomicExpr::AO__atomic_store_n:
2943 Form = Copy;
2944 break;
2945
2946 case AtomicExpr::AO__c11_atomic_fetch_add:
2947 case AtomicExpr::AO__c11_atomic_fetch_sub:
2948 case AtomicExpr::AO__opencl_atomic_fetch_add:
2949 case AtomicExpr::AO__opencl_atomic_fetch_sub:
2950 case AtomicExpr::AO__opencl_atomic_fetch_min:
2951 case AtomicExpr::AO__opencl_atomic_fetch_max:
2952 case AtomicExpr::AO__atomic_fetch_add:
2953 case AtomicExpr::AO__atomic_fetch_sub:
2954 case AtomicExpr::AO__atomic_add_fetch:
2955 case AtomicExpr::AO__atomic_sub_fetch:
2956 IsAddSub = true;
2957 // Fall through.
2958 case AtomicExpr::AO__c11_atomic_fetch_and:
2959 case AtomicExpr::AO__c11_atomic_fetch_or:
2960 case AtomicExpr::AO__c11_atomic_fetch_xor:
2961 case AtomicExpr::AO__opencl_atomic_fetch_and:
2962 case AtomicExpr::AO__opencl_atomic_fetch_or:
2963 case AtomicExpr::AO__opencl_atomic_fetch_xor:
2964 case AtomicExpr::AO__atomic_fetch_and:
2965 case AtomicExpr::AO__atomic_fetch_or:
2966 case AtomicExpr::AO__atomic_fetch_xor:
2967 case AtomicExpr::AO__atomic_fetch_nand:
2968 case AtomicExpr::AO__atomic_and_fetch:
2969 case AtomicExpr::AO__atomic_or_fetch:
2970 case AtomicExpr::AO__atomic_xor_fetch:
2971 case AtomicExpr::AO__atomic_nand_fetch:
2972 Form = Arithmetic;
2973 break;
2974
2975 case AtomicExpr::AO__c11_atomic_exchange:
2976 case AtomicExpr::AO__opencl_atomic_exchange:
2977 case AtomicExpr::AO__atomic_exchange_n:
2978 Form = Xchg;
2979 break;
2980
2981 case AtomicExpr::AO__atomic_exchange:
2982 Form = GNUXchg;
2983 break;
2984
2985 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2986 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2987 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2988 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
2989 Form = C11CmpXchg;
2990 break;
2991
2992 case AtomicExpr::AO__atomic_compare_exchange:
2993 case AtomicExpr::AO__atomic_compare_exchange_n:
2994 Form = GNUCmpXchg;
2995 break;
2996 }
2997
2998 unsigned AdjustedNumArgs = NumArgs[Form];
2999 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3000 ++AdjustedNumArgs;
3001 // Check we have the right number of arguments.
3002 if (TheCall->getNumArgs() < AdjustedNumArgs) {
3003 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3004 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3005 << TheCall->getCallee()->getSourceRange();
3006 return ExprError();
3007 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3008 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3009 diag::err_typecheck_call_too_many_args)
3010 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3011 << TheCall->getCallee()->getSourceRange();
3012 return ExprError();
3013 }
3014
3015 // Inspect the first argument of the atomic operation.
3016 Expr *Ptr = TheCall->getArg(0);
3017 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3018 if (ConvertedPtr.isInvalid())
3019 return ExprError();
3020
3021 Ptr = ConvertedPtr.get();
3022 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3023 if (!pointerType) {
3024 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3025 << Ptr->getType() << Ptr->getSourceRange();
3026 return ExprError();
3027 }
3028
3029 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3030 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3031 QualType ValType = AtomTy; // 'C'
3032 if (IsC11) {
3033 if (!AtomTy->isAtomicType()) {
3034 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3035 << Ptr->getType() << Ptr->getSourceRange();
3036 return ExprError();
3037 }
3038 if (AtomTy.isConstQualified() ||
3039 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3040 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3041 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3042 << Ptr->getSourceRange();
3043 return ExprError();
3044 }
3045 ValType = AtomTy->getAs<AtomicType>()->getValueType();
3046 } else if (Form != Load && Form != LoadCopy) {
3047 if (ValType.isConstQualified()) {
3048 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3049 << Ptr->getType() << Ptr->getSourceRange();
3050 return ExprError();
3051 }
3052 }
3053
3054 // For an arithmetic operation, the implied arithmetic must be well-formed.
3055 if (Form == Arithmetic) {
3056 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3057 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3058 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3059 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3060 return ExprError();
3061 }
3062 if (!IsAddSub && !ValType->isIntegerType()) {
3063 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3064 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3065 return ExprError();
3066 }
3067 if (IsC11 && ValType->isPointerType() &&
3068 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3069 diag::err_incomplete_type)) {
3070 return ExprError();
3071 }
3072 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3073 // For __atomic_*_n operations, the value type must be a scalar integral or
3074 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3075 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3076 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3077 return ExprError();
3078 }
3079
3080 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3081 !AtomTy->isScalarType()) {
3082 // For GNU atomics, require a trivially-copyable type. This is not part of
3083 // the GNU atomics specification, but we enforce it for sanity.
3084 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3085 << Ptr->getType() << Ptr->getSourceRange();
3086 return ExprError();
3087 }
3088
3089 switch (ValType.getObjCLifetime()) {
3090 case Qualifiers::OCL_None:
3091 case Qualifiers::OCL_ExplicitNone:
3092 // okay
3093 break;
3094
3095 case Qualifiers::OCL_Weak:
3096 case Qualifiers::OCL_Strong:
3097 case Qualifiers::OCL_Autoreleasing:
3098 // FIXME: Can this happen? By this point, ValType should be known
3099 // to be trivially copyable.
3100 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3101 << ValType << Ptr->getSourceRange();
3102 return ExprError();
3103 }
3104
3105 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3106 // volatile-ness of the pointee-type inject itself into the result or the
3107 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3108 ValType.removeLocalVolatile();
3109 ValType.removeLocalConst();
3110 QualType ResultType = ValType;
3111 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3112 Form == Init)
3113 ResultType = Context.VoidTy;
3114 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3115 ResultType = Context.BoolTy;
3116
3117 // The type of a parameter passed 'by value'. In the GNU atomics, such
3118 // arguments are actually passed as pointers.
3119 QualType ByValType = ValType; // 'CP'
3120 if (!IsC11 && !IsN)
3121 ByValType = Ptr->getType();
3122
3123 // The first argument --- the pointer --- has a fixed type; we
3124 // deduce the types of the rest of the arguments accordingly. Walk
3125 // the remaining arguments, converting them to the deduced value type.
3126 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3127 QualType Ty;
3128 if (i < NumVals[Form] + 1) {
3129 switch (i) {
3130 case 1:
3131 // The second argument is the non-atomic operand. For arithmetic, this
3132 // is always passed by value, and for a compare_exchange it is always
3133 // passed by address. For the rest, GNU uses by-address and C11 uses
3134 // by-value.
3135 assert(Form != Load)((Form != Load) ? static_cast<void> (0) : __assert_fail
("Form != Load", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 3135, __PRETTY_FUNCTION__))
;
3136 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3137 Ty = ValType;
3138 else if (Form == Copy || Form == Xchg)
3139 Ty = ByValType;
3140 else if (Form == Arithmetic)
3141 Ty = Context.getPointerDiffType();
3142 else {
3143 Expr *ValArg = TheCall->getArg(i);
3144 // Treat this argument as _Nonnull as we want to show a warning if
3145 // NULL is passed into it.
3146 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3147 LangAS AS = LangAS::Default;
3148 // Keep address space of non-atomic pointer type.
3149 if (const PointerType *PtrTy =
3150 ValArg->getType()->getAs<PointerType>()) {
3151 AS = PtrTy->getPointeeType().getAddressSpace();
3152 }
3153 Ty = Context.getPointerType(
3154 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3155 }
3156 break;
3157 case 2:
3158 // The third argument to compare_exchange / GNU exchange is a
3159 // (pointer to a) desired value.
3160 Ty = ByValType;
3161 break;
3162 case 3:
3163 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3164 Ty = Context.BoolTy;
3165 break;
3166 }
3167 } else {
3168 // The order(s) and scope are always converted to int.
3169 Ty = Context.IntTy;
3170 }
3171
3172 InitializedEntity Entity =
3173 InitializedEntity::InitializeParameter(Context, Ty, false);
3174 ExprResult Arg = TheCall->getArg(i);
3175 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3176 if (Arg.isInvalid())
3177 return true;
3178 TheCall->setArg(i, Arg.get());
3179 }
3180
3181 // Permute the arguments into a 'consistent' order.
3182 SmallVector<Expr*, 5> SubExprs;
3183 SubExprs.push_back(Ptr);
3184 switch (Form) {
3185 case Init:
3186 // Note, AtomicExpr::getVal1() has a special case for this atomic.
3187 SubExprs.push_back(TheCall->getArg(1)); // Val1
3188 break;
3189 case Load:
3190 SubExprs.push_back(TheCall->getArg(1)); // Order
3191 break;
3192 case LoadCopy:
3193 case Copy:
3194 case Arithmetic:
3195 case Xchg:
3196 SubExprs.push_back(TheCall->getArg(2)); // Order
3197 SubExprs.push_back(TheCall->getArg(1)); // Val1
3198 break;
3199 case GNUXchg:
3200 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3201 SubExprs.push_back(TheCall->getArg(3)); // Order
3202 SubExprs.push_back(TheCall->getArg(1)); // Val1
3203 SubExprs.push_back(TheCall->getArg(2)); // Val2
3204 break;
3205 case C11CmpXchg:
3206 SubExprs.push_back(TheCall->getArg(3)); // Order
3207 SubExprs.push_back(TheCall->getArg(1)); // Val1
3208 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3209 SubExprs.push_back(TheCall->getArg(2)); // Val2
3210 break;
3211 case GNUCmpXchg:
3212 SubExprs.push_back(TheCall->getArg(4)); // Order
3213 SubExprs.push_back(TheCall->getArg(1)); // Val1
3214 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3215 SubExprs.push_back(TheCall->getArg(2)); // Val2
3216 SubExprs.push_back(TheCall->getArg(3)); // Weak
3217 break;
3218 }
3219
3220 if (SubExprs.size() >= 2 && Form != Init) {
3221 llvm::APSInt Result(32);
3222 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3223 !isValidOrderingForOp(Result.getSExtValue(), Op))
3224 Diag(SubExprs[1]->getLocStart(),
3225 diag::warn_atomic_op_has_invalid_memory_order)
3226 << SubExprs[1]->getSourceRange();
3227 }
3228
3229 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3230 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3231 llvm::APSInt Result(32);
3232 if (Scope->isIntegerConstantExpr(Result, Context) &&
3233 !ScopeModel->isValid(Result.getZExtValue())) {
3234 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3235 << Scope->getSourceRange();
3236 }
3237 SubExprs.push_back(Scope);
3238 }
3239
3240 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3241 SubExprs, ResultType, Op,
3242 TheCall->getRParenLoc());
3243
3244 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3245 Op == AtomicExpr::AO__c11_atomic_store ||
3246 Op == AtomicExpr::AO__opencl_atomic_load ||
3247 Op == AtomicExpr::AO__opencl_atomic_store ) &&
3248 Context.AtomicUsesUnsupportedLibcall(AE))
3249 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3250 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3251 Op == AtomicExpr::AO__opencl_atomic_load)
3252 ? 0 : 1);
3253
3254 return AE;
3255}
3256
3257/// checkBuiltinArgument - Given a call to a builtin function, perform
3258/// normal type-checking on the given argument, updating the call in
3259/// place. This is useful when a builtin function requires custom
3260/// type-checking for some of its arguments but not necessarily all of
3261/// them.
3262///
3263/// Returns true on error.
3264static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3265 FunctionDecl *Fn = E->getDirectCallee();
3266 assert(Fn && "builtin call without direct callee!")((Fn && "builtin call without direct callee!") ? static_cast
<void> (0) : __assert_fail ("Fn && \"builtin call without direct callee!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 3266, __PRETTY_FUNCTION__))
;
3267
3268 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3269 InitializedEntity Entity =
3270 InitializedEntity::InitializeParameter(S.Context, Param);
3271
3272 ExprResult Arg = E->getArg(0);
3273 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3274 if (Arg.isInvalid())
3275 return true;
3276
3277 E->setArg(ArgIndex, Arg.get());
3278 return false;
3279}
3280
3281/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3282/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3283/// type of its first argument. The main ActOnCallExpr routines have already
3284/// promoted the types of arguments because all of these calls are prototyped as
3285/// void(...).
3286///
3287/// This function goes through and does final semantic checking for these
3288/// builtins,
3289ExprResult
3290Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3291 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3292 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3293 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3294
3295 // Ensure that we have at least one argument to do type inference from.
3296 if (TheCall->getNumArgs() < 1) {
3297 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3298 << 0 << 1 << TheCall->getNumArgs()
3299 << TheCall->getCallee()->getSourceRange();
3300 return ExprError();
3301 }
3302
3303 // Inspect the first argument of the atomic builtin. This should always be
3304 // a pointer type, whose element is an integral scalar or pointer type.
3305 // Because it is a pointer type, we don't have to worry about any implicit
3306 // casts here.
3307 // FIXME: We don't allow floating point scalars as input.
3308 Expr *FirstArg = TheCall->getArg(0);
3309 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3310 if (FirstArgResult.isInvalid())
3311 return ExprError();
3312 FirstArg = FirstArgResult.get();
3313 TheCall->setArg(0, FirstArg);
3314
3315 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3316 if (!pointerType) {
3317 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3318 << FirstArg->getType() << FirstArg->getSourceRange();
3319 return ExprError();
3320 }
3321
3322 QualType ValType = pointerType->getPointeeType();
3323 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3324 !ValType->isBlockPointerType()) {
3325 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3326 << FirstArg->getType() << FirstArg->getSourceRange();
3327 return ExprError();
3328 }
3329
3330 switch (ValType.getObjCLifetime()) {
3331 case Qualifiers::OCL_None:
3332 case Qualifiers::OCL_ExplicitNone:
3333 // okay
3334 break;
3335
3336 case Qualifiers::OCL_Weak:
3337 case Qualifiers::OCL_Strong:
3338 case Qualifiers::OCL_Autoreleasing:
3339 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3340 << ValType << FirstArg->getSourceRange();
3341 return ExprError();
3342 }
3343
3344 // Strip any qualifiers off ValType.
3345 ValType = ValType.getUnqualifiedType();
3346
3347 // The majority of builtins return a value, but a few have special return
3348 // types, so allow them to override appropriately below.
3349 QualType ResultType = ValType;
3350
3351 // We need to figure out which concrete builtin this maps onto. For example,
3352 // __sync_fetch_and_add with a 2 byte object turns into
3353 // __sync_fetch_and_add_2.
3354#define BUILTIN_ROW(x) \
3355 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3356 Builtin::BI##x##_8, Builtin::BI##x##_16 }
3357
3358 static const unsigned BuiltinIndices[][5] = {
3359 BUILTIN_ROW(__sync_fetch_and_add),
3360 BUILTIN_ROW(__sync_fetch_and_sub),
3361 BUILTIN_ROW(__sync_fetch_and_or),
3362 BUILTIN_ROW(__sync_fetch_and_and),
3363 BUILTIN_ROW(__sync_fetch_and_xor),
3364 BUILTIN_ROW(__sync_fetch_and_nand),
3365
3366 BUILTIN_ROW(__sync_add_and_fetch),
3367 BUILTIN_ROW(__sync_sub_and_fetch),
3368 BUILTIN_ROW(__sync_and_and_fetch),
3369 BUILTIN_ROW(__sync_or_and_fetch),
3370 BUILTIN_ROW(__sync_xor_and_fetch),
3371 BUILTIN_ROW(__sync_nand_and_fetch),
3372
3373 BUILTIN_ROW(__sync_val_compare_and_swap),
3374 BUILTIN_ROW(__sync_bool_compare_and_swap),
3375 BUILTIN_ROW(__sync_lock_test_and_set),
3376 BUILTIN_ROW(__sync_lock_release),
3377 BUILTIN_ROW(__sync_swap)
3378 };
3379#undef BUILTIN_ROW
3380
3381 // Determine the index of the size.
3382 unsigned SizeIndex;
3383 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3384 case 1: SizeIndex = 0; break;
3385 case 2: SizeIndex = 1; break;
3386 case 4: SizeIndex = 2; break;
3387 case 8: SizeIndex = 3; break;
3388 case 16: SizeIndex = 4; break;
3389 default:
3390 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3391 << FirstArg->getType() << FirstArg->getSourceRange();
3392 return ExprError();
3393 }
3394
3395 // Each of these builtins has one pointer argument, followed by some number of
3396 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3397 // that we ignore. Find out which row of BuiltinIndices to read from as well
3398 // as the number of fixed args.
3399 unsigned BuiltinID = FDecl->getBuiltinID();
3400 unsigned BuiltinIndex, NumFixed = 1;
3401 bool WarnAboutSemanticsChange = false;
3402 switch (BuiltinID) {
3403 default: llvm_unreachable("Unknown overloaded atomic builtin!")::llvm::llvm_unreachable_internal("Unknown overloaded atomic builtin!"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 3403)
;
3404 case Builtin::BI__sync_fetch_and_add:
3405 case Builtin::BI__sync_fetch_and_add_1:
3406 case Builtin::BI__sync_fetch_and_add_2:
3407 case Builtin::BI__sync_fetch_and_add_4:
3408 case Builtin::BI__sync_fetch_and_add_8:
3409 case Builtin::BI__sync_fetch_and_add_16:
3410 BuiltinIndex = 0;
3411 break;
3412
3413 case Builtin::BI__sync_fetch_and_sub:
3414 case Builtin::BI__sync_fetch_and_sub_1:
3415 case Builtin::BI__sync_fetch_and_sub_2:
3416 case Builtin::BI__sync_fetch_and_sub_4:
3417 case Builtin::BI__sync_fetch_and_sub_8:
3418 case Builtin::BI__sync_fetch_and_sub_16:
3419 BuiltinIndex = 1;
3420 break;
3421
3422 case Builtin::BI__sync_fetch_and_or:
3423 case Builtin::BI__sync_fetch_and_or_1:
3424 case Builtin::BI__sync_fetch_and_or_2:
3425 case Builtin::BI__sync_fetch_and_or_4:
3426 case Builtin::BI__sync_fetch_and_or_8:
3427 case Builtin::BI__sync_fetch_and_or_16:
3428 BuiltinIndex = 2;
3429 break;
3430
3431 case Builtin::BI__sync_fetch_and_and:
3432 case Builtin::BI__sync_fetch_and_and_1:
3433 case Builtin::BI__sync_fetch_and_and_2:
3434 case Builtin::BI__sync_fetch_and_and_4:
3435 case Builtin::BI__sync_fetch_and_and_8:
3436 case Builtin::BI__sync_fetch_and_and_16:
3437 BuiltinIndex = 3;
3438 break;
3439
3440 case Builtin::BI__sync_fetch_and_xor:
3441 case Builtin::BI__sync_fetch_and_xor_1:
3442 case Builtin::BI__sync_fetch_and_xor_2:
3443 case Builtin::BI__sync_fetch_and_xor_4:
3444 case Builtin::BI__sync_fetch_and_xor_8:
3445 case Builtin::BI__sync_fetch_and_xor_16:
3446 BuiltinIndex = 4;
3447 break;
3448
3449 case Builtin::BI__sync_fetch_and_nand:
3450 case Builtin::BI__sync_fetch_and_nand_1:
3451 case Builtin::BI__sync_fetch_and_nand_2:
3452 case Builtin::BI__sync_fetch_and_nand_4:
3453 case Builtin::BI__sync_fetch_and_nand_8:
3454 case Builtin::BI__sync_fetch_and_nand_16:
3455 BuiltinIndex = 5;
3456 WarnAboutSemanticsChange = true;
3457 break;
3458
3459 case Builtin::BI__sync_add_and_fetch:
3460 case Builtin::BI__sync_add_and_fetch_1:
3461 case Builtin::BI__sync_add_and_fetch_2:
3462 case Builtin::BI__sync_add_and_fetch_4:
3463 case Builtin::BI__sync_add_and_fetch_8:
3464 case Builtin::BI__sync_add_and_fetch_16:
3465 BuiltinIndex = 6;
3466 break;
3467
3468 case Builtin::BI__sync_sub_and_fetch:
3469 case Builtin::BI__sync_sub_and_fetch_1:
3470 case Builtin::BI__sync_sub_and_fetch_2:
3471 case Builtin::BI__sync_sub_and_fetch_4:
3472 case Builtin::BI__sync_sub_and_fetch_8:
3473 case Builtin::BI__sync_sub_and_fetch_16:
3474 BuiltinIndex = 7;
3475 break;
3476
3477 case Builtin::BI__sync_and_and_fetch:
3478 case Builtin::BI__sync_and_and_fetch_1:
3479 case Builtin::BI__sync_and_and_fetch_2:
3480 case Builtin::BI__sync_and_and_fetch_4:
3481 case Builtin::BI__sync_and_and_fetch_8:
3482 case Builtin::BI__sync_and_and_fetch_16:
3483 BuiltinIndex = 8;
3484 break;
3485
3486 case Builtin::BI__sync_or_and_fetch:
3487 case Builtin::BI__sync_or_and_fetch_1:
3488 case Builtin::BI__sync_or_and_fetch_2:
3489 case Builtin::BI__sync_or_and_fetch_4:
3490 case Builtin::BI__sync_or_and_fetch_8:
3491 case Builtin::BI__sync_or_and_fetch_16:
3492 BuiltinIndex = 9;
3493 break;
3494
3495 case Builtin::BI__sync_xor_and_fetch:
3496 case Builtin::BI__sync_xor_and_fetch_1:
3497 case Builtin::BI__sync_xor_and_fetch_2:
3498 case Builtin::BI__sync_xor_and_fetch_4:
3499 case Builtin::BI__sync_xor_and_fetch_8:
3500 case Builtin::BI__sync_xor_and_fetch_16:
3501 BuiltinIndex = 10;
3502 break;
3503
3504 case Builtin::BI__sync_nand_and_fetch:
3505 case Builtin::BI__sync_nand_and_fetch_1:
3506 case Builtin::BI__sync_nand_and_fetch_2:
3507 case Builtin::BI__sync_nand_and_fetch_4:
3508 case Builtin::BI__sync_nand_and_fetch_8:
3509 case Builtin::BI__sync_nand_and_fetch_16:
3510 BuiltinIndex = 11;
3511 WarnAboutSemanticsChange = true;
3512 break;
3513
3514 case Builtin::BI__sync_val_compare_and_swap:
3515 case Builtin::BI__sync_val_compare_and_swap_1:
3516 case Builtin::BI__sync_val_compare_and_swap_2:
3517 case Builtin::BI__sync_val_compare_and_swap_4:
3518 case Builtin::BI__sync_val_compare_and_swap_8:
3519 case Builtin::BI__sync_val_compare_and_swap_16:
3520 BuiltinIndex = 12;
3521 NumFixed = 2;
3522 break;
3523
3524 case Builtin::BI__sync_bool_compare_and_swap:
3525 case Builtin::BI__sync_bool_compare_and_swap_1:
3526 case Builtin::BI__sync_bool_compare_and_swap_2:
3527 case Builtin::BI__sync_bool_compare_and_swap_4:
3528 case Builtin::BI__sync_bool_compare_and_swap_8:
3529 case Builtin::BI__sync_bool_compare_and_swap_16:
3530 BuiltinIndex = 13;
3531 NumFixed = 2;
3532 ResultType = Context.BoolTy;
3533 break;
3534
3535 case Builtin::BI__sync_lock_test_and_set:
3536 case Builtin::BI__sync_lock_test_and_set_1:
3537 case Builtin::BI__sync_lock_test_and_set_2:
3538 case Builtin::BI__sync_lock_test_and_set_4:
3539 case Builtin::BI__sync_lock_test_and_set_8:
3540 case Builtin::BI__sync_lock_test_and_set_16:
3541 BuiltinIndex = 14;
3542 break;
3543
3544 case Builtin::BI__sync_lock_release:
3545 case Builtin::BI__sync_lock_release_1:
3546 case Builtin::BI__sync_lock_release_2:
3547 case Builtin::BI__sync_lock_release_4:
3548 case Builtin::BI__sync_lock_release_8:
3549 case Builtin::BI__sync_lock_release_16:
3550 BuiltinIndex = 15;
3551 NumFixed = 0;
3552 ResultType = Context.VoidTy;
3553 break;
3554
3555 case Builtin::BI__sync_swap:
3556 case Builtin::BI__sync_swap_1:
3557 case Builtin::BI__sync_swap_2:
3558 case Builtin::BI__sync_swap_4:
3559 case Builtin::BI__sync_swap_8:
3560 case Builtin::BI__sync_swap_16:
3561 BuiltinIndex = 16;
3562 break;
3563 }
3564
3565 // Now that we know how many fixed arguments we expect, first check that we
3566 // have at least that many.
3567 if (TheCall->getNumArgs() < 1+NumFixed) {
3568 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3569 << 0 << 1+NumFixed << TheCall->getNumArgs()
3570 << TheCall->getCallee()->getSourceRange();
3571 return ExprError();
3572 }
3573
3574 if (WarnAboutSemanticsChange) {
3575 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3576 << TheCall->getCallee()->getSourceRange();
3577 }
3578
3579 // Get the decl for the concrete builtin from this, we can tell what the
3580 // concrete integer type we should convert to is.
3581 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3582 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3583 FunctionDecl *NewBuiltinDecl;
3584 if (NewBuiltinID == BuiltinID)
3585 NewBuiltinDecl = FDecl;
3586 else {
3587 // Perform builtin lookup to avoid redeclaring it.
3588 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3589 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3590 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3591 assert(Res.getFoundDecl())((Res.getFoundDecl()) ? static_cast<void> (0) : __assert_fail
("Res.getFoundDecl()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 3591, __PRETTY_FUNCTION__))
;
3592 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3593 if (!NewBuiltinDecl)
3594 return ExprError();
3595 }
3596
3597 // The first argument --- the pointer --- has a fixed type; we
3598 // deduce the types of the rest of the arguments accordingly. Walk
3599 // the remaining arguments, converting them to the deduced value type.
3600 for (unsigned i = 0; i != NumFixed; ++i) {
3601 ExprResult Arg = TheCall->getArg(i+1);
3602
3603 // GCC does an implicit conversion to the pointer or integer ValType. This
3604 // can fail in some cases (1i -> int**), check for this error case now.
3605 // Initialize the argument.
3606 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3607 ValType, /*consume*/ false);
3608 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3609 if (Arg.isInvalid())
3610 return ExprError();
3611
3612 // Okay, we have something that *can* be converted to the right type. Check
3613 // to see if there is a potentially weird extension going on here. This can
3614 // happen when you do an atomic operation on something like an char* and
3615 // pass in 42. The 42 gets converted to char. This is even more strange
3616 // for things like 45.123 -> char, etc.
3617 // FIXME: Do this check.
3618 TheCall->setArg(i+1, Arg.get());
3619 }
3620
3621 ASTContext& Context = this->getASTContext();
3622
3623 // Create a new DeclRefExpr to refer to the new decl.
3624 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3625 Context,
3626 DRE->getQualifierLoc(),
3627 SourceLocation(),
3628 NewBuiltinDecl,
3629 /*enclosing*/ false,
3630 DRE->getLocation(),
3631 Context.BuiltinFnTy,
3632 DRE->getValueKind());
3633
3634 // Set the callee in the CallExpr.
3635 // FIXME: This loses syntactic information.
3636 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3637 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3638 CK_BuiltinFnToFnPtr);
3639 TheCall->setCallee(PromotedCall.get());
3640
3641 // Change the result type of the call to match the original value type. This
3642 // is arbitrary, but the codegen for these builtins ins design to handle it
3643 // gracefully.
3644 TheCall->setType(ResultType);
3645
3646 return TheCallResult;
3647}
3648
3649/// SemaBuiltinNontemporalOverloaded - We have a call to
3650/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3651/// overloaded function based on the pointer type of its last argument.
3652///
3653/// This function goes through and does final semantic checking for these
3654/// builtins.
3655ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3656 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3657 DeclRefExpr *DRE =
3658 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3659 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3660 unsigned BuiltinID = FDecl->getBuiltinID();
3661 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||(((BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID
== Builtin::BI__builtin_nontemporal_load) && "Unexpected nontemporal load/store builtin!"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 3663, __PRETTY_FUNCTION__))
3662 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&(((BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID
== Builtin::BI__builtin_nontemporal_load) && "Unexpected nontemporal load/store builtin!"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 3663, __PRETTY_FUNCTION__))
3663 "Unexpected nontemporal load/store builtin!")(((BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID
== Builtin::BI__builtin_nontemporal_load) && "Unexpected nontemporal load/store builtin!"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 3663, __PRETTY_FUNCTION__))
;
3664 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3665 unsigned numArgs = isStore ? 2 : 1;
3666
3667 // Ensure that we have the proper number of arguments.
3668 if (checkArgCount(*this, TheCall, numArgs))
3669 return ExprError();
3670
3671 // Inspect the last argument of the nontemporal builtin. This should always
3672 // be a pointer type, from which we imply the type of the memory access.
3673 // Because it is a pointer type, we don't have to worry about any implicit
3674 // casts here.
3675 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3676 ExprResult PointerArgResult =
3677 DefaultFunctionArrayLvalueConversion(PointerArg);
3678
3679 if (PointerArgResult.isInvalid())
3680 return ExprError();
3681 PointerArg = PointerArgResult.get();
3682 TheCall->setArg(numArgs - 1, PointerArg);
3683
3684 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3685 if (!pointerType) {
3686 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3687 << PointerArg->getType() << PointerArg->getSourceRange();
3688 return ExprError();
3689 }
3690
3691 QualType ValType = pointerType->getPointeeType();
3692
3693 // Strip any qualifiers off ValType.
3694 ValType = ValType.getUnqualifiedType();
3695 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3696 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3697 !ValType->isVectorType()) {
3698 Diag(DRE->getLocStart(),
3699 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3700 << PointerArg->getType() << PointerArg->getSourceRange();
3701 return ExprError();
3702 }
3703
3704 if (!isStore) {
3705 TheCall->setType(ValType);
3706 return TheCallResult;
3707 }
3708
3709 ExprResult ValArg = TheCall->getArg(0);
3710 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3711 Context, ValType, /*consume*/ false);
3712 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3713 if (ValArg.isInvalid())
3714 return ExprError();
3715
3716 TheCall->setArg(0, ValArg.get());
3717 TheCall->setType(Context.VoidTy);
3718 return TheCallResult;
3719}
3720
3721/// CheckObjCString - Checks that the argument to the builtin
3722/// CFString constructor is correct
3723/// Note: It might also make sense to do the UTF-16 conversion here (would
3724/// simplify the backend).
3725bool Sema::CheckObjCString(Expr *Arg) {
3726 Arg = Arg->IgnoreParenCasts();
3727 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3728
3729 if (!Literal || !Literal->isAscii()) {
3730 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3731 << Arg->getSourceRange();
3732 return true;
3733 }
3734
3735 if (Literal->containsNonAsciiOrNull()) {
3736 StringRef String = Literal->getString();
3737 unsigned NumBytes = String.size();
3738 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3739 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3740 llvm::UTF16 *ToPtr = &ToBuf[0];
3741
3742 llvm::ConversionResult Result =
3743 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3744 ToPtr + NumBytes, llvm::strictConversion);
3745 // Check for conversion failure.
3746 if (Result != llvm::conversionOK)
3747 Diag(Arg->getLocStart(),
3748 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3749 }
3750 return false;
3751}
3752
3753/// CheckObjCString - Checks that the format string argument to the os_log()
3754/// and os_trace() functions is correct, and converts it to const char *.
3755ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3756 Arg = Arg->IgnoreParenCasts();
3757 auto *Literal = dyn_cast<StringLiteral>(Arg);
3758 if (!Literal) {
3759 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3760 Literal = ObjcLiteral->getString();
3761 }
3762 }
3763
3764 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3765 return ExprError(
3766 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3767 << Arg->getSourceRange());
3768 }
3769
3770 ExprResult Result(Literal);
3771 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3772 InitializedEntity Entity =
3773 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3774 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3775 return Result;
3776}
3777
3778/// Check that the user is calling the appropriate va_start builtin for the
3779/// target and calling convention.
3780static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3781 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3782 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3783 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3784 bool IsWindows = TT.isOSWindows();
3785 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3786 if (IsX64 || IsAArch64) {
3787 clang::CallingConv CC = CC_C;
3788 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3789 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3790 if (IsMSVAStart) {
3791 // Don't allow this in System V ABI functions.
3792 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3793 return S.Diag(Fn->getLocStart(),
3794 diag::err_ms_va_start_used_in_sysv_function);
3795 } else {
3796 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3797 // On x64 Windows, don't allow this in System V ABI functions.
3798 // (Yes, that means there's no corresponding way to support variadic
3799 // System V ABI functions on Windows.)
3800 if ((IsWindows && CC == CC_X86_64SysV) ||
3801 (!IsWindows && CC == CC_Win64))
3802 return S.Diag(Fn->getLocStart(),
3803 diag::err_va_start_used_in_wrong_abi_function)
3804 << !IsWindows;
3805 }
3806 return false;
3807 }
3808
3809 if (IsMSVAStart)
3810 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3811 return false;
3812}
3813
3814static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3815 ParmVarDecl **LastParam = nullptr) {
3816 // Determine whether the current function, block, or obj-c method is variadic
3817 // and get its parameter list.
3818 bool IsVariadic = false;
3819 ArrayRef<ParmVarDecl *> Params;
3820 DeclContext *Caller = S.CurContext;
3821 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3822 IsVariadic = Block->isVariadic();
3823 Params = Block->parameters();
3824 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3825 IsVariadic = FD->isVariadic();
3826 Params = FD->parameters();
3827 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3828 IsVariadic = MD->isVariadic();
3829 // FIXME: This isn't correct for methods (results in bogus warning).
3830 Params = MD->parameters();
3831 } else if (isa<CapturedDecl>(Caller)) {
3832 // We don't support va_start in a CapturedDecl.
3833 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3834 return true;
3835 } else {
3836 // This must be some other declcontext that parses exprs.
3837 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3838 return true;
3839 }
3840
3841 if (!IsVariadic) {
3842 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3843 return true;
3844 }
3845
3846 if (LastParam)
3847 *LastParam = Params.empty() ? nullptr : Params.back();
3848
3849 return false;
3850}
3851
3852/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3853/// for validity. Emit an error and return true on failure; return false
3854/// on success.
3855bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3856 Expr *Fn = TheCall->getCallee();
3857
3858 if (checkVAStartABI(*this, BuiltinID, Fn))
3859 return true;
3860
3861 if (TheCall->getNumArgs() > 2) {
3862 Diag(TheCall->getArg(2)->getLocStart(),
3863 diag::err_typecheck_call_too_many_args)
3864 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3865 << Fn->getSourceRange()
3866 << SourceRange(TheCall->getArg(2)->getLocStart(),
3867 (*(TheCall->arg_end()-1))->getLocEnd());
3868 return true;
3869 }
3870
3871 if (TheCall->getNumArgs() < 2) {
3872 return Diag(TheCall->getLocEnd(),
3873 diag::err_typecheck_call_too_few_args_at_least)
3874 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3875 }
3876
3877 // Type-check the first argument normally.
3878 if (checkBuiltinArgument(*this, TheCall, 0))
3879 return true;
3880
3881 // Check that the current function is variadic, and get its last parameter.
3882 ParmVarDecl *LastParam;
3883 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3884 return true;
3885
3886 // Verify that the second argument to the builtin is the last argument of the
3887 // current function or method.
3888 bool SecondArgIsLastNamedArgument = false;
3889 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3890
3891 // These are valid if SecondArgIsLastNamedArgument is false after the next
3892 // block.
3893 QualType Type;
3894 SourceLocation ParamLoc;
3895 bool IsCRegister = false;
3896
3897 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3898 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3899 SecondArgIsLastNamedArgument = PV == LastParam;
3900
3901 Type = PV->getType();
3902 ParamLoc = PV->getLocation();
3903 IsCRegister =
3904 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3905 }
3906 }
3907
3908 if (!SecondArgIsLastNamedArgument)
3909 Diag(TheCall->getArg(1)->getLocStart(),
3910 diag::warn_second_arg_of_va_start_not_last_named_param);
3911 else if (IsCRegister || Type->isReferenceType() ||
3912 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3913 // Promotable integers are UB, but enumerations need a bit of
3914 // extra checking to see what their promotable type actually is.
3915 if (!Type->isPromotableIntegerType())
3916 return false;
3917 if (!Type->isEnumeralType())
3918 return true;
3919 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3920 return !(ED &&
3921 Context.typesAreCompatible(ED->getPromotionType(), Type));
3922 }()) {
3923 unsigned Reason = 0;
3924 if (Type->isReferenceType()) Reason = 1;
3925 else if (IsCRegister) Reason = 2;
3926 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3927 Diag(ParamLoc, diag::note_parameter_type) << Type;
3928 }
3929
3930 TheCall->setType(Context.VoidTy);
3931 return false;
3932}
3933
3934bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
3935 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3936 // const char *named_addr);
3937
3938 Expr *Func = Call->getCallee();
3939
3940 if (Call->getNumArgs() < 3)
3941 return Diag(Call->getLocEnd(),
3942 diag::err_typecheck_call_too_few_args_at_least)
3943 << 0 /*function call*/ << 3 << Call->getNumArgs();
3944
3945 // Type-check the first argument normally.
3946 if (checkBuiltinArgument(*this, Call, 0))
3947 return true;
3948
3949 // Check that the current function is variadic.
3950 if (checkVAStartIsInVariadicFunction(*this, Func))
3951 return true;
3952
3953 // __va_start on Windows does not validate the parameter qualifiers
3954
3955 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
3956 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
3957
3958 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
3959 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
3960
3961 const QualType &ConstCharPtrTy =
3962 Context.getPointerType(Context.CharTy.withConst());
3963 if (!Arg1Ty->isPointerType() ||
3964 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
3965 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
3966 << Arg1->getType() << ConstCharPtrTy
3967 << 1 /* different class */
3968 << 0 /* qualifier difference */
3969 << 3 /* parameter mismatch */
3970 << 2 << Arg1->getType() << ConstCharPtrTy;
3971
3972 const QualType SizeTy = Context.getSizeType();
3973 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
3974 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
3975 << Arg2->getType() << SizeTy
3976 << 1 /* different class */
3977 << 0 /* qualifier difference */
3978 << 3 /* parameter mismatch */
3979 << 3 << Arg2->getType() << SizeTy;
3980
3981 return false;
3982}
3983
3984/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3985/// friends. This is declared to take (...), so we have to check everything.
3986bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3987 if (TheCall->getNumArgs() < 2)
3988 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3989 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3990 if (TheCall->getNumArgs() > 2)
3991 return Diag(TheCall->getArg(2)->getLocStart(),
3992 diag::err_typecheck_call_too_many_args)
3993 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3994 << SourceRange(TheCall->getArg(2)->getLocStart(),
3995 (*(TheCall->arg_end()-1))->getLocEnd());
3996
3997 ExprResult OrigArg0 = TheCall->getArg(0);
3998 ExprResult OrigArg1 = TheCall->getArg(1);
3999
4000 // Do standard promotions between the two arguments, returning their common
4001 // type.
4002 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4003 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4004 return true;
4005
4006 // Make sure any conversions are pushed back into the call; this is
4007 // type safe since unordered compare builtins are declared as "_Bool
4008 // foo(...)".
4009 TheCall->setArg(0, OrigArg0.get());
4010 TheCall->setArg(1, OrigArg1.get());
4011
4012 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4013 return false;
4014
4015 // If the common type isn't a real floating type, then the arguments were
4016 // invalid for this operation.
4017 if (Res.isNull() || !Res->isRealFloatingType())
4018 return Diag(OrigArg0.get()->getLocStart(),
4019 diag::err_typecheck_call_invalid_ordered_compare)
4020 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4021 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4022
4023 return false;
4024}
4025
4026/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4027/// __builtin_isnan and friends. This is declared to take (...), so we have
4028/// to check everything. We expect the last argument to be a floating point
4029/// value.
4030bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4031 if (TheCall->getNumArgs() < NumArgs)
4032 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4033 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4034 if (TheCall->getNumArgs() > NumArgs)
4035 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4036 diag::err_typecheck_call_too_many_args)
4037 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4038 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4039 (*(TheCall->arg_end()-1))->getLocEnd());
4040
4041 Expr *OrigArg = TheCall->getArg(NumArgs-1);
4042
4043 if (OrigArg->isTypeDependent())
4044 return false;
4045
4046 // This operation requires a non-_Complex floating-point number.
4047 if (!OrigArg->getType()->isRealFloatingType())
4048 return Diag(OrigArg->getLocStart(),
4049 diag::err_typecheck_call_invalid_unary_fp)
4050 << OrigArg->getType() << OrigArg->getSourceRange();
4051
4052 // If this is an implicit conversion from float -> float or double, remove it.
4053 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4054 // Only remove standard FloatCasts, leaving other casts inplace
4055 if (Cast->getCastKind() == CK_FloatingCast) {
4056 Expr *CastArg = Cast->getSubExpr();
4057 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4058 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||(((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float)) && "promotion from float to either float or double is the only expected cast here"
) ? static_cast<void> (0) : __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && \"promotion from float to either float or double is the only expected cast here\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4060, __PRETTY_FUNCTION__))
4059 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&(((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float)) && "promotion from float to either float or double is the only expected cast here"
) ? static_cast<void> (0) : __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && \"promotion from float to either float or double is the only expected cast here\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4060, __PRETTY_FUNCTION__))
4060 "promotion from float to either float or double is the only expected cast here")(((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float)) && "promotion from float to either float or double is the only expected cast here"
) ? static_cast<void> (0) : __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && \"promotion from float to either float or double is the only expected cast here\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4060, __PRETTY_FUNCTION__))
;
4061 Cast->setSubExpr(nullptr);
4062 TheCall->setArg(NumArgs-1, CastArg);
4063 }
4064 }
4065 }
4066
4067 return false;
4068}
4069
4070// Customized Sema Checking for VSX builtins that have the following signature:
4071// vector [...] builtinName(vector [...], vector [...], const int);
4072// Which takes the same type of vectors (any legal vector type) for the first
4073// two arguments and takes compile time constant for the third argument.
4074// Example builtins are :
4075// vector double vec_xxpermdi(vector double, vector double, int);
4076// vector short vec_xxsldwi(vector short, vector short, int);
4077bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4078 unsigned ExpectedNumArgs = 3;
4079 if (TheCall->getNumArgs() < ExpectedNumArgs)
4080 return Diag(TheCall->getLocEnd(),
4081 diag::err_typecheck_call_too_few_args_at_least)
4082 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4083 << TheCall->getSourceRange();
4084
4085 if (TheCall->getNumArgs() > ExpectedNumArgs)
4086 return Diag(TheCall->getLocEnd(),
4087 diag::err_typecheck_call_too_many_args_at_most)
4088 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4089 << TheCall->getSourceRange();
4090
4091 // Check the third argument is a compile time constant
4092 llvm::APSInt Value;
4093 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4094 return Diag(TheCall->getLocStart(),
4095 diag::err_vsx_builtin_nonconstant_argument)
4096 << 3 /* argument index */ << TheCall->getDirectCallee()
4097 << SourceRange(TheCall->getArg(2)->getLocStart(),
4098 TheCall->getArg(2)->getLocEnd());
4099
4100 QualType Arg1Ty = TheCall->getArg(0)->getType();
4101 QualType Arg2Ty = TheCall->getArg(1)->getType();
4102
4103 // Check the type of argument 1 and argument 2 are vectors.
4104 SourceLocation BuiltinLoc = TheCall->getLocStart();
4105 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4106 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4107 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4108 << TheCall->getDirectCallee()
4109 << SourceRange(TheCall->getArg(0)->getLocStart(),
4110 TheCall->getArg(1)->getLocEnd());
4111 }
4112
4113 // Check the first two arguments are the same type.
4114 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4115 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4116 << TheCall->getDirectCallee()
4117 << SourceRange(TheCall->getArg(0)->getLocStart(),
4118 TheCall->getArg(1)->getLocEnd());
4119 }
4120
4121 // When default clang type checking is turned off and the customized type
4122 // checking is used, the returning type of the function must be explicitly
4123 // set. Otherwise it is _Bool by default.
4124 TheCall->setType(Arg1Ty);
4125
4126 return false;
4127}
4128
4129/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4130// This is declared to take (...), so we have to check everything.
4131ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4132 if (TheCall->getNumArgs() < 2)
4133 return ExprError(Diag(TheCall->getLocEnd(),
4134 diag::err_typecheck_call_too_few_args_at_least)
4135 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4136 << TheCall->getSourceRange());
4137
4138 // Determine which of the following types of shufflevector we're checking:
4139 // 1) unary, vector mask: (lhs, mask)
4140 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4141 QualType resType = TheCall->getArg(0)->getType();
4142 unsigned numElements = 0;
4143
4144 if (!TheCall->getArg(0)->isTypeDependent() &&
4145 !TheCall->getArg(1)->isTypeDependent()) {
4146 QualType LHSType = TheCall->getArg(0)->getType();
4147 QualType RHSType = TheCall->getArg(1)->getType();
4148
4149 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4150 return ExprError(Diag(TheCall->getLocStart(),
4151 diag::err_vec_builtin_non_vector)
4152 << TheCall->getDirectCallee()
4153 << SourceRange(TheCall->getArg(0)->getLocStart(),
4154 TheCall->getArg(1)->getLocEnd()));
4155
4156 numElements = LHSType->getAs<VectorType>()->getNumElements();
4157 unsigned numResElements = TheCall->getNumArgs() - 2;
4158
4159 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4160 // with mask. If so, verify that RHS is an integer vector type with the
4161 // same number of elts as lhs.
4162 if (TheCall->getNumArgs() == 2) {
4163 if (!RHSType->hasIntegerRepresentation() ||
4164 RHSType->getAs<VectorType>()->getNumElements() != numElements)
4165 return ExprError(Diag(TheCall->getLocStart(),
4166 diag::err_vec_builtin_incompatible_vector)
4167 << TheCall->getDirectCallee()
4168 << SourceRange(TheCall->getArg(1)->getLocStart(),
4169 TheCall->getArg(1)->getLocEnd()));
4170 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4171 return ExprError(Diag(TheCall->getLocStart(),
4172 diag::err_vec_builtin_incompatible_vector)
4173 << TheCall->getDirectCallee()
4174 << SourceRange(TheCall->getArg(0)->getLocStart(),
4175 TheCall->getArg(1)->getLocEnd()));
4176 } else if (numElements != numResElements) {
4177 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4178 resType = Context.getVectorType(eltType, numResElements,
4179 VectorType::GenericVector);
4180 }
4181 }
4182
4183 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4184 if (TheCall->getArg(i)->isTypeDependent() ||
4185 TheCall->getArg(i)->isValueDependent())
4186 continue;
4187
4188 llvm::APSInt Result(32);
4189 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4190 return ExprError(Diag(TheCall->getLocStart(),
4191 diag::err_shufflevector_nonconstant_argument)
4192 << TheCall->getArg(i)->getSourceRange());
4193
4194 // Allow -1 which will be translated to undef in the IR.
4195 if (Result.isSigned() && Result.isAllOnesValue())
4196 continue;
4197
4198 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4199 return ExprError(Diag(TheCall->getLocStart(),
4200 diag::err_shufflevector_argument_too_large)
4201 << TheCall->getArg(i)->getSourceRange());
4202 }
4203
4204 SmallVector<Expr*, 32> exprs;
4205
4206 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4207 exprs.push_back(TheCall->getArg(i));
4208 TheCall->setArg(i, nullptr);
4209 }
4210
4211 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4212 TheCall->getCallee()->getLocStart(),
4213 TheCall->getRParenLoc());
4214}
4215
4216/// SemaConvertVectorExpr - Handle __builtin_convertvector
4217ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4218 SourceLocation BuiltinLoc,
4219 SourceLocation RParenLoc) {
4220 ExprValueKind VK = VK_RValue;
4221 ExprObjectKind OK = OK_Ordinary;
4222 QualType DstTy = TInfo->getType();
4223 QualType SrcTy = E->getType();
4224
4225 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4226 return ExprError(Diag(BuiltinLoc,
4227 diag::err_convertvector_non_vector)
4228 << E->getSourceRange());
4229 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4230 return ExprError(Diag(BuiltinLoc,
4231 diag::err_convertvector_non_vector_type));
4232
4233 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4234 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4235 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4236 if (SrcElts != DstElts)
4237 return ExprError(Diag(BuiltinLoc,
4238 diag::err_convertvector_incompatible_vector)
4239 << E->getSourceRange());
4240 }
4241
4242 return new (Context)
4243 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4244}
4245
4246/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4247// This is declared to take (const void*, ...) and can take two
4248// optional constant int args.
4249bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4250 unsigned NumArgs = TheCall->getNumArgs();
4251
4252 if (NumArgs > 3)
4253 return Diag(TheCall->getLocEnd(),
4254 diag::err_typecheck_call_too_many_args_at_most)
4255 << 0 /*function call*/ << 3 << NumArgs
4256 << TheCall->getSourceRange();
4257
4258 // Argument 0 is checked for us and the remaining arguments must be
4259 // constant integers.
4260 for (unsigned i = 1; i != NumArgs; ++i)
4261 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4262 return true;
4263
4264 return false;
4265}
4266
4267/// SemaBuiltinAssume - Handle __assume (MS Extension).
4268// __assume does not evaluate its arguments, and should warn if its argument
4269// has side effects.
4270bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4271 Expr *Arg = TheCall->getArg(0);
4272 if (Arg->isInstantiationDependent()) return false;
4273
4274 if (Arg->HasSideEffects(Context))
4275 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4276 << Arg->getSourceRange()
4277 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4278
4279 return false;
4280}
4281
4282/// Handle __builtin_alloca_with_align. This is declared
4283/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4284/// than 8.
4285bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4286 // The alignment must be a constant integer.
4287 Expr *Arg = TheCall->getArg(1);
4288
4289 // We can't check the value of a dependent argument.
4290 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4291 if (const auto *UE =
4292 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4293 if (UE->getKind() == UETT_AlignOf)
4294 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4295 << Arg->getSourceRange();
4296
4297 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4298
4299 if (!Result.isPowerOf2())
4300 return Diag(TheCall->getLocStart(),
4301 diag::err_alignment_not_power_of_two)
4302 << Arg->getSourceRange();
4303
4304 if (Result < Context.getCharWidth())
4305 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4306 << (unsigned)Context.getCharWidth()
4307 << Arg->getSourceRange();
4308
4309 if (Result > INT32_MAX(2147483647))
4310 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4311 << INT32_MAX(2147483647)
4312 << Arg->getSourceRange();
4313 }
4314
4315 return false;
4316}
4317
4318/// Handle __builtin_assume_aligned. This is declared
4319/// as (const void*, size_t, ...) and can take one optional constant int arg.
4320bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4321 unsigned NumArgs = TheCall->getNumArgs();
4322
4323 if (NumArgs > 3)
4324 return Diag(TheCall->getLocEnd(),
4325 diag::err_typecheck_call_too_many_args_at_most)
4326 << 0 /*function call*/ << 3 << NumArgs
4327 << TheCall->getSourceRange();
4328
4329 // The alignment must be a constant integer.
4330 Expr *Arg = TheCall->getArg(1);
4331
4332 // We can't check the value of a dependent argument.
4333 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4334 llvm::APSInt Result;
4335 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4336 return true;
4337
4338 if (!Result.isPowerOf2())
4339 return Diag(TheCall->getLocStart(),
4340 diag::err_alignment_not_power_of_two)
4341 << Arg->getSourceRange();
4342 }
4343
4344 if (NumArgs > 2) {
4345 ExprResult Arg(TheCall->getArg(2));
4346 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4347 Context.getSizeType(), false);
4348 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4349 if (Arg.isInvalid()) return true;
4350 TheCall->setArg(2, Arg.get());
4351 }
4352
4353 return false;
4354}
4355
4356bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4357 unsigned BuiltinID =
4358 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4359 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4360
4361 unsigned NumArgs = TheCall->getNumArgs();
4362 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4363 if (NumArgs < NumRequiredArgs) {
4364 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4365 << 0 /* function call */ << NumRequiredArgs << NumArgs
4366 << TheCall->getSourceRange();
4367 }
4368 if (NumArgs >= NumRequiredArgs + 0x100) {
4369 return Diag(TheCall->getLocEnd(),
4370 diag::err_typecheck_call_too_many_args_at_most)
4371 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4372 << TheCall->getSourceRange();
4373 }
4374 unsigned i = 0;
4375
4376 // For formatting call, check buffer arg.
4377 if (!IsSizeCall) {
4378 ExprResult Arg(TheCall->getArg(i));
4379 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4380 Context, Context.VoidPtrTy, false);
4381 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4382 if (Arg.isInvalid())
4383 return true;
4384 TheCall->setArg(i, Arg.get());
4385 i++;
4386 }
4387
4388 // Check string literal arg.
4389 unsigned FormatIdx = i;
4390 {
4391 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4392 if (Arg.isInvalid())
4393 return true;
4394 TheCall->setArg(i, Arg.get());
4395 i++;
4396 }
4397
4398 // Make sure variadic args are scalar.
4399 unsigned FirstDataArg = i;
4400 while (i < NumArgs) {
4401 ExprResult Arg = DefaultVariadicArgumentPromotion(
4402 TheCall->getArg(i), VariadicFunction, nullptr);
4403 if (Arg.isInvalid())
4404 return true;
4405 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4406 if (ArgSize.getQuantity() >= 0x100) {
4407 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4408 << i << (int)ArgSize.getQuantity() << 0xff
4409 << TheCall->getSourceRange();
4410 }
4411 TheCall->setArg(i, Arg.get());
4412 i++;
4413 }
4414
4415 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4416 // call to avoid duplicate diagnostics.
4417 if (!IsSizeCall) {
4418 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4419 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4420 bool Success = CheckFormatArguments(
4421 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4422 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4423 CheckedVarArgs);
4424 if (!Success)
4425 return true;
4426 }
4427
4428 if (IsSizeCall) {
4429 TheCall->setType(Context.getSizeType());
4430 } else {
4431 TheCall->setType(Context.VoidPtrTy);
4432 }
4433 return false;
4434}
4435
4436/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4437/// TheCall is a constant expression.
4438bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4439 llvm::APSInt &Result) {
4440 Expr *Arg = TheCall->getArg(ArgNum);
4441 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4442 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4443
4444 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4445
4446 if (!Arg->isIntegerConstantExpr(Result, Context))
4447 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4448 << FDecl->getDeclName() << Arg->getSourceRange();
4449
4450 return false;
4451}
4452
4453/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4454/// TheCall is a constant expression in the range [Low, High].
4455bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4456 int Low, int High) {
4457 llvm::APSInt Result;
4458
4459 // We can't check the value of a dependent argument.
4460 Expr *Arg = TheCall->getArg(ArgNum);
4461 if (Arg->isTypeDependent() || Arg->isValueDependent())
4462 return false;
4463
4464 // Check constant-ness first.
4465 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4466 return true;
4467
4468 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4469 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4470 << Low << High << Arg->getSourceRange();
4471
4472 return false;
4473}
4474
4475/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4476/// TheCall is a constant expression is a multiple of Num..
4477bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4478 unsigned Num) {
4479 llvm::APSInt Result;
4480
4481 // We can't check the value of a dependent argument.
4482 Expr *Arg = TheCall->getArg(ArgNum);
4483 if (Arg->isTypeDependent() || Arg->isValueDependent())
4484 return false;
4485
4486 // Check constant-ness first.
4487 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4488 return true;
4489
4490 if (Result.getSExtValue() % Num != 0)
4491 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4492 << Num << Arg->getSourceRange();
4493
4494 return false;
4495}
4496
4497/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4498/// TheCall is an ARM/AArch64 special register string literal.
4499bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4500 int ArgNum, unsigned ExpectedFieldNum,
4501 bool AllowName) {
4502 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4503 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4504 BuiltinID == ARM::BI__builtin_arm_rsr ||
4505 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4506 BuiltinID == ARM::BI__builtin_arm_wsr ||
4507 BuiltinID == ARM::BI__builtin_arm_wsrp;
4508 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4509 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4510 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4511 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4512 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4513 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4514 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.")(((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."
) ? static_cast<void> (0) : __assert_fail ("(IsARMBuiltin || IsAArch64Builtin) && \"Unexpected ARM builtin.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4514, __PRETTY_FUNCTION__))
;
4515
4516 // We can't check the value of a dependent argument.
4517 Expr *Arg = TheCall->getArg(ArgNum);
4518 if (Arg->isTypeDependent() || Arg->isValueDependent())
4519 return false;
4520
4521 // Check if the argument is a string literal.
4522 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4523 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4524 << Arg->getSourceRange();
4525
4526 // Check the type of special register given.
4527 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4528 SmallVector<StringRef, 6> Fields;
4529 Reg.split(Fields, ":");
4530
4531 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4532 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4533 << Arg->getSourceRange();
4534
4535 // If the string is the name of a register then we cannot check that it is
4536 // valid here but if the string is of one the forms described in ACLE then we
4537 // can check that the supplied fields are integers and within the valid
4538 // ranges.
4539 if (Fields.size() > 1) {
4540 bool FiveFields = Fields.size() == 5;
4541
4542 bool ValidString = true;
4543 if (IsARMBuiltin) {
4544 ValidString &= Fields[0].startswith_lower("cp") ||
4545 Fields[0].startswith_lower("p");
4546 if (ValidString)
4547 Fields[0] =
4548 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4549
4550 ValidString &= Fields[2].startswith_lower("c");
4551 if (ValidString)
4552 Fields[2] = Fields[2].drop_front(1);
4553
4554 if (FiveFields) {
4555 ValidString &= Fields[3].startswith_lower("c");
4556 if (ValidString)
4557 Fields[3] = Fields[3].drop_front(1);
4558 }
4559 }
4560
4561 SmallVector<int, 5> Ranges;
4562 if (FiveFields)
4563 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4564 else
4565 Ranges.append({15, 7, 15});
4566
4567 for (unsigned i=0; i<Fields.size(); ++i) {
4568 int IntField;
4569 ValidString &= !Fields[i].getAsInteger(10, IntField);
4570 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4571 }
4572
4573 if (!ValidString)
4574 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4575 << Arg->getSourceRange();
4576
4577 } else if (IsAArch64Builtin && Fields.size() == 1) {
4578 // If the register name is one of those that appear in the condition below
4579 // and the special register builtin being used is one of the write builtins,
4580 // then we require that the argument provided for writing to the register
4581 // is an integer constant expression. This is because it will be lowered to
4582 // an MSR (immediate) instruction, so we need to know the immediate at
4583 // compile time.
4584 if (TheCall->getNumArgs() != 2)
4585 return false;
4586
4587 std::string RegLower = Reg.lower();
4588 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4589 RegLower != "pan" && RegLower != "uao")
4590 return false;
4591
4592 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4593 }
4594
4595 return false;
4596}
4597
4598/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4599/// This checks that the target supports __builtin_longjmp and
4600/// that val is a constant 1.
4601bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4602 if (!Context.getTargetInfo().hasSjLjLowering())
4603 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4604 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4605
4606 Expr *Arg = TheCall->getArg(1);
4607 llvm::APSInt Result;
4608
4609 // TODO: This is less than ideal. Overload this to take a value.
4610 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4611 return true;
4612
4613 if (Result != 1)
4614 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4615 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4616
4617 return false;
4618}
4619
4620/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4621/// This checks that the target supports __builtin_setjmp.
4622bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4623 if (!Context.getTargetInfo().hasSjLjLowering())
4624 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4625 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4626 return false;
4627}
4628
4629namespace {
4630class UncoveredArgHandler {
4631 enum { Unknown = -1, AllCovered = -2 };
4632 signed FirstUncoveredArg;
4633 SmallVector<const Expr *, 4> DiagnosticExprs;
4634
4635public:
4636 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4637
4638 bool hasUncoveredArg() const {
4639 return (FirstUncoveredArg >= 0);
4640 }
4641
4642 unsigned getUncoveredArg() const {
4643 assert(hasUncoveredArg() && "no uncovered argument")((hasUncoveredArg() && "no uncovered argument") ? static_cast
<void> (0) : __assert_fail ("hasUncoveredArg() && \"no uncovered argument\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4643, __PRETTY_FUNCTION__))
;
4644 return FirstUncoveredArg;
4645 }
4646
4647 void setAllCovered() {
4648 // A string has been found with all arguments covered, so clear out
4649 // the diagnostics.
4650 DiagnosticExprs.clear();
4651 FirstUncoveredArg = AllCovered;
4652 }
4653
4654 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4655 assert(NewFirstUncoveredArg >= 0 && "Outside range")((NewFirstUncoveredArg >= 0 && "Outside range") ? static_cast
<void> (0) : __assert_fail ("NewFirstUncoveredArg >= 0 && \"Outside range\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4655, __PRETTY_FUNCTION__))
;
4656
4657 // Don't update if a previous string covers all arguments.
4658 if (FirstUncoveredArg == AllCovered)
4659 return;
4660
4661 // UncoveredArgHandler tracks the highest uncovered argument index
4662 // and with it all the strings that match this index.
4663 if (NewFirstUncoveredArg == FirstUncoveredArg)
4664 DiagnosticExprs.push_back(StrExpr);
4665 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4666 DiagnosticExprs.clear();
4667 DiagnosticExprs.push_back(StrExpr);
4668 FirstUncoveredArg = NewFirstUncoveredArg;
4669 }
4670 }
4671
4672 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4673};
4674
4675enum StringLiteralCheckType {
4676 SLCT_NotALiteral,
4677 SLCT_UncheckedLiteral,
4678 SLCT_CheckedLiteral
4679};
4680} // end anonymous namespace
4681
4682static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4683 BinaryOperatorKind BinOpKind,
4684 bool AddendIsRight) {
4685 unsigned BitWidth = Offset.getBitWidth();
4686 unsigned AddendBitWidth = Addend.getBitWidth();
4687 // There might be negative interim results.
4688 if (Addend.isUnsigned()) {
4689 Addend = Addend.zext(++AddendBitWidth);
4690 Addend.setIsSigned(true);
4691 }
4692 // Adjust the bit width of the APSInts.
4693 if (AddendBitWidth > BitWidth) {
4694 Offset = Offset.sext(AddendBitWidth);
4695 BitWidth = AddendBitWidth;
4696 } else if (BitWidth > AddendBitWidth) {
4697 Addend = Addend.sext(BitWidth);
4698 }
4699
4700 bool Ov = false;
4701 llvm::APSInt ResOffset = Offset;
4702 if (BinOpKind == BO_Add)
4703 ResOffset = Offset.sadd_ov(Addend, Ov);
4704 else {
4705 assert(AddendIsRight && BinOpKind == BO_Sub &&((AddendIsRight && BinOpKind == BO_Sub && "operator must be add or sub with addend on the right"
) ? static_cast<void> (0) : __assert_fail ("AddendIsRight && BinOpKind == BO_Sub && \"operator must be add or sub with addend on the right\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4706, __PRETTY_FUNCTION__))
4706 "operator must be add or sub with addend on the right")((AddendIsRight && BinOpKind == BO_Sub && "operator must be add or sub with addend on the right"
) ? static_cast<void> (0) : __assert_fail ("AddendIsRight && BinOpKind == BO_Sub && \"operator must be add or sub with addend on the right\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4706, __PRETTY_FUNCTION__))
;
4707 ResOffset = Offset.ssub_ov(Addend, Ov);
4708 }
4709
4710 // We add an offset to a pointer here so we should support an offset as big as
4711 // possible.
4712 if (Ov) {
4713 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big")((BitWidth <= (2147483647 *2U +1U) / 2 && "index (intermediate) result too big"
) ? static_cast<void> (0) : __assert_fail ("BitWidth <= UINT_MAX / 2 && \"index (intermediate) result too big\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4713, __PRETTY_FUNCTION__))
;
4714 Offset = Offset.sext(2 * BitWidth);
4715 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4716 return;
4717 }
4718
4719 Offset = ResOffset;
4720}
4721
4722namespace {
4723// This is a wrapper class around StringLiteral to support offsetted string
4724// literals as format strings. It takes the offset into account when returning
4725// the string and its length or the source locations to display notes correctly.
4726class FormatStringLiteral {
4727 const StringLiteral *FExpr;
4728 int64_t Offset;
4729
4730 public:
4731 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4732 : FExpr(fexpr), Offset(Offset) {}
4733
4734 StringRef getString() const {
4735 return FExpr->getString().drop_front(Offset);
4736 }
4737
4738 unsigned getByteLength() const {
4739 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4740 }
4741 unsigned getLength() const { return FExpr->getLength() - Offset; }
4742 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4743
4744 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4745
4746 QualType getType() const { return FExpr->getType(); }
4747
4748 bool isAscii() const { return FExpr->isAscii(); }
4749 bool isWide() const { return FExpr->isWide(); }
4750 bool isUTF8() const { return FExpr->isUTF8(); }
4751 bool isUTF16() const { return FExpr->isUTF16(); }
4752 bool isUTF32() const { return FExpr->isUTF32(); }
4753 bool isPascal() const { return FExpr->isPascal(); }
4754
4755 SourceLocation getLocationOfByte(
4756 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4757 const TargetInfo &Target, unsigned *StartToken = nullptr,
4758 unsigned *StartTokenByteOffset = nullptr) const {
4759 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4760 StartToken, StartTokenByteOffset);
4761 }
4762
4763 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
4764 return FExpr->getLocStart().getLocWithOffset(Offset);
4765 }
4766 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return FExpr->getLocEnd(); }
4767};
4768} // end anonymous namespace
4769
4770static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4771 const Expr *OrigFormatExpr,
4772 ArrayRef<const Expr *> Args,
4773 bool HasVAListArg, unsigned format_idx,
4774 unsigned firstDataArg,
4775 Sema::FormatStringType Type,
4776 bool inFunctionCall,
4777 Sema::VariadicCallType CallType,
4778 llvm::SmallBitVector &CheckedVarArgs,
4779 UncoveredArgHandler &UncoveredArg);
4780
4781// Determine if an expression is a string literal or constant string.
4782// If this function returns false on the arguments to a function expecting a
4783// format string, we will usually need to emit a warning.
4784// True string literals are then checked by CheckFormatString.
4785static StringLiteralCheckType
4786checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4787 bool HasVAListArg, unsigned format_idx,
4788 unsigned firstDataArg, Sema::FormatStringType Type,
4789 Sema::VariadicCallType CallType, bool InFunctionCall,
4790 llvm::SmallBitVector &CheckedVarArgs,
4791 UncoveredArgHandler &UncoveredArg,
4792 llvm::APSInt Offset) {
4793 tryAgain:
4794 assert(Offset.isSigned() && "invalid offset")((Offset.isSigned() && "invalid offset") ? static_cast
<void> (0) : __assert_fail ("Offset.isSigned() && \"invalid offset\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 4794, __PRETTY_FUNCTION__))
;
4795
4796 if (E->isTypeDependent() || E->isValueDependent())
4797 return SLCT_NotALiteral;
4798
4799 E = E->IgnoreParenCasts();
4800
4801 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4802 // Technically -Wformat-nonliteral does not warn about this case.
4803 // The behavior of printf and friends in this case is implementation
4804 // dependent. Ideally if the format string cannot be null then
4805 // it should have a 'nonnull' attribute in the function prototype.
4806 return SLCT_UncheckedLiteral;
4807
4808 switch (E->getStmtClass()) {
4809 case Stmt::BinaryConditionalOperatorClass:
4810 case Stmt::ConditionalOperatorClass: {
4811 // The expression is a literal if both sub-expressions were, and it was
4812 // completely checked only if both sub-expressions were checked.
4813 const AbstractConditionalOperator *C =
4814 cast<AbstractConditionalOperator>(E);
4815
4816 // Determine whether it is necessary to check both sub-expressions, for
4817 // example, because the condition expression is a constant that can be
4818 // evaluated at compile time.
4819 bool CheckLeft = true, CheckRight = true;
4820
4821 bool Cond;
4822 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4823 if (Cond)
4824 CheckRight = false;
4825 else
4826 CheckLeft = false;
4827 }
4828
4829 // We need to maintain the offsets for the right and the left hand side
4830 // separately to check if every possible indexed expression is a valid
4831 // string literal. They might have different offsets for different string
4832 // literals in the end.
4833 StringLiteralCheckType Left;
4834 if (!CheckLeft)
4835 Left = SLCT_UncheckedLiteral;
4836 else {
4837 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4838 HasVAListArg, format_idx, firstDataArg,
4839 Type, CallType, InFunctionCall,
4840 CheckedVarArgs, UncoveredArg, Offset);
4841 if (Left == SLCT_NotALiteral || !CheckRight) {
4842 return Left;
4843 }
4844 }
4845
4846 StringLiteralCheckType Right =
4847 checkFormatStringExpr(S, C->getFalseExpr(), Args,
4848 HasVAListArg, format_idx, firstDataArg,
4849 Type, CallType, InFunctionCall, CheckedVarArgs,
4850 UncoveredArg, Offset);
4851
4852 return (CheckLeft && Left < Right) ? Left : Right;
4853 }
4854
4855 case Stmt::ImplicitCastExprClass: {
4856 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4857 goto tryAgain;
4858 }
4859
4860 case Stmt::OpaqueValueExprClass:
4861 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4862 E = src;
4863 goto tryAgain;
4864 }
4865 return SLCT_NotALiteral;
4866
4867 case Stmt::PredefinedExprClass:
4868 // While __func__, etc., are technically not string literals, they
4869 // cannot contain format specifiers and thus are not a security
4870 // liability.
4871 return SLCT_UncheckedLiteral;
4872
4873 case Stmt::DeclRefExprClass: {
4874 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4875
4876 // As an exception, do not flag errors for variables binding to
4877 // const string literals.
4878 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4879 bool isConstant = false;
4880 QualType T = DR->getType();
4881
4882 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4883 isConstant = AT->getElementType().isConstant(S.Context);
4884 } else if (const PointerType *PT = T->getAs<PointerType>()) {
4885 isConstant = T.isConstant(S.Context) &&
4886 PT->getPointeeType().isConstant(S.Context);
4887 } else if (T->isObjCObjectPointerType()) {
4888 // In ObjC, there is usually no "const ObjectPointer" type,
4889 // so don't check if the pointee type is constant.
4890 isConstant = T.isConstant(S.Context);
4891 }
4892
4893 if (isConstant) {
4894 if (const Expr *Init = VD->getAnyInitializer()) {
4895 // Look through initializers like const char c[] = { "foo" }
4896 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4897 if (InitList->isStringLiteralInit())
4898 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4899 }
4900 return checkFormatStringExpr(S, Init, Args,
4901 HasVAListArg, format_idx,
4902 firstDataArg, Type, CallType,
4903 /*InFunctionCall*/ false, CheckedVarArgs,
4904 UncoveredArg, Offset);
4905 }
4906 }
4907
4908 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4909 // special check to see if the format string is a function parameter
4910 // of the function calling the printf function. If the function
4911 // has an attribute indicating it is a printf-like function, then we
4912 // should suppress warnings concerning non-literals being used in a call
4913 // to a vprintf function. For example:
4914 //
4915 // void
4916 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4917 // va_list ap;
4918 // va_start(ap, fmt);
4919 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4920 // ...
4921 // }
4922 if (HasVAListArg) {
4923 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4924 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4925 int PVIndex = PV->getFunctionScopeIndex() + 1;
4926 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4927 // adjust for implicit parameter
4928 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4929 if (MD->isInstance())
4930 ++PVIndex;
4931 // We also check if the formats are compatible.
4932 // We can't pass a 'scanf' string to a 'printf' function.
4933 if (PVIndex == PVFormat->getFormatIdx() &&
4934 Type == S.GetFormatStringType(PVFormat))
4935 return SLCT_UncheckedLiteral;
4936 }
4937 }
4938 }
4939 }
4940 }
4941
4942 return SLCT_NotALiteral;
4943 }
4944
4945 case Stmt::CallExprClass:
4946 case Stmt::CXXMemberCallExprClass: {
4947 const CallExpr *CE = cast<CallExpr>(E);
4948 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4949 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4950 unsigned ArgIndex = FA->getFormatIdx();
4951 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4952 if (MD->isInstance())
4953 --ArgIndex;
4954 const Expr *Arg = CE->getArg(ArgIndex - 1);
4955
4956 return checkFormatStringExpr(S, Arg, Args,
4957 HasVAListArg, format_idx, firstDataArg,
4958 Type, CallType, InFunctionCall,
4959 CheckedVarArgs, UncoveredArg, Offset);
4960 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4961 unsigned BuiltinID = FD->getBuiltinID();
4962 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4963 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4964 const Expr *Arg = CE->getArg(0);
4965 return checkFormatStringExpr(S, Arg, Args,
4966 HasVAListArg, format_idx,
4967 firstDataArg, Type, CallType,
4968 InFunctionCall, CheckedVarArgs,
4969 UncoveredArg, Offset);
4970 }
4971 }
4972 }
4973
4974 return SLCT_NotALiteral;
4975 }
4976 case Stmt::ObjCMessageExprClass: {
4977 const auto *ME = cast<ObjCMessageExpr>(E);
4978 if (const auto *ND = ME->getMethodDecl()) {
4979 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4980 unsigned ArgIndex = FA->getFormatIdx();
4981 const Expr *Arg = ME->getArg(ArgIndex - 1);
4982 return checkFormatStringExpr(
4983 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4984 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4985 }
4986 }
4987
4988 return SLCT_NotALiteral;
4989 }
4990 case Stmt::ObjCStringLiteralClass:
4991 case Stmt::StringLiteralClass: {
4992 const StringLiteral *StrE = nullptr;
4993
4994 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4995 StrE = ObjCFExpr->getString();
4996 else
4997 StrE = cast<StringLiteral>(E);
4998
4999 if (StrE) {
5000 if (Offset.isNegative() || Offset > StrE->getLength()) {
5001 // TODO: It would be better to have an explicit warning for out of
5002 // bounds literals.
5003 return SLCT_NotALiteral;
5004 }
5005 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5006 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5007 firstDataArg, Type, InFunctionCall, CallType,
5008 CheckedVarArgs, UncoveredArg);
5009 return SLCT_CheckedLiteral;
5010 }
5011
5012 return SLCT_NotALiteral;
5013 }
5014 case Stmt::BinaryOperatorClass: {
5015 llvm::APSInt LResult;
5016 llvm::APSInt RResult;
5017
5018 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5019
5020 // A string literal + an int offset is still a string literal.
5021 if (BinOp->isAdditiveOp()) {
5022 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5023 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5024
5025 if (LIsInt != RIsInt) {
5026 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5027
5028 if (LIsInt) {
5029 if (BinOpKind == BO_Add) {
5030 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5031 E = BinOp->getRHS();
5032 goto tryAgain;
5033 }
5034 } else {
5035 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5036 E = BinOp->getLHS();
5037 goto tryAgain;
5038 }
5039 }
5040 }
5041
5042 return SLCT_NotALiteral;
5043 }
5044 case Stmt::UnaryOperatorClass: {
5045 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5046 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5047 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5048 llvm::APSInt IndexResult;
5049 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5050 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5051 E = ASE->getBase();
5052 goto tryAgain;
5053 }
5054 }
5055
5056 return SLCT_NotALiteral;
5057 }
5058
5059 default:
5060 return SLCT_NotALiteral;
5061 }
5062}
5063
5064Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5065 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5066 .Case("scanf", FST_Scanf)
5067 .Cases("printf", "printf0", FST_Printf)
5068 .Cases("NSString", "CFString", FST_NSString)
5069 .Case("strftime", FST_Strftime)
5070 .Case("strfmon", FST_Strfmon)
5071 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5072 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5073 .Case("os_trace", FST_OSLog)
5074 .Case("os_log", FST_OSLog)
5075 .Default(FST_Unknown);
5076}
5077
5078/// CheckFormatArguments - Check calls to printf and scanf (and similar
5079/// functions) for correct use of format strings.
5080/// Returns true if a format string has been fully checked.
5081bool Sema::CheckFormatArguments(const FormatAttr *Format,
5082 ArrayRef<const Expr *> Args,
5083 bool IsCXXMember,
5084 VariadicCallType CallType,
5085 SourceLocation Loc, SourceRange Range,
5086 llvm::SmallBitVector &CheckedVarArgs) {
5087 FormatStringInfo FSI;
5088 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5089 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5090 FSI.FirstDataArg, GetFormatStringType(Format),
5091 CallType, Loc, Range, CheckedVarArgs);
5092 return false;
5093}
5094
5095bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5096 bool HasVAListArg, unsigned format_idx,
5097 unsigned firstDataArg, FormatStringType Type,
5098 VariadicCallType CallType,
5099 SourceLocation Loc, SourceRange Range,
5100 llvm::SmallBitVector &CheckedVarArgs) {
5101 // CHECK: printf/scanf-like function is called with no format string.
5102 if (format_idx >= Args.size()) {
5103 Diag(Loc, diag::warn_missing_format_string) << Range;
5104 return false;
5105 }
5106
5107 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5108
5109 // CHECK: format string is not a string literal.
5110 //
5111 // Dynamically generated format strings are difficult to
5112 // automatically vet at compile time. Requiring that format strings
5113 // are string literals: (1) permits the checking of format strings by
5114 // the compiler and thereby (2) can practically remove the source of
5115 // many format string exploits.
5116
5117 // Format string can be either ObjC string (e.g. @"%d") or
5118 // C string (e.g. "%d")
5119 // ObjC string uses the same format specifiers as C string, so we can use
5120 // the same format string checking logic for both ObjC and C strings.
5121 UncoveredArgHandler UncoveredArg;
5122 StringLiteralCheckType CT =
5123 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5124 format_idx, firstDataArg, Type, CallType,
5125 /*IsFunctionCall*/ true, CheckedVarArgs,
5126 UncoveredArg,
5127 /*no string offset*/ llvm::APSInt(64, false) = 0);
5128
5129 // Generate a diagnostic where an uncovered argument is detected.
5130 if (UncoveredArg.hasUncoveredArg()) {
5131 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5132 assert(ArgIdx < Args.size() && "ArgIdx outside bounds")((ArgIdx < Args.size() && "ArgIdx outside bounds")
? static_cast<void> (0) : __assert_fail ("ArgIdx < Args.size() && \"ArgIdx outside bounds\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 5132, __PRETTY_FUNCTION__))
;
5133 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5134 }
5135
5136 if (CT != SLCT_NotALiteral)
5137 // Literal format string found, check done!
5138 return CT == SLCT_CheckedLiteral;
5139
5140 // Strftime is particular as it always uses a single 'time' argument,
5141 // so it is safe to pass a non-literal string.
5142 if (Type == FST_Strftime)
5143 return false;
5144
5145 // Do not emit diag when the string param is a macro expansion and the
5146 // format is either NSString or CFString. This is a hack to prevent
5147 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5148 // which are usually used in place of NS and CF string literals.
5149 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5150 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5151 return false;
5152
5153 // If there are no arguments specified, warn with -Wformat-security, otherwise
5154 // warn only with -Wformat-nonliteral.
5155 if (Args.size() == firstDataArg) {
5156 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5157 << OrigFormatExpr->getSourceRange();
5158 switch (Type) {
5159 default:
5160 break;
5161 case FST_Kprintf:
5162 case FST_FreeBSDKPrintf:
5163 case FST_Printf:
5164 Diag(FormatLoc, diag::note_format_security_fixit)
5165 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5166 break;
5167 case FST_NSString:
5168 Diag(FormatLoc, diag::note_format_security_fixit)
5169 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5170 break;
5171 }
5172 } else {
5173 Diag(FormatLoc, diag::warn_format_nonliteral)
5174 << OrigFormatExpr->getSourceRange();
5175 }
5176 return false;
5177}
5178
5179namespace {
5180class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5181protected:
5182 Sema &S;
5183 const FormatStringLiteral *FExpr;
5184 const Expr *OrigFormatExpr;
5185 const Sema::FormatStringType FSType;
5186 const unsigned FirstDataArg;
5187 const unsigned NumDataArgs;
5188 const char *Beg; // Start of format string.
5189 const bool HasVAListArg;
5190 ArrayRef<const Expr *> Args;
5191 unsigned FormatIdx;
5192 llvm::SmallBitVector CoveredArgs;
5193 bool usesPositionalArgs;
5194 bool atFirstArg;
5195 bool inFunctionCall;
5196 Sema::VariadicCallType CallType;
5197 llvm::SmallBitVector &CheckedVarArgs;
5198 UncoveredArgHandler &UncoveredArg;
5199
5200public:
5201 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5202 const Expr *origFormatExpr,
5203 const Sema::FormatStringType type, unsigned firstDataArg,
5204 unsigned numDataArgs, const char *beg, bool hasVAListArg,
5205 ArrayRef<const Expr *> Args, unsigned formatIdx,
5206 bool inFunctionCall, Sema::VariadicCallType callType,
5207 llvm::SmallBitVector &CheckedVarArgs,
5208 UncoveredArgHandler &UncoveredArg)
5209 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5210 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5211 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5212 usesPositionalArgs(false), atFirstArg(true),
5213 inFunctionCall(inFunctionCall), CallType(callType),
5214 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5215 CoveredArgs.resize(numDataArgs);
5216 CoveredArgs.reset();
5217 }
5218
5219 void DoneProcessing();
5220
5221 void HandleIncompleteSpecifier(const char *startSpecifier,
5222 unsigned specifierLen) override;
5223
5224 void HandleInvalidLengthModifier(
5225 const analyze_format_string::FormatSpecifier &FS,
5226 const analyze_format_string::ConversionSpecifier &CS,
5227 const char *startSpecifier, unsigned specifierLen,
5228 unsigned DiagID);
5229
5230 void HandleNonStandardLengthModifier(
5231 const analyze_format_string::FormatSpecifier &FS,
5232 const char *startSpecifier, unsigned specifierLen);
5233
5234 void HandleNonStandardConversionSpecifier(
5235 const analyze_format_string::ConversionSpecifier &CS,
5236 const char *startSpecifier, unsigned specifierLen);
5237
5238 void HandlePosition(const char *startPos, unsigned posLen) override;
5239
5240 void HandleInvalidPosition(const char *startSpecifier,
5241 unsigned specifierLen,
5242 analyze_format_string::PositionContext p) override;
5243
5244 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5245
5246 void HandleNullChar(const char *nullCharacter) override;
5247
5248 template <typename Range>
5249 static void
5250 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5251 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5252 bool IsStringLocation, Range StringRange,
5253 ArrayRef<FixItHint> Fixit = None);
5254
5255protected:
5256 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5257 const char *startSpec,
5258 unsigned specifierLen,
5259 const char *csStart, unsigned csLen);
5260
5261 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5262 const char *startSpec,
5263 unsigned specifierLen);
5264
5265 SourceRange getFormatStringRange();
5266 CharSourceRange getSpecifierRange(const char *startSpecifier,
5267 unsigned specifierLen);
5268 SourceLocation getLocationOfByte(const char *x);
5269
5270 const Expr *getDataArg(unsigned i) const;
5271
5272 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5273 const analyze_format_string::ConversionSpecifier &CS,
5274 const char *startSpecifier, unsigned specifierLen,
5275 unsigned argIndex);
5276
5277 template <typename Range>
5278 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5279 bool IsStringLocation, Range StringRange,
5280 ArrayRef<FixItHint> Fixit = None);
5281};
5282} // end anonymous namespace
5283
5284SourceRange CheckFormatHandler::getFormatStringRange() {
5285 return OrigFormatExpr->getSourceRange();
5286}
5287
5288CharSourceRange CheckFormatHandler::
5289getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5290 SourceLocation Start = getLocationOfByte(startSpecifier);
5291 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5292
5293 // Advance the end SourceLocation by one due to half-open ranges.
5294 End = End.getLocWithOffset(1);
5295
5296 return CharSourceRange::getCharRange(Start, End);
5297}
5298
5299SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5300 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5301 S.getLangOpts(), S.Context.getTargetInfo());
5302}
5303
5304void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5305 unsigned specifierLen){
5306 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5307 getLocationOfByte(startSpecifier),
5308 /*IsStringLocation*/true,
5309 getSpecifierRange(startSpecifier, specifierLen));
5310}
5311
5312void CheckFormatHandler::HandleInvalidLengthModifier(
5313 const analyze_format_string::FormatSpecifier &FS,
5314 const analyze_format_string::ConversionSpecifier &CS,
5315 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5316 using namespace analyze_format_string;
5317
5318 const LengthModifier &LM = FS.getLengthModifier();
5319 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5320
5321 // See if we know how to fix this length modifier.
5322 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5323 if (FixedLM) {
5324 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5325 getLocationOfByte(LM.getStart()),
5326 /*IsStringLocation*/true,
5327 getSpecifierRange(startSpecifier, specifierLen));
5328
5329 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5330 << FixedLM->toString()
5331 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5332
5333 } else {
5334 FixItHint Hint;
5335 if (DiagID == diag::warn_format_nonsensical_length)
5336 Hint = FixItHint::CreateRemoval(LMRange);
5337
5338 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5339 getLocationOfByte(LM.getStart()),
5340 /*IsStringLocation*/true,
5341 getSpecifierRange(startSpecifier, specifierLen),
5342 Hint);
5343 }
5344}
5345
5346void CheckFormatHandler::HandleNonStandardLengthModifier(
5347 const analyze_format_string::FormatSpecifier &FS,
5348 const char *startSpecifier, unsigned specifierLen) {
5349 using namespace analyze_format_string;
5350
5351 const LengthModifier &LM = FS.getLengthModifier();
5352 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5353
5354 // See if we know how to fix this length modifier.
5355 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5356 if (FixedLM) {
5357 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5358 << LM.toString() << 0,
5359 getLocationOfByte(LM.getStart()),
5360 /*IsStringLocation*/true,
5361 getSpecifierRange(startSpecifier, specifierLen));
5362
5363 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5364 << FixedLM->toString()
5365 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5366
5367 } else {
5368 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5369 << LM.toString() << 0,
5370 getLocationOfByte(LM.getStart()),
5371 /*IsStringLocation*/true,
5372 getSpecifierRange(startSpecifier, specifierLen));
5373 }
5374}
5375
5376void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5377 const analyze_format_string::ConversionSpecifier &CS,
5378 const char *startSpecifier, unsigned specifierLen) {
5379 using namespace analyze_format_string;
5380
5381 // See if we know how to fix this conversion specifier.
5382 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5383 if (FixedCS) {
5384 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5385 << CS.toString() << /*conversion specifier*/1,
5386 getLocationOfByte(CS.getStart()),
5387 /*IsStringLocation*/true,
5388 getSpecifierRange(startSpecifier, specifierLen));
5389
5390 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5391 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5392 << FixedCS->toString()
5393 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5394 } else {
5395 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5396 << CS.toString() << /*conversion specifier*/1,
5397 getLocationOfByte(CS.getStart()),
5398 /*IsStringLocation*/true,
5399 getSpecifierRange(startSpecifier, specifierLen));
5400 }
5401}
5402
5403void CheckFormatHandler::HandlePosition(const char *startPos,
5404 unsigned posLen) {
5405 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5406 getLocationOfByte(startPos),
5407 /*IsStringLocation*/true,
5408 getSpecifierRange(startPos, posLen));
5409}
5410
5411void
5412CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5413 analyze_format_string::PositionContext p) {
5414 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5415 << (unsigned) p,
5416 getLocationOfByte(startPos), /*IsStringLocation*/true,
5417 getSpecifierRange(startPos, posLen));
5418}
5419
5420void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5421 unsigned posLen) {
5422 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5423 getLocationOfByte(startPos),
5424 /*IsStringLocation*/true,
5425 getSpecifierRange(startPos, posLen));
5426}
5427
5428void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5429 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5430 // The presence of a null character is likely an error.
5431 EmitFormatDiagnostic(
5432 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5433 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5434 getFormatStringRange());
5435 }
5436}
5437
5438// Note that this may return NULL if there was an error parsing or building
5439// one of the argument expressions.
5440const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5441 return Args[FirstDataArg + i];
5442}
5443
5444void CheckFormatHandler::DoneProcessing() {
5445 // Does the number of data arguments exceed the number of
5446 // format conversions in the format string?
5447 if (!HasVAListArg) {
5448 // Find any arguments that weren't covered.
5449 CoveredArgs.flip();
5450 signed notCoveredArg = CoveredArgs.find_first();
5451 if (notCoveredArg >= 0) {
5452 assert((unsigned)notCoveredArg < NumDataArgs)(((unsigned)notCoveredArg < NumDataArgs) ? static_cast<
void> (0) : __assert_fail ("(unsigned)notCoveredArg < NumDataArgs"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 5452, __PRETTY_FUNCTION__))
;
5453 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5454 } else {
5455 UncoveredArg.setAllCovered();
5456 }
5457 }
5458}
5459
5460void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5461 const Expr *ArgExpr) {
5462 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&((hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
"Invalid state") ? static_cast<void> (0) : __assert_fail
("hasUncoveredArg() && DiagnosticExprs.size() > 0 && \"Invalid state\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 5463, __PRETTY_FUNCTION__))
5463 "Invalid state")((hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
"Invalid state") ? static_cast<void> (0) : __assert_fail
("hasUncoveredArg() && DiagnosticExprs.size() > 0 && \"Invalid state\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 5463, __PRETTY_FUNCTION__))
;
5464
5465 if (!ArgExpr)
5466 return;
5467
5468 SourceLocation Loc = ArgExpr->getLocStart();
5469
5470 if (S.getSourceManager().isInSystemMacro(Loc))
5471 return;
5472
5473 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5474 for (auto E : DiagnosticExprs)
5475 PDiag << E->getSourceRange();
5476
5477 CheckFormatHandler::EmitFormatDiagnostic(
5478 S, IsFunctionCall, DiagnosticExprs[0],
5479 PDiag, Loc, /*IsStringLocation*/false,
5480 DiagnosticExprs[0]->getSourceRange());
5481}
5482
5483bool
5484CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5485 SourceLocation Loc,
5486 const char *startSpec,
5487 unsigned specifierLen,
5488 const char *csStart,
5489 unsigned csLen) {
5490 bool keepGoing = true;
5491 if (argIndex < NumDataArgs) {
5492 // Consider the argument coverered, even though the specifier doesn't
5493 // make sense.
5494 CoveredArgs.set(argIndex);
5495 }
5496 else {
5497 // If argIndex exceeds the number of data arguments we
5498 // don't issue a warning because that is just a cascade of warnings (and
5499 // they may have intended '%%' anyway). We don't want to continue processing
5500 // the format string after this point, however, as we will like just get
5501 // gibberish when trying to match arguments.
5502 keepGoing = false;
5503 }
5504
5505 StringRef Specifier(csStart, csLen);
5506
5507 // If the specifier in non-printable, it could be the first byte of a UTF-8
5508 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5509 // hex value.
5510 std::string CodePointStr;
5511 if (!llvm::sys::locale::isPrint(*csStart)) {
5512 llvm::UTF32 CodePoint;
5513 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5514 const llvm::UTF8 *E =
5515 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5516 llvm::ConversionResult Result =
5517 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5518
5519 if (Result != llvm::conversionOK) {
5520 unsigned char FirstChar = *csStart;
5521 CodePoint = (llvm::UTF32)FirstChar;
5522 }
5523
5524 llvm::raw_string_ostream OS(CodePointStr);
5525 if (CodePoint < 256)
5526 OS << "\\x" << llvm::format("%02x", CodePoint);
5527 else if (CodePoint <= 0xFFFF)
5528 OS << "\\u" << llvm::format("%04x", CodePoint);
5529 else
5530 OS << "\\U" << llvm::format("%08x", CodePoint);
5531 OS.flush();
5532 Specifier = CodePointStr;
5533 }
5534
5535 EmitFormatDiagnostic(
5536 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5537 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5538
5539 return keepGoing;
5540}
5541
5542void
5543CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5544 const char *startSpec,
5545 unsigned specifierLen) {
5546 EmitFormatDiagnostic(
5547 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5548 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5549}
5550
5551bool
5552CheckFormatHandler::CheckNumArgs(
5553 const analyze_format_string::FormatSpecifier &FS,
5554 const analyze_format_string::ConversionSpecifier &CS,
5555 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5556
5557 if (argIndex >= NumDataArgs) {
5558 PartialDiagnostic PDiag = FS.usesPositionalArg()
5559 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5560 << (argIndex+1) << NumDataArgs)
5561 : S.PDiag(diag::warn_printf_insufficient_data_args);
5562 EmitFormatDiagnostic(
5563 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5564 getSpecifierRange(startSpecifier, specifierLen));
5565
5566 // Since more arguments than conversion tokens are given, by extension
5567 // all arguments are covered, so mark this as so.
5568 UncoveredArg.setAllCovered();
5569 return false;
5570 }
5571 return true;
5572}
5573
5574template<typename Range>
5575void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5576 SourceLocation Loc,
5577 bool IsStringLocation,
5578 Range StringRange,
5579 ArrayRef<FixItHint> FixIt) {
5580 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5581 Loc, IsStringLocation, StringRange, FixIt);
5582}
5583
5584/// \brief If the format string is not within the funcion call, emit a note
5585/// so that the function call and string are in diagnostic messages.
5586///
5587/// \param InFunctionCall if true, the format string is within the function
5588/// call and only one diagnostic message will be produced. Otherwise, an
5589/// extra note will be emitted pointing to location of the format string.
5590///
5591/// \param ArgumentExpr the expression that is passed as the format string
5592/// argument in the function call. Used for getting locations when two
5593/// diagnostics are emitted.
5594///
5595/// \param PDiag the callee should already have provided any strings for the
5596/// diagnostic message. This function only adds locations and fixits
5597/// to diagnostics.
5598///
5599/// \param Loc primary location for diagnostic. If two diagnostics are
5600/// required, one will be at Loc and a new SourceLocation will be created for
5601/// the other one.
5602///
5603/// \param IsStringLocation if true, Loc points to the format string should be
5604/// used for the note. Otherwise, Loc points to the argument list and will
5605/// be used with PDiag.
5606///
5607/// \param StringRange some or all of the string to highlight. This is
5608/// templated so it can accept either a CharSourceRange or a SourceRange.
5609///
5610/// \param FixIt optional fix it hint for the format string.
5611template <typename Range>
5612void CheckFormatHandler::EmitFormatDiagnostic(
5613 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5614 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5615 Range StringRange, ArrayRef<FixItHint> FixIt) {
5616 if (InFunctionCall) {
5617 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5618 D << StringRange;
5619 D << FixIt;
5620 } else {
5621 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5622 << ArgumentExpr->getSourceRange();
5623
5624 const Sema::SemaDiagnosticBuilder &Note =
5625 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5626 diag::note_format_string_defined);
5627
5628 Note << StringRange;
5629 Note << FixIt;
5630 }
5631}
5632
5633//===--- CHECK: Printf format string checking ------------------------------===//
5634
5635namespace {
5636class CheckPrintfHandler : public CheckFormatHandler {
5637public:
5638 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5639 const Expr *origFormatExpr,
5640 const Sema::FormatStringType type, unsigned firstDataArg,
5641 unsigned numDataArgs, bool isObjC, const char *beg,
5642 bool hasVAListArg, ArrayRef<const Expr *> Args,
5643 unsigned formatIdx, bool inFunctionCall,
5644 Sema::VariadicCallType CallType,
5645 llvm::SmallBitVector &CheckedVarArgs,
5646 UncoveredArgHandler &UncoveredArg)
5647 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5648 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5649 inFunctionCall, CallType, CheckedVarArgs,
5650 UncoveredArg) {}
5651
5652 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5653
5654 /// Returns true if '%@' specifiers are allowed in the format string.
5655 bool allowsObjCArg() const {
5656 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5657 FSType == Sema::FST_OSTrace;
5658 }
5659
5660 bool HandleInvalidPrintfConversionSpecifier(
5661 const analyze_printf::PrintfSpecifier &FS,
5662 const char *startSpecifier,
5663 unsigned specifierLen) override;
5664
5665 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5666 const char *startSpecifier,
5667 unsigned specifierLen) override;
5668 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5669 const char *StartSpecifier,
5670 unsigned SpecifierLen,
5671 const Expr *E);
5672
5673 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5674 const char *startSpecifier, unsigned specifierLen);
5675 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5676 const analyze_printf::OptionalAmount &Amt,
5677 unsigned type,
5678 const char *startSpecifier, unsigned specifierLen);
5679 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5680 const analyze_printf::OptionalFlag &flag,
5681 const char *startSpecifier, unsigned specifierLen);
5682 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5683 const analyze_printf::OptionalFlag &ignoredFlag,
5684 const analyze_printf::OptionalFlag &flag,
5685 const char *startSpecifier, unsigned specifierLen);
5686 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5687 const Expr *E);
5688
5689 void HandleEmptyObjCModifierFlag(const char *startFlag,
5690 unsigned flagLen) override;
5691
5692 void HandleInvalidObjCModifierFlag(const char *startFlag,
5693 unsigned flagLen) override;
5694
5695 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5696 const char *flagsEnd,
5697 const char *conversionPosition)
5698 override;
5699};
5700} // end anonymous namespace
5701
5702bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5703 const analyze_printf::PrintfSpecifier &FS,
5704 const char *startSpecifier,
5705 unsigned specifierLen) {
5706 const analyze_printf::PrintfConversionSpecifier &CS =
5707 FS.getConversionSpecifier();
5708
5709 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5710 getLocationOfByte(CS.getStart()),
5711 startSpecifier, specifierLen,
5712 CS.getStart(), CS.getLength());
5713}
5714
5715bool CheckPrintfHandler::HandleAmount(
5716 const analyze_format_string::OptionalAmount &Amt,
5717 unsigned k, const char *startSpecifier,
5718 unsigned specifierLen) {
5719 if (Amt.hasDataArgument()) {
5720 if (!HasVAListArg) {
5721 unsigned argIndex = Amt.getArgIndex();
5722 if (argIndex >= NumDataArgs) {
5723 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5724 << k,
5725 getLocationOfByte(Amt.getStart()),
5726 /*IsStringLocation*/true,
5727 getSpecifierRange(startSpecifier, specifierLen));
5728 // Don't do any more checking. We will just emit
5729 // spurious errors.
5730 return false;
5731 }
5732
5733 // Type check the data argument. It should be an 'int'.
5734 // Although not in conformance with C99, we also allow the argument to be
5735 // an 'unsigned int' as that is a reasonably safe case. GCC also
5736 // doesn't emit a warning for that case.
5737 CoveredArgs.set(argIndex);
5738 const Expr *Arg = getDataArg(argIndex);
5739 if (!Arg)
5740 return false;
5741
5742 QualType T = Arg->getType();
5743
5744 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5745 assert(AT.isValid())((AT.isValid()) ? static_cast<void> (0) : __assert_fail
("AT.isValid()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 5745, __PRETTY_FUNCTION__))
;
5746
5747 if (!AT.matchesType(S.Context, T)) {
5748 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5749 << k << AT.getRepresentativeTypeName(S.Context)
5750 << T << Arg->getSourceRange(),
5751 getLocationOfByte(Amt.getStart()),
5752 /*IsStringLocation*/true,
5753 getSpecifierRange(startSpecifier, specifierLen));
5754 // Don't do any more checking. We will just emit
5755 // spurious errors.
5756 return false;
5757 }
5758 }
5759 }
5760 return true;
5761}
5762
5763void CheckPrintfHandler::HandleInvalidAmount(
5764 const analyze_printf::PrintfSpecifier &FS,
5765 const analyze_printf::OptionalAmount &Amt,
5766 unsigned type,
5767 const char *startSpecifier,
5768 unsigned specifierLen) {
5769 const analyze_printf::PrintfConversionSpecifier &CS =
5770 FS.getConversionSpecifier();
5771
5772 FixItHint fixit =
5773 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5774 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5775 Amt.getConstantLength()))
5776 : FixItHint();
5777
5778 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5779 << type << CS.toString(),
5780 getLocationOfByte(Amt.getStart()),
5781 /*IsStringLocation*/true,
5782 getSpecifierRange(startSpecifier, specifierLen),
5783 fixit);
5784}
5785
5786void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5787 const analyze_printf::OptionalFlag &flag,
5788 const char *startSpecifier,
5789 unsigned specifierLen) {
5790 // Warn about pointless flag with a fixit removal.
5791 const analyze_printf::PrintfConversionSpecifier &CS =
5792 FS.getConversionSpecifier();
5793 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5794 << flag.toString() << CS.toString(),
5795 getLocationOfByte(flag.getPosition()),
5796 /*IsStringLocation*/true,
5797 getSpecifierRange(startSpecifier, specifierLen),
5798 FixItHint::CreateRemoval(
5799 getSpecifierRange(flag.getPosition(), 1)));
5800}
5801
5802void CheckPrintfHandler::HandleIgnoredFlag(
5803 const analyze_printf::PrintfSpecifier &FS,
5804 const analyze_printf::OptionalFlag &ignoredFlag,
5805 const analyze_printf::OptionalFlag &flag,
5806 const char *startSpecifier,
5807 unsigned specifierLen) {
5808 // Warn about ignored flag with a fixit removal.
5809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5810 << ignoredFlag.toString() << flag.toString(),
5811 getLocationOfByte(ignoredFlag.getPosition()),
5812 /*IsStringLocation*/true,
5813 getSpecifierRange(startSpecifier, specifierLen),
5814 FixItHint::CreateRemoval(
5815 getSpecifierRange(ignoredFlag.getPosition(), 1)));
5816}
5817
5818// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5819// bool IsStringLocation, Range StringRange,
5820// ArrayRef<FixItHint> Fixit = None);
5821
5822void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5823 unsigned flagLen) {
5824 // Warn about an empty flag.
5825 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5826 getLocationOfByte(startFlag),
5827 /*IsStringLocation*/true,
5828 getSpecifierRange(startFlag, flagLen));
5829}
5830
5831void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5832 unsigned flagLen) {
5833 // Warn about an invalid flag.
5834 auto Range = getSpecifierRange(startFlag, flagLen);
5835 StringRef flag(startFlag, flagLen);
5836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5837 getLocationOfByte(startFlag),
5838 /*IsStringLocation*/true,
5839 Range, FixItHint::CreateRemoval(Range));
5840}
5841
5842void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5843 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5844 // Warn about using '[...]' without a '@' conversion.
5845 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5846 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5847 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5848 getLocationOfByte(conversionPosition),
5849 /*IsStringLocation*/true,
5850 Range, FixItHint::CreateRemoval(Range));
5851}
5852
5853// Determines if the specified is a C++ class or struct containing
5854// a member with the specified name and kind (e.g. a CXXMethodDecl named
5855// "c_str()").
5856template<typename MemberKind>
5857static llvm::SmallPtrSet<MemberKind*, 1>
5858CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5859 const RecordType *RT = Ty->getAs<RecordType>();
5860 llvm::SmallPtrSet<MemberKind*, 1> Results;
5861
5862 if (!RT)
5863 return Results;
5864 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5865 if (!RD || !RD->getDefinition())
5866 return Results;
5867
5868 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5869 Sema::LookupMemberName);
5870 R.suppressDiagnostics();
5871
5872 // We just need to include all members of the right kind turned up by the
5873 // filter, at this point.
5874 if (S.LookupQualifiedName(R, RT->getDecl()))
5875 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5876 NamedDecl *decl = (*I)->getUnderlyingDecl();
5877 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5878 Results.insert(FK);
5879 }
5880 return Results;
5881}
5882
5883/// Check if we could call '.c_str()' on an object.
5884///
5885/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5886/// allow the call, or if it would be ambiguous).
5887bool Sema::hasCStrMethod(const Expr *E) {
5888 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5889 MethodSet Results =
5890 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5891 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5892 MI != ME; ++MI)
5893 if ((*MI)->getMinRequiredArguments() == 0)
5894 return true;
5895 return false;
5896}
5897
5898// Check if a (w)string was passed when a (w)char* was needed, and offer a
5899// better diagnostic if so. AT is assumed to be valid.
5900// Returns true when a c_str() conversion method is found.
5901bool CheckPrintfHandler::checkForCStrMembers(
5902 const analyze_printf::ArgType &AT, const Expr *E) {
5903 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5904
5905 MethodSet Results =
5906 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5907
5908 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5909 MI != ME; ++MI) {
5910 const CXXMethodDecl *Method = *MI;
5911 if (Method->getMinRequiredArguments() == 0 &&
5912 AT.matchesType(S.Context, Method->getReturnType())) {
5913 // FIXME: Suggest parens if the expression needs them.
5914 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5915 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5916 << "c_str()"
5917 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5918 return true;
5919 }
5920 }
5921
5922 return false;
5923}
5924
5925bool
5926CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5927 &FS,
5928 const char *startSpecifier,
5929 unsigned specifierLen) {
5930 using namespace analyze_format_string;
5931 using namespace analyze_printf;
5932 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5933
5934 if (FS.consumesDataArgument()) {
5935 if (atFirstArg) {
5936 atFirstArg = false;
5937 usesPositionalArgs = FS.usesPositionalArg();
5938 }
5939 else if (usesPositionalArgs != FS.usesPositionalArg()) {
5940 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5941 startSpecifier, specifierLen);
5942 return false;
5943 }
5944 }
5945
5946 // First check if the field width, precision, and conversion specifier
5947 // have matching data arguments.
5948 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5949 startSpecifier, specifierLen)) {
5950 return false;
5951 }
5952
5953 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5954 startSpecifier, specifierLen)) {
5955 return false;
5956 }
5957
5958 if (!CS.consumesDataArgument()) {
5959 // FIXME: Technically specifying a precision or field width here
5960 // makes no sense. Worth issuing a warning at some point.
5961 return true;
5962 }
5963
5964 // Consume the argument.
5965 unsigned argIndex = FS.getArgIndex();
5966 if (argIndex < NumDataArgs) {
5967 // The check to see if the argIndex is valid will come later.
5968 // We set the bit here because we may exit early from this
5969 // function if we encounter some other error.
5970 CoveredArgs.set(argIndex);
5971 }
5972
5973 // FreeBSD kernel extensions.
5974 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5975 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5976 // We need at least two arguments.
5977 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5978 return false;
5979
5980 // Claim the second argument.
5981 CoveredArgs.set(argIndex + 1);
5982
5983 // Type check the first argument (int for %b, pointer for %D)
5984 const Expr *Ex = getDataArg(argIndex);
5985 const analyze_printf::ArgType &AT =
5986 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5987 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5988 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5989 EmitFormatDiagnostic(
5990 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5991 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5992 << false << Ex->getSourceRange(),
5993 Ex->getLocStart(), /*IsStringLocation*/false,
5994 getSpecifierRange(startSpecifier, specifierLen));
5995
5996 // Type check the second argument (char * for both %b and %D)
5997 Ex = getDataArg(argIndex + 1);
5998 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5999 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6000 EmitFormatDiagnostic(
6001 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6002 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6003 << false << Ex->getSourceRange(),
6004 Ex->getLocStart(), /*IsStringLocation*/false,
6005 getSpecifierRange(startSpecifier, specifierLen));
6006
6007 return true;
6008 }
6009
6010 // Check for using an Objective-C specific conversion specifier
6011 // in a non-ObjC literal.
6012 if (!allowsObjCArg() && CS.isObjCArg()) {
6013 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6014 specifierLen);
6015 }
6016
6017 // %P can only be used with os_log.
6018 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6019 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6020 specifierLen);
6021 }
6022
6023 // %n is not allowed with os_log.
6024 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6025 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6026 getLocationOfByte(CS.getStart()),
6027 /*IsStringLocation*/ false,
6028 getSpecifierRange(startSpecifier, specifierLen));
6029
6030 return true;
6031 }
6032
6033 // Only scalars are allowed for os_trace.
6034 if (FSType == Sema::FST_OSTrace &&
6035 (CS.getKind() == ConversionSpecifier::PArg ||
6036 CS.getKind() == ConversionSpecifier::sArg ||
6037 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6038 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6039 specifierLen);
6040 }
6041
6042 // Check for use of public/private annotation outside of os_log().
6043 if (FSType != Sema::FST_OSLog) {
6044 if (FS.isPublic().isSet()) {
6045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6046 << "public",
6047 getLocationOfByte(FS.isPublic().getPosition()),
6048 /*IsStringLocation*/ false,
6049 getSpecifierRange(startSpecifier, specifierLen));
6050 }
6051 if (FS.isPrivate().isSet()) {
6052 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6053 << "private",
6054 getLocationOfByte(FS.isPrivate().getPosition()),
6055 /*IsStringLocation*/ false,
6056 getSpecifierRange(startSpecifier, specifierLen));
6057 }
6058 }
6059
6060 // Check for invalid use of field width
6061 if (!FS.hasValidFieldWidth()) {
6062 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6063 startSpecifier, specifierLen);
6064 }
6065
6066 // Check for invalid use of precision
6067 if (!FS.hasValidPrecision()) {
6068 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6069 startSpecifier, specifierLen);
6070 }
6071
6072 // Precision is mandatory for %P specifier.
6073 if (CS.getKind() == ConversionSpecifier::PArg &&
6074 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6075 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6076 getLocationOfByte(startSpecifier),
6077 /*IsStringLocation*/ false,
6078 getSpecifierRange(startSpecifier, specifierLen));
6079 }
6080
6081 // Check each flag does not conflict with any other component.
6082 if (!FS.hasValidThousandsGroupingPrefix())
6083 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6084 if (!FS.hasValidLeadingZeros())
6085 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6086 if (!FS.hasValidPlusPrefix())
6087 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6088 if (!FS.hasValidSpacePrefix())
6089 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6090 if (!FS.hasValidAlternativeForm())
6091 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6092 if (!FS.hasValidLeftJustified())
6093 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6094
6095 // Check that flags are not ignored by another flag
6096 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6097 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6098 startSpecifier, specifierLen);
6099 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6100 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6101 startSpecifier, specifierLen);
6102
6103 // Check the length modifier is valid with the given conversion specifier.
6104 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6105 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6106 diag::warn_format_nonsensical_length);
6107 else if (!FS.hasStandardLengthModifier())
6108 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6109 else if (!FS.hasStandardLengthConversionCombination())
6110 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6111 diag::warn_format_non_standard_conversion_spec);
6112
6113 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6114 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6115
6116 // The remaining checks depend on the data arguments.
6117 if (HasVAListArg)
6118 return true;
6119
6120 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6121 return false;
6122
6123 const Expr *Arg = getDataArg(argIndex);
6124 if (!Arg)
6125 return true;
6126
6127 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6128}
6129
6130static bool requiresParensToAddCast(const Expr *E) {
6131 // FIXME: We should have a general way to reason about operator
6132 // precedence and whether parens are actually needed here.
6133 // Take care of a few common cases where they aren't.
6134 const Expr *Inside = E->IgnoreImpCasts();
6135 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6136 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6137
6138 switch (Inside->getStmtClass()) {
6139 case Stmt::ArraySubscriptExprClass:
6140 case Stmt::CallExprClass:
6141 case Stmt::CharacterLiteralClass:
6142 case Stmt::CXXBoolLiteralExprClass:
6143 case Stmt::DeclRefExprClass:
6144 case Stmt::FloatingLiteralClass:
6145 case Stmt::IntegerLiteralClass:
6146 case Stmt::MemberExprClass:
6147 case Stmt::ObjCArrayLiteralClass:
6148 case Stmt::ObjCBoolLiteralExprClass:
6149 case Stmt::ObjCBoxedExprClass:
6150 case Stmt::ObjCDictionaryLiteralClass:
6151 case Stmt::ObjCEncodeExprClass:
6152 case Stmt::ObjCIvarRefExprClass:
6153 case Stmt::ObjCMessageExprClass:
6154 case Stmt::ObjCPropertyRefExprClass:
6155 case Stmt::ObjCStringLiteralClass:
6156 case Stmt::ObjCSubscriptRefExprClass:
6157 case Stmt::ParenExprClass:
6158 case Stmt::StringLiteralClass:
6159 case Stmt::UnaryOperatorClass:
6160 return false;
6161 default:
6162 return true;
6163 }
6164}
6165
6166static std::pair<QualType, StringRef>
6167shouldNotPrintDirectly(const ASTContext &Context,
6168 QualType IntendedTy,
6169 const Expr *E) {
6170 // Use a 'while' to peel off layers of typedefs.
6171 QualType TyTy = IntendedTy;
6172 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6173 StringRef Name = UserTy->getDecl()->getName();
6174 QualType CastTy = llvm::StringSwitch<QualType>(Name)
6175 .Case("CFIndex", Context.getNSIntegerType())
6176 .Case("NSInteger", Context.getNSIntegerType())
6177 .Case("NSUInteger", Context.getNSUIntegerType())
6178 .Case("SInt32", Context.IntTy)
6179 .Case("UInt32", Context.UnsignedIntTy)
6180 .Default(QualType());
6181
6182 if (!CastTy.isNull())
6183 return std::make_pair(CastTy, Name);
6184
6185 TyTy = UserTy->desugar();
6186 }
6187
6188 // Strip parens if necessary.
6189 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6190 return shouldNotPrintDirectly(Context,
6191 PE->getSubExpr()->getType(),
6192 PE->getSubExpr());
6193
6194 // If this is a conditional expression, then its result type is constructed
6195 // via usual arithmetic conversions and thus there might be no necessary
6196 // typedef sugar there. Recurse to operands to check for NSInteger &
6197 // Co. usage condition.
6198 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6199 QualType TrueTy, FalseTy;
6200 StringRef TrueName, FalseName;
6201
6202 std::tie(TrueTy, TrueName) =
6203 shouldNotPrintDirectly(Context,
6204 CO->getTrueExpr()->getType(),
6205 CO->getTrueExpr());
6206 std::tie(FalseTy, FalseName) =
6207 shouldNotPrintDirectly(Context,
6208 CO->getFalseExpr()->getType(),
6209 CO->getFalseExpr());
6210
6211 if (TrueTy == FalseTy)
6212 return std::make_pair(TrueTy, TrueName);
6213 else if (TrueTy.isNull())
6214 return std::make_pair(FalseTy, FalseName);
6215 else if (FalseTy.isNull())
6216 return std::make_pair(TrueTy, TrueName);
6217 }
6218
6219 return std::make_pair(QualType(), StringRef());
6220}
6221
6222bool
6223CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6224 const char *StartSpecifier,
6225 unsigned SpecifierLen,
6226 const Expr *E) {
6227 using namespace analyze_format_string;
6228 using namespace analyze_printf;
6229 // Now type check the data expression that matches the
6230 // format specifier.
6231 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6232 if (!AT.isValid())
6233 return true;
6234
6235 QualType ExprTy = E->getType();
6236 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6237 ExprTy = TET->getUnderlyingExpr()->getType();
6238 }
6239
6240 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6241
6242 if (match == analyze_printf::ArgType::Match) {
6243 return true;
6244 }
6245
6246 // Look through argument promotions for our error message's reported type.
6247 // This includes the integral and floating promotions, but excludes array
6248 // and function pointer decay; seeing that an argument intended to be a
6249 // string has type 'char [6]' is probably more confusing than 'char *'.
6250 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6251 if (ICE->getCastKind() == CK_IntegralCast ||
6252 ICE->getCastKind() == CK_FloatingCast) {
6253 E = ICE->getSubExpr();
6254 ExprTy = E->getType();
6255
6256 // Check if we didn't match because of an implicit cast from a 'char'
6257 // or 'short' to an 'int'. This is done because printf is a varargs
6258 // function.
6259 if (ICE->getType() == S.Context.IntTy ||
6260 ICE->getType() == S.Context.UnsignedIntTy) {
6261 // All further checking is done on the subexpression.
6262 if (AT.matchesType(S.Context, ExprTy))
6263 return true;
6264 }
6265 }
6266 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6267 // Special case for 'a', which has type 'int' in C.
6268 // Note, however, that we do /not/ want to treat multibyte constants like
6269 // 'MooV' as characters! This form is deprecated but still exists.
6270 if (ExprTy == S.Context.IntTy)
6271 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6272 ExprTy = S.Context.CharTy;
6273 }
6274
6275 // Look through enums to their underlying type.
6276 bool IsEnum = false;
6277 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6278 ExprTy = EnumTy->getDecl()->getIntegerType();
6279 IsEnum = true;
6280 }
6281
6282 // %C in an Objective-C context prints a unichar, not a wchar_t.
6283 // If the argument is an integer of some kind, believe the %C and suggest
6284 // a cast instead of changing the conversion specifier.
6285 QualType IntendedTy = ExprTy;
6286 if (isObjCContext() &&
6287 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6288 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6289 !ExprTy->isCharType()) {
6290 // 'unichar' is defined as a typedef of unsigned short, but we should
6291 // prefer using the typedef if it is visible.
6292 IntendedTy = S.Context.UnsignedShortTy;
6293
6294 // While we are here, check if the value is an IntegerLiteral that happens
6295 // to be within the valid range.
6296 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6297 const llvm::APInt &V = IL->getValue();
6298 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6299 return true;
6300 }
6301
6302 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6303 Sema::LookupOrdinaryName);
6304 if (S.LookupName(Result, S.getCurScope())) {
6305 NamedDecl *ND = Result.getFoundDecl();
6306 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6307 if (TD->getUnderlyingType() == IntendedTy)
6308 IntendedTy = S.Context.getTypedefType(TD);
6309 }
6310 }
6311 }
6312
6313 // Special-case some of Darwin's platform-independence types by suggesting
6314 // casts to primitive types that are known to be large enough.
6315 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6316 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6317 QualType CastTy;
6318 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6319 if (!CastTy.isNull()) {
6320 IntendedTy = CastTy;
6321 ShouldNotPrintDirectly = true;
6322 }
6323 }
6324
6325 // We may be able to offer a FixItHint if it is a supported type.
6326 PrintfSpecifier fixedFS = FS;
6327 bool success =
6328 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6329
6330 if (success) {
6331 // Get the fix string from the fixed format specifier
6332 SmallString<16> buf;
6333 llvm::raw_svector_ostream os(buf);
6334 fixedFS.toString(os);
6335
6336 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6337
6338 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6339 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6340 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6341 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6342 }
6343 // In this case, the specifier is wrong and should be changed to match
6344 // the argument.
6345 EmitFormatDiagnostic(S.PDiag(diag)
6346 << AT.getRepresentativeTypeName(S.Context)
6347 << IntendedTy << IsEnum << E->getSourceRange(),
6348 E->getLocStart(),
6349 /*IsStringLocation*/ false, SpecRange,
6350 FixItHint::CreateReplacement(SpecRange, os.str()));
6351 } else {
6352 // The canonical type for formatting this value is different from the
6353 // actual type of the expression. (This occurs, for example, with Darwin's
6354 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6355 // should be printed as 'long' for 64-bit compatibility.)
6356 // Rather than emitting a normal format/argument mismatch, we want to
6357 // add a cast to the recommended type (and correct the format string
6358 // if necessary).
6359 SmallString<16> CastBuf;
6360 llvm::raw_svector_ostream CastFix(CastBuf);
6361 CastFix << "(";
6362 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6363 CastFix << ")";
6364
6365 SmallVector<FixItHint,4> Hints;
6366 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6367 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6368
6369 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6370 // If there's already a cast present, just replace it.
6371 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6372 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6373
6374 } else if (!requiresParensToAddCast(E)) {
6375 // If the expression has high enough precedence,
6376 // just write the C-style cast.
6377 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6378 CastFix.str()));
6379 } else {
6380 // Otherwise, add parens around the expression as well as the cast.
6381 CastFix << "(";
6382 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6383 CastFix.str()));
6384
6385 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6386 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6387 }
6388
6389 if (ShouldNotPrintDirectly) {
6390 // The expression has a type that should not be printed directly.
6391 // We extract the name from the typedef because we don't want to show
6392 // the underlying type in the diagnostic.
6393 StringRef Name;
6394 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6395 Name = TypedefTy->getDecl()->getName();
6396 else
6397 Name = CastTyName;
6398 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6399 << Name << IntendedTy << IsEnum
6400 << E->getSourceRange(),
6401 E->getLocStart(), /*IsStringLocation=*/false,
6402 SpecRange, Hints);
6403 } else {
6404 // In this case, the expression could be printed using a different
6405 // specifier, but we've decided that the specifier is probably correct
6406 // and we should cast instead. Just use the normal warning message.
6407 EmitFormatDiagnostic(
6408 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6409 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6410 << E->getSourceRange(),
6411 E->getLocStart(), /*IsStringLocation*/false,
6412 SpecRange, Hints);
6413 }
6414 }
6415 } else {
6416 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6417 SpecifierLen);
6418 // Since the warning for passing non-POD types to variadic functions
6419 // was deferred until now, we emit a warning for non-POD
6420 // arguments here.
6421 switch (S.isValidVarArgType(ExprTy)) {
6422 case Sema::VAK_Valid:
6423 case Sema::VAK_ValidInCXX11: {
6424 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6425 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6426 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6427 }
6428
6429 EmitFormatDiagnostic(
6430 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6431 << IsEnum << CSR << E->getSourceRange(),
6432 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6433 break;
6434 }
6435 case Sema::VAK_Undefined:
6436 case Sema::VAK_MSVCUndefined:
6437 EmitFormatDiagnostic(
6438 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6439 << S.getLangOpts().CPlusPlus11
6440 << ExprTy
6441 << CallType
6442 << AT.getRepresentativeTypeName(S.Context)
6443 << CSR
6444 << E->getSourceRange(),
6445 E->getLocStart(), /*IsStringLocation*/false, CSR);
6446 checkForCStrMembers(AT, E);
6447 break;
6448
6449 case Sema::VAK_Invalid:
6450 if (ExprTy->isObjCObjectType())
6451 EmitFormatDiagnostic(
6452 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6453 << S.getLangOpts().CPlusPlus11
6454 << ExprTy
6455 << CallType
6456 << AT.getRepresentativeTypeName(S.Context)
6457 << CSR
6458 << E->getSourceRange(),
6459 E->getLocStart(), /*IsStringLocation*/false, CSR);
6460 else
6461 // FIXME: If this is an initializer list, suggest removing the braces
6462 // or inserting a cast to the target type.
6463 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6464 << isa<InitListExpr>(E) << ExprTy << CallType
6465 << AT.getRepresentativeTypeName(S.Context)
6466 << E->getSourceRange();
6467 break;
6468 }
6469
6470 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&((FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
"format string specifier index out of range") ? static_cast<
void> (0) : __assert_fail ("FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && \"format string specifier index out of range\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 6471, __PRETTY_FUNCTION__))
6471 "format string specifier index out of range")((FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
"format string specifier index out of range") ? static_cast<
void> (0) : __assert_fail ("FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && \"format string specifier index out of range\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 6471, __PRETTY_FUNCTION__))
;
6472 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6473 }
6474
6475 return true;
6476}
6477
6478//===--- CHECK: Scanf format string checking ------------------------------===//
6479
6480namespace {
6481class CheckScanfHandler : public CheckFormatHandler {
6482public:
6483 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6484 const Expr *origFormatExpr, Sema::FormatStringType type,
6485 unsigned firstDataArg, unsigned numDataArgs,
6486 const char *beg, bool hasVAListArg,
6487 ArrayRef<const Expr *> Args, unsigned formatIdx,
6488 bool inFunctionCall, Sema::VariadicCallType CallType,
6489 llvm::SmallBitVector &CheckedVarArgs,
6490 UncoveredArgHandler &UncoveredArg)
6491 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6492 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6493 inFunctionCall, CallType, CheckedVarArgs,
6494 UncoveredArg) {}
6495
6496 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6497 const char *startSpecifier,
6498 unsigned specifierLen) override;
6499
6500 bool HandleInvalidScanfConversionSpecifier(
6501 const analyze_scanf::ScanfSpecifier &FS,
6502 const char *startSpecifier,
6503 unsigned specifierLen) override;
6504
6505 void HandleIncompleteScanList(const char *start, const char *end) override;
6506};
6507} // end anonymous namespace
6508
6509void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6510 const char *end) {
6511 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6512 getLocationOfByte(end), /*IsStringLocation*/true,
6513 getSpecifierRange(start, end - start));
6514}
6515
6516bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6517 const analyze_scanf::ScanfSpecifier &FS,
6518 const char *startSpecifier,
6519 unsigned specifierLen) {
6520
6521 const analyze_scanf::ScanfConversionSpecifier &CS =
6522 FS.getConversionSpecifier();
6523
6524 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6525 getLocationOfByte(CS.getStart()),
6526 startSpecifier, specifierLen,
6527 CS.getStart(), CS.getLength());
6528}
6529
6530bool CheckScanfHandler::HandleScanfSpecifier(
6531 const analyze_scanf::ScanfSpecifier &FS,
6532 const char *startSpecifier,
6533 unsigned specifierLen) {
6534 using namespace analyze_scanf;
6535 using namespace analyze_format_string;
6536
6537 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6538
6539 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6540 // be used to decide if we are using positional arguments consistently.
6541 if (FS.consumesDataArgument()) {
6542 if (atFirstArg) {
6543 atFirstArg = false;
6544 usesPositionalArgs = FS.usesPositionalArg();
6545 }
6546 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6547 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6548 startSpecifier, specifierLen);
6549 return false;
6550 }
6551 }
6552
6553 // Check if the field with is non-zero.
6554 const OptionalAmount &Amt = FS.getFieldWidth();
6555 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6556 if (Amt.getConstantAmount() == 0) {
6557 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6558 Amt.getConstantLength());
6559 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6560 getLocationOfByte(Amt.getStart()),
6561 /*IsStringLocation*/true, R,
6562 FixItHint::CreateRemoval(R));
6563 }
6564 }
6565
6566 if (!FS.consumesDataArgument()) {
6567 // FIXME: Technically specifying a precision or field width here
6568 // makes no sense. Worth issuing a warning at some point.
6569 return true;
6570 }
6571
6572 // Consume the argument.
6573 unsigned argIndex = FS.getArgIndex();
6574 if (argIndex < NumDataArgs) {
6575 // The check to see if the argIndex is valid will come later.
6576 // We set the bit here because we may exit early from this
6577 // function if we encounter some other error.
6578 CoveredArgs.set(argIndex);
6579 }
6580
6581 // Check the length modifier is valid with the given conversion specifier.
6582 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6583 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6584 diag::warn_format_nonsensical_length);
6585 else if (!FS.hasStandardLengthModifier())
6586 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6587 else if (!FS.hasStandardLengthConversionCombination())
6588 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6589 diag::warn_format_non_standard_conversion_spec);
6590
6591 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6592 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6593
6594 // The remaining checks depend on the data arguments.
6595 if (HasVAListArg)
6596 return true;
6597
6598 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6599 return false;
6600
6601 // Check that the argument type matches the format specifier.
6602 const Expr *Ex = getDataArg(argIndex);
6603 if (!Ex)
6604 return true;
6605
6606 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6607
6608 if (!AT.isValid()) {
6609 return true;
6610 }
6611
6612 analyze_format_string::ArgType::MatchKind match =
6613 AT.matchesType(S.Context, Ex->getType());
6614 if (match == analyze_format_string::ArgType::Match) {
6615 return true;
6616 }
6617
6618 ScanfSpecifier fixedFS = FS;
6619 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6620 S.getLangOpts(), S.Context);
6621
6622 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6623 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6624 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6625 }
6626
6627 if (success) {
6628 // Get the fix string from the fixed format specifier.
6629 SmallString<128> buf;
6630 llvm::raw_svector_ostream os(buf);
6631 fixedFS.toString(os);
6632
6633 EmitFormatDiagnostic(
6634 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6635 << Ex->getType() << false << Ex->getSourceRange(),
6636 Ex->getLocStart(),
6637 /*IsStringLocation*/ false,
6638 getSpecifierRange(startSpecifier, specifierLen),
6639 FixItHint::CreateReplacement(
6640 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6641 } else {
6642 EmitFormatDiagnostic(S.PDiag(diag)
6643 << AT.getRepresentativeTypeName(S.Context)
6644 << Ex->getType() << false << Ex->getSourceRange(),
6645 Ex->getLocStart(),
6646 /*IsStringLocation*/ false,
6647 getSpecifierRange(startSpecifier, specifierLen));
6648 }
6649
6650 return true;
6651}
6652
6653static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6654 const Expr *OrigFormatExpr,
6655 ArrayRef<const Expr *> Args,
6656 bool HasVAListArg, unsigned format_idx,
6657 unsigned firstDataArg,
6658 Sema::FormatStringType Type,
6659 bool inFunctionCall,
6660 Sema::VariadicCallType CallType,
6661 llvm::SmallBitVector &CheckedVarArgs,
6662 UncoveredArgHandler &UncoveredArg) {
6663 // CHECK: is the format string a wide literal?
6664 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6665 CheckFormatHandler::EmitFormatDiagnostic(
6666 S, inFunctionCall, Args[format_idx],
6667 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6668 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6669 return;
6670 }
6671
6672 // Str - The format string. NOTE: this is NOT null-terminated!
6673 StringRef StrRef = FExpr->getString();
6674 const char *Str = StrRef.data();
6675 // Account for cases where the string literal is truncated in a declaration.
6676 const ConstantArrayType *T =
6677 S.Context.getAsConstantArrayType(FExpr->getType());
6678 assert(T && "String literal not of constant array type!")((T && "String literal not of constant array type!") ?
static_cast<void> (0) : __assert_fail ("T && \"String literal not of constant array type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 6678, __PRETTY_FUNCTION__))
;
6679 size_t TypeSize = T->getSize().getZExtValue();
6680 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6681 const unsigned numDataArgs = Args.size() - firstDataArg;
6682
6683 // Emit a warning if the string literal is truncated and does not contain an
6684 // embedded null character.
6685 if (TypeSize <= StrRef.size() &&
6686 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6687 CheckFormatHandler::EmitFormatDiagnostic(
6688 S, inFunctionCall, Args[format_idx],
6689 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6690 FExpr->getLocStart(),
6691 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6692 return;
6693 }
6694
6695 // CHECK: empty format string?
6696 if (StrLen == 0 && numDataArgs > 0) {
6697 CheckFormatHandler::EmitFormatDiagnostic(
6698 S, inFunctionCall, Args[format_idx],
6699 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6700 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6701 return;
6702 }
6703
6704 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6705 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6706 Type == Sema::FST_OSTrace) {
6707 CheckPrintfHandler H(
6708 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6709 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6710 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6711 CheckedVarArgs, UncoveredArg);
6712
6713 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6714 S.getLangOpts(),
6715 S.Context.getTargetInfo(),
6716 Type == Sema::FST_FreeBSDKPrintf))
6717 H.DoneProcessing();
6718 } else if (Type == Sema::FST_Scanf) {
6719 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6720 numDataArgs, Str, HasVAListArg, Args, format_idx,
6721 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6722
6723 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6724 S.getLangOpts(),
6725 S.Context.getTargetInfo()))
6726 H.DoneProcessing();
6727 } // TODO: handle other formats
6728}
6729
6730bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6731 // Str - The format string. NOTE: this is NOT null-terminated!
6732 StringRef StrRef = FExpr->getString();
6733 const char *Str = StrRef.data();
6734 // Account for cases where the string literal is truncated in a declaration.
6735 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6736 assert(T && "String literal not of constant array type!")((T && "String literal not of constant array type!") ?
static_cast<void> (0) : __assert_fail ("T && \"String literal not of constant array type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 6736, __PRETTY_FUNCTION__))
;
6737 size_t TypeSize = T->getSize().getZExtValue();
6738 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6739 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6740 getLangOpts(),
6741 Context.getTargetInfo());
6742}
6743
6744//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6745
6746// Returns the related absolute value function that is larger, of 0 if one
6747// does not exist.
6748static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6749 switch (AbsFunction) {
6750 default:
6751 return 0;
6752
6753 case Builtin::BI__builtin_abs:
6754 return Builtin::BI__builtin_labs;
6755 case Builtin::BI__builtin_labs:
6756 return Builtin::BI__builtin_llabs;
6757 case Builtin::BI__builtin_llabs:
6758 return 0;
6759
6760 case Builtin::BI__builtin_fabsf:
6761 return Builtin::BI__builtin_fabs;
6762 case Builtin::BI__builtin_fabs:
6763 return Builtin::BI__builtin_fabsl;
6764 case Builtin::BI__builtin_fabsl:
6765 return 0;
6766
6767 case Builtin::BI__builtin_cabsf:
6768 return Builtin::BI__builtin_cabs;
6769 case Builtin::BI__builtin_cabs:
6770 return Builtin::BI__builtin_cabsl;
6771 case Builtin::BI__builtin_cabsl:
6772 return 0;
6773
6774 case Builtin::BIabs:
6775 return Builtin::BIlabs;
6776 case Builtin::BIlabs:
6777 return Builtin::BIllabs;
6778 case Builtin::BIllabs:
6779 return 0;
6780
6781 case Builtin::BIfabsf:
6782 return Builtin::BIfabs;
6783 case Builtin::BIfabs:
6784 return Builtin::BIfabsl;
6785 case Builtin::BIfabsl:
6786 return 0;
6787
6788 case Builtin::BIcabsf:
6789 return Builtin::BIcabs;
6790 case Builtin::BIcabs:
6791 return Builtin::BIcabsl;
6792 case Builtin::BIcabsl:
6793 return 0;
6794 }
6795}
6796
6797// Returns the argument type of the absolute value function.
6798static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6799 unsigned AbsType) {
6800 if (AbsType == 0)
6801 return QualType();
6802
6803 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6804 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6805 if (Error != ASTContext::GE_None)
6806 return QualType();
6807
6808 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6809 if (!FT)
6810 return QualType();
6811
6812 if (FT->getNumParams() != 1)
6813 return QualType();
6814
6815 return FT->getParamType(0);
6816}
6817
6818// Returns the best absolute value function, or zero, based on type and
6819// current absolute value function.
6820static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6821 unsigned AbsFunctionKind) {
6822 unsigned BestKind = 0;
6823 uint64_t ArgSize = Context.getTypeSize(ArgType);
6824 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6825 Kind = getLargerAbsoluteValueFunction(Kind)) {
6826 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6827 if (Context.getTypeSize(ParamType) >= ArgSize) {
6828 if (BestKind == 0)
6829 BestKind = Kind;
6830 else if (Context.hasSameType(ParamType, ArgType)) {
6831 BestKind = Kind;
6832 break;
6833 }
6834 }
6835 }
6836 return BestKind;
6837}
6838
6839enum AbsoluteValueKind {
6840 AVK_Integer,
6841 AVK_Floating,
6842 AVK_Complex
6843};
6844
6845static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6846 if (T->isIntegralOrEnumerationType())
6847 return AVK_Integer;
6848 if (T->isRealFloatingType())
6849 return AVK_Floating;
6850 if (T->isAnyComplexType())
6851 return AVK_Complex;
6852
6853 llvm_unreachable("Type not integer, floating, or complex")::llvm::llvm_unreachable_internal("Type not integer, floating, or complex"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 6853)
;
6854}
6855
6856// Changes the absolute value function to a different type. Preserves whether
6857// the function is a builtin.
6858static unsigned changeAbsFunction(unsigned AbsKind,
6859 AbsoluteValueKind ValueKind) {
6860 switch (ValueKind) {
6861 case AVK_Integer:
6862 switch (AbsKind) {
6863 default:
6864 return 0;
6865 case Builtin::BI__builtin_fabsf:
6866 case Builtin::BI__builtin_fabs:
6867 case Builtin::BI__builtin_fabsl:
6868 case Builtin::BI__builtin_cabsf:
6869 case Builtin::BI__builtin_cabs:
6870 case Builtin::BI__builtin_cabsl:
6871 return Builtin::BI__builtin_abs;
6872 case Builtin::BIfabsf:
6873 case Builtin::BIfabs:
6874 case Builtin::BIfabsl:
6875 case Builtin::BIcabsf:
6876 case Builtin::BIcabs:
6877 case Builtin::BIcabsl:
6878 return Builtin::BIabs;
6879 }
6880 case AVK_Floating:
6881 switch (AbsKind) {
6882 default:
6883 return 0;
6884 case Builtin::BI__builtin_abs:
6885 case Builtin::BI__builtin_labs:
6886 case Builtin::BI__builtin_llabs:
6887 case Builtin::BI__builtin_cabsf:
6888 case Builtin::BI__builtin_cabs:
6889 case Builtin::BI__builtin_cabsl:
6890 return Builtin::BI__builtin_fabsf;
6891 case Builtin::BIabs:
6892 case Builtin::BIlabs:
6893 case Builtin::BIllabs:
6894 case Builtin::BIcabsf:
6895 case Builtin::BIcabs:
6896 case Builtin::BIcabsl:
6897 return Builtin::BIfabsf;
6898 }
6899 case AVK_Complex:
6900 switch (AbsKind) {
6901 default:
6902 return 0;
6903 case Builtin::BI__builtin_abs:
6904 case Builtin::BI__builtin_labs:
6905 case Builtin::BI__builtin_llabs:
6906 case Builtin::BI__builtin_fabsf:
6907 case Builtin::BI__builtin_fabs:
6908 case Builtin::BI__builtin_fabsl:
6909 return Builtin::BI__builtin_cabsf;
6910 case Builtin::BIabs:
6911 case Builtin::BIlabs:
6912 case Builtin::BIllabs:
6913 case Builtin::BIfabsf:
6914 case Builtin::BIfabs:
6915 case Builtin::BIfabsl:
6916 return Builtin::BIcabsf;
6917 }
6918 }
6919 llvm_unreachable("Unable to convert function")::llvm::llvm_unreachable_internal("Unable to convert function"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 6919)
;
6920}
6921
6922static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6923 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6924 if (!FnInfo)
6925 return 0;
6926
6927 switch (FDecl->getBuiltinID()) {
6928 default:
6929 return 0;
6930 case Builtin::BI__builtin_abs:
6931 case Builtin::BI__builtin_fabs:
6932 case Builtin::BI__builtin_fabsf:
6933 case Builtin::BI__builtin_fabsl:
6934 case Builtin::BI__builtin_labs:
6935 case Builtin::BI__builtin_llabs:
6936 case Builtin::BI__builtin_cabs:
6937 case Builtin::BI__builtin_cabsf:
6938 case Builtin::BI__builtin_cabsl:
6939 case Builtin::BIabs:
6940 case Builtin::BIlabs:
6941 case Builtin::BIllabs:
6942 case Builtin::BIfabs:
6943 case Builtin::BIfabsf:
6944 case Builtin::BIfabsl:
6945 case Builtin::BIcabs:
6946 case Builtin::BIcabsf:
6947 case Builtin::BIcabsl:
6948 return FDecl->getBuiltinID();
6949 }
6950 llvm_unreachable("Unknown Builtin type")::llvm::llvm_unreachable_internal("Unknown Builtin type", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 6950)
;
6951}
6952
6953// If the replacement is valid, emit a note with replacement function.
6954// Additionally, suggest including the proper header if not already included.
6955static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6956 unsigned AbsKind, QualType ArgType) {
6957 bool EmitHeaderHint = true;
6958 const char *HeaderName = nullptr;
6959 const char *FunctionName = nullptr;
6960 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6961 FunctionName = "std::abs";
6962 if (ArgType->isIntegralOrEnumerationType()) {
6963 HeaderName = "cstdlib";
6964 } else if (ArgType->isRealFloatingType()) {
6965 HeaderName = "cmath";
6966 } else {
6967 llvm_unreachable("Invalid Type")::llvm::llvm_unreachable_internal("Invalid Type", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 6967)
;
6968 }
6969
6970 // Lookup all std::abs
6971 if (NamespaceDecl *Std = S.getStdNamespace()) {
6972 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6973 R.suppressDiagnostics();
6974 S.LookupQualifiedName(R, Std);
6975
6976 for (const auto *I : R) {
6977 const FunctionDecl *FDecl = nullptr;
6978 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6979 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6980 } else {
6981 FDecl = dyn_cast<FunctionDecl>(I);
6982 }
6983 if (!FDecl)
6984 continue;
6985
6986 // Found std::abs(), check that they are the right ones.
6987 if (FDecl->getNumParams() != 1)
6988 continue;
6989
6990 // Check that the parameter type can handle the argument.
6991 QualType ParamType = FDecl->getParamDecl(0)->getType();
6992 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6993 S.Context.getTypeSize(ArgType) <=
6994 S.Context.getTypeSize(ParamType)) {
6995 // Found a function, don't need the header hint.
6996 EmitHeaderHint = false;
6997 break;
6998 }
6999 }
7000 }
7001 } else {
7002 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7003 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7004
7005 if (HeaderName) {
7006 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7007 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7008 R.suppressDiagnostics();
7009 S.LookupName(R, S.getCurScope());
7010
7011 if (R.isSingleResult()) {
7012 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7013 if (FD && FD->getBuiltinID() == AbsKind) {
7014 EmitHeaderHint = false;
7015 } else {
7016 return;
7017 }
7018 } else if (!R.empty()) {
7019 return;
7020 }
7021 }
7022 }
7023
7024 S.Diag(Loc, diag::note_replace_abs_function)
7025 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7026
7027 if (!HeaderName)
7028 return;
7029
7030 if (!EmitHeaderHint)
7031 return;
7032
7033 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7034 << FunctionName;
7035}
7036
7037template <std::size_t StrLen>
7038static bool IsStdFunction(const FunctionDecl *FDecl,
7039 const char (&Str)[StrLen]) {
7040 if (!FDecl)
7041 return false;
7042 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7043 return false;
7044 if (!FDecl->isInStdNamespace())
7045 return false;
7046
7047 return true;
7048}
7049
7050// Warn when using the wrong abs() function.
7051void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7052 const FunctionDecl *FDecl) {
7053 if (Call->getNumArgs() != 1)
7054 return;
7055
7056 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7057 bool IsStdAbs = IsStdFunction(FDecl, "abs");
7058 if (AbsKind == 0 && !IsStdAbs)
7059 return;
7060
7061 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7062 QualType ParamType = Call->getArg(0)->getType();
7063
7064 // Unsigned types cannot be negative. Suggest removing the absolute value
7065 // function call.
7066 if (ArgType->isUnsignedIntegerType()) {
7067 const char *FunctionName =
7068 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7069 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7070 Diag(Call->getExprLoc(), diag::note_remove_abs)
7071 << FunctionName
7072 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7073 return;
7074 }
7075
7076 // Taking the absolute value of a pointer is very suspicious, they probably
7077 // wanted to index into an array, dereference a pointer, call a function, etc.
7078 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7079 unsigned DiagType = 0;
7080 if (ArgType->isFunctionType())
7081 DiagType = 1;
7082 else if (ArgType->isArrayType())
7083 DiagType = 2;
7084
7085 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7086 return;
7087 }
7088
7089 // std::abs has overloads which prevent most of the absolute value problems
7090 // from occurring.
7091 if (IsStdAbs)
7092 return;
7093
7094 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7095 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7096
7097 // The argument and parameter are the same kind. Check if they are the right
7098 // size.
7099 if (ArgValueKind == ParamValueKind) {
7100 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7101 return;
7102
7103 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7104 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7105 << FDecl << ArgType << ParamType;
7106
7107 if (NewAbsKind == 0)
7108 return;
7109
7110 emitReplacement(*this, Call->getExprLoc(),
7111 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7112 return;
7113 }
7114
7115 // ArgValueKind != ParamValueKind
7116 // The wrong type of absolute value function was used. Attempt to find the
7117 // proper one.
7118 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7119 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7120 if (NewAbsKind == 0)
7121 return;
7122
7123 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7124 << FDecl << ParamValueKind << ArgValueKind;
7125
7126 emitReplacement(*this, Call->getExprLoc(),
7127 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7128}
7129
7130//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7131void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7132 const FunctionDecl *FDecl) {
7133 if (!Call || !FDecl) return;
7134
7135 // Ignore template specializations and macros.
7136 if (inTemplateInstantiation()) return;
7137 if (Call->getExprLoc().isMacroID()) return;
7138
7139 // Only care about the one template argument, two function parameter std::max
7140 if (Call->getNumArgs() != 2) return;
7141 if (!IsStdFunction(FDecl, "max")) return;
7142 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7143 if (!ArgList) return;
7144 if (ArgList->size() != 1) return;
7145
7146 // Check that template type argument is unsigned integer.
7147 const auto& TA = ArgList->get(0);
7148 if (TA.getKind() != TemplateArgument::Type) return;
7149 QualType ArgType = TA.getAsType();
7150 if (!ArgType->isUnsignedIntegerType()) return;
7151
7152 // See if either argument is a literal zero.
7153 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7154 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7155 if (!MTE) return false;
7156 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7157 if (!Num) return false;
7158 if (Num->getValue() != 0) return false;
7159 return true;
7160 };
7161
7162 const Expr *FirstArg = Call->getArg(0);
7163 const Expr *SecondArg = Call->getArg(1);
7164 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7165 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7166
7167 // Only warn when exactly one argument is zero.
7168 if (IsFirstArgZero == IsSecondArgZero) return;
7169
7170 SourceRange FirstRange = FirstArg->getSourceRange();
7171 SourceRange SecondRange = SecondArg->getSourceRange();
7172
7173 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7174
7175 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7176 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7177
7178 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7179 SourceRange RemovalRange;
7180 if (IsFirstArgZero) {
7181 RemovalRange = SourceRange(FirstRange.getBegin(),
7182 SecondRange.getBegin().getLocWithOffset(-1));
7183 } else {
7184 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7185 SecondRange.getEnd());
7186 }
7187
7188 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7189 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7190 << FixItHint::CreateRemoval(RemovalRange);
7191}
7192
7193//===--- CHECK: Standard memory functions ---------------------------------===//
7194
7195/// \brief Takes the expression passed to the size_t parameter of functions
7196/// such as memcmp, strncat, etc and warns if it's a comparison.
7197///
7198/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7199static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7200 IdentifierInfo *FnName,
7201 SourceLocation FnLoc,
7202 SourceLocation RParenLoc) {
7203 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7204 if (!Size)
7205 return false;
7206
7207 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7208 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7209 return false;
7210
7211 SourceRange SizeRange = Size->getSourceRange();
7212 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7213 << SizeRange << FnName;
7214 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7215 << FnName << FixItHint::CreateInsertion(
7216 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7217 << FixItHint::CreateRemoval(RParenLoc);
7218 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7219 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7220 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7221 ")");
7222
7223 return true;
7224}
7225
7226/// \brief Determine whether the given type is or contains a dynamic class type
7227/// (e.g., whether it has a vtable).
7228static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7229 bool &IsContained) {
7230 // Look through array types while ignoring qualifiers.
7231 const Type *Ty = T->getBaseElementTypeUnsafe();
7232 IsContained = false;
7233
7234 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7235 RD = RD ? RD->getDefinition() : nullptr;
7236 if (!RD || RD->isInvalidDecl())
7237 return nullptr;
7238
7239 if (RD->isDynamicClass())
7240 return RD;
7241
7242 // Check all the fields. If any bases were dynamic, the class is dynamic.
7243 // It's impossible for a class to transitively contain itself by value, so
7244 // infinite recursion is impossible.
7245 for (auto *FD : RD->fields()) {
7246 bool SubContained;
7247 if (const CXXRecordDecl *ContainedRD =
7248 getContainedDynamicClass(FD->getType(), SubContained)) {
7249 IsContained = true;
7250 return ContainedRD;
7251 }
7252 }
7253
7254 return nullptr;
7255}
7256
7257/// \brief If E is a sizeof expression, returns its argument expression,
7258/// otherwise returns NULL.
7259static const Expr *getSizeOfExprArg(const Expr *E) {
7260 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7261 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7262 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7263 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7264
7265 return nullptr;
7266}
7267
7268/// \brief If E is a sizeof expression, returns its argument type.
7269static QualType getSizeOfArgType(const Expr *E) {
7270 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7271 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7272 if (SizeOf->getKind() == clang::UETT_SizeOf)
7273 return SizeOf->getTypeOfArgument();
7274
7275 return QualType();
7276}
7277
7278/// \brief Check for dangerous or invalid arguments to memset().
7279///
7280/// This issues warnings on known problematic, dangerous or unspecified
7281/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7282/// function calls.
7283///
7284/// \param Call The call expression to diagnose.
7285void Sema::CheckMemaccessArguments(const CallExpr *Call,
7286 unsigned BId,
7287 IdentifierInfo *FnName) {
7288 assert(BId != 0)((BId != 0) ? static_cast<void> (0) : __assert_fail ("BId != 0"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 7288, __PRETTY_FUNCTION__))
;
7289
7290 // It is possible to have a non-standard definition of memset. Validate
7291 // we have enough arguments, and if not, abort further checking.
7292 unsigned ExpectedNumArgs =
7293 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7294 if (Call->getNumArgs() < ExpectedNumArgs)
7295 return;
7296
7297 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7298 BId == Builtin::BIstrndup ? 1 : 2);
7299 unsigned LenArg =
7300 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7301 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7302
7303 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7304 Call->getLocStart(), Call->getRParenLoc()))
7305 return;
7306
7307 // We have special checking when the length is a sizeof expression.
7308 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7309 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7310 llvm::FoldingSetNodeID SizeOfArgID;
7311
7312 // Although widely used, 'bzero' is not a standard function. Be more strict
7313 // with the argument types before allowing diagnostics and only allow the
7314 // form bzero(ptr, sizeof(...)).
7315 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7316 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7317 return;
7318
7319 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7320 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7321 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7322
7323 QualType DestTy = Dest->getType();
7324 QualType PointeeTy;
7325 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7326 PointeeTy = DestPtrTy->getPointeeType();
7327
7328 // Never warn about void type pointers. This can be used to suppress
7329 // false positives.
7330 if (PointeeTy->isVoidType())
7331 continue;
7332
7333 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7334 // actually comparing the expressions for equality. Because computing the
7335 // expression IDs can be expensive, we only do this if the diagnostic is
7336 // enabled.
7337 if (SizeOfArg &&
7338 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7339 SizeOfArg->getExprLoc())) {
7340 // We only compute IDs for expressions if the warning is enabled, and
7341 // cache the sizeof arg's ID.
7342 if (SizeOfArgID == llvm::FoldingSetNodeID())
7343 SizeOfArg->Profile(SizeOfArgID, Context, true);
7344 llvm::FoldingSetNodeID DestID;
7345 Dest->Profile(DestID, Context, true);
7346 if (DestID == SizeOfArgID) {
7347 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7348 // over sizeof(src) as well.
7349 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7350 StringRef ReadableName = FnName->getName();
7351
7352 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7353 if (UnaryOp->getOpcode() == UO_AddrOf)
7354 ActionIdx = 1; // If its an address-of operator, just remove it.
7355 if (!PointeeTy->isIncompleteType() &&
7356 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7357 ActionIdx = 2; // If the pointee's size is sizeof(char),
7358 // suggest an explicit length.
7359
7360 // If the function is defined as a builtin macro, do not show macro
7361 // expansion.
7362 SourceLocation SL = SizeOfArg->getExprLoc();
7363 SourceRange DSR = Dest->getSourceRange();
7364 SourceRange SSR = SizeOfArg->getSourceRange();
7365 SourceManager &SM = getSourceManager();
7366
7367 if (SM.isMacroArgExpansion(SL)) {
7368 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7369 SL = SM.getSpellingLoc(SL);
7370 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7371 SM.getSpellingLoc(DSR.getEnd()));
7372 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7373 SM.getSpellingLoc(SSR.getEnd()));
7374 }
7375
7376 DiagRuntimeBehavior(SL, SizeOfArg,
7377 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7378 << ReadableName
7379 << PointeeTy
7380 << DestTy
7381 << DSR
7382 << SSR);
7383 DiagRuntimeBehavior(SL, SizeOfArg,
7384 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7385 << ActionIdx
7386 << SSR);
7387
7388 break;
7389 }
7390 }
7391
7392 // Also check for cases where the sizeof argument is the exact same
7393 // type as the memory argument, and where it points to a user-defined
7394 // record type.
7395 if (SizeOfArgTy != QualType()) {
7396 if (PointeeTy->isRecordType() &&
7397 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7398 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7399 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7400 << FnName << SizeOfArgTy << ArgIdx
7401 << PointeeTy << Dest->getSourceRange()
7402 << LenExpr->getSourceRange());
7403 break;
7404 }
7405 }
7406 } else if (DestTy->isArrayType()) {
7407 PointeeTy = DestTy;
7408 }
7409
7410 if (PointeeTy == QualType())
7411 continue;
7412
7413 // Always complain about dynamic classes.
7414 bool IsContained;
7415 if (const CXXRecordDecl *ContainedRD =
7416 getContainedDynamicClass(PointeeTy, IsContained)) {
7417
7418 unsigned OperationType = 0;
7419 // "overwritten" if we're warning about the destination for any call
7420 // but memcmp; otherwise a verb appropriate to the call.
7421 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7422 if (BId == Builtin::BImemcpy)
7423 OperationType = 1;
7424 else if(BId == Builtin::BImemmove)
7425 OperationType = 2;
7426 else if (BId == Builtin::BImemcmp)
7427 OperationType = 3;
7428 }
7429
7430 DiagRuntimeBehavior(
7431 Dest->getExprLoc(), Dest,
7432 PDiag(diag::warn_dyn_class_memaccess)
7433 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7434 << FnName << IsContained << ContainedRD << OperationType
7435 << Call->getCallee()->getSourceRange());
7436 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7437 BId != Builtin::BImemset)
7438 DiagRuntimeBehavior(
7439 Dest->getExprLoc(), Dest,
7440 PDiag(diag::warn_arc_object_memaccess)
7441 << ArgIdx << FnName << PointeeTy
7442 << Call->getCallee()->getSourceRange());
7443 else
7444 continue;
7445
7446 DiagRuntimeBehavior(
7447 Dest->getExprLoc(), Dest,
7448 PDiag(diag::note_bad_memaccess_silence)
7449 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7450 break;
7451 }
7452}
7453
7454// A little helper routine: ignore addition and subtraction of integer literals.
7455// This intentionally does not ignore all integer constant expressions because
7456// we don't want to remove sizeof().
7457static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7458 Ex = Ex->IgnoreParenCasts();
7459
7460 for (;;) {
7461 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7462 if (!BO || !BO->isAdditiveOp())
7463 break;
7464
7465 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7466 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7467
7468 if (isa<IntegerLiteral>(RHS))
7469 Ex = LHS;
7470 else if (isa<IntegerLiteral>(LHS))
7471 Ex = RHS;
7472 else
7473 break;
7474 }
7475
7476 return Ex;
7477}
7478
7479static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7480 ASTContext &Context) {
7481 // Only handle constant-sized or VLAs, but not flexible members.
7482 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7483 // Only issue the FIXIT for arrays of size > 1.
7484 if (CAT->getSize().getSExtValue() <= 1)
7485 return false;
7486 } else if (!Ty->isVariableArrayType()) {
7487 return false;
7488 }
7489 return true;
7490}
7491
7492// Warn if the user has made the 'size' argument to strlcpy or strlcat
7493// be the size of the source, instead of the destination.
7494void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7495 IdentifierInfo *FnName) {
7496
7497 // Don't crash if the user has the wrong number of arguments
7498 unsigned NumArgs = Call->getNumArgs();
7499 if ((NumArgs != 3) && (NumArgs != 4))
7500 return;
7501
7502 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7503 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7504 const Expr *CompareWithSrc = nullptr;
7505
7506 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7507 Call->getLocStart(), Call->getRParenLoc()))
7508 return;
7509
7510 // Look for 'strlcpy(dst, x, sizeof(x))'
7511 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7512 CompareWithSrc = Ex;
7513 else {
7514 // Look for 'strlcpy(dst, x, strlen(x))'
7515 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7516 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7517 SizeCall->getNumArgs() == 1)
7518 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7519 }
7520 }
7521
7522 if (!CompareWithSrc)
7523 return;
7524
7525 // Determine if the argument to sizeof/strlen is equal to the source
7526 // argument. In principle there's all kinds of things you could do
7527 // here, for instance creating an == expression and evaluating it with
7528 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7529 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7530 if (!SrcArgDRE)
7531 return;
7532
7533 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7534 if (!CompareWithSrcDRE ||
7535 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7536 return;
7537
7538 const Expr *OriginalSizeArg = Call->getArg(2);
7539 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7540 << OriginalSizeArg->getSourceRange() << FnName;
7541
7542 // Output a FIXIT hint if the destination is an array (rather than a
7543 // pointer to an array). This could be enhanced to handle some
7544 // pointers if we know the actual size, like if DstArg is 'array+2'
7545 // we could say 'sizeof(array)-2'.
7546 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7547 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7548 return;
7549
7550 SmallString<128> sizeString;
7551 llvm::raw_svector_ostream OS(sizeString);
7552 OS << "sizeof(";
7553 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7554 OS << ")";
7555
7556 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7557 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7558 OS.str());
7559}
7560
7561/// Check if two expressions refer to the same declaration.
7562static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7563 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7564 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7565 return D1->getDecl() == D2->getDecl();
7566 return false;
7567}
7568
7569static const Expr *getStrlenExprArg(const Expr *E) {
7570 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7571 const FunctionDecl *FD = CE->getDirectCallee();
7572 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7573 return nullptr;
7574 return CE->getArg(0)->IgnoreParenCasts();
7575 }
7576 return nullptr;
7577}
7578
7579// Warn on anti-patterns as the 'size' argument to strncat.
7580// The correct size argument should look like following:
7581// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7582void Sema::CheckStrncatArguments(const CallExpr *CE,
7583 IdentifierInfo *FnName) {
7584 // Don't crash if the user has the wrong number of arguments.
7585 if (CE->getNumArgs() < 3)
7586 return;
7587 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7588 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7589 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7590
7591 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7592 CE->getRParenLoc()))
7593 return;
7594
7595 // Identify common expressions, which are wrongly used as the size argument
7596 // to strncat and may lead to buffer overflows.
7597 unsigned PatternType = 0;
7598 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7599 // - sizeof(dst)
7600 if (referToTheSameDecl(SizeOfArg, DstArg))
7601 PatternType = 1;
7602 // - sizeof(src)
7603 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7604 PatternType = 2;
7605 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7606 if (BE->getOpcode() == BO_Sub) {
7607 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7608 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7609 // - sizeof(dst) - strlen(dst)
7610 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7611 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7612 PatternType = 1;
7613 // - sizeof(src) - (anything)
7614 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7615 PatternType = 2;
7616 }
7617 }
7618
7619 if (PatternType == 0)
7620 return;
7621
7622 // Generate the diagnostic.
7623 SourceLocation SL = LenArg->getLocStart();
7624 SourceRange SR = LenArg->getSourceRange();
7625 SourceManager &SM = getSourceManager();
7626
7627 // If the function is defined as a builtin macro, do not show macro expansion.
7628 if (SM.isMacroArgExpansion(SL)) {
7629 SL = SM.getSpellingLoc(SL);
7630 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7631 SM.getSpellingLoc(SR.getEnd()));
7632 }
7633
7634 // Check if the destination is an array (rather than a pointer to an array).
7635 QualType DstTy = DstArg->getType();
7636 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7637 Context);
7638 if (!isKnownSizeArray) {
7639 if (PatternType == 1)
7640 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7641 else
7642 Diag(SL, diag::warn_strncat_src_size) << SR;
7643 return;
7644 }
7645
7646 if (PatternType == 1)
7647 Diag(SL, diag::warn_strncat_large_size) << SR;
7648 else
7649 Diag(SL, diag::warn_strncat_src_size) << SR;
7650
7651 SmallString<128> sizeString;
7652 llvm::raw_svector_ostream OS(sizeString);
7653 OS << "sizeof(";
7654 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7655 OS << ") - ";
7656 OS << "strlen(";
7657 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7658 OS << ") - 1";
7659
7660 Diag(SL, diag::note_strncat_wrong_size)
7661 << FixItHint::CreateReplacement(SR, OS.str());
7662}
7663
7664//===--- CHECK: Return Address of Stack Variable --------------------------===//
7665
7666static const Expr *EvalVal(const Expr *E,
7667 SmallVectorImpl<const DeclRefExpr *> &refVars,
7668 const Decl *ParentDecl);
7669static const Expr *EvalAddr(const Expr *E,
7670 SmallVectorImpl<const DeclRefExpr *> &refVars,
7671 const Decl *ParentDecl);
7672
7673/// CheckReturnStackAddr - Check if a return statement returns the address
7674/// of a stack variable.
7675static void
7676CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7677 SourceLocation ReturnLoc) {
7678
7679 const Expr *stackE = nullptr;
7680 SmallVector<const DeclRefExpr *, 8> refVars;
7681
7682 // Perform checking for returned stack addresses, local blocks,
7683 // label addresses or references to temporaries.
7684 if (lhsType->isPointerType() ||
7685 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7686 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7687 } else if (lhsType->isReferenceType()) {
7688 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7689 }
7690
7691 if (!stackE)
7692 return; // Nothing suspicious was found.
7693
7694 // Parameters are initialized in the calling scope, so taking the address
7695 // of a parameter reference doesn't need a warning.
7696 for (auto *DRE : refVars)
7697 if (isa<ParmVarDecl>(DRE->getDecl()))
7698 return;
7699
7700 SourceLocation diagLoc;
7701 SourceRange diagRange;
7702 if (refVars.empty()) {
7703 diagLoc = stackE->getLocStart();
7704 diagRange = stackE->getSourceRange();
7705 } else {
7706 // We followed through a reference variable. 'stackE' contains the
7707 // problematic expression but we will warn at the return statement pointing
7708 // at the reference variable. We will later display the "trail" of
7709 // reference variables using notes.
7710 diagLoc = refVars[0]->getLocStart();
7711 diagRange = refVars[0]->getSourceRange();
7712 }
7713
7714 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7715 // address of local var
7716 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7717 << DR->getDecl()->getDeclName() << diagRange;
7718 } else if (isa<BlockExpr>(stackE)) { // local block.
7719 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7720 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7721 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7722 } else { // local temporary.
7723 // If there is an LValue->RValue conversion, then the value of the
7724 // reference type is used, not the reference.
7725 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7726 if (ICE->getCastKind() == CK_LValueToRValue) {
7727 return;
7728 }
7729 }
7730 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7731 << lhsType->isReferenceType() << diagRange;
7732 }
7733
7734 // Display the "trail" of reference variables that we followed until we
7735 // found the problematic expression using notes.
7736 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7737 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7738 // If this var binds to another reference var, show the range of the next
7739 // var, otherwise the var binds to the problematic expression, in which case
7740 // show the range of the expression.
7741 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7742 : stackE->getSourceRange();
7743 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7744 << VD->getDeclName() << range;
7745 }
7746}
7747
7748/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7749/// check if the expression in a return statement evaluates to an address
7750/// to a location on the stack, a local block, an address of a label, or a
7751/// reference to local temporary. The recursion is used to traverse the
7752/// AST of the return expression, with recursion backtracking when we
7753/// encounter a subexpression that (1) clearly does not lead to one of the
7754/// above problematic expressions (2) is something we cannot determine leads to
7755/// a problematic expression based on such local checking.
7756///
7757/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7758/// the expression that they point to. Such variables are added to the
7759/// 'refVars' vector so that we know what the reference variable "trail" was.
7760///
7761/// EvalAddr processes expressions that are pointers that are used as
7762/// references (and not L-values). EvalVal handles all other values.
7763/// At the base case of the recursion is a check for the above problematic
7764/// expressions.
7765///
7766/// This implementation handles:
7767///
7768/// * pointer-to-pointer casts
7769/// * implicit conversions from array references to pointers
7770/// * taking the address of fields
7771/// * arbitrary interplay between "&" and "*" operators
7772/// * pointer arithmetic from an address of a stack variable
7773/// * taking the address of an array element where the array is on the stack
7774static const Expr *EvalAddr(const Expr *E,
7775 SmallVectorImpl<const DeclRefExpr *> &refVars,
7776 const Decl *ParentDecl) {
7777 if (E->isTypeDependent())
7778 return nullptr;
7779
7780 // We should only be called for evaluating pointer expressions.
7781 assert((E->getType()->isAnyPointerType() ||(((E->getType()->isAnyPointerType() || E->getType()->
isBlockPointerType() || E->getType()->isObjCQualifiedIdType
()) && "EvalAddr only works on pointers") ? static_cast
<void> (0) : __assert_fail ("(E->getType()->isAnyPointerType() || E->getType()->isBlockPointerType() || E->getType()->isObjCQualifiedIdType()) && \"EvalAddr only works on pointers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 7784, __PRETTY_FUNCTION__))
7782 E->getType()->isBlockPointerType() ||(((E->getType()->isAnyPointerType() || E->getType()->
isBlockPointerType() || E->getType()->isObjCQualifiedIdType
()) && "EvalAddr only works on pointers") ? static_cast
<void> (0) : __assert_fail ("(E->getType()->isAnyPointerType() || E->getType()->isBlockPointerType() || E->getType()->isObjCQualifiedIdType()) && \"EvalAddr only works on pointers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 7784, __PRETTY_FUNCTION__))
7783 E->getType()->isObjCQualifiedIdType()) &&(((E->getType()->isAnyPointerType() || E->getType()->
isBlockPointerType() || E->getType()->isObjCQualifiedIdType
()) && "EvalAddr only works on pointers") ? static_cast
<void> (0) : __assert_fail ("(E->getType()->isAnyPointerType() || E->getType()->isBlockPointerType() || E->getType()->isObjCQualifiedIdType()) && \"EvalAddr only works on pointers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 7784, __PRETTY_FUNCTION__))
7784 "EvalAddr only works on pointers")(((E->getType()->isAnyPointerType() || E->getType()->
isBlockPointerType() || E->getType()->isObjCQualifiedIdType
()) && "EvalAddr only works on pointers") ? static_cast
<void> (0) : __assert_fail ("(E->getType()->isAnyPointerType() || E->getType()->isBlockPointerType() || E->getType()->isObjCQualifiedIdType()) && \"EvalAddr only works on pointers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp"
, 7784, __PRETTY_FUNCTION__))
;
7785
7786 E = E->IgnoreParens();
7787
7788 // Our "symbolic interpreter" is just a dispatch off the currently
7789 // viewed AST node. We then recursively traverse the AST by calling
7790 // EvalAddr and EvalVal appropriately.
7791 switch (E->getStmtClass()) {
7792 case Stmt::DeclRefExprClass: {
7793 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7794
7795 // If we leave the immediate function, the lifetime isn't about to end.
7796 if (DR->refersToEnclosingVariableOrCapture())
7797 return nullptr;
7798
7799 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7800 // If this is a reference variable, follow through to the expression that
7801 // it points to.
7802 if (V->hasLocalStorage() &&
7803 V->getType()->isReferenceType() && V->hasInit()) {
7804 // Add the reference variable to the "trail".
7805 refVars.push_back(DR);
7806 return EvalAddr(V->getInit(), refVars, ParentDecl);
7807 }
7808
7809 return nullptr;
7810 }
7811
7812 case Stmt::UnaryOperatorClass: {
7813 // The only unary operator that make sense to handle here
7814 // is AddrOf. All others don't make sense as pointers.
7815 const UnaryOperator *U = cast<UnaryOperator>(E);
7816
7817 if (U->getOpcode() == UO_AddrOf)
7818 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7819 return nullptr;
7820 }
7821
7822