File: | tools/clang/lib/Sema/SemaChecking.cpp |
Warning: | line 112, column 5 Potential memory leak |
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 | ||||
45 | using namespace clang; | |||
46 | using namespace sema; | |||
47 | ||||
48 | SourceLocation 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. | |||
56 | static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { | |||
57 | unsigned argCount = call->getNumArgs(); | |||
58 | if (argCount == desiredArgCount) return false; | |||
59 | ||||
60 | if (argCount < desiredArgCount) | |||
61 | return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) | |||
62 | << 0 /*function call*/ << desiredArgCount << argCount | |||
63 | << call->getSourceRange(); | |||
64 | ||||
65 | // Highlight all the excess arguments. | |||
66 | SourceRange range(call->getArg(desiredArgCount)->getLocStart(), | |||
67 | call->getArg(argCount - 1)->getLocEnd()); | |||
68 | ||||
69 | return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) | |||
70 | << 0 /*function call*/ << desiredArgCount << argCount | |||
71 | << call->getArg(1)->getSourceRange(); | |||
72 | } | |||
73 | ||||
74 | /// Check that the first argument to __builtin_annotation is an integer | |||
75 | /// and the second argument is a non-wide string literal. | |||
76 | static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { | |||
77 | if (checkArgCount(S, TheCall, 2)) | |||
78 | return true; | |||
79 | ||||
80 | // First argument should be an integer. | |||
81 | Expr *ValArg = TheCall->getArg(0); | |||
82 | QualType Ty = ValArg->getType(); | |||
83 | if (!Ty->isIntegerType()) { | |||
84 | S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) | |||
85 | << ValArg->getSourceRange(); | |||
86 | return true; | |||
87 | } | |||
88 | ||||
89 | // Second argument should be a constant string. | |||
90 | Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); | |||
91 | StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); | |||
92 | if (!Literal || !Literal->isAscii()) { | |||
93 | S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) | |||
94 | << StrArg->getSourceRange(); | |||
95 | return true; | |||
96 | } | |||
97 | ||||
98 | TheCall->setType(Ty); | |||
99 | return false; | |||
100 | } | |||
101 | ||||
102 | static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { | |||
103 | // We need at least one argument. | |||
104 | if (TheCall->getNumArgs() < 1) { | |||
105 | S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) | |||
106 | << 0 << 1 << TheCall->getNumArgs() | |||
107 | << TheCall->getCallee()->getSourceRange(); | |||
108 | return true; | |||
109 | } | |||
110 | ||||
111 | // All arguments should be wide string literals. | |||
112 | for (Expr *Arg : TheCall->arguments()) { | |||
113 | auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); | |||
114 | if (!Literal || !Literal->isWide()) { | |||
115 | S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str) | |||
116 | << Arg->getSourceRange(); | |||
117 | return true; | |||
118 | } | |||
119 | } | |||
120 | ||||
121 | return false; | |||
122 | } | |||
123 | ||||
124 | /// Check that the argument to __builtin_addressof is a glvalue, and set the | |||
125 | /// result type to the corresponding pointer type. | |||
126 | static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { | |||
127 | if (checkArgCount(S, TheCall, 1)) | |||
128 | return true; | |||
129 | ||||
130 | ExprResult Arg(TheCall->getArg(0)); | |||
131 | QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); | |||
132 | if (ResultType.isNull()) | |||
133 | return true; | |||
134 | ||||
135 | TheCall->setArg(0, Arg.get()); | |||
136 | TheCall->setType(ResultType); | |||
137 | return false; | |||
138 | } | |||
139 | ||||
140 | static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { | |||
141 | if (checkArgCount(S, TheCall, 3)) | |||
142 | return true; | |||
143 | ||||
144 | // First two arguments should be integers. | |||
145 | for (unsigned I = 0; I < 2; ++I) { | |||
146 | Expr *Arg = TheCall->getArg(I); | |||
147 | QualType Ty = Arg->getType(); | |||
148 | if (!Ty->isIntegerType()) { | |||
149 | S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int) | |||
150 | << Ty << Arg->getSourceRange(); | |||
151 | return true; | |||
152 | } | |||
153 | } | |||
154 | ||||
155 | // Third argument should be a pointer to a non-const integer. | |||
156 | // IRGen correctly handles volatile, restrict, and address spaces, and | |||
157 | // the other qualifiers aren't possible. | |||
158 | { | |||
159 | Expr *Arg = TheCall->getArg(2); | |||
160 | QualType Ty = Arg->getType(); | |||
161 | const auto *PtrTy = Ty->getAs<PointerType>(); | |||
162 | if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && | |||
163 | !PtrTy->getPointeeType().isConstQualified())) { | |||
164 | S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int) | |||
165 | << Ty << Arg->getSourceRange(); | |||
166 | return true; | |||
167 | } | |||
168 | } | |||
169 | ||||
170 | return false; | |||
171 | } | |||
172 | ||||
173 | static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, | |||
174 | CallExpr *TheCall, unsigned SizeIdx, | |||
175 | unsigned DstSizeIdx) { | |||
176 | if (TheCall->getNumArgs() <= SizeIdx || | |||
177 | TheCall->getNumArgs() <= DstSizeIdx) | |||
178 | return; | |||
179 | ||||
180 | const Expr *SizeArg = TheCall->getArg(SizeIdx); | |||
181 | const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); | |||
182 | ||||
183 | llvm::APSInt Size, DstSize; | |||
184 | ||||
185 | // find out if both sizes are known at compile time | |||
186 | if (!SizeArg->EvaluateAsInt(Size, S.Context) || | |||
187 | !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) | |||
188 | return; | |||
189 | ||||
190 | if (Size.ule(DstSize)) | |||
191 | return; | |||
192 | ||||
193 | // confirmed overflow so generate the diagnostic. | |||
194 | IdentifierInfo *FnName = FDecl->getIdentifier(); | |||
195 | SourceLocation SL = TheCall->getLocStart(); | |||
196 | SourceRange SR = TheCall->getSourceRange(); | |||
197 | ||||
198 | S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; | |||
199 | } | |||
200 | ||||
201 | static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { | |||
202 | if (checkArgCount(S, BuiltinCall, 2)) | |||
203 | return true; | |||
204 | ||||
205 | SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); | |||
206 | Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); | |||
207 | Expr *Call = BuiltinCall->getArg(0); | |||
208 | Expr *Chain = BuiltinCall->getArg(1); | |||
209 | ||||
210 | if (Call->getStmtClass() != Stmt::CallExprClass) { | |||
211 | S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) | |||
212 | << Call->getSourceRange(); | |||
213 | return true; | |||
214 | } | |||
215 | ||||
216 | auto CE = cast<CallExpr>(Call); | |||
217 | if (CE->getCallee()->getType()->isBlockPointerType()) { | |||
218 | S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) | |||
219 | << Call->getSourceRange(); | |||
220 | return true; | |||
221 | } | |||
222 | ||||
223 | const Decl *TargetDecl = CE->getCalleeDecl(); | |||
224 | if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) | |||
225 | if (FD->getBuiltinID()) { | |||
226 | S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) | |||
227 | << Call->getSourceRange(); | |||
228 | return true; | |||
229 | } | |||
230 | ||||
231 | if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { | |||
232 | S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) | |||
233 | << Call->getSourceRange(); | |||
234 | return true; | |||
235 | } | |||
236 | ||||
237 | ExprResult ChainResult = S.UsualUnaryConversions(Chain); | |||
238 | if (ChainResult.isInvalid()) | |||
239 | return true; | |||
240 | if (!ChainResult.get()->getType()->isPointerType()) { | |||
241 | S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) | |||
242 | << Chain->getSourceRange(); | |||
243 | return true; | |||
244 | } | |||
245 | ||||
246 | QualType ReturnTy = CE->getCallReturnType(S.Context); | |||
247 | QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; | |||
248 | QualType BuiltinTy = S.Context.getFunctionType( | |||
249 | ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); | |||
250 | QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); | |||
251 | ||||
252 | Builtin = | |||
253 | S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); | |||
254 | ||||
255 | BuiltinCall->setType(CE->getType()); | |||
256 | BuiltinCall->setValueKind(CE->getValueKind()); | |||
257 | BuiltinCall->setObjectKind(CE->getObjectKind()); | |||
258 | BuiltinCall->setCallee(Builtin); | |||
259 | BuiltinCall->setArg(1, ChainResult.get()); | |||
260 | ||||
261 | return false; | |||
262 | } | |||
263 | ||||
264 | static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, | |||
265 | Scope::ScopeFlags NeededScopeFlags, | |||
266 | unsigned DiagID) { | |||
267 | // Scopes aren't available during instantiation. Fortunately, builtin | |||
268 | // functions cannot be template args so they cannot be formed through template | |||
269 | // instantiation. Therefore checking once during the parse is sufficient. | |||
270 | if (SemaRef.inTemplateInstantiation()) | |||
271 | return false; | |||
272 | ||||
273 | Scope *S = SemaRef.getCurScope(); | |||
274 | while (S && !S->isSEHExceptScope()) | |||
275 | S = S->getParent(); | |||
276 | if (!S || !(S->getFlags() & NeededScopeFlags)) { | |||
277 | auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); | |||
278 | SemaRef.Diag(TheCall->getExprLoc(), DiagID) | |||
279 | << DRE->getDecl()->getIdentifier(); | |||
280 | return true; | |||
281 | } | |||
282 | ||||
283 | return false; | |||
284 | } | |||
285 | ||||
286 | static inline bool isBlockPointer(Expr *Arg) { | |||
287 | return Arg->getType()->isBlockPointerType(); | |||
288 | } | |||
289 | ||||
290 | /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local | |||
291 | /// void*, which is a requirement of device side enqueue. | |||
292 | static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { | |||
293 | const BlockPointerType *BPT = | |||
294 | cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); | |||
295 | ArrayRef<QualType> Params = | |||
296 | BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); | |||
297 | unsigned ArgCounter = 0; | |||
298 | bool IllegalParams = false; | |||
299 | // Iterate through the block parameters until either one is found that is not | |||
300 | // a local void*, or the block is valid. | |||
301 | for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); | |||
302 | I != E; ++I, ++ArgCounter) { | |||
303 | if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || | |||
304 | (*I)->getPointeeType().getQualifiers().getAddressSpace() != | |||
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 | ||||
325 | static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { | |||
326 | if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { | |||
327 | S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) | |||
328 | << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; | |||
329 | return true; | |||
330 | } | |||
331 | return false; | |||
332 | } | |||
333 | ||||
334 | static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { | |||
335 | if (checkArgCount(S, TheCall, 2)) | |||
336 | return true; | |||
337 | ||||
338 | if (checkOpenCLSubgroupExt(S, TheCall)) | |||
339 | return true; | |||
340 | ||||
341 | // First argument is an ndrange_t type. | |||
342 | Expr *NDRangeArg = TheCall->getArg(0); | |||
343 | if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { | |||
344 | S.Diag(NDRangeArg->getLocStart(), | |||
345 | diag::err_opencl_builtin_expected_type) | |||
346 | << TheCall->getDirectCallee() << "'ndrange_t'"; | |||
347 | return true; | |||
348 | } | |||
349 | ||||
350 | Expr *BlockArg = TheCall->getArg(1); | |||
351 | if (!isBlockPointer(BlockArg)) { | |||
352 | S.Diag(BlockArg->getLocStart(), | |||
353 | diag::err_opencl_builtin_expected_type) | |||
354 | << TheCall->getDirectCallee() << "block"; | |||
355 | return true; | |||
356 | } | |||
357 | return checkOpenCLBlockArgs(S, BlockArg); | |||
358 | } | |||
359 | ||||
360 | /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the | |||
361 | /// get_kernel_work_group_size | |||
362 | /// and get_kernel_preferred_work_group_size_multiple builtin functions. | |||
363 | static 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. | |||
378 | static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, | |||
379 | const QualType &IntType); | |||
380 | ||||
381 | static 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. | |||
392 | static 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, ...) | |||
440 | static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { | |||
441 | unsigned NumArgs = TheCall->getNumArgs(); | |||
442 | ||||
443 | if (NumArgs < 4) { | |||
444 | S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); | |||
445 | return true; | |||
446 | } | |||
447 | ||||
448 | Expr *Arg0 = TheCall->getArg(0); | |||
449 | Expr *Arg1 = TheCall->getArg(1); | |||
450 | Expr *Arg2 = TheCall->getArg(2); | |||
451 | Expr *Arg3 = TheCall->getArg(3); | |||
452 | ||||
453 | // First argument always needs to be a queue_t type. | |||
454 | if (!Arg0->getType()->isQueueT()) { | |||
455 | S.Diag(TheCall->getArg(0)->getLocStart(), | |||
456 | diag::err_opencl_builtin_expected_type) | |||
457 | << TheCall->getDirectCallee() << S.Context.OCLQueueTy; | |||
458 | return true; | |||
459 | } | |||
460 | ||||
461 | // Second argument always needs to be a kernel_enqueue_flags_t enum value. | |||
462 | if (!Arg1->getType()->isIntegerType()) { | |||
463 | S.Diag(TheCall->getArg(1)->getLocStart(), | |||
464 | diag::err_opencl_builtin_expected_type) | |||
465 | << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; | |||
466 | return true; | |||
467 | } | |||
468 | ||||
469 | // Third argument is always an ndrange_t type. | |||
470 | if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { | |||
471 | S.Diag(TheCall->getArg(2)->getLocStart(), | |||
472 | diag::err_opencl_builtin_expected_type) | |||
473 | << TheCall->getDirectCallee() << "'ndrange_t'"; | |||
474 | return true; | |||
475 | } | |||
476 | ||||
477 | // With four arguments, there is only one form that the function could be | |||
478 | // called in: no events and no variable arguments. | |||
479 | if (NumArgs == 4) { | |||
480 | // check that the last argument is the right block type. | |||
481 | if (!isBlockPointer(Arg3)) { | |||
482 | S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) | |||
483 | << TheCall->getDirectCallee() << "block"; | |||
484 | return true; | |||
485 | } | |||
486 | // we have a block type, check the prototype | |||
487 | const BlockPointerType *BPT = | |||
488 | cast<BlockPointerType>(Arg3->getType().getCanonicalType()); | |||
489 | if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { | |||
490 | S.Diag(Arg3->getLocStart(), | |||
491 | diag::err_opencl_enqueue_kernel_blocks_no_args); | |||
492 | return true; | |||
493 | } | |||
494 | return false; | |||
495 | } | |||
496 | // we can have block + varargs. | |||
497 | if (isBlockPointer(Arg3)) | |||
498 | return (checkOpenCLBlockArgs(S, Arg3) || | |||
499 | checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); | |||
500 | // last two cases with either exactly 7 args or 7 args and varargs. | |||
501 | if (NumArgs >= 7) { | |||
502 | // check common block argument. | |||
503 | Expr *Arg6 = TheCall->getArg(6); | |||
504 | if (!isBlockPointer(Arg6)) { | |||
505 | S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) | |||
506 | << TheCall->getDirectCallee() << "block"; | |||
507 | return true; | |||
508 | } | |||
509 | if (checkOpenCLBlockArgs(S, Arg6)) | |||
510 | return true; | |||
511 | ||||
512 | // Forth argument has to be any integer type. | |||
513 | if (!Arg3->getType()->isIntegerType()) { | |||
514 | S.Diag(TheCall->getArg(3)->getLocStart(), | |||
515 | diag::err_opencl_builtin_expected_type) | |||
516 | << TheCall->getDirectCallee() << "integer"; | |||
517 | return true; | |||
518 | } | |||
519 | // check remaining common arguments. | |||
520 | Expr *Arg4 = TheCall->getArg(4); | |||
521 | Expr *Arg5 = TheCall->getArg(5); | |||
522 | ||||
523 | // Fifth argument is always passed as a pointer to clk_event_t. | |||
524 | if (!Arg4->isNullPointerConstant(S.Context, | |||
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. | |||
559 | static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { | |||
560 | return D->getAttr<OpenCLAccessAttr>(); | |||
561 | } | |||
562 | ||||
563 | /// Returns true if pipe element type is different from the pointer. | |||
564 | static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { | |||
565 | const Expr *Arg0 = Call->getArg(0); | |||
566 | // First argument type should always be pipe. | |||
567 | if (!Arg0->getType()->isPipeType()) { | |||
568 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) | |||
569 | << Call->getDirectCallee() << Arg0->getSourceRange(); | |||
570 | return true; | |||
571 | } | |||
572 | OpenCLAccessAttr *AccessQual = | |||
573 | getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); | |||
574 | // Validates the access qualifier is compatible with the call. | |||
575 | // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be | |||
576 | // read_only and write_only, and assumed to be read_only if no qualifier is | |||
577 | // specified. | |||
578 | switch (Call->getDirectCallee()->getBuiltinID()) { | |||
579 | case Builtin::BIread_pipe: | |||
580 | case Builtin::BIreserve_read_pipe: | |||
581 | case Builtin::BIcommit_read_pipe: | |||
582 | case Builtin::BIwork_group_reserve_read_pipe: | |||
583 | case Builtin::BIsub_group_reserve_read_pipe: | |||
584 | case Builtin::BIwork_group_commit_read_pipe: | |||
585 | case Builtin::BIsub_group_commit_read_pipe: | |||
586 | if (!(!AccessQual || AccessQual->isReadOnly())) { | |||
587 | S.Diag(Arg0->getLocStart(), | |||
588 | diag::err_opencl_builtin_pipe_invalid_access_modifier) | |||
589 | << "read_only" << Arg0->getSourceRange(); | |||
590 | return true; | |||
591 | } | |||
592 | break; | |||
593 | case Builtin::BIwrite_pipe: | |||
594 | case Builtin::BIreserve_write_pipe: | |||
595 | case Builtin::BIcommit_write_pipe: | |||
596 | case Builtin::BIwork_group_reserve_write_pipe: | |||
597 | case Builtin::BIsub_group_reserve_write_pipe: | |||
598 | case Builtin::BIwork_group_commit_write_pipe: | |||
599 | case Builtin::BIsub_group_commit_write_pipe: | |||
600 | if (!(AccessQual && AccessQual->isWriteOnly())) { | |||
601 | S.Diag(Arg0->getLocStart(), | |||
602 | diag::err_opencl_builtin_pipe_invalid_access_modifier) | |||
603 | << "write_only" << Arg0->getSourceRange(); | |||
604 | return true; | |||
605 | } | |||
606 | break; | |||
607 | default: | |||
608 | break; | |||
609 | } | |||
610 | return false; | |||
611 | } | |||
612 | ||||
613 | /// Returns true if pipe element type is different from the pointer. | |||
614 | static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { | |||
615 | const Expr *Arg0 = Call->getArg(0); | |||
616 | const Expr *ArgIdx = Call->getArg(Idx); | |||
617 | const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); | |||
618 | const QualType EltTy = PipeTy->getElementType(); | |||
619 | const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); | |||
620 | // The Idx argument should be a pointer and the type of the pointer and | |||
621 | // the type of pipe element should also be the same. | |||
622 | if (!ArgTy || | |||
623 | !S.Context.hasSameType( | |||
624 | EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { | |||
625 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
626 | << Call->getDirectCallee() << S.Context.getPointerType(EltTy) | |||
627 | << ArgIdx->getType() << ArgIdx->getSourceRange(); | |||
628 | return true; | |||
629 | } | |||
630 | return false; | |||
631 | } | |||
632 | ||||
633 | // \brief Performs semantic analysis for the read/write_pipe call. | |||
634 | // \param S Reference to the semantic analyzer. | |||
635 | // \param Call A pointer to the builtin call. | |||
636 | // \return True if a semantic error has been found, false otherwise. | |||
637 | static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { | |||
638 | // OpenCL v2.0 s6.13.16.2 - The built-in read/write | |||
639 | // functions have two forms. | |||
640 | switch (Call->getNumArgs()) { | |||
641 | case 2: { | |||
642 | if (checkOpenCLPipeArg(S, Call)) | |||
643 | return true; | |||
644 | // The call with 2 arguments should be | |||
645 | // read/write_pipe(pipe T, T*). | |||
646 | // Check packet type T. | |||
647 | if (checkOpenCLPipePacketType(S, Call, 1)) | |||
648 | return true; | |||
649 | } break; | |||
650 | ||||
651 | case 4: { | |||
652 | if (checkOpenCLPipeArg(S, Call)) | |||
653 | return true; | |||
654 | // The call with 4 arguments should be | |||
655 | // read/write_pipe(pipe T, reserve_id_t, uint, T*). | |||
656 | // Check reserve_id_t. | |||
657 | if (!Call->getArg(1)->getType()->isReserveIDT()) { | |||
658 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
659 | << Call->getDirectCallee() << S.Context.OCLReserveIDTy | |||
660 | << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); | |||
661 | return true; | |||
662 | } | |||
663 | ||||
664 | // Check the index. | |||
665 | const Expr *Arg2 = Call->getArg(2); | |||
666 | if (!Arg2->getType()->isIntegerType() && | |||
667 | !Arg2->getType()->isUnsignedIntegerType()) { | |||
668 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
669 | << Call->getDirectCallee() << S.Context.UnsignedIntTy | |||
670 | << Arg2->getType() << Arg2->getSourceRange(); | |||
671 | return true; | |||
672 | } | |||
673 | ||||
674 | // Check packet type T. | |||
675 | if (checkOpenCLPipePacketType(S, Call, 3)) | |||
676 | return true; | |||
677 | } break; | |||
678 | default: | |||
679 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) | |||
680 | << Call->getDirectCallee() << Call->getSourceRange(); | |||
681 | return true; | |||
682 | } | |||
683 | ||||
684 | return false; | |||
685 | } | |||
686 | ||||
687 | // \brief Performs a semantic analysis on the {work_group_/sub_group_ | |||
688 | // /_}reserve_{read/write}_pipe | |||
689 | // \param S Reference to the semantic analyzer. | |||
690 | // \param Call The call to the builtin function to be analyzed. | |||
691 | // \return True if a semantic error was found, false otherwise. | |||
692 | static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { | |||
693 | if (checkArgCount(S, Call, 2)) | |||
694 | return true; | |||
695 | ||||
696 | if (checkOpenCLPipeArg(S, Call)) | |||
697 | return true; | |||
698 | ||||
699 | // Check the reserve size. | |||
700 | if (!Call->getArg(1)->getType()->isIntegerType() && | |||
701 | !Call->getArg(1)->getType()->isUnsignedIntegerType()) { | |||
702 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
703 | << Call->getDirectCallee() << S.Context.UnsignedIntTy | |||
704 | << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); | |||
705 | return true; | |||
706 | } | |||
707 | ||||
708 | // Since return type of reserve_read/write_pipe built-in function is | |||
709 | // reserve_id_t, which is not defined in the builtin def file , we used int | |||
710 | // as return type and need to override the return type of these functions. | |||
711 | Call->setType(S.Context.OCLReserveIDTy); | |||
712 | ||||
713 | return false; | |||
714 | } | |||
715 | ||||
716 | // \brief Performs a semantic analysis on {work_group_/sub_group_ | |||
717 | // /_}commit_{read/write}_pipe | |||
718 | // \param S Reference to the semantic analyzer. | |||
719 | // \param Call The call to the builtin function to be analyzed. | |||
720 | // \return True if a semantic error was found, false otherwise. | |||
721 | static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { | |||
722 | if (checkArgCount(S, Call, 2)) | |||
723 | return true; | |||
724 | ||||
725 | if (checkOpenCLPipeArg(S, Call)) | |||
726 | return true; | |||
727 | ||||
728 | // Check reserve_id_t. | |||
729 | if (!Call->getArg(1)->getType()->isReserveIDT()) { | |||
730 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
731 | << Call->getDirectCallee() << S.Context.OCLReserveIDTy | |||
732 | << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); | |||
733 | return true; | |||
734 | } | |||
735 | ||||
736 | return false; | |||
737 | } | |||
738 | ||||
739 | // \brief Performs a semantic analysis on the call to built-in Pipe | |||
740 | // Query Functions. | |||
741 | // \param S Reference to the semantic analyzer. | |||
742 | // \param Call The call to the builtin function to be analyzed. | |||
743 | // \return True if a semantic error was found, false otherwise. | |||
744 | static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { | |||
745 | if (checkArgCount(S, Call, 1)) | |||
746 | return true; | |||
747 | ||||
748 | if (!Call->getArg(0)->getType()->isPipeType()) { | |||
749 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) | |||
750 | << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); | |||
751 | return true; | |||
752 | } | |||
753 | ||||
754 | return false; | |||
755 | } | |||
756 | // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions. | |||
757 | // \brief Performs semantic analysis for the to_global/local/private call. | |||
758 | // \param S Reference to the semantic analyzer. | |||
759 | // \param BuiltinID ID of the builtin function. | |||
760 | // \param Call A pointer to the builtin call. | |||
761 | // \return True if a semantic error has been found, false otherwise. | |||
762 | static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, | |||
763 | CallExpr *Call) { | |||
764 | if (Call->getNumArgs() != 1) { | |||
765 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) | |||
766 | << Call->getDirectCallee() << Call->getSourceRange(); | |||
767 | return true; | |||
768 | } | |||
769 | ||||
770 | auto RT = Call->getArg(0)->getType(); | |||
771 | if (!RT->isPointerType() || RT->getPointeeType() | |||
772 | .getAddressSpace() == LangAS::opencl_constant) { | |||
773 | S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) | |||
774 | << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); | |||
775 | return true; | |||
776 | } | |||
777 | ||||
778 | RT = RT->getPointeeType(); | |||
779 | auto Qual = RT.getQualifiers(); | |||
780 | switch (BuiltinID) { | |||
781 | case Builtin::BIto_global: | |||
782 | Qual.setAddressSpace(LangAS::opencl_global); | |||
783 | break; | |||
784 | case Builtin::BIto_local: | |||
785 | Qual.setAddressSpace(LangAS::opencl_local); | |||
786 | break; | |||
787 | case Builtin::BIto_private: | |||
788 | Qual.setAddressSpace(LangAS::opencl_private); | |||
789 | break; | |||
790 | default: | |||
791 | llvm_unreachable("Invalid builtin function")::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 | ||||
799 | ExprResult | |||
800 | Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, | |||
801 | CallExpr *TheCall) { | |||
802 | ExprResult TheCallResult(TheCall); | |||
803 | ||||
804 | // Find out if any arguments are required to be integer constant expressions. | |||
805 | unsigned ICEArguments = 0; | |||
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. | |||
1226 | static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { | |||
1227 | NeonTypeFlags Type(t); | |||
1228 | int IsQuad = ForceQuad ? true : Type.isQuad(); | |||
1229 | switch (Type.getEltType()) { | |||
1230 | case NeonTypeFlags::Int8: | |||
1231 | case NeonTypeFlags::Poly8: | |||
1232 | return shift ? 7 : (8 << IsQuad) - 1; | |||
1233 | case NeonTypeFlags::Int16: | |||
1234 | case NeonTypeFlags::Poly16: | |||
1235 | return shift ? 15 : (4 << IsQuad) - 1; | |||
1236 | case NeonTypeFlags::Int32: | |||
1237 | return shift ? 31 : (2 << IsQuad) - 1; | |||
1238 | case NeonTypeFlags::Int64: | |||
1239 | case NeonTypeFlags::Poly64: | |||
1240 | return shift ? 63 : (1 << IsQuad) - 1; | |||
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. | |||
1259 | static 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 | ||||
1295 | bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { | |||
1296 | llvm::APSInt Result; | |||
1297 | uint64_t mask = 0; | |||
1298 | unsigned TV = 0; | |||
1299 | int PtrArgNum = -1; | |||
1300 | bool HasConstPtr = false; | |||
1301 | switch (BuiltinID) { | |||
1302 | #define GET_NEON_OVERLOAD_CHECK | |||
1303 | #include "clang/Basic/arm_neon.inc" | |||
1304 | #undef GET_NEON_OVERLOAD_CHECK | |||
1305 | } | |||
1306 | ||||
1307 | // For NEON intrinsics which are overloaded on vector element type, validate | |||
1308 | // the immediate which specifies which variant to emit. | |||
1309 | unsigned ImmArg = TheCall->getNumArgs()-1; | |||
1310 | if (mask) { | |||
1311 | if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) | |||
1312 | return true; | |||
1313 | ||||
1314 | TV = Result.getLimitedValue(64); | |||
1315 | if ((TV > 63) || (mask & (1ULL << TV)) == 0) | |||
1316 | return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) | |||
1317 | << TheCall->getArg(ImmArg)->getSourceRange(); | |||
1318 | } | |||
1319 | ||||
1320 | if (PtrArgNum >= 0) { | |||
1321 | // Check that pointer arguments have the specified type. | |||
1322 | Expr *Arg = TheCall->getArg(PtrArgNum); | |||
1323 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) | |||
1324 | Arg = ICE->getSubExpr(); | |||
1325 | ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); | |||
1326 | QualType RHSTy = RHS.get()->getType(); | |||
1327 | ||||
1328 | llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); | |||
1329 | bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || | |||
1330 | Arch == llvm::Triple::aarch64_be; | |||
1331 | bool IsInt64Long = | |||
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 | ||||
1361 | bool 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 | ||||
1477 | bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { | |||
1478 | if (BuiltinID == ARM::BI__builtin_arm_ldrex || | |||
1479 | BuiltinID == ARM::BI__builtin_arm_ldaex || | |||
1480 | BuiltinID == ARM::BI__builtin_arm_strex || | |||
1481 | BuiltinID == ARM::BI__builtin_arm_stlex) { | |||
1482 | return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); | |||
1483 | } | |||
1484 | ||||
1485 | if (BuiltinID == ARM::BI__builtin_arm_prefetch) { | |||
1486 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || | |||
1487 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); | |||
1488 | } | |||
1489 | ||||
1490 | if (BuiltinID == ARM::BI__builtin_arm_rsr64 || | |||
1491 | BuiltinID == ARM::BI__builtin_arm_wsr64) | |||
1492 | return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); | |||
1493 | ||||
1494 | if (BuiltinID == ARM::BI__builtin_arm_rsr || | |||
1495 | BuiltinID == ARM::BI__builtin_arm_rsrp || | |||
1496 | BuiltinID == ARM::BI__builtin_arm_wsr || | |||
1497 | BuiltinID == ARM::BI__builtin_arm_wsrp) | |||
1498 | return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); | |||
1499 | ||||
1500 | if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) | |||
1501 | return true; | |||
1502 | ||||
1503 | // For intrinsics which take an immediate value as part of the instruction, | |||
1504 | // range check them here. | |||
1505 | unsigned i = 0, l = 0, u = 0; | |||
1506 | switch (BuiltinID) { | |||
1507 | default: return false; | |||
1508 | case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; | |||
1509 | case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; | |||
1510 | case ARM::BI__builtin_arm_vcvtr_f: | |||
1511 | case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; | |||
1512 | case ARM::BI__builtin_arm_dmb: | |||
1513 | case ARM::BI__builtin_arm_dsb: | |||
1514 | case ARM::BI__builtin_arm_isb: | |||
1515 | case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; | |||
1516 | } | |||
1517 | ||||
1518 | // FIXME: VFP Intrinsics should error if VFP not present. | |||
1519 | return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); | |||
1520 | } | |||
1521 | ||||
1522 | bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, | |||
1523 | CallExpr *TheCall) { | |||
1524 | if (BuiltinID == AArch64::BI__builtin_arm_ldrex || | |||
1525 | BuiltinID == AArch64::BI__builtin_arm_ldaex || | |||
1526 | BuiltinID == AArch64::BI__builtin_arm_strex || | |||
1527 | BuiltinID == AArch64::BI__builtin_arm_stlex) { | |||
1528 | return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); | |||
1529 | } | |||
1530 | ||||
1531 | if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { | |||
1532 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || | |||
1533 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || | |||
1534 | SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || | |||
1535 | SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); | |||
1536 | } | |||
1537 | ||||
1538 | if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || | |||
1539 | BuiltinID == AArch64::BI__builtin_arm_wsr64) | |||
1540 | return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); | |||
1541 | ||||
1542 | if (BuiltinID == AArch64::BI__builtin_arm_rsr || | |||
1543 | BuiltinID == AArch64::BI__builtin_arm_rsrp || | |||
1544 | BuiltinID == AArch64::BI__builtin_arm_wsr || | |||
1545 | BuiltinID == AArch64::BI__builtin_arm_wsrp) | |||
1546 | return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); | |||
1547 | ||||
1548 | if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) | |||
1549 | return true; | |||
1550 | ||||
1551 | // For intrinsics which take an immediate value as part of the instruction, | |||
1552 | // range check them here. | |||
1553 | unsigned i = 0, l = 0, u = 0; | |||
1554 | switch (BuiltinID) { | |||
1555 | default: return false; | |||
1556 | case AArch64::BI__builtin_arm_dmb: | |||
1557 | case AArch64::BI__builtin_arm_dsb: | |||
1558 | case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; | |||
1559 | } | |||
1560 | ||||
1561 | return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); | |||
1562 | } | |||
1563 | ||||
1564 | // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the | |||
1565 | // intrinsic is correct. The switch statement is ordered by DSP, MSA. The | |||
1566 | // ordering for DSP is unspecified. MSA is ordered by the data format used | |||
1567 | // by the underlying instruction i.e., df/m, df/n and then by size. | |||
1568 | // | |||
1569 | // FIXME: The size tests here should instead be tablegen'd along with the | |||
1570 | // definitions from include/clang/Basic/BuiltinsMips.def. | |||
1571 | // FIXME: GCC is strict on signedness for some of these intrinsics, we should | |||
1572 | // be too. | |||
1573 | bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { | |||
1574 | unsigned i = 0, l = 0, u = 0, m = 0; | |||
1575 | switch (BuiltinID) { | |||
1576 | default: return false; | |||
1577 | case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; | |||
1578 | case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; | |||
1579 | case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; | |||
1580 | case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; | |||
1581 | case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; | |||
1582 | case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; | |||
1583 | case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; | |||
1584 | // MSA instrinsics. Instructions (which the intrinsics maps to) which use the | |||
1585 | // df/m field. | |||
1586 | // These intrinsics take an unsigned 3 bit immediate. | |||
1587 | case Mips::BI__builtin_msa_bclri_b: | |||
1588 | case Mips::BI__builtin_msa_bnegi_b: | |||
1589 | case Mips::BI__builtin_msa_bseti_b: | |||
1590 | case Mips::BI__builtin_msa_sat_s_b: | |||
1591 | case Mips::BI__builtin_msa_sat_u_b: | |||
1592 | case Mips::BI__builtin_msa_slli_b: | |||
1593 | case Mips::BI__builtin_msa_srai_b: | |||
1594 | case Mips::BI__builtin_msa_srari_b: | |||
1595 | case Mips::BI__builtin_msa_srli_b: | |||
1596 | case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; | |||
1597 | case Mips::BI__builtin_msa_binsli_b: | |||
1598 | case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; | |||
1599 | // These intrinsics take an unsigned 4 bit immediate. | |||
1600 | case Mips::BI__builtin_msa_bclri_h: | |||
1601 | case Mips::BI__builtin_msa_bnegi_h: | |||
1602 | case Mips::BI__builtin_msa_bseti_h: | |||
1603 | case Mips::BI__builtin_msa_sat_s_h: | |||
1604 | case Mips::BI__builtin_msa_sat_u_h: | |||
1605 | case Mips::BI__builtin_msa_slli_h: | |||
1606 | case Mips::BI__builtin_msa_srai_h: | |||
1607 | case Mips::BI__builtin_msa_srari_h: | |||
1608 | case Mips::BI__builtin_msa_srli_h: | |||
1609 | case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; | |||
1610 | case Mips::BI__builtin_msa_binsli_h: | |||
1611 | case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; | |||
1612 | // These intrinsics take an unsigned 5 bit immedate. | |||
1613 | // The first block of intrinsics actually have an unsigned 5 bit field, | |||
1614 | // not a df/n field. | |||
1615 | case Mips::BI__builtin_msa_clei_u_b: | |||
1616 | case Mips::BI__builtin_msa_clei_u_h: | |||
1617 | case Mips::BI__builtin_msa_clei_u_w: | |||
1618 | case Mips::BI__builtin_msa_clei_u_d: | |||
1619 | case Mips::BI__builtin_msa_clti_u_b: | |||
1620 | case Mips::BI__builtin_msa_clti_u_h: | |||
1621 | case Mips::BI__builtin_msa_clti_u_w: | |||
1622 | case Mips::BI__builtin_msa_clti_u_d: | |||
1623 | case Mips::BI__builtin_msa_maxi_u_b: | |||
1624 | case Mips::BI__builtin_msa_maxi_u_h: | |||
1625 | case Mips::BI__builtin_msa_maxi_u_w: | |||
1626 | case Mips::BI__builtin_msa_maxi_u_d: | |||
1627 | case Mips::BI__builtin_msa_mini_u_b: | |||
1628 | case Mips::BI__builtin_msa_mini_u_h: | |||
1629 | case Mips::BI__builtin_msa_mini_u_w: | |||
1630 | case Mips::BI__builtin_msa_mini_u_d: | |||
1631 | case Mips::BI__builtin_msa_addvi_b: | |||
1632 | case Mips::BI__builtin_msa_addvi_h: | |||
1633 | case Mips::BI__builtin_msa_addvi_w: | |||
1634 | case Mips::BI__builtin_msa_addvi_d: | |||
1635 | case Mips::BI__builtin_msa_bclri_w: | |||
1636 | case Mips::BI__builtin_msa_bnegi_w: | |||
1637 | case Mips::BI__builtin_msa_bseti_w: | |||
1638 | case Mips::BI__builtin_msa_sat_s_w: | |||
1639 | case Mips::BI__builtin_msa_sat_u_w: | |||
1640 | case Mips::BI__builtin_msa_slli_w: | |||
1641 | case Mips::BI__builtin_msa_srai_w: | |||
1642 | case Mips::BI__builtin_msa_srari_w: | |||
1643 | case Mips::BI__builtin_msa_srli_w: | |||
1644 | case Mips::BI__builtin_msa_srlri_w: | |||
1645 | case Mips::BI__builtin_msa_subvi_b: | |||
1646 | case Mips::BI__builtin_msa_subvi_h: | |||
1647 | case Mips::BI__builtin_msa_subvi_w: | |||
1648 | case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; | |||
1649 | case Mips::BI__builtin_msa_binsli_w: | |||
1650 | case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; | |||
1651 | // These intrinsics take an unsigned 6 bit immediate. | |||
1652 | case Mips::BI__builtin_msa_bclri_d: | |||
1653 | case Mips::BI__builtin_msa_bnegi_d: | |||
1654 | case Mips::BI__builtin_msa_bseti_d: | |||
1655 | case Mips::BI__builtin_msa_sat_s_d: | |||
1656 | case Mips::BI__builtin_msa_sat_u_d: | |||
1657 | case Mips::BI__builtin_msa_slli_d: | |||
1658 | case Mips::BI__builtin_msa_srai_d: | |||
1659 | case Mips::BI__builtin_msa_srari_d: | |||
1660 | case Mips::BI__builtin_msa_srli_d: | |||
1661 | case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; | |||
1662 | case Mips::BI__builtin_msa_binsli_d: | |||
1663 | case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; | |||
1664 | // These intrinsics take a signed 5 bit immediate. | |||
1665 | case Mips::BI__builtin_msa_ceqi_b: | |||
1666 | case Mips::BI__builtin_msa_ceqi_h: | |||
1667 | case Mips::BI__builtin_msa_ceqi_w: | |||
1668 | case Mips::BI__builtin_msa_ceqi_d: | |||
1669 | case Mips::BI__builtin_msa_clti_s_b: | |||
1670 | case Mips::BI__builtin_msa_clti_s_h: | |||
1671 | case Mips::BI__builtin_msa_clti_s_w: | |||
1672 | case Mips::BI__builtin_msa_clti_s_d: | |||
1673 | case Mips::BI__builtin_msa_clei_s_b: | |||
1674 | case Mips::BI__builtin_msa_clei_s_h: | |||
1675 | case Mips::BI__builtin_msa_clei_s_w: | |||
1676 | case Mips::BI__builtin_msa_clei_s_d: | |||
1677 | case Mips::BI__builtin_msa_maxi_s_b: | |||
1678 | case Mips::BI__builtin_msa_maxi_s_h: | |||
1679 | case Mips::BI__builtin_msa_maxi_s_w: | |||
1680 | case Mips::BI__builtin_msa_maxi_s_d: | |||
1681 | case Mips::BI__builtin_msa_mini_s_b: | |||
1682 | case Mips::BI__builtin_msa_mini_s_h: | |||
1683 | case Mips::BI__builtin_msa_mini_s_w: | |||
1684 | case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; | |||
1685 | // These intrinsics take an unsigned 8 bit immediate. | |||
1686 | case Mips::BI__builtin_msa_andi_b: | |||
1687 | case Mips::BI__builtin_msa_nori_b: | |||
1688 | case Mips::BI__builtin_msa_ori_b: | |||
1689 | case Mips::BI__builtin_msa_shf_b: | |||
1690 | case Mips::BI__builtin_msa_shf_h: | |||
1691 | case Mips::BI__builtin_msa_shf_w: | |||
1692 | case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; | |||
1693 | case Mips::BI__builtin_msa_bseli_b: | |||
1694 | case Mips::BI__builtin_msa_bmnzi_b: | |||
1695 | case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; | |||
1696 | // df/n format | |||
1697 | // These intrinsics take an unsigned 4 bit immediate. | |||
1698 | case Mips::BI__builtin_msa_copy_s_b: | |||
1699 | case Mips::BI__builtin_msa_copy_u_b: | |||
1700 | case Mips::BI__builtin_msa_insve_b: | |||
1701 | case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; | |||
1702 | case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; | |||
1703 | // These intrinsics take an unsigned 3 bit immediate. | |||
1704 | case Mips::BI__builtin_msa_copy_s_h: | |||
1705 | case Mips::BI__builtin_msa_copy_u_h: | |||
1706 | case Mips::BI__builtin_msa_insve_h: | |||
1707 | case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; | |||
1708 | case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; | |||
1709 | // These intrinsics take an unsigned 2 bit immediate. | |||
1710 | case Mips::BI__builtin_msa_copy_s_w: | |||
1711 | case Mips::BI__builtin_msa_copy_u_w: | |||
1712 | case Mips::BI__builtin_msa_insve_w: | |||
1713 | case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; | |||
1714 | case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; | |||
1715 | // These intrinsics take an unsigned 1 bit immediate. | |||
1716 | case Mips::BI__builtin_msa_copy_s_d: | |||
1717 | case Mips::BI__builtin_msa_copy_u_d: | |||
1718 | case Mips::BI__builtin_msa_insve_d: | |||
1719 | case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; | |||
1720 | case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; | |||
1721 | // Memory offsets and immediate loads. | |||
1722 | // These intrinsics take a signed 10 bit immediate. | |||
1723 | case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; | |||
1724 | case Mips::BI__builtin_msa_ldi_h: | |||
1725 | case Mips::BI__builtin_msa_ldi_w: | |||
1726 | case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; | |||
1727 | case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; | |||
1728 | case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; | |||
1729 | case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; | |||
1730 | case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; | |||
1731 | case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; | |||
1732 | case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; | |||
1733 | case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; | |||
1734 | case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; | |||
1735 | } | |||
1736 | ||||
1737 | if (!m) | |||
1738 | return SemaBuiltinConstantArgRange(TheCall, i, l, u); | |||
1739 | ||||
1740 | return SemaBuiltinConstantArgRange(TheCall, i, l, u) || | |||
1741 | SemaBuiltinConstantArgMultiple(TheCall, i, m); | |||
1742 | } | |||
1743 | ||||
1744 | bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { | |||
1745 | unsigned i = 0, l = 0, u = 0; | |||
1746 | bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || | |||
1747 | BuiltinID == PPC::BI__builtin_divdeu || | |||
1748 | BuiltinID == PPC::BI__builtin_bpermd; | |||
1749 | bool IsTarget64Bit = Context.getTargetInfo() | |||
1750 | .getTypeWidth(Context | |||
1751 | .getTargetInfo() | |||
1752 | .getIntPtrType()) == 64; | |||
1753 | bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || | |||
1754 | BuiltinID == PPC::BI__builtin_divweu || | |||
1755 | BuiltinID == PPC::BI__builtin_divde || | |||
1756 | BuiltinID == PPC::BI__builtin_divdeu; | |||
1757 | ||||
1758 | if (Is64BitBltin && !IsTarget64Bit) | |||
1759 | return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) | |||
1760 | << TheCall->getSourceRange(); | |||
1761 | ||||
1762 | if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || | |||
1763 | (BuiltinID == PPC::BI__builtin_bpermd && | |||
1764 | !Context.getTargetInfo().hasFeature("bpermd"))) | |||
1765 | return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) | |||
1766 | << TheCall->getSourceRange(); | |||
1767 | ||||
1768 | switch (BuiltinID) { | |||
1769 | default: return false; | |||
1770 | case PPC::BI__builtin_altivec_crypto_vshasigmaw: | |||
1771 | case PPC::BI__builtin_altivec_crypto_vshasigmad: | |||
1772 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || | |||
1773 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); | |||
1774 | case PPC::BI__builtin_tbegin: | |||
1775 | case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; | |||
1776 | case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; | |||
1777 | case PPC::BI__builtin_tabortwc: | |||
1778 | case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; | |||
1779 | case PPC::BI__builtin_tabortwci: | |||
1780 | case PPC::BI__builtin_tabortdci: | |||
1781 | return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || | |||
1782 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); | |||
1783 | case PPC::BI__builtin_vsx_xxpermdi: | |||
1784 | case PPC::BI__builtin_vsx_xxsldwi: | |||
1785 | return SemaBuiltinVSX(TheCall); | |||
1786 | } | |||
1787 | return SemaBuiltinConstantArgRange(TheCall, i, l, u); | |||
1788 | } | |||
1789 | ||||
1790 | bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, | |||
1791 | CallExpr *TheCall) { | |||
1792 | if (BuiltinID == SystemZ::BI__builtin_tabort) { | |||
1793 | Expr *Arg = TheCall->getArg(0); | |||
1794 | llvm::APSInt AbortCode(32); | |||
1795 | if (Arg->isIntegerConstantExpr(AbortCode, Context) && | |||
1796 | AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) | |||
1797 | return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) | |||
1798 | << Arg->getSourceRange(); | |||
1799 | } | |||
1800 | ||||
1801 | // For intrinsics which take an immediate value as part of the instruction, | |||
1802 | // range check them here. | |||
1803 | unsigned i = 0, l = 0, u = 0; | |||
1804 | switch (BuiltinID) { | |||
1805 | default: return false; | |||
1806 | case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; | |||
1807 | case SystemZ::BI__builtin_s390_verimb: | |||
1808 | case SystemZ::BI__builtin_s390_verimh: | |||
1809 | case SystemZ::BI__builtin_s390_verimf: | |||
1810 | case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; | |||
1811 | case SystemZ::BI__builtin_s390_vfaeb: | |||
1812 | case SystemZ::BI__builtin_s390_vfaeh: | |||
1813 | case SystemZ::BI__builtin_s390_vfaef: | |||
1814 | case SystemZ::BI__builtin_s390_vfaebs: | |||
1815 | case SystemZ::BI__builtin_s390_vfaehs: | |||
1816 | case SystemZ::BI__builtin_s390_vfaefs: | |||
1817 | case SystemZ::BI__builtin_s390_vfaezb: | |||
1818 | case SystemZ::BI__builtin_s390_vfaezh: | |||
1819 | case SystemZ::BI__builtin_s390_vfaezf: | |||
1820 | case SystemZ::BI__builtin_s390_vfaezbs: | |||
1821 | case SystemZ::BI__builtin_s390_vfaezhs: | |||
1822 | case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; | |||
1823 | case SystemZ::BI__builtin_s390_vfisb: | |||
1824 | case SystemZ::BI__builtin_s390_vfidb: | |||
1825 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || | |||
1826 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); | |||
1827 | case SystemZ::BI__builtin_s390_vftcisb: | |||
1828 | case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; | |||
1829 | case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; | |||
1830 | case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; | |||
1831 | case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; | |||
1832 | case SystemZ::BI__builtin_s390_vstrcb: | |||
1833 | case SystemZ::BI__builtin_s390_vstrch: | |||
1834 | case SystemZ::BI__builtin_s390_vstrcf: | |||
1835 | case SystemZ::BI__builtin_s390_vstrczb: | |||
1836 | case SystemZ::BI__builtin_s390_vstrczh: | |||
1837 | case SystemZ::BI__builtin_s390_vstrczf: | |||
1838 | case SystemZ::BI__builtin_s390_vstrcbs: | |||
1839 | case SystemZ::BI__builtin_s390_vstrchs: | |||
1840 | case SystemZ::BI__builtin_s390_vstrcfs: | |||
1841 | case SystemZ::BI__builtin_s390_vstrczbs: | |||
1842 | case SystemZ::BI__builtin_s390_vstrczhs: | |||
1843 | case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; | |||
1844 | case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; | |||
1845 | case SystemZ::BI__builtin_s390_vfminsb: | |||
1846 | case SystemZ::BI__builtin_s390_vfmaxsb: | |||
1847 | case SystemZ::BI__builtin_s390_vfmindb: | |||
1848 | case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; | |||
1849 | } | |||
1850 | return SemaBuiltinConstantArgRange(TheCall, i, l, u); | |||
1851 | } | |||
1852 | ||||
1853 | /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). | |||
1854 | /// This checks that the target supports __builtin_cpu_supports and | |||
1855 | /// that the string argument is constant and valid. | |||
1856 | static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { | |||
1857 | Expr *Arg = TheCall->getArg(0); | |||
1858 | ||||
1859 | // Check if the argument is a string literal. | |||
1860 | if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) | |||
1861 | return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) | |||
1862 | << Arg->getSourceRange(); | |||
1863 | ||||
1864 | // Check the contents of the string. | |||
1865 | StringRef Feature = | |||
1866 | cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); | |||
1867 | if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) | |||
1868 | return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) | |||
1869 | << Arg->getSourceRange(); | |||
1870 | return false; | |||
1871 | } | |||
1872 | ||||
1873 | /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). | |||
1874 | /// This checks that the target supports __builtin_cpu_is and | |||
1875 | /// that the string argument is constant and valid. | |||
1876 | static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { | |||
1877 | Expr *Arg = TheCall->getArg(0); | |||
1878 | ||||
1879 | // Check if the argument is a string literal. | |||
1880 | if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) | |||
1881 | return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) | |||
1882 | << Arg->getSourceRange(); | |||
1883 | ||||
1884 | // Check the contents of the string. | |||
1885 | StringRef Feature = | |||
1886 | cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); | |||
1887 | if (!S.Context.getTargetInfo().validateCpuIs(Feature)) | |||
1888 | return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) | |||
1889 | << Arg->getSourceRange(); | |||
1890 | return false; | |||
1891 | } | |||
1892 | ||||
1893 | // Check if the rounding mode is legal. | |||
1894 | bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { | |||
1895 | // Indicates if this instruction has rounding control or just SAE. | |||
1896 | bool HasRC = false; | |||
1897 | ||||
1898 | unsigned ArgNum = 0; | |||
1899 | switch (BuiltinID) { | |||
1900 | default: | |||
1901 | return false; | |||
1902 | case X86::BI__builtin_ia32_vcvttsd2si32: | |||
1903 | case X86::BI__builtin_ia32_vcvttsd2si64: | |||
1904 | case X86::BI__builtin_ia32_vcvttsd2usi32: | |||
1905 | case X86::BI__builtin_ia32_vcvttsd2usi64: | |||
1906 | case X86::BI__builtin_ia32_vcvttss2si32: | |||
1907 | case X86::BI__builtin_ia32_vcvttss2si64: | |||
1908 | case X86::BI__builtin_ia32_vcvttss2usi32: | |||
1909 | case X86::BI__builtin_ia32_vcvttss2usi64: | |||
1910 | ArgNum = 1; | |||
1911 | break; | |||
1912 | case X86::BI__builtin_ia32_cvtps2pd512_mask: | |||
1913 | case X86::BI__builtin_ia32_cvttpd2dq512_mask: | |||
1914 | case X86::BI__builtin_ia32_cvttpd2qq512_mask: | |||
1915 | case X86::BI__builtin_ia32_cvttpd2udq512_mask: | |||
1916 | case X86::BI__builtin_ia32_cvttpd2uqq512_mask: | |||
1917 | case X86::BI__builtin_ia32_cvttps2dq512_mask: | |||
1918 | case X86::BI__builtin_ia32_cvttps2qq512_mask: | |||
1919 | case X86::BI__builtin_ia32_cvttps2udq512_mask: | |||
1920 | case X86::BI__builtin_ia32_cvttps2uqq512_mask: | |||
1921 | case X86::BI__builtin_ia32_exp2pd_mask: | |||
1922 | case X86::BI__builtin_ia32_exp2ps_mask: | |||
1923 | case X86::BI__builtin_ia32_getexppd512_mask: | |||
1924 | case X86::BI__builtin_ia32_getexpps512_mask: | |||
1925 | case X86::BI__builtin_ia32_rcp28pd_mask: | |||
1926 | case X86::BI__builtin_ia32_rcp28ps_mask: | |||
1927 | case X86::BI__builtin_ia32_rsqrt28pd_mask: | |||
1928 | case X86::BI__builtin_ia32_rsqrt28ps_mask: | |||
1929 | case X86::BI__builtin_ia32_vcomisd: | |||
1930 | case X86::BI__builtin_ia32_vcomiss: | |||
1931 | case X86::BI__builtin_ia32_vcvtph2ps512_mask: | |||
1932 | ArgNum = 3; | |||
1933 | break; | |||
1934 | case X86::BI__builtin_ia32_cmppd512_mask: | |||
1935 | case X86::BI__builtin_ia32_cmpps512_mask: | |||
1936 | case X86::BI__builtin_ia32_cmpsd_mask: | |||
1937 | case X86::BI__builtin_ia32_cmpss_mask: | |||
1938 | case X86::BI__builtin_ia32_cvtss2sd_round_mask: | |||
1939 | case X86::BI__builtin_ia32_getexpsd128_round_mask: | |||
1940 | case X86::BI__builtin_ia32_getexpss128_round_mask: | |||
1941 | case X86::BI__builtin_ia32_maxpd512_mask: | |||
1942 | case X86::BI__builtin_ia32_maxps512_mask: | |||
1943 | case X86::BI__builtin_ia32_maxsd_round_mask: | |||
1944 | case X86::BI__builtin_ia32_maxss_round_mask: | |||
1945 | case X86::BI__builtin_ia32_minpd512_mask: | |||
1946 | case X86::BI__builtin_ia32_minps512_mask: | |||
1947 | case X86::BI__builtin_ia32_minsd_round_mask: | |||
1948 | case X86::BI__builtin_ia32_minss_round_mask: | |||
1949 | case X86::BI__builtin_ia32_rcp28sd_round_mask: | |||
1950 | case X86::BI__builtin_ia32_rcp28ss_round_mask: | |||
1951 | case X86::BI__builtin_ia32_reducepd512_mask: | |||
1952 | case X86::BI__builtin_ia32_reduceps512_mask: | |||
1953 | case X86::BI__builtin_ia32_rndscalepd_mask: | |||
1954 | case X86::BI__builtin_ia32_rndscaleps_mask: | |||
1955 | case X86::BI__builtin_ia32_rsqrt28sd_round_mask: | |||
1956 | case X86::BI__builtin_ia32_rsqrt28ss_round_mask: | |||
1957 | ArgNum = 4; | |||
1958 | break; | |||
1959 | case X86::BI__builtin_ia32_fixupimmpd512_mask: | |||
1960 | case X86::BI__builtin_ia32_fixupimmpd512_maskz: | |||
1961 | case X86::BI__builtin_ia32_fixupimmps512_mask: | |||
1962 | case X86::BI__builtin_ia32_fixupimmps512_maskz: | |||
1963 | case X86::BI__builtin_ia32_fixupimmsd_mask: | |||
1964 | case X86::BI__builtin_ia32_fixupimmsd_maskz: | |||
1965 | case X86::BI__builtin_ia32_fixupimmss_mask: | |||
1966 | case X86::BI__builtin_ia32_fixupimmss_maskz: | |||
1967 | case X86::BI__builtin_ia32_rangepd512_mask: | |||
1968 | case X86::BI__builtin_ia32_rangeps512_mask: | |||
1969 | case X86::BI__builtin_ia32_rangesd128_round_mask: | |||
1970 | case X86::BI__builtin_ia32_rangess128_round_mask: | |||
1971 | case X86::BI__builtin_ia32_reducesd_mask: | |||
1972 | case X86::BI__builtin_ia32_reducess_mask: | |||
1973 | case X86::BI__builtin_ia32_rndscalesd_round_mask: | |||
1974 | case X86::BI__builtin_ia32_rndscaless_round_mask: | |||
1975 | ArgNum = 5; | |||
1976 | break; | |||
1977 | case X86::BI__builtin_ia32_vcvtsd2si64: | |||
1978 | case X86::BI__builtin_ia32_vcvtsd2si32: | |||
1979 | case X86::BI__builtin_ia32_vcvtsd2usi32: | |||
1980 | case X86::BI__builtin_ia32_vcvtsd2usi64: | |||
1981 | case X86::BI__builtin_ia32_vcvtss2si32: | |||
1982 | case X86::BI__builtin_ia32_vcvtss2si64: | |||
1983 | case X86::BI__builtin_ia32_vcvtss2usi32: | |||
1984 | case X86::BI__builtin_ia32_vcvtss2usi64: | |||
1985 | ArgNum = 1; | |||
1986 | HasRC = true; | |||
1987 | break; | |||
1988 | case X86::BI__builtin_ia32_cvtsi2sd64: | |||
1989 | case X86::BI__builtin_ia32_cvtsi2ss32: | |||
1990 | case X86::BI__builtin_ia32_cvtsi2ss64: | |||
1991 | case X86::BI__builtin_ia32_cvtusi2sd64: | |||
1992 | case X86::BI__builtin_ia32_cvtusi2ss32: | |||
1993 | case X86::BI__builtin_ia32_cvtusi2ss64: | |||
1994 | ArgNum = 2; | |||
1995 | HasRC = true; | |||
1996 | break; | |||
1997 | case X86::BI__builtin_ia32_cvtdq2ps512_mask: | |||
1998 | case X86::BI__builtin_ia32_cvtudq2ps512_mask: | |||
1999 | case X86::BI__builtin_ia32_cvtpd2ps512_mask: | |||
2000 | case X86::BI__builtin_ia32_cvtpd2qq512_mask: | |||
2001 | case X86::BI__builtin_ia32_cvtpd2uqq512_mask: | |||
2002 | case X86::BI__builtin_ia32_cvtps2qq512_mask: | |||
2003 | case X86::BI__builtin_ia32_cvtps2uqq512_mask: | |||
2004 | case X86::BI__builtin_ia32_cvtqq2pd512_mask: | |||
2005 | case X86::BI__builtin_ia32_cvtqq2ps512_mask: | |||
2006 | case X86::BI__builtin_ia32_cvtuqq2pd512_mask: | |||
2007 | case X86::BI__builtin_ia32_cvtuqq2ps512_mask: | |||
2008 | case X86::BI__builtin_ia32_sqrtpd512_mask: | |||
2009 | case X86::BI__builtin_ia32_sqrtps512_mask: | |||
2010 | ArgNum = 3; | |||
2011 | HasRC = true; | |||
2012 | break; | |||
2013 | case X86::BI__builtin_ia32_addpd512_mask: | |||
2014 | case X86::BI__builtin_ia32_addps512_mask: | |||
2015 | case X86::BI__builtin_ia32_divpd512_mask: | |||
2016 | case X86::BI__builtin_ia32_divps512_mask: | |||
2017 | case X86::BI__builtin_ia32_mulpd512_mask: | |||
2018 | case X86::BI__builtin_ia32_mulps512_mask: | |||
2019 | case X86::BI__builtin_ia32_subpd512_mask: | |||
2020 | case X86::BI__builtin_ia32_subps512_mask: | |||
2021 | case X86::BI__builtin_ia32_addss_round_mask: | |||
2022 | case X86::BI__builtin_ia32_addsd_round_mask: | |||
2023 | case X86::BI__builtin_ia32_divss_round_mask: | |||
2024 | case X86::BI__builtin_ia32_divsd_round_mask: | |||
2025 | case X86::BI__builtin_ia32_mulss_round_mask: | |||
2026 | case X86::BI__builtin_ia32_mulsd_round_mask: | |||
2027 | case X86::BI__builtin_ia32_subss_round_mask: | |||
2028 | case X86::BI__builtin_ia32_subsd_round_mask: | |||
2029 | case X86::BI__builtin_ia32_scalefpd512_mask: | |||
2030 | case X86::BI__builtin_ia32_scalefps512_mask: | |||
2031 | case X86::BI__builtin_ia32_scalefsd_round_mask: | |||
2032 | case X86::BI__builtin_ia32_scalefss_round_mask: | |||
2033 | case X86::BI__builtin_ia32_getmantpd512_mask: | |||
2034 | case X86::BI__builtin_ia32_getmantps512_mask: | |||
2035 | case X86::BI__builtin_ia32_cvtsd2ss_round_mask: | |||
2036 | case X86::BI__builtin_ia32_sqrtsd_round_mask: | |||
2037 | case X86::BI__builtin_ia32_sqrtss_round_mask: | |||
2038 | case X86::BI__builtin_ia32_vfmaddpd512_mask: | |||
2039 | case X86::BI__builtin_ia32_vfmaddpd512_mask3: | |||
2040 | case X86::BI__builtin_ia32_vfmaddpd512_maskz: | |||
2041 | case X86::BI__builtin_ia32_vfmaddps512_mask: | |||
2042 | case X86::BI__builtin_ia32_vfmaddps512_mask3: | |||
2043 | case X86::BI__builtin_ia32_vfmaddps512_maskz: | |||
2044 | case X86::BI__builtin_ia32_vfmaddsubpd512_mask: | |||
2045 | case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: | |||
2046 | case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: | |||
2047 | case X86::BI__builtin_ia32_vfmaddsubps512_mask: | |||
2048 | case X86::BI__builtin_ia32_vfmaddsubps512_mask3: | |||
2049 | case X86::BI__builtin_ia32_vfmaddsubps512_maskz: | |||
2050 | case X86::BI__builtin_ia32_vfmsubpd512_mask3: | |||
2051 | case X86::BI__builtin_ia32_vfmsubps512_mask3: | |||
2052 | case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: | |||
2053 | case X86::BI__builtin_ia32_vfmsubaddps512_mask3: | |||
2054 | case X86::BI__builtin_ia32_vfnmaddpd512_mask: | |||
2055 | case X86::BI__builtin_ia32_vfnmaddps512_mask: | |||
2056 | case X86::BI__builtin_ia32_vfnmsubpd512_mask: | |||
2057 | case X86::BI__builtin_ia32_vfnmsubpd512_mask3: | |||
2058 | case X86::BI__builtin_ia32_vfnmsubps512_mask: | |||
2059 | case X86::BI__builtin_ia32_vfnmsubps512_mask3: | |||
2060 | case X86::BI__builtin_ia32_vfmaddsd3_mask: | |||
2061 | case X86::BI__builtin_ia32_vfmaddsd3_maskz: | |||
2062 | case X86::BI__builtin_ia32_vfmaddsd3_mask3: | |||
2063 | case X86::BI__builtin_ia32_vfmaddss3_mask: | |||
2064 | case X86::BI__builtin_ia32_vfmaddss3_maskz: | |||
2065 | case X86::BI__builtin_ia32_vfmaddss3_mask3: | |||
2066 | ArgNum = 4; | |||
2067 | HasRC = true; | |||
2068 | break; | |||
2069 | case X86::BI__builtin_ia32_getmantsd_round_mask: | |||
2070 | case X86::BI__builtin_ia32_getmantss_round_mask: | |||
2071 | ArgNum = 5; | |||
2072 | HasRC = true; | |||
2073 | break; | |||
2074 | } | |||
2075 | ||||
2076 | llvm::APSInt Result; | |||
2077 | ||||
2078 | // We can't check the value of a dependent argument. | |||
2079 | Expr *Arg = TheCall->getArg(ArgNum); | |||
2080 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
2081 | return false; | |||
2082 | ||||
2083 | // Check constant-ness first. | |||
2084 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
2085 | return true; | |||
2086 | ||||
2087 | // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit | |||
2088 | // is set. If the intrinsic has rounding control(bits 1:0), make sure its only | |||
2089 | // combined with ROUND_NO_EXC. | |||
2090 | if (Result == 4/*ROUND_CUR_DIRECTION*/ || | |||
2091 | Result == 8/*ROUND_NO_EXC*/ || | |||
2092 | (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) | |||
2093 | return false; | |||
2094 | ||||
2095 | return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) | |||
2096 | << Arg->getSourceRange(); | |||
2097 | } | |||
2098 | ||||
2099 | // Check if the gather/scatter scale is legal. | |||
2100 | bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, | |||
2101 | CallExpr *TheCall) { | |||
2102 | unsigned ArgNum = 0; | |||
2103 | switch (BuiltinID) { | |||
2104 | default: | |||
2105 | return false; | |||
2106 | case X86::BI__builtin_ia32_gatherpfdpd: | |||
2107 | case X86::BI__builtin_ia32_gatherpfdps: | |||
2108 | case X86::BI__builtin_ia32_gatherpfqpd: | |||
2109 | case X86::BI__builtin_ia32_gatherpfqps: | |||
2110 | case X86::BI__builtin_ia32_scatterpfdpd: | |||
2111 | case X86::BI__builtin_ia32_scatterpfdps: | |||
2112 | case X86::BI__builtin_ia32_scatterpfqpd: | |||
2113 | case X86::BI__builtin_ia32_scatterpfqps: | |||
2114 | ArgNum = 3; | |||
2115 | break; | |||
2116 | case X86::BI__builtin_ia32_gatherd_pd: | |||
2117 | case X86::BI__builtin_ia32_gatherd_pd256: | |||
2118 | case X86::BI__builtin_ia32_gatherq_pd: | |||
2119 | case X86::BI__builtin_ia32_gatherq_pd256: | |||
2120 | case X86::BI__builtin_ia32_gatherd_ps: | |||
2121 | case X86::BI__builtin_ia32_gatherd_ps256: | |||
2122 | case X86::BI__builtin_ia32_gatherq_ps: | |||
2123 | case X86::BI__builtin_ia32_gatherq_ps256: | |||
2124 | case X86::BI__builtin_ia32_gatherd_q: | |||
2125 | case X86::BI__builtin_ia32_gatherd_q256: | |||
2126 | case X86::BI__builtin_ia32_gatherq_q: | |||
2127 | case X86::BI__builtin_ia32_gatherq_q256: | |||
2128 | case X86::BI__builtin_ia32_gatherd_d: | |||
2129 | case X86::BI__builtin_ia32_gatherd_d256: | |||
2130 | case X86::BI__builtin_ia32_gatherq_d: | |||
2131 | case X86::BI__builtin_ia32_gatherq_d256: | |||
2132 | case X86::BI__builtin_ia32_gather3div2df: | |||
2133 | case X86::BI__builtin_ia32_gather3div2di: | |||
2134 | case X86::BI__builtin_ia32_gather3div4df: | |||
2135 | case X86::BI__builtin_ia32_gather3div4di: | |||
2136 | case X86::BI__builtin_ia32_gather3div4sf: | |||
2137 | case X86::BI__builtin_ia32_gather3div4si: | |||
2138 | case X86::BI__builtin_ia32_gather3div8sf: | |||
2139 | case X86::BI__builtin_ia32_gather3div8si: | |||
2140 | case X86::BI__builtin_ia32_gather3siv2df: | |||
2141 | case X86::BI__builtin_ia32_gather3siv2di: | |||
2142 | case X86::BI__builtin_ia32_gather3siv4df: | |||
2143 | case X86::BI__builtin_ia32_gather3siv4di: | |||
2144 | case X86::BI__builtin_ia32_gather3siv4sf: | |||
2145 | case X86::BI__builtin_ia32_gather3siv4si: | |||
2146 | case X86::BI__builtin_ia32_gather3siv8sf: | |||
2147 | case X86::BI__builtin_ia32_gather3siv8si: | |||
2148 | case X86::BI__builtin_ia32_gathersiv8df: | |||
2149 | case X86::BI__builtin_ia32_gathersiv16sf: | |||
2150 | case X86::BI__builtin_ia32_gatherdiv8df: | |||
2151 | case X86::BI__builtin_ia32_gatherdiv16sf: | |||
2152 | case X86::BI__builtin_ia32_gathersiv8di: | |||
2153 | case X86::BI__builtin_ia32_gathersiv16si: | |||
2154 | case X86::BI__builtin_ia32_gatherdiv8di: | |||
2155 | case X86::BI__builtin_ia32_gatherdiv16si: | |||
2156 | case X86::BI__builtin_ia32_scatterdiv2df: | |||
2157 | case X86::BI__builtin_ia32_scatterdiv2di: | |||
2158 | case X86::BI__builtin_ia32_scatterdiv4df: | |||
2159 | case X86::BI__builtin_ia32_scatterdiv4di: | |||
2160 | case X86::BI__builtin_ia32_scatterdiv4sf: | |||
2161 | case X86::BI__builtin_ia32_scatterdiv4si: | |||
2162 | case X86::BI__builtin_ia32_scatterdiv8sf: | |||
2163 | case X86::BI__builtin_ia32_scatterdiv8si: | |||
2164 | case X86::BI__builtin_ia32_scattersiv2df: | |||
2165 | case X86::BI__builtin_ia32_scattersiv2di: | |||
2166 | case X86::BI__builtin_ia32_scattersiv4df: | |||
2167 | case X86::BI__builtin_ia32_scattersiv4di: | |||
2168 | case X86::BI__builtin_ia32_scattersiv4sf: | |||
2169 | case X86::BI__builtin_ia32_scattersiv4si: | |||
2170 | case X86::BI__builtin_ia32_scattersiv8sf: | |||
2171 | case X86::BI__builtin_ia32_scattersiv8si: | |||
2172 | case X86::BI__builtin_ia32_scattersiv8df: | |||
2173 | case X86::BI__builtin_ia32_scattersiv16sf: | |||
2174 | case X86::BI__builtin_ia32_scatterdiv8df: | |||
2175 | case X86::BI__builtin_ia32_scatterdiv16sf: | |||
2176 | case X86::BI__builtin_ia32_scattersiv8di: | |||
2177 | case X86::BI__builtin_ia32_scattersiv16si: | |||
2178 | case X86::BI__builtin_ia32_scatterdiv8di: | |||
2179 | case X86::BI__builtin_ia32_scatterdiv16si: | |||
2180 | ArgNum = 4; | |||
2181 | break; | |||
2182 | } | |||
2183 | ||||
2184 | llvm::APSInt Result; | |||
2185 | ||||
2186 | // We can't check the value of a dependent argument. | |||
2187 | Expr *Arg = TheCall->getArg(ArgNum); | |||
2188 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
2189 | return false; | |||
2190 | ||||
2191 | // Check constant-ness first. | |||
2192 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
2193 | return true; | |||
2194 | ||||
2195 | if (Result == 1 || Result == 2 || Result == 4 || Result == 8) | |||
2196 | return false; | |||
2197 | ||||
2198 | return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) | |||
2199 | << Arg->getSourceRange(); | |||
2200 | } | |||
2201 | ||||
2202 | bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { | |||
2203 | if (BuiltinID == X86::BI__builtin_cpu_supports) | |||
2204 | return SemaBuiltinCpuSupports(*this, TheCall); | |||
2205 | ||||
2206 | if (BuiltinID == X86::BI__builtin_cpu_is) | |||
2207 | return SemaBuiltinCpuIs(*this, TheCall); | |||
2208 | ||||
2209 | // If the intrinsic has rounding or SAE make sure its valid. | |||
2210 | if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) | |||
2211 | return true; | |||
2212 | ||||
2213 | // If the intrinsic has a gather/scatter scale immediate make sure its valid. | |||
2214 | if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) | |||
2215 | return true; | |||
2216 | ||||
2217 | // For intrinsics which take an immediate value as part of the instruction, | |||
2218 | // range check them here. | |||
2219 | int i = 0, l = 0, u = 0; | |||
2220 | switch (BuiltinID) { | |||
2221 | default: | |||
2222 | return false; | |||
2223 | case X86::BI_mm_prefetch: | |||
2224 | i = 1; l = 0; u = 3; | |||
2225 | break; | |||
2226 | case X86::BI__builtin_ia32_sha1rnds4: | |||
2227 | case X86::BI__builtin_ia32_shuf_f32x4_256_mask: | |||
2228 | case X86::BI__builtin_ia32_shuf_f64x2_256_mask: | |||
2229 | case X86::BI__builtin_ia32_shuf_i32x4_256_mask: | |||
2230 | case X86::BI__builtin_ia32_shuf_i64x2_256_mask: | |||
2231 | i = 2; l = 0; u = 3; | |||
2232 | break; | |||
2233 | case X86::BI__builtin_ia32_vpermil2pd: | |||
2234 | case X86::BI__builtin_ia32_vpermil2pd256: | |||
2235 | case X86::BI__builtin_ia32_vpermil2ps: | |||
2236 | case X86::BI__builtin_ia32_vpermil2ps256: | |||
2237 | i = 3; l = 0; u = 3; | |||
2238 | break; | |||
2239 | case X86::BI__builtin_ia32_cmpb128_mask: | |||
2240 | case X86::BI__builtin_ia32_cmpw128_mask: | |||
2241 | case X86::BI__builtin_ia32_cmpd128_mask: | |||
2242 | case X86::BI__builtin_ia32_cmpq128_mask: | |||
2243 | case X86::BI__builtin_ia32_cmpb256_mask: | |||
2244 | case X86::BI__builtin_ia32_cmpw256_mask: | |||
2245 | case X86::BI__builtin_ia32_cmpd256_mask: | |||
2246 | case X86::BI__builtin_ia32_cmpq256_mask: | |||
2247 | case X86::BI__builtin_ia32_cmpb512_mask: | |||
2248 | case X86::BI__builtin_ia32_cmpw512_mask: | |||
2249 | case X86::BI__builtin_ia32_cmpd512_mask: | |||
2250 | case X86::BI__builtin_ia32_cmpq512_mask: | |||
2251 | case X86::BI__builtin_ia32_ucmpb128_mask: | |||
2252 | case X86::BI__builtin_ia32_ucmpw128_mask: | |||
2253 | case X86::BI__builtin_ia32_ucmpd128_mask: | |||
2254 | case X86::BI__builtin_ia32_ucmpq128_mask: | |||
2255 | case X86::BI__builtin_ia32_ucmpb256_mask: | |||
2256 | case X86::BI__builtin_ia32_ucmpw256_mask: | |||
2257 | case X86::BI__builtin_ia32_ucmpd256_mask: | |||
2258 | case X86::BI__builtin_ia32_ucmpq256_mask: | |||
2259 | case X86::BI__builtin_ia32_ucmpb512_mask: | |||
2260 | case X86::BI__builtin_ia32_ucmpw512_mask: | |||
2261 | case X86::BI__builtin_ia32_ucmpd512_mask: | |||
2262 | case X86::BI__builtin_ia32_ucmpq512_mask: | |||
2263 | case X86::BI__builtin_ia32_vpcomub: | |||
2264 | case X86::BI__builtin_ia32_vpcomuw: | |||
2265 | case X86::BI__builtin_ia32_vpcomud: | |||
2266 | case X86::BI__builtin_ia32_vpcomuq: | |||
2267 | case X86::BI__builtin_ia32_vpcomb: | |||
2268 | case X86::BI__builtin_ia32_vpcomw: | |||
2269 | case X86::BI__builtin_ia32_vpcomd: | |||
2270 | case X86::BI__builtin_ia32_vpcomq: | |||
2271 | i = 2; l = 0; u = 7; | |||
2272 | break; | |||
2273 | case X86::BI__builtin_ia32_roundps: | |||
2274 | case X86::BI__builtin_ia32_roundpd: | |||
2275 | case X86::BI__builtin_ia32_roundps256: | |||
2276 | case X86::BI__builtin_ia32_roundpd256: | |||
2277 | i = 1; l = 0; u = 15; | |||
2278 | break; | |||
2279 | case X86::BI__builtin_ia32_roundss: | |||
2280 | case X86::BI__builtin_ia32_roundsd: | |||
2281 | case X86::BI__builtin_ia32_rangepd128_mask: | |||
2282 | case X86::BI__builtin_ia32_rangepd256_mask: | |||
2283 | case X86::BI__builtin_ia32_rangepd512_mask: | |||
2284 | case X86::BI__builtin_ia32_rangeps128_mask: | |||
2285 | case X86::BI__builtin_ia32_rangeps256_mask: | |||
2286 | case X86::BI__builtin_ia32_rangeps512_mask: | |||
2287 | case X86::BI__builtin_ia32_getmantsd_round_mask: | |||
2288 | case X86::BI__builtin_ia32_getmantss_round_mask: | |||
2289 | i = 2; l = 0; u = 15; | |||
2290 | break; | |||
2291 | case X86::BI__builtin_ia32_cmpps: | |||
2292 | case X86::BI__builtin_ia32_cmpss: | |||
2293 | case X86::BI__builtin_ia32_cmppd: | |||
2294 | case X86::BI__builtin_ia32_cmpsd: | |||
2295 | case X86::BI__builtin_ia32_cmpps256: | |||
2296 | case X86::BI__builtin_ia32_cmppd256: | |||
2297 | case X86::BI__builtin_ia32_cmpps128_mask: | |||
2298 | case X86::BI__builtin_ia32_cmppd128_mask: | |||
2299 | case X86::BI__builtin_ia32_cmpps256_mask: | |||
2300 | case X86::BI__builtin_ia32_cmppd256_mask: | |||
2301 | case X86::BI__builtin_ia32_cmpps512_mask: | |||
2302 | case X86::BI__builtin_ia32_cmppd512_mask: | |||
2303 | case X86::BI__builtin_ia32_cmpsd_mask: | |||
2304 | case X86::BI__builtin_ia32_cmpss_mask: | |||
2305 | i = 2; l = 0; u = 31; | |||
2306 | break; | |||
2307 | case X86::BI__builtin_ia32_xabort: | |||
2308 | i = 0; l = -128; u = 255; | |||
2309 | break; | |||
2310 | case X86::BI__builtin_ia32_pshufw: | |||
2311 | case X86::BI__builtin_ia32_aeskeygenassist128: | |||
2312 | i = 1; l = -128; u = 255; | |||
2313 | break; | |||
2314 | case X86::BI__builtin_ia32_vcvtps2ph: | |||
2315 | case X86::BI__builtin_ia32_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. | |||
2447 | bool 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. | |||
2469 | static 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 | ||||
2494 | static 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 | ||||
2502 | bool 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. | |||
2513 | static void | |||
2514 | DiagnoseCStringFormatDirectiveInCFAPI(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. | |||
2554 | static bool isNonNullType(ASTContext &ctx, QualType type) { | |||
2555 | if (auto nullability = type->getNullability(ctx)) | |||
2556 | return *nullability == NullabilityKind::NonNull; | |||
2557 | ||||
2558 | return false; | |||
2559 | } | |||
2560 | ||||
2561 | static 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. | |||
2657 | void 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()) | |||
2663 | return; | |||
2664 | ||||
2665 | // Printf and scanf checking. | |||
2666 | llvm::SmallBitVector CheckedVarArgs; | |||
2667 | if (FDecl) { | |||
2668 | for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { | |||
2669 | // Only create vector if there are format attributes. | |||
2670 | CheckedVarArgs.resize(Args.size()); | |||
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. | |||
2714 | void 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. | |||
2726 | bool 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 | ||||
2781 | bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, | |||
2782 | ArrayRef<const Expr *> Args) { | |||
2783 | VariadicCallType CallType = | |||
2784 | Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; | |||
| ||||
2785 | ||||
2786 | checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, | |||
2787 | /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), | |||
2788 | CallType); | |||
2789 | ||||
2790 | return false; | |||
2791 | } | |||
2792 | ||||
2793 | bool 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. | |||
2826 | bool 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 | ||||
2837 | static 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 | ||||
2867 | ExprResult 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. | |||
3264 | static 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, | |||
3289 | ExprResult | |||
3290 | Sema::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. | |||
3655 | ExprResult 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). | |||
3725 | bool 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 *. | |||
3755 | ExprResult 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. | |||
3780 | static 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 | ||||
3814 | static 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. | |||
3855 | bool 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 | ||||
3934 | bool 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. | |||
3986 | bool 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. | |||
4030 | bool 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); | |||
4077 | bool 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. | |||
4131 | ExprResult 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 | |||
4217 | ExprResult 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. | |||
4249 | bool 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. | |||
4270 | bool 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. | |||
4285 | bool 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. | |||
4320 | bool 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 | ||||
4356 | bool 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. | |||
4438 | bool 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]. | |||
4455 | bool 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.. | |||
4477 | bool 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. | |||
4499 | bool 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. | |||
4601 | bool 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. | |||
4622 | bool 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 | ||||
4629 | namespace { | |||
4630 | class UncoveredArgHandler { | |||
4631 | enum { Unknown = -1, AllCovered = -2 }; | |||
4632 | signed FirstUncoveredArg; | |||
4633 | SmallVector<const Expr *, 4> DiagnosticExprs; | |||
4634 | ||||
4635 | public: | |||
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 | ||||
4675 | enum StringLiteralCheckType { | |||
4676 | SLCT_NotALiteral, | |||
4677 | SLCT_UncheckedLiteral, | |||
4678 | SLCT_CheckedLiteral | |||
4679 | }; | |||
4680 | } // end anonymous namespace | |||
4681 | ||||
4682 | static 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 | ||||
4722 | namespace { | |||
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. | |||
4726 | class 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 | ||||
4770 | static 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. | |||
4785 | static StringLiteralCheckType | |||
4786 | checkFormatStringExpr(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 | ||||
5064 | Sema::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. | |||
5081 | bool 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 | ||||
5095 | bool 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 | ||||
5179 | namespace { | |||
5180 | class CheckFormatHandler : public analyze_format_string::FormatStringHandler { | |||
5181 | protected: | |||
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 | ||||
5200 | public: | |||
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 | ||||
5255 | protected: | |||
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 | ||||
5284 | SourceRange CheckFormatHandler::getFormatStringRange() { | |||
5285 | return OrigFormatExpr->getSourceRange(); | |||
5286 | } | |||
5287 | ||||
5288 | CharSourceRange CheckFormatHandler:: | |||
5289 | getSpecifierRange(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 | ||||
5299 | SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { | |||
5300 | return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), | |||
5301 | S.getLangOpts(), S.Context.getTargetInfo()); | |||
5302 | } | |||
5303 | ||||
5304 | void 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 | ||||
5312 | void 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 | ||||
5346 | void 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 | ||||
5376 | void 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 | ||||
5403 | void 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 | ||||
5411 | void | |||
5412 | CheckFormatHandler::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 | ||||
5420 | void 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 | ||||
5428 | void 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. | |||
5440 | const Expr *CheckFormatHandler::getDataArg(unsigned i) const { | |||
5441 | return Args[FirstDataArg + i]; | |||
5442 | } | |||
5443 | ||||
5444 | void 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 | ||||
5460 | void 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 | ||||
5483 | bool | |||
5484 | CheckFormatHandler::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 | ||||
5542 | void | |||
5543 | CheckFormatHandler::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 | ||||
5551 | bool | |||
5552 | CheckFormatHandler::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 | ||||
5574 | template<typename Range> | |||
5575 | void 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. | |||
5611 | template <typename Range> | |||
5612 | void 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 | ||||
5635 | namespace { | |||
5636 | class CheckPrintfHandler : public CheckFormatHandler { | |||
5637 | public: | |||
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 | ||||
5702 | bool 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 | ||||
5715 | bool 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 | ||||
5763 | void 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 | ||||
5786 | void 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 | ||||
5802 | void 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 | ||||
5822 | void 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 | ||||
5831 | void 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 | ||||
5842 | void 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()"). | |||
5856 | template<typename MemberKind> | |||
5857 | static llvm::SmallPtrSet<MemberKind*, 1> | |||
5858 | CXXRecordMembersNamed(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). | |||
5887 | bool 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. | |||
5901 | bool 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 | ||||
5925 | bool | |||
5926 | CheckPrintfHandler::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 | ||||
6130 | static 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 | ||||
6166 | static std::pair<QualType, StringRef> | |||
6167 | shouldNotPrintDirectly(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 | ||||
6222 | bool | |||
6223 | CheckPrintfHandler::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 | ||||
6480 | namespace { | |||
6481 | class CheckScanfHandler : public CheckFormatHandler { | |||
6482 | public: | |||
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 | ||||
6509 | void 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 | ||||
6516 | bool 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 | ||||
6530 | bool 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 | ||||
6653 | static 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 | ||||
6730 | bool 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. | |||
6748 | static 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. | |||
6798 | static 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. | |||
6820 | static 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 | ||||
6839 | enum AbsoluteValueKind { | |||
6840 | AVK_Integer, | |||
6841 | AVK_Floating, | |||
6842 | AVK_Complex | |||
6843 | }; | |||
6844 | ||||
6845 | static 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. | |||
6858 | static 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 | ||||
6922 | static 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. | |||
6955 | static 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 | ||||
7037 | template <std::size_t StrLen> | |||
7038 | static 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. | |||
7051 | void 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---------------===// | |||
7131 | void 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))`. | |||
7199 | static 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). | |||
7228 | static 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. | |||
7259 | static 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. | |||
7269 | static 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. | |||
7285 | void 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(). | |||
7457 | static 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 | ||||
7479 | static 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. | |||
7494 | void 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. | |||
7562 | static 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 | ||||
7569 | static 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); | |||
7582 | void 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 | ||||
7666 | static const Expr *EvalVal(const Expr *E, | |||
7667 | SmallVectorImpl<const DeclRefExpr *> &refVars, | |||
7668 | const Decl *ParentDecl); | |||
7669 | static 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. | |||
7675 | static void | |||
7676 | CheckReturnStackAddr(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 | |||
7774 | static 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 | case Stmt::BinaryOperatorClass: { | |||
7823 | // Handle pointer arithmetic. All other binary operators are not valid | |||
7824 | // in this context. | |||
7825 | const BinaryOperator *B = cast<BinaryOperator>(E); | |||
7826 | BinaryOperatorKind op = B->getOpcode(); | |||
7827 | ||||
7828 | if (op != BO_Add && op != BO_Sub) | |||
7829 | return nullptr; | |||
7830 | ||||
7831 | const Expr *Base = B->getLHS(); | |||
7832 | ||||
7833 | // Determine which argument is the real pointer base. It could be | |||
7834 | // the RHS argument instead of the LHS. | |||
7835 | if (!Base->getType()->isPointerType()) | |||
7836 | Base = B->getRHS(); | |||
7837 | ||||
7838 | assert(Base->getType()->isPointerType())((Base->getType()->isPointerType()) ? static_cast<void > (0) : __assert_fail ("Base->getType()->isPointerType()" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 7838, __PRETTY_FUNCTION__)); | |||
7839 | return EvalAddr(Base, refVars, ParentDecl); | |||
7840 | } | |||
7841 | ||||
7842 | // For conditional operators we need to see if either the LHS or RHS are | |||
7843 | // valid DeclRefExpr*s. If one of them is valid, we return it. | |||
7844 | case Stmt::ConditionalOperatorClass: { | |||
7845 | const ConditionalOperator *C = cast<ConditionalOperator>(E); | |||
7846 | ||||
7847 | // Handle the GNU extension for missing LHS. | |||
7848 | // FIXME: That isn't a ConditionalOperator, so doesn't get here. | |||
7849 | if (const Expr *LHSExpr = C->getLHS()) { | |||
7850 | // In C++, we can have a throw-expression, which has 'void' type. | |||
7851 | if (!LHSExpr->getType()->isVoidType()) | |||
7852 | if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) | |||
7853 | return LHS; | |||
7854 | } | |||
7855 | ||||
7856 | // In C++, we can have a throw-expression, which has 'void' type. | |||
7857 | if (C->getRHS()->getType()->isVoidType()) | |||
7858 | return nullptr; | |||
7859 | ||||
7860 | return EvalAddr(C->getRHS(), refVars, ParentDecl); | |||
7861 | } | |||
7862 | ||||
7863 | case Stmt::BlockExprClass: | |||
7864 | if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) | |||
7865 | return E; // local block. | |||
7866 | return nullptr; | |||
7867 | ||||
7868 | case Stmt::AddrLabelExprClass: | |||
7869 | return E; // address of label. | |||
7870 | ||||
7871 | case Stmt::ExprWithCleanupsClass: | |||
7872 | return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, | |||
7873 | ParentDecl); | |||
7874 | ||||
7875 | // For casts, we need to handle conversions from arrays to | |||
7876 | // pointer values, and pointer-to-pointer conversions. | |||
7877 | case Stmt::ImplicitCastExprClass: | |||
7878 | case Stmt::CStyleCastExprClass: | |||
7879 | case Stmt::CXXFunctionalCastExprClass: | |||
7880 | case Stmt::ObjCBridgedCastExprClass: | |||
7881 | case Stmt::CXXStaticCastExprClass: | |||
7882 | case Stmt::CXXDynamicCastExprClass: | |||
7883 | case Stmt::CXXConstCastExprClass: | |||
7884 | case Stmt::CXXReinterpretCastExprClass: { | |||
7885 | const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); | |||
7886 | switch (cast<CastExpr>(E)->getCastKind()) { | |||
7887 | case CK_LValueToRValue: | |||
7888 | case CK_NoOp: | |||
7889 | case CK_BaseToDerived: | |||
7890 | case CK_DerivedToBase: | |||
7891 | case CK_UncheckedDerivedToBase: | |||
7892 | case CK_Dynamic: | |||
7893 | case CK_CPointerToObjCPointerCast: | |||
7894 | case CK_BlockPointerToObjCPointerCast: | |||
7895 | case CK_AnyPointerToBlockPointerCast: | |||
7896 | return EvalAddr(SubExpr, refVars, ParentDecl); | |||
7897 | ||||
7898 | case CK_ArrayToPointerDecay: | |||
7899 | return EvalVal(SubExpr, refVars, ParentDecl); | |||
7900 | ||||
7901 | case CK_BitCast: | |||
7902 | if (SubExpr->getType()->isAnyPointerType() || | |||
7903 | SubExpr->getType()->isBlockPointerType() || | |||
7904 | SubExpr->getType()->isObjCQualifiedIdType()) | |||
7905 | return EvalAddr(SubExpr, refVars, ParentDecl); | |||
7906 | else | |||
7907 | return nullptr; | |||
7908 | ||||
7909 | default: | |||
7910 | return nullptr; | |||
7911 | } | |||
7912 | } | |||
7913 | ||||
7914 | case Stmt::MaterializeTemporaryExprClass: | |||
7915 | if (const Expr *Result = | |||
7916 | EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), | |||
7917 | refVars, ParentDecl)) | |||
7918 | return Result; | |||
7919 | return E; | |||
7920 | ||||
7921 | // Everything else: we simply don't reason about them. | |||
7922 | default: | |||
7923 | return nullptr; | |||
7924 | } | |||
7925 | } | |||
7926 | ||||
7927 | /// EvalVal - This function is complements EvalAddr in the mutual recursion. | |||
7928 | /// See the comments for EvalAddr for more details. | |||
7929 | static const Expr *EvalVal(const Expr *E, | |||
7930 | SmallVectorImpl<const DeclRefExpr *> &refVars, | |||
7931 | const Decl *ParentDecl) { | |||
7932 | do { | |||
7933 | // We should only be called for evaluating non-pointer expressions, or | |||
7934 | // expressions with a pointer type that are not used as references but | |||
7935 | // instead | |||
7936 | // are l-values (e.g., DeclRefExpr with a pointer type). | |||
7937 | ||||
7938 | // Our "symbolic interpreter" is just a dispatch off the currently | |||
7939 | // viewed AST node. We then recursively traverse the AST by calling | |||
7940 | // EvalAddr and EvalVal appropriately. | |||
7941 | ||||
7942 | E = E->IgnoreParens(); | |||
7943 | switch (E->getStmtClass()) { | |||
7944 | case Stmt::ImplicitCastExprClass: { | |||
7945 | const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); | |||
7946 | if (IE->getValueKind() == VK_LValue) { | |||
7947 | E = IE->getSubExpr(); | |||
7948 | continue; | |||
7949 | } | |||
7950 | return nullptr; | |||
7951 | } | |||
7952 | ||||
7953 | case Stmt::ExprWithCleanupsClass: | |||
7954 | return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, | |||
7955 | ParentDecl); | |||
7956 | ||||
7957 | case Stmt::DeclRefExprClass: { | |||
7958 | // When we hit a DeclRefExpr we are looking at code that refers to a | |||
7959 | // variable's name. If it's not a reference variable we check if it has | |||
7960 | // local storage within the function, and if so, return the expression. | |||
7961 | const DeclRefExpr *DR = cast<DeclRefExpr>(E); | |||
7962 | ||||
7963 | // If we leave the immediate function, the lifetime isn't about to end. | |||
7964 | if (DR->refersToEnclosingVariableOrCapture()) | |||
7965 | return nullptr; | |||
7966 | ||||
7967 | if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { | |||
7968 | // Check if it refers to itself, e.g. "int& i = i;". | |||
7969 | if (V == ParentDecl) | |||
7970 | return DR; | |||
7971 | ||||
7972 | if (V->hasLocalStorage()) { | |||
7973 | if (!V->getType()->isReferenceType()) | |||
7974 | return DR; | |||
7975 | ||||
7976 | // Reference variable, follow through to the expression that | |||
7977 | // it points to. | |||
7978 | if (V->hasInit()) { | |||
7979 | // Add the reference variable to the "trail". | |||
7980 | refVars.push_back(DR); | |||
7981 | return EvalVal(V->getInit(), refVars, V); | |||
7982 | } | |||
7983 | } | |||
7984 | } | |||
7985 | ||||
7986 | return nullptr; | |||
7987 | } | |||
7988 | ||||
7989 | case Stmt::UnaryOperatorClass: { | |||
7990 | // The only unary operator that make sense to handle here | |||
7991 | // is Deref. All others don't resolve to a "name." This includes | |||
7992 | // handling all sorts of rvalues passed to a unary operator. | |||
7993 | const UnaryOperator *U = cast<UnaryOperator>(E); | |||
7994 | ||||
7995 | if (U->getOpcode() == UO_Deref) | |||
7996 | return EvalAddr(U->getSubExpr(), refVars, ParentDecl); | |||
7997 | ||||
7998 | return nullptr; | |||
7999 | } | |||
8000 | ||||
8001 | case Stmt::ArraySubscriptExprClass: { | |||
8002 | // Array subscripts are potential references to data on the stack. We | |||
8003 | // retrieve the DeclRefExpr* for the array variable if it indeed | |||
8004 | // has local storage. | |||
8005 | const auto *ASE = cast<ArraySubscriptExpr>(E); | |||
8006 | if (ASE->isTypeDependent()) | |||
8007 | return nullptr; | |||
8008 | return EvalAddr(ASE->getBase(), refVars, ParentDecl); | |||
8009 | } | |||
8010 | ||||
8011 | case Stmt::OMPArraySectionExprClass: { | |||
8012 | return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, | |||
8013 | ParentDecl); | |||
8014 | } | |||
8015 | ||||
8016 | case Stmt::ConditionalOperatorClass: { | |||
8017 | // For conditional operators we need to see if either the LHS or RHS are | |||
8018 | // non-NULL Expr's. If one is non-NULL, we return it. | |||
8019 | const ConditionalOperator *C = cast<ConditionalOperator>(E); | |||
8020 | ||||
8021 | // Handle the GNU extension for missing LHS. | |||
8022 | if (const Expr *LHSExpr = C->getLHS()) { | |||
8023 | // In C++, we can have a throw-expression, which has 'void' type. | |||
8024 | if (!LHSExpr->getType()->isVoidType()) | |||
8025 | if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) | |||
8026 | return LHS; | |||
8027 | } | |||
8028 | ||||
8029 | // In C++, we can have a throw-expression, which has 'void' type. | |||
8030 | if (C->getRHS()->getType()->isVoidType()) | |||
8031 | return nullptr; | |||
8032 | ||||
8033 | return EvalVal(C->getRHS(), refVars, ParentDecl); | |||
8034 | } | |||
8035 | ||||
8036 | // Accesses to members are potential references to data on the stack. | |||
8037 | case Stmt::MemberExprClass: { | |||
8038 | const MemberExpr *M = cast<MemberExpr>(E); | |||
8039 | ||||
8040 | // Check for indirect access. We only want direct field accesses. | |||
8041 | if (M->isArrow()) | |||
8042 | return nullptr; | |||
8043 | ||||
8044 | // Check whether the member type is itself a reference, in which case | |||
8045 | // we're not going to refer to the member, but to what the member refers | |||
8046 | // to. | |||
8047 | if (M->getMemberDecl()->getType()->isReferenceType()) | |||
8048 | return nullptr; | |||
8049 | ||||
8050 | return EvalVal(M->getBase(), refVars, ParentDecl); | |||
8051 | } | |||
8052 | ||||
8053 | case Stmt::MaterializeTemporaryExprClass: | |||
8054 | if (const Expr *Result = | |||
8055 | EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), | |||
8056 | refVars, ParentDecl)) | |||
8057 | return Result; | |||
8058 | return E; | |||
8059 | ||||
8060 | default: | |||
8061 | // Check that we don't return or take the address of a reference to a | |||
8062 | // temporary. This is only useful in C++. | |||
8063 | if (!E->isTypeDependent() && E->isRValue()) | |||
8064 | return E; | |||
8065 | ||||
8066 | // Everything else: we simply don't reason about them. | |||
8067 | return nullptr; | |||
8068 | } | |||
8069 | } while (true); | |||
8070 | } | |||
8071 | ||||
8072 | void | |||
8073 | Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, | |||
8074 | SourceLocation ReturnLoc, | |||
8075 | bool isObjCMethod, | |||
8076 | const AttrVec *Attrs, | |||
8077 | const FunctionDecl *FD) { | |||
8078 | CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); | |||
8079 | ||||
8080 | // Check if the return value is null but should not be. | |||
8081 | if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || | |||
8082 | (!isObjCMethod && isNonNullType(Context, lhsType))) && | |||
8083 | CheckNonNullExpr(*this, RetValExp)) | |||
8084 | Diag(ReturnLoc, diag::warn_null_ret) | |||
8085 | << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); | |||
8086 | ||||
8087 | // C++11 [basic.stc.dynamic.allocation]p4: | |||
8088 | // If an allocation function declared with a non-throwing | |||
8089 | // exception-specification fails to allocate storage, it shall return | |||
8090 | // a null pointer. Any other allocation function that fails to allocate | |||
8091 | // storage shall indicate failure only by throwing an exception [...] | |||
8092 | if (FD) { | |||
8093 | OverloadedOperatorKind Op = FD->getOverloadedOperator(); | |||
8094 | if (Op == OO_New || Op == OO_Array_New) { | |||
8095 | const FunctionProtoType *Proto | |||
8096 | = FD->getType()->castAs<FunctionProtoType>(); | |||
8097 | if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && | |||
8098 | CheckNonNullExpr(*this, RetValExp)) | |||
8099 | Diag(ReturnLoc, diag::warn_operator_new_returns_null) | |||
8100 | << FD << getLangOpts().CPlusPlus11; | |||
8101 | } | |||
8102 | } | |||
8103 | } | |||
8104 | ||||
8105 | //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// | |||
8106 | ||||
8107 | /// Check for comparisons of floating point operands using != and ==. | |||
8108 | /// Issue a warning if these are no self-comparisons, as they are not likely | |||
8109 | /// to do what the programmer intended. | |||
8110 | void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { | |||
8111 | Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); | |||
8112 | Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); | |||
8113 | ||||
8114 | // Special case: check for x == x (which is OK). | |||
8115 | // Do not emit warnings for such cases. | |||
8116 | if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) | |||
8117 | if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) | |||
8118 | if (DRL->getDecl() == DRR->getDecl()) | |||
8119 | return; | |||
8120 | ||||
8121 | // Special case: check for comparisons against literals that can be exactly | |||
8122 | // represented by APFloat. In such cases, do not emit a warning. This | |||
8123 | // is a heuristic: often comparison against such literals are used to | |||
8124 | // detect if a value in a variable has not changed. This clearly can | |||
8125 | // lead to false negatives. | |||
8126 | if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { | |||
8127 | if (FLL->isExact()) | |||
8128 | return; | |||
8129 | } else | |||
8130 | if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) | |||
8131 | if (FLR->isExact()) | |||
8132 | return; | |||
8133 | ||||
8134 | // Check for comparisons with builtin types. | |||
8135 | if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) | |||
8136 | if (CL->getBuiltinCallee()) | |||
8137 | return; | |||
8138 | ||||
8139 | if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) | |||
8140 | if (CR->getBuiltinCallee()) | |||
8141 | return; | |||
8142 | ||||
8143 | // Emit the diagnostic. | |||
8144 | Diag(Loc, diag::warn_floatingpoint_eq) | |||
8145 | << LHS->getSourceRange() << RHS->getSourceRange(); | |||
8146 | } | |||
8147 | ||||
8148 | //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// | |||
8149 | //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// | |||
8150 | ||||
8151 | namespace { | |||
8152 | ||||
8153 | /// Structure recording the 'active' range of an integer-valued | |||
8154 | /// expression. | |||
8155 | struct IntRange { | |||
8156 | /// The number of bits active in the int. | |||
8157 | unsigned Width; | |||
8158 | ||||
8159 | /// True if the int is known not to have negative values. | |||
8160 | bool NonNegative; | |||
8161 | ||||
8162 | IntRange(unsigned Width, bool NonNegative) | |||
8163 | : Width(Width), NonNegative(NonNegative) | |||
8164 | {} | |||
8165 | ||||
8166 | /// Returns the range of the bool type. | |||
8167 | static IntRange forBoolType() { | |||
8168 | return IntRange(1, true); | |||
8169 | } | |||
8170 | ||||
8171 | /// Returns the range of an opaque value of the given integral type. | |||
8172 | static IntRange forValueOfType(ASTContext &C, QualType T) { | |||
8173 | return forValueOfCanonicalType(C, | |||
8174 | T->getCanonicalTypeInternal().getTypePtr()); | |||
8175 | } | |||
8176 | ||||
8177 | /// Returns the range of an opaque value of a canonical integral type. | |||
8178 | static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { | |||
8179 | assert(T->isCanonicalUnqualified())((T->isCanonicalUnqualified()) ? static_cast<void> ( 0) : __assert_fail ("T->isCanonicalUnqualified()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8179, __PRETTY_FUNCTION__)); | |||
8180 | ||||
8181 | if (const VectorType *VT = dyn_cast<VectorType>(T)) | |||
8182 | T = VT->getElementType().getTypePtr(); | |||
8183 | if (const ComplexType *CT = dyn_cast<ComplexType>(T)) | |||
8184 | T = CT->getElementType().getTypePtr(); | |||
8185 | if (const AtomicType *AT = dyn_cast<AtomicType>(T)) | |||
8186 | T = AT->getValueType().getTypePtr(); | |||
8187 | ||||
8188 | if (!C.getLangOpts().CPlusPlus) { | |||
8189 | // For enum types in C code, use the underlying datatype. | |||
8190 | if (const EnumType *ET = dyn_cast<EnumType>(T)) | |||
8191 | T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); | |||
8192 | } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { | |||
8193 | // For enum types in C++, use the known bit width of the enumerators. | |||
8194 | EnumDecl *Enum = ET->getDecl(); | |||
8195 | // In C++11, enums without definitions can have an explicitly specified | |||
8196 | // underlying type. Use this type to compute the range. | |||
8197 | if (!Enum->isCompleteDefinition()) | |||
8198 | return IntRange(C.getIntWidth(QualType(T, 0)), | |||
8199 | !ET->isSignedIntegerOrEnumerationType()); | |||
8200 | ||||
8201 | unsigned NumPositive = Enum->getNumPositiveBits(); | |||
8202 | unsigned NumNegative = Enum->getNumNegativeBits(); | |||
8203 | ||||
8204 | if (NumNegative == 0) | |||
8205 | return IntRange(NumPositive, true/*NonNegative*/); | |||
8206 | else | |||
8207 | return IntRange(std::max(NumPositive + 1, NumNegative), | |||
8208 | false/*NonNegative*/); | |||
8209 | } | |||
8210 | ||||
8211 | const BuiltinType *BT = cast<BuiltinType>(T); | |||
8212 | assert(BT->isInteger())((BT->isInteger()) ? static_cast<void> (0) : __assert_fail ("BT->isInteger()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8212, __PRETTY_FUNCTION__)); | |||
8213 | ||||
8214 | return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); | |||
8215 | } | |||
8216 | ||||
8217 | /// Returns the "target" range of a canonical integral type, i.e. | |||
8218 | /// the range of values expressible in the type. | |||
8219 | /// | |||
8220 | /// This matches forValueOfCanonicalType except that enums have the | |||
8221 | /// full range of their type, not the range of their enumerators. | |||
8222 | static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { | |||
8223 | assert(T->isCanonicalUnqualified())((T->isCanonicalUnqualified()) ? static_cast<void> ( 0) : __assert_fail ("T->isCanonicalUnqualified()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8223, __PRETTY_FUNCTION__)); | |||
8224 | ||||
8225 | if (const VectorType *VT = dyn_cast<VectorType>(T)) | |||
8226 | T = VT->getElementType().getTypePtr(); | |||
8227 | if (const ComplexType *CT = dyn_cast<ComplexType>(T)) | |||
8228 | T = CT->getElementType().getTypePtr(); | |||
8229 | if (const AtomicType *AT = dyn_cast<AtomicType>(T)) | |||
8230 | T = AT->getValueType().getTypePtr(); | |||
8231 | if (const EnumType *ET = dyn_cast<EnumType>(T)) | |||
8232 | T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); | |||
8233 | ||||
8234 | const BuiltinType *BT = cast<BuiltinType>(T); | |||
8235 | assert(BT->isInteger())((BT->isInteger()) ? static_cast<void> (0) : __assert_fail ("BT->isInteger()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8235, __PRETTY_FUNCTION__)); | |||
8236 | ||||
8237 | return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); | |||
8238 | } | |||
8239 | ||||
8240 | /// Returns the supremum of two ranges: i.e. their conservative merge. | |||
8241 | static IntRange join(IntRange L, IntRange R) { | |||
8242 | return IntRange(std::max(L.Width, R.Width), | |||
8243 | L.NonNegative && R.NonNegative); | |||
8244 | } | |||
8245 | ||||
8246 | /// Returns the infinum of two ranges: i.e. their aggressive merge. | |||
8247 | static IntRange meet(IntRange L, IntRange R) { | |||
8248 | return IntRange(std::min(L.Width, R.Width), | |||
8249 | L.NonNegative || R.NonNegative); | |||
8250 | } | |||
8251 | }; | |||
8252 | ||||
8253 | IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { | |||
8254 | if (value.isSigned() && value.isNegative()) | |||
8255 | return IntRange(value.getMinSignedBits(), false); | |||
8256 | ||||
8257 | if (value.getBitWidth() > MaxWidth) | |||
8258 | value = value.trunc(MaxWidth); | |||
8259 | ||||
8260 | // isNonNegative() just checks the sign bit without considering | |||
8261 | // signedness. | |||
8262 | return IntRange(value.getActiveBits(), true); | |||
8263 | } | |||
8264 | ||||
8265 | IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, | |||
8266 | unsigned MaxWidth) { | |||
8267 | if (result.isInt()) | |||
8268 | return GetValueRange(C, result.getInt(), MaxWidth); | |||
8269 | ||||
8270 | if (result.isVector()) { | |||
8271 | IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); | |||
8272 | for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { | |||
8273 | IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); | |||
8274 | R = IntRange::join(R, El); | |||
8275 | } | |||
8276 | return R; | |||
8277 | } | |||
8278 | ||||
8279 | if (result.isComplexInt()) { | |||
8280 | IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); | |||
8281 | IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); | |||
8282 | return IntRange::join(R, I); | |||
8283 | } | |||
8284 | ||||
8285 | // This can happen with lossless casts to intptr_t of "based" lvalues. | |||
8286 | // Assume it might use arbitrary bits. | |||
8287 | // FIXME: The only reason we need to pass the type in here is to get | |||
8288 | // the sign right on this one case. It would be nice if APValue | |||
8289 | // preserved this. | |||
8290 | assert(result.isLValue() || result.isAddrLabelDiff())((result.isLValue() || result.isAddrLabelDiff()) ? static_cast <void> (0) : __assert_fail ("result.isLValue() || result.isAddrLabelDiff()" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8290, __PRETTY_FUNCTION__)); | |||
8291 | return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); | |||
8292 | } | |||
8293 | ||||
8294 | QualType GetExprType(const Expr *E) { | |||
8295 | QualType Ty = E->getType(); | |||
8296 | if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) | |||
8297 | Ty = AtomicRHS->getValueType(); | |||
8298 | return Ty; | |||
8299 | } | |||
8300 | ||||
8301 | /// Pseudo-evaluate the given integer expression, estimating the | |||
8302 | /// range of values it might take. | |||
8303 | /// | |||
8304 | /// \param MaxWidth - the width to which the value will be truncated | |||
8305 | IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { | |||
8306 | E = E->IgnoreParens(); | |||
8307 | ||||
8308 | // Try a full evaluation first. | |||
8309 | Expr::EvalResult result; | |||
8310 | if (E->EvaluateAsRValue(result, C)) | |||
8311 | return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); | |||
8312 | ||||
8313 | // I think we only want to look through implicit casts here; if the | |||
8314 | // user has an explicit widening cast, we should treat the value as | |||
8315 | // being of the new, wider type. | |||
8316 | if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { | |||
8317 | if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) | |||
8318 | return GetExprRange(C, CE->getSubExpr(), MaxWidth); | |||
8319 | ||||
8320 | IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); | |||
8321 | ||||
8322 | bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || | |||
8323 | CE->getCastKind() == CK_BooleanToSignedIntegral; | |||
8324 | ||||
8325 | // Assume that non-integer casts can span the full range of the type. | |||
8326 | if (!isIntegerCast) | |||
8327 | return OutputTypeRange; | |||
8328 | ||||
8329 | IntRange SubRange | |||
8330 | = GetExprRange(C, CE->getSubExpr(), | |||
8331 | std::min(MaxWidth, OutputTypeRange.Width)); | |||
8332 | ||||
8333 | // Bail out if the subexpr's range is as wide as the cast type. | |||
8334 | if (SubRange.Width >= OutputTypeRange.Width) | |||
8335 | return OutputTypeRange; | |||
8336 | ||||
8337 | // Otherwise, we take the smaller width, and we're non-negative if | |||
8338 | // either the output type or the subexpr is. | |||
8339 | return IntRange(SubRange.Width, | |||
8340 | SubRange.NonNegative || OutputTypeRange.NonNegative); | |||
8341 | } | |||
8342 | ||||
8343 | if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { | |||
8344 | // If we can fold the condition, just take that operand. | |||
8345 | bool CondResult; | |||
8346 | if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) | |||
8347 | return GetExprRange(C, CondResult ? CO->getTrueExpr() | |||
8348 | : CO->getFalseExpr(), | |||
8349 | MaxWidth); | |||
8350 | ||||
8351 | // Otherwise, conservatively merge. | |||
8352 | IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); | |||
8353 | IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); | |||
8354 | return IntRange::join(L, R); | |||
8355 | } | |||
8356 | ||||
8357 | if (const auto *BO = dyn_cast<BinaryOperator>(E)) { | |||
8358 | switch (BO->getOpcode()) { | |||
8359 | ||||
8360 | // Boolean-valued operations are single-bit and positive. | |||
8361 | case BO_LAnd: | |||
8362 | case BO_LOr: | |||
8363 | case BO_LT: | |||
8364 | case BO_GT: | |||
8365 | case BO_LE: | |||
8366 | case BO_GE: | |||
8367 | case BO_EQ: | |||
8368 | case BO_NE: | |||
8369 | return IntRange::forBoolType(); | |||
8370 | ||||
8371 | // The type of the assignments is the type of the LHS, so the RHS | |||
8372 | // is not necessarily the same type. | |||
8373 | case BO_MulAssign: | |||
8374 | case BO_DivAssign: | |||
8375 | case BO_RemAssign: | |||
8376 | case BO_AddAssign: | |||
8377 | case BO_SubAssign: | |||
8378 | case BO_XorAssign: | |||
8379 | case BO_OrAssign: | |||
8380 | // TODO: bitfields? | |||
8381 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
8382 | ||||
8383 | // Simple assignments just pass through the RHS, which will have | |||
8384 | // been coerced to the LHS type. | |||
8385 | case BO_Assign: | |||
8386 | // TODO: bitfields? | |||
8387 | return GetExprRange(C, BO->getRHS(), MaxWidth); | |||
8388 | ||||
8389 | // Operations with opaque sources are black-listed. | |||
8390 | case BO_PtrMemD: | |||
8391 | case BO_PtrMemI: | |||
8392 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
8393 | ||||
8394 | // Bitwise-and uses the *infinum* of the two source ranges. | |||
8395 | case BO_And: | |||
8396 | case BO_AndAssign: | |||
8397 | return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), | |||
8398 | GetExprRange(C, BO->getRHS(), MaxWidth)); | |||
8399 | ||||
8400 | // Left shift gets black-listed based on a judgement call. | |||
8401 | case BO_Shl: | |||
8402 | // ...except that we want to treat '1 << (blah)' as logically | |||
8403 | // positive. It's an important idiom. | |||
8404 | if (IntegerLiteral *I | |||
8405 | = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { | |||
8406 | if (I->getValue() == 1) { | |||
8407 | IntRange R = IntRange::forValueOfType(C, GetExprType(E)); | |||
8408 | return IntRange(R.Width, /*NonNegative*/ true); | |||
8409 | } | |||
8410 | } | |||
8411 | // fallthrough | |||
8412 | ||||
8413 | case BO_ShlAssign: | |||
8414 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
8415 | ||||
8416 | // Right shift by a constant can narrow its left argument. | |||
8417 | case BO_Shr: | |||
8418 | case BO_ShrAssign: { | |||
8419 | IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); | |||
8420 | ||||
8421 | // If the shift amount is a positive constant, drop the width by | |||
8422 | // that much. | |||
8423 | llvm::APSInt shift; | |||
8424 | if (BO->getRHS()->isIntegerConstantExpr(shift, C) && | |||
8425 | shift.isNonNegative()) { | |||
8426 | unsigned zext = shift.getZExtValue(); | |||
8427 | if (zext >= L.Width) | |||
8428 | L.Width = (L.NonNegative ? 0 : 1); | |||
8429 | else | |||
8430 | L.Width -= zext; | |||
8431 | } | |||
8432 | ||||
8433 | return L; | |||
8434 | } | |||
8435 | ||||
8436 | // Comma acts as its right operand. | |||
8437 | case BO_Comma: | |||
8438 | return GetExprRange(C, BO->getRHS(), MaxWidth); | |||
8439 | ||||
8440 | // Black-list pointer subtractions. | |||
8441 | case BO_Sub: | |||
8442 | if (BO->getLHS()->getType()->isPointerType()) | |||
8443 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
8444 | break; | |||
8445 | ||||
8446 | // The width of a division result is mostly determined by the size | |||
8447 | // of the LHS. | |||
8448 | case BO_Div: { | |||
8449 | // Don't 'pre-truncate' the operands. | |||
8450 | unsigned opWidth = C.getIntWidth(GetExprType(E)); | |||
8451 | IntRange L = GetExprRange(C, BO->getLHS(), opWidth); | |||
8452 | ||||
8453 | // If the divisor is constant, use that. | |||
8454 | llvm::APSInt divisor; | |||
8455 | if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { | |||
8456 | unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) | |||
8457 | if (log2 >= L.Width) | |||
8458 | L.Width = (L.NonNegative ? 0 : 1); | |||
8459 | else | |||
8460 | L.Width = std::min(L.Width - log2, MaxWidth); | |||
8461 | return L; | |||
8462 | } | |||
8463 | ||||
8464 | // Otherwise, just use the LHS's width. | |||
8465 | IntRange R = GetExprRange(C, BO->getRHS(), opWidth); | |||
8466 | return IntRange(L.Width, L.NonNegative && R.NonNegative); | |||
8467 | } | |||
8468 | ||||
8469 | // The result of a remainder can't be larger than the result of | |||
8470 | // either side. | |||
8471 | case BO_Rem: { | |||
8472 | // Don't 'pre-truncate' the operands. | |||
8473 | unsigned opWidth = C.getIntWidth(GetExprType(E)); | |||
8474 | IntRange L = GetExprRange(C, BO->getLHS(), opWidth); | |||
8475 | IntRange R = GetExprRange(C, BO->getRHS(), opWidth); | |||
8476 | ||||
8477 | IntRange meet = IntRange::meet(L, R); | |||
8478 | meet.Width = std::min(meet.Width, MaxWidth); | |||
8479 | return meet; | |||
8480 | } | |||
8481 | ||||
8482 | // The default behavior is okay for these. | |||
8483 | case BO_Mul: | |||
8484 | case BO_Add: | |||
8485 | case BO_Xor: | |||
8486 | case BO_Or: | |||
8487 | break; | |||
8488 | } | |||
8489 | ||||
8490 | // The default case is to treat the operation as if it were closed | |||
8491 | // on the narrowest type that encompasses both operands. | |||
8492 | IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); | |||
8493 | IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); | |||
8494 | return IntRange::join(L, R); | |||
8495 | } | |||
8496 | ||||
8497 | if (const auto *UO = dyn_cast<UnaryOperator>(E)) { | |||
8498 | switch (UO->getOpcode()) { | |||
8499 | // Boolean-valued operations are white-listed. | |||
8500 | case UO_LNot: | |||
8501 | return IntRange::forBoolType(); | |||
8502 | ||||
8503 | // Operations with opaque sources are black-listed. | |||
8504 | case UO_Deref: | |||
8505 | case UO_AddrOf: // should be impossible | |||
8506 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
8507 | ||||
8508 | default: | |||
8509 | return GetExprRange(C, UO->getSubExpr(), MaxWidth); | |||
8510 | } | |||
8511 | } | |||
8512 | ||||
8513 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) | |||
8514 | return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); | |||
8515 | ||||
8516 | if (const auto *BitField = E->getSourceBitField()) | |||
8517 | return IntRange(BitField->getBitWidthValue(C), | |||
8518 | BitField->getType()->isUnsignedIntegerOrEnumerationType()); | |||
8519 | ||||
8520 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
8521 | } | |||
8522 | ||||
8523 | IntRange GetExprRange(ASTContext &C, const Expr *E) { | |||
8524 | return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); | |||
8525 | } | |||
8526 | ||||
8527 | /// Checks whether the given value, which currently has the given | |||
8528 | /// source semantics, has the same value when coerced through the | |||
8529 | /// target semantics. | |||
8530 | bool IsSameFloatAfterCast(const llvm::APFloat &value, | |||
8531 | const llvm::fltSemantics &Src, | |||
8532 | const llvm::fltSemantics &Tgt) { | |||
8533 | llvm::APFloat truncated = value; | |||
8534 | ||||
8535 | bool ignored; | |||
8536 | truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); | |||
8537 | truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); | |||
8538 | ||||
8539 | return truncated.bitwiseIsEqual(value); | |||
8540 | } | |||
8541 | ||||
8542 | /// Checks whether the given value, which currently has the given | |||
8543 | /// source semantics, has the same value when coerced through the | |||
8544 | /// target semantics. | |||
8545 | /// | |||
8546 | /// The value might be a vector of floats (or a complex number). | |||
8547 | bool IsSameFloatAfterCast(const APValue &value, | |||
8548 | const llvm::fltSemantics &Src, | |||
8549 | const llvm::fltSemantics &Tgt) { | |||
8550 | if (value.isFloat()) | |||
8551 | return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); | |||
8552 | ||||
8553 | if (value.isVector()) { | |||
8554 | for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) | |||
8555 | if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) | |||
8556 | return false; | |||
8557 | return true; | |||
8558 | } | |||
8559 | ||||
8560 | assert(value.isComplexFloat())((value.isComplexFloat()) ? static_cast<void> (0) : __assert_fail ("value.isComplexFloat()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8560, __PRETTY_FUNCTION__)); | |||
8561 | return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && | |||
8562 | IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); | |||
8563 | } | |||
8564 | ||||
8565 | void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); | |||
8566 | ||||
8567 | bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { | |||
8568 | // Suppress cases where we are comparing against an enum constant. | |||
8569 | if (const DeclRefExpr *DR = | |||
8570 | dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) | |||
8571 | if (isa<EnumConstantDecl>(DR->getDecl())) | |||
8572 | return true; | |||
8573 | ||||
8574 | // Suppress cases where the '0' value is expanded from a macro. | |||
8575 | if (E->getLocStart().isMacroID()) | |||
8576 | return true; | |||
8577 | ||||
8578 | return false; | |||
8579 | } | |||
8580 | ||||
8581 | bool isNonBooleanIntegerValue(Expr *E) { | |||
8582 | return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType(); | |||
8583 | } | |||
8584 | ||||
8585 | bool isNonBooleanUnsignedValue(Expr *E) { | |||
8586 | // We are checking that the expression is not known to have boolean value, | |||
8587 | // is an integer type; and is either unsigned after implicit casts, | |||
8588 | // or was unsigned before implicit casts. | |||
8589 | return isNonBooleanIntegerValue(E) && | |||
8590 | (!E->getType()->isSignedIntegerType() || | |||
8591 | !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); | |||
8592 | } | |||
8593 | ||||
8594 | enum class LimitType { | |||
8595 | Max = 1U << 0U, // e.g. 32767 for short | |||
8596 | Min = 1U << 1U, // e.g. -32768 for short | |||
8597 | Both = Max | Min // When the value is both the Min and the Max limit at the | |||
8598 | // same time; e.g. in C++, A::a in enum A { a = 0 }; | |||
8599 | }; | |||
8600 | ||||
8601 | /// Checks whether Expr 'Constant' may be the | |||
8602 | /// std::numeric_limits<>::max() or std::numeric_limits<>::min() | |||
8603 | /// of the Expr 'Other'. If true, then returns the limit type (min or max). | |||
8604 | /// The Value is the evaluation of Constant | |||
8605 | llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant, Expr *Other, | |||
8606 | const llvm::APSInt &Value) { | |||
8607 | if (IsEnumConstOrFromMacro(S, Constant)) | |||
8608 | return llvm::Optional<LimitType>(); | |||
8609 | ||||
8610 | if (isNonBooleanUnsignedValue(Other) && Value == 0) | |||
8611 | return LimitType::Min; | |||
8612 | ||||
8613 | // TODO: Investigate using GetExprRange() to get tighter bounds | |||
8614 | // on the bit ranges. | |||
8615 | QualType OtherT = Other->IgnoreParenImpCasts()->getType(); | |||
8616 | if (const auto *AT = OtherT->getAs<AtomicType>()) | |||
8617 | OtherT = AT->getValueType(); | |||
8618 | ||||
8619 | IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); | |||
8620 | ||||
8621 | // Special-case for C++ for enum with one enumerator with value of 0. | |||
8622 | if (OtherRange.Width == 0) | |||
8623 | return Value == 0 ? LimitType::Both : llvm::Optional<LimitType>(); | |||
8624 | ||||
8625 | if (llvm::APSInt::isSameValue( | |||
8626 | llvm::APSInt::getMaxValue(OtherRange.Width, | |||
8627 | OtherT->isUnsignedIntegerType()), | |||
8628 | Value)) | |||
8629 | return LimitType::Max; | |||
8630 | ||||
8631 | if (llvm::APSInt::isSameValue( | |||
8632 | llvm::APSInt::getMinValue(OtherRange.Width, | |||
8633 | OtherT->isUnsignedIntegerType()), | |||
8634 | Value)) | |||
8635 | return LimitType::Min; | |||
8636 | ||||
8637 | return llvm::None; | |||
8638 | } | |||
8639 | ||||
8640 | bool HasEnumType(Expr *E) { | |||
8641 | // Strip off implicit integral promotions. | |||
8642 | while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { | |||
8643 | if (ICE->getCastKind() != CK_IntegralCast && | |||
8644 | ICE->getCastKind() != CK_NoOp) | |||
8645 | break; | |||
8646 | E = ICE->getSubExpr(); | |||
8647 | } | |||
8648 | ||||
8649 | return E->getType()->isEnumeralType(); | |||
8650 | } | |||
8651 | ||||
8652 | bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, | |||
8653 | Expr *Other, const llvm::APSInt &Value, | |||
8654 | bool RhsConstant) { | |||
8655 | // Disable warning in template instantiations | |||
8656 | // and only analyze <, >, <= and >= operations. | |||
8657 | if (S.inTemplateInstantiation() || !E->isRelationalOp()) | |||
8658 | return false; | |||
8659 | ||||
8660 | BinaryOperatorKind Op = E->getOpcode(); | |||
8661 | ||||
8662 | QualType OType = Other->IgnoreParenImpCasts()->getType(); | |||
8663 | ||||
8664 | llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant? | |||
8665 | ||||
8666 | if (!(isNonBooleanIntegerValue(Other) && | |||
8667 | (ValueType = IsTypeLimit(S, Constant, Other, Value)))) | |||
8668 | return false; | |||
8669 | ||||
8670 | bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant; | |||
8671 | bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE); | |||
8672 | if (ValueType != LimitType::Both) { | |||
8673 | bool ResultWhenConstNeOther = | |||
8674 | ConstIsLowerBound ^ (ValueType == LimitType::Max); | |||
8675 | if (ResultWhenConstEqualsOther != ResultWhenConstNeOther) | |||
8676 | return false; // The comparison is not tautological. | |||
8677 | } else if (ResultWhenConstEqualsOther == ConstIsLowerBound) | |||
8678 | return false; // The comparison is not tautological. | |||
8679 | ||||
8680 | const bool Result = ResultWhenConstEqualsOther; | |||
8681 | ||||
8682 | unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0) | |||
8683 | ? (HasEnumType(Other) | |||
8684 | ? diag::warn_unsigned_enum_always_true_comparison | |||
8685 | : diag::warn_unsigned_always_true_comparison) | |||
8686 | : diag::warn_tautological_constant_compare; | |||
8687 | ||||
8688 | // Should be enough for uint128 (39 decimal digits) | |||
8689 | SmallString<64> PrettySourceValue; | |||
8690 | llvm::raw_svector_ostream OS(PrettySourceValue); | |||
8691 | OS << Value; | |||
8692 | ||||
8693 | S.Diag(E->getOperatorLoc(), Diag) | |||
8694 | << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result | |||
8695 | << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); | |||
8696 | ||||
8697 | return true; | |||
8698 | } | |||
8699 | ||||
8700 | bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, | |||
8701 | Expr *Other, const llvm::APSInt &Value, | |||
8702 | bool RhsConstant) { | |||
8703 | // Disable warning in template instantiations. | |||
8704 | if (S.inTemplateInstantiation()) | |||
8705 | return false; | |||
8706 | ||||
8707 | Constant = Constant->IgnoreParenImpCasts(); | |||
8708 | Other = Other->IgnoreParenImpCasts(); | |||
8709 | ||||
8710 | // TODO: Investigate using GetExprRange() to get tighter bounds | |||
8711 | // on the bit ranges. | |||
8712 | QualType OtherT = Other->getType(); | |||
8713 | if (const auto *AT = OtherT->getAs<AtomicType>()) | |||
8714 | OtherT = AT->getValueType(); | |||
8715 | IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); | |||
8716 | unsigned OtherWidth = OtherRange.Width; | |||
8717 | ||||
8718 | bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); | |||
8719 | ||||
8720 | BinaryOperatorKind op = E->getOpcode(); | |||
8721 | bool IsTrue = true; | |||
8722 | ||||
8723 | // Used for diagnostic printout. | |||
8724 | enum { | |||
8725 | LiteralConstant = 0, | |||
8726 | CXXBoolLiteralTrue, | |||
8727 | CXXBoolLiteralFalse | |||
8728 | } LiteralOrBoolConstant = LiteralConstant; | |||
8729 | ||||
8730 | if (!OtherIsBooleanType) { | |||
8731 | QualType ConstantT = Constant->getType(); | |||
8732 | QualType CommonT = E->getLHS()->getType(); | |||
8733 | ||||
8734 | if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) | |||
8735 | return false; | |||
8736 | assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&(((OtherT->isIntegerType() && ConstantT->isIntegerType ()) && "comparison with non-integer type") ? static_cast <void> (0) : __assert_fail ("(OtherT->isIntegerType() && ConstantT->isIntegerType()) && \"comparison with non-integer type\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8737, __PRETTY_FUNCTION__)) | |||
8737 | "comparison with non-integer type")(((OtherT->isIntegerType() && ConstantT->isIntegerType ()) && "comparison with non-integer type") ? static_cast <void> (0) : __assert_fail ("(OtherT->isIntegerType() && ConstantT->isIntegerType()) && \"comparison with non-integer type\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8737, __PRETTY_FUNCTION__)); | |||
8738 | ||||
8739 | bool ConstantSigned = ConstantT->isSignedIntegerType(); | |||
8740 | bool CommonSigned = CommonT->isSignedIntegerType(); | |||
8741 | ||||
8742 | bool EqualityOnly = false; | |||
8743 | ||||
8744 | if (CommonSigned) { | |||
8745 | // The common type is signed, therefore no signed to unsigned conversion. | |||
8746 | if (!OtherRange.NonNegative) { | |||
8747 | // Check that the constant is representable in type OtherT. | |||
8748 | if (ConstantSigned) { | |||
8749 | if (OtherWidth >= Value.getMinSignedBits()) | |||
8750 | return false; | |||
8751 | } else { // !ConstantSigned | |||
8752 | if (OtherWidth >= Value.getActiveBits() + 1) | |||
8753 | return false; | |||
8754 | } | |||
8755 | } else { // !OtherSigned | |||
8756 | // Check that the constant is representable in type OtherT. | |||
8757 | // Negative values are out of range. | |||
8758 | if (ConstantSigned) { | |||
8759 | if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) | |||
8760 | return false; | |||
8761 | } else { // !ConstantSigned | |||
8762 | if (OtherWidth >= Value.getActiveBits()) | |||
8763 | return false; | |||
8764 | } | |||
8765 | } | |||
8766 | } else { // !CommonSigned | |||
8767 | if (OtherRange.NonNegative) { | |||
8768 | if (OtherWidth >= Value.getActiveBits()) | |||
8769 | return false; | |||
8770 | } else { // OtherSigned | |||
8771 | assert(!ConstantSigned &&((!ConstantSigned && "Two signed types converted to unsigned types." ) ? static_cast<void> (0) : __assert_fail ("!ConstantSigned && \"Two signed types converted to unsigned types.\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8772, __PRETTY_FUNCTION__)) | |||
8772 | "Two signed types converted to unsigned types.")((!ConstantSigned && "Two signed types converted to unsigned types." ) ? static_cast<void> (0) : __assert_fail ("!ConstantSigned && \"Two signed types converted to unsigned types.\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8772, __PRETTY_FUNCTION__)); | |||
8773 | // Check to see if the constant is representable in OtherT. | |||
8774 | if (OtherWidth > Value.getActiveBits()) | |||
8775 | return false; | |||
8776 | // Check to see if the constant is equivalent to a negative value | |||
8777 | // cast to CommonT. | |||
8778 | if (S.Context.getIntWidth(ConstantT) == | |||
8779 | S.Context.getIntWidth(CommonT) && | |||
8780 | Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) | |||
8781 | return false; | |||
8782 | // The constant value rests between values that OtherT can represent | |||
8783 | // after conversion. Relational comparison still works, but equality | |||
8784 | // comparisons will be tautological. | |||
8785 | EqualityOnly = true; | |||
8786 | } | |||
8787 | } | |||
8788 | ||||
8789 | bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); | |||
8790 | ||||
8791 | if (op == BO_EQ || op == BO_NE) { | |||
8792 | IsTrue = op == BO_NE; | |||
8793 | } else if (EqualityOnly) { | |||
8794 | return false; | |||
8795 | } else if (RhsConstant) { | |||
8796 | if (op == BO_GT || op == BO_GE) | |||
8797 | IsTrue = !PositiveConstant; | |||
8798 | else // op == BO_LT || op == BO_LE | |||
8799 | IsTrue = PositiveConstant; | |||
8800 | } else { | |||
8801 | if (op == BO_LT || op == BO_LE) | |||
8802 | IsTrue = !PositiveConstant; | |||
8803 | else // op == BO_GT || op == BO_GE | |||
8804 | IsTrue = PositiveConstant; | |||
8805 | } | |||
8806 | } else { | |||
8807 | // Other isKnownToHaveBooleanValue | |||
8808 | enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; | |||
8809 | enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; | |||
8810 | enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; | |||
8811 | ||||
8812 | static const struct LinkedConditions { | |||
8813 | CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; | |||
8814 | CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; | |||
8815 | CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; | |||
8816 | CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; | |||
8817 | CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; | |||
8818 | CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; | |||
8819 | ||||
8820 | } TruthTable = { | |||
8821 | // Constant on LHS. | Constant on RHS. | | |||
8822 | // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| | |||
8823 | { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, | |||
8824 | { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, | |||
8825 | { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, | |||
8826 | { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, | |||
8827 | { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, | |||
8828 | { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } | |||
8829 | }; | |||
8830 | ||||
8831 | bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); | |||
8832 | ||||
8833 | enum ConstantValue ConstVal = Zero; | |||
8834 | if (Value.isUnsigned() || Value.isNonNegative()) { | |||
8835 | if (Value == 0) { | |||
8836 | LiteralOrBoolConstant = | |||
8837 | ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; | |||
8838 | ConstVal = Zero; | |||
8839 | } else if (Value == 1) { | |||
8840 | LiteralOrBoolConstant = | |||
8841 | ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; | |||
8842 | ConstVal = One; | |||
8843 | } else { | |||
8844 | LiteralOrBoolConstant = LiteralConstant; | |||
8845 | ConstVal = GT_One; | |||
8846 | } | |||
8847 | } else { | |||
8848 | ConstVal = LT_Zero; | |||
8849 | } | |||
8850 | ||||
8851 | CompareBoolWithConstantResult CmpRes; | |||
8852 | ||||
8853 | switch (op) { | |||
8854 | case BO_LT: | |||
8855 | CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; | |||
8856 | break; | |||
8857 | case BO_GT: | |||
8858 | CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; | |||
8859 | break; | |||
8860 | case BO_LE: | |||
8861 | CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; | |||
8862 | break; | |||
8863 | case BO_GE: | |||
8864 | CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; | |||
8865 | break; | |||
8866 | case BO_EQ: | |||
8867 | CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; | |||
8868 | break; | |||
8869 | case BO_NE: | |||
8870 | CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; | |||
8871 | break; | |||
8872 | default: | |||
8873 | CmpRes = Unkwn; | |||
8874 | break; | |||
8875 | } | |||
8876 | ||||
8877 | if (CmpRes == AFals) { | |||
8878 | IsTrue = false; | |||
8879 | } else if (CmpRes == ATrue) { | |||
8880 | IsTrue = true; | |||
8881 | } else { | |||
8882 | return false; | |||
8883 | } | |||
8884 | } | |||
8885 | ||||
8886 | // If this is a comparison to an enum constant, include that | |||
8887 | // constant in the diagnostic. | |||
8888 | const EnumConstantDecl *ED = nullptr; | |||
8889 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) | |||
8890 | ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); | |||
8891 | ||||
8892 | SmallString<64> PrettySourceValue; | |||
8893 | llvm::raw_svector_ostream OS(PrettySourceValue); | |||
8894 | if (ED) | |||
8895 | OS << '\'' << *ED << "' (" << Value << ")"; | |||
8896 | else | |||
8897 | OS << Value; | |||
8898 | ||||
8899 | S.DiagRuntimeBehavior( | |||
8900 | E->getOperatorLoc(), E, | |||
8901 | S.PDiag(diag::warn_out_of_range_compare) | |||
8902 | << OS.str() << LiteralOrBoolConstant | |||
8903 | << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue | |||
8904 | << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); | |||
8905 | ||||
8906 | return true; | |||
8907 | } | |||
8908 | ||||
8909 | /// Analyze the operands of the given comparison. Implements the | |||
8910 | /// fallback case from AnalyzeComparison. | |||
8911 | void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { | |||
8912 | AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); | |||
8913 | AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); | |||
8914 | } | |||
8915 | ||||
8916 | /// \brief Implements -Wsign-compare. | |||
8917 | /// | |||
8918 | /// \param E the binary operator to check for warnings | |||
8919 | void AnalyzeComparison(Sema &S, BinaryOperator *E) { | |||
8920 | // The type the comparison is being performed in. | |||
8921 | QualType T = E->getLHS()->getType(); | |||
8922 | ||||
8923 | // Only analyze comparison operators where both sides have been converted to | |||
8924 | // the same type. | |||
8925 | if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) | |||
8926 | return AnalyzeImpConvsInComparison(S, E); | |||
8927 | ||||
8928 | // Don't analyze value-dependent comparisons directly. | |||
8929 | if (E->isValueDependent()) | |||
8930 | return AnalyzeImpConvsInComparison(S, E); | |||
8931 | ||||
8932 | Expr *LHS = E->getLHS(); | |||
8933 | Expr *RHS = E->getRHS(); | |||
8934 | ||||
8935 | if (T->isIntegralType(S.Context)) { | |||
8936 | llvm::APSInt RHSValue; | |||
8937 | llvm::APSInt LHSValue; | |||
8938 | ||||
8939 | bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); | |||
8940 | bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); | |||
8941 | ||||
8942 | // We don't care about expressions whose result is a constant. | |||
8943 | if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) | |||
8944 | return AnalyzeImpConvsInComparison(S, E); | |||
8945 | ||||
8946 | // We only care about expressions where just one side is literal | |||
8947 | if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { | |||
8948 | // Is the constant on the RHS or LHS? | |||
8949 | const bool RhsConstant = IsRHSIntegralLiteral; | |||
8950 | Expr *Const = RhsConstant ? RHS : LHS; | |||
8951 | Expr *Other = RhsConstant ? LHS : RHS; | |||
8952 | const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; | |||
8953 | ||||
8954 | // Check whether an integer constant comparison results in a value | |||
8955 | // of 'true' or 'false'. | |||
8956 | ||||
8957 | if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) | |||
8958 | return AnalyzeImpConvsInComparison(S, E); | |||
8959 | ||||
8960 | if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant)) | |||
8961 | return AnalyzeImpConvsInComparison(S, E); | |||
8962 | } | |||
8963 | } | |||
8964 | ||||
8965 | if (!T->hasUnsignedIntegerRepresentation()) { | |||
8966 | // We don't do anything special if this isn't an unsigned integral | |||
8967 | // comparison: we're only interested in integral comparisons, and | |||
8968 | // signed comparisons only happen in cases we don't care to warn about. | |||
8969 | return AnalyzeImpConvsInComparison(S, E); | |||
8970 | } | |||
8971 | ||||
8972 | LHS = LHS->IgnoreParenImpCasts(); | |||
8973 | RHS = RHS->IgnoreParenImpCasts(); | |||
8974 | ||||
8975 | // Check to see if one of the (unmodified) operands is of different | |||
8976 | // signedness. | |||
8977 | Expr *signedOperand, *unsignedOperand; | |||
8978 | if (LHS->getType()->hasSignedIntegerRepresentation()) { | |||
8979 | assert(!RHS->getType()->hasSignedIntegerRepresentation() &&((!RHS->getType()->hasSignedIntegerRepresentation() && "unsigned comparison between two signed integer expressions?" ) ? static_cast<void> (0) : __assert_fail ("!RHS->getType()->hasSignedIntegerRepresentation() && \"unsigned comparison between two signed integer expressions?\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8980, __PRETTY_FUNCTION__)) | |||
8980 | "unsigned comparison between two signed integer expressions?")((!RHS->getType()->hasSignedIntegerRepresentation() && "unsigned comparison between two signed integer expressions?" ) ? static_cast<void> (0) : __assert_fail ("!RHS->getType()->hasSignedIntegerRepresentation() && \"unsigned comparison between two signed integer expressions?\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 8980, __PRETTY_FUNCTION__)); | |||
8981 | signedOperand = LHS; | |||
8982 | unsignedOperand = RHS; | |||
8983 | } else if (RHS->getType()->hasSignedIntegerRepresentation()) { | |||
8984 | signedOperand = RHS; | |||
8985 | unsignedOperand = LHS; | |||
8986 | } else { | |||
8987 | return AnalyzeImpConvsInComparison(S, E); | |||
8988 | } | |||
8989 | ||||
8990 | // Otherwise, calculate the effective range of the signed operand. | |||
8991 | IntRange signedRange = GetExprRange(S.Context, signedOperand); | |||
8992 | ||||
8993 | // Go ahead and analyze implicit conversions in the operands. Note | |||
8994 | // that we skip the implicit conversions on both sides. | |||
8995 | AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); | |||
8996 | AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); | |||
8997 | ||||
8998 | // If the signed range is non-negative, -Wsign-compare won't fire. | |||
8999 | if (signedRange.NonNegative) | |||
9000 | return; | |||
9001 | ||||
9002 | // For (in)equality comparisons, if the unsigned operand is a | |||
9003 | // constant which cannot collide with a overflowed signed operand, | |||
9004 | // then reinterpreting the signed operand as unsigned will not | |||
9005 | // change the result of the comparison. | |||
9006 | if (E->isEqualityOp()) { | |||
9007 | unsigned comparisonWidth = S.Context.getIntWidth(T); | |||
9008 | IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); | |||
9009 | ||||
9010 | // We should never be unable to prove that the unsigned operand is | |||
9011 | // non-negative. | |||
9012 | assert(unsignedRange.NonNegative && "unsigned range includes negative?")((unsignedRange.NonNegative && "unsigned range includes negative?" ) ? static_cast<void> (0) : __assert_fail ("unsignedRange.NonNegative && \"unsigned range includes negative?\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 9012, __PRETTY_FUNCTION__)); | |||
9013 | ||||
9014 | if (unsignedRange.Width < comparisonWidth) | |||
9015 | return; | |||
9016 | } | |||
9017 | ||||
9018 | S.DiagRuntimeBehavior(E->getOperatorLoc(), E, | |||
9019 | S.PDiag(diag::warn_mixed_sign_comparison) | |||
9020 | << LHS->getType() << RHS->getType() | |||
9021 | << LHS->getSourceRange() << RHS->getSourceRange()); | |||
9022 | } | |||
9023 | ||||
9024 | /// Analyzes an attempt to assign the given value to a bitfield. | |||
9025 | /// | |||
9026 | /// Returns true if there was something fishy about the attempt. | |||
9027 | bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, | |||
9028 | SourceLocation InitLoc) { | |||
9029 | assert(Bitfield->isBitField())((Bitfield->isBitField()) ? static_cast<void> (0) : __assert_fail ("Bitfield->isBitField()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 9029, __PRETTY_FUNCTION__)); | |||
9030 | if (Bitfield->isInvalidDecl()) | |||
9031 | return false; | |||
9032 | ||||
9033 | // White-list bool bitfields. | |||
9034 | QualType BitfieldType = Bitfield->getType(); | |||
9035 | if (BitfieldType->isBooleanType()) | |||
9036 | return false; | |||
9037 | ||||
9038 | if (BitfieldType->isEnumeralType()) { | |||
9039 | EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); | |||
9040 | // If the underlying enum type was not explicitly specified as an unsigned | |||
9041 | // type and the enum contain only positive values, MSVC++ will cause an | |||
9042 | // inconsistency by storing this as a signed type. | |||
9043 | if (S.getLangOpts().CPlusPlus11 && | |||
9044 | !BitfieldEnumDecl->getIntegerTypeSourceInfo() && | |||
9045 | BitfieldEnumDecl->getNumPositiveBits() > 0 && | |||
9046 | BitfieldEnumDecl->getNumNegativeBits() == 0) { | |||
9047 | S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) | |||
9048 | << BitfieldEnumDecl->getNameAsString(); | |||
9049 | } | |||
9050 | } | |||
9051 | ||||
9052 | if (Bitfield->getType()->isBooleanType()) | |||
9053 | return false; | |||
9054 | ||||
9055 | // Ignore value- or type-dependent expressions. | |||
9056 | if (Bitfield->getBitWidth()->isValueDependent() || | |||
9057 | Bitfield->getBitWidth()->isTypeDependent() || | |||
9058 | Init->isValueDependent() || | |||
9059 | Init->isTypeDependent()) | |||
9060 | return false; | |||
9061 | ||||
9062 | Expr *OriginalInit = Init->IgnoreParenImpCasts(); | |||
9063 | unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); | |||
9064 | ||||
9065 | llvm::APSInt Value; | |||
9066 | if (!OriginalInit->EvaluateAsInt(Value, S.Context, | |||
9067 | Expr::SE_AllowSideEffects)) { | |||
9068 | // The RHS is not constant. If the RHS has an enum type, make sure the | |||
9069 | // bitfield is wide enough to hold all the values of the enum without | |||
9070 | // truncation. | |||
9071 | if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { | |||
9072 | EnumDecl *ED = EnumTy->getDecl(); | |||
9073 | bool SignedBitfield = BitfieldType->isSignedIntegerType(); | |||
9074 | ||||
9075 | // Enum types are implicitly signed on Windows, so check if there are any | |||
9076 | // negative enumerators to see if the enum was intended to be signed or | |||
9077 | // not. | |||
9078 | bool SignedEnum = ED->getNumNegativeBits() > 0; | |||
9079 | ||||
9080 | // Check for surprising sign changes when assigning enum values to a | |||
9081 | // bitfield of different signedness. If the bitfield is signed and we | |||
9082 | // have exactly the right number of bits to store this unsigned enum, | |||
9083 | // suggest changing the enum to an unsigned type. This typically happens | |||
9084 | // on Windows where unfixed enums always use an underlying type of 'int'. | |||
9085 | unsigned DiagID = 0; | |||
9086 | if (SignedEnum && !SignedBitfield) { | |||
9087 | DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; | |||
9088 | } else if (SignedBitfield && !SignedEnum && | |||
9089 | ED->getNumPositiveBits() == FieldWidth) { | |||
9090 | DiagID = diag::warn_signed_bitfield_enum_conversion; | |||
9091 | } | |||
9092 | ||||
9093 | if (DiagID) { | |||
9094 | S.Diag(InitLoc, DiagID) << Bitfield << ED; | |||
9095 | TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); | |||
9096 | SourceRange TypeRange = | |||
9097 | TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); | |||
9098 | S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) | |||
9099 | << SignedEnum << TypeRange; | |||
9100 | } | |||
9101 | ||||
9102 | // Compute the required bitwidth. If the enum has negative values, we need | |||
9103 | // one more bit than the normal number of positive bits to represent the | |||
9104 | // sign bit. | |||
9105 | unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, | |||
9106 | ED->getNumNegativeBits()) | |||
9107 | : ED->getNumPositiveBits(); | |||
9108 | ||||
9109 | // Check the bitwidth. | |||
9110 | if (BitsNeeded > FieldWidth) { | |||
9111 | Expr *WidthExpr = Bitfield->getBitWidth(); | |||
9112 | S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) | |||
9113 | << Bitfield << ED; | |||
9114 | S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) | |||
9115 | << BitsNeeded << ED << WidthExpr->getSourceRange(); | |||
9116 | } | |||
9117 | } | |||
9118 | ||||
9119 | return false; | |||
9120 | } | |||
9121 | ||||
9122 | unsigned OriginalWidth = Value.getBitWidth(); | |||
9123 | ||||
9124 | if (!Value.isSigned() || Value.isNegative()) | |||
9125 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) | |||
9126 | if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) | |||
9127 | OriginalWidth = Value.getMinSignedBits(); | |||
9128 | ||||
9129 | if (OriginalWidth <= FieldWidth) | |||
9130 | return false; | |||
9131 | ||||
9132 | // Compute the value which the bitfield will contain. | |||
9133 | llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); | |||
9134 | TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); | |||
9135 | ||||
9136 | // Check whether the stored value is equal to the original value. | |||
9137 | TruncatedValue = TruncatedValue.extend(OriginalWidth); | |||
9138 | if (llvm::APSInt::isSameValue(Value, TruncatedValue)) | |||
9139 | return false; | |||
9140 | ||||
9141 | // Special-case bitfields of width 1: booleans are naturally 0/1, and | |||
9142 | // therefore don't strictly fit into a signed bitfield of width 1. | |||
9143 | if (FieldWidth == 1 && Value == 1) | |||
9144 | return false; | |||
9145 | ||||
9146 | std::string PrettyValue = Value.toString(10); | |||
9147 | std::string PrettyTrunc = TruncatedValue.toString(10); | |||
9148 | ||||
9149 | S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) | |||
9150 | << PrettyValue << PrettyTrunc << OriginalInit->getType() | |||
9151 | << Init->getSourceRange(); | |||
9152 | ||||
9153 | return true; | |||
9154 | } | |||
9155 | ||||
9156 | /// Analyze the given simple or compound assignment for warning-worthy | |||
9157 | /// operations. | |||
9158 | void AnalyzeAssignment(Sema &S, BinaryOperator *E) { | |||
9159 | // Just recurse on the LHS. | |||
9160 | AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); | |||
9161 | ||||
9162 | // We want to recurse on the RHS as normal unless we're assigning to | |||
9163 | // a bitfield. | |||
9164 | if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { | |||
9165 | if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), | |||
9166 | E->getOperatorLoc())) { | |||
9167 | // Recurse, ignoring any implicit conversions on the RHS. | |||
9168 | return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), | |||
9169 | E->getOperatorLoc()); | |||
9170 | } | |||
9171 | } | |||
9172 | ||||
9173 | AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); | |||
9174 | } | |||
9175 | ||||
9176 | /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. | |||
9177 | void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, | |||
9178 | SourceLocation CContext, unsigned diag, | |||
9179 | bool pruneControlFlow = false) { | |||
9180 | if (pruneControlFlow) { | |||
9181 | S.DiagRuntimeBehavior(E->getExprLoc(), E, | |||
9182 | S.PDiag(diag) | |||
9183 | << SourceType << T << E->getSourceRange() | |||
9184 | << SourceRange(CContext)); | |||
9185 | return; | |||
9186 | } | |||
9187 | S.Diag(E->getExprLoc(), diag) | |||
9188 | << SourceType << T << E->getSourceRange() << SourceRange(CContext); | |||
9189 | } | |||
9190 | ||||
9191 | /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. | |||
9192 | void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, | |||
9193 | unsigned diag, bool pruneControlFlow = false) { | |||
9194 | DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); | |||
9195 | } | |||
9196 | ||||
9197 | ||||
9198 | /// Diagnose an implicit cast from a floating point value to an integer value. | |||
9199 | void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, | |||
9200 | ||||
9201 | SourceLocation CContext) { | |||
9202 | const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); | |||
9203 | const bool PruneWarnings = S.inTemplateInstantiation(); | |||
9204 | ||||
9205 | Expr *InnerE = E->IgnoreParenImpCasts(); | |||
9206 | // We also want to warn on, e.g., "int i = -1.234" | |||
9207 | if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) | |||
9208 | if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) | |||
9209 | InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); | |||
9210 | ||||
9211 | const bool IsLiteral = | |||
9212 | isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); | |||
9213 | ||||
9214 | llvm::APFloat Value(0.0); | |||
9215 | bool IsConstant = | |||
9216 | E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); | |||
9217 | if (!IsConstant) { | |||
9218 | return DiagnoseImpCast(S, E, T, CContext, | |||
9219 | diag::warn_impcast_float_integer, PruneWarnings); | |||
9220 | } | |||
9221 | ||||
9222 | bool isExact = false; | |||
9223 | ||||
9224 | llvm::APSInt IntegerValue(S.Context.getIntWidth(T), | |||
9225 | T->hasUnsignedIntegerRepresentation()); | |||
9226 | if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, | |||
9227 | &isExact) == llvm::APFloat::opOK && | |||
9228 | isExact) { | |||
9229 | if (IsLiteral) return; | |||
9230 | return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, | |||
9231 | PruneWarnings); | |||
9232 | } | |||
9233 | ||||
9234 | unsigned DiagID = 0; | |||
9235 | if (IsLiteral) { | |||
9236 | // Warn on floating point literal to integer. | |||
9237 | DiagID = diag::warn_impcast_literal_float_to_integer; | |||
9238 | } else if (IntegerValue == 0) { | |||
9239 | if (Value.isZero()) { // Skip -0.0 to 0 conversion. | |||
9240 | return DiagnoseImpCast(S, E, T, CContext, | |||
9241 | diag::warn_impcast_float_integer, PruneWarnings); | |||
9242 | } | |||
9243 | // Warn on non-zero to zero conversion. | |||
9244 | DiagID = diag::warn_impcast_float_to_integer_zero; | |||
9245 | } else { | |||
9246 | if (IntegerValue.isUnsigned()) { | |||
9247 | if (!IntegerValue.isMaxValue()) { | |||
9248 | return DiagnoseImpCast(S, E, T, CContext, | |||
9249 | diag::warn_impcast_float_integer, PruneWarnings); | |||
9250 | } | |||
9251 | } else { // IntegerValue.isSigned() | |||
9252 | if (!IntegerValue.isMaxSignedValue() && | |||
9253 | !IntegerValue.isMinSignedValue()) { | |||
9254 | return DiagnoseImpCast(S, E, T, CContext, | |||
9255 | diag::warn_impcast_float_integer, PruneWarnings); | |||
9256 | } | |||
9257 | } | |||
9258 | // Warn on evaluatable floating point expression to integer conversion. | |||
9259 | DiagID = diag::warn_impcast_float_to_integer; | |||
9260 | } | |||
9261 | ||||
9262 | // FIXME: Force the precision of the source value down so we don't print | |||
9263 | // digits which are usually useless (we don't really care here if we | |||
9264 | // truncate a digit by accident in edge cases). Ideally, APFloat::toString | |||
9265 | // would automatically print the shortest representation, but it's a bit | |||
9266 | // tricky to implement. | |||
9267 | SmallString<16> PrettySourceValue; | |||
9268 | unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); | |||
9269 | precision = (precision * 59 + 195) / 196; | |||
9270 | Value.toString(PrettySourceValue, precision); | |||
9271 | ||||
9272 | SmallString<16> PrettyTargetValue; | |||
9273 | if (IsBool) | |||
9274 | PrettyTargetValue = Value.isZero() ? "false" : "true"; | |||
9275 | else | |||
9276 | IntegerValue.toString(PrettyTargetValue); | |||
9277 | ||||
9278 | if (PruneWarnings) { | |||
9279 | S.DiagRuntimeBehavior(E->getExprLoc(), E, | |||
9280 | S.PDiag(DiagID) | |||
9281 | << E->getType() << T.getUnqualifiedType() | |||
9282 | << PrettySourceValue << PrettyTargetValue | |||
9283 | << E->getSourceRange() << SourceRange(CContext)); | |||
9284 | } else { | |||
9285 | S.Diag(E->getExprLoc(), DiagID) | |||
9286 | << E->getType() << T.getUnqualifiedType() << PrettySourceValue | |||
9287 | << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); | |||
9288 | } | |||
9289 | } | |||
9290 | ||||
9291 | std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { | |||
9292 | if (!Range.Width) return "0"; | |||
9293 | ||||
9294 | llvm::APSInt ValueInRange = Value; | |||
9295 | ValueInRange.setIsSigned(!Range.NonNegative); | |||
9296 | ValueInRange = ValueInRange.trunc(Range.Width); | |||
9297 | return ValueInRange.toString(10); | |||
9298 | } | |||
9299 | ||||
9300 | bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { | |||
9301 | if (!isa<ImplicitCastExpr>(Ex)) | |||
9302 | return false; | |||
9303 | ||||
9304 | Expr *InnerE = Ex->IgnoreParenImpCasts(); | |||
9305 | const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); | |||
9306 | const Type *Source = | |||
9307 | S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); | |||
9308 | if (Target->isDependentType()) | |||
9309 | return false; | |||
9310 | ||||
9311 | const BuiltinType *FloatCandidateBT = | |||
9312 | dyn_cast<BuiltinType>(ToBool ? Source : Target); | |||
9313 | const Type *BoolCandidateType = ToBool ? Target : Source; | |||
9314 | ||||
9315 | return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && | |||
9316 | FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); | |||
9317 | } | |||
9318 | ||||
9319 | void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, | |||
9320 | SourceLocation CC) { | |||
9321 | unsigned NumArgs = TheCall->getNumArgs(); | |||
9322 | for (unsigned i = 0; i < NumArgs; ++i) { | |||
9323 | Expr *CurrA = TheCall->getArg(i); | |||
9324 | if (!IsImplicitBoolFloatConversion(S, CurrA, true)) | |||
9325 | continue; | |||
9326 | ||||
9327 | bool IsSwapped = ((i > 0) && | |||
9328 | IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); | |||
9329 | IsSwapped |= ((i < (NumArgs - 1)) && | |||
9330 | IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); | |||
9331 | if (IsSwapped) { | |||
9332 | // Warn on this floating-point to bool conversion. | |||
9333 | DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), | |||
9334 | CurrA->getType(), CC, | |||
9335 | diag::warn_impcast_floating_point_to_bool); | |||
9336 | } | |||
9337 | } | |||
9338 | } | |||
9339 | ||||
9340 | void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { | |||
9341 | if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, | |||
9342 | E->getExprLoc())) | |||
9343 | return; | |||
9344 | ||||
9345 | // Don't warn on functions which have return type nullptr_t. | |||
9346 | if (isa<CallExpr>(E)) | |||
9347 | return; | |||
9348 | ||||
9349 | // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). | |||
9350 | const Expr::NullPointerConstantKind NullKind = | |||
9351 | E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); | |||
9352 | if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) | |||
9353 | return; | |||
9354 | ||||
9355 | // Return if target type is a safe conversion. | |||
9356 | if (T->isAnyPointerType() || T->isBlockPointerType() || | |||
9357 | T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) | |||
9358 | return; | |||
9359 | ||||
9360 | SourceLocation Loc = E->getSourceRange().getBegin(); | |||
9361 | ||||
9362 | // Venture through the macro stacks to get to the source of macro arguments. | |||
9363 | // The new location is a better location than the complete location that was | |||
9364 | // passed in. | |||
9365 | while (S.SourceMgr.isMacroArgExpansion(Loc)) | |||
9366 | Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); | |||
9367 | ||||
9368 | while (S.SourceMgr.isMacroArgExpansion(CC)) | |||
9369 | CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); | |||
9370 | ||||
9371 | // __null is usually wrapped in a macro. Go up a macro if that is the case. | |||
9372 | if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { | |||
9373 | StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( | |||
9374 | Loc, S.SourceMgr, S.getLangOpts()); | |||
9375 | if (MacroName == "NULL") | |||
9376 | Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; | |||
9377 | } | |||
9378 | ||||
9379 | // Only warn if the null and context location are in the same macro expansion. | |||
9380 | if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) | |||
9381 | return; | |||
9382 | ||||
9383 | S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) | |||
9384 | << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) | |||
9385 | << FixItHint::CreateReplacement(Loc, | |||
9386 | S.getFixItZeroLiteralForType(T, Loc)); | |||
9387 | } | |||
9388 | ||||
9389 | void checkObjCArrayLiteral(Sema &S, QualType TargetType, | |||
9390 | ObjCArrayLiteral *ArrayLiteral); | |||
9391 | void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, | |||
9392 | ObjCDictionaryLiteral *DictionaryLiteral); | |||
9393 | ||||
9394 | /// Check a single element within a collection literal against the | |||
9395 | /// target element type. | |||
9396 | void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, | |||
9397 | Expr *Element, unsigned ElementKind) { | |||
9398 | // Skip a bitcast to 'id' or qualified 'id'. | |||
9399 | if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { | |||
9400 | if (ICE->getCastKind() == CK_BitCast && | |||
9401 | ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) | |||
9402 | Element = ICE->getSubExpr(); | |||
9403 | } | |||
9404 | ||||
9405 | QualType ElementType = Element->getType(); | |||
9406 | ExprResult ElementResult(Element); | |||
9407 | if (ElementType->getAs<ObjCObjectPointerType>() && | |||
9408 | S.CheckSingleAssignmentConstraints(TargetElementType, | |||
9409 | ElementResult, | |||
9410 | false, false) | |||
9411 | != Sema::Compatible) { | |||
9412 | S.Diag(Element->getLocStart(), | |||
9413 | diag::warn_objc_collection_literal_element) | |||
9414 | << ElementType << ElementKind << TargetElementType | |||
9415 | << Element->getSourceRange(); | |||
9416 | } | |||
9417 | ||||
9418 | if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) | |||
9419 | checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); | |||
9420 | else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) | |||
9421 | checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); | |||
9422 | } | |||
9423 | ||||
9424 | /// Check an Objective-C array literal being converted to the given | |||
9425 | /// target type. | |||
9426 | void checkObjCArrayLiteral(Sema &S, QualType TargetType, | |||
9427 | ObjCArrayLiteral *ArrayLiteral) { | |||
9428 | if (!S.NSArrayDecl) | |||
9429 | return; | |||
9430 | ||||
9431 | const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); | |||
9432 | if (!TargetObjCPtr) | |||
9433 | return; | |||
9434 | ||||
9435 | if (TargetObjCPtr->isUnspecialized() || | |||
9436 | TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() | |||
9437 | != S.NSArrayDecl->getCanonicalDecl()) | |||
9438 | return; | |||
9439 | ||||
9440 | auto TypeArgs = TargetObjCPtr->getTypeArgs(); | |||
9441 | if (TypeArgs.size() != 1) | |||
9442 | return; | |||
9443 | ||||
9444 | QualType TargetElementType = TypeArgs[0]; | |||
9445 | for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { | |||
9446 | checkObjCCollectionLiteralElement(S, TargetElementType, | |||
9447 | ArrayLiteral->getElement(I), | |||
9448 | 0); | |||
9449 | } | |||
9450 | } | |||
9451 | ||||
9452 | /// Check an Objective-C dictionary literal being converted to the given | |||
9453 | /// target type. | |||
9454 | void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, | |||
9455 | ObjCDictionaryLiteral *DictionaryLiteral) { | |||
9456 | if (!S.NSDictionaryDecl) | |||
9457 | return; | |||
9458 | ||||
9459 | const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); | |||
9460 | if (!TargetObjCPtr) | |||
9461 | return; | |||
9462 | ||||
9463 | if (TargetObjCPtr->isUnspecialized() || | |||
9464 | TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() | |||
9465 | != S.NSDictionaryDecl->getCanonicalDecl()) | |||
9466 | return; | |||
9467 | ||||
9468 | auto TypeArgs = TargetObjCPtr->getTypeArgs(); | |||
9469 | if (TypeArgs.size() != 2) | |||
9470 | return; | |||
9471 | ||||
9472 | QualType TargetKeyType = TypeArgs[0]; | |||
9473 | QualType TargetObjectType = TypeArgs[1]; | |||
9474 | for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { | |||
9475 | auto Element = DictionaryLiteral->getKeyValueElement(I); | |||
9476 | checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); | |||
9477 | checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); | |||
9478 | } | |||
9479 | } | |||
9480 | ||||
9481 | // Helper function to filter out cases for constant width constant conversion. | |||
9482 | // Don't warn on char array initialization or for non-decimal values. | |||
9483 | bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, | |||
9484 | SourceLocation CC) { | |||
9485 | // If initializing from a constant, and the constant starts with '0', | |||
9486 | // then it is a binary, octal, or hexadecimal. Allow these constants | |||
9487 | // to fill all the bits, even if there is a sign change. | |||
9488 | if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { | |||
9489 | const char FirstLiteralCharacter = | |||
9490 | S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; | |||
9491 | if (FirstLiteralCharacter == '0') | |||
9492 | return false; | |||
9493 | } | |||
9494 | ||||
9495 | // If the CC location points to a '{', and the type is char, then assume | |||
9496 | // assume it is an array initialization. | |||
9497 | if (CC.isValid() && T->isCharType()) { | |||
9498 | const char FirstContextCharacter = | |||
9499 | S.getSourceManager().getCharacterData(CC)[0]; | |||
9500 | if (FirstContextCharacter == '{') | |||
9501 | return false; | |||
9502 | } | |||
9503 | ||||
9504 | return true; | |||
9505 | } | |||
9506 | ||||
9507 | void CheckImplicitConversion(Sema &S, Expr *E, QualType T, | |||
9508 | SourceLocation CC, bool *ICContext = nullptr) { | |||
9509 | if (E->isTypeDependent() || E->isValueDependent()) return; | |||
9510 | ||||
9511 | const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); | |||
9512 | const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); | |||
9513 | if (Source == Target) return; | |||
9514 | if (Target->isDependentType()) return; | |||
9515 | ||||
9516 | // If the conversion context location is invalid don't complain. We also | |||
9517 | // don't want to emit a warning if the issue occurs from the expansion of | |||
9518 | // a system macro. The problem is that 'getSpellingLoc()' is slow, so we | |||
9519 | // delay this check as long as possible. Once we detect we are in that | |||
9520 | // scenario, we just return. | |||
9521 | if (CC.isInvalid()) | |||
9522 | return; | |||
9523 | ||||
9524 | // Diagnose implicit casts to bool. | |||
9525 | if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { | |||
9526 | if (isa<StringLiteral>(E)) | |||
9527 | // Warn on string literal to bool. Checks for string literals in logical | |||
9528 | // and expressions, for instance, assert(0 && "error here"), are | |||
9529 | // prevented by a check in AnalyzeImplicitConversions(). | |||
9530 | return DiagnoseImpCast(S, E, T, CC, | |||
9531 | diag::warn_impcast_string_literal_to_bool); | |||
9532 | if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || | |||
9533 | isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { | |||
9534 | // This covers the literal expressions that evaluate to Objective-C | |||
9535 | // objects. | |||
9536 | return DiagnoseImpCast(S, E, T, CC, | |||
9537 | diag::warn_impcast_objective_c_literal_to_bool); | |||
9538 | } | |||
9539 | if (Source->isPointerType() || Source->canDecayToPointerType()) { | |||
9540 | // Warn on pointer to bool conversion that is always true. | |||
9541 | S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, | |||
9542 | SourceRange(CC)); | |||
9543 | } | |||
9544 | } | |||
9545 | ||||
9546 | // Check implicit casts from Objective-C collection literals to specialized | |||
9547 | // collection types, e.g., NSArray<NSString *> *. | |||
9548 | if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) | |||
9549 | checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); | |||
9550 | else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) | |||
9551 | checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); | |||
9552 | ||||
9553 | // Strip vector types. | |||
9554 | if (isa<VectorType>(Source)) { | |||
9555 | if (!isa<VectorType>(Target)) { | |||
9556 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
9557 | return; | |||
9558 | return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); | |||
9559 | } | |||
9560 | ||||
9561 | // If the vector cast is cast between two vectors of the same size, it is | |||
9562 | // a bitcast, not a conversion. | |||
9563 | if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) | |||
9564 | return; | |||
9565 | ||||
9566 | Source = cast<VectorType>(Source)->getElementType().getTypePtr(); | |||
9567 | Target = cast<VectorType>(Target)->getElementType().getTypePtr(); | |||
9568 | } | |||
9569 | if (auto VecTy = dyn_cast<VectorType>(Target)) | |||
9570 | Target = VecTy->getElementType().getTypePtr(); | |||
9571 | ||||
9572 | // Strip complex types. | |||
9573 | if (isa<ComplexType>(Source)) { | |||
9574 | if (!isa<ComplexType>(Target)) { | |||
9575 | if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) | |||
9576 | return; | |||
9577 | ||||
9578 | return DiagnoseImpCast(S, E, T, CC, | |||
9579 | S.getLangOpts().CPlusPlus | |||
9580 | ? diag::err_impcast_complex_scalar | |||
9581 | : diag::warn_impcast_complex_scalar); | |||
9582 | } | |||
9583 | ||||
9584 | Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); | |||
9585 | Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); | |||
9586 | } | |||
9587 | ||||
9588 | const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); | |||
9589 | const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); | |||
9590 | ||||
9591 | // If the source is floating point... | |||
9592 | if (SourceBT && SourceBT->isFloatingPoint()) { | |||
9593 | // ...and the target is floating point... | |||
9594 | if (TargetBT && TargetBT->isFloatingPoint()) { | |||
9595 | // ...then warn if we're dropping FP rank. | |||
9596 | ||||
9597 | // Builtin FP kinds are ordered by increasing FP rank. | |||
9598 | if (SourceBT->getKind() > TargetBT->getKind()) { | |||
9599 | // Don't warn about float constants that are precisely | |||
9600 | // representable in the target type. | |||
9601 | Expr::EvalResult result; | |||
9602 | if (E->EvaluateAsRValue(result, S.Context)) { | |||
9603 | // Value might be a float, a float vector, or a float complex. | |||
9604 | if (IsSameFloatAfterCast(result.Val, | |||
9605 | S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), | |||
9606 | S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) | |||
9607 | return; | |||
9608 | } | |||
9609 | ||||
9610 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
9611 | return; | |||
9612 | ||||
9613 | DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); | |||
9614 | } | |||
9615 | // ... or possibly if we're increasing rank, too | |||
9616 | else if (TargetBT->getKind() > SourceBT->getKind()) { | |||
9617 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
9618 | return; | |||
9619 | ||||
9620 | DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); | |||
9621 | } | |||
9622 | return; | |||
9623 | } | |||
9624 | ||||
9625 | // If the target is integral, always warn. | |||
9626 | if (TargetBT && TargetBT->isInteger()) { | |||
9627 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
9628 | return; | |||
9629 | ||||
9630 | DiagnoseFloatingImpCast(S, E, T, CC); | |||
9631 | } | |||
9632 | ||||
9633 | // Detect the case where a call result is converted from floating-point to | |||
9634 | // to bool, and the final argument to the call is converted from bool, to | |||
9635 | // discover this typo: | |||
9636 | // | |||
9637 | // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" | |||
9638 | // | |||
9639 | // FIXME: This is an incredibly special case; is there some more general | |||
9640 | // way to detect this class of misplaced-parentheses bug? | |||
9641 | if (Target->isBooleanType() && isa<CallExpr>(E)) { | |||
9642 | // Check last argument of function call to see if it is an | |||
9643 | // implicit cast from a type matching the type the result | |||
9644 | // is being cast to. | |||
9645 | CallExpr *CEx = cast<CallExpr>(E); | |||
9646 | if (unsigned NumArgs = CEx->getNumArgs()) { | |||
9647 | Expr *LastA = CEx->getArg(NumArgs - 1); | |||
9648 | Expr *InnerE = LastA->IgnoreParenImpCasts(); | |||
9649 | if (isa<ImplicitCastExpr>(LastA) && | |||
9650 | InnerE->getType()->isBooleanType()) { | |||
9651 | // Warn on this floating-point to bool conversion | |||
9652 | DiagnoseImpCast(S, E, T, CC, | |||
9653 | diag::warn_impcast_floating_point_to_bool); | |||
9654 | } | |||
9655 | } | |||
9656 | } | |||
9657 | return; | |||
9658 | } | |||
9659 | ||||
9660 | DiagnoseNullConversion(S, E, T, CC); | |||
9661 | ||||
9662 | S.DiscardMisalignedMemberAddress(Target, E); | |||
9663 | ||||
9664 | if (!Source->isIntegerType() || !Target->isIntegerType()) | |||
9665 | return; | |||
9666 | ||||
9667 | // TODO: remove this early return once the false positives for constant->bool | |||
9668 | // in templates, macros, etc, are reduced or removed. | |||
9669 | if (Target->isSpecificBuiltinType(BuiltinType::Bool)) | |||
9670 | return; | |||
9671 | ||||
9672 | IntRange SourceRange = GetExprRange(S.Context, E); | |||
9673 | IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); | |||
9674 | ||||
9675 | if (SourceRange.Width > TargetRange.Width) { | |||
9676 | // If the source is a constant, use a default-on diagnostic. | |||
9677 | // TODO: this should happen for bitfield stores, too. | |||
9678 | llvm::APSInt Value(32); | |||
9679 | if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { | |||
9680 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
9681 | return; | |||
9682 | ||||
9683 | std::string PrettySourceValue = Value.toString(10); | |||
9684 | std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); | |||
9685 | ||||
9686 | S.DiagRuntimeBehavior(E->getExprLoc(), E, | |||
9687 | S.PDiag(diag::warn_impcast_integer_precision_constant) | |||
9688 | << PrettySourceValue << PrettyTargetValue | |||
9689 | << E->getType() << T << E->getSourceRange() | |||
9690 | << clang::SourceRange(CC)); | |||
9691 | return; | |||
9692 | } | |||
9693 | ||||
9694 | // People want to build with -Wshorten-64-to-32 and not -Wconversion. | |||
9695 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
9696 | return; | |||
9697 | ||||
9698 | if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) | |||
9699 | return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, | |||
9700 | /* pruneControlFlow */ true); | |||
9701 | return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); | |||
9702 | } | |||
9703 | ||||
9704 | if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && | |||
9705 | SourceRange.NonNegative && Source->isSignedIntegerType()) { | |||
9706 | // Warn when doing a signed to signed conversion, warn if the positive | |||
9707 | // source value is exactly the width of the target type, which will | |||
9708 | // cause a negative value to be stored. | |||
9709 | ||||
9710 | llvm::APSInt Value; | |||
9711 | if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && | |||
9712 | !S.SourceMgr.isInSystemMacro(CC)) { | |||
9713 | if (isSameWidthConstantConversion(S, E, T, CC)) { | |||
9714 | std::string PrettySourceValue = Value.toString(10); | |||
9715 | std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); | |||
9716 | ||||
9717 | S.DiagRuntimeBehavior( | |||
9718 | E->getExprLoc(), E, | |||
9719 | S.PDiag(diag::warn_impcast_integer_precision_constant) | |||
9720 | << PrettySourceValue << PrettyTargetValue << E->getType() << T | |||
9721 | << E->getSourceRange() << clang::SourceRange(CC)); | |||
9722 | return; | |||
9723 | } | |||
9724 | } | |||
9725 | ||||
9726 | // Fall through for non-constants to give a sign conversion warning. | |||
9727 | } | |||
9728 | ||||
9729 | if ((TargetRange.NonNegative && !SourceRange.NonNegative) || | |||
9730 | (!TargetRange.NonNegative && SourceRange.NonNegative && | |||
9731 | SourceRange.Width == TargetRange.Width)) { | |||
9732 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
9733 | return; | |||
9734 | ||||
9735 | unsigned DiagID = diag::warn_impcast_integer_sign; | |||
9736 | ||||
9737 | // Traditionally, gcc has warned about this under -Wsign-compare. | |||
9738 | // We also want to warn about it in -Wconversion. | |||
9739 | // So if -Wconversion is off, use a completely identical diagnostic | |||
9740 | // in the sign-compare group. | |||
9741 | // The conditional-checking code will | |||
9742 | if (ICContext) { | |||
9743 | DiagID = diag::warn_impcast_integer_sign_conditional; | |||
9744 | *ICContext = true; | |||
9745 | } | |||
9746 | ||||
9747 | return DiagnoseImpCast(S, E, T, CC, DiagID); | |||
9748 | } | |||
9749 | ||||
9750 | // Diagnose conversions between different enumeration types. | |||
9751 | // In C, we pretend that the type of an EnumConstantDecl is its enumeration | |||
9752 | // type, to give us better diagnostics. | |||
9753 | QualType SourceType = E->getType(); | |||
9754 | if (!S.getLangOpts().CPlusPlus) { | |||
9755 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | |||
9756 | if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { | |||
9757 | EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); | |||
9758 | SourceType = S.Context.getTypeDeclType(Enum); | |||
9759 | Source = S.Context.getCanonicalType(SourceType).getTypePtr(); | |||
9760 | } | |||
9761 | } | |||
9762 | ||||
9763 | if (const EnumType *SourceEnum = Source->getAs<EnumType>()) | |||
9764 | if (const EnumType *TargetEnum = Target->getAs<EnumType>()) | |||
9765 | if (SourceEnum->getDecl()->hasNameForLinkage() && | |||
9766 | TargetEnum->getDecl()->hasNameForLinkage() && | |||
9767 | SourceEnum != TargetEnum) { | |||
9768 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
9769 | return; | |||
9770 | ||||
9771 | return DiagnoseImpCast(S, E, SourceType, T, CC, | |||
9772 | diag::warn_impcast_different_enum_types); | |||
9773 | } | |||
9774 | } | |||
9775 | ||||
9776 | void CheckConditionalOperator(Sema &S, ConditionalOperator *E, | |||
9777 | SourceLocation CC, QualType T); | |||
9778 | ||||
9779 | void CheckConditionalOperand(Sema &S, Expr *E, QualType T, | |||
9780 | SourceLocation CC, bool &ICContext) { | |||
9781 | E = E->IgnoreParenImpCasts(); | |||
9782 | ||||
9783 | if (isa<ConditionalOperator>(E)) | |||
9784 | return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); | |||
9785 | ||||
9786 | AnalyzeImplicitConversions(S, E, CC); | |||
9787 | if (E->getType() != T) | |||
9788 | return CheckImplicitConversion(S, E, T, CC, &ICContext); | |||
9789 | } | |||
9790 | ||||
9791 | void CheckConditionalOperator(Sema &S, ConditionalOperator *E, | |||
9792 | SourceLocation CC, QualType T) { | |||
9793 | AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); | |||
9794 | ||||
9795 | bool Suspicious = false; | |||
9796 | CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); | |||
9797 | CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); | |||
9798 | ||||
9799 | // If -Wconversion would have warned about either of the candidates | |||
9800 | // for a signedness conversion to the context type... | |||
9801 | if (!Suspicious) return; | |||
9802 | ||||
9803 | // ...but it's currently ignored... | |||
9804 | if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) | |||
9805 | return; | |||
9806 | ||||
9807 | // ...then check whether it would have warned about either of the | |||
9808 | // candidates for a signedness conversion to the condition type. | |||
9809 | if (E->getType() == T) return; | |||
9810 | ||||
9811 | Suspicious = false; | |||
9812 | CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), | |||
9813 | E->getType(), CC, &Suspicious); | |||
9814 | if (!Suspicious) | |||
9815 | CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), | |||
9816 | E->getType(), CC, &Suspicious); | |||
9817 | } | |||
9818 | ||||
9819 | /// CheckBoolLikeConversion - Check conversion of given expression to boolean. | |||
9820 | /// Input argument E is a logical expression. | |||
9821 | void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { | |||
9822 | if (S.getLangOpts().Bool) | |||
9823 | return; | |||
9824 | CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); | |||
9825 | } | |||
9826 | ||||
9827 | /// AnalyzeImplicitConversions - Find and report any interesting | |||
9828 | /// implicit conversions in the given expression. There are a couple | |||
9829 | /// of competing diagnostics here, -Wconversion and -Wsign-compare. | |||
9830 | void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { | |||
9831 | QualType T = OrigE->getType(); | |||
9832 | Expr *E = OrigE->IgnoreParenImpCasts(); | |||
9833 | ||||
9834 | if (E->isTypeDependent() || E->isValueDependent()) | |||
9835 | return; | |||
9836 | ||||
9837 | // For conditional operators, we analyze the arguments as if they | |||
9838 | // were being fed directly into the output. | |||
9839 | if (isa<ConditionalOperator>(E)) { | |||
9840 | ConditionalOperator *CO = cast<ConditionalOperator>(E); | |||
9841 | CheckConditionalOperator(S, CO, CC, T); | |||
9842 | return; | |||
9843 | } | |||
9844 | ||||
9845 | // Check implicit argument conversions for function calls. | |||
9846 | if (CallExpr *Call = dyn_cast<CallExpr>(E)) | |||
9847 | CheckImplicitArgumentConversions(S, Call, CC); | |||
9848 | ||||
9849 | // Go ahead and check any implicit conversions we might have skipped. | |||
9850 | // The non-canonical typecheck is just an optimization; | |||
9851 | // CheckImplicitConversion will filter out dead implicit conversions. | |||
9852 | if (E->getType() != T) | |||
9853 | CheckImplicitConversion(S, E, T, CC); | |||
9854 | ||||
9855 | // Now continue drilling into this expression. | |||
9856 | ||||
9857 | if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { | |||
9858 | // The bound subexpressions in a PseudoObjectExpr are not reachable | |||
9859 | // as transitive children. | |||
9860 | // FIXME: Use a more uniform representation for this. | |||
9861 | for (auto *SE : POE->semantics()) | |||
9862 | if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) | |||
9863 | AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); | |||
9864 | } | |||
9865 | ||||
9866 | // Skip past explicit casts. | |||
9867 | if (isa<ExplicitCastExpr>(E)) { | |||
9868 | E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); | |||
9869 | return AnalyzeImplicitConversions(S, E, CC); | |||
9870 | } | |||
9871 | ||||
9872 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
9873 | // Do a somewhat different check with comparison operators. | |||
9874 | if (BO->isComparisonOp()) | |||
9875 | return AnalyzeComparison(S, BO); | |||
9876 | ||||
9877 | // And with simple assignments. | |||
9878 | if (BO->getOpcode() == BO_Assign) | |||
9879 | return AnalyzeAssignment(S, BO); | |||
9880 | } | |||
9881 | ||||
9882 | // These break the otherwise-useful invariant below. Fortunately, | |||
9883 | // we don't really need to recurse into them, because any internal | |||
9884 | // expressions should have been analyzed already when they were | |||
9885 | // built into statements. | |||
9886 | if (isa<StmtExpr>(E)) return; | |||
9887 | ||||
9888 | // Don't descend into unevaluated contexts. | |||
9889 | if (isa<UnaryExprOrTypeTraitExpr>(E)) return; | |||
9890 | ||||
9891 | // Now just recurse over the expression's children. | |||
9892 | CC = E->getExprLoc(); | |||
9893 | BinaryOperator *BO = dyn_cast<BinaryOperator>(E); | |||
9894 | bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; | |||
9895 | for (Stmt *SubStmt : E->children()) { | |||
9896 | Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); | |||
9897 | if (!ChildExpr) | |||
9898 | continue; | |||
9899 | ||||
9900 | if (IsLogicalAndOperator && | |||
9901 | isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) | |||
9902 | // Ignore checking string literals that are in logical and operators. | |||
9903 | // This is a common pattern for asserts. | |||
9904 | continue; | |||
9905 | AnalyzeImplicitConversions(S, ChildExpr, CC); | |||
9906 | } | |||
9907 | ||||
9908 | if (BO && BO->isLogicalOp()) { | |||
9909 | Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); | |||
9910 | if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) | |||
9911 | ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); | |||
9912 | ||||
9913 | SubExpr = BO->getRHS()->IgnoreParenImpCasts(); | |||
9914 | if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) | |||
9915 | ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); | |||
9916 | } | |||
9917 | ||||
9918 | if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) | |||
9919 | if (U->getOpcode() == UO_LNot) | |||
9920 | ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); | |||
9921 | } | |||
9922 | ||||
9923 | } // end anonymous namespace | |||
9924 | ||||
9925 | /// Diagnose integer type and any valid implicit convertion to it. | |||
9926 | static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { | |||
9927 | // Taking into account implicit conversions, | |||
9928 | // allow any integer. | |||
9929 | if (!E->getType()->isIntegerType()) { | |||
9930 | S.Diag(E->getLocStart(), | |||
9931 | diag::err_opencl_enqueue_kernel_invalid_local_size_type); | |||
9932 | return true; | |||
9933 | } | |||
9934 | // Potentially emit standard warnings for implicit conversions if enabled | |||
9935 | // using -Wconversion. | |||
9936 | CheckImplicitConversion(S, E, IntT, E->getLocStart()); | |||
9937 | return false; | |||
9938 | } | |||
9939 | ||||
9940 | // Helper function for Sema::DiagnoseAlwaysNonNullPointer. | |||
9941 | // Returns true when emitting a warning about taking the address of a reference. | |||
9942 | static bool CheckForReference(Sema &SemaRef, const Expr *E, | |||
9943 | const PartialDiagnostic &PD) { | |||
9944 | E = E->IgnoreParenImpCasts(); | |||
9945 | ||||
9946 | const FunctionDecl *FD = nullptr; | |||
9947 | ||||
9948 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
9949 | if (!DRE->getDecl()->getType()->isReferenceType()) | |||
9950 | return false; | |||
9951 | } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { | |||
9952 | if (!M->getMemberDecl()->getType()->isReferenceType()) | |||
9953 | return false; | |||
9954 | } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { | |||
9955 | if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) | |||
9956 | return false; | |||
9957 | FD = Call->getDirectCallee(); | |||
9958 | } else { | |||
9959 | return false; | |||
9960 | } | |||
9961 | ||||
9962 | SemaRef.Diag(E->getExprLoc(), PD); | |||
9963 | ||||
9964 | // If possible, point to location of function. | |||
9965 | if (FD) { | |||
9966 | SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; | |||
9967 | } | |||
9968 | ||||
9969 | return true; | |||
9970 | } | |||
9971 | ||||
9972 | // Returns true if the SourceLocation is expanded from any macro body. | |||
9973 | // Returns false if the SourceLocation is invalid, is from not in a macro | |||
9974 | // expansion, or is from expanded from a top-level macro argument. | |||
9975 | static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { | |||
9976 | if (Loc.isInvalid()) | |||
9977 | return false; | |||
9978 | ||||
9979 | while (Loc.isMacroID()) { | |||
9980 | if (SM.isMacroBodyExpansion(Loc)) | |||
9981 | return true; | |||
9982 | Loc = SM.getImmediateMacroCallerLoc(Loc); | |||
9983 | } | |||
9984 | ||||
9985 | return false; | |||
9986 | } | |||
9987 | ||||
9988 | /// \brief Diagnose pointers that are always non-null. | |||
9989 | /// \param E the expression containing the pointer | |||
9990 | /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is | |||
9991 | /// compared to a null pointer | |||
9992 | /// \param IsEqual True when the comparison is equal to a null pointer | |||
9993 | /// \param Range Extra SourceRange to highlight in the diagnostic | |||
9994 | void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, | |||
9995 | Expr::NullPointerConstantKind NullKind, | |||
9996 | bool IsEqual, SourceRange Range) { | |||
9997 | if (!E) | |||
9998 | return; | |||
9999 | ||||
10000 | // Don't warn inside macros. | |||
10001 | if (E->getExprLoc().isMacroID()) { | |||
10002 | const SourceManager &SM = getSourceManager(); | |||
10003 | if (IsInAnyMacroBody(SM, E->getExprLoc()) || | |||
10004 | IsInAnyMacroBody(SM, Range.getBegin())) | |||
10005 | return; | |||
10006 | } | |||
10007 | E = E->IgnoreImpCasts(); | |||
10008 | ||||
10009 | const bool IsCompare = NullKind != Expr::NPCK_NotNull; | |||
10010 | ||||
10011 | if (isa<CXXThisExpr>(E)) { | |||
10012 | unsigned DiagID = IsCompare ? diag::warn_this_null_compare | |||
10013 | : diag::warn_this_bool_conversion; | |||
10014 | Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; | |||
10015 | return; | |||
10016 | } | |||
10017 | ||||
10018 | bool IsAddressOf = false; | |||
10019 | ||||
10020 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
10021 | if (UO->getOpcode() != UO_AddrOf) | |||
10022 | return; | |||
10023 | IsAddressOf = true; | |||
10024 | E = UO->getSubExpr(); | |||
10025 | } | |||
10026 | ||||
10027 | if (IsAddressOf) { | |||
10028 | unsigned DiagID = IsCompare | |||
10029 | ? diag::warn_address_of_reference_null_compare | |||
10030 | : diag::warn_address_of_reference_bool_conversion; | |||
10031 | PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range | |||
10032 | << IsEqual; | |||
10033 | if (CheckForReference(*this, E, PD)) { | |||
10034 | return; | |||
10035 | } | |||
10036 | } | |||
10037 | ||||
10038 | auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { | |||
10039 | bool IsParam = isa<NonNullAttr>(NonnullAttr); | |||
10040 | std::string Str; | |||
10041 | llvm::raw_string_ostream S(Str); | |||
10042 | E->printPretty(S, nullptr, getPrintingPolicy()); | |||
10043 | unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare | |||
10044 | : diag::warn_cast_nonnull_to_bool; | |||
10045 | Diag(E->getExprLoc(), DiagID) << IsParam << S.str() | |||
10046 | << E->getSourceRange() << Range << IsEqual; | |||
10047 | Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; | |||
10048 | }; | |||
10049 | ||||
10050 | // If we have a CallExpr that is tagged with returns_nonnull, we can complain. | |||
10051 | if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { | |||
10052 | if (auto *Callee = Call->getDirectCallee()) { | |||
10053 | if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { | |||
10054 | ComplainAboutNonnullParamOrCall(A); | |||
10055 | return; | |||
10056 | } | |||
10057 | } | |||
10058 | } | |||
10059 | ||||
10060 | // Expect to find a single Decl. Skip anything more complicated. | |||
10061 | ValueDecl *D = nullptr; | |||
10062 | if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { | |||
10063 | D = R->getDecl(); | |||
10064 | } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { | |||
10065 | D = M->getMemberDecl(); | |||
10066 | } | |||
10067 | ||||
10068 | // Weak Decls can be null. | |||
10069 | if (!D || D->isWeak()) | |||
10070 | return; | |||
10071 | ||||
10072 | // Check for parameter decl with nonnull attribute | |||
10073 | if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { | |||
10074 | if (getCurFunction() && | |||
10075 | !getCurFunction()->ModifiedNonNullParams.count(PV)) { | |||
10076 | if (const Attr *A = PV->getAttr<NonNullAttr>()) { | |||
10077 | ComplainAboutNonnullParamOrCall(A); | |||
10078 | return; | |||
10079 | } | |||
10080 | ||||
10081 | if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { | |||
10082 | auto ParamIter = llvm::find(FD->parameters(), PV); | |||
10083 | assert(ParamIter != FD->param_end())((ParamIter != FD->param_end()) ? static_cast<void> ( 0) : __assert_fail ("ParamIter != FD->param_end()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 10083, __PRETTY_FUNCTION__)); | |||
10084 | unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); | |||
10085 | ||||
10086 | for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { | |||
10087 | if (!NonNull->args_size()) { | |||
10088 | ComplainAboutNonnullParamOrCall(NonNull); | |||
10089 | return; | |||
10090 | } | |||
10091 | ||||
10092 | for (unsigned ArgNo : NonNull->args()) { | |||
10093 | if (ArgNo == ParamNo) { | |||
10094 | ComplainAboutNonnullParamOrCall(NonNull); | |||
10095 | return; | |||
10096 | } | |||
10097 | } | |||
10098 | } | |||
10099 | } | |||
10100 | } | |||
10101 | } | |||
10102 | ||||
10103 | QualType T = D->getType(); | |||
10104 | const bool IsArray = T->isArrayType(); | |||
10105 | const bool IsFunction = T->isFunctionType(); | |||
10106 | ||||
10107 | // Address of function is used to silence the function warning. | |||
10108 | if (IsAddressOf && IsFunction) { | |||
10109 | return; | |||
10110 | } | |||
10111 | ||||
10112 | // Found nothing. | |||
10113 | if (!IsAddressOf && !IsFunction && !IsArray) | |||
10114 | return; | |||
10115 | ||||
10116 | // Pretty print the expression for the diagnostic. | |||
10117 | std::string Str; | |||
10118 | llvm::raw_string_ostream S(Str); | |||
10119 | E->printPretty(S, nullptr, getPrintingPolicy()); | |||
10120 | ||||
10121 | unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare | |||
10122 | : diag::warn_impcast_pointer_to_bool; | |||
10123 | enum { | |||
10124 | AddressOf, | |||
10125 | FunctionPointer, | |||
10126 | ArrayPointer | |||
10127 | } DiagType; | |||
10128 | if (IsAddressOf) | |||
10129 | DiagType = AddressOf; | |||
10130 | else if (IsFunction) | |||
10131 | DiagType = FunctionPointer; | |||
10132 | else if (IsArray) | |||
10133 | DiagType = ArrayPointer; | |||
10134 | else | |||
10135 | llvm_unreachable("Could not determine diagnostic.")::llvm::llvm_unreachable_internal("Could not determine diagnostic." , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 10135); | |||
10136 | Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() | |||
10137 | << Range << IsEqual; | |||
10138 | ||||
10139 | if (!IsFunction) | |||
10140 | return; | |||
10141 | ||||
10142 | // Suggest '&' to silence the function warning. | |||
10143 | Diag(E->getExprLoc(), diag::note_function_warning_silence) | |||
10144 | << FixItHint::CreateInsertion(E->getLocStart(), "&"); | |||
10145 | ||||
10146 | // Check to see if '()' fixit should be emitted. | |||
10147 | QualType ReturnType; | |||
10148 | UnresolvedSet<4> NonTemplateOverloads; | |||
10149 | tryExprAsCall(*E, ReturnType, NonTemplateOverloads); | |||
10150 | if (ReturnType.isNull()) | |||
10151 | return; | |||
10152 | ||||
10153 | if (IsCompare) { | |||
10154 | // There are two cases here. If there is null constant, the only suggest | |||
10155 | // for a pointer return type. If the null is 0, then suggest if the return | |||
10156 | // type is a pointer or an integer type. | |||
10157 | if (!ReturnType->isPointerType()) { | |||
10158 | if (NullKind == Expr::NPCK_ZeroExpression || | |||
10159 | NullKind == Expr::NPCK_ZeroLiteral) { | |||
10160 | if (!ReturnType->isIntegerType()) | |||
10161 | return; | |||
10162 | } else { | |||
10163 | return; | |||
10164 | } | |||
10165 | } | |||
10166 | } else { // !IsCompare | |||
10167 | // For function to bool, only suggest if the function pointer has bool | |||
10168 | // return type. | |||
10169 | if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) | |||
10170 | return; | |||
10171 | } | |||
10172 | Diag(E->getExprLoc(), diag::note_function_to_function_call) | |||
10173 | << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); | |||
10174 | } | |||
10175 | ||||
10176 | /// Diagnoses "dangerous" implicit conversions within the given | |||
10177 | /// expression (which is a full expression). Implements -Wconversion | |||
10178 | /// and -Wsign-compare. | |||
10179 | /// | |||
10180 | /// \param CC the "context" location of the implicit conversion, i.e. | |||
10181 | /// the most location of the syntactic entity requiring the implicit | |||
10182 | /// conversion | |||
10183 | void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { | |||
10184 | // Don't diagnose in unevaluated contexts. | |||
10185 | if (isUnevaluatedContext()) | |||
10186 | return; | |||
10187 | ||||
10188 | // Don't diagnose for value- or type-dependent expressions. | |||
10189 | if (E->isTypeDependent() || E->isValueDependent()) | |||
10190 | return; | |||
10191 | ||||
10192 | // Check for array bounds violations in cases where the check isn't triggered | |||
10193 | // elsewhere for other Expr types (like BinaryOperators), e.g. when an | |||
10194 | // ArraySubscriptExpr is on the RHS of a variable initialization. | |||
10195 | CheckArrayAccess(E); | |||
10196 | ||||
10197 | // This is not the right CC for (e.g.) a variable initialization. | |||
10198 | AnalyzeImplicitConversions(*this, E, CC); | |||
10199 | } | |||
10200 | ||||
10201 | /// CheckBoolLikeConversion - Check conversion of given expression to boolean. | |||
10202 | /// Input argument E is a logical expression. | |||
10203 | void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { | |||
10204 | ::CheckBoolLikeConversion(*this, E, CC); | |||
10205 | } | |||
10206 | ||||
10207 | /// Diagnose when expression is an integer constant expression and its evaluation | |||
10208 | /// results in integer overflow | |||
10209 | void Sema::CheckForIntOverflow (Expr *E) { | |||
10210 | // Use a work list to deal with nested struct initializers. | |||
10211 | SmallVector<Expr *, 2> Exprs(1, E); | |||
10212 | ||||
10213 | do { | |||
10214 | Expr *E = Exprs.pop_back_val(); | |||
10215 | ||||
10216 | if (isa<BinaryOperator>(E->IgnoreParenCasts())) { | |||
10217 | E->IgnoreParenCasts()->EvaluateForOverflow(Context); | |||
10218 | continue; | |||
10219 | } | |||
10220 | ||||
10221 | if (auto InitList = dyn_cast<InitListExpr>(E)) | |||
10222 | Exprs.append(InitList->inits().begin(), InitList->inits().end()); | |||
10223 | ||||
10224 | if (isa<ObjCBoxedExpr>(E)) | |||
10225 | E->IgnoreParenCasts()->EvaluateForOverflow(Context); | |||
10226 | } while (!Exprs.empty()); | |||
10227 | } | |||
10228 | ||||
10229 | namespace { | |||
10230 | /// \brief Visitor for expressions which looks for unsequenced operations on the | |||
10231 | /// same object. | |||
10232 | class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { | |||
10233 | typedef EvaluatedExprVisitor<SequenceChecker> Base; | |||
10234 | ||||
10235 | /// \brief A tree of sequenced regions within an expression. Two regions are | |||
10236 | /// unsequenced if one is an ancestor or a descendent of the other. When we | |||
10237 | /// finish processing an expression with sequencing, such as a comma | |||
10238 | /// expression, we fold its tree nodes into its parent, since they are | |||
10239 | /// unsequenced with respect to nodes we will visit later. | |||
10240 | class SequenceTree { | |||
10241 | struct Value { | |||
10242 | explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} | |||
10243 | unsigned Parent : 31; | |||
10244 | unsigned Merged : 1; | |||
10245 | }; | |||
10246 | SmallVector<Value, 8> Values; | |||
10247 | ||||
10248 | public: | |||
10249 | /// \brief A region within an expression which may be sequenced with respect | |||
10250 | /// to some other region. | |||
10251 | class Seq { | |||
10252 | explicit Seq(unsigned N) : Index(N) {} | |||
10253 | unsigned Index; | |||
10254 | friend class SequenceTree; | |||
10255 | public: | |||
10256 | Seq() : Index(0) {} | |||
10257 | }; | |||
10258 | ||||
10259 | SequenceTree() { Values.push_back(Value(0)); } | |||
10260 | Seq root() const { return Seq(0); } | |||
10261 | ||||
10262 | /// \brief Create a new sequence of operations, which is an unsequenced | |||
10263 | /// subset of \p Parent. This sequence of operations is sequenced with | |||
10264 | /// respect to other children of \p Parent. | |||
10265 | Seq allocate(Seq Parent) { | |||
10266 | Values.push_back(Value(Parent.Index)); | |||
10267 | return Seq(Values.size() - 1); | |||
10268 | } | |||
10269 | ||||
10270 | /// \brief Merge a sequence of operations into its parent. | |||
10271 | void merge(Seq S) { | |||
10272 | Values[S.Index].Merged = true; | |||
10273 | } | |||
10274 | ||||
10275 | /// \brief Determine whether two operations are unsequenced. This operation | |||
10276 | /// is asymmetric: \p Cur should be the more recent sequence, and \p Old | |||
10277 | /// should have been merged into its parent as appropriate. | |||
10278 | bool isUnsequenced(Seq Cur, Seq Old) { | |||
10279 | unsigned C = representative(Cur.Index); | |||
10280 | unsigned Target = representative(Old.Index); | |||
10281 | while (C >= Target) { | |||
10282 | if (C == Target) | |||
10283 | return true; | |||
10284 | C = Values[C].Parent; | |||
10285 | } | |||
10286 | return false; | |||
10287 | } | |||
10288 | ||||
10289 | private: | |||
10290 | /// \brief Pick a representative for a sequence. | |||
10291 | unsigned representative(unsigned K) { | |||
10292 | if (Values[K].Merged) | |||
10293 | // Perform path compression as we go. | |||
10294 | return Values[K].Parent = representative(Values[K].Parent); | |||
10295 | return K; | |||
10296 | } | |||
10297 | }; | |||
10298 | ||||
10299 | /// An object for which we can track unsequenced uses. | |||
10300 | typedef NamedDecl *Object; | |||
10301 | ||||
10302 | /// Different flavors of object usage which we track. We only track the | |||
10303 | /// least-sequenced usage of each kind. | |||
10304 | enum UsageKind { | |||
10305 | /// A read of an object. Multiple unsequenced reads are OK. | |||
10306 | UK_Use, | |||
10307 | /// A modification of an object which is sequenced before the value | |||
10308 | /// computation of the expression, such as ++n in C++. | |||
10309 | UK_ModAsValue, | |||
10310 | /// A modification of an object which is not sequenced before the value | |||
10311 | /// computation of the expression, such as n++. | |||
10312 | UK_ModAsSideEffect, | |||
10313 | ||||
10314 | UK_Count = UK_ModAsSideEffect + 1 | |||
10315 | }; | |||
10316 | ||||
10317 | struct Usage { | |||
10318 | Usage() : Use(nullptr), Seq() {} | |||
10319 | Expr *Use; | |||
10320 | SequenceTree::Seq Seq; | |||
10321 | }; | |||
10322 | ||||
10323 | struct UsageInfo { | |||
10324 | UsageInfo() : Diagnosed(false) {} | |||
10325 | Usage Uses[UK_Count]; | |||
10326 | /// Have we issued a diagnostic for this variable already? | |||
10327 | bool Diagnosed; | |||
10328 | }; | |||
10329 | typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; | |||
10330 | ||||
10331 | Sema &SemaRef; | |||
10332 | /// Sequenced regions within the expression. | |||
10333 | SequenceTree Tree; | |||
10334 | /// Declaration modifications and references which we have seen. | |||
10335 | UsageInfoMap UsageMap; | |||
10336 | /// The region we are currently within. | |||
10337 | SequenceTree::Seq Region; | |||
10338 | /// Filled in with declarations which were modified as a side-effect | |||
10339 | /// (that is, post-increment operations). | |||
10340 | SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; | |||
10341 | /// Expressions to check later. We defer checking these to reduce | |||
10342 | /// stack usage. | |||
10343 | SmallVectorImpl<Expr *> &WorkList; | |||
10344 | ||||
10345 | /// RAII object wrapping the visitation of a sequenced subexpression of an | |||
10346 | /// expression. At the end of this process, the side-effects of the evaluation | |||
10347 | /// become sequenced with respect to the value computation of the result, so | |||
10348 | /// we downgrade any UK_ModAsSideEffect within the evaluation to | |||
10349 | /// UK_ModAsValue. | |||
10350 | struct SequencedSubexpression { | |||
10351 | SequencedSubexpression(SequenceChecker &Self) | |||
10352 | : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { | |||
10353 | Self.ModAsSideEffect = &ModAsSideEffect; | |||
10354 | } | |||
10355 | ~SequencedSubexpression() { | |||
10356 | for (auto &M : llvm::reverse(ModAsSideEffect)) { | |||
10357 | UsageInfo &U = Self.UsageMap[M.first]; | |||
10358 | auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; | |||
10359 | Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); | |||
10360 | SideEffectUsage = M.second; | |||
10361 | } | |||
10362 | Self.ModAsSideEffect = OldModAsSideEffect; | |||
10363 | } | |||
10364 | ||||
10365 | SequenceChecker &Self; | |||
10366 | SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; | |||
10367 | SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; | |||
10368 | }; | |||
10369 | ||||
10370 | /// RAII object wrapping the visitation of a subexpression which we might | |||
10371 | /// choose to evaluate as a constant. If any subexpression is evaluated and | |||
10372 | /// found to be non-constant, this allows us to suppress the evaluation of | |||
10373 | /// the outer expression. | |||
10374 | class EvaluationTracker { | |||
10375 | public: | |||
10376 | EvaluationTracker(SequenceChecker &Self) | |||
10377 | : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { | |||
10378 | Self.EvalTracker = this; | |||
10379 | } | |||
10380 | ~EvaluationTracker() { | |||
10381 | Self.EvalTracker = Prev; | |||
10382 | if (Prev) | |||
10383 | Prev->EvalOK &= EvalOK; | |||
10384 | } | |||
10385 | ||||
10386 | bool evaluate(const Expr *E, bool &Result) { | |||
10387 | if (!EvalOK || E->isValueDependent()) | |||
10388 | return false; | |||
10389 | EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); | |||
10390 | return EvalOK; | |||
10391 | } | |||
10392 | ||||
10393 | private: | |||
10394 | SequenceChecker &Self; | |||
10395 | EvaluationTracker *Prev; | |||
10396 | bool EvalOK; | |||
10397 | } *EvalTracker; | |||
10398 | ||||
10399 | /// \brief Find the object which is produced by the specified expression, | |||
10400 | /// if any. | |||
10401 | Object getObject(Expr *E, bool Mod) const { | |||
10402 | E = E->IgnoreParenCasts(); | |||
10403 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
10404 | if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) | |||
10405 | return getObject(UO->getSubExpr(), Mod); | |||
10406 | } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
10407 | if (BO->getOpcode() == BO_Comma) | |||
10408 | return getObject(BO->getRHS(), Mod); | |||
10409 | if (Mod && BO->isAssignmentOp()) | |||
10410 | return getObject(BO->getLHS(), Mod); | |||
10411 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
10412 | // FIXME: Check for more interesting cases, like "x.n = ++x.n". | |||
10413 | if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) | |||
10414 | return ME->getMemberDecl(); | |||
10415 | } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | |||
10416 | // FIXME: If this is a reference, map through to its value. | |||
10417 | return DRE->getDecl(); | |||
10418 | return nullptr; | |||
10419 | } | |||
10420 | ||||
10421 | /// \brief Note that an object was modified or used by an expression. | |||
10422 | void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { | |||
10423 | Usage &U = UI.Uses[UK]; | |||
10424 | if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { | |||
10425 | if (UK == UK_ModAsSideEffect && ModAsSideEffect) | |||
10426 | ModAsSideEffect->push_back(std::make_pair(O, U)); | |||
10427 | U.Use = Ref; | |||
10428 | U.Seq = Region; | |||
10429 | } | |||
10430 | } | |||
10431 | /// \brief Check whether a modification or use conflicts with a prior usage. | |||
10432 | void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, | |||
10433 | bool IsModMod) { | |||
10434 | if (UI.Diagnosed) | |||
10435 | return; | |||
10436 | ||||
10437 | const Usage &U = UI.Uses[OtherKind]; | |||
10438 | if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) | |||
10439 | return; | |||
10440 | ||||
10441 | Expr *Mod = U.Use; | |||
10442 | Expr *ModOrUse = Ref; | |||
10443 | if (OtherKind == UK_Use) | |||
10444 | std::swap(Mod, ModOrUse); | |||
10445 | ||||
10446 | SemaRef.Diag(Mod->getExprLoc(), | |||
10447 | IsModMod ? diag::warn_unsequenced_mod_mod | |||
10448 | : diag::warn_unsequenced_mod_use) | |||
10449 | << O << SourceRange(ModOrUse->getExprLoc()); | |||
10450 | UI.Diagnosed = true; | |||
10451 | } | |||
10452 | ||||
10453 | void notePreUse(Object O, Expr *Use) { | |||
10454 | UsageInfo &U = UsageMap[O]; | |||
10455 | // Uses conflict with other modifications. | |||
10456 | checkUsage(O, U, Use, UK_ModAsValue, false); | |||
10457 | } | |||
10458 | void notePostUse(Object O, Expr *Use) { | |||
10459 | UsageInfo &U = UsageMap[O]; | |||
10460 | checkUsage(O, U, Use, UK_ModAsSideEffect, false); | |||
10461 | addUsage(U, O, Use, UK_Use); | |||
10462 | } | |||
10463 | ||||
10464 | void notePreMod(Object O, Expr *Mod) { | |||
10465 | UsageInfo &U = UsageMap[O]; | |||
10466 | // Modifications conflict with other modifications and with uses. | |||
10467 | checkUsage(O, U, Mod, UK_ModAsValue, true); | |||
10468 | checkUsage(O, U, Mod, UK_Use, false); | |||
10469 | } | |||
10470 | void notePostMod(Object O, Expr *Use, UsageKind UK) { | |||
10471 | UsageInfo &U = UsageMap[O]; | |||
10472 | checkUsage(O, U, Use, UK_ModAsSideEffect, true); | |||
10473 | addUsage(U, O, Use, UK); | |||
10474 | } | |||
10475 | ||||
10476 | public: | |||
10477 | SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) | |||
10478 | : Base(S.Context), SemaRef(S), Region(Tree.root()), | |||
10479 | ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { | |||
10480 | Visit(E); | |||
10481 | } | |||
10482 | ||||
10483 | void VisitStmt(Stmt *S) { | |||
10484 | // Skip all statements which aren't expressions for now. | |||
10485 | } | |||
10486 | ||||
10487 | void VisitExpr(Expr *E) { | |||
10488 | // By default, just recurse to evaluated subexpressions. | |||
10489 | Base::VisitStmt(E); | |||
10490 | } | |||
10491 | ||||
10492 | void VisitCastExpr(CastExpr *E) { | |||
10493 | Object O = Object(); | |||
10494 | if (E->getCastKind() == CK_LValueToRValue) | |||
10495 | O = getObject(E->getSubExpr(), false); | |||
10496 | ||||
10497 | if (O) | |||
10498 | notePreUse(O, E); | |||
10499 | VisitExpr(E); | |||
10500 | if (O) | |||
10501 | notePostUse(O, E); | |||
10502 | } | |||
10503 | ||||
10504 | void VisitBinComma(BinaryOperator *BO) { | |||
10505 | // C++11 [expr.comma]p1: | |||
10506 | // Every value computation and side effect associated with the left | |||
10507 | // expression is sequenced before every value computation and side | |||
10508 | // effect associated with the right expression. | |||
10509 | SequenceTree::Seq LHS = Tree.allocate(Region); | |||
10510 | SequenceTree::Seq RHS = Tree.allocate(Region); | |||
10511 | SequenceTree::Seq OldRegion = Region; | |||
10512 | ||||
10513 | { | |||
10514 | SequencedSubexpression SeqLHS(*this); | |||
10515 | Region = LHS; | |||
10516 | Visit(BO->getLHS()); | |||
10517 | } | |||
10518 | ||||
10519 | Region = RHS; | |||
10520 | Visit(BO->getRHS()); | |||
10521 | ||||
10522 | Region = OldRegion; | |||
10523 | ||||
10524 | // Forget that LHS and RHS are sequenced. They are both unsequenced | |||
10525 | // with respect to other stuff. | |||
10526 | Tree.merge(LHS); | |||
10527 | Tree.merge(RHS); | |||
10528 | } | |||
10529 | ||||
10530 | void VisitBinAssign(BinaryOperator *BO) { | |||
10531 | // The modification is sequenced after the value computation of the LHS | |||
10532 | // and RHS, so check it before inspecting the operands and update the | |||
10533 | // map afterwards. | |||
10534 | Object O = getObject(BO->getLHS(), true); | |||
10535 | if (!O) | |||
10536 | return VisitExpr(BO); | |||
10537 | ||||
10538 | notePreMod(O, BO); | |||
10539 | ||||
10540 | // C++11 [expr.ass]p7: | |||
10541 | // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated | |||
10542 | // only once. | |||
10543 | // | |||
10544 | // Therefore, for a compound assignment operator, O is considered used | |||
10545 | // everywhere except within the evaluation of E1 itself. | |||
10546 | if (isa<CompoundAssignOperator>(BO)) | |||
10547 | notePreUse(O, BO); | |||
10548 | ||||
10549 | Visit(BO->getLHS()); | |||
10550 | ||||
10551 | if (isa<CompoundAssignOperator>(BO)) | |||
10552 | notePostUse(O, BO); | |||
10553 | ||||
10554 | Visit(BO->getRHS()); | |||
10555 | ||||
10556 | // C++11 [expr.ass]p1: | |||
10557 | // the assignment is sequenced [...] before the value computation of the | |||
10558 | // assignment expression. | |||
10559 | // C11 6.5.16/3 has no such rule. | |||
10560 | notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue | |||
10561 | : UK_ModAsSideEffect); | |||
10562 | } | |||
10563 | ||||
10564 | void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { | |||
10565 | VisitBinAssign(CAO); | |||
10566 | } | |||
10567 | ||||
10568 | void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } | |||
10569 | void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } | |||
10570 | void VisitUnaryPreIncDec(UnaryOperator *UO) { | |||
10571 | Object O = getObject(UO->getSubExpr(), true); | |||
10572 | if (!O) | |||
10573 | return VisitExpr(UO); | |||
10574 | ||||
10575 | notePreMod(O, UO); | |||
10576 | Visit(UO->getSubExpr()); | |||
10577 | // C++11 [expr.pre.incr]p1: | |||
10578 | // the expression ++x is equivalent to x+=1 | |||
10579 | notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue | |||
10580 | : UK_ModAsSideEffect); | |||
10581 | } | |||
10582 | ||||
10583 | void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } | |||
10584 | void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } | |||
10585 | void VisitUnaryPostIncDec(UnaryOperator *UO) { | |||
10586 | Object O = getObject(UO->getSubExpr(), true); | |||
10587 | if (!O) | |||
10588 | return VisitExpr(UO); | |||
10589 | ||||
10590 | notePreMod(O, UO); | |||
10591 | Visit(UO->getSubExpr()); | |||
10592 | notePostMod(O, UO, UK_ModAsSideEffect); | |||
10593 | } | |||
10594 | ||||
10595 | /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. | |||
10596 | void VisitBinLOr(BinaryOperator *BO) { | |||
10597 | // The side-effects of the LHS of an '&&' are sequenced before the | |||
10598 | // value computation of the RHS, and hence before the value computation | |||
10599 | // of the '&&' itself, unless the LHS evaluates to zero. We treat them | |||
10600 | // as if they were unconditionally sequenced. | |||
10601 | EvaluationTracker Eval(*this); | |||
10602 | { | |||
10603 | SequencedSubexpression Sequenced(*this); | |||
10604 | Visit(BO->getLHS()); | |||
10605 | } | |||
10606 | ||||
10607 | bool Result; | |||
10608 | if (Eval.evaluate(BO->getLHS(), Result)) { | |||
10609 | if (!Result) | |||
10610 | Visit(BO->getRHS()); | |||
10611 | } else { | |||
10612 | // Check for unsequenced operations in the RHS, treating it as an | |||
10613 | // entirely separate evaluation. | |||
10614 | // | |||
10615 | // FIXME: If there are operations in the RHS which are unsequenced | |||
10616 | // with respect to operations outside the RHS, and those operations | |||
10617 | // are unconditionally evaluated, diagnose them. | |||
10618 | WorkList.push_back(BO->getRHS()); | |||
10619 | } | |||
10620 | } | |||
10621 | void VisitBinLAnd(BinaryOperator *BO) { | |||
10622 | EvaluationTracker Eval(*this); | |||
10623 | { | |||
10624 | SequencedSubexpression Sequenced(*this); | |||
10625 | Visit(BO->getLHS()); | |||
10626 | } | |||
10627 | ||||
10628 | bool Result; | |||
10629 | if (Eval.evaluate(BO->getLHS(), Result)) { | |||
10630 | if (Result) | |||
10631 | Visit(BO->getRHS()); | |||
10632 | } else { | |||
10633 | WorkList.push_back(BO->getRHS()); | |||
10634 | } | |||
10635 | } | |||
10636 | ||||
10637 | // Only visit the condition, unless we can be sure which subexpression will | |||
10638 | // be chosen. | |||
10639 | void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { | |||
10640 | EvaluationTracker Eval(*this); | |||
10641 | { | |||
10642 | SequencedSubexpression Sequenced(*this); | |||
10643 | Visit(CO->getCond()); | |||
10644 | } | |||
10645 | ||||
10646 | bool Result; | |||
10647 | if (Eval.evaluate(CO->getCond(), Result)) | |||
10648 | Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); | |||
10649 | else { | |||
10650 | WorkList.push_back(CO->getTrueExpr()); | |||
10651 | WorkList.push_back(CO->getFalseExpr()); | |||
10652 | } | |||
10653 | } | |||
10654 | ||||
10655 | void VisitCallExpr(CallExpr *CE) { | |||
10656 | // C++11 [intro.execution]p15: | |||
10657 | // When calling a function [...], every value computation and side effect | |||
10658 | // associated with any argument expression, or with the postfix expression | |||
10659 | // designating the called function, is sequenced before execution of every | |||
10660 | // expression or statement in the body of the function [and thus before | |||
10661 | // the value computation of its result]. | |||
10662 | SequencedSubexpression Sequenced(*this); | |||
10663 | Base::VisitCallExpr(CE); | |||
10664 | ||||
10665 | // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. | |||
10666 | } | |||
10667 | ||||
10668 | void VisitCXXConstructExpr(CXXConstructExpr *CCE) { | |||
10669 | // This is a call, so all subexpressions are sequenced before the result. | |||
10670 | SequencedSubexpression Sequenced(*this); | |||
10671 | ||||
10672 | if (!CCE->isListInitialization()) | |||
10673 | return VisitExpr(CCE); | |||
10674 | ||||
10675 | // In C++11, list initializations are sequenced. | |||
10676 | SmallVector<SequenceTree::Seq, 32> Elts; | |||
10677 | SequenceTree::Seq Parent = Region; | |||
10678 | for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), | |||
10679 | E = CCE->arg_end(); | |||
10680 | I != E; ++I) { | |||
10681 | Region = Tree.allocate(Parent); | |||
10682 | Elts.push_back(Region); | |||
10683 | Visit(*I); | |||
10684 | } | |||
10685 | ||||
10686 | // Forget that the initializers are sequenced. | |||
10687 | Region = Parent; | |||
10688 | for (unsigned I = 0; I < Elts.size(); ++I) | |||
10689 | Tree.merge(Elts[I]); | |||
10690 | } | |||
10691 | ||||
10692 | void VisitInitListExpr(InitListExpr *ILE) { | |||
10693 | if (!SemaRef.getLangOpts().CPlusPlus11) | |||
10694 | return VisitExpr(ILE); | |||
10695 | ||||
10696 | // In C++11, list initializations are sequenced. | |||
10697 | SmallVector<SequenceTree::Seq, 32> Elts; | |||
10698 | SequenceTree::Seq Parent = Region; | |||
10699 | for (unsigned I = 0; I < ILE->getNumInits(); ++I) { | |||
10700 | Expr *E = ILE->getInit(I); | |||
10701 | if (!E) continue; | |||
10702 | Region = Tree.allocate(Parent); | |||
10703 | Elts.push_back(Region); | |||
10704 | Visit(E); | |||
10705 | } | |||
10706 | ||||
10707 | // Forget that the initializers are sequenced. | |||
10708 | Region = Parent; | |||
10709 | for (unsigned I = 0; I < Elts.size(); ++I) | |||
10710 | Tree.merge(Elts[I]); | |||
10711 | } | |||
10712 | }; | |||
10713 | } // end anonymous namespace | |||
10714 | ||||
10715 | void Sema::CheckUnsequencedOperations(Expr *E) { | |||
10716 | SmallVector<Expr *, 8> WorkList; | |||
10717 | WorkList.push_back(E); | |||
10718 | while (!WorkList.empty()) { | |||
10719 | Expr *Item = WorkList.pop_back_val(); | |||
10720 | SequenceChecker(*this, Item, WorkList); | |||
10721 | } | |||
10722 | } | |||
10723 | ||||
10724 | void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, | |||
10725 | bool IsConstexpr) { | |||
10726 | CheckImplicitConversions(E, CheckLoc); | |||
10727 | if (!E->isInstantiationDependent()) | |||
10728 | CheckUnsequencedOperations(E); | |||
10729 | if (!IsConstexpr && !E->isValueDependent()) | |||
10730 | CheckForIntOverflow(E); | |||
10731 | DiagnoseMisalignedMembers(); | |||
10732 | } | |||
10733 | ||||
10734 | void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, | |||
10735 | FieldDecl *BitField, | |||
10736 | Expr *Init) { | |||
10737 | (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); | |||
10738 | } | |||
10739 | ||||
10740 | static void diagnoseArrayStarInParamType(Sema &S, QualType PType, | |||
10741 | SourceLocation Loc) { | |||
10742 | if (!PType->isVariablyModifiedType()) | |||
10743 | return; | |||
10744 | if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { | |||
10745 | diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); | |||
10746 | return; | |||
10747 | } | |||
10748 | if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { | |||
10749 | diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); | |||
10750 | return; | |||
10751 | } | |||
10752 | if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { | |||
10753 | diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); | |||
10754 | return; | |||
10755 | } | |||
10756 | ||||
10757 | const ArrayType *AT = S.Context.getAsArrayType(PType); | |||
10758 | if (!AT) | |||
10759 | return; | |||
10760 | ||||
10761 | if (AT->getSizeModifier() != ArrayType::Star) { | |||
10762 | diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); | |||
10763 | return; | |||
10764 | } | |||
10765 | ||||
10766 | S.Diag(Loc, diag::err_array_star_in_function_definition); | |||
10767 | } | |||
10768 | ||||
10769 | /// CheckParmsForFunctionDef - Check that the parameters of the given | |||
10770 | /// function are appropriate for the definition of a function. This | |||
10771 | /// takes care of any checks that cannot be performed on the | |||
10772 | /// declaration itself, e.g., that the types of each of the function | |||
10773 | /// parameters are complete. | |||
10774 | bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, | |||
10775 | bool CheckParameterNames) { | |||
10776 | bool HasInvalidParm = false; | |||
10777 | for (ParmVarDecl *Param : Parameters) { | |||
10778 | // C99 6.7.5.3p4: the parameters in a parameter type list in a | |||
10779 | // function declarator that is part of a function definition of | |||
10780 | // that function shall not have incomplete type. | |||
10781 | // | |||
10782 | // This is also C++ [dcl.fct]p6. | |||
10783 | if (!Param->isInvalidDecl() && | |||
10784 | RequireCompleteType(Param->getLocation(), Param->getType(), | |||
10785 | diag::err_typecheck_decl_incomplete_type)) { | |||
10786 | Param->setInvalidDecl(); | |||
10787 | HasInvalidParm = true; | |||
10788 | } | |||
10789 | ||||
10790 | // C99 6.9.1p5: If the declarator includes a parameter type list, the | |||
10791 | // declaration of each parameter shall include an identifier. | |||
10792 | if (CheckParameterNames && | |||
10793 | Param->getIdentifier() == nullptr && | |||
10794 | !Param->isImplicit() && | |||
10795 | !getLangOpts().CPlusPlus) | |||
10796 | Diag(Param->getLocation(), diag::err_parameter_name_omitted); | |||
10797 | ||||
10798 | // C99 6.7.5.3p12: | |||
10799 | // If the function declarator is not part of a definition of that | |||
10800 | // function, parameters may have incomplete type and may use the [*] | |||
10801 | // notation in their sequences of declarator specifiers to specify | |||
10802 | // variable length array types. | |||
10803 | QualType PType = Param->getOriginalType(); | |||
10804 | // FIXME: This diagnostic should point the '[*]' if source-location | |||
10805 | // information is added for it. | |||
10806 | diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); | |||
10807 | ||||
10808 | // MSVC destroys objects passed by value in the callee. Therefore a | |||
10809 | // function definition which takes such a parameter must be able to call the | |||
10810 | // object's destructor. However, we don't perform any direct access check | |||
10811 | // on the dtor. | |||
10812 | if (getLangOpts().CPlusPlus && Context.getTargetInfo() | |||
10813 | .getCXXABI() | |||
10814 | .areArgsDestroyedLeftToRightInCallee()) { | |||
10815 | if (!Param->isInvalidDecl()) { | |||
10816 | if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { | |||
10817 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
10818 | if (!ClassDecl->isInvalidDecl() && | |||
10819 | !ClassDecl->hasIrrelevantDestructor() && | |||
10820 | !ClassDecl->isDependentContext()) { | |||
10821 | CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); | |||
10822 | MarkFunctionReferenced(Param->getLocation(), Destructor); | |||
10823 | DiagnoseUseOfDecl(Destructor, Param->getLocation()); | |||
10824 | } | |||
10825 | } | |||
10826 | } | |||
10827 | } | |||
10828 | ||||
10829 | // Parameters with the pass_object_size attribute only need to be marked | |||
10830 | // constant at function definitions. Because we lack information about | |||
10831 | // whether we're on a declaration or definition when we're instantiating the | |||
10832 | // attribute, we need to check for constness here. | |||
10833 | if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) | |||
10834 | if (!Param->getType().isConstQualified()) | |||
10835 | Diag(Param->getLocation(), diag::err_attribute_pointers_only) | |||
10836 | << Attr->getSpelling() << 1; | |||
10837 | } | |||
10838 | ||||
10839 | return HasInvalidParm; | |||
10840 | } | |||
10841 | ||||
10842 | /// A helper function to get the alignment of a Decl referred to by DeclRefExpr | |||
10843 | /// or MemberExpr. | |||
10844 | static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, | |||
10845 | ASTContext &Context) { | |||
10846 | if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) | |||
10847 | return Context.getDeclAlign(DRE->getDecl()); | |||
10848 | ||||
10849 | if (const auto *ME = dyn_cast<MemberExpr>(E)) | |||
10850 | return Context.getDeclAlign(ME->getMemberDecl()); | |||
10851 | ||||
10852 | return TypeAlign; | |||
10853 | } | |||
10854 | ||||
10855 | /// CheckCastAlign - Implements -Wcast-align, which warns when a | |||
10856 | /// pointer cast increases the alignment requirements. | |||
10857 | void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { | |||
10858 | // This is actually a lot of work to potentially be doing on every | |||
10859 | // cast; don't do it if we're ignoring -Wcast_align (as is the default). | |||
10860 | if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) | |||
10861 | return; | |||
10862 | ||||
10863 | // Ignore dependent types. | |||
10864 | if (T->isDependentType() || Op->getType()->isDependentType()) | |||
10865 | return; | |||
10866 | ||||
10867 | // Require that the destination be a pointer type. | |||
10868 | const PointerType *DestPtr = T->getAs<PointerType>(); | |||
10869 | if (!DestPtr) return; | |||
10870 | ||||
10871 | // If the destination has alignment 1, we're done. | |||
10872 | QualType DestPointee = DestPtr->getPointeeType(); | |||
10873 | if (DestPointee->isIncompleteType()) return; | |||
10874 | CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); | |||
10875 | if (DestAlign.isOne()) return; | |||
10876 | ||||
10877 | // Require that the source be a pointer type. | |||
10878 | const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); | |||
10879 | if (!SrcPtr) return; | |||
10880 | QualType SrcPointee = SrcPtr->getPointeeType(); | |||
10881 | ||||
10882 | // Whitelist casts from cv void*. We already implicitly | |||
10883 | // whitelisted casts to cv void*, since they have alignment 1. | |||
10884 | // Also whitelist casts involving incomplete types, which implicitly | |||
10885 | // includes 'void'. | |||
10886 | if (SrcPointee->isIncompleteType()) return; | |||
10887 | ||||
10888 | CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); | |||
10889 | ||||
10890 | if (auto *CE = dyn_cast<CastExpr>(Op)) { | |||
10891 | if (CE->getCastKind() == CK_ArrayToPointerDecay) | |||
10892 | SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); | |||
10893 | } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { | |||
10894 | if (UO->getOpcode() == UO_AddrOf) | |||
10895 | SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); | |||
10896 | } | |||
10897 | ||||
10898 | if (SrcAlign >= DestAlign) return; | |||
10899 | ||||
10900 | Diag(TRange.getBegin(), diag::warn_cast_align) | |||
10901 | << Op->getType() << T | |||
10902 | << static_cast<unsigned>(SrcAlign.getQuantity()) | |||
10903 | << static_cast<unsigned>(DestAlign.getQuantity()) | |||
10904 | << TRange << Op->getSourceRange(); | |||
10905 | } | |||
10906 | ||||
10907 | /// \brief Check whether this array fits the idiom of a size-one tail padded | |||
10908 | /// array member of a struct. | |||
10909 | /// | |||
10910 | /// We avoid emitting out-of-bounds access warnings for such arrays as they are | |||
10911 | /// commonly used to emulate flexible arrays in C89 code. | |||
10912 | static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, | |||
10913 | const NamedDecl *ND) { | |||
10914 | if (Size != 1 || !ND) return false; | |||
10915 | ||||
10916 | const FieldDecl *FD = dyn_cast<FieldDecl>(ND); | |||
10917 | if (!FD) return false; | |||
10918 | ||||
10919 | // Don't consider sizes resulting from macro expansions or template argument | |||
10920 | // substitution to form C89 tail-padded arrays. | |||
10921 | ||||
10922 | TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); | |||
10923 | while (TInfo) { | |||
10924 | TypeLoc TL = TInfo->getTypeLoc(); | |||
10925 | // Look through typedefs. | |||
10926 | if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { | |||
10927 | const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); | |||
10928 | TInfo = TDL->getTypeSourceInfo(); | |||
10929 | continue; | |||
10930 | } | |||
10931 | if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { | |||
10932 | const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); | |||
10933 | if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) | |||
10934 | return false; | |||
10935 | } | |||
10936 | break; | |||
10937 | } | |||
10938 | ||||
10939 | const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); | |||
10940 | if (!RD) return false; | |||
10941 | if (RD->isUnion()) return false; | |||
10942 | if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | |||
10943 | if (!CRD->isStandardLayout()) return false; | |||
10944 | } | |||
10945 | ||||
10946 | // See if this is the last field decl in the record. | |||
10947 | const Decl *D = FD; | |||
10948 | while ((D = D->getNextDeclInContext())) | |||
10949 | if (isa<FieldDecl>(D)) | |||
10950 | return false; | |||
10951 | return true; | |||
10952 | } | |||
10953 | ||||
10954 | void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, | |||
10955 | const ArraySubscriptExpr *ASE, | |||
10956 | bool AllowOnePastEnd, bool IndexNegated) { | |||
10957 | IndexExpr = IndexExpr->IgnoreParenImpCasts(); | |||
10958 | if (IndexExpr->isValueDependent()) | |||
10959 | return; | |||
10960 | ||||
10961 | const Type *EffectiveType = | |||
10962 | BaseExpr->getType()->getPointeeOrArrayElementType(); | |||
10963 | BaseExpr = BaseExpr->IgnoreParenCasts(); | |||
10964 | const ConstantArrayType *ArrayTy = | |||
10965 | Context.getAsConstantArrayType(BaseExpr->getType()); | |||
10966 | if (!ArrayTy) | |||
10967 | return; | |||
10968 | ||||
10969 | llvm::APSInt index; | |||
10970 | if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) | |||
10971 | return; | |||
10972 | if (IndexNegated) | |||
10973 | index = -index; | |||
10974 | ||||
10975 | const NamedDecl *ND = nullptr; | |||
10976 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) | |||
10977 | ND = dyn_cast<NamedDecl>(DRE->getDecl()); | |||
10978 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) | |||
10979 | ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); | |||
10980 | ||||
10981 | if (index.isUnsigned() || !index.isNegative()) { | |||
10982 | llvm::APInt size = ArrayTy->getSize(); | |||
10983 | if (!size.isStrictlyPositive()) | |||
10984 | return; | |||
10985 | ||||
10986 | const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); | |||
10987 | if (BaseType != EffectiveType) { | |||
10988 | // Make sure we're comparing apples to apples when comparing index to size | |||
10989 | uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); | |||
10990 | uint64_t array_typesize = Context.getTypeSize(BaseType); | |||
10991 | // Handle ptrarith_typesize being zero, such as when casting to void* | |||
10992 | if (!ptrarith_typesize) ptrarith_typesize = 1; | |||
10993 | if (ptrarith_typesize != array_typesize) { | |||
10994 | // There's a cast to a different size type involved | |||
10995 | uint64_t ratio = array_typesize / ptrarith_typesize; | |||
10996 | // TODO: Be smarter about handling cases where array_typesize is not a | |||
10997 | // multiple of ptrarith_typesize | |||
10998 | if (ptrarith_typesize * ratio == array_typesize) | |||
10999 | size *= llvm::APInt(size.getBitWidth(), ratio); | |||
11000 | } | |||
11001 | } | |||
11002 | ||||
11003 | if (size.getBitWidth() > index.getBitWidth()) | |||
11004 | index = index.zext(size.getBitWidth()); | |||
11005 | else if (size.getBitWidth() < index.getBitWidth()) | |||
11006 | size = size.zext(index.getBitWidth()); | |||
11007 | ||||
11008 | // For array subscripting the index must be less than size, but for pointer | |||
11009 | // arithmetic also allow the index (offset) to be equal to size since | |||
11010 | // computing the next address after the end of the array is legal and | |||
11011 | // commonly done e.g. in C++ iterators and range-based for loops. | |||
11012 | if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) | |||
11013 | return; | |||
11014 | ||||
11015 | // Also don't warn for arrays of size 1 which are members of some | |||
11016 | // structure. These are often used to approximate flexible arrays in C89 | |||
11017 | // code. | |||
11018 | if (IsTailPaddedMemberArray(*this, size, ND)) | |||
11019 | return; | |||
11020 | ||||
11021 | // Suppress the warning if the subscript expression (as identified by the | |||
11022 | // ']' location) and the index expression are both from macro expansions | |||
11023 | // within a system header. | |||
11024 | if (ASE) { | |||
11025 | SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( | |||
11026 | ASE->getRBracketLoc()); | |||
11027 | if (SourceMgr.isInSystemHeader(RBracketLoc)) { | |||
11028 | SourceLocation IndexLoc = SourceMgr.getSpellingLoc( | |||
11029 | IndexExpr->getLocStart()); | |||
11030 | if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) | |||
11031 | return; | |||
11032 | } | |||
11033 | } | |||
11034 | ||||
11035 | unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; | |||
11036 | if (ASE) | |||
11037 | DiagID = diag::warn_array_index_exceeds_bounds; | |||
11038 | ||||
11039 | DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, | |||
11040 | PDiag(DiagID) << index.toString(10, true) | |||
11041 | << size.toString(10, true) | |||
11042 | << (unsigned)size.getLimitedValue(~0U) | |||
11043 | << IndexExpr->getSourceRange()); | |||
11044 | } else { | |||
11045 | unsigned DiagID = diag::warn_array_index_precedes_bounds; | |||
11046 | if (!ASE) { | |||
11047 | DiagID = diag::warn_ptr_arith_precedes_bounds; | |||
11048 | if (index.isNegative()) index = -index; | |||
11049 | } | |||
11050 | ||||
11051 | DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, | |||
11052 | PDiag(DiagID) << index.toString(10, true) | |||
11053 | << IndexExpr->getSourceRange()); | |||
11054 | } | |||
11055 | ||||
11056 | if (!ND) { | |||
11057 | // Try harder to find a NamedDecl to point at in the note. | |||
11058 | while (const ArraySubscriptExpr *ASE = | |||
11059 | dyn_cast<ArraySubscriptExpr>(BaseExpr)) | |||
11060 | BaseExpr = ASE->getBase()->IgnoreParenCasts(); | |||
11061 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) | |||
11062 | ND = dyn_cast<NamedDecl>(DRE->getDecl()); | |||
11063 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) | |||
11064 | ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); | |||
11065 | } | |||
11066 | ||||
11067 | if (ND) | |||
11068 | DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, | |||
11069 | PDiag(diag::note_array_index_out_of_bounds) | |||
11070 | << ND->getDeclName()); | |||
11071 | } | |||
11072 | ||||
11073 | void Sema::CheckArrayAccess(const Expr *expr) { | |||
11074 | int AllowOnePastEnd = 0; | |||
11075 | while (expr) { | |||
11076 | expr = expr->IgnoreParenImpCasts(); | |||
11077 | switch (expr->getStmtClass()) { | |||
11078 | case Stmt::ArraySubscriptExprClass: { | |||
11079 | const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); | |||
11080 | CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, | |||
11081 | AllowOnePastEnd > 0); | |||
11082 | return; | |||
11083 | } | |||
11084 | case Stmt::OMPArraySectionExprClass: { | |||
11085 | const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); | |||
11086 | if (ASE->getLowerBound()) | |||
11087 | CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), | |||
11088 | /*ASE=*/nullptr, AllowOnePastEnd > 0); | |||
11089 | return; | |||
11090 | } | |||
11091 | case Stmt::UnaryOperatorClass: { | |||
11092 | // Only unwrap the * and & unary operators | |||
11093 | const UnaryOperator *UO = cast<UnaryOperator>(expr); | |||
11094 | expr = UO->getSubExpr(); | |||
11095 | switch (UO->getOpcode()) { | |||
11096 | case UO_AddrOf: | |||
11097 | AllowOnePastEnd++; | |||
11098 | break; | |||
11099 | case UO_Deref: | |||
11100 | AllowOnePastEnd--; | |||
11101 | break; | |||
11102 | default: | |||
11103 | return; | |||
11104 | } | |||
11105 | break; | |||
11106 | } | |||
11107 | case Stmt::ConditionalOperatorClass: { | |||
11108 | const ConditionalOperator *cond = cast<ConditionalOperator>(expr); | |||
11109 | if (const Expr *lhs = cond->getLHS()) | |||
11110 | CheckArrayAccess(lhs); | |||
11111 | if (const Expr *rhs = cond->getRHS()) | |||
11112 | CheckArrayAccess(rhs); | |||
11113 | return; | |||
11114 | } | |||
11115 | case Stmt::CXXOperatorCallExprClass: { | |||
11116 | const auto *OCE = cast<CXXOperatorCallExpr>(expr); | |||
11117 | for (const auto *Arg : OCE->arguments()) | |||
11118 | CheckArrayAccess(Arg); | |||
11119 | return; | |||
11120 | } | |||
11121 | default: | |||
11122 | return; | |||
11123 | } | |||
11124 | } | |||
11125 | } | |||
11126 | ||||
11127 | //===--- CHECK: Objective-C retain cycles ----------------------------------// | |||
11128 | ||||
11129 | namespace { | |||
11130 | struct RetainCycleOwner { | |||
11131 | RetainCycleOwner() : Variable(nullptr), Indirect(false) {} | |||
11132 | VarDecl *Variable; | |||
11133 | SourceRange Range; | |||
11134 | SourceLocation Loc; | |||
11135 | bool Indirect; | |||
11136 | ||||
11137 | void setLocsFrom(Expr *e) { | |||
11138 | Loc = e->getExprLoc(); | |||
11139 | Range = e->getSourceRange(); | |||
11140 | } | |||
11141 | }; | |||
11142 | } // end anonymous namespace | |||
11143 | ||||
11144 | /// Consider whether capturing the given variable can possibly lead to | |||
11145 | /// a retain cycle. | |||
11146 | static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { | |||
11147 | // In ARC, it's captured strongly iff the variable has __strong | |||
11148 | // lifetime. In MRR, it's captured strongly if the variable is | |||
11149 | // __block and has an appropriate type. | |||
11150 | if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) | |||
11151 | return false; | |||
11152 | ||||
11153 | owner.Variable = var; | |||
11154 | if (ref) | |||
11155 | owner.setLocsFrom(ref); | |||
11156 | return true; | |||
11157 | } | |||
11158 | ||||
11159 | static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { | |||
11160 | while (true) { | |||
11161 | e = e->IgnoreParens(); | |||
11162 | if (CastExpr *cast = dyn_cast<CastExpr>(e)) { | |||
11163 | switch (cast->getCastKind()) { | |||
11164 | case CK_BitCast: | |||
11165 | case CK_LValueBitCast: | |||
11166 | case CK_LValueToRValue: | |||
11167 | case CK_ARCReclaimReturnedObject: | |||
11168 | e = cast->getSubExpr(); | |||
11169 | continue; | |||
11170 | ||||
11171 | default: | |||
11172 | return false; | |||
11173 | } | |||
11174 | } | |||
11175 | ||||
11176 | if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { | |||
11177 | ObjCIvarDecl *ivar = ref->getDecl(); | |||
11178 | if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) | |||
11179 | return false; | |||
11180 | ||||
11181 | // Try to find a retain cycle in the base. | |||
11182 | if (!findRetainCycleOwner(S, ref->getBase(), owner)) | |||
11183 | return false; | |||
11184 | ||||
11185 | if (ref->isFreeIvar()) owner.setLocsFrom(ref); | |||
11186 | owner.Indirect = true; | |||
11187 | return true; | |||
11188 | } | |||
11189 | ||||
11190 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { | |||
11191 | VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); | |||
11192 | if (!var) return false; | |||
11193 | return considerVariable(var, ref, owner); | |||
11194 | } | |||
11195 | ||||
11196 | if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { | |||
11197 | if (member->isArrow()) return false; | |||
11198 | ||||
11199 | // Don't count this as an indirect ownership. | |||
11200 | e = member->getBase(); | |||
11201 | continue; | |||
11202 | } | |||
11203 | ||||
11204 | if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { | |||
11205 | // Only pay attention to pseudo-objects on property references. | |||
11206 | ObjCPropertyRefExpr *pre | |||
11207 | = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() | |||
11208 | ->IgnoreParens()); | |||
11209 | if (!pre) return false; | |||
11210 | if (pre->isImplicitProperty()) return false; | |||
11211 | ObjCPropertyDecl *property = pre->getExplicitProperty(); | |||
11212 | if (!property->isRetaining() && | |||
11213 | !(property->getPropertyIvarDecl() && | |||
11214 | property->getPropertyIvarDecl()->getType() | |||
11215 | .getObjCLifetime() == Qualifiers::OCL_Strong)) | |||
11216 | return false; | |||
11217 | ||||
11218 | owner.Indirect = true; | |||
11219 | if (pre->isSuperReceiver()) { | |||
11220 | owner.Variable = S.getCurMethodDecl()->getSelfDecl(); | |||
11221 | if (!owner.Variable) | |||
11222 | return false; | |||
11223 | owner.Loc = pre->getLocation(); | |||
11224 | owner.Range = pre->getSourceRange(); | |||
11225 | return true; | |||
11226 | } | |||
11227 | e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) | |||
11228 | ->getSourceExpr()); | |||
11229 | continue; | |||
11230 | } | |||
11231 | ||||
11232 | // Array ivars? | |||
11233 | ||||
11234 | return false; | |||
11235 | } | |||
11236 | } | |||
11237 | ||||
11238 | namespace { | |||
11239 | struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { | |||
11240 | FindCaptureVisitor(ASTContext &Context, VarDecl *variable) | |||
11241 | : EvaluatedExprVisitor<FindCaptureVisitor>(Context), | |||
11242 | Context(Context), Variable(variable), Capturer(nullptr), | |||
11243 | VarWillBeReased(false) {} | |||
11244 | ASTContext &Context; | |||
11245 | VarDecl *Variable; | |||
11246 | Expr *Capturer; | |||
11247 | bool VarWillBeReased; | |||
11248 | ||||
11249 | void VisitDeclRefExpr(DeclRefExpr *ref) { | |||
11250 | if (ref->getDecl() == Variable && !Capturer) | |||
11251 | Capturer = ref; | |||
11252 | } | |||
11253 | ||||
11254 | void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { | |||
11255 | if (Capturer) return; | |||
11256 | Visit(ref->getBase()); | |||
11257 | if (Capturer && ref->isFreeIvar()) | |||
11258 | Capturer = ref; | |||
11259 | } | |||
11260 | ||||
11261 | void VisitBlockExpr(BlockExpr *block) { | |||
11262 | // Look inside nested blocks | |||
11263 | if (block->getBlockDecl()->capturesVariable(Variable)) | |||
11264 | Visit(block->getBlockDecl()->getBody()); | |||
11265 | } | |||
11266 | ||||
11267 | void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { | |||
11268 | if (Capturer) return; | |||
11269 | if (OVE->getSourceExpr()) | |||
11270 | Visit(OVE->getSourceExpr()); | |||
11271 | } | |||
11272 | void VisitBinaryOperator(BinaryOperator *BinOp) { | |||
11273 | if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) | |||
11274 | return; | |||
11275 | Expr *LHS = BinOp->getLHS(); | |||
11276 | if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { | |||
11277 | if (DRE->getDecl() != Variable) | |||
11278 | return; | |||
11279 | if (Expr *RHS = BinOp->getRHS()) { | |||
11280 | RHS = RHS->IgnoreParenCasts(); | |||
11281 | llvm::APSInt Value; | |||
11282 | VarWillBeReased = | |||
11283 | (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); | |||
11284 | } | |||
11285 | } | |||
11286 | } | |||
11287 | }; | |||
11288 | } // end anonymous namespace | |||
11289 | ||||
11290 | /// Check whether the given argument is a block which captures a | |||
11291 | /// variable. | |||
11292 | static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { | |||
11293 | assert(owner.Variable && owner.Loc.isValid())((owner.Variable && owner.Loc.isValid()) ? static_cast <void> (0) : __assert_fail ("owner.Variable && owner.Loc.isValid()" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 11293, __PRETTY_FUNCTION__)); | |||
11294 | ||||
11295 | e = e->IgnoreParenCasts(); | |||
11296 | ||||
11297 | // Look through [^{...} copy] and Block_copy(^{...}). | |||
11298 | if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { | |||
11299 | Selector Cmd = ME->getSelector(); | |||
11300 | if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { | |||
11301 | e = ME->getInstanceReceiver(); | |||
11302 | if (!e) | |||
11303 | return nullptr; | |||
11304 | e = e->IgnoreParenCasts(); | |||
11305 | } | |||
11306 | } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { | |||
11307 | if (CE->getNumArgs() == 1) { | |||
11308 | FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); | |||
11309 | if (Fn) { | |||
11310 | const IdentifierInfo *FnI = Fn->getIdentifier(); | |||
11311 | if (FnI && FnI->isStr("_Block_copy")) { | |||
11312 | e = CE->getArg(0)->IgnoreParenCasts(); | |||
11313 | } | |||
11314 | } | |||
11315 | } | |||
11316 | } | |||
11317 | ||||
11318 | BlockExpr *block = dyn_cast<BlockExpr>(e); | |||
11319 | if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) | |||
11320 | return nullptr; | |||
11321 | ||||
11322 | FindCaptureVisitor visitor(S.Context, owner.Variable); | |||
11323 | visitor.Visit(block->getBlockDecl()->getBody()); | |||
11324 | return visitor.VarWillBeReased ? nullptr : visitor.Capturer; | |||
11325 | } | |||
11326 | ||||
11327 | static void diagnoseRetainCycle(Sema &S, Expr *capturer, | |||
11328 | RetainCycleOwner &owner) { | |||
11329 | assert(capturer)((capturer) ? static_cast<void> (0) : __assert_fail ("capturer" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 11329, __PRETTY_FUNCTION__)); | |||
11330 | assert(owner.Variable && owner.Loc.isValid())((owner.Variable && owner.Loc.isValid()) ? static_cast <void> (0) : __assert_fail ("owner.Variable && owner.Loc.isValid()" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 11330, __PRETTY_FUNCTION__)); | |||
11331 | ||||
11332 | S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) | |||
11333 | << owner.Variable << capturer->getSourceRange(); | |||
11334 | S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) | |||
11335 | << owner.Indirect << owner.Range; | |||
11336 | } | |||
11337 | ||||
11338 | /// Check for a keyword selector that starts with the word 'add' or | |||
11339 | /// 'set'. | |||
11340 | static bool isSetterLikeSelector(Selector sel) { | |||
11341 | if (sel.isUnarySelector()) return false; | |||
11342 | ||||
11343 | StringRef str = sel.getNameForSlot(0); | |||
11344 | while (!str.empty() && str.front() == '_') str = str.substr(1); | |||
11345 | if (str.startswith("set")) | |||
11346 | str = str.substr(3); | |||
11347 | else if (str.startswith("add")) { | |||
11348 | // Specially whitelist 'addOperationWithBlock:'. | |||
11349 | if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) | |||
11350 | return false; | |||
11351 | str = str.substr(3); | |||
11352 | } | |||
11353 | else | |||
11354 | return false; | |||
11355 | ||||
11356 | if (str.empty()) return true; | |||
11357 | return !isLowercase(str.front()); | |||
11358 | } | |||
11359 | ||||
11360 | static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, | |||
11361 | ObjCMessageExpr *Message) { | |||
11362 | bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( | |||
11363 | Message->getReceiverInterface(), | |||
11364 | NSAPI::ClassId_NSMutableArray); | |||
11365 | if (!IsMutableArray) { | |||
11366 | return None; | |||
11367 | } | |||
11368 | ||||
11369 | Selector Sel = Message->getSelector(); | |||
11370 | ||||
11371 | Optional<NSAPI::NSArrayMethodKind> MKOpt = | |||
11372 | S.NSAPIObj->getNSArrayMethodKind(Sel); | |||
11373 | if (!MKOpt) { | |||
11374 | return None; | |||
11375 | } | |||
11376 | ||||
11377 | NSAPI::NSArrayMethodKind MK = *MKOpt; | |||
11378 | ||||
11379 | switch (MK) { | |||
11380 | case NSAPI::NSMutableArr_addObject: | |||
11381 | case NSAPI::NSMutableArr_insertObjectAtIndex: | |||
11382 | case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: | |||
11383 | return 0; | |||
11384 | case NSAPI::NSMutableArr_replaceObjectAtIndex: | |||
11385 | return 1; | |||
11386 | ||||
11387 | default: | |||
11388 | return None; | |||
11389 | } | |||
11390 | ||||
11391 | return None; | |||
11392 | } | |||
11393 | ||||
11394 | static | |||
11395 | Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, | |||
11396 | ObjCMessageExpr *Message) { | |||
11397 | bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( | |||
11398 | Message->getReceiverInterface(), | |||
11399 | NSAPI::ClassId_NSMutableDictionary); | |||
11400 | if (!IsMutableDictionary) { | |||
11401 | return None; | |||
11402 | } | |||
11403 | ||||
11404 | Selector Sel = Message->getSelector(); | |||
11405 | ||||
11406 | Optional<NSAPI::NSDictionaryMethodKind> MKOpt = | |||
11407 | S.NSAPIObj->getNSDictionaryMethodKind(Sel); | |||
11408 | if (!MKOpt) { | |||
11409 | return None; | |||
11410 | } | |||
11411 | ||||
11412 | NSAPI::NSDictionaryMethodKind MK = *MKOpt; | |||
11413 | ||||
11414 | switch (MK) { | |||
11415 | case NSAPI::NSMutableDict_setObjectForKey: | |||
11416 | case NSAPI::NSMutableDict_setValueForKey: | |||
11417 | case NSAPI::NSMutableDict_setObjectForKeyedSubscript: | |||
11418 | return 0; | |||
11419 | ||||
11420 | default: | |||
11421 | return None; | |||
11422 | } | |||
11423 | ||||
11424 | return None; | |||
11425 | } | |||
11426 | ||||
11427 | static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { | |||
11428 | bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( | |||
11429 | Message->getReceiverInterface(), | |||
11430 | NSAPI::ClassId_NSMutableSet); | |||
11431 | ||||
11432 | bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( | |||
11433 | Message->getReceiverInterface(), | |||
11434 | NSAPI::ClassId_NSMutableOrderedSet); | |||
11435 | if (!IsMutableSet && !IsMutableOrderedSet) { | |||
11436 | return None; | |||
11437 | } | |||
11438 | ||||
11439 | Selector Sel = Message->getSelector(); | |||
11440 | ||||
11441 | Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); | |||
11442 | if (!MKOpt) { | |||
11443 | return None; | |||
11444 | } | |||
11445 | ||||
11446 | NSAPI::NSSetMethodKind MK = *MKOpt; | |||
11447 | ||||
11448 | switch (MK) { | |||
11449 | case NSAPI::NSMutableSet_addObject: | |||
11450 | case NSAPI::NSOrderedSet_setObjectAtIndex: | |||
11451 | case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: | |||
11452 | case NSAPI::NSOrderedSet_insertObjectAtIndex: | |||
11453 | return 0; | |||
11454 | case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: | |||
11455 | return 1; | |||
11456 | } | |||
11457 | ||||
11458 | return None; | |||
11459 | } | |||
11460 | ||||
11461 | void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { | |||
11462 | if (!Message->isInstanceMessage()) { | |||
11463 | return; | |||
11464 | } | |||
11465 | ||||
11466 | Optional<int> ArgOpt; | |||
11467 | ||||
11468 | if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && | |||
11469 | !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && | |||
11470 | !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { | |||
11471 | return; | |||
11472 | } | |||
11473 | ||||
11474 | int ArgIndex = *ArgOpt; | |||
11475 | ||||
11476 | Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); | |||
11477 | if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { | |||
11478 | Arg = OE->getSourceExpr()->IgnoreImpCasts(); | |||
11479 | } | |||
11480 | ||||
11481 | if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { | |||
11482 | if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { | |||
11483 | if (ArgRE->isObjCSelfExpr()) { | |||
11484 | Diag(Message->getSourceRange().getBegin(), | |||
11485 | diag::warn_objc_circular_container) | |||
11486 | << ArgRE->getDecl()->getName() << StringRef("super"); | |||
11487 | } | |||
11488 | } | |||
11489 | } else { | |||
11490 | Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); | |||
11491 | ||||
11492 | if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { | |||
11493 | Receiver = OE->getSourceExpr()->IgnoreImpCasts(); | |||
11494 | } | |||
11495 | ||||
11496 | if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { | |||
11497 | if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { | |||
11498 | if (ReceiverRE->getDecl() == ArgRE->getDecl()) { | |||
11499 | ValueDecl *Decl = ReceiverRE->getDecl(); | |||
11500 | Diag(Message->getSourceRange().getBegin(), | |||
11501 | diag::warn_objc_circular_container) | |||
11502 | << Decl->getName() << Decl->getName(); | |||
11503 | if (!ArgRE->isObjCSelfExpr()) { | |||
11504 | Diag(Decl->getLocation(), | |||
11505 | diag::note_objc_circular_container_declared_here) | |||
11506 | << Decl->getName(); | |||
11507 | } | |||
11508 | } | |||
11509 | } | |||
11510 | } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { | |||
11511 | if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { | |||
11512 | if (IvarRE->getDecl() == IvarArgRE->getDecl()) { | |||
11513 | ObjCIvarDecl *Decl = IvarRE->getDecl(); | |||
11514 | Diag(Message->getSourceRange().getBegin(), | |||
11515 | diag::warn_objc_circular_container) | |||
11516 | << Decl->getName() << Decl->getName(); | |||
11517 | Diag(Decl->getLocation(), | |||
11518 | diag::note_objc_circular_container_declared_here) | |||
11519 | << Decl->getName(); | |||
11520 | } | |||
11521 | } | |||
11522 | } | |||
11523 | } | |||
11524 | } | |||
11525 | ||||
11526 | /// Check a message send to see if it's likely to cause a retain cycle. | |||
11527 | void Sema::checkRetainCycles(ObjCMessageExpr *msg) { | |||
11528 | // Only check instance methods whose selector looks like a setter. | |||
11529 | if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) | |||
11530 | return; | |||
11531 | ||||
11532 | // Try to find a variable that the receiver is strongly owned by. | |||
11533 | RetainCycleOwner owner; | |||
11534 | if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { | |||
11535 | if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) | |||
11536 | return; | |||
11537 | } else { | |||
11538 | assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance)((msg->getReceiverKind() == ObjCMessageExpr::SuperInstance ) ? static_cast<void> (0) : __assert_fail ("msg->getReceiverKind() == ObjCMessageExpr::SuperInstance" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 11538, __PRETTY_FUNCTION__)); | |||
11539 | owner.Variable = getCurMethodDecl()->getSelfDecl(); | |||
11540 | owner.Loc = msg->getSuperLoc(); | |||
11541 | owner.Range = msg->getSuperLoc(); | |||
11542 | } | |||
11543 | ||||
11544 | // Check whether the receiver is captured by any of the arguments. | |||
11545 | for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) | |||
11546 | if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) | |||
11547 | return diagnoseRetainCycle(*this, capturer, owner); | |||
11548 | } | |||
11549 | ||||
11550 | /// Check a property assign to see if it's likely to cause a retain cycle. | |||
11551 | void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { | |||
11552 | RetainCycleOwner owner; | |||
11553 | if (!findRetainCycleOwner(*this, receiver, owner)) | |||
11554 | return; | |||
11555 | ||||
11556 | if (Expr *capturer = findCapturingExpr(*this, argument, owner)) | |||
11557 | diagnoseRetainCycle(*this, capturer, owner); | |||
11558 | } | |||
11559 | ||||
11560 | void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { | |||
11561 | RetainCycleOwner Owner; | |||
11562 | if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) | |||
11563 | return; | |||
11564 | ||||
11565 | // Because we don't have an expression for the variable, we have to set the | |||
11566 | // location explicitly here. | |||
11567 | Owner.Loc = Var->getLocation(); | |||
11568 | Owner.Range = Var->getSourceRange(); | |||
11569 | ||||
11570 | if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) | |||
11571 | diagnoseRetainCycle(*this, Capturer, Owner); | |||
11572 | } | |||
11573 | ||||
11574 | static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, | |||
11575 | Expr *RHS, bool isProperty) { | |||
11576 | // Check if RHS is an Objective-C object literal, which also can get | |||
11577 | // immediately zapped in a weak reference. Note that we explicitly | |||
11578 | // allow ObjCStringLiterals, since those are designed to never really die. | |||
11579 | RHS = RHS->IgnoreParenImpCasts(); | |||
11580 | ||||
11581 | // This enum needs to match with the 'select' in | |||
11582 | // warn_objc_arc_literal_assign (off-by-1). | |||
11583 | Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); | |||
11584 | if (Kind == Sema::LK_String || Kind == Sema::LK_None) | |||
11585 | return false; | |||
11586 | ||||
11587 | S.Diag(Loc, diag::warn_arc_literal_assign) | |||
11588 | << (unsigned) Kind | |||
11589 | << (isProperty ? 0 : 1) | |||
11590 | << RHS->getSourceRange(); | |||
11591 | ||||
11592 | return true; | |||
11593 | } | |||
11594 | ||||
11595 | static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, | |||
11596 | Qualifiers::ObjCLifetime LT, | |||
11597 | Expr *RHS, bool isProperty) { | |||
11598 | // Strip off any implicit cast added to get to the one ARC-specific. | |||
11599 | while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { | |||
11600 | if (cast->getCastKind() == CK_ARCConsumeObject) { | |||
11601 | S.Diag(Loc, diag::warn_arc_retained_assign) | |||
11602 | << (LT == Qualifiers::OCL_ExplicitNone) | |||
11603 | << (isProperty ? 0 : 1) | |||
11604 | << RHS->getSourceRange(); | |||
11605 | return true; | |||
11606 | } | |||
11607 | RHS = cast->getSubExpr(); | |||
11608 | } | |||
11609 | ||||
11610 | if (LT == Qualifiers::OCL_Weak && | |||
11611 | checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) | |||
11612 | return true; | |||
11613 | ||||
11614 | return false; | |||
11615 | } | |||
11616 | ||||
11617 | bool Sema::checkUnsafeAssigns(SourceLocation Loc, | |||
11618 | QualType LHS, Expr *RHS) { | |||
11619 | Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); | |||
11620 | ||||
11621 | if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) | |||
11622 | return false; | |||
11623 | ||||
11624 | if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) | |||
11625 | return true; | |||
11626 | ||||
11627 | return false; | |||
11628 | } | |||
11629 | ||||
11630 | void Sema::checkUnsafeExprAssigns(SourceLocation Loc, | |||
11631 | Expr *LHS, Expr *RHS) { | |||
11632 | QualType LHSType; | |||
11633 | // PropertyRef on LHS type need be directly obtained from | |||
11634 | // its declaration as it has a PseudoType. | |||
11635 | ObjCPropertyRefExpr *PRE | |||
11636 | = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); | |||
11637 | if (PRE && !PRE->isImplicitProperty()) { | |||
11638 | const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); | |||
11639 | if (PD) | |||
11640 | LHSType = PD->getType(); | |||
11641 | } | |||
11642 | ||||
11643 | if (LHSType.isNull()) | |||
11644 | LHSType = LHS->getType(); | |||
11645 | ||||
11646 | Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); | |||
11647 | ||||
11648 | if (LT == Qualifiers::OCL_Weak) { | |||
11649 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | |||
11650 | getCurFunction()->markSafeWeakUse(LHS); | |||
11651 | } | |||
11652 | ||||
11653 | if (checkUnsafeAssigns(Loc, LHSType, RHS)) | |||
11654 | return; | |||
11655 | ||||
11656 | // FIXME. Check for other life times. | |||
11657 | if (LT != Qualifiers::OCL_None) | |||
11658 | return; | |||
11659 | ||||
11660 | if (PRE) { | |||
11661 | if (PRE->isImplicitProperty()) | |||
11662 | return; | |||
11663 | const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); | |||
11664 | if (!PD) | |||
11665 | return; | |||
11666 | ||||
11667 | unsigned Attributes = PD->getPropertyAttributes(); | |||
11668 | if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { | |||
11669 | // when 'assign' attribute was not explicitly specified | |||
11670 | // by user, ignore it and rely on property type itself | |||
11671 | // for lifetime info. | |||
11672 | unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); | |||
11673 | if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && | |||
11674 | LHSType->isObjCRetainableType()) | |||
11675 | return; | |||
11676 | ||||
11677 | while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { | |||
11678 | if (cast->getCastKind() == CK_ARCConsumeObject) { | |||
11679 | Diag(Loc, diag::warn_arc_retained_property_assign) | |||
11680 | << RHS->getSourceRange(); | |||
11681 | return; | |||
11682 | } | |||
11683 | RHS = cast->getSubExpr(); | |||
11684 | } | |||
11685 | } | |||
11686 | else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { | |||
11687 | if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) | |||
11688 | return; | |||
11689 | } | |||
11690 | } | |||
11691 | } | |||
11692 | ||||
11693 | //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// | |||
11694 | ||||
11695 | namespace { | |||
11696 | bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, | |||
11697 | SourceLocation StmtLoc, | |||
11698 | const NullStmt *Body) { | |||
11699 | // Do not warn if the body is a macro that expands to nothing, e.g: | |||
11700 | // | |||
11701 | // #define CALL(x) | |||
11702 | // if (condition) | |||
11703 | // CALL(0); | |||
11704 | // | |||
11705 | if (Body->hasLeadingEmptyMacro()) | |||
11706 | return false; | |||
11707 | ||||
11708 | // Get line numbers of statement and body. | |||
11709 | bool StmtLineInvalid; | |||
11710 | unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, | |||
11711 | &StmtLineInvalid); | |||
11712 | if (StmtLineInvalid) | |||
11713 | return false; | |||
11714 | ||||
11715 | bool BodyLineInvalid; | |||
11716 | unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), | |||
11717 | &BodyLineInvalid); | |||
11718 | if (BodyLineInvalid) | |||
11719 | return false; | |||
11720 | ||||
11721 | // Warn if null statement and body are on the same line. | |||
11722 | if (StmtLine != BodyLine) | |||
11723 | return false; | |||
11724 | ||||
11725 | return true; | |||
11726 | } | |||
11727 | } // end anonymous namespace | |||
11728 | ||||
11729 | void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, | |||
11730 | const Stmt *Body, | |||
11731 | unsigned DiagID) { | |||
11732 | // Since this is a syntactic check, don't emit diagnostic for template | |||
11733 | // instantiations, this just adds noise. | |||
11734 | if (CurrentInstantiationScope) | |||
11735 | return; | |||
11736 | ||||
11737 | // The body should be a null statement. | |||
11738 | const NullStmt *NBody = dyn_cast<NullStmt>(Body); | |||
11739 | if (!NBody) | |||
11740 | return; | |||
11741 | ||||
11742 | // Do the usual checks. | |||
11743 | if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) | |||
11744 | return; | |||
11745 | ||||
11746 | Diag(NBody->getSemiLoc(), DiagID); | |||
11747 | Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); | |||
11748 | } | |||
11749 | ||||
11750 | void Sema::DiagnoseEmptyLoopBody(const Stmt *S, | |||
11751 | const Stmt *PossibleBody) { | |||
11752 | assert(!CurrentInstantiationScope)((!CurrentInstantiationScope) ? static_cast<void> (0) : __assert_fail ("!CurrentInstantiationScope", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 11752, __PRETTY_FUNCTION__)); // Ensured by caller | |||
11753 | ||||
11754 | SourceLocation StmtLoc; | |||
11755 | const Stmt *Body; | |||
11756 | unsigned DiagID; | |||
11757 | if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { | |||
11758 | StmtLoc = FS->getRParenLoc(); | |||
11759 | Body = FS->getBody(); | |||
11760 | DiagID = diag::warn_empty_for_body; | |||
11761 | } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { | |||
11762 | StmtLoc = WS->getCond()->getSourceRange().getEnd(); | |||
11763 | Body = WS->getBody(); | |||
11764 | DiagID = diag::warn_empty_while_body; | |||
11765 | } else | |||
11766 | return; // Neither `for' nor `while'. | |||
11767 | ||||
11768 | // The body should be a null statement. | |||
11769 | const NullStmt *NBody = dyn_cast<NullStmt>(Body); | |||
11770 | if (!NBody) | |||
11771 | return; | |||
11772 | ||||
11773 | // Skip expensive checks if diagnostic is disabled. | |||
11774 | if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) | |||
11775 | return; | |||
11776 | ||||
11777 | // Do the usual checks. | |||
11778 | if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) | |||
11779 | return; | |||
11780 | ||||
11781 | // `for(...);' and `while(...);' are popular idioms, so in order to keep | |||
11782 | // noise level low, emit diagnostics only if for/while is followed by a | |||
11783 | // CompoundStmt, e.g.: | |||
11784 | // for (int i = 0; i < n; i++); | |||
11785 | // { | |||
11786 | // a(i); | |||
11787 | // } | |||
11788 | // or if for/while is followed by a statement with more indentation | |||
11789 | // than for/while itself: | |||
11790 | // for (int i = 0; i < n; i++); | |||
11791 | // a(i); | |||
11792 | bool ProbableTypo = isa<CompoundStmt>(PossibleBody); | |||
11793 | if (!ProbableTypo) { | |||
11794 | bool BodyColInvalid; | |||
11795 | unsigned BodyCol = SourceMgr.getPresumedColumnNumber( | |||
11796 | PossibleBody->getLocStart(), | |||
11797 | &BodyColInvalid); | |||
11798 | if (BodyColInvalid) | |||
11799 | return; | |||
11800 | ||||
11801 | bool StmtColInvalid; | |||
11802 | unsigned StmtCol = SourceMgr.getPresumedColumnNumber( | |||
11803 | S->getLocStart(), | |||
11804 | &StmtColInvalid); | |||
11805 | if (StmtColInvalid) | |||
11806 | return; | |||
11807 | ||||
11808 | if (BodyCol > StmtCol) | |||
11809 | ProbableTypo = true; | |||
11810 | } | |||
11811 | ||||
11812 | if (ProbableTypo) { | |||
11813 | Diag(NBody->getSemiLoc(), DiagID); | |||
11814 | Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); | |||
11815 | } | |||
11816 | } | |||
11817 | ||||
11818 | //===--- CHECK: Warn on self move with std::move. -------------------------===// | |||
11819 | ||||
11820 | /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. | |||
11821 | void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, | |||
11822 | SourceLocation OpLoc) { | |||
11823 | if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) | |||
11824 | return; | |||
11825 | ||||
11826 | if (inTemplateInstantiation()) | |||
11827 | return; | |||
11828 | ||||
11829 | // Strip parens and casts away. | |||
11830 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | |||
11831 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | |||
11832 | ||||
11833 | // Check for a call expression | |||
11834 | const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); | |||
11835 | if (!CE || CE->getNumArgs() != 1) | |||
11836 | return; | |||
11837 | ||||
11838 | // Check for a call to std::move | |||
11839 | if (!CE->isCallToStdMove()) | |||
11840 | return; | |||
11841 | ||||
11842 | // Get argument from std::move | |||
11843 | RHSExpr = CE->getArg(0); | |||
11844 | ||||
11845 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | |||
11846 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | |||
11847 | ||||
11848 | // Two DeclRefExpr's, check that the decls are the same. | |||
11849 | if (LHSDeclRef && RHSDeclRef) { | |||
11850 | if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) | |||
11851 | return; | |||
11852 | if (LHSDeclRef->getDecl()->getCanonicalDecl() != | |||
11853 | RHSDeclRef->getDecl()->getCanonicalDecl()) | |||
11854 | return; | |||
11855 | ||||
11856 | Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() | |||
11857 | << LHSExpr->getSourceRange() | |||
11858 | << RHSExpr->getSourceRange(); | |||
11859 | return; | |||
11860 | } | |||
11861 | ||||
11862 | // Member variables require a different approach to check for self moves. | |||
11863 | // MemberExpr's are the same if every nested MemberExpr refers to the same | |||
11864 | // Decl and that the base Expr's are DeclRefExpr's with the same Decl or | |||
11865 | // the base Expr's are CXXThisExpr's. | |||
11866 | const Expr *LHSBase = LHSExpr; | |||
11867 | const Expr *RHSBase = RHSExpr; | |||
11868 | const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); | |||
11869 | const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); | |||
11870 | if (!LHSME || !RHSME) | |||
11871 | return; | |||
11872 | ||||
11873 | while (LHSME && RHSME) { | |||
11874 | if (LHSME->getMemberDecl()->getCanonicalDecl() != | |||
11875 | RHSME->getMemberDecl()->getCanonicalDecl()) | |||
11876 | return; | |||
11877 | ||||
11878 | LHSBase = LHSME->getBase(); | |||
11879 | RHSBase = RHSME->getBase(); | |||
11880 | LHSME = dyn_cast<MemberExpr>(LHSBase); | |||
11881 | RHSME = dyn_cast<MemberExpr>(RHSBase); | |||
11882 | } | |||
11883 | ||||
11884 | LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); | |||
11885 | RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); | |||
11886 | if (LHSDeclRef && RHSDeclRef) { | |||
11887 | if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) | |||
11888 | return; | |||
11889 | if (LHSDeclRef->getDecl()->getCanonicalDecl() != | |||
11890 | RHSDeclRef->getDecl()->getCanonicalDecl()) | |||
11891 | return; | |||
11892 | ||||
11893 | Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() | |||
11894 | << LHSExpr->getSourceRange() | |||
11895 | << RHSExpr->getSourceRange(); | |||
11896 | return; | |||
11897 | } | |||
11898 | ||||
11899 | if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) | |||
11900 | Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() | |||
11901 | << LHSExpr->getSourceRange() | |||
11902 | << RHSExpr->getSourceRange(); | |||
11903 | } | |||
11904 | ||||
11905 | //===--- Layout compatibility ----------------------------------------------// | |||
11906 | ||||
11907 | namespace { | |||
11908 | ||||
11909 | bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); | |||
11910 | ||||
11911 | /// \brief Check if two enumeration types are layout-compatible. | |||
11912 | bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { | |||
11913 | // C++11 [dcl.enum] p8: | |||
11914 | // Two enumeration types are layout-compatible if they have the same | |||
11915 | // underlying type. | |||
11916 | return ED1->isComplete() && ED2->isComplete() && | |||
11917 | C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); | |||
11918 | } | |||
11919 | ||||
11920 | /// \brief Check if two fields are layout-compatible. | |||
11921 | bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { | |||
11922 | if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) | |||
11923 | return false; | |||
11924 | ||||
11925 | if (Field1->isBitField() != Field2->isBitField()) | |||
11926 | return false; | |||
11927 | ||||
11928 | if (Field1->isBitField()) { | |||
11929 | // Make sure that the bit-fields are the same length. | |||
11930 | unsigned Bits1 = Field1->getBitWidthValue(C); | |||
11931 | unsigned Bits2 = Field2->getBitWidthValue(C); | |||
11932 | ||||
11933 | if (Bits1 != Bits2) | |||
11934 | return false; | |||
11935 | } | |||
11936 | ||||
11937 | return true; | |||
11938 | } | |||
11939 | ||||
11940 | /// \brief Check if two standard-layout structs are layout-compatible. | |||
11941 | /// (C++11 [class.mem] p17) | |||
11942 | bool isLayoutCompatibleStruct(ASTContext &C, | |||
11943 | RecordDecl *RD1, | |||
11944 | RecordDecl *RD2) { | |||
11945 | // If both records are C++ classes, check that base classes match. | |||
11946 | if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { | |||
11947 | // If one of records is a CXXRecordDecl we are in C++ mode, | |||
11948 | // thus the other one is a CXXRecordDecl, too. | |||
11949 | const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); | |||
11950 | // Check number of base classes. | |||
11951 | if (D1CXX->getNumBases() != D2CXX->getNumBases()) | |||
11952 | return false; | |||
11953 | ||||
11954 | // Check the base classes. | |||
11955 | for (CXXRecordDecl::base_class_const_iterator | |||
11956 | Base1 = D1CXX->bases_begin(), | |||
11957 | BaseEnd1 = D1CXX->bases_end(), | |||
11958 | Base2 = D2CXX->bases_begin(); | |||
11959 | Base1 != BaseEnd1; | |||
11960 | ++Base1, ++Base2) { | |||
11961 | if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) | |||
11962 | return false; | |||
11963 | } | |||
11964 | } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { | |||
11965 | // If only RD2 is a C++ class, it should have zero base classes. | |||
11966 | if (D2CXX->getNumBases() > 0) | |||
11967 | return false; | |||
11968 | } | |||
11969 | ||||
11970 | // Check the fields. | |||
11971 | RecordDecl::field_iterator Field2 = RD2->field_begin(), | |||
11972 | Field2End = RD2->field_end(), | |||
11973 | Field1 = RD1->field_begin(), | |||
11974 | Field1End = RD1->field_end(); | |||
11975 | for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { | |||
11976 | if (!isLayoutCompatible(C, *Field1, *Field2)) | |||
11977 | return false; | |||
11978 | } | |||
11979 | if (Field1 != Field1End || Field2 != Field2End) | |||
11980 | return false; | |||
11981 | ||||
11982 | return true; | |||
11983 | } | |||
11984 | ||||
11985 | /// \brief Check if two standard-layout unions are layout-compatible. | |||
11986 | /// (C++11 [class.mem] p18) | |||
11987 | bool isLayoutCompatibleUnion(ASTContext &C, | |||
11988 | RecordDecl *RD1, | |||
11989 | RecordDecl *RD2) { | |||
11990 | llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; | |||
11991 | for (auto *Field2 : RD2->fields()) | |||
11992 | UnmatchedFields.insert(Field2); | |||
11993 | ||||
11994 | for (auto *Field1 : RD1->fields()) { | |||
11995 | llvm::SmallPtrSet<FieldDecl *, 8>::iterator | |||
11996 | I = UnmatchedFields.begin(), | |||
11997 | E = UnmatchedFields.end(); | |||
11998 | ||||
11999 | for ( ; I != E; ++I) { | |||
12000 | if (isLayoutCompatible(C, Field1, *I)) { | |||
12001 | bool Result = UnmatchedFields.erase(*I); | |||
12002 | (void) Result; | |||
12003 | assert(Result)((Result) ? static_cast<void> (0) : __assert_fail ("Result" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 12003, __PRETTY_FUNCTION__)); | |||
12004 | break; | |||
12005 | } | |||
12006 | } | |||
12007 | if (I == E) | |||
12008 | return false; | |||
12009 | } | |||
12010 | ||||
12011 | return UnmatchedFields.empty(); | |||
12012 | } | |||
12013 | ||||
12014 | bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { | |||
12015 | if (RD1->isUnion() != RD2->isUnion()) | |||
12016 | return false; | |||
12017 | ||||
12018 | if (RD1->isUnion()) | |||
12019 | return isLayoutCompatibleUnion(C, RD1, RD2); | |||
12020 | else | |||
12021 | return isLayoutCompatibleStruct(C, RD1, RD2); | |||
12022 | } | |||
12023 | ||||
12024 | /// \brief Check if two types are layout-compatible in C++11 sense. | |||
12025 | bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { | |||
12026 | if (T1.isNull() || T2.isNull()) | |||
12027 | return false; | |||
12028 | ||||
12029 | // C++11 [basic.types] p11: | |||
12030 | // If two types T1 and T2 are the same type, then T1 and T2 are | |||
12031 | // layout-compatible types. | |||
12032 | if (C.hasSameType(T1, T2)) | |||
12033 | return true; | |||
12034 | ||||
12035 | T1 = T1.getCanonicalType().getUnqualifiedType(); | |||
12036 | T2 = T2.getCanonicalType().getUnqualifiedType(); | |||
12037 | ||||
12038 | const Type::TypeClass TC1 = T1->getTypeClass(); | |||
12039 | const Type::TypeClass TC2 = T2->getTypeClass(); | |||
12040 | ||||
12041 | if (TC1 != TC2) | |||
12042 | return false; | |||
12043 | ||||
12044 | if (TC1 == Type::Enum) { | |||
12045 | return isLayoutCompatible(C, | |||
12046 | cast<EnumType>(T1)->getDecl(), | |||
12047 | cast<EnumType>(T2)->getDecl()); | |||
12048 | } else if (TC1 == Type::Record) { | |||
12049 | if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) | |||
12050 | return false; | |||
12051 | ||||
12052 | return isLayoutCompatible(C, | |||
12053 | cast<RecordType>(T1)->getDecl(), | |||
12054 | cast<RecordType>(T2)->getDecl()); | |||
12055 | } | |||
12056 | ||||
12057 | return false; | |||
12058 | } | |||
12059 | } // end anonymous namespace | |||
12060 | ||||
12061 | //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// | |||
12062 | ||||
12063 | namespace { | |||
12064 | /// \brief Given a type tag expression find the type tag itself. | |||
12065 | /// | |||
12066 | /// \param TypeExpr Type tag expression, as it appears in user's code. | |||
12067 | /// | |||
12068 | /// \param VD Declaration of an identifier that appears in a type tag. | |||
12069 | /// | |||
12070 | /// \param MagicValue Type tag magic value. | |||
12071 | bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, | |||
12072 | const ValueDecl **VD, uint64_t *MagicValue) { | |||
12073 | while(true) { | |||
12074 | if (!TypeExpr) | |||
12075 | return false; | |||
12076 | ||||
12077 | TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); | |||
12078 | ||||
12079 | switch (TypeExpr->getStmtClass()) { | |||
12080 | case Stmt::UnaryOperatorClass: { | |||
12081 | const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); | |||
12082 | if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { | |||
12083 | TypeExpr = UO->getSubExpr(); | |||
12084 | continue; | |||
12085 | } | |||
12086 | return false; | |||
12087 | } | |||
12088 | ||||
12089 | case Stmt::DeclRefExprClass: { | |||
12090 | const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); | |||
12091 | *VD = DRE->getDecl(); | |||
12092 | return true; | |||
12093 | } | |||
12094 | ||||
12095 | case Stmt::IntegerLiteralClass: { | |||
12096 | const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); | |||
12097 | llvm::APInt MagicValueAPInt = IL->getValue(); | |||
12098 | if (MagicValueAPInt.getActiveBits() <= 64) { | |||
12099 | *MagicValue = MagicValueAPInt.getZExtValue(); | |||
12100 | return true; | |||
12101 | } else | |||
12102 | return false; | |||
12103 | } | |||
12104 | ||||
12105 | case Stmt::BinaryConditionalOperatorClass: | |||
12106 | case Stmt::ConditionalOperatorClass: { | |||
12107 | const AbstractConditionalOperator *ACO = | |||
12108 | cast<AbstractConditionalOperator>(TypeExpr); | |||
12109 | bool Result; | |||
12110 | if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { | |||
12111 | if (Result) | |||
12112 | TypeExpr = ACO->getTrueExpr(); | |||
12113 | else | |||
12114 | TypeExpr = ACO->getFalseExpr(); | |||
12115 | continue; | |||
12116 | } | |||
12117 | return false; | |||
12118 | } | |||
12119 | ||||
12120 | case Stmt::BinaryOperatorClass: { | |||
12121 | const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); | |||
12122 | if (BO->getOpcode() == BO_Comma) { | |||
12123 | TypeExpr = BO->getRHS(); | |||
12124 | continue; | |||
12125 | } | |||
12126 | return false; | |||
12127 | } | |||
12128 | ||||
12129 | default: | |||
12130 | return false; | |||
12131 | } | |||
12132 | } | |||
12133 | } | |||
12134 | ||||
12135 | /// \brief Retrieve the C type corresponding to type tag TypeExpr. | |||
12136 | /// | |||
12137 | /// \param TypeExpr Expression that specifies a type tag. | |||
12138 | /// | |||
12139 | /// \param MagicValues Registered magic values. | |||
12140 | /// | |||
12141 | /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong | |||
12142 | /// kind. | |||
12143 | /// | |||
12144 | /// \param TypeInfo Information about the corresponding C type. | |||
12145 | /// | |||
12146 | /// \returns true if the corresponding C type was found. | |||
12147 | bool GetMatchingCType( | |||
12148 | const IdentifierInfo *ArgumentKind, | |||
12149 | const Expr *TypeExpr, const ASTContext &Ctx, | |||
12150 | const llvm::DenseMap<Sema::TypeTagMagicValue, | |||
12151 | Sema::TypeTagData> *MagicValues, | |||
12152 | bool &FoundWrongKind, | |||
12153 | Sema::TypeTagData &TypeInfo) { | |||
12154 | FoundWrongKind = false; | |||
12155 | ||||
12156 | // Variable declaration that has type_tag_for_datatype attribute. | |||
12157 | const ValueDecl *VD = nullptr; | |||
12158 | ||||
12159 | uint64_t MagicValue; | |||
12160 | ||||
12161 | if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) | |||
12162 | return false; | |||
12163 | ||||
12164 | if (VD) { | |||
12165 | if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { | |||
12166 | if (I->getArgumentKind() != ArgumentKind) { | |||
12167 | FoundWrongKind = true; | |||
12168 | return false; | |||
12169 | } | |||
12170 | TypeInfo.Type = I->getMatchingCType(); | |||
12171 | TypeInfo.LayoutCompatible = I->getLayoutCompatible(); | |||
12172 | TypeInfo.MustBeNull = I->getMustBeNull(); | |||
12173 | return true; | |||
12174 | } | |||
12175 | return false; | |||
12176 | } | |||
12177 | ||||
12178 | if (!MagicValues) | |||
12179 | return false; | |||
12180 | ||||
12181 | llvm::DenseMap<Sema::TypeTagMagicValue, | |||
12182 | Sema::TypeTagData>::const_iterator I = | |||
12183 | MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); | |||
12184 | if (I == MagicValues->end()) | |||
12185 | return false; | |||
12186 | ||||
12187 | TypeInfo = I->second; | |||
12188 | return true; | |||
12189 | } | |||
12190 | } // end anonymous namespace | |||
12191 | ||||
12192 | void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, | |||
12193 | uint64_t MagicValue, QualType Type, | |||
12194 | bool LayoutCompatible, | |||
12195 | bool MustBeNull) { | |||
12196 | if (!TypeTagForDatatypeMagicValues) | |||
12197 | TypeTagForDatatypeMagicValues.reset( | |||
12198 | new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); | |||
12199 | ||||
12200 | TypeTagMagicValue Magic(ArgumentKind, MagicValue); | |||
12201 | (*TypeTagForDatatypeMagicValues)[Magic] = | |||
12202 | TypeTagData(Type, LayoutCompatible, MustBeNull); | |||
12203 | } | |||
12204 | ||||
12205 | namespace { | |||
12206 | bool IsSameCharType(QualType T1, QualType T2) { | |||
12207 | const BuiltinType *BT1 = T1->getAs<BuiltinType>(); | |||
12208 | if (!BT1) | |||
12209 | return false; | |||
12210 | ||||
12211 | const BuiltinType *BT2 = T2->getAs<BuiltinType>(); | |||
12212 | if (!BT2) | |||
12213 | return false; | |||
12214 | ||||
12215 | BuiltinType::Kind T1Kind = BT1->getKind(); | |||
12216 | BuiltinType::Kind T2Kind = BT2->getKind(); | |||
12217 | ||||
12218 | return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || | |||
12219 | (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || | |||
12220 | (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || | |||
12221 | (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); | |||
12222 | } | |||
12223 | } // end anonymous namespace | |||
12224 | ||||
12225 | void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, | |||
12226 | const Expr * const *ExprArgs) { | |||
12227 | const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); | |||
12228 | bool IsPointerAttr = Attr->getIsPointer(); | |||
12229 | ||||
12230 | const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; | |||
12231 | bool FoundWrongKind; | |||
12232 | TypeTagData TypeInfo; | |||
12233 | if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, | |||
12234 | TypeTagForDatatypeMagicValues.get(), | |||
12235 | FoundWrongKind, TypeInfo)) { | |||
12236 | if (FoundWrongKind) | |||
12237 | Diag(TypeTagExpr->getExprLoc(), | |||
12238 | diag::warn_type_tag_for_datatype_wrong_kind) | |||
12239 | << TypeTagExpr->getSourceRange(); | |||
12240 | return; | |||
12241 | } | |||
12242 | ||||
12243 | const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; | |||
12244 | if (IsPointerAttr) { | |||
12245 | // Skip implicit cast of pointer to `void *' (as a function argument). | |||
12246 | if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) | |||
12247 | if (ICE->getType()->isVoidPointerType() && | |||
12248 | ICE->getCastKind() == CK_BitCast) | |||
12249 | ArgumentExpr = ICE->getSubExpr(); | |||
12250 | } | |||
12251 | QualType ArgumentType = ArgumentExpr->getType(); | |||
12252 | ||||
12253 | // Passing a `void*' pointer shouldn't trigger a warning. | |||
12254 | if (IsPointerAttr && ArgumentType->isVoidPointerType()) | |||
12255 | return; | |||
12256 | ||||
12257 | if (TypeInfo.MustBeNull) { | |||
12258 | // Type tag with matching void type requires a null pointer. | |||
12259 | if (!ArgumentExpr->isNullPointerConstant(Context, | |||
12260 | Expr::NPC_ValueDependentIsNotNull)) { | |||
12261 | Diag(ArgumentExpr->getExprLoc(), | |||
12262 | diag::warn_type_safety_null_pointer_required) | |||
12263 | << ArgumentKind->getName() | |||
12264 | << ArgumentExpr->getSourceRange() | |||
12265 | << TypeTagExpr->getSourceRange(); | |||
12266 | } | |||
12267 | return; | |||
12268 | } | |||
12269 | ||||
12270 | QualType RequiredType = TypeInfo.Type; | |||
12271 | if (IsPointerAttr) | |||
12272 | RequiredType = Context.getPointerType(RequiredType); | |||
12273 | ||||
12274 | bool mismatch = false; | |||
12275 | if (!TypeInfo.LayoutCompatible) { | |||
12276 | mismatch = !Context.hasSameType(ArgumentType, RequiredType); | |||
12277 | ||||
12278 | // C++11 [basic.fundamental] p1: | |||
12279 | // Plain char, signed char, and unsigned char are three distinct types. | |||
12280 | // | |||
12281 | // But we treat plain `char' as equivalent to `signed char' or `unsigned | |||
12282 | // char' depending on the current char signedness mode. | |||
12283 | if (mismatch) | |||
12284 | if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), | |||
12285 | RequiredType->getPointeeType())) || | |||
12286 | (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) | |||
12287 | mismatch = false; | |||
12288 | } else | |||
12289 | if (IsPointerAttr) | |||
12290 | mismatch = !isLayoutCompatible(Context, | |||
12291 | ArgumentType->getPointeeType(), | |||
12292 | RequiredType->getPointeeType()); | |||
12293 | else | |||
12294 | mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); | |||
12295 | ||||
12296 | if (mismatch) | |||
12297 | Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) | |||
12298 | << ArgumentType << ArgumentKind | |||
12299 | << TypeInfo.LayoutCompatible << RequiredType | |||
12300 | << ArgumentExpr->getSourceRange() | |||
12301 | << TypeTagExpr->getSourceRange(); | |||
12302 | } | |||
12303 | ||||
12304 | void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, | |||
12305 | CharUnits Alignment) { | |||
12306 | MisalignedMembers.emplace_back(E, RD, MD, Alignment); | |||
12307 | } | |||
12308 | ||||
12309 | void Sema::DiagnoseMisalignedMembers() { | |||
12310 | for (MisalignedMember &m : MisalignedMembers) { | |||
12311 | const NamedDecl *ND = m.RD; | |||
12312 | if (ND->getName().empty()) { | |||
12313 | if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) | |||
12314 | ND = TD; | |||
12315 | } | |||
12316 | Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) | |||
12317 | << m.MD << ND << m.E->getSourceRange(); | |||
12318 | } | |||
12319 | MisalignedMembers.clear(); | |||
12320 | } | |||
12321 | ||||
12322 | void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { | |||
12323 | E = E->IgnoreParens(); | |||
12324 | if (!T->isPointerType() && !T->isIntegerType()) | |||
12325 | return; | |||
12326 | if (isa<UnaryOperator>(E) && | |||
12327 | cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { | |||
12328 | auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); | |||
12329 | if (isa<MemberExpr>(Op)) { | |||
12330 | auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), | |||
12331 | MisalignedMember(Op)); | |||
12332 | if (MA != MisalignedMembers.end() && | |||
12333 | (T->isIntegerType() || | |||
12334 | (T->isPointerType() && | |||
12335 | Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment))) | |||
12336 | MisalignedMembers.erase(MA); | |||
12337 | } | |||
12338 | } | |||
12339 | } | |||
12340 | ||||
12341 | void Sema::RefersToMemberWithReducedAlignment( | |||
12342 | Expr *E, | |||
12343 | llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> | |||
12344 | Action) { | |||
12345 | const auto *ME = dyn_cast<MemberExpr>(E); | |||
12346 | if (!ME) | |||
12347 | return; | |||
12348 | ||||
12349 | // No need to check expressions with an __unaligned-qualified type. | |||
12350 | if (E->getType().getQualifiers().hasUnaligned()) | |||
12351 | return; | |||
12352 | ||||
12353 | // For a chain of MemberExpr like "a.b.c.d" this list | |||
12354 | // will keep FieldDecl's like [d, c, b]. | |||
12355 | SmallVector<FieldDecl *, 4> ReverseMemberChain; | |||
12356 | const MemberExpr *TopME = nullptr; | |||
12357 | bool AnyIsPacked = false; | |||
12358 | do { | |||
12359 | QualType BaseType = ME->getBase()->getType(); | |||
12360 | if (ME->isArrow()) | |||
12361 | BaseType = BaseType->getPointeeType(); | |||
12362 | RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); | |||
12363 | if (RD->isInvalidDecl()) | |||
12364 | return; | |||
12365 | ||||
12366 | ValueDecl *MD = ME->getMemberDecl(); | |||
12367 | auto *FD = dyn_cast<FieldDecl>(MD); | |||
12368 | // We do not care about non-data members. | |||
12369 | if (!FD || FD->isInvalidDecl()) | |||
12370 | return; | |||
12371 | ||||
12372 | AnyIsPacked = | |||
12373 | AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); | |||
12374 | ReverseMemberChain.push_back(FD); | |||
12375 | ||||
12376 | TopME = ME; | |||
12377 | ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); | |||
12378 | } while (ME); | |||
12379 | assert(TopME && "We did not compute a topmost MemberExpr!")((TopME && "We did not compute a topmost MemberExpr!" ) ? static_cast<void> (0) : __assert_fail ("TopME && \"We did not compute a topmost MemberExpr!\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 12379, __PRETTY_FUNCTION__)); | |||
12380 | ||||
12381 | // Not the scope of this diagnostic. | |||
12382 | if (!AnyIsPacked) | |||
12383 | return; | |||
12384 | ||||
12385 | const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); | |||
12386 | const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); | |||
12387 | // TODO: The innermost base of the member expression may be too complicated. | |||
12388 | // For now, just disregard these cases. This is left for future | |||
12389 | // improvement. | |||
12390 | if (!DRE && !isa<CXXThisExpr>(TopBase)) | |||
12391 | return; | |||
12392 | ||||
12393 | // Alignment expected by the whole expression. | |||
12394 | CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); | |||
12395 | ||||
12396 | // No need to do anything else with this case. | |||
12397 | if (ExpectedAlignment.isOne()) | |||
12398 | return; | |||
12399 | ||||
12400 | // Synthesize offset of the whole access. | |||
12401 | CharUnits Offset; | |||
12402 | for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); | |||
12403 | I++) { | |||
12404 | Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); | |||
12405 | } | |||
12406 | ||||
12407 | // Compute the CompleteObjectAlignment as the alignment of the whole chain. | |||
12408 | CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( | |||
12409 | ReverseMemberChain.back()->getParent()->getTypeForDecl()); | |||
12410 | ||||
12411 | // The base expression of the innermost MemberExpr may give | |||
12412 | // stronger guarantees than the class containing the member. | |||
12413 | if (DRE && !TopME->isArrow()) { | |||
12414 | const ValueDecl *VD = DRE->getDecl(); | |||
12415 | if (!VD->getType()->isReferenceType()) | |||
12416 | CompleteObjectAlignment = | |||
12417 | std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); | |||
12418 | } | |||
12419 | ||||
12420 | // Check if the synthesized offset fulfills the alignment. | |||
12421 | if (Offset % ExpectedAlignment != 0 || | |||
12422 | // It may fulfill the offset it but the effective alignment may still be | |||
12423 | // lower than the expected expression alignment. | |||
12424 | CompleteObjectAlignment < ExpectedAlignment) { | |||
12425 | // If this happens, we want to determine a sensible culprit of this. | |||
12426 | // Intuitively, watching the chain of member expressions from right to | |||
12427 | // left, we start with the required alignment (as required by the field | |||
12428 | // type) but some packed attribute in that chain has reduced the alignment. | |||
12429 | // It may happen that another packed structure increases it again. But if | |||
12430 | // we are here such increase has not been enough. So pointing the first | |||
12431 | // FieldDecl that either is packed or else its RecordDecl is, | |||
12432 | // seems reasonable. | |||
12433 | FieldDecl *FD = nullptr; | |||
12434 | CharUnits Alignment; | |||
12435 | for (FieldDecl *FDI : ReverseMemberChain) { | |||
12436 | if (FDI->hasAttr<PackedAttr>() || | |||
12437 | FDI->getParent()->hasAttr<PackedAttr>()) { | |||
12438 | FD = FDI; | |||
12439 | Alignment = std::min( | |||
12440 | Context.getTypeAlignInChars(FD->getType()), | |||
12441 | Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); | |||
12442 | break; | |||
12443 | } | |||
12444 | } | |||
12445 | assert(FD && "We did not find a packed FieldDecl!")((FD && "We did not find a packed FieldDecl!") ? static_cast <void> (0) : __assert_fail ("FD && \"We did not find a packed FieldDecl!\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaChecking.cpp" , 12445, __PRETTY_FUNCTION__)); | |||
12446 | Action(E, FD->getParent(), FD, Alignment); | |||
12447 | } | |||
12448 | } | |||
12449 | ||||
12450 | void Sema::CheckAddressOfPackedMember(Expr *rhs) { | |||
12451 | using namespace std::placeholders; | |||
12452 | RefersToMemberWithReducedAlignment( | |||
12453 | rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, | |||
12454 | _2, _3, _4)); | |||
12455 | } | |||
12456 |
1 | //===- llvm/ADT/SmallBitVector.h - 'Normally small' bit vectors -*- C++ -*-===// | |||||
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 the SmallBitVector class. | |||||
11 | // | |||||
12 | //===----------------------------------------------------------------------===// | |||||
13 | ||||||
14 | #ifndef LLVM_ADT_SMALLBITVECTOR_H | |||||
15 | #define LLVM_ADT_SMALLBITVECTOR_H | |||||
16 | ||||||
17 | #include "llvm/ADT/BitVector.h" | |||||
18 | #include "llvm/ADT/iterator_range.h" | |||||
19 | #include "llvm/Support/MathExtras.h" | |||||
20 | #include <algorithm> | |||||
21 | #include <cassert> | |||||
22 | #include <climits> | |||||
23 | #include <cstddef> | |||||
24 | #include <cstdint> | |||||
25 | #include <limits> | |||||
26 | #include <utility> | |||||
27 | ||||||
28 | namespace llvm { | |||||
29 | ||||||
30 | /// This is a 'bitvector' (really, a variable-sized bit array), optimized for | |||||
31 | /// the case when the array is small. It contains one pointer-sized field, which | |||||
32 | /// is directly used as a plain collection of bits when possible, or as a | |||||
33 | /// pointer to a larger heap-allocated array when necessary. This allows normal | |||||
34 | /// "small" cases to be fast without losing generality for large inputs. | |||||
35 | class SmallBitVector { | |||||
36 | // TODO: In "large" mode, a pointer to a BitVector is used, leading to an | |||||
37 | // unnecessary level of indirection. It would be more efficient to use a | |||||
38 | // pointer to memory containing size, allocation size, and the array of bits. | |||||
39 | uintptr_t X = 1; | |||||
40 | ||||||
41 | enum { | |||||
42 | // The number of bits in this class. | |||||
43 | NumBaseBits = sizeof(uintptr_t) * CHAR_BIT8, | |||||
44 | ||||||
45 | // One bit is used to discriminate between small and large mode. The | |||||
46 | // remaining bits are used for the small-mode representation. | |||||
47 | SmallNumRawBits = NumBaseBits - 1, | |||||
48 | ||||||
49 | // A few more bits are used to store the size of the bit set in small mode. | |||||
50 | // Theoretically this is a ceil-log2. These bits are encoded in the most | |||||
51 | // significant bits of the raw bits. | |||||
52 | SmallNumSizeBits = (NumBaseBits == 32 ? 5 : | |||||
53 | NumBaseBits == 64 ? 6 : | |||||
54 | SmallNumRawBits), | |||||
55 | ||||||
56 | // The remaining bits are used to store the actual set in small mode. | |||||
57 | SmallNumDataBits = SmallNumRawBits - SmallNumSizeBits | |||||
58 | }; | |||||
59 | ||||||
60 | static_assert(NumBaseBits == 64 || NumBaseBits == 32, | |||||
61 | "Unsupported word size"); | |||||
62 | ||||||
63 | public: | |||||
64 | using size_type = unsigned; | |||||
65 | ||||||
66 | // Encapsulation of a single bit. | |||||
67 | class reference { | |||||
68 | SmallBitVector &TheVector; | |||||
69 | unsigned BitPos; | |||||
70 | ||||||
71 | public: | |||||
72 | reference(SmallBitVector &b, unsigned Idx) : TheVector(b), BitPos(Idx) {} | |||||
73 | ||||||
74 | reference(const reference&) = default; | |||||
75 | ||||||
76 | reference& operator=(reference t) { | |||||
77 | *this = bool(t); | |||||
78 | return *this; | |||||
79 | } | |||||
80 | ||||||
81 | reference& operator=(bool t) { | |||||
82 | if (t) | |||||
83 | TheVector.set(BitPos); | |||||
84 | else | |||||
85 | TheVector.reset(BitPos); | |||||
86 | return *this; | |||||
87 | } | |||||
88 | ||||||
89 | operator bool() const { | |||||
90 | return const_cast<const SmallBitVector &>(TheVector).operator[](BitPos); | |||||
91 | } | |||||
92 | }; | |||||
93 | ||||||
94 | private: | |||||
95 | bool isSmall() const { | |||||
96 | return X & uintptr_t(1); | |||||
97 | } | |||||
98 | ||||||
99 | BitVector *getPointer() const { | |||||
100 | assert(!isSmall())((!isSmall()) ? static_cast<void> (0) : __assert_fail ( "!isSmall()", "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 100, __PRETTY_FUNCTION__)); | |||||
101 | return reinterpret_cast<BitVector *>(X); | |||||
102 | } | |||||
103 | ||||||
104 | void switchToSmall(uintptr_t NewSmallBits, size_t NewSize) { | |||||
105 | X = 1; | |||||
106 | setSmallSize(NewSize); | |||||
107 | setSmallBits(NewSmallBits); | |||||
108 | } | |||||
109 | ||||||
110 | void switchToLarge(BitVector *BV) { | |||||
111 | X = reinterpret_cast<uintptr_t>(BV); | |||||
112 | assert(!isSmall() && "Tried to use an unaligned pointer")((!isSmall() && "Tried to use an unaligned pointer") ? static_cast<void> (0) : __assert_fail ("!isSmall() && \"Tried to use an unaligned pointer\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 112, __PRETTY_FUNCTION__)); | |||||
| ||||||
113 | } | |||||
114 | ||||||
115 | // Return all the bits used for the "small" representation; this includes | |||||
116 | // bits for the size as well as the element bits. | |||||
117 | uintptr_t getSmallRawBits() const { | |||||
118 | assert(isSmall())((isSmall()) ? static_cast<void> (0) : __assert_fail ("isSmall()" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 118, __PRETTY_FUNCTION__)); | |||||
119 | return X >> 1; | |||||
120 | } | |||||
121 | ||||||
122 | void setSmallRawBits(uintptr_t NewRawBits) { | |||||
123 | assert(isSmall())((isSmall()) ? static_cast<void> (0) : __assert_fail ("isSmall()" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 123, __PRETTY_FUNCTION__)); | |||||
124 | X = (NewRawBits << 1) | uintptr_t(1); | |||||
125 | } | |||||
126 | ||||||
127 | // Return the size. | |||||
128 | size_t getSmallSize() const { return getSmallRawBits() >> SmallNumDataBits; } | |||||
129 | ||||||
130 | void setSmallSize(size_t Size) { | |||||
131 | setSmallRawBits(getSmallBits() | (Size << SmallNumDataBits)); | |||||
132 | } | |||||
133 | ||||||
134 | // Return the element bits. | |||||
135 | uintptr_t getSmallBits() const { | |||||
136 | return getSmallRawBits() & ~(~uintptr_t(0) << getSmallSize()); | |||||
137 | } | |||||
138 | ||||||
139 | void setSmallBits(uintptr_t NewBits) { | |||||
140 | setSmallRawBits((NewBits & ~(~uintptr_t(0) << getSmallSize())) | | |||||
141 | (getSmallSize() << SmallNumDataBits)); | |||||
142 | } | |||||
143 | ||||||
144 | public: | |||||
145 | /// Creates an empty bitvector. | |||||
146 | SmallBitVector() = default; | |||||
147 | ||||||
148 | /// Creates a bitvector of specified number of bits. All bits are initialized | |||||
149 | /// to the specified value. | |||||
150 | explicit SmallBitVector(unsigned s, bool t = false) { | |||||
151 | if (s <= SmallNumDataBits) | |||||
152 | switchToSmall(t ? ~uintptr_t(0) : 0, s); | |||||
153 | else | |||||
154 | switchToLarge(new BitVector(s, t)); | |||||
155 | } | |||||
156 | ||||||
157 | /// SmallBitVector copy ctor. | |||||
158 | SmallBitVector(const SmallBitVector &RHS) { | |||||
159 | if (RHS.isSmall()) | |||||
160 | X = RHS.X; | |||||
161 | else | |||||
162 | switchToLarge(new BitVector(*RHS.getPointer())); | |||||
163 | } | |||||
164 | ||||||
165 | SmallBitVector(SmallBitVector &&RHS) : X(RHS.X) { | |||||
166 | RHS.X = 1; | |||||
167 | } | |||||
168 | ||||||
169 | ~SmallBitVector() { | |||||
170 | if (!isSmall()) | |||||
171 | delete getPointer(); | |||||
172 | } | |||||
173 | ||||||
174 | using const_set_bits_iterator = const_set_bits_iterator_impl<SmallBitVector>; | |||||
175 | using set_iterator = const_set_bits_iterator; | |||||
176 | ||||||
177 | const_set_bits_iterator set_bits_begin() const { | |||||
178 | return const_set_bits_iterator(*this); | |||||
179 | } | |||||
180 | ||||||
181 | const_set_bits_iterator set_bits_end() const { | |||||
182 | return const_set_bits_iterator(*this, -1); | |||||
183 | } | |||||
184 | ||||||
185 | iterator_range<const_set_bits_iterator> set_bits() const { | |||||
186 | return make_range(set_bits_begin(), set_bits_end()); | |||||
187 | } | |||||
188 | ||||||
189 | /// Tests whether there are no bits in this bitvector. | |||||
190 | bool empty() const { | |||||
191 | return isSmall() ? getSmallSize() == 0 : getPointer()->empty(); | |||||
192 | } | |||||
193 | ||||||
194 | /// Returns the number of bits in this bitvector. | |||||
195 | size_t size() const { | |||||
196 | return isSmall() ? getSmallSize() : getPointer()->size(); | |||||
197 | } | |||||
198 | ||||||
199 | /// Returns the number of bits which are set. | |||||
200 | size_type count() const { | |||||
201 | if (isSmall()) { | |||||
202 | uintptr_t Bits = getSmallBits(); | |||||
203 | return countPopulation(Bits); | |||||
204 | } | |||||
205 | return getPointer()->count(); | |||||
206 | } | |||||
207 | ||||||
208 | /// Returns true if any bit is set. | |||||
209 | bool any() const { | |||||
210 | if (isSmall()) | |||||
211 | return getSmallBits() != 0; | |||||
212 | return getPointer()->any(); | |||||
213 | } | |||||
214 | ||||||
215 | /// Returns true if all bits are set. | |||||
216 | bool all() const { | |||||
217 | if (isSmall()) | |||||
218 | return getSmallBits() == (uintptr_t(1) << getSmallSize()) - 1; | |||||
219 | return getPointer()->all(); | |||||
220 | } | |||||
221 | ||||||
222 | /// Returns true if none of the bits are set. | |||||
223 | bool none() const { | |||||
224 | if (isSmall()) | |||||
225 | return getSmallBits() == 0; | |||||
226 | return getPointer()->none(); | |||||
227 | } | |||||
228 | ||||||
229 | /// Returns the index of the first set bit, -1 if none of the bits are set. | |||||
230 | int find_first() const { | |||||
231 | if (isSmall()) { | |||||
232 | uintptr_t Bits = getSmallBits(); | |||||
233 | if (Bits == 0) | |||||
234 | return -1; | |||||
235 | return countTrailingZeros(Bits); | |||||
236 | } | |||||
237 | return getPointer()->find_first(); | |||||
238 | } | |||||
239 | ||||||
240 | int find_last() const { | |||||
241 | if (isSmall()) { | |||||
242 | uintptr_t Bits = getSmallBits(); | |||||
243 | if (Bits == 0) | |||||
244 | return -1; | |||||
245 | return NumBaseBits - countLeadingZeros(Bits); | |||||
246 | } | |||||
247 | return getPointer()->find_last(); | |||||
248 | } | |||||
249 | ||||||
250 | /// Returns the index of the first unset bit, -1 if all of the bits are set. | |||||
251 | int find_first_unset() const { | |||||
252 | if (isSmall()) { | |||||
253 | if (count() == getSmallSize()) | |||||
254 | return -1; | |||||
255 | ||||||
256 | uintptr_t Bits = getSmallBits(); | |||||
257 | return countTrailingOnes(Bits); | |||||
258 | } | |||||
259 | return getPointer()->find_first_unset(); | |||||
260 | } | |||||
261 | ||||||
262 | int find_last_unset() const { | |||||
263 | if (isSmall()) { | |||||
264 | if (count() == getSmallSize()) | |||||
265 | return -1; | |||||
266 | ||||||
267 | uintptr_t Bits = getSmallBits(); | |||||
268 | return NumBaseBits - countLeadingOnes(Bits); | |||||
269 | } | |||||
270 | return getPointer()->find_last_unset(); | |||||
271 | } | |||||
272 | ||||||
273 | /// Returns the index of the next set bit following the "Prev" bit. | |||||
274 | /// Returns -1 if the next set bit is not found. | |||||
275 | int find_next(unsigned Prev) const { | |||||
276 | if (isSmall()) { | |||||
277 | uintptr_t Bits = getSmallBits(); | |||||
278 | // Mask off previous bits. | |||||
279 | Bits &= ~uintptr_t(0) << (Prev + 1); | |||||
280 | if (Bits == 0 || Prev + 1 >= getSmallSize()) | |||||
281 | return -1; | |||||
282 | return countTrailingZeros(Bits); | |||||
283 | } | |||||
284 | return getPointer()->find_next(Prev); | |||||
285 | } | |||||
286 | ||||||
287 | /// Returns the index of the next unset bit following the "Prev" bit. | |||||
288 | /// Returns -1 if the next unset bit is not found. | |||||
289 | int find_next_unset(unsigned Prev) const { | |||||
290 | if (isSmall()) { | |||||
291 | ++Prev; | |||||
292 | uintptr_t Bits = getSmallBits(); | |||||
293 | // Mask in previous bits. | |||||
294 | uintptr_t Mask = (1 << Prev) - 1; | |||||
295 | Bits |= Mask; | |||||
296 | ||||||
297 | if (Bits == ~uintptr_t(0) || Prev + 1 >= getSmallSize()) | |||||
298 | return -1; | |||||
299 | return countTrailingOnes(Bits); | |||||
300 | } | |||||
301 | return getPointer()->find_next_unset(Prev); | |||||
302 | } | |||||
303 | ||||||
304 | /// find_prev - Returns the index of the first set bit that precedes the | |||||
305 | /// the bit at \p PriorTo. Returns -1 if all previous bits are unset. | |||||
306 | int find_prev(unsigned PriorTo) const { | |||||
307 | if (isSmall()) { | |||||
308 | if (PriorTo == 0) | |||||
309 | return -1; | |||||
310 | ||||||
311 | --PriorTo; | |||||
312 | uintptr_t Bits = getSmallBits(); | |||||
313 | Bits &= maskTrailingOnes<uintptr_t>(PriorTo + 1); | |||||
314 | if (Bits == 0) | |||||
315 | return -1; | |||||
316 | ||||||
317 | return NumBaseBits - countLeadingZeros(Bits) - 1; | |||||
318 | } | |||||
319 | return getPointer()->find_prev(PriorTo); | |||||
320 | } | |||||
321 | ||||||
322 | /// Clear all bits. | |||||
323 | void clear() { | |||||
324 | if (!isSmall()) | |||||
325 | delete getPointer(); | |||||
326 | switchToSmall(0, 0); | |||||
327 | } | |||||
328 | ||||||
329 | /// Grow or shrink the bitvector. | |||||
330 | void resize(unsigned N, bool t = false) { | |||||
331 | if (!isSmall()) { | |||||
332 | getPointer()->resize(N, t); | |||||
333 | } else if (SmallNumDataBits >= N) { | |||||
334 | uintptr_t NewBits = t ? ~uintptr_t(0) << getSmallSize() : 0; | |||||
335 | setSmallSize(N); | |||||
336 | setSmallBits(NewBits | getSmallBits()); | |||||
337 | } else { | |||||
338 | BitVector *BV = new BitVector(N, t); | |||||
339 | uintptr_t OldBits = getSmallBits(); | |||||
340 | for (size_t i = 0, e = getSmallSize(); i != e; ++i) | |||||
341 | (*BV)[i] = (OldBits >> i) & 1; | |||||
342 | switchToLarge(BV); | |||||
343 | } | |||||
344 | } | |||||
345 | ||||||
346 | void reserve(unsigned N) { | |||||
347 | if (isSmall()) { | |||||
348 | if (N > SmallNumDataBits) { | |||||
349 | uintptr_t OldBits = getSmallRawBits(); | |||||
350 | size_t SmallSize = getSmallSize(); | |||||
351 | BitVector *BV = new BitVector(SmallSize); | |||||
352 | for (size_t i = 0; i < SmallSize; ++i) | |||||
353 | if ((OldBits >> i) & 1) | |||||
354 | BV->set(i); | |||||
355 | BV->reserve(N); | |||||
356 | switchToLarge(BV); | |||||
357 | } | |||||
358 | } else { | |||||
359 | getPointer()->reserve(N); | |||||
360 | } | |||||
361 | } | |||||
362 | ||||||
363 | // Set, reset, flip | |||||
364 | SmallBitVector &set() { | |||||
365 | if (isSmall()) | |||||
366 | setSmallBits(~uintptr_t(0)); | |||||
367 | else | |||||
368 | getPointer()->set(); | |||||
369 | return *this; | |||||
370 | } | |||||
371 | ||||||
372 | SmallBitVector &set(unsigned Idx) { | |||||
373 | if (isSmall()) { | |||||
374 | assert(Idx <= static_cast<unsigned>(((Idx <= static_cast<unsigned>( std::numeric_limits< uintptr_t>::digits) && "undefined behavior") ? static_cast <void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 376, __PRETTY_FUNCTION__)) | |||||
375 | std::numeric_limits<uintptr_t>::digits) &&((Idx <= static_cast<unsigned>( std::numeric_limits< uintptr_t>::digits) && "undefined behavior") ? static_cast <void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 376, __PRETTY_FUNCTION__)) | |||||
376 | "undefined behavior")((Idx <= static_cast<unsigned>( std::numeric_limits< uintptr_t>::digits) && "undefined behavior") ? static_cast <void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 376, __PRETTY_FUNCTION__)); | |||||
377 | setSmallBits(getSmallBits() | (uintptr_t(1) << Idx)); | |||||
378 | } | |||||
379 | else | |||||
380 | getPointer()->set(Idx); | |||||
381 | return *this; | |||||
382 | } | |||||
383 | ||||||
384 | /// Efficiently set a range of bits in [I, E) | |||||
385 | SmallBitVector &set(unsigned I, unsigned E) { | |||||
386 | assert(I <= E && "Attempted to set backwards range!")((I <= E && "Attempted to set backwards range!") ? static_cast<void> (0) : __assert_fail ("I <= E && \"Attempted to set backwards range!\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 386, __PRETTY_FUNCTION__)); | |||||
387 | assert(E <= size() && "Attempted to set out-of-bounds range!")((E <= size() && "Attempted to set out-of-bounds range!" ) ? static_cast<void> (0) : __assert_fail ("E <= size() && \"Attempted to set out-of-bounds range!\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 387, __PRETTY_FUNCTION__)); | |||||
388 | if (I == E) return *this; | |||||
389 | if (isSmall()) { | |||||
390 | uintptr_t EMask = ((uintptr_t)1) << E; | |||||
391 | uintptr_t IMask = ((uintptr_t)1) << I; | |||||
392 | uintptr_t Mask = EMask - IMask; | |||||
393 | setSmallBits(getSmallBits() | Mask); | |||||
394 | } else | |||||
395 | getPointer()->set(I, E); | |||||
396 | return *this; | |||||
397 | } | |||||
398 | ||||||
399 | SmallBitVector &reset() { | |||||
400 | if (isSmall()) | |||||
401 | setSmallBits(0); | |||||
402 | else | |||||
403 | getPointer()->reset(); | |||||
404 | return *this; | |||||
405 | } | |||||
406 | ||||||
407 | SmallBitVector &reset(unsigned Idx) { | |||||
408 | if (isSmall()) | |||||
409 | setSmallBits(getSmallBits() & ~(uintptr_t(1) << Idx)); | |||||
410 | else | |||||
411 | getPointer()->reset(Idx); | |||||
412 | return *this; | |||||
413 | } | |||||
414 | ||||||
415 | /// Efficiently reset a range of bits in [I, E) | |||||
416 | SmallBitVector &reset(unsigned I, unsigned E) { | |||||
417 | assert(I <= E && "Attempted to reset backwards range!")((I <= E && "Attempted to reset backwards range!") ? static_cast<void> (0) : __assert_fail ("I <= E && \"Attempted to reset backwards range!\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 417, __PRETTY_FUNCTION__)); | |||||
418 | assert(E <= size() && "Attempted to reset out-of-bounds range!")((E <= size() && "Attempted to reset out-of-bounds range!" ) ? static_cast<void> (0) : __assert_fail ("E <= size() && \"Attempted to reset out-of-bounds range!\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 418, __PRETTY_FUNCTION__)); | |||||
419 | if (I == E) return *this; | |||||
420 | if (isSmall()) { | |||||
421 | uintptr_t EMask = ((uintptr_t)1) << E; | |||||
422 | uintptr_t IMask = ((uintptr_t)1) << I; | |||||
423 | uintptr_t Mask = EMask - IMask; | |||||
424 | setSmallBits(getSmallBits() & ~Mask); | |||||
425 | } else | |||||
426 | getPointer()->reset(I, E); | |||||
427 | return *this; | |||||
428 | } | |||||
429 | ||||||
430 | SmallBitVector &flip() { | |||||
431 | if (isSmall()) | |||||
432 | setSmallBits(~getSmallBits()); | |||||
433 | else | |||||
434 | getPointer()->flip(); | |||||
435 | return *this; | |||||
436 | } | |||||
437 | ||||||
438 | SmallBitVector &flip(unsigned Idx) { | |||||
439 | if (isSmall()) | |||||
440 | setSmallBits(getSmallBits() ^ (uintptr_t(1) << Idx)); | |||||
441 | else | |||||
442 | getPointer()->flip(Idx); | |||||
443 | return *this; | |||||
444 | } | |||||
445 | ||||||
446 | // No argument flip. | |||||
447 | SmallBitVector operator~() const { | |||||
448 | return SmallBitVector(*this).flip(); | |||||
449 | } | |||||
450 | ||||||
451 | // Indexing. | |||||
452 | reference operator[](unsigned Idx) { | |||||
453 | assert(Idx < size() && "Out-of-bounds Bit access.")((Idx < size() && "Out-of-bounds Bit access.") ? static_cast <void> (0) : __assert_fail ("Idx < size() && \"Out-of-bounds Bit access.\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 453, __PRETTY_FUNCTION__)); | |||||
454 | return reference(*this, Idx); | |||||
455 | } | |||||
456 | ||||||
457 | bool operator[](unsigned Idx) const { | |||||
458 | assert(Idx < size() && "Out-of-bounds Bit access.")((Idx < size() && "Out-of-bounds Bit access.") ? static_cast <void> (0) : __assert_fail ("Idx < size() && \"Out-of-bounds Bit access.\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 458, __PRETTY_FUNCTION__)); | |||||
459 | if (isSmall()) | |||||
460 | return ((getSmallBits() >> Idx) & 1) != 0; | |||||
461 | return getPointer()->operator[](Idx); | |||||
462 | } | |||||
463 | ||||||
464 | bool test(unsigned Idx) const { | |||||
465 | return (*this)[Idx]; | |||||
466 | } | |||||
467 | ||||||
468 | /// Test if any common bits are set. | |||||
469 | bool anyCommon(const SmallBitVector &RHS) const { | |||||
470 | if (isSmall() && RHS.isSmall()) | |||||
471 | return (getSmallBits() & RHS.getSmallBits()) != 0; | |||||
472 | if (!isSmall() && !RHS.isSmall()) | |||||
473 | return getPointer()->anyCommon(*RHS.getPointer()); | |||||
474 | ||||||
475 | for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i) | |||||
476 | if (test(i) && RHS.test(i)) | |||||
477 | return true; | |||||
478 | return false; | |||||
479 | } | |||||
480 | ||||||
481 | // Comparison operators. | |||||
482 | bool operator==(const SmallBitVector &RHS) const { | |||||
483 | if (size() != RHS.size()) | |||||
484 | return false; | |||||
485 | if (isSmall()) | |||||
486 | return getSmallBits() == RHS.getSmallBits(); | |||||
487 | else | |||||
488 | return *getPointer() == *RHS.getPointer(); | |||||
489 | } | |||||
490 | ||||||
491 | bool operator!=(const SmallBitVector &RHS) const { | |||||
492 | return !(*this == RHS); | |||||
493 | } | |||||
494 | ||||||
495 | // Intersection, union, disjoint union. | |||||
496 | SmallBitVector &operator&=(const SmallBitVector &RHS) { | |||||
497 | resize(std::max(size(), RHS.size())); | |||||
498 | if (isSmall()) | |||||
499 | setSmallBits(getSmallBits() & RHS.getSmallBits()); | |||||
500 | else if (!RHS.isSmall()) | |||||
501 | getPointer()->operator&=(*RHS.getPointer()); | |||||
502 | else { | |||||
503 | SmallBitVector Copy = RHS; | |||||
504 | Copy.resize(size()); | |||||
505 | getPointer()->operator&=(*Copy.getPointer()); | |||||
506 | } | |||||
507 | return *this; | |||||
508 | } | |||||
509 | ||||||
510 | /// Reset bits that are set in RHS. Same as *this &= ~RHS. | |||||
511 | SmallBitVector &reset(const SmallBitVector &RHS) { | |||||
512 | if (isSmall() && RHS.isSmall()) | |||||
513 | setSmallBits(getSmallBits() & ~RHS.getSmallBits()); | |||||
514 | else if (!isSmall() && !RHS.isSmall()) | |||||
515 | getPointer()->reset(*RHS.getPointer()); | |||||
516 | else | |||||
517 | for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i) | |||||
518 | if (RHS.test(i)) | |||||
519 | reset(i); | |||||
520 | ||||||
521 | return *this; | |||||
522 | } | |||||
523 | ||||||
524 | /// Check if (This - RHS) is zero. This is the same as reset(RHS) and any(). | |||||
525 | bool test(const SmallBitVector &RHS) const { | |||||
526 | if (isSmall() && RHS.isSmall()) | |||||
527 | return (getSmallBits() & ~RHS.getSmallBits()) != 0; | |||||
528 | if (!isSmall() && !RHS.isSmall()) | |||||
529 | return getPointer()->test(*RHS.getPointer()); | |||||
530 | ||||||
531 | unsigned i, e; | |||||
532 | for (i = 0, e = std::min(size(), RHS.size()); i != e; ++i) | |||||
533 | if (test(i) && !RHS.test(i)) | |||||
534 | return true; | |||||
535 | ||||||
536 | for (e = size(); i != e; ++i) | |||||
537 | if (test(i)) | |||||
538 | return true; | |||||
539 | ||||||
540 | return false; | |||||
541 | } | |||||
542 | ||||||
543 | SmallBitVector &operator|=(const SmallBitVector &RHS) { | |||||
544 | resize(std::max(size(), RHS.size())); | |||||
545 | if (isSmall()) | |||||
546 | setSmallBits(getSmallBits() | RHS.getSmallBits()); | |||||
547 | else if (!RHS.isSmall()) | |||||
548 | getPointer()->operator|=(*RHS.getPointer()); | |||||
549 | else { | |||||
550 | SmallBitVector Copy = RHS; | |||||
551 | Copy.resize(size()); | |||||
552 | getPointer()->operator|=(*Copy.getPointer()); | |||||
553 | } | |||||
554 | return *this; | |||||
555 | } | |||||
556 | ||||||
557 | SmallBitVector &operator^=(const SmallBitVector &RHS) { | |||||
558 | resize(std::max(size(), RHS.size())); | |||||
559 | if (isSmall()) | |||||
560 | setSmallBits(getSmallBits() ^ RHS.getSmallBits()); | |||||
561 | else if (!RHS.isSmall()) | |||||
562 | getPointer()->operator^=(*RHS.getPointer()); | |||||
563 | else { | |||||
564 | SmallBitVector Copy = RHS; | |||||
565 | Copy.resize(size()); | |||||
566 | getPointer()->operator^=(*Copy.getPointer()); | |||||
567 | } | |||||
568 | return *this; | |||||
569 | } | |||||
570 | ||||||
571 | SmallBitVector &operator<<=(unsigned N) { | |||||
572 | if (isSmall()) | |||||
573 | setSmallBits(getSmallBits() << N); | |||||
574 | else | |||||
575 | getPointer()->operator<<=(N); | |||||
576 | return *this; | |||||
577 | } | |||||
578 | ||||||
579 | SmallBitVector &operator>>=(unsigned N) { | |||||
580 | if (isSmall()) | |||||
581 | setSmallBits(getSmallBits() >> N); | |||||
582 | else | |||||
583 | getPointer()->operator>>=(N); | |||||
584 | return *this; | |||||
585 | } | |||||
586 | ||||||
587 | // Assignment operator. | |||||
588 | const SmallBitVector &operator=(const SmallBitVector &RHS) { | |||||
589 | if (isSmall()) { | |||||
590 | if (RHS.isSmall()) | |||||
591 | X = RHS.X; | |||||
592 | else | |||||
593 | switchToLarge(new BitVector(*RHS.getPointer())); | |||||
594 | } else { | |||||
595 | if (!RHS.isSmall()) | |||||
596 | *getPointer() = *RHS.getPointer(); | |||||
597 | else { | |||||
598 | delete getPointer(); | |||||
599 | X = RHS.X; | |||||
600 | } | |||||
601 | } | |||||
602 | return *this; | |||||
603 | } | |||||
604 | ||||||
605 | const SmallBitVector &operator=(SmallBitVector &&RHS) { | |||||
606 | if (this != &RHS) { | |||||
607 | clear(); | |||||
608 | swap(RHS); | |||||
609 | } | |||||
610 | return *this; | |||||
611 | } | |||||
612 | ||||||
613 | void swap(SmallBitVector &RHS) { | |||||
614 | std::swap(X, RHS.X); | |||||
615 | } | |||||
616 | ||||||
617 | /// Add '1' bits from Mask to this vector. Don't resize. | |||||
618 | /// This computes "*this |= Mask". | |||||
619 | void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) { | |||||
620 | if (isSmall()) | |||||
621 | applyMask<true, false>(Mask, MaskWords); | |||||
622 | else | |||||
623 | getPointer()->setBitsInMask(Mask, MaskWords); | |||||
624 | } | |||||
625 | ||||||
626 | /// Clear any bits in this vector that are set in Mask. Don't resize. | |||||
627 | /// This computes "*this &= ~Mask". | |||||
628 | void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) { | |||||
629 | if (isSmall()) | |||||
630 | applyMask<false, false>(Mask, MaskWords); | |||||
631 | else | |||||
632 | getPointer()->clearBitsInMask(Mask, MaskWords); | |||||
633 | } | |||||
634 | ||||||
635 | /// Add a bit to this vector for every '0' bit in Mask. Don't resize. | |||||
636 | /// This computes "*this |= ~Mask". | |||||
637 | void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) { | |||||
638 | if (isSmall()) | |||||
639 | applyMask<true, true>(Mask, MaskWords); | |||||
640 | else | |||||
641 | getPointer()->setBitsNotInMask(Mask, MaskWords); | |||||
642 | } | |||||
643 | ||||||
644 | /// Clear a bit in this vector for every '0' bit in Mask. Don't resize. | |||||
645 | /// This computes "*this &= Mask". | |||||
646 | void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) { | |||||
647 | if (isSmall()) | |||||
648 | applyMask<false, true>(Mask, MaskWords); | |||||
649 | else | |||||
650 | getPointer()->clearBitsNotInMask(Mask, MaskWords); | |||||
651 | } | |||||
652 | ||||||
653 | private: | |||||
654 | template <bool AddBits, bool InvertMask> | |||||
655 | void applyMask(const uint32_t *Mask, unsigned MaskWords) { | |||||
656 | assert(MaskWords <= sizeof(uintptr_t) && "Mask is larger than base!")((MaskWords <= sizeof(uintptr_t) && "Mask is larger than base!" ) ? static_cast<void> (0) : __assert_fail ("MaskWords <= sizeof(uintptr_t) && \"Mask is larger than base!\"" , "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/SmallBitVector.h" , 656, __PRETTY_FUNCTION__)); | |||||
657 | uintptr_t M = Mask[0]; | |||||
658 | if (NumBaseBits == 64) | |||||
659 | M |= uint64_t(Mask[1]) << 32; | |||||
660 | if (InvertMask) | |||||
661 | M = ~M; | |||||
662 | if (AddBits) | |||||
663 | setSmallBits(getSmallBits() | M); | |||||
664 | else | |||||
665 | setSmallBits(getSmallBits() & ~M); | |||||
666 | } | |||||
667 | }; | |||||
668 | ||||||
669 | inline SmallBitVector | |||||
670 | operator&(const SmallBitVector &LHS, const SmallBitVector &RHS) { | |||||
671 | SmallBitVector Result(LHS); | |||||
672 | Result &= RHS; | |||||
673 | return Result; | |||||
674 | } | |||||
675 | ||||||
676 | inline SmallBitVector | |||||
677 | operator|(const SmallBitVector &LHS, const SmallBitVector &RHS) { | |||||
678 | SmallBitVector Result(LHS); | |||||
679 | Result |= RHS; | |||||
680 | return Result; | |||||
681 | } | |||||
682 | ||||||
683 | inline SmallBitVector | |||||
684 | operator^(const SmallBitVector &LHS, const SmallBitVector &RHS) { | |||||
685 | SmallBitVector Result(LHS); | |||||
686 | Result ^= RHS; | |||||
687 | return Result; | |||||
688 | } | |||||
689 | ||||||
690 | } // end namespace llvm | |||||
691 | ||||||
692 | namespace std { | |||||
693 | ||||||
694 | /// Implement std::swap in terms of BitVector swap. | |||||
695 | inline void | |||||
696 | swap(llvm::SmallBitVector &LHS, llvm::SmallBitVector &RHS) { | |||||
697 | LHS.swap(RHS); | |||||
698 | } | |||||
699 | ||||||
700 | } // end namespace std | |||||
701 | ||||||
702 | #endif // LLVM_ADT_SMALLBITVECTOR_H |