File: | clang/lib/Sema/SemaChecking.cpp |
Warning: | line 10304, column 7 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file implements extra semantic analysis beyond what is enforced | |||
10 | // by the C type system. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "clang/AST/APValue.h" | |||
15 | #include "clang/AST/ASTContext.h" | |||
16 | #include "clang/AST/Attr.h" | |||
17 | #include "clang/AST/AttrIterator.h" | |||
18 | #include "clang/AST/CharUnits.h" | |||
19 | #include "clang/AST/Decl.h" | |||
20 | #include "clang/AST/DeclBase.h" | |||
21 | #include "clang/AST/DeclCXX.h" | |||
22 | #include "clang/AST/DeclObjC.h" | |||
23 | #include "clang/AST/DeclarationName.h" | |||
24 | #include "clang/AST/EvaluatedExprVisitor.h" | |||
25 | #include "clang/AST/Expr.h" | |||
26 | #include "clang/AST/ExprCXX.h" | |||
27 | #include "clang/AST/ExprObjC.h" | |||
28 | #include "clang/AST/ExprOpenMP.h" | |||
29 | #include "clang/AST/FormatString.h" | |||
30 | #include "clang/AST/NSAPI.h" | |||
31 | #include "clang/AST/NonTrivialTypeVisitor.h" | |||
32 | #include "clang/AST/OperationKinds.h" | |||
33 | #include "clang/AST/RecordLayout.h" | |||
34 | #include "clang/AST/Stmt.h" | |||
35 | #include "clang/AST/TemplateBase.h" | |||
36 | #include "clang/AST/Type.h" | |||
37 | #include "clang/AST/TypeLoc.h" | |||
38 | #include "clang/AST/UnresolvedSet.h" | |||
39 | #include "clang/Basic/AddressSpaces.h" | |||
40 | #include "clang/Basic/CharInfo.h" | |||
41 | #include "clang/Basic/Diagnostic.h" | |||
42 | #include "clang/Basic/IdentifierTable.h" | |||
43 | #include "clang/Basic/LLVM.h" | |||
44 | #include "clang/Basic/LangOptions.h" | |||
45 | #include "clang/Basic/OpenCLOptions.h" | |||
46 | #include "clang/Basic/OperatorKinds.h" | |||
47 | #include "clang/Basic/PartialDiagnostic.h" | |||
48 | #include "clang/Basic/SourceLocation.h" | |||
49 | #include "clang/Basic/SourceManager.h" | |||
50 | #include "clang/Basic/Specifiers.h" | |||
51 | #include "clang/Basic/SyncScope.h" | |||
52 | #include "clang/Basic/TargetBuiltins.h" | |||
53 | #include "clang/Basic/TargetCXXABI.h" | |||
54 | #include "clang/Basic/TargetInfo.h" | |||
55 | #include "clang/Basic/TypeTraits.h" | |||
56 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. | |||
57 | #include "clang/Sema/Initialization.h" | |||
58 | #include "clang/Sema/Lookup.h" | |||
59 | #include "clang/Sema/Ownership.h" | |||
60 | #include "clang/Sema/Scope.h" | |||
61 | #include "clang/Sema/ScopeInfo.h" | |||
62 | #include "clang/Sema/Sema.h" | |||
63 | #include "clang/Sema/SemaInternal.h" | |||
64 | #include "llvm/ADT/APFloat.h" | |||
65 | #include "llvm/ADT/APInt.h" | |||
66 | #include "llvm/ADT/APSInt.h" | |||
67 | #include "llvm/ADT/ArrayRef.h" | |||
68 | #include "llvm/ADT/DenseMap.h" | |||
69 | #include "llvm/ADT/FoldingSet.h" | |||
70 | #include "llvm/ADT/None.h" | |||
71 | #include "llvm/ADT/Optional.h" | |||
72 | #include "llvm/ADT/STLExtras.h" | |||
73 | #include "llvm/ADT/SmallBitVector.h" | |||
74 | #include "llvm/ADT/SmallPtrSet.h" | |||
75 | #include "llvm/ADT/SmallString.h" | |||
76 | #include "llvm/ADT/SmallVector.h" | |||
77 | #include "llvm/ADT/StringRef.h" | |||
78 | #include "llvm/ADT/StringSet.h" | |||
79 | #include "llvm/ADT/StringSwitch.h" | |||
80 | #include "llvm/ADT/Triple.h" | |||
81 | #include "llvm/Support/AtomicOrdering.h" | |||
82 | #include "llvm/Support/Casting.h" | |||
83 | #include "llvm/Support/Compiler.h" | |||
84 | #include "llvm/Support/ConvertUTF.h" | |||
85 | #include "llvm/Support/ErrorHandling.h" | |||
86 | #include "llvm/Support/Format.h" | |||
87 | #include "llvm/Support/Locale.h" | |||
88 | #include "llvm/Support/MathExtras.h" | |||
89 | #include "llvm/Support/SaveAndRestore.h" | |||
90 | #include "llvm/Support/raw_ostream.h" | |||
91 | #include <algorithm> | |||
92 | #include <bitset> | |||
93 | #include <cassert> | |||
94 | #include <cstddef> | |||
95 | #include <cstdint> | |||
96 | #include <functional> | |||
97 | #include <limits> | |||
98 | #include <string> | |||
99 | #include <tuple> | |||
100 | #include <utility> | |||
101 | ||||
102 | using namespace clang; | |||
103 | using namespace sema; | |||
104 | ||||
105 | SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, | |||
106 | unsigned ByteNo) const { | |||
107 | return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, | |||
108 | Context.getTargetInfo()); | |||
109 | } | |||
110 | ||||
111 | /// Checks that a call expression's argument count is the desired number. | |||
112 | /// This is useful when doing custom type-checking. Returns true on error. | |||
113 | static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { | |||
114 | unsigned argCount = call->getNumArgs(); | |||
115 | if (argCount == desiredArgCount) return false; | |||
116 | ||||
117 | if (argCount < desiredArgCount) | |||
118 | return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) | |||
119 | << 0 /*function call*/ << desiredArgCount << argCount | |||
120 | << call->getSourceRange(); | |||
121 | ||||
122 | // Highlight all the excess arguments. | |||
123 | SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), | |||
124 | call->getArg(argCount - 1)->getEndLoc()); | |||
125 | ||||
126 | return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) | |||
127 | << 0 /*function call*/ << desiredArgCount << argCount | |||
128 | << call->getArg(1)->getSourceRange(); | |||
129 | } | |||
130 | ||||
131 | /// Check that the first argument to __builtin_annotation is an integer | |||
132 | /// and the second argument is a non-wide string literal. | |||
133 | static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { | |||
134 | if (checkArgCount(S, TheCall, 2)) | |||
135 | return true; | |||
136 | ||||
137 | // First argument should be an integer. | |||
138 | Expr *ValArg = TheCall->getArg(0); | |||
139 | QualType Ty = ValArg->getType(); | |||
140 | if (!Ty->isIntegerType()) { | |||
141 | S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) | |||
142 | << ValArg->getSourceRange(); | |||
143 | return true; | |||
144 | } | |||
145 | ||||
146 | // Second argument should be a constant string. | |||
147 | Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); | |||
148 | StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); | |||
149 | if (!Literal || !Literal->isAscii()) { | |||
150 | S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) | |||
151 | << StrArg->getSourceRange(); | |||
152 | return true; | |||
153 | } | |||
154 | ||||
155 | TheCall->setType(Ty); | |||
156 | return false; | |||
157 | } | |||
158 | ||||
159 | static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { | |||
160 | // We need at least one argument. | |||
161 | if (TheCall->getNumArgs() < 1) { | |||
162 | S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) | |||
163 | << 0 << 1 << TheCall->getNumArgs() | |||
164 | << TheCall->getCallee()->getSourceRange(); | |||
165 | return true; | |||
166 | } | |||
167 | ||||
168 | // All arguments should be wide string literals. | |||
169 | for (Expr *Arg : TheCall->arguments()) { | |||
170 | auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); | |||
171 | if (!Literal || !Literal->isWide()) { | |||
172 | S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) | |||
173 | << Arg->getSourceRange(); | |||
174 | return true; | |||
175 | } | |||
176 | } | |||
177 | ||||
178 | return false; | |||
179 | } | |||
180 | ||||
181 | /// Check that the argument to __builtin_addressof is a glvalue, and set the | |||
182 | /// result type to the corresponding pointer type. | |||
183 | static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { | |||
184 | if (checkArgCount(S, TheCall, 1)) | |||
185 | return true; | |||
186 | ||||
187 | ExprResult Arg(TheCall->getArg(0)); | |||
188 | QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); | |||
189 | if (ResultType.isNull()) | |||
190 | return true; | |||
191 | ||||
192 | TheCall->setArg(0, Arg.get()); | |||
193 | TheCall->setType(ResultType); | |||
194 | return false; | |||
195 | } | |||
196 | ||||
197 | /// Check the number of arguments and set the result type to | |||
198 | /// the argument type. | |||
199 | static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { | |||
200 | if (checkArgCount(S, TheCall, 1)) | |||
201 | return true; | |||
202 | ||||
203 | TheCall->setType(TheCall->getArg(0)->getType()); | |||
204 | return false; | |||
205 | } | |||
206 | ||||
207 | /// Check that the value argument for __builtin_is_aligned(value, alignment) and | |||
208 | /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer | |||
209 | /// type (but not a function pointer) and that the alignment is a power-of-two. | |||
210 | static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { | |||
211 | if (checkArgCount(S, TheCall, 2)) | |||
212 | return true; | |||
213 | ||||
214 | clang::Expr *Source = TheCall->getArg(0); | |||
215 | bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; | |||
216 | ||||
217 | auto IsValidIntegerType = [](QualType Ty) { | |||
218 | return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); | |||
219 | }; | |||
220 | QualType SrcTy = Source->getType(); | |||
221 | // We should also be able to use it with arrays (but not functions!). | |||
222 | if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { | |||
223 | SrcTy = S.Context.getDecayedType(SrcTy); | |||
224 | } | |||
225 | if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || | |||
226 | SrcTy->isFunctionPointerType()) { | |||
227 | // FIXME: this is not quite the right error message since we don't allow | |||
228 | // floating point types, or member pointers. | |||
229 | S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) | |||
230 | << SrcTy; | |||
231 | return true; | |||
232 | } | |||
233 | ||||
234 | clang::Expr *AlignOp = TheCall->getArg(1); | |||
235 | if (!IsValidIntegerType(AlignOp->getType())) { | |||
236 | S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) | |||
237 | << AlignOp->getType(); | |||
238 | return true; | |||
239 | } | |||
240 | Expr::EvalResult AlignResult; | |||
241 | unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; | |||
242 | // We can't check validity of alignment if it is value dependent. | |||
243 | if (!AlignOp->isValueDependent() && | |||
244 | AlignOp->EvaluateAsInt(AlignResult, S.Context, | |||
245 | Expr::SE_AllowSideEffects)) { | |||
246 | llvm::APSInt AlignValue = AlignResult.Val.getInt(); | |||
247 | llvm::APSInt MaxValue( | |||
248 | llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); | |||
249 | if (AlignValue < 1) { | |||
250 | S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; | |||
251 | return true; | |||
252 | } | |||
253 | if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { | |||
254 | S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) | |||
255 | << MaxValue.toString(10); | |||
256 | return true; | |||
257 | } | |||
258 | if (!AlignValue.isPowerOf2()) { | |||
259 | S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); | |||
260 | return true; | |||
261 | } | |||
262 | if (AlignValue == 1) { | |||
263 | S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) | |||
264 | << IsBooleanAlignBuiltin; | |||
265 | } | |||
266 | } | |||
267 | ||||
268 | ExprResult SrcArg = S.PerformCopyInitialization( | |||
269 | InitializedEntity::InitializeParameter(S.Context, SrcTy, false), | |||
270 | SourceLocation(), Source); | |||
271 | if (SrcArg.isInvalid()) | |||
272 | return true; | |||
273 | TheCall->setArg(0, SrcArg.get()); | |||
274 | ExprResult AlignArg = | |||
275 | S.PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
276 | S.Context, AlignOp->getType(), false), | |||
277 | SourceLocation(), AlignOp); | |||
278 | if (AlignArg.isInvalid()) | |||
279 | return true; | |||
280 | TheCall->setArg(1, AlignArg.get()); | |||
281 | // For align_up/align_down, the return type is the same as the (potentially | |||
282 | // decayed) argument type including qualifiers. For is_aligned(), the result | |||
283 | // is always bool. | |||
284 | TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); | |||
285 | return false; | |||
286 | } | |||
287 | ||||
288 | static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, | |||
289 | unsigned BuiltinID) { | |||
290 | if (checkArgCount(S, TheCall, 3)) | |||
291 | return true; | |||
292 | ||||
293 | // First two arguments should be integers. | |||
294 | for (unsigned I = 0; I < 2; ++I) { | |||
295 | ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); | |||
296 | if (Arg.isInvalid()) return true; | |||
297 | TheCall->setArg(I, Arg.get()); | |||
298 | ||||
299 | QualType Ty = Arg.get()->getType(); | |||
300 | if (!Ty->isIntegerType()) { | |||
301 | S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) | |||
302 | << Ty << Arg.get()->getSourceRange(); | |||
303 | return true; | |||
304 | } | |||
305 | } | |||
306 | ||||
307 | // Third argument should be a pointer to a non-const integer. | |||
308 | // IRGen correctly handles volatile, restrict, and address spaces, and | |||
309 | // the other qualifiers aren't possible. | |||
310 | { | |||
311 | ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); | |||
312 | if (Arg.isInvalid()) return true; | |||
313 | TheCall->setArg(2, Arg.get()); | |||
314 | ||||
315 | QualType Ty = Arg.get()->getType(); | |||
316 | const auto *PtrTy = Ty->getAs<PointerType>(); | |||
317 | if (!PtrTy || | |||
318 | !PtrTy->getPointeeType()->isIntegerType() || | |||
319 | PtrTy->getPointeeType().isConstQualified()) { | |||
320 | S.Diag(Arg.get()->getBeginLoc(), | |||
321 | diag::err_overflow_builtin_must_be_ptr_int) | |||
322 | << Ty << Arg.get()->getSourceRange(); | |||
323 | return true; | |||
324 | } | |||
325 | } | |||
326 | ||||
327 | // Disallow signed ExtIntType args larger than 128 bits to mul function until | |||
328 | // we improve backend support. | |||
329 | if (BuiltinID == Builtin::BI__builtin_mul_overflow) { | |||
330 | for (unsigned I = 0; I < 3; ++I) { | |||
331 | const auto Arg = TheCall->getArg(I); | |||
332 | // Third argument will be a pointer. | |||
333 | auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); | |||
334 | if (Ty->isExtIntType() && Ty->isSignedIntegerType() && | |||
335 | S.getASTContext().getIntWidth(Ty) > 128) | |||
336 | return S.Diag(Arg->getBeginLoc(), | |||
337 | diag::err_overflow_builtin_ext_int_max_size) | |||
338 | << 128; | |||
339 | } | |||
340 | } | |||
341 | ||||
342 | return false; | |||
343 | } | |||
344 | ||||
345 | static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { | |||
346 | if (checkArgCount(S, BuiltinCall, 2)) | |||
347 | return true; | |||
348 | ||||
349 | SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); | |||
350 | Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); | |||
351 | Expr *Call = BuiltinCall->getArg(0); | |||
352 | Expr *Chain = BuiltinCall->getArg(1); | |||
353 | ||||
354 | if (Call->getStmtClass() != Stmt::CallExprClass) { | |||
355 | S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) | |||
356 | << Call->getSourceRange(); | |||
357 | return true; | |||
358 | } | |||
359 | ||||
360 | auto CE = cast<CallExpr>(Call); | |||
361 | if (CE->getCallee()->getType()->isBlockPointerType()) { | |||
362 | S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) | |||
363 | << Call->getSourceRange(); | |||
364 | return true; | |||
365 | } | |||
366 | ||||
367 | const Decl *TargetDecl = CE->getCalleeDecl(); | |||
368 | if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) | |||
369 | if (FD->getBuiltinID()) { | |||
370 | S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) | |||
371 | << Call->getSourceRange(); | |||
372 | return true; | |||
373 | } | |||
374 | ||||
375 | if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { | |||
376 | S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) | |||
377 | << Call->getSourceRange(); | |||
378 | return true; | |||
379 | } | |||
380 | ||||
381 | ExprResult ChainResult = S.UsualUnaryConversions(Chain); | |||
382 | if (ChainResult.isInvalid()) | |||
383 | return true; | |||
384 | if (!ChainResult.get()->getType()->isPointerType()) { | |||
385 | S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) | |||
386 | << Chain->getSourceRange(); | |||
387 | return true; | |||
388 | } | |||
389 | ||||
390 | QualType ReturnTy = CE->getCallReturnType(S.Context); | |||
391 | QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; | |||
392 | QualType BuiltinTy = S.Context.getFunctionType( | |||
393 | ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); | |||
394 | QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); | |||
395 | ||||
396 | Builtin = | |||
397 | S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); | |||
398 | ||||
399 | BuiltinCall->setType(CE->getType()); | |||
400 | BuiltinCall->setValueKind(CE->getValueKind()); | |||
401 | BuiltinCall->setObjectKind(CE->getObjectKind()); | |||
402 | BuiltinCall->setCallee(Builtin); | |||
403 | BuiltinCall->setArg(1, ChainResult.get()); | |||
404 | ||||
405 | return false; | |||
406 | } | |||
407 | ||||
408 | namespace { | |||
409 | ||||
410 | class EstimateSizeFormatHandler | |||
411 | : public analyze_format_string::FormatStringHandler { | |||
412 | size_t Size; | |||
413 | ||||
414 | public: | |||
415 | EstimateSizeFormatHandler(StringRef Format) | |||
416 | : Size(std::min(Format.find(0), Format.size()) + | |||
417 | 1 /* null byte always written by sprintf */) {} | |||
418 | ||||
419 | bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, | |||
420 | const char *, unsigned SpecifierLen) override { | |||
421 | ||||
422 | const size_t FieldWidth = computeFieldWidth(FS); | |||
423 | const size_t Precision = computePrecision(FS); | |||
424 | ||||
425 | // The actual format. | |||
426 | switch (FS.getConversionSpecifier().getKind()) { | |||
427 | // Just a char. | |||
428 | case analyze_format_string::ConversionSpecifier::cArg: | |||
429 | case analyze_format_string::ConversionSpecifier::CArg: | |||
430 | Size += std::max(FieldWidth, (size_t)1); | |||
431 | break; | |||
432 | // Just an integer. | |||
433 | case analyze_format_string::ConversionSpecifier::dArg: | |||
434 | case analyze_format_string::ConversionSpecifier::DArg: | |||
435 | case analyze_format_string::ConversionSpecifier::iArg: | |||
436 | case analyze_format_string::ConversionSpecifier::oArg: | |||
437 | case analyze_format_string::ConversionSpecifier::OArg: | |||
438 | case analyze_format_string::ConversionSpecifier::uArg: | |||
439 | case analyze_format_string::ConversionSpecifier::UArg: | |||
440 | case analyze_format_string::ConversionSpecifier::xArg: | |||
441 | case analyze_format_string::ConversionSpecifier::XArg: | |||
442 | Size += std::max(FieldWidth, Precision); | |||
443 | break; | |||
444 | ||||
445 | // %g style conversion switches between %f or %e style dynamically. | |||
446 | // %f always takes less space, so default to it. | |||
447 | case analyze_format_string::ConversionSpecifier::gArg: | |||
448 | case analyze_format_string::ConversionSpecifier::GArg: | |||
449 | ||||
450 | // Floating point number in the form '[+]ddd.ddd'. | |||
451 | case analyze_format_string::ConversionSpecifier::fArg: | |||
452 | case analyze_format_string::ConversionSpecifier::FArg: | |||
453 | Size += std::max(FieldWidth, 1 /* integer part */ + | |||
454 | (Precision ? 1 + Precision | |||
455 | : 0) /* period + decimal */); | |||
456 | break; | |||
457 | ||||
458 | // Floating point number in the form '[-]d.ddde[+-]dd'. | |||
459 | case analyze_format_string::ConversionSpecifier::eArg: | |||
460 | case analyze_format_string::ConversionSpecifier::EArg: | |||
461 | Size += | |||
462 | std::max(FieldWidth, | |||
463 | 1 /* integer part */ + | |||
464 | (Precision ? 1 + Precision : 0) /* period + decimal */ + | |||
465 | 1 /* e or E letter */ + 2 /* exponent */); | |||
466 | break; | |||
467 | ||||
468 | // Floating point number in the form '[-]0xh.hhhhp±dd'. | |||
469 | case analyze_format_string::ConversionSpecifier::aArg: | |||
470 | case analyze_format_string::ConversionSpecifier::AArg: | |||
471 | Size += | |||
472 | std::max(FieldWidth, | |||
473 | 2 /* 0x */ + 1 /* integer part */ + | |||
474 | (Precision ? 1 + Precision : 0) /* period + decimal */ + | |||
475 | 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); | |||
476 | break; | |||
477 | ||||
478 | // Just a string. | |||
479 | case analyze_format_string::ConversionSpecifier::sArg: | |||
480 | case analyze_format_string::ConversionSpecifier::SArg: | |||
481 | Size += FieldWidth; | |||
482 | break; | |||
483 | ||||
484 | // Just a pointer in the form '0xddd'. | |||
485 | case analyze_format_string::ConversionSpecifier::pArg: | |||
486 | Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); | |||
487 | break; | |||
488 | ||||
489 | // A plain percent. | |||
490 | case analyze_format_string::ConversionSpecifier::PercentArg: | |||
491 | Size += 1; | |||
492 | break; | |||
493 | ||||
494 | default: | |||
495 | break; | |||
496 | } | |||
497 | ||||
498 | Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); | |||
499 | ||||
500 | if (FS.hasAlternativeForm()) { | |||
501 | switch (FS.getConversionSpecifier().getKind()) { | |||
502 | default: | |||
503 | break; | |||
504 | // Force a leading '0'. | |||
505 | case analyze_format_string::ConversionSpecifier::oArg: | |||
506 | Size += 1; | |||
507 | break; | |||
508 | // Force a leading '0x'. | |||
509 | case analyze_format_string::ConversionSpecifier::xArg: | |||
510 | case analyze_format_string::ConversionSpecifier::XArg: | |||
511 | Size += 2; | |||
512 | break; | |||
513 | // Force a period '.' before decimal, even if precision is 0. | |||
514 | case analyze_format_string::ConversionSpecifier::aArg: | |||
515 | case analyze_format_string::ConversionSpecifier::AArg: | |||
516 | case analyze_format_string::ConversionSpecifier::eArg: | |||
517 | case analyze_format_string::ConversionSpecifier::EArg: | |||
518 | case analyze_format_string::ConversionSpecifier::fArg: | |||
519 | case analyze_format_string::ConversionSpecifier::FArg: | |||
520 | case analyze_format_string::ConversionSpecifier::gArg: | |||
521 | case analyze_format_string::ConversionSpecifier::GArg: | |||
522 | Size += (Precision ? 0 : 1); | |||
523 | break; | |||
524 | } | |||
525 | } | |||
526 | assert(SpecifierLen <= Size && "no underflow")((SpecifierLen <= Size && "no underflow") ? static_cast <void> (0) : __assert_fail ("SpecifierLen <= Size && \"no underflow\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 526, __PRETTY_FUNCTION__)); | |||
527 | Size -= SpecifierLen; | |||
528 | return true; | |||
529 | } | |||
530 | ||||
531 | size_t getSizeLowerBound() const { return Size; } | |||
532 | ||||
533 | private: | |||
534 | static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { | |||
535 | const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); | |||
536 | size_t FieldWidth = 0; | |||
537 | if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) | |||
538 | FieldWidth = FW.getConstantAmount(); | |||
539 | return FieldWidth; | |||
540 | } | |||
541 | ||||
542 | static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { | |||
543 | const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); | |||
544 | size_t Precision = 0; | |||
545 | ||||
546 | // See man 3 printf for default precision value based on the specifier. | |||
547 | switch (FW.getHowSpecified()) { | |||
548 | case analyze_format_string::OptionalAmount::NotSpecified: | |||
549 | switch (FS.getConversionSpecifier().getKind()) { | |||
550 | default: | |||
551 | break; | |||
552 | case analyze_format_string::ConversionSpecifier::dArg: // %d | |||
553 | case analyze_format_string::ConversionSpecifier::DArg: // %D | |||
554 | case analyze_format_string::ConversionSpecifier::iArg: // %i | |||
555 | Precision = 1; | |||
556 | break; | |||
557 | case analyze_format_string::ConversionSpecifier::oArg: // %d | |||
558 | case analyze_format_string::ConversionSpecifier::OArg: // %D | |||
559 | case analyze_format_string::ConversionSpecifier::uArg: // %d | |||
560 | case analyze_format_string::ConversionSpecifier::UArg: // %D | |||
561 | case analyze_format_string::ConversionSpecifier::xArg: // %d | |||
562 | case analyze_format_string::ConversionSpecifier::XArg: // %D | |||
563 | Precision = 1; | |||
564 | break; | |||
565 | case analyze_format_string::ConversionSpecifier::fArg: // %f | |||
566 | case analyze_format_string::ConversionSpecifier::FArg: // %F | |||
567 | case analyze_format_string::ConversionSpecifier::eArg: // %e | |||
568 | case analyze_format_string::ConversionSpecifier::EArg: // %E | |||
569 | case analyze_format_string::ConversionSpecifier::gArg: // %g | |||
570 | case analyze_format_string::ConversionSpecifier::GArg: // %G | |||
571 | Precision = 6; | |||
572 | break; | |||
573 | case analyze_format_string::ConversionSpecifier::pArg: // %d | |||
574 | Precision = 1; | |||
575 | break; | |||
576 | } | |||
577 | break; | |||
578 | case analyze_format_string::OptionalAmount::Constant: | |||
579 | Precision = FW.getConstantAmount(); | |||
580 | break; | |||
581 | default: | |||
582 | break; | |||
583 | } | |||
584 | return Precision; | |||
585 | } | |||
586 | }; | |||
587 | ||||
588 | } // namespace | |||
589 | ||||
590 | /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a | |||
591 | /// __builtin_*_chk function, then use the object size argument specified in the | |||
592 | /// source. Otherwise, infer the object size using __builtin_object_size. | |||
593 | void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, | |||
594 | CallExpr *TheCall) { | |||
595 | // FIXME: There are some more useful checks we could be doing here: | |||
596 | // - Evaluate strlen of strcpy arguments, use as object size. | |||
597 | ||||
598 | if (TheCall->isValueDependent() || TheCall->isTypeDependent() || | |||
599 | isConstantEvaluated()) | |||
600 | return; | |||
601 | ||||
602 | unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); | |||
603 | if (!BuiltinID) | |||
604 | return; | |||
605 | ||||
606 | const TargetInfo &TI = getASTContext().getTargetInfo(); | |||
607 | unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); | |||
608 | ||||
609 | unsigned DiagID = 0; | |||
610 | bool IsChkVariant = false; | |||
611 | Optional<llvm::APSInt> UsedSize; | |||
612 | unsigned SizeIndex, ObjectIndex; | |||
613 | switch (BuiltinID) { | |||
614 | default: | |||
615 | return; | |||
616 | case Builtin::BIsprintf: | |||
617 | case Builtin::BI__builtin___sprintf_chk: { | |||
618 | size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; | |||
619 | auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); | |||
620 | ||||
621 | if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { | |||
622 | ||||
623 | if (!Format->isAscii() && !Format->isUTF8()) | |||
624 | return; | |||
625 | ||||
626 | StringRef FormatStrRef = Format->getString(); | |||
627 | EstimateSizeFormatHandler H(FormatStrRef); | |||
628 | const char *FormatBytes = FormatStrRef.data(); | |||
629 | const ConstantArrayType *T = | |||
630 | Context.getAsConstantArrayType(Format->getType()); | |||
631 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 631, __PRETTY_FUNCTION__)); | |||
632 | size_t TypeSize = T->getSize().getZExtValue(); | |||
633 | ||||
634 | // In case there's a null byte somewhere. | |||
635 | size_t StrLen = | |||
636 | std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); | |||
637 | if (!analyze_format_string::ParsePrintfString( | |||
638 | H, FormatBytes, FormatBytes + StrLen, getLangOpts(), | |||
639 | Context.getTargetInfo(), false)) { | |||
640 | DiagID = diag::warn_fortify_source_format_overflow; | |||
641 | UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) | |||
642 | .extOrTrunc(SizeTypeWidth); | |||
643 | if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { | |||
644 | IsChkVariant = true; | |||
645 | ObjectIndex = 2; | |||
646 | } else { | |||
647 | IsChkVariant = false; | |||
648 | ObjectIndex = 0; | |||
649 | } | |||
650 | break; | |||
651 | } | |||
652 | } | |||
653 | return; | |||
654 | } | |||
655 | case Builtin::BI__builtin___memcpy_chk: | |||
656 | case Builtin::BI__builtin___memmove_chk: | |||
657 | case Builtin::BI__builtin___memset_chk: | |||
658 | // case Builtin::BI__builtin___strlcat_chk: | |||
659 | // case Builtin::BI__builtin___strlcpy_chk: | |||
660 | case Builtin::BI__builtin___strncat_chk: | |||
661 | case Builtin::BI__builtin___strncpy_chk: | |||
662 | case Builtin::BI__builtin___stpncpy_chk: | |||
663 | case Builtin::BI__builtin___memccpy_chk: | |||
664 | case Builtin::BI__builtin___mempcpy_chk: { | |||
665 | DiagID = diag::warn_builtin_chk_overflow; | |||
666 | IsChkVariant = true; | |||
667 | SizeIndex = TheCall->getNumArgs() - 2; | |||
668 | ObjectIndex = TheCall->getNumArgs() - 1; | |||
669 | break; | |||
670 | } | |||
671 | ||||
672 | case Builtin::BI__builtin___snprintf_chk: | |||
673 | case Builtin::BI__builtin___vsnprintf_chk: { | |||
674 | DiagID = diag::warn_builtin_chk_overflow; | |||
675 | IsChkVariant = true; | |||
676 | SizeIndex = 1; | |||
677 | ObjectIndex = 3; | |||
678 | break; | |||
679 | } | |||
680 | ||||
681 | case Builtin::BIstrncat: | |||
682 | case Builtin::BI__builtin_strncat: | |||
683 | case Builtin::BIstrncpy: | |||
684 | case Builtin::BI__builtin_strncpy: | |||
685 | case Builtin::BIstpncpy: | |||
686 | case Builtin::BI__builtin_stpncpy: { | |||
687 | // Whether these functions overflow depends on the runtime strlen of the | |||
688 | // string, not just the buffer size, so emitting the "always overflow" | |||
689 | // diagnostic isn't quite right. We should still diagnose passing a buffer | |||
690 | // size larger than the destination buffer though; this is a runtime abort | |||
691 | // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. | |||
692 | DiagID = diag::warn_fortify_source_size_mismatch; | |||
693 | SizeIndex = TheCall->getNumArgs() - 1; | |||
694 | ObjectIndex = 0; | |||
695 | break; | |||
696 | } | |||
697 | ||||
698 | case Builtin::BImemcpy: | |||
699 | case Builtin::BI__builtin_memcpy: | |||
700 | case Builtin::BImemmove: | |||
701 | case Builtin::BI__builtin_memmove: | |||
702 | case Builtin::BImemset: | |||
703 | case Builtin::BI__builtin_memset: | |||
704 | case Builtin::BImempcpy: | |||
705 | case Builtin::BI__builtin_mempcpy: { | |||
706 | DiagID = diag::warn_fortify_source_overflow; | |||
707 | SizeIndex = TheCall->getNumArgs() - 1; | |||
708 | ObjectIndex = 0; | |||
709 | break; | |||
710 | } | |||
711 | case Builtin::BIsnprintf: | |||
712 | case Builtin::BI__builtin_snprintf: | |||
713 | case Builtin::BIvsnprintf: | |||
714 | case Builtin::BI__builtin_vsnprintf: { | |||
715 | DiagID = diag::warn_fortify_source_size_mismatch; | |||
716 | SizeIndex = 1; | |||
717 | ObjectIndex = 0; | |||
718 | break; | |||
719 | } | |||
720 | } | |||
721 | ||||
722 | llvm::APSInt ObjectSize; | |||
723 | // For __builtin___*_chk, the object size is explicitly provided by the caller | |||
724 | // (usually using __builtin_object_size). Use that value to check this call. | |||
725 | if (IsChkVariant) { | |||
726 | Expr::EvalResult Result; | |||
727 | Expr *SizeArg = TheCall->getArg(ObjectIndex); | |||
728 | if (!SizeArg->EvaluateAsInt(Result, getASTContext())) | |||
729 | return; | |||
730 | ObjectSize = Result.Val.getInt(); | |||
731 | ||||
732 | // Otherwise, try to evaluate an imaginary call to __builtin_object_size. | |||
733 | } else { | |||
734 | // If the parameter has a pass_object_size attribute, then we should use its | |||
735 | // (potentially) more strict checking mode. Otherwise, conservatively assume | |||
736 | // type 0. | |||
737 | int BOSType = 0; | |||
738 | if (const auto *POS = | |||
739 | FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) | |||
740 | BOSType = POS->getType(); | |||
741 | ||||
742 | Expr *ObjArg = TheCall->getArg(ObjectIndex); | |||
743 | uint64_t Result; | |||
744 | if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) | |||
745 | return; | |||
746 | // Get the object size in the target's size_t width. | |||
747 | ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); | |||
748 | } | |||
749 | ||||
750 | // Evaluate the number of bytes of the object that this call will use. | |||
751 | if (!UsedSize) { | |||
752 | Expr::EvalResult Result; | |||
753 | Expr *UsedSizeArg = TheCall->getArg(SizeIndex); | |||
754 | if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) | |||
755 | return; | |||
756 | UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); | |||
757 | } | |||
758 | ||||
759 | if (UsedSize.getValue().ule(ObjectSize)) | |||
760 | return; | |||
761 | ||||
762 | StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); | |||
763 | // Skim off the details of whichever builtin was called to produce a better | |||
764 | // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. | |||
765 | if (IsChkVariant) { | |||
766 | FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); | |||
767 | FunctionName = FunctionName.drop_back(std::strlen("_chk")); | |||
768 | } else if (FunctionName.startswith("__builtin_")) { | |||
769 | FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); | |||
770 | } | |||
771 | ||||
772 | DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, | |||
773 | PDiag(DiagID) | |||
774 | << FunctionName << ObjectSize.toString(/*Radix=*/10) | |||
775 | << UsedSize.getValue().toString(/*Radix=*/10)); | |||
776 | } | |||
777 | ||||
778 | static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, | |||
779 | Scope::ScopeFlags NeededScopeFlags, | |||
780 | unsigned DiagID) { | |||
781 | // Scopes aren't available during instantiation. Fortunately, builtin | |||
782 | // functions cannot be template args so they cannot be formed through template | |||
783 | // instantiation. Therefore checking once during the parse is sufficient. | |||
784 | if (SemaRef.inTemplateInstantiation()) | |||
785 | return false; | |||
786 | ||||
787 | Scope *S = SemaRef.getCurScope(); | |||
788 | while (S && !S->isSEHExceptScope()) | |||
789 | S = S->getParent(); | |||
790 | if (!S || !(S->getFlags() & NeededScopeFlags)) { | |||
791 | auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); | |||
792 | SemaRef.Diag(TheCall->getExprLoc(), DiagID) | |||
793 | << DRE->getDecl()->getIdentifier(); | |||
794 | return true; | |||
795 | } | |||
796 | ||||
797 | return false; | |||
798 | } | |||
799 | ||||
800 | static inline bool isBlockPointer(Expr *Arg) { | |||
801 | return Arg->getType()->isBlockPointerType(); | |||
802 | } | |||
803 | ||||
804 | /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local | |||
805 | /// void*, which is a requirement of device side enqueue. | |||
806 | static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { | |||
807 | const BlockPointerType *BPT = | |||
808 | cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); | |||
809 | ArrayRef<QualType> Params = | |||
810 | BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); | |||
811 | unsigned ArgCounter = 0; | |||
812 | bool IllegalParams = false; | |||
813 | // Iterate through the block parameters until either one is found that is not | |||
814 | // a local void*, or the block is valid. | |||
815 | for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); | |||
816 | I != E; ++I, ++ArgCounter) { | |||
817 | if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || | |||
818 | (*I)->getPointeeType().getQualifiers().getAddressSpace() != | |||
819 | LangAS::opencl_local) { | |||
820 | // Get the location of the error. If a block literal has been passed | |||
821 | // (BlockExpr) then we can point straight to the offending argument, | |||
822 | // else we just point to the variable reference. | |||
823 | SourceLocation ErrorLoc; | |||
824 | if (isa<BlockExpr>(BlockArg)) { | |||
825 | BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); | |||
826 | ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); | |||
827 | } else if (isa<DeclRefExpr>(BlockArg)) { | |||
828 | ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); | |||
829 | } | |||
830 | S.Diag(ErrorLoc, | |||
831 | diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); | |||
832 | IllegalParams = true; | |||
833 | } | |||
834 | } | |||
835 | ||||
836 | return IllegalParams; | |||
837 | } | |||
838 | ||||
839 | static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { | |||
840 | if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { | |||
841 | S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) | |||
842 | << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; | |||
843 | return true; | |||
844 | } | |||
845 | return false; | |||
846 | } | |||
847 | ||||
848 | static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { | |||
849 | if (checkArgCount(S, TheCall, 2)) | |||
850 | return true; | |||
851 | ||||
852 | if (checkOpenCLSubgroupExt(S, TheCall)) | |||
853 | return true; | |||
854 | ||||
855 | // First argument is an ndrange_t type. | |||
856 | Expr *NDRangeArg = TheCall->getArg(0); | |||
857 | if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { | |||
858 | S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) | |||
859 | << TheCall->getDirectCallee() << "'ndrange_t'"; | |||
860 | return true; | |||
861 | } | |||
862 | ||||
863 | Expr *BlockArg = TheCall->getArg(1); | |||
864 | if (!isBlockPointer(BlockArg)) { | |||
865 | S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) | |||
866 | << TheCall->getDirectCallee() << "block"; | |||
867 | return true; | |||
868 | } | |||
869 | return checkOpenCLBlockArgs(S, BlockArg); | |||
870 | } | |||
871 | ||||
872 | /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the | |||
873 | /// get_kernel_work_group_size | |||
874 | /// and get_kernel_preferred_work_group_size_multiple builtin functions. | |||
875 | static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { | |||
876 | if (checkArgCount(S, TheCall, 1)) | |||
877 | return true; | |||
878 | ||||
879 | Expr *BlockArg = TheCall->getArg(0); | |||
880 | if (!isBlockPointer(BlockArg)) { | |||
881 | S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) | |||
882 | << TheCall->getDirectCallee() << "block"; | |||
883 | return true; | |||
884 | } | |||
885 | return checkOpenCLBlockArgs(S, BlockArg); | |||
886 | } | |||
887 | ||||
888 | /// Diagnose integer type and any valid implicit conversion to it. | |||
889 | static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, | |||
890 | const QualType &IntType); | |||
891 | ||||
892 | static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, | |||
893 | unsigned Start, unsigned End) { | |||
894 | bool IllegalParams = false; | |||
895 | for (unsigned I = Start; I <= End; ++I) | |||
896 | IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), | |||
897 | S.Context.getSizeType()); | |||
898 | return IllegalParams; | |||
899 | } | |||
900 | ||||
901 | /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all | |||
902 | /// 'local void*' parameter of passed block. | |||
903 | static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, | |||
904 | Expr *BlockArg, | |||
905 | unsigned NumNonVarArgs) { | |||
906 | const BlockPointerType *BPT = | |||
907 | cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); | |||
908 | unsigned NumBlockParams = | |||
909 | BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); | |||
910 | unsigned TotalNumArgs = TheCall->getNumArgs(); | |||
911 | ||||
912 | // For each argument passed to the block, a corresponding uint needs to | |||
913 | // be passed to describe the size of the local memory. | |||
914 | if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { | |||
915 | S.Diag(TheCall->getBeginLoc(), | |||
916 | diag::err_opencl_enqueue_kernel_local_size_args); | |||
917 | return true; | |||
918 | } | |||
919 | ||||
920 | // Check that the sizes of the local memory are specified by integers. | |||
921 | return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, | |||
922 | TotalNumArgs - 1); | |||
923 | } | |||
924 | ||||
925 | /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different | |||
926 | /// overload formats specified in Table 6.13.17.1. | |||
927 | /// int enqueue_kernel(queue_t queue, | |||
928 | /// kernel_enqueue_flags_t flags, | |||
929 | /// const ndrange_t ndrange, | |||
930 | /// void (^block)(void)) | |||
931 | /// int enqueue_kernel(queue_t queue, | |||
932 | /// kernel_enqueue_flags_t flags, | |||
933 | /// const ndrange_t ndrange, | |||
934 | /// uint num_events_in_wait_list, | |||
935 | /// clk_event_t *event_wait_list, | |||
936 | /// clk_event_t *event_ret, | |||
937 | /// void (^block)(void)) | |||
938 | /// int enqueue_kernel(queue_t queue, | |||
939 | /// kernel_enqueue_flags_t flags, | |||
940 | /// const ndrange_t ndrange, | |||
941 | /// void (^block)(local void*, ...), | |||
942 | /// uint size0, ...) | |||
943 | /// int enqueue_kernel(queue_t queue, | |||
944 | /// kernel_enqueue_flags_t flags, | |||
945 | /// const ndrange_t ndrange, | |||
946 | /// uint num_events_in_wait_list, | |||
947 | /// clk_event_t *event_wait_list, | |||
948 | /// clk_event_t *event_ret, | |||
949 | /// void (^block)(local void*, ...), | |||
950 | /// uint size0, ...) | |||
951 | static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { | |||
952 | unsigned NumArgs = TheCall->getNumArgs(); | |||
953 | ||||
954 | if (NumArgs < 4) { | |||
955 | S.Diag(TheCall->getBeginLoc(), | |||
956 | diag::err_typecheck_call_too_few_args_at_least) | |||
957 | << 0 << 4 << NumArgs; | |||
958 | return true; | |||
959 | } | |||
960 | ||||
961 | Expr *Arg0 = TheCall->getArg(0); | |||
962 | Expr *Arg1 = TheCall->getArg(1); | |||
963 | Expr *Arg2 = TheCall->getArg(2); | |||
964 | Expr *Arg3 = TheCall->getArg(3); | |||
965 | ||||
966 | // First argument always needs to be a queue_t type. | |||
967 | if (!Arg0->getType()->isQueueT()) { | |||
968 | S.Diag(TheCall->getArg(0)->getBeginLoc(), | |||
969 | diag::err_opencl_builtin_expected_type) | |||
970 | << TheCall->getDirectCallee() << S.Context.OCLQueueTy; | |||
971 | return true; | |||
972 | } | |||
973 | ||||
974 | // Second argument always needs to be a kernel_enqueue_flags_t enum value. | |||
975 | if (!Arg1->getType()->isIntegerType()) { | |||
976 | S.Diag(TheCall->getArg(1)->getBeginLoc(), | |||
977 | diag::err_opencl_builtin_expected_type) | |||
978 | << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; | |||
979 | return true; | |||
980 | } | |||
981 | ||||
982 | // Third argument is always an ndrange_t type. | |||
983 | if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { | |||
984 | S.Diag(TheCall->getArg(2)->getBeginLoc(), | |||
985 | diag::err_opencl_builtin_expected_type) | |||
986 | << TheCall->getDirectCallee() << "'ndrange_t'"; | |||
987 | return true; | |||
988 | } | |||
989 | ||||
990 | // With four arguments, there is only one form that the function could be | |||
991 | // called in: no events and no variable arguments. | |||
992 | if (NumArgs == 4) { | |||
993 | // check that the last argument is the right block type. | |||
994 | if (!isBlockPointer(Arg3)) { | |||
995 | S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) | |||
996 | << TheCall->getDirectCallee() << "block"; | |||
997 | return true; | |||
998 | } | |||
999 | // we have a block type, check the prototype | |||
1000 | const BlockPointerType *BPT = | |||
1001 | cast<BlockPointerType>(Arg3->getType().getCanonicalType()); | |||
1002 | if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { | |||
1003 | S.Diag(Arg3->getBeginLoc(), | |||
1004 | diag::err_opencl_enqueue_kernel_blocks_no_args); | |||
1005 | return true; | |||
1006 | } | |||
1007 | return false; | |||
1008 | } | |||
1009 | // we can have block + varargs. | |||
1010 | if (isBlockPointer(Arg3)) | |||
1011 | return (checkOpenCLBlockArgs(S, Arg3) || | |||
1012 | checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); | |||
1013 | // last two cases with either exactly 7 args or 7 args and varargs. | |||
1014 | if (NumArgs >= 7) { | |||
1015 | // check common block argument. | |||
1016 | Expr *Arg6 = TheCall->getArg(6); | |||
1017 | if (!isBlockPointer(Arg6)) { | |||
1018 | S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) | |||
1019 | << TheCall->getDirectCallee() << "block"; | |||
1020 | return true; | |||
1021 | } | |||
1022 | if (checkOpenCLBlockArgs(S, Arg6)) | |||
1023 | return true; | |||
1024 | ||||
1025 | // Forth argument has to be any integer type. | |||
1026 | if (!Arg3->getType()->isIntegerType()) { | |||
1027 | S.Diag(TheCall->getArg(3)->getBeginLoc(), | |||
1028 | diag::err_opencl_builtin_expected_type) | |||
1029 | << TheCall->getDirectCallee() << "integer"; | |||
1030 | return true; | |||
1031 | } | |||
1032 | // check remaining common arguments. | |||
1033 | Expr *Arg4 = TheCall->getArg(4); | |||
1034 | Expr *Arg5 = TheCall->getArg(5); | |||
1035 | ||||
1036 | // Fifth argument is always passed as a pointer to clk_event_t. | |||
1037 | if (!Arg4->isNullPointerConstant(S.Context, | |||
1038 | Expr::NPC_ValueDependentIsNotNull) && | |||
1039 | !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { | |||
1040 | S.Diag(TheCall->getArg(4)->getBeginLoc(), | |||
1041 | diag::err_opencl_builtin_expected_type) | |||
1042 | << TheCall->getDirectCallee() | |||
1043 | << S.Context.getPointerType(S.Context.OCLClkEventTy); | |||
1044 | return true; | |||
1045 | } | |||
1046 | ||||
1047 | // Sixth argument is always passed as a pointer to clk_event_t. | |||
1048 | if (!Arg5->isNullPointerConstant(S.Context, | |||
1049 | Expr::NPC_ValueDependentIsNotNull) && | |||
1050 | !(Arg5->getType()->isPointerType() && | |||
1051 | Arg5->getType()->getPointeeType()->isClkEventT())) { | |||
1052 | S.Diag(TheCall->getArg(5)->getBeginLoc(), | |||
1053 | diag::err_opencl_builtin_expected_type) | |||
1054 | << TheCall->getDirectCallee() | |||
1055 | << S.Context.getPointerType(S.Context.OCLClkEventTy); | |||
1056 | return true; | |||
1057 | } | |||
1058 | ||||
1059 | if (NumArgs == 7) | |||
1060 | return false; | |||
1061 | ||||
1062 | return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); | |||
1063 | } | |||
1064 | ||||
1065 | // None of the specific case has been detected, give generic error | |||
1066 | S.Diag(TheCall->getBeginLoc(), | |||
1067 | diag::err_opencl_enqueue_kernel_incorrect_args); | |||
1068 | return true; | |||
1069 | } | |||
1070 | ||||
1071 | /// Returns OpenCL access qual. | |||
1072 | static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { | |||
1073 | return D->getAttr<OpenCLAccessAttr>(); | |||
1074 | } | |||
1075 | ||||
1076 | /// Returns true if pipe element type is different from the pointer. | |||
1077 | static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { | |||
1078 | const Expr *Arg0 = Call->getArg(0); | |||
1079 | // First argument type should always be pipe. | |||
1080 | if (!Arg0->getType()->isPipeType()) { | |||
1081 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) | |||
1082 | << Call->getDirectCallee() << Arg0->getSourceRange(); | |||
1083 | return true; | |||
1084 | } | |||
1085 | OpenCLAccessAttr *AccessQual = | |||
1086 | getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); | |||
1087 | // Validates the access qualifier is compatible with the call. | |||
1088 | // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be | |||
1089 | // read_only and write_only, and assumed to be read_only if no qualifier is | |||
1090 | // specified. | |||
1091 | switch (Call->getDirectCallee()->getBuiltinID()) { | |||
1092 | case Builtin::BIread_pipe: | |||
1093 | case Builtin::BIreserve_read_pipe: | |||
1094 | case Builtin::BIcommit_read_pipe: | |||
1095 | case Builtin::BIwork_group_reserve_read_pipe: | |||
1096 | case Builtin::BIsub_group_reserve_read_pipe: | |||
1097 | case Builtin::BIwork_group_commit_read_pipe: | |||
1098 | case Builtin::BIsub_group_commit_read_pipe: | |||
1099 | if (!(!AccessQual || AccessQual->isReadOnly())) { | |||
1100 | S.Diag(Arg0->getBeginLoc(), | |||
1101 | diag::err_opencl_builtin_pipe_invalid_access_modifier) | |||
1102 | << "read_only" << Arg0->getSourceRange(); | |||
1103 | return true; | |||
1104 | } | |||
1105 | break; | |||
1106 | case Builtin::BIwrite_pipe: | |||
1107 | case Builtin::BIreserve_write_pipe: | |||
1108 | case Builtin::BIcommit_write_pipe: | |||
1109 | case Builtin::BIwork_group_reserve_write_pipe: | |||
1110 | case Builtin::BIsub_group_reserve_write_pipe: | |||
1111 | case Builtin::BIwork_group_commit_write_pipe: | |||
1112 | case Builtin::BIsub_group_commit_write_pipe: | |||
1113 | if (!(AccessQual && AccessQual->isWriteOnly())) { | |||
1114 | S.Diag(Arg0->getBeginLoc(), | |||
1115 | diag::err_opencl_builtin_pipe_invalid_access_modifier) | |||
1116 | << "write_only" << Arg0->getSourceRange(); | |||
1117 | return true; | |||
1118 | } | |||
1119 | break; | |||
1120 | default: | |||
1121 | break; | |||
1122 | } | |||
1123 | return false; | |||
1124 | } | |||
1125 | ||||
1126 | /// Returns true if pipe element type is different from the pointer. | |||
1127 | static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { | |||
1128 | const Expr *Arg0 = Call->getArg(0); | |||
1129 | const Expr *ArgIdx = Call->getArg(Idx); | |||
1130 | const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); | |||
1131 | const QualType EltTy = PipeTy->getElementType(); | |||
1132 | const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); | |||
1133 | // The Idx argument should be a pointer and the type of the pointer and | |||
1134 | // the type of pipe element should also be the same. | |||
1135 | if (!ArgTy || | |||
1136 | !S.Context.hasSameType( | |||
1137 | EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { | |||
1138 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
1139 | << Call->getDirectCallee() << S.Context.getPointerType(EltTy) | |||
1140 | << ArgIdx->getType() << ArgIdx->getSourceRange(); | |||
1141 | return true; | |||
1142 | } | |||
1143 | return false; | |||
1144 | } | |||
1145 | ||||
1146 | // Performs semantic analysis for the read/write_pipe call. | |||
1147 | // \param S Reference to the semantic analyzer. | |||
1148 | // \param Call A pointer to the builtin call. | |||
1149 | // \return True if a semantic error has been found, false otherwise. | |||
1150 | static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { | |||
1151 | // OpenCL v2.0 s6.13.16.2 - The built-in read/write | |||
1152 | // functions have two forms. | |||
1153 | switch (Call->getNumArgs()) { | |||
1154 | case 2: | |||
1155 | if (checkOpenCLPipeArg(S, Call)) | |||
1156 | return true; | |||
1157 | // The call with 2 arguments should be | |||
1158 | // read/write_pipe(pipe T, T*). | |||
1159 | // Check packet type T. | |||
1160 | if (checkOpenCLPipePacketType(S, Call, 1)) | |||
1161 | return true; | |||
1162 | break; | |||
1163 | ||||
1164 | case 4: { | |||
1165 | if (checkOpenCLPipeArg(S, Call)) | |||
1166 | return true; | |||
1167 | // The call with 4 arguments should be | |||
1168 | // read/write_pipe(pipe T, reserve_id_t, uint, T*). | |||
1169 | // Check reserve_id_t. | |||
1170 | if (!Call->getArg(1)->getType()->isReserveIDT()) { | |||
1171 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
1172 | << Call->getDirectCallee() << S.Context.OCLReserveIDTy | |||
1173 | << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); | |||
1174 | return true; | |||
1175 | } | |||
1176 | ||||
1177 | // Check the index. | |||
1178 | const Expr *Arg2 = Call->getArg(2); | |||
1179 | if (!Arg2->getType()->isIntegerType() && | |||
1180 | !Arg2->getType()->isUnsignedIntegerType()) { | |||
1181 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
1182 | << Call->getDirectCallee() << S.Context.UnsignedIntTy | |||
1183 | << Arg2->getType() << Arg2->getSourceRange(); | |||
1184 | return true; | |||
1185 | } | |||
1186 | ||||
1187 | // Check packet type T. | |||
1188 | if (checkOpenCLPipePacketType(S, Call, 3)) | |||
1189 | return true; | |||
1190 | } break; | |||
1191 | default: | |||
1192 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) | |||
1193 | << Call->getDirectCallee() << Call->getSourceRange(); | |||
1194 | return true; | |||
1195 | } | |||
1196 | ||||
1197 | return false; | |||
1198 | } | |||
1199 | ||||
1200 | // Performs a semantic analysis on the {work_group_/sub_group_ | |||
1201 | // /_}reserve_{read/write}_pipe | |||
1202 | // \param S Reference to the semantic analyzer. | |||
1203 | // \param Call The call to the builtin function to be analyzed. | |||
1204 | // \return True if a semantic error was found, false otherwise. | |||
1205 | static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { | |||
1206 | if (checkArgCount(S, Call, 2)) | |||
1207 | return true; | |||
1208 | ||||
1209 | if (checkOpenCLPipeArg(S, Call)) | |||
1210 | return true; | |||
1211 | ||||
1212 | // Check the reserve size. | |||
1213 | if (!Call->getArg(1)->getType()->isIntegerType() && | |||
1214 | !Call->getArg(1)->getType()->isUnsignedIntegerType()) { | |||
1215 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
1216 | << Call->getDirectCallee() << S.Context.UnsignedIntTy | |||
1217 | << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); | |||
1218 | return true; | |||
1219 | } | |||
1220 | ||||
1221 | // Since return type of reserve_read/write_pipe built-in function is | |||
1222 | // reserve_id_t, which is not defined in the builtin def file , we used int | |||
1223 | // as return type and need to override the return type of these functions. | |||
1224 | Call->setType(S.Context.OCLReserveIDTy); | |||
1225 | ||||
1226 | return false; | |||
1227 | } | |||
1228 | ||||
1229 | // Performs a semantic analysis on {work_group_/sub_group_ | |||
1230 | // /_}commit_{read/write}_pipe | |||
1231 | // \param S Reference to the semantic analyzer. | |||
1232 | // \param Call The call to the builtin function to be analyzed. | |||
1233 | // \return True if a semantic error was found, false otherwise. | |||
1234 | static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { | |||
1235 | if (checkArgCount(S, Call, 2)) | |||
1236 | return true; | |||
1237 | ||||
1238 | if (checkOpenCLPipeArg(S, Call)) | |||
1239 | return true; | |||
1240 | ||||
1241 | // Check reserve_id_t. | |||
1242 | if (!Call->getArg(1)->getType()->isReserveIDT()) { | |||
1243 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) | |||
1244 | << Call->getDirectCallee() << S.Context.OCLReserveIDTy | |||
1245 | << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); | |||
1246 | return true; | |||
1247 | } | |||
1248 | ||||
1249 | return false; | |||
1250 | } | |||
1251 | ||||
1252 | // Performs a semantic analysis on the call to built-in Pipe | |||
1253 | // Query Functions. | |||
1254 | // \param S Reference to the semantic analyzer. | |||
1255 | // \param Call The call to the builtin function to be analyzed. | |||
1256 | // \return True if a semantic error was found, false otherwise. | |||
1257 | static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { | |||
1258 | if (checkArgCount(S, Call, 1)) | |||
1259 | return true; | |||
1260 | ||||
1261 | if (!Call->getArg(0)->getType()->isPipeType()) { | |||
1262 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) | |||
1263 | << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); | |||
1264 | return true; | |||
1265 | } | |||
1266 | ||||
1267 | return false; | |||
1268 | } | |||
1269 | ||||
1270 | // OpenCL v2.0 s6.13.9 - Address space qualifier functions. | |||
1271 | // Performs semantic analysis for the to_global/local/private call. | |||
1272 | // \param S Reference to the semantic analyzer. | |||
1273 | // \param BuiltinID ID of the builtin function. | |||
1274 | // \param Call A pointer to the builtin call. | |||
1275 | // \return True if a semantic error has been found, false otherwise. | |||
1276 | static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, | |||
1277 | CallExpr *Call) { | |||
1278 | if (checkArgCount(S, Call, 1)) | |||
1279 | return true; | |||
1280 | ||||
1281 | auto RT = Call->getArg(0)->getType(); | |||
1282 | if (!RT->isPointerType() || RT->getPointeeType() | |||
1283 | .getAddressSpace() == LangAS::opencl_constant) { | |||
1284 | S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) | |||
1285 | << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); | |||
1286 | return true; | |||
1287 | } | |||
1288 | ||||
1289 | if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { | |||
1290 | S.Diag(Call->getArg(0)->getBeginLoc(), | |||
1291 | diag::warn_opencl_generic_address_space_arg) | |||
1292 | << Call->getDirectCallee()->getNameInfo().getAsString() | |||
1293 | << Call->getArg(0)->getSourceRange(); | |||
1294 | } | |||
1295 | ||||
1296 | RT = RT->getPointeeType(); | |||
1297 | auto Qual = RT.getQualifiers(); | |||
1298 | switch (BuiltinID) { | |||
1299 | case Builtin::BIto_global: | |||
1300 | Qual.setAddressSpace(LangAS::opencl_global); | |||
1301 | break; | |||
1302 | case Builtin::BIto_local: | |||
1303 | Qual.setAddressSpace(LangAS::opencl_local); | |||
1304 | break; | |||
1305 | case Builtin::BIto_private: | |||
1306 | Qual.setAddressSpace(LangAS::opencl_private); | |||
1307 | break; | |||
1308 | default: | |||
1309 | llvm_unreachable("Invalid builtin function")::llvm::llvm_unreachable_internal("Invalid builtin function", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 1309); | |||
1310 | } | |||
1311 | Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( | |||
1312 | RT.getUnqualifiedType(), Qual))); | |||
1313 | ||||
1314 | return false; | |||
1315 | } | |||
1316 | ||||
1317 | static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { | |||
1318 | if (checkArgCount(S, TheCall, 1)) | |||
1319 | return ExprError(); | |||
1320 | ||||
1321 | // Compute __builtin_launder's parameter type from the argument. | |||
1322 | // The parameter type is: | |||
1323 | // * The type of the argument if it's not an array or function type, | |||
1324 | // Otherwise, | |||
1325 | // * The decayed argument type. | |||
1326 | QualType ParamTy = [&]() { | |||
1327 | QualType ArgTy = TheCall->getArg(0)->getType(); | |||
1328 | if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) | |||
1329 | return S.Context.getPointerType(Ty->getElementType()); | |||
1330 | if (ArgTy->isFunctionType()) { | |||
1331 | return S.Context.getPointerType(ArgTy); | |||
1332 | } | |||
1333 | return ArgTy; | |||
1334 | }(); | |||
1335 | ||||
1336 | TheCall->setType(ParamTy); | |||
1337 | ||||
1338 | auto DiagSelect = [&]() -> llvm::Optional<unsigned> { | |||
1339 | if (!ParamTy->isPointerType()) | |||
1340 | return 0; | |||
1341 | if (ParamTy->isFunctionPointerType()) | |||
1342 | return 1; | |||
1343 | if (ParamTy->isVoidPointerType()) | |||
1344 | return 2; | |||
1345 | return llvm::Optional<unsigned>{}; | |||
1346 | }(); | |||
1347 | if (DiagSelect.hasValue()) { | |||
1348 | S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) | |||
1349 | << DiagSelect.getValue() << TheCall->getSourceRange(); | |||
1350 | return ExprError(); | |||
1351 | } | |||
1352 | ||||
1353 | // We either have an incomplete class type, or we have a class template | |||
1354 | // whose instantiation has not been forced. Example: | |||
1355 | // | |||
1356 | // template <class T> struct Foo { T value; }; | |||
1357 | // Foo<int> *p = nullptr; | |||
1358 | // auto *d = __builtin_launder(p); | |||
1359 | if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), | |||
1360 | diag::err_incomplete_type)) | |||
1361 | return ExprError(); | |||
1362 | ||||
1363 | assert(ParamTy->getPointeeType()->isObjectType() &&((ParamTy->getPointeeType()->isObjectType() && "Unhandled non-object pointer case" ) ? static_cast<void> (0) : __assert_fail ("ParamTy->getPointeeType()->isObjectType() && \"Unhandled non-object pointer case\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 1364, __PRETTY_FUNCTION__)) | |||
1364 | "Unhandled non-object pointer case")((ParamTy->getPointeeType()->isObjectType() && "Unhandled non-object pointer case" ) ? static_cast<void> (0) : __assert_fail ("ParamTy->getPointeeType()->isObjectType() && \"Unhandled non-object pointer case\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 1364, __PRETTY_FUNCTION__)); | |||
1365 | ||||
1366 | InitializedEntity Entity = | |||
1367 | InitializedEntity::InitializeParameter(S.Context, ParamTy, false); | |||
1368 | ExprResult Arg = | |||
1369 | S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); | |||
1370 | if (Arg.isInvalid()) | |||
1371 | return ExprError(); | |||
1372 | TheCall->setArg(0, Arg.get()); | |||
1373 | ||||
1374 | return TheCall; | |||
1375 | } | |||
1376 | ||||
1377 | // Emit an error and return true if the current architecture is not in the list | |||
1378 | // of supported architectures. | |||
1379 | static bool | |||
1380 | CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, | |||
1381 | ArrayRef<llvm::Triple::ArchType> SupportedArchs) { | |||
1382 | llvm::Triple::ArchType CurArch = | |||
1383 | S.getASTContext().getTargetInfo().getTriple().getArch(); | |||
1384 | if (llvm::is_contained(SupportedArchs, CurArch)) | |||
1385 | return false; | |||
1386 | S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) | |||
1387 | << TheCall->getSourceRange(); | |||
1388 | return true; | |||
1389 | } | |||
1390 | ||||
1391 | static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, | |||
1392 | SourceLocation CallSiteLoc); | |||
1393 | ||||
1394 | bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, | |||
1395 | CallExpr *TheCall) { | |||
1396 | switch (TI.getTriple().getArch()) { | |||
1397 | default: | |||
1398 | // Some builtins don't require additional checking, so just consider these | |||
1399 | // acceptable. | |||
1400 | return false; | |||
1401 | case llvm::Triple::arm: | |||
1402 | case llvm::Triple::armeb: | |||
1403 | case llvm::Triple::thumb: | |||
1404 | case llvm::Triple::thumbeb: | |||
1405 | return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); | |||
1406 | case llvm::Triple::aarch64: | |||
1407 | case llvm::Triple::aarch64_32: | |||
1408 | case llvm::Triple::aarch64_be: | |||
1409 | return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); | |||
1410 | case llvm::Triple::bpfeb: | |||
1411 | case llvm::Triple::bpfel: | |||
1412 | return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); | |||
1413 | case llvm::Triple::hexagon: | |||
1414 | return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); | |||
1415 | case llvm::Triple::mips: | |||
1416 | case llvm::Triple::mipsel: | |||
1417 | case llvm::Triple::mips64: | |||
1418 | case llvm::Triple::mips64el: | |||
1419 | return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); | |||
1420 | case llvm::Triple::systemz: | |||
1421 | return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); | |||
1422 | case llvm::Triple::x86: | |||
1423 | case llvm::Triple::x86_64: | |||
1424 | return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); | |||
1425 | case llvm::Triple::ppc: | |||
1426 | case llvm::Triple::ppcle: | |||
1427 | case llvm::Triple::ppc64: | |||
1428 | case llvm::Triple::ppc64le: | |||
1429 | return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); | |||
1430 | case llvm::Triple::amdgcn: | |||
1431 | return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); | |||
1432 | } | |||
1433 | } | |||
1434 | ||||
1435 | ExprResult | |||
1436 | Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, | |||
1437 | CallExpr *TheCall) { | |||
1438 | ExprResult TheCallResult(TheCall); | |||
1439 | ||||
1440 | // Find out if any arguments are required to be integer constant expressions. | |||
1441 | unsigned ICEArguments = 0; | |||
1442 | ASTContext::GetBuiltinTypeError Error; | |||
1443 | Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); | |||
1444 | if (Error != ASTContext::GE_None) | |||
1445 | ICEArguments = 0; // Don't diagnose previously diagnosed errors. | |||
1446 | ||||
1447 | // If any arguments are required to be ICE's, check and diagnose. | |||
1448 | for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { | |||
1449 | // Skip arguments not required to be ICE's. | |||
1450 | if ((ICEArguments & (1 << ArgNo)) == 0) continue; | |||
1451 | ||||
1452 | llvm::APSInt Result; | |||
1453 | if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) | |||
1454 | return true; | |||
1455 | ICEArguments &= ~(1 << ArgNo); | |||
1456 | } | |||
1457 | ||||
1458 | switch (BuiltinID) { | |||
1459 | case Builtin::BI__builtin___CFStringMakeConstantString: | |||
1460 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 1461, __PRETTY_FUNCTION__)) | |||
1461 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 1461, __PRETTY_FUNCTION__)); | |||
1462 | if (CheckObjCString(TheCall->getArg(0))) | |||
1463 | return ExprError(); | |||
1464 | break; | |||
1465 | case Builtin::BI__builtin_ms_va_start: | |||
1466 | case Builtin::BI__builtin_stdarg_start: | |||
1467 | case Builtin::BI__builtin_va_start: | |||
1468 | if (SemaBuiltinVAStart(BuiltinID, TheCall)) | |||
1469 | return ExprError(); | |||
1470 | break; | |||
1471 | case Builtin::BI__va_start: { | |||
1472 | switch (Context.getTargetInfo().getTriple().getArch()) { | |||
1473 | case llvm::Triple::aarch64: | |||
1474 | case llvm::Triple::arm: | |||
1475 | case llvm::Triple::thumb: | |||
1476 | if (SemaBuiltinVAStartARMMicrosoft(TheCall)) | |||
1477 | return ExprError(); | |||
1478 | break; | |||
1479 | default: | |||
1480 | if (SemaBuiltinVAStart(BuiltinID, TheCall)) | |||
1481 | return ExprError(); | |||
1482 | break; | |||
1483 | } | |||
1484 | break; | |||
1485 | } | |||
1486 | ||||
1487 | // The acquire, release, and no fence variants are ARM and AArch64 only. | |||
1488 | case Builtin::BI_interlockedbittestandset_acq: | |||
1489 | case Builtin::BI_interlockedbittestandset_rel: | |||
1490 | case Builtin::BI_interlockedbittestandset_nf: | |||
1491 | case Builtin::BI_interlockedbittestandreset_acq: | |||
1492 | case Builtin::BI_interlockedbittestandreset_rel: | |||
1493 | case Builtin::BI_interlockedbittestandreset_nf: | |||
1494 | if (CheckBuiltinTargetSupport( | |||
1495 | *this, BuiltinID, TheCall, | |||
1496 | {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) | |||
1497 | return ExprError(); | |||
1498 | break; | |||
1499 | ||||
1500 | // The 64-bit bittest variants are x64, ARM, and AArch64 only. | |||
1501 | case Builtin::BI_bittest64: | |||
1502 | case Builtin::BI_bittestandcomplement64: | |||
1503 | case Builtin::BI_bittestandreset64: | |||
1504 | case Builtin::BI_bittestandset64: | |||
1505 | case Builtin::BI_interlockedbittestandreset64: | |||
1506 | case Builtin::BI_interlockedbittestandset64: | |||
1507 | if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, | |||
1508 | {llvm::Triple::x86_64, llvm::Triple::arm, | |||
1509 | llvm::Triple::thumb, llvm::Triple::aarch64})) | |||
1510 | return ExprError(); | |||
1511 | break; | |||
1512 | ||||
1513 | case Builtin::BI__builtin_isgreater: | |||
1514 | case Builtin::BI__builtin_isgreaterequal: | |||
1515 | case Builtin::BI__builtin_isless: | |||
1516 | case Builtin::BI__builtin_islessequal: | |||
1517 | case Builtin::BI__builtin_islessgreater: | |||
1518 | case Builtin::BI__builtin_isunordered: | |||
1519 | if (SemaBuiltinUnorderedCompare(TheCall)) | |||
1520 | return ExprError(); | |||
1521 | break; | |||
1522 | case Builtin::BI__builtin_fpclassify: | |||
1523 | if (SemaBuiltinFPClassification(TheCall, 6)) | |||
1524 | return ExprError(); | |||
1525 | break; | |||
1526 | case Builtin::BI__builtin_isfinite: | |||
1527 | case Builtin::BI__builtin_isinf: | |||
1528 | case Builtin::BI__builtin_isinf_sign: | |||
1529 | case Builtin::BI__builtin_isnan: | |||
1530 | case Builtin::BI__builtin_isnormal: | |||
1531 | case Builtin::BI__builtin_signbit: | |||
1532 | case Builtin::BI__builtin_signbitf: | |||
1533 | case Builtin::BI__builtin_signbitl: | |||
1534 | if (SemaBuiltinFPClassification(TheCall, 1)) | |||
1535 | return ExprError(); | |||
1536 | break; | |||
1537 | case Builtin::BI__builtin_shufflevector: | |||
1538 | return SemaBuiltinShuffleVector(TheCall); | |||
1539 | // TheCall will be freed by the smart pointer here, but that's fine, since | |||
1540 | // SemaBuiltinShuffleVector guts it, but then doesn't release it. | |||
1541 | case Builtin::BI__builtin_prefetch: | |||
1542 | if (SemaBuiltinPrefetch(TheCall)) | |||
1543 | return ExprError(); | |||
1544 | break; | |||
1545 | case Builtin::BI__builtin_alloca_with_align: | |||
1546 | if (SemaBuiltinAllocaWithAlign(TheCall)) | |||
1547 | return ExprError(); | |||
1548 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
1549 | case Builtin::BI__builtin_alloca: | |||
1550 | Diag(TheCall->getBeginLoc(), diag::warn_alloca) | |||
1551 | << TheCall->getDirectCallee(); | |||
1552 | break; | |||
1553 | case Builtin::BI__assume: | |||
1554 | case Builtin::BI__builtin_assume: | |||
1555 | if (SemaBuiltinAssume(TheCall)) | |||
1556 | return ExprError(); | |||
1557 | break; | |||
1558 | case Builtin::BI__builtin_assume_aligned: | |||
1559 | if (SemaBuiltinAssumeAligned(TheCall)) | |||
1560 | return ExprError(); | |||
1561 | break; | |||
1562 | case Builtin::BI__builtin_dynamic_object_size: | |||
1563 | case Builtin::BI__builtin_object_size: | |||
1564 | if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) | |||
1565 | return ExprError(); | |||
1566 | break; | |||
1567 | case Builtin::BI__builtin_longjmp: | |||
1568 | if (SemaBuiltinLongjmp(TheCall)) | |||
1569 | return ExprError(); | |||
1570 | break; | |||
1571 | case Builtin::BI__builtin_setjmp: | |||
1572 | if (SemaBuiltinSetjmp(TheCall)) | |||
1573 | return ExprError(); | |||
1574 | break; | |||
1575 | case Builtin::BI__builtin_classify_type: | |||
1576 | if (checkArgCount(*this, TheCall, 1)) return true; | |||
1577 | TheCall->setType(Context.IntTy); | |||
1578 | break; | |||
1579 | case Builtin::BI__builtin_complex: | |||
1580 | if (SemaBuiltinComplex(TheCall)) | |||
1581 | return ExprError(); | |||
1582 | break; | |||
1583 | case Builtin::BI__builtin_constant_p: { | |||
1584 | if (checkArgCount(*this, TheCall, 1)) return true; | |||
1585 | ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); | |||
1586 | if (Arg.isInvalid()) return true; | |||
1587 | TheCall->setArg(0, Arg.get()); | |||
1588 | TheCall->setType(Context.IntTy); | |||
1589 | break; | |||
1590 | } | |||
1591 | case Builtin::BI__builtin_launder: | |||
1592 | return SemaBuiltinLaunder(*this, TheCall); | |||
1593 | case Builtin::BI__sync_fetch_and_add: | |||
1594 | case Builtin::BI__sync_fetch_and_add_1: | |||
1595 | case Builtin::BI__sync_fetch_and_add_2: | |||
1596 | case Builtin::BI__sync_fetch_and_add_4: | |||
1597 | case Builtin::BI__sync_fetch_and_add_8: | |||
1598 | case Builtin::BI__sync_fetch_and_add_16: | |||
1599 | case Builtin::BI__sync_fetch_and_sub: | |||
1600 | case Builtin::BI__sync_fetch_and_sub_1: | |||
1601 | case Builtin::BI__sync_fetch_and_sub_2: | |||
1602 | case Builtin::BI__sync_fetch_and_sub_4: | |||
1603 | case Builtin::BI__sync_fetch_and_sub_8: | |||
1604 | case Builtin::BI__sync_fetch_and_sub_16: | |||
1605 | case Builtin::BI__sync_fetch_and_or: | |||
1606 | case Builtin::BI__sync_fetch_and_or_1: | |||
1607 | case Builtin::BI__sync_fetch_and_or_2: | |||
1608 | case Builtin::BI__sync_fetch_and_or_4: | |||
1609 | case Builtin::BI__sync_fetch_and_or_8: | |||
1610 | case Builtin::BI__sync_fetch_and_or_16: | |||
1611 | case Builtin::BI__sync_fetch_and_and: | |||
1612 | case Builtin::BI__sync_fetch_and_and_1: | |||
1613 | case Builtin::BI__sync_fetch_and_and_2: | |||
1614 | case Builtin::BI__sync_fetch_and_and_4: | |||
1615 | case Builtin::BI__sync_fetch_and_and_8: | |||
1616 | case Builtin::BI__sync_fetch_and_and_16: | |||
1617 | case Builtin::BI__sync_fetch_and_xor: | |||
1618 | case Builtin::BI__sync_fetch_and_xor_1: | |||
1619 | case Builtin::BI__sync_fetch_and_xor_2: | |||
1620 | case Builtin::BI__sync_fetch_and_xor_4: | |||
1621 | case Builtin::BI__sync_fetch_and_xor_8: | |||
1622 | case Builtin::BI__sync_fetch_and_xor_16: | |||
1623 | case Builtin::BI__sync_fetch_and_nand: | |||
1624 | case Builtin::BI__sync_fetch_and_nand_1: | |||
1625 | case Builtin::BI__sync_fetch_and_nand_2: | |||
1626 | case Builtin::BI__sync_fetch_and_nand_4: | |||
1627 | case Builtin::BI__sync_fetch_and_nand_8: | |||
1628 | case Builtin::BI__sync_fetch_and_nand_16: | |||
1629 | case Builtin::BI__sync_add_and_fetch: | |||
1630 | case Builtin::BI__sync_add_and_fetch_1: | |||
1631 | case Builtin::BI__sync_add_and_fetch_2: | |||
1632 | case Builtin::BI__sync_add_and_fetch_4: | |||
1633 | case Builtin::BI__sync_add_and_fetch_8: | |||
1634 | case Builtin::BI__sync_add_and_fetch_16: | |||
1635 | case Builtin::BI__sync_sub_and_fetch: | |||
1636 | case Builtin::BI__sync_sub_and_fetch_1: | |||
1637 | case Builtin::BI__sync_sub_and_fetch_2: | |||
1638 | case Builtin::BI__sync_sub_and_fetch_4: | |||
1639 | case Builtin::BI__sync_sub_and_fetch_8: | |||
1640 | case Builtin::BI__sync_sub_and_fetch_16: | |||
1641 | case Builtin::BI__sync_and_and_fetch: | |||
1642 | case Builtin::BI__sync_and_and_fetch_1: | |||
1643 | case Builtin::BI__sync_and_and_fetch_2: | |||
1644 | case Builtin::BI__sync_and_and_fetch_4: | |||
1645 | case Builtin::BI__sync_and_and_fetch_8: | |||
1646 | case Builtin::BI__sync_and_and_fetch_16: | |||
1647 | case Builtin::BI__sync_or_and_fetch: | |||
1648 | case Builtin::BI__sync_or_and_fetch_1: | |||
1649 | case Builtin::BI__sync_or_and_fetch_2: | |||
1650 | case Builtin::BI__sync_or_and_fetch_4: | |||
1651 | case Builtin::BI__sync_or_and_fetch_8: | |||
1652 | case Builtin::BI__sync_or_and_fetch_16: | |||
1653 | case Builtin::BI__sync_xor_and_fetch: | |||
1654 | case Builtin::BI__sync_xor_and_fetch_1: | |||
1655 | case Builtin::BI__sync_xor_and_fetch_2: | |||
1656 | case Builtin::BI__sync_xor_and_fetch_4: | |||
1657 | case Builtin::BI__sync_xor_and_fetch_8: | |||
1658 | case Builtin::BI__sync_xor_and_fetch_16: | |||
1659 | case Builtin::BI__sync_nand_and_fetch: | |||
1660 | case Builtin::BI__sync_nand_and_fetch_1: | |||
1661 | case Builtin::BI__sync_nand_and_fetch_2: | |||
1662 | case Builtin::BI__sync_nand_and_fetch_4: | |||
1663 | case Builtin::BI__sync_nand_and_fetch_8: | |||
1664 | case Builtin::BI__sync_nand_and_fetch_16: | |||
1665 | case Builtin::BI__sync_val_compare_and_swap: | |||
1666 | case Builtin::BI__sync_val_compare_and_swap_1: | |||
1667 | case Builtin::BI__sync_val_compare_and_swap_2: | |||
1668 | case Builtin::BI__sync_val_compare_and_swap_4: | |||
1669 | case Builtin::BI__sync_val_compare_and_swap_8: | |||
1670 | case Builtin::BI__sync_val_compare_and_swap_16: | |||
1671 | case Builtin::BI__sync_bool_compare_and_swap: | |||
1672 | case Builtin::BI__sync_bool_compare_and_swap_1: | |||
1673 | case Builtin::BI__sync_bool_compare_and_swap_2: | |||
1674 | case Builtin::BI__sync_bool_compare_and_swap_4: | |||
1675 | case Builtin::BI__sync_bool_compare_and_swap_8: | |||
1676 | case Builtin::BI__sync_bool_compare_and_swap_16: | |||
1677 | case Builtin::BI__sync_lock_test_and_set: | |||
1678 | case Builtin::BI__sync_lock_test_and_set_1: | |||
1679 | case Builtin::BI__sync_lock_test_and_set_2: | |||
1680 | case Builtin::BI__sync_lock_test_and_set_4: | |||
1681 | case Builtin::BI__sync_lock_test_and_set_8: | |||
1682 | case Builtin::BI__sync_lock_test_and_set_16: | |||
1683 | case Builtin::BI__sync_lock_release: | |||
1684 | case Builtin::BI__sync_lock_release_1: | |||
1685 | case Builtin::BI__sync_lock_release_2: | |||
1686 | case Builtin::BI__sync_lock_release_4: | |||
1687 | case Builtin::BI__sync_lock_release_8: | |||
1688 | case Builtin::BI__sync_lock_release_16: | |||
1689 | case Builtin::BI__sync_swap: | |||
1690 | case Builtin::BI__sync_swap_1: | |||
1691 | case Builtin::BI__sync_swap_2: | |||
1692 | case Builtin::BI__sync_swap_4: | |||
1693 | case Builtin::BI__sync_swap_8: | |||
1694 | case Builtin::BI__sync_swap_16: | |||
1695 | return SemaBuiltinAtomicOverloaded(TheCallResult); | |||
1696 | case Builtin::BI__sync_synchronize: | |||
1697 | Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) | |||
1698 | << TheCall->getCallee()->getSourceRange(); | |||
1699 | break; | |||
1700 | case Builtin::BI__builtin_nontemporal_load: | |||
1701 | case Builtin::BI__builtin_nontemporal_store: | |||
1702 | return SemaBuiltinNontemporalOverloaded(TheCallResult); | |||
1703 | case Builtin::BI__builtin_memcpy_inline: { | |||
1704 | clang::Expr *SizeOp = TheCall->getArg(2); | |||
1705 | // We warn about copying to or from `nullptr` pointers when `size` is | |||
1706 | // greater than 0. When `size` is value dependent we cannot evaluate its | |||
1707 | // value so we bail out. | |||
1708 | if (SizeOp->isValueDependent()) | |||
1709 | break; | |||
1710 | if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { | |||
1711 | CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); | |||
1712 | CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); | |||
1713 | } | |||
1714 | break; | |||
1715 | } | |||
1716 | #define BUILTIN(ID, TYPE, ATTRS) | |||
1717 | #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ | |||
1718 | case Builtin::BI##ID: \ | |||
1719 | return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); | |||
1720 | #include "clang/Basic/Builtins.def" | |||
1721 | case Builtin::BI__annotation: | |||
1722 | if (SemaBuiltinMSVCAnnotation(*this, TheCall)) | |||
1723 | return ExprError(); | |||
1724 | break; | |||
1725 | case Builtin::BI__builtin_annotation: | |||
1726 | if (SemaBuiltinAnnotation(*this, TheCall)) | |||
1727 | return ExprError(); | |||
1728 | break; | |||
1729 | case Builtin::BI__builtin_addressof: | |||
1730 | if (SemaBuiltinAddressof(*this, TheCall)) | |||
1731 | return ExprError(); | |||
1732 | break; | |||
1733 | case Builtin::BI__builtin_is_aligned: | |||
1734 | case Builtin::BI__builtin_align_up: | |||
1735 | case Builtin::BI__builtin_align_down: | |||
1736 | if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) | |||
1737 | return ExprError(); | |||
1738 | break; | |||
1739 | case Builtin::BI__builtin_add_overflow: | |||
1740 | case Builtin::BI__builtin_sub_overflow: | |||
1741 | case Builtin::BI__builtin_mul_overflow: | |||
1742 | if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) | |||
1743 | return ExprError(); | |||
1744 | break; | |||
1745 | case Builtin::BI__builtin_operator_new: | |||
1746 | case Builtin::BI__builtin_operator_delete: { | |||
1747 | bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; | |||
1748 | ExprResult Res = | |||
1749 | SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); | |||
1750 | if (Res.isInvalid()) | |||
1751 | CorrectDelayedTyposInExpr(TheCallResult.get()); | |||
1752 | return Res; | |||
1753 | } | |||
1754 | case Builtin::BI__builtin_dump_struct: { | |||
1755 | // We first want to ensure we are called with 2 arguments | |||
1756 | if (checkArgCount(*this, TheCall, 2)) | |||
1757 | return ExprError(); | |||
1758 | // Ensure that the first argument is of type 'struct XX *' | |||
1759 | const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); | |||
1760 | const QualType PtrArgType = PtrArg->getType(); | |||
1761 | if (!PtrArgType->isPointerType() || | |||
1762 | !PtrArgType->getPointeeType()->isRecordType()) { | |||
1763 | Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) | |||
1764 | << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType | |||
1765 | << "structure pointer"; | |||
1766 | return ExprError(); | |||
1767 | } | |||
1768 | ||||
1769 | // Ensure that the second argument is of type 'FunctionType' | |||
1770 | const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); | |||
1771 | const QualType FnPtrArgType = FnPtrArg->getType(); | |||
1772 | if (!FnPtrArgType->isPointerType()) { | |||
1773 | Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) | |||
1774 | << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 | |||
1775 | << FnPtrArgType << "'int (*)(const char *, ...)'"; | |||
1776 | return ExprError(); | |||
1777 | } | |||
1778 | ||||
1779 | const auto *FuncType = | |||
1780 | FnPtrArgType->getPointeeType()->getAs<FunctionType>(); | |||
1781 | ||||
1782 | if (!FuncType) { | |||
1783 | Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) | |||
1784 | << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 | |||
1785 | << FnPtrArgType << "'int (*)(const char *, ...)'"; | |||
1786 | return ExprError(); | |||
1787 | } | |||
1788 | ||||
1789 | if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { | |||
1790 | if (!FT->getNumParams()) { | |||
1791 | Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) | |||
1792 | << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 | |||
1793 | << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; | |||
1794 | return ExprError(); | |||
1795 | } | |||
1796 | QualType PT = FT->getParamType(0); | |||
1797 | if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || | |||
1798 | !PT->isPointerType() || !PT->getPointeeType()->isCharType() || | |||
1799 | !PT->getPointeeType().isConstQualified()) { | |||
1800 | Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) | |||
1801 | << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 | |||
1802 | << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; | |||
1803 | return ExprError(); | |||
1804 | } | |||
1805 | } | |||
1806 | ||||
1807 | TheCall->setType(Context.IntTy); | |||
1808 | break; | |||
1809 | } | |||
1810 | case Builtin::BI__builtin_expect_with_probability: { | |||
1811 | // We first want to ensure we are called with 3 arguments | |||
1812 | if (checkArgCount(*this, TheCall, 3)) | |||
1813 | return ExprError(); | |||
1814 | // then check probability is constant float in range [0.0, 1.0] | |||
1815 | const Expr *ProbArg = TheCall->getArg(2); | |||
1816 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
1817 | Expr::EvalResult Eval; | |||
1818 | Eval.Diag = &Notes; | |||
1819 | if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || | |||
1820 | !Eval.Val.isFloat()) { | |||
1821 | Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) | |||
1822 | << ProbArg->getSourceRange(); | |||
1823 | for (const PartialDiagnosticAt &PDiag : Notes) | |||
1824 | Diag(PDiag.first, PDiag.second); | |||
1825 | return ExprError(); | |||
1826 | } | |||
1827 | llvm::APFloat Probability = Eval.Val.getFloat(); | |||
1828 | bool LoseInfo = false; | |||
1829 | Probability.convert(llvm::APFloat::IEEEdouble(), | |||
1830 | llvm::RoundingMode::Dynamic, &LoseInfo); | |||
1831 | if (!(Probability >= llvm::APFloat(0.0) && | |||
1832 | Probability <= llvm::APFloat(1.0))) { | |||
1833 | Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) | |||
1834 | << ProbArg->getSourceRange(); | |||
1835 | return ExprError(); | |||
1836 | } | |||
1837 | break; | |||
1838 | } | |||
1839 | case Builtin::BI__builtin_preserve_access_index: | |||
1840 | if (SemaBuiltinPreserveAI(*this, TheCall)) | |||
1841 | return ExprError(); | |||
1842 | break; | |||
1843 | case Builtin::BI__builtin_call_with_static_chain: | |||
1844 | if (SemaBuiltinCallWithStaticChain(*this, TheCall)) | |||
1845 | return ExprError(); | |||
1846 | break; | |||
1847 | case Builtin::BI__exception_code: | |||
1848 | case Builtin::BI_exception_code: | |||
1849 | if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, | |||
1850 | diag::err_seh___except_block)) | |||
1851 | return ExprError(); | |||
1852 | break; | |||
1853 | case Builtin::BI__exception_info: | |||
1854 | case Builtin::BI_exception_info: | |||
1855 | if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, | |||
1856 | diag::err_seh___except_filter)) | |||
1857 | return ExprError(); | |||
1858 | break; | |||
1859 | case Builtin::BI__GetExceptionInfo: | |||
1860 | if (checkArgCount(*this, TheCall, 1)) | |||
1861 | return ExprError(); | |||
1862 | ||||
1863 | if (CheckCXXThrowOperand( | |||
1864 | TheCall->getBeginLoc(), | |||
1865 | Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), | |||
1866 | TheCall)) | |||
1867 | return ExprError(); | |||
1868 | ||||
1869 | TheCall->setType(Context.VoidPtrTy); | |||
1870 | break; | |||
1871 | // OpenCL v2.0, s6.13.16 - Pipe functions | |||
1872 | case Builtin::BIread_pipe: | |||
1873 | case Builtin::BIwrite_pipe: | |||
1874 | // Since those two functions are declared with var args, we need a semantic | |||
1875 | // check for the argument. | |||
1876 | if (SemaBuiltinRWPipe(*this, TheCall)) | |||
1877 | return ExprError(); | |||
1878 | break; | |||
1879 | case Builtin::BIreserve_read_pipe: | |||
1880 | case Builtin::BIreserve_write_pipe: | |||
1881 | case Builtin::BIwork_group_reserve_read_pipe: | |||
1882 | case Builtin::BIwork_group_reserve_write_pipe: | |||
1883 | if (SemaBuiltinReserveRWPipe(*this, TheCall)) | |||
1884 | return ExprError(); | |||
1885 | break; | |||
1886 | case Builtin::BIsub_group_reserve_read_pipe: | |||
1887 | case Builtin::BIsub_group_reserve_write_pipe: | |||
1888 | if (checkOpenCLSubgroupExt(*this, TheCall) || | |||
1889 | SemaBuiltinReserveRWPipe(*this, TheCall)) | |||
1890 | return ExprError(); | |||
1891 | break; | |||
1892 | case Builtin::BIcommit_read_pipe: | |||
1893 | case Builtin::BIcommit_write_pipe: | |||
1894 | case Builtin::BIwork_group_commit_read_pipe: | |||
1895 | case Builtin::BIwork_group_commit_write_pipe: | |||
1896 | if (SemaBuiltinCommitRWPipe(*this, TheCall)) | |||
1897 | return ExprError(); | |||
1898 | break; | |||
1899 | case Builtin::BIsub_group_commit_read_pipe: | |||
1900 | case Builtin::BIsub_group_commit_write_pipe: | |||
1901 | if (checkOpenCLSubgroupExt(*this, TheCall) || | |||
1902 | SemaBuiltinCommitRWPipe(*this, TheCall)) | |||
1903 | return ExprError(); | |||
1904 | break; | |||
1905 | case Builtin::BIget_pipe_num_packets: | |||
1906 | case Builtin::BIget_pipe_max_packets: | |||
1907 | if (SemaBuiltinPipePackets(*this, TheCall)) | |||
1908 | return ExprError(); | |||
1909 | break; | |||
1910 | case Builtin::BIto_global: | |||
1911 | case Builtin::BIto_local: | |||
1912 | case Builtin::BIto_private: | |||
1913 | if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) | |||
1914 | return ExprError(); | |||
1915 | break; | |||
1916 | // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. | |||
1917 | case Builtin::BIenqueue_kernel: | |||
1918 | if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) | |||
1919 | return ExprError(); | |||
1920 | break; | |||
1921 | case Builtin::BIget_kernel_work_group_size: | |||
1922 | case Builtin::BIget_kernel_preferred_work_group_size_multiple: | |||
1923 | if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) | |||
1924 | return ExprError(); | |||
1925 | break; | |||
1926 | case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: | |||
1927 | case Builtin::BIget_kernel_sub_group_count_for_ndrange: | |||
1928 | if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) | |||
1929 | return ExprError(); | |||
1930 | break; | |||
1931 | case Builtin::BI__builtin_os_log_format: | |||
1932 | Cleanup.setExprNeedsCleanups(true); | |||
1933 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
1934 | case Builtin::BI__builtin_os_log_format_buffer_size: | |||
1935 | if (SemaBuiltinOSLogFormat(TheCall)) | |||
1936 | return ExprError(); | |||
1937 | break; | |||
1938 | case Builtin::BI__builtin_frame_address: | |||
1939 | case Builtin::BI__builtin_return_address: { | |||
1940 | if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) | |||
1941 | return ExprError(); | |||
1942 | ||||
1943 | // -Wframe-address warning if non-zero passed to builtin | |||
1944 | // return/frame address. | |||
1945 | Expr::EvalResult Result; | |||
1946 | if (!TheCall->getArg(0)->isValueDependent() && | |||
1947 | TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && | |||
1948 | Result.Val.getInt() != 0) | |||
1949 | Diag(TheCall->getBeginLoc(), diag::warn_frame_address) | |||
1950 | << ((BuiltinID == Builtin::BI__builtin_return_address) | |||
1951 | ? "__builtin_return_address" | |||
1952 | : "__builtin_frame_address") | |||
1953 | << TheCall->getSourceRange(); | |||
1954 | break; | |||
1955 | } | |||
1956 | ||||
1957 | case Builtin::BI__builtin_matrix_transpose: | |||
1958 | return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); | |||
1959 | ||||
1960 | case Builtin::BI__builtin_matrix_column_major_load: | |||
1961 | return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); | |||
1962 | ||||
1963 | case Builtin::BI__builtin_matrix_column_major_store: | |||
1964 | return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); | |||
1965 | } | |||
1966 | ||||
1967 | // Since the target specific builtins for each arch overlap, only check those | |||
1968 | // of the arch we are compiling for. | |||
1969 | if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { | |||
1970 | if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { | |||
1971 | assert(Context.getAuxTargetInfo() &&((Context.getAuxTargetInfo() && "Aux Target Builtin, but not an aux target?" ) ? static_cast<void> (0) : __assert_fail ("Context.getAuxTargetInfo() && \"Aux Target Builtin, but not an aux target?\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 1972, __PRETTY_FUNCTION__)) | |||
1972 | "Aux Target Builtin, but not an aux target?")((Context.getAuxTargetInfo() && "Aux Target Builtin, but not an aux target?" ) ? static_cast<void> (0) : __assert_fail ("Context.getAuxTargetInfo() && \"Aux Target Builtin, but not an aux target?\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 1972, __PRETTY_FUNCTION__)); | |||
1973 | ||||
1974 | if (CheckTSBuiltinFunctionCall( | |||
1975 | *Context.getAuxTargetInfo(), | |||
1976 | Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) | |||
1977 | return ExprError(); | |||
1978 | } else { | |||
1979 | if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, | |||
1980 | TheCall)) | |||
1981 | return ExprError(); | |||
1982 | } | |||
1983 | } | |||
1984 | ||||
1985 | return TheCallResult; | |||
1986 | } | |||
1987 | ||||
1988 | // Get the valid immediate range for the specified NEON type code. | |||
1989 | static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { | |||
1990 | NeonTypeFlags Type(t); | |||
1991 | int IsQuad = ForceQuad ? true : Type.isQuad(); | |||
1992 | switch (Type.getEltType()) { | |||
1993 | case NeonTypeFlags::Int8: | |||
1994 | case NeonTypeFlags::Poly8: | |||
1995 | return shift ? 7 : (8 << IsQuad) - 1; | |||
1996 | case NeonTypeFlags::Int16: | |||
1997 | case NeonTypeFlags::Poly16: | |||
1998 | return shift ? 15 : (4 << IsQuad) - 1; | |||
1999 | case NeonTypeFlags::Int32: | |||
2000 | return shift ? 31 : (2 << IsQuad) - 1; | |||
2001 | case NeonTypeFlags::Int64: | |||
2002 | case NeonTypeFlags::Poly64: | |||
2003 | return shift ? 63 : (1 << IsQuad) - 1; | |||
2004 | case NeonTypeFlags::Poly128: | |||
2005 | return shift ? 127 : (1 << IsQuad) - 1; | |||
2006 | case NeonTypeFlags::Float16: | |||
2007 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2007, __PRETTY_FUNCTION__)); | |||
2008 | return (4 << IsQuad) - 1; | |||
2009 | case NeonTypeFlags::Float32: | |||
2010 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2010, __PRETTY_FUNCTION__)); | |||
2011 | return (2 << IsQuad) - 1; | |||
2012 | case NeonTypeFlags::Float64: | |||
2013 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2013, __PRETTY_FUNCTION__)); | |||
2014 | return (1 << IsQuad) - 1; | |||
2015 | case NeonTypeFlags::BFloat16: | |||
2016 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2016, __PRETTY_FUNCTION__)); | |||
2017 | return (4 << IsQuad) - 1; | |||
2018 | } | |||
2019 | llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2019); | |||
2020 | } | |||
2021 | ||||
2022 | /// getNeonEltType - Return the QualType corresponding to the elements of | |||
2023 | /// the vector type specified by the NeonTypeFlags. This is used to check | |||
2024 | /// the pointer arguments for Neon load/store intrinsics. | |||
2025 | static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, | |||
2026 | bool IsPolyUnsigned, bool IsInt64Long) { | |||
2027 | switch (Flags.getEltType()) { | |||
2028 | case NeonTypeFlags::Int8: | |||
2029 | return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; | |||
2030 | case NeonTypeFlags::Int16: | |||
2031 | return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; | |||
2032 | case NeonTypeFlags::Int32: | |||
2033 | return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; | |||
2034 | case NeonTypeFlags::Int64: | |||
2035 | if (IsInt64Long) | |||
2036 | return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; | |||
2037 | else | |||
2038 | return Flags.isUnsigned() ? Context.UnsignedLongLongTy | |||
2039 | : Context.LongLongTy; | |||
2040 | case NeonTypeFlags::Poly8: | |||
2041 | return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; | |||
2042 | case NeonTypeFlags::Poly16: | |||
2043 | return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; | |||
2044 | case NeonTypeFlags::Poly64: | |||
2045 | if (IsInt64Long) | |||
2046 | return Context.UnsignedLongTy; | |||
2047 | else | |||
2048 | return Context.UnsignedLongLongTy; | |||
2049 | case NeonTypeFlags::Poly128: | |||
2050 | break; | |||
2051 | case NeonTypeFlags::Float16: | |||
2052 | return Context.HalfTy; | |||
2053 | case NeonTypeFlags::Float32: | |||
2054 | return Context.FloatTy; | |||
2055 | case NeonTypeFlags::Float64: | |||
2056 | return Context.DoubleTy; | |||
2057 | case NeonTypeFlags::BFloat16: | |||
2058 | return Context.BFloat16Ty; | |||
2059 | } | |||
2060 | llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2060); | |||
2061 | } | |||
2062 | ||||
2063 | bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { | |||
2064 | // Range check SVE intrinsics that take immediate values. | |||
2065 | SmallVector<std::tuple<int,int,int>, 3> ImmChecks; | |||
2066 | ||||
2067 | switch (BuiltinID) { | |||
2068 | default: | |||
2069 | return false; | |||
2070 | #define GET_SVE_IMMEDIATE_CHECK | |||
2071 | #include "clang/Basic/arm_sve_sema_rangechecks.inc" | |||
2072 | #undef GET_SVE_IMMEDIATE_CHECK | |||
2073 | } | |||
2074 | ||||
2075 | // Perform all the immediate checks for this builtin call. | |||
2076 | bool HasError = false; | |||
2077 | for (auto &I : ImmChecks) { | |||
2078 | int ArgNum, CheckTy, ElementSizeInBits; | |||
2079 | std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; | |||
2080 | ||||
2081 | typedef bool(*OptionSetCheckFnTy)(int64_t Value); | |||
2082 | ||||
2083 | // Function that checks whether the operand (ArgNum) is an immediate | |||
2084 | // that is one of the predefined values. | |||
2085 | auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, | |||
2086 | int ErrDiag) -> bool { | |||
2087 | // We can't check the value of a dependent argument. | |||
2088 | Expr *Arg = TheCall->getArg(ArgNum); | |||
2089 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
2090 | return false; | |||
2091 | ||||
2092 | // Check constant-ness first. | |||
2093 | llvm::APSInt Imm; | |||
2094 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) | |||
2095 | return true; | |||
2096 | ||||
2097 | if (!CheckImm(Imm.getSExtValue())) | |||
2098 | return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); | |||
2099 | return false; | |||
2100 | }; | |||
2101 | ||||
2102 | switch ((SVETypeFlags::ImmCheckType)CheckTy) { | |||
2103 | case SVETypeFlags::ImmCheck0_31: | |||
2104 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) | |||
2105 | HasError = true; | |||
2106 | break; | |||
2107 | case SVETypeFlags::ImmCheck0_13: | |||
2108 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) | |||
2109 | HasError = true; | |||
2110 | break; | |||
2111 | case SVETypeFlags::ImmCheck1_16: | |||
2112 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) | |||
2113 | HasError = true; | |||
2114 | break; | |||
2115 | case SVETypeFlags::ImmCheck0_7: | |||
2116 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) | |||
2117 | HasError = true; | |||
2118 | break; | |||
2119 | case SVETypeFlags::ImmCheckExtract: | |||
2120 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, | |||
2121 | (2048 / ElementSizeInBits) - 1)) | |||
2122 | HasError = true; | |||
2123 | break; | |||
2124 | case SVETypeFlags::ImmCheckShiftRight: | |||
2125 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) | |||
2126 | HasError = true; | |||
2127 | break; | |||
2128 | case SVETypeFlags::ImmCheckShiftRightNarrow: | |||
2129 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, | |||
2130 | ElementSizeInBits / 2)) | |||
2131 | HasError = true; | |||
2132 | break; | |||
2133 | case SVETypeFlags::ImmCheckShiftLeft: | |||
2134 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, | |||
2135 | ElementSizeInBits - 1)) | |||
2136 | HasError = true; | |||
2137 | break; | |||
2138 | case SVETypeFlags::ImmCheckLaneIndex: | |||
2139 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, | |||
2140 | (128 / (1 * ElementSizeInBits)) - 1)) | |||
2141 | HasError = true; | |||
2142 | break; | |||
2143 | case SVETypeFlags::ImmCheckLaneIndexCompRotate: | |||
2144 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, | |||
2145 | (128 / (2 * ElementSizeInBits)) - 1)) | |||
2146 | HasError = true; | |||
2147 | break; | |||
2148 | case SVETypeFlags::ImmCheckLaneIndexDot: | |||
2149 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, | |||
2150 | (128 / (4 * ElementSizeInBits)) - 1)) | |||
2151 | HasError = true; | |||
2152 | break; | |||
2153 | case SVETypeFlags::ImmCheckComplexRot90_270: | |||
2154 | if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, | |||
2155 | diag::err_rotation_argument_to_cadd)) | |||
2156 | HasError = true; | |||
2157 | break; | |||
2158 | case SVETypeFlags::ImmCheckComplexRotAll90: | |||
2159 | if (CheckImmediateInSet( | |||
2160 | [](int64_t V) { | |||
2161 | return V == 0 || V == 90 || V == 180 || V == 270; | |||
2162 | }, | |||
2163 | diag::err_rotation_argument_to_cmla)) | |||
2164 | HasError = true; | |||
2165 | break; | |||
2166 | case SVETypeFlags::ImmCheck0_1: | |||
2167 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) | |||
2168 | HasError = true; | |||
2169 | break; | |||
2170 | case SVETypeFlags::ImmCheck0_2: | |||
2171 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) | |||
2172 | HasError = true; | |||
2173 | break; | |||
2174 | case SVETypeFlags::ImmCheck0_3: | |||
2175 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) | |||
2176 | HasError = true; | |||
2177 | break; | |||
2178 | } | |||
2179 | } | |||
2180 | ||||
2181 | return HasError; | |||
2182 | } | |||
2183 | ||||
2184 | bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, | |||
2185 | unsigned BuiltinID, CallExpr *TheCall) { | |||
2186 | llvm::APSInt Result; | |||
2187 | uint64_t mask = 0; | |||
2188 | unsigned TV = 0; | |||
2189 | int PtrArgNum = -1; | |||
2190 | bool HasConstPtr = false; | |||
2191 | switch (BuiltinID) { | |||
2192 | #define GET_NEON_OVERLOAD_CHECK | |||
2193 | #include "clang/Basic/arm_neon.inc" | |||
2194 | #include "clang/Basic/arm_fp16.inc" | |||
2195 | #undef GET_NEON_OVERLOAD_CHECK | |||
2196 | } | |||
2197 | ||||
2198 | // For NEON intrinsics which are overloaded on vector element type, validate | |||
2199 | // the immediate which specifies which variant to emit. | |||
2200 | unsigned ImmArg = TheCall->getNumArgs()-1; | |||
2201 | if (mask) { | |||
2202 | if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) | |||
2203 | return true; | |||
2204 | ||||
2205 | TV = Result.getLimitedValue(64); | |||
2206 | if ((TV > 63) || (mask & (1ULL << TV)) == 0) | |||
2207 | return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) | |||
2208 | << TheCall->getArg(ImmArg)->getSourceRange(); | |||
2209 | } | |||
2210 | ||||
2211 | if (PtrArgNum >= 0) { | |||
2212 | // Check that pointer arguments have the specified type. | |||
2213 | Expr *Arg = TheCall->getArg(PtrArgNum); | |||
2214 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) | |||
2215 | Arg = ICE->getSubExpr(); | |||
2216 | ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); | |||
2217 | QualType RHSTy = RHS.get()->getType(); | |||
2218 | ||||
2219 | llvm::Triple::ArchType Arch = TI.getTriple().getArch(); | |||
2220 | bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || | |||
2221 | Arch == llvm::Triple::aarch64_32 || | |||
2222 | Arch == llvm::Triple::aarch64_be; | |||
2223 | bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; | |||
2224 | QualType EltTy = | |||
2225 | getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); | |||
2226 | if (HasConstPtr) | |||
2227 | EltTy = EltTy.withConst(); | |||
2228 | QualType LHSTy = Context.getPointerType(EltTy); | |||
2229 | AssignConvertType ConvTy; | |||
2230 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | |||
2231 | if (RHS.isInvalid()) | |||
2232 | return true; | |||
2233 | if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, | |||
2234 | RHS.get(), AA_Assigning)) | |||
2235 | return true; | |||
2236 | } | |||
2237 | ||||
2238 | // For NEON intrinsics which take an immediate value as part of the | |||
2239 | // instruction, range check them here. | |||
2240 | unsigned i = 0, l = 0, u = 0; | |||
2241 | switch (BuiltinID) { | |||
2242 | default: | |||
2243 | return false; | |||
2244 | #define GET_NEON_IMMEDIATE_CHECK | |||
2245 | #include "clang/Basic/arm_neon.inc" | |||
2246 | #include "clang/Basic/arm_fp16.inc" | |||
2247 | #undef GET_NEON_IMMEDIATE_CHECK | |||
2248 | } | |||
2249 | ||||
2250 | return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); | |||
2251 | } | |||
2252 | ||||
2253 | bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { | |||
2254 | switch (BuiltinID) { | |||
2255 | default: | |||
2256 | return false; | |||
2257 | #include "clang/Basic/arm_mve_builtin_sema.inc" | |||
2258 | } | |||
2259 | } | |||
2260 | ||||
2261 | bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, | |||
2262 | CallExpr *TheCall) { | |||
2263 | bool Err = false; | |||
2264 | switch (BuiltinID) { | |||
2265 | default: | |||
2266 | return false; | |||
2267 | #include "clang/Basic/arm_cde_builtin_sema.inc" | |||
2268 | } | |||
2269 | ||||
2270 | if (Err) | |||
2271 | return true; | |||
2272 | ||||
2273 | return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); | |||
2274 | } | |||
2275 | ||||
2276 | bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, | |||
2277 | const Expr *CoprocArg, bool WantCDE) { | |||
2278 | if (isConstantEvaluated()) | |||
2279 | return false; | |||
2280 | ||||
2281 | // We can't check the value of a dependent argument. | |||
2282 | if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) | |||
2283 | return false; | |||
2284 | ||||
2285 | llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); | |||
2286 | int64_t CoprocNo = CoprocNoAP.getExtValue(); | |||
2287 | assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative")((CoprocNo >= 0 && "Coprocessor immediate must be non-negative" ) ? static_cast<void> (0) : __assert_fail ("CoprocNo >= 0 && \"Coprocessor immediate must be non-negative\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2287, __PRETTY_FUNCTION__)); | |||
2288 | ||||
2289 | uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); | |||
2290 | bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); | |||
2291 | ||||
2292 | if (IsCDECoproc != WantCDE) | |||
2293 | return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) | |||
2294 | << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); | |||
2295 | ||||
2296 | return false; | |||
2297 | } | |||
2298 | ||||
2299 | bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, | |||
2300 | unsigned MaxWidth) { | |||
2301 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)) | |||
2302 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)) | |||
2303 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)) | |||
2304 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)) | |||
2305 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)) | |||
2306 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)) | |||
2307 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)) | |||
2308 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)) | |||
2309 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2309, __PRETTY_FUNCTION__)); | |||
2310 | bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || | |||
2311 | BuiltinID == ARM::BI__builtin_arm_ldaex || | |||
2312 | BuiltinID == AArch64::BI__builtin_arm_ldrex || | |||
2313 | BuiltinID == AArch64::BI__builtin_arm_ldaex; | |||
2314 | ||||
2315 | DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); | |||
2316 | ||||
2317 | // Ensure that we have the proper number of arguments. | |||
2318 | if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) | |||
2319 | return true; | |||
2320 | ||||
2321 | // Inspect the pointer argument of the atomic builtin. This should always be | |||
2322 | // a pointer type, whose element is an integral scalar or pointer type. | |||
2323 | // Because it is a pointer type, we don't have to worry about any implicit | |||
2324 | // casts here. | |||
2325 | Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); | |||
2326 | ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); | |||
2327 | if (PointerArgRes.isInvalid()) | |||
2328 | return true; | |||
2329 | PointerArg = PointerArgRes.get(); | |||
2330 | ||||
2331 | const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); | |||
2332 | if (!pointerType) { | |||
2333 | Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) | |||
2334 | << PointerArg->getType() << PointerArg->getSourceRange(); | |||
2335 | return true; | |||
2336 | } | |||
2337 | ||||
2338 | // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next | |||
2339 | // task is to insert the appropriate casts into the AST. First work out just | |||
2340 | // what the appropriate type is. | |||
2341 | QualType ValType = pointerType->getPointeeType(); | |||
2342 | QualType AddrType = ValType.getUnqualifiedType().withVolatile(); | |||
2343 | if (IsLdrex) | |||
2344 | AddrType.addConst(); | |||
2345 | ||||
2346 | // Issue a warning if the cast is dodgy. | |||
2347 | CastKind CastNeeded = CK_NoOp; | |||
2348 | if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { | |||
2349 | CastNeeded = CK_BitCast; | |||
2350 | Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) | |||
2351 | << PointerArg->getType() << Context.getPointerType(AddrType) | |||
2352 | << AA_Passing << PointerArg->getSourceRange(); | |||
2353 | } | |||
2354 | ||||
2355 | // Finally, do the cast and replace the argument with the corrected version. | |||
2356 | AddrType = Context.getPointerType(AddrType); | |||
2357 | PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); | |||
2358 | if (PointerArgRes.isInvalid()) | |||
2359 | return true; | |||
2360 | PointerArg = PointerArgRes.get(); | |||
2361 | ||||
2362 | TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); | |||
2363 | ||||
2364 | // In general, we allow ints, floats and pointers to be loaded and stored. | |||
2365 | if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && | |||
2366 | !ValType->isBlockPointerType() && !ValType->isFloatingType()) { | |||
2367 | Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) | |||
2368 | << PointerArg->getType() << PointerArg->getSourceRange(); | |||
2369 | return true; | |||
2370 | } | |||
2371 | ||||
2372 | // But ARM doesn't have instructions to deal with 128-bit versions. | |||
2373 | if (Context.getTypeSize(ValType) > MaxWidth) { | |||
2374 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2374, __PRETTY_FUNCTION__)); | |||
2375 | Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) | |||
2376 | << PointerArg->getType() << PointerArg->getSourceRange(); | |||
2377 | return true; | |||
2378 | } | |||
2379 | ||||
2380 | switch (ValType.getObjCLifetime()) { | |||
2381 | case Qualifiers::OCL_None: | |||
2382 | case Qualifiers::OCL_ExplicitNone: | |||
2383 | // okay | |||
2384 | break; | |||
2385 | ||||
2386 | case Qualifiers::OCL_Weak: | |||
2387 | case Qualifiers::OCL_Strong: | |||
2388 | case Qualifiers::OCL_Autoreleasing: | |||
2389 | Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) | |||
2390 | << ValType << PointerArg->getSourceRange(); | |||
2391 | return true; | |||
2392 | } | |||
2393 | ||||
2394 | if (IsLdrex) { | |||
2395 | TheCall->setType(ValType); | |||
2396 | return false; | |||
2397 | } | |||
2398 | ||||
2399 | // Initialize the argument to be stored. | |||
2400 | ExprResult ValArg = TheCall->getArg(0); | |||
2401 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
2402 | Context, ValType, /*consume*/ false); | |||
2403 | ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); | |||
2404 | if (ValArg.isInvalid()) | |||
2405 | return true; | |||
2406 | TheCall->setArg(0, ValArg.get()); | |||
2407 | ||||
2408 | // __builtin_arm_strex always returns an int. It's marked as such in the .def, | |||
2409 | // but the custom checker bypasses all default analysis. | |||
2410 | TheCall->setType(Context.IntTy); | |||
2411 | return false; | |||
2412 | } | |||
2413 | ||||
2414 | bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, | |||
2415 | CallExpr *TheCall) { | |||
2416 | if (BuiltinID == ARM::BI__builtin_arm_ldrex || | |||
2417 | BuiltinID == ARM::BI__builtin_arm_ldaex || | |||
2418 | BuiltinID == ARM::BI__builtin_arm_strex || | |||
2419 | BuiltinID == ARM::BI__builtin_arm_stlex) { | |||
2420 | return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); | |||
2421 | } | |||
2422 | ||||
2423 | if (BuiltinID == ARM::BI__builtin_arm_prefetch) { | |||
2424 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || | |||
2425 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); | |||
2426 | } | |||
2427 | ||||
2428 | if (BuiltinID == ARM::BI__builtin_arm_rsr64 || | |||
2429 | BuiltinID == ARM::BI__builtin_arm_wsr64) | |||
2430 | return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); | |||
2431 | ||||
2432 | if (BuiltinID == ARM::BI__builtin_arm_rsr || | |||
2433 | BuiltinID == ARM::BI__builtin_arm_rsrp || | |||
2434 | BuiltinID == ARM::BI__builtin_arm_wsr || | |||
2435 | BuiltinID == ARM::BI__builtin_arm_wsrp) | |||
2436 | return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); | |||
2437 | ||||
2438 | if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) | |||
2439 | return true; | |||
2440 | if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) | |||
2441 | return true; | |||
2442 | if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) | |||
2443 | return true; | |||
2444 | ||||
2445 | // For intrinsics which take an immediate value as part of the instruction, | |||
2446 | // range check them here. | |||
2447 | // FIXME: VFP Intrinsics should error if VFP not present. | |||
2448 | switch (BuiltinID) { | |||
2449 | default: return false; | |||
2450 | case ARM::BI__builtin_arm_ssat: | |||
2451 | return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); | |||
2452 | case ARM::BI__builtin_arm_usat: | |||
2453 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); | |||
2454 | case ARM::BI__builtin_arm_ssat16: | |||
2455 | return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); | |||
2456 | case ARM::BI__builtin_arm_usat16: | |||
2457 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); | |||
2458 | case ARM::BI__builtin_arm_vcvtr_f: | |||
2459 | case ARM::BI__builtin_arm_vcvtr_d: | |||
2460 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); | |||
2461 | case ARM::BI__builtin_arm_dmb: | |||
2462 | case ARM::BI__builtin_arm_dsb: | |||
2463 | case ARM::BI__builtin_arm_isb: | |||
2464 | case ARM::BI__builtin_arm_dbg: | |||
2465 | return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); | |||
2466 | case ARM::BI__builtin_arm_cdp: | |||
2467 | case ARM::BI__builtin_arm_cdp2: | |||
2468 | case ARM::BI__builtin_arm_mcr: | |||
2469 | case ARM::BI__builtin_arm_mcr2: | |||
2470 | case ARM::BI__builtin_arm_mrc: | |||
2471 | case ARM::BI__builtin_arm_mrc2: | |||
2472 | case ARM::BI__builtin_arm_mcrr: | |||
2473 | case ARM::BI__builtin_arm_mcrr2: | |||
2474 | case ARM::BI__builtin_arm_mrrc: | |||
2475 | case ARM::BI__builtin_arm_mrrc2: | |||
2476 | case ARM::BI__builtin_arm_ldc: | |||
2477 | case ARM::BI__builtin_arm_ldcl: | |||
2478 | case ARM::BI__builtin_arm_ldc2: | |||
2479 | case ARM::BI__builtin_arm_ldc2l: | |||
2480 | case ARM::BI__builtin_arm_stc: | |||
2481 | case ARM::BI__builtin_arm_stcl: | |||
2482 | case ARM::BI__builtin_arm_stc2: | |||
2483 | case ARM::BI__builtin_arm_stc2l: | |||
2484 | return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || | |||
2485 | CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), | |||
2486 | /*WantCDE*/ false); | |||
2487 | } | |||
2488 | } | |||
2489 | ||||
2490 | bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, | |||
2491 | unsigned BuiltinID, | |||
2492 | CallExpr *TheCall) { | |||
2493 | if (BuiltinID == AArch64::BI__builtin_arm_ldrex || | |||
2494 | BuiltinID == AArch64::BI__builtin_arm_ldaex || | |||
2495 | BuiltinID == AArch64::BI__builtin_arm_strex || | |||
2496 | BuiltinID == AArch64::BI__builtin_arm_stlex) { | |||
2497 | return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); | |||
2498 | } | |||
2499 | ||||
2500 | if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { | |||
2501 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || | |||
2502 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || | |||
2503 | SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || | |||
2504 | SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); | |||
2505 | } | |||
2506 | ||||
2507 | if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || | |||
2508 | BuiltinID == AArch64::BI__builtin_arm_wsr64) | |||
2509 | return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); | |||
2510 | ||||
2511 | // Memory Tagging Extensions (MTE) Intrinsics | |||
2512 | if (BuiltinID == AArch64::BI__builtin_arm_irg || | |||
2513 | BuiltinID == AArch64::BI__builtin_arm_addg || | |||
2514 | BuiltinID == AArch64::BI__builtin_arm_gmi || | |||
2515 | BuiltinID == AArch64::BI__builtin_arm_ldg || | |||
2516 | BuiltinID == AArch64::BI__builtin_arm_stg || | |||
2517 | BuiltinID == AArch64::BI__builtin_arm_subp) { | |||
2518 | return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); | |||
2519 | } | |||
2520 | ||||
2521 | if (BuiltinID == AArch64::BI__builtin_arm_rsr || | |||
2522 | BuiltinID == AArch64::BI__builtin_arm_rsrp || | |||
2523 | BuiltinID == AArch64::BI__builtin_arm_wsr || | |||
2524 | BuiltinID == AArch64::BI__builtin_arm_wsrp) | |||
2525 | return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); | |||
2526 | ||||
2527 | // Only check the valid encoding range. Any constant in this range would be | |||
2528 | // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw | |||
2529 | // an exception for incorrect registers. This matches MSVC behavior. | |||
2530 | if (BuiltinID == AArch64::BI_ReadStatusReg || | |||
2531 | BuiltinID == AArch64::BI_WriteStatusReg) | |||
2532 | return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); | |||
2533 | ||||
2534 | if (BuiltinID == AArch64::BI__getReg) | |||
2535 | return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); | |||
2536 | ||||
2537 | if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) | |||
2538 | return true; | |||
2539 | ||||
2540 | if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) | |||
2541 | return true; | |||
2542 | ||||
2543 | // For intrinsics which take an immediate value as part of the instruction, | |||
2544 | // range check them here. | |||
2545 | unsigned i = 0, l = 0, u = 0; | |||
2546 | switch (BuiltinID) { | |||
2547 | default: return false; | |||
2548 | case AArch64::BI__builtin_arm_dmb: | |||
2549 | case AArch64::BI__builtin_arm_dsb: | |||
2550 | case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; | |||
2551 | case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; | |||
2552 | } | |||
2553 | ||||
2554 | return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); | |||
2555 | } | |||
2556 | ||||
2557 | static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { | |||
2558 | if (Arg->getType()->getAsPlaceholderType()) | |||
2559 | return false; | |||
2560 | ||||
2561 | // The first argument needs to be a record field access. | |||
2562 | // If it is an array element access, we delay decision | |||
2563 | // to BPF backend to check whether the access is a | |||
2564 | // field access or not. | |||
2565 | return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || | |||
2566 | dyn_cast<MemberExpr>(Arg->IgnoreParens()) || | |||
2567 | dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); | |||
2568 | } | |||
2569 | ||||
2570 | static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, | |||
2571 | QualType VectorTy, QualType EltTy) { | |||
2572 | QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); | |||
2573 | if (!Context.hasSameType(VectorEltTy, EltTy)) { | |||
2574 | S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) | |||
2575 | << Call->getSourceRange() << VectorEltTy << EltTy; | |||
2576 | return false; | |||
2577 | } | |||
2578 | return true; | |||
2579 | } | |||
2580 | ||||
2581 | static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { | |||
2582 | QualType ArgType = Arg->getType(); | |||
2583 | if (ArgType->getAsPlaceholderType()) | |||
2584 | return false; | |||
2585 | ||||
2586 | // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type | |||
2587 | // format: | |||
2588 | // 1. __builtin_preserve_type_info(*(<type> *)0, flag); | |||
2589 | // 2. <type> var; | |||
2590 | // __builtin_preserve_type_info(var, flag); | |||
2591 | if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && | |||
2592 | !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) | |||
2593 | return false; | |||
2594 | ||||
2595 | // Typedef type. | |||
2596 | if (ArgType->getAs<TypedefType>()) | |||
2597 | return true; | |||
2598 | ||||
2599 | // Record type or Enum type. | |||
2600 | const Type *Ty = ArgType->getUnqualifiedDesugaredType(); | |||
2601 | if (const auto *RT = Ty->getAs<RecordType>()) { | |||
2602 | if (!RT->getDecl()->getDeclName().isEmpty()) | |||
2603 | return true; | |||
2604 | } else if (const auto *ET = Ty->getAs<EnumType>()) { | |||
2605 | if (!ET->getDecl()->getDeclName().isEmpty()) | |||
2606 | return true; | |||
2607 | } | |||
2608 | ||||
2609 | return false; | |||
2610 | } | |||
2611 | ||||
2612 | static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { | |||
2613 | QualType ArgType = Arg->getType(); | |||
2614 | if (ArgType->getAsPlaceholderType()) | |||
2615 | return false; | |||
2616 | ||||
2617 | // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type | |||
2618 | // format: | |||
2619 | // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, | |||
2620 | // flag); | |||
2621 | const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); | |||
2622 | if (!UO) | |||
2623 | return false; | |||
2624 | ||||
2625 | const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); | |||
2626 | if (!CE || CE->getCastKind() != CK_IntegralToPointer) | |||
2627 | return false; | |||
2628 | ||||
2629 | // The integer must be from an EnumConstantDecl. | |||
2630 | const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); | |||
2631 | if (!DR) | |||
2632 | return false; | |||
2633 | ||||
2634 | const EnumConstantDecl *Enumerator = | |||
2635 | dyn_cast<EnumConstantDecl>(DR->getDecl()); | |||
2636 | if (!Enumerator) | |||
2637 | return false; | |||
2638 | ||||
2639 | // The type must be EnumType. | |||
2640 | const Type *Ty = ArgType->getUnqualifiedDesugaredType(); | |||
2641 | const auto *ET = Ty->getAs<EnumType>(); | |||
2642 | if (!ET) | |||
2643 | return false; | |||
2644 | ||||
2645 | // The enum value must be supported. | |||
2646 | for (auto *EDI : ET->getDecl()->enumerators()) { | |||
2647 | if (EDI == Enumerator) | |||
2648 | return true; | |||
2649 | } | |||
2650 | ||||
2651 | return false; | |||
2652 | } | |||
2653 | ||||
2654 | bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, | |||
2655 | CallExpr *TheCall) { | |||
2656 | assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||(((BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && "unexpected BPF builtin") ? static_cast<void> (0) : __assert_fail ("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2660, __PRETTY_FUNCTION__)) | |||
2657 | BuiltinID == BPF::BI__builtin_btf_type_id ||(((BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && "unexpected BPF builtin") ? static_cast<void> (0) : __assert_fail ("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2660, __PRETTY_FUNCTION__)) | |||
2658 | BuiltinID == BPF::BI__builtin_preserve_type_info ||(((BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && "unexpected BPF builtin") ? static_cast<void> (0) : __assert_fail ("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2660, __PRETTY_FUNCTION__)) | |||
2659 | BuiltinID == BPF::BI__builtin_preserve_enum_value) &&(((BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && "unexpected BPF builtin") ? static_cast<void> (0) : __assert_fail ("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2660, __PRETTY_FUNCTION__)) | |||
2660 | "unexpected BPF builtin")(((BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && "unexpected BPF builtin") ? static_cast<void> (0) : __assert_fail ("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 2660, __PRETTY_FUNCTION__)); | |||
2661 | ||||
2662 | if (checkArgCount(*this, TheCall, 2)) | |||
2663 | return true; | |||
2664 | ||||
2665 | // The second argument needs to be a constant int | |||
2666 | Expr *Arg = TheCall->getArg(1); | |||
2667 | Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); | |||
2668 | diag::kind kind; | |||
2669 | if (!Value) { | |||
2670 | if (BuiltinID == BPF::BI__builtin_preserve_field_info) | |||
2671 | kind = diag::err_preserve_field_info_not_const; | |||
2672 | else if (BuiltinID == BPF::BI__builtin_btf_type_id) | |||
2673 | kind = diag::err_btf_type_id_not_const; | |||
2674 | else if (BuiltinID == BPF::BI__builtin_preserve_type_info) | |||
2675 | kind = diag::err_preserve_type_info_not_const; | |||
2676 | else | |||
2677 | kind = diag::err_preserve_enum_value_not_const; | |||
2678 | Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); | |||
2679 | return true; | |||
2680 | } | |||
2681 | ||||
2682 | // The first argument | |||
2683 | Arg = TheCall->getArg(0); | |||
2684 | bool InvalidArg = false; | |||
2685 | bool ReturnUnsignedInt = true; | |||
2686 | if (BuiltinID == BPF::BI__builtin_preserve_field_info) { | |||
2687 | if (!isValidBPFPreserveFieldInfoArg(Arg)) { | |||
2688 | InvalidArg = true; | |||
2689 | kind = diag::err_preserve_field_info_not_field; | |||
2690 | } | |||
2691 | } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { | |||
2692 | if (!isValidBPFPreserveTypeInfoArg(Arg)) { | |||
2693 | InvalidArg = true; | |||
2694 | kind = diag::err_preserve_type_info_invalid; | |||
2695 | } | |||
2696 | } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { | |||
2697 | if (!isValidBPFPreserveEnumValueArg(Arg)) { | |||
2698 | InvalidArg = true; | |||
2699 | kind = diag::err_preserve_enum_value_invalid; | |||
2700 | } | |||
2701 | ReturnUnsignedInt = false; | |||
2702 | } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { | |||
2703 | ReturnUnsignedInt = false; | |||
2704 | } | |||
2705 | ||||
2706 | if (InvalidArg) { | |||
2707 | Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); | |||
2708 | return true; | |||
2709 | } | |||
2710 | ||||
2711 | if (ReturnUnsignedInt) | |||
2712 | TheCall->setType(Context.UnsignedIntTy); | |||
2713 | else | |||
2714 | TheCall->setType(Context.UnsignedLongTy); | |||
2715 | return false; | |||
2716 | } | |||
2717 | ||||
2718 | bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { | |||
2719 | struct ArgInfo { | |||
2720 | uint8_t OpNum; | |||
2721 | bool IsSigned; | |||
2722 | uint8_t BitWidth; | |||
2723 | uint8_t Align; | |||
2724 | }; | |||
2725 | struct BuiltinInfo { | |||
2726 | unsigned BuiltinID; | |||
2727 | ArgInfo Infos[2]; | |||
2728 | }; | |||
2729 | ||||
2730 | static BuiltinInfo Infos[] = { | |||
2731 | { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, | |||
2732 | { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, | |||
2733 | { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, | |||
2734 | { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, | |||
2735 | { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, | |||
2736 | { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, | |||
2737 | { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, | |||
2738 | { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, | |||
2739 | { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, | |||
2740 | { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, | |||
2741 | { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, | |||
2742 | ||||
2743 | { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, | |||
2744 | { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, | |||
2745 | { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, | |||
2746 | { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, | |||
2747 | { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, | |||
2748 | { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, | |||
2749 | { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, | |||
2750 | { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, | |||
2751 | { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, | |||
2752 | { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, | |||
2753 | { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, | |||
2754 | ||||
2755 | { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, | |||
2756 | { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, | |||
2757 | { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, | |||
2758 | { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, | |||
2759 | { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, | |||
2760 | { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, | |||
2761 | { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, | |||
2762 | { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, | |||
2763 | { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, | |||
2764 | { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, | |||
2765 | { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, | |||
2766 | { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, | |||
2767 | { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, | |||
2768 | { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, | |||
2769 | { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, | |||
2770 | { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, | |||
2771 | { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, | |||
2772 | { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, | |||
2773 | { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, | |||
2774 | { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, | |||
2775 | { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, | |||
2776 | { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, | |||
2777 | { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, | |||
2778 | { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, | |||
2779 | { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, | |||
2780 | { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, | |||
2781 | { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, | |||
2782 | { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, | |||
2783 | { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, | |||
2784 | { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, | |||
2785 | { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, | |||
2786 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, | |||
2787 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, | |||
2788 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, | |||
2789 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, | |||
2790 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, | |||
2791 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, | |||
2792 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, | |||
2793 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, | |||
2794 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, | |||
2795 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, | |||
2796 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, | |||
2797 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, | |||
2798 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, | |||
2799 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, | |||
2800 | { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, | |||
2801 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, | |||
2802 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, | |||
2803 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, | |||
2804 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, | |||
2805 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, | |||
2806 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, | |||
2807 | {{ 1, false, 6, 0 }} }, | |||
2808 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, | |||
2809 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, | |||
2810 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, | |||
2811 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, | |||
2812 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, | |||
2813 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, | |||
2814 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, | |||
2815 | {{ 1, false, 5, 0 }} }, | |||
2816 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, | |||
2817 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, | |||
2818 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, | |||
2819 | { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, | |||
2820 | { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, | |||
2821 | { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, | |||
2822 | { 2, false, 5, 0 }} }, | |||
2823 | { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, | |||
2824 | { 2, false, 6, 0 }} }, | |||
2825 | { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, | |||
2826 | { 3, false, 5, 0 }} }, | |||
2827 | { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, | |||
2828 | { 3, false, 6, 0 }} }, | |||
2829 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, | |||
2830 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, | |||
2831 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, | |||
2832 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, | |||
2833 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, | |||
2834 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, | |||
2835 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, | |||
2836 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, | |||
2837 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, | |||
2838 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, | |||
2839 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, | |||
2840 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, | |||
2841 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, | |||
2842 | { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, | |||
2843 | { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, | |||
2844 | { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, | |||
2845 | {{ 2, false, 4, 0 }, | |||
2846 | { 3, false, 5, 0 }} }, | |||
2847 | { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, | |||
2848 | {{ 2, false, 4, 0 }, | |||
2849 | { 3, false, 5, 0 }} }, | |||
2850 | { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, | |||
2851 | {{ 2, false, 4, 0 }, | |||
2852 | { 3, false, 5, 0 }} }, | |||
2853 | { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, | |||
2854 | {{ 2, false, 4, 0 }, | |||
2855 | { 3, false, 5, 0 }} }, | |||
2856 | { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, | |||
2857 | { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, | |||
2858 | { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, | |||
2859 | { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, | |||
2860 | { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, | |||
2861 | { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, | |||
2862 | { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, | |||
2863 | { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, | |||
2864 | { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, | |||
2865 | { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, | |||
2866 | { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, | |||
2867 | { 2, false, 5, 0 }} }, | |||
2868 | { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, | |||
2869 | { 2, false, 6, 0 }} }, | |||
2870 | { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, | |||
2871 | { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, | |||
2872 | { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, | |||
2873 | { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, | |||
2874 | { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, | |||
2875 | { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, | |||
2876 | { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, | |||
2877 | { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, | |||
2878 | { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, | |||
2879 | {{ 1, false, 4, 0 }} }, | |||
2880 | { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, | |||
2881 | { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, | |||
2882 | {{ 1, false, 4, 0 }} }, | |||
2883 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, | |||
2884 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, | |||
2885 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, | |||
2886 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, | |||
2887 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, | |||
2888 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, | |||
2889 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, | |||
2890 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, | |||
2891 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, | |||
2892 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, | |||
2893 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, | |||
2894 | { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, | |||
2895 | { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, | |||
2896 | { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, | |||
2897 | { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, | |||
2898 | { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, | |||
2899 | { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, | |||
2900 | { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, | |||
2901 | { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, | |||
2902 | { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, | |||
2903 | {{ 3, false, 1, 0 }} }, | |||
2904 | { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, | |||
2905 | { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, | |||
2906 | { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, | |||
2907 | { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, | |||
2908 | {{ 3, false, 1, 0 }} }, | |||
2909 | { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, | |||
2910 | { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, | |||
2911 | { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, | |||
2912 | { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, | |||
2913 | {{ 3, false, 1, 0 }} }, | |||
2914 | }; | |||
2915 | ||||
2916 | // Use a dynamically initialized static to sort the table exactly once on | |||
2917 | // first run. | |||
2918 | static const bool SortOnce = | |||
2919 | (llvm::sort(Infos, | |||
2920 | [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { | |||
2921 | return LHS.BuiltinID < RHS.BuiltinID; | |||
2922 | }), | |||
2923 | true); | |||
2924 | (void)SortOnce; | |||
2925 | ||||
2926 | const BuiltinInfo *F = llvm::partition_point( | |||
2927 | Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); | |||
2928 | if (F == std::end(Infos) || F->BuiltinID != BuiltinID) | |||
2929 | return false; | |||
2930 | ||||
2931 | bool Error = false; | |||
2932 | ||||
2933 | for (const ArgInfo &A : F->Infos) { | |||
2934 | // Ignore empty ArgInfo elements. | |||
2935 | if (A.BitWidth == 0) | |||
2936 | continue; | |||
2937 | ||||
2938 | int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; | |||
2939 | int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; | |||
2940 | if (!A.Align) { | |||
2941 | Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); | |||
2942 | } else { | |||
2943 | unsigned M = 1 << A.Align; | |||
2944 | Min *= M; | |||
2945 | Max *= M; | |||
2946 | Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | | |||
2947 | SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); | |||
2948 | } | |||
2949 | } | |||
2950 | return Error; | |||
2951 | } | |||
2952 | ||||
2953 | bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, | |||
2954 | CallExpr *TheCall) { | |||
2955 | return CheckHexagonBuiltinArgument(BuiltinID, TheCall); | |||
2956 | } | |||
2957 | ||||
2958 | bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, | |||
2959 | unsigned BuiltinID, CallExpr *TheCall) { | |||
2960 | return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || | |||
2961 | CheckMipsBuiltinArgument(BuiltinID, TheCall); | |||
2962 | } | |||
2963 | ||||
2964 | bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, | |||
2965 | CallExpr *TheCall) { | |||
2966 | ||||
2967 | if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && | |||
2968 | BuiltinID <= Mips::BI__builtin_mips_lwx) { | |||
2969 | if (!TI.hasFeature("dsp")) | |||
2970 | return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); | |||
2971 | } | |||
2972 | ||||
2973 | if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && | |||
2974 | BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { | |||
2975 | if (!TI.hasFeature("dspr2")) | |||
2976 | return Diag(TheCall->getBeginLoc(), | |||
2977 | diag::err_mips_builtin_requires_dspr2); | |||
2978 | } | |||
2979 | ||||
2980 | if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && | |||
2981 | BuiltinID <= Mips::BI__builtin_msa_xori_b) { | |||
2982 | if (!TI.hasFeature("msa")) | |||
2983 | return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); | |||
2984 | } | |||
2985 | ||||
2986 | return false; | |||
2987 | } | |||
2988 | ||||
2989 | // CheckMipsBuiltinArgument - Checks the constant value passed to the | |||
2990 | // intrinsic is correct. The switch statement is ordered by DSP, MSA. The | |||
2991 | // ordering for DSP is unspecified. MSA is ordered by the data format used | |||
2992 | // by the underlying instruction i.e., df/m, df/n and then by size. | |||
2993 | // | |||
2994 | // FIXME: The size tests here should instead be tablegen'd along with the | |||
2995 | // definitions from include/clang/Basic/BuiltinsMips.def. | |||
2996 | // FIXME: GCC is strict on signedness for some of these intrinsics, we should | |||
2997 | // be too. | |||
2998 | bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { | |||
2999 | unsigned i = 0, l = 0, u = 0, m = 0; | |||
3000 | switch (BuiltinID) { | |||
3001 | default: return false; | |||
3002 | case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; | |||
3003 | case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; | |||
3004 | case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; | |||
3005 | case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; | |||
3006 | case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; | |||
3007 | case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; | |||
3008 | case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; | |||
3009 | // MSA intrinsics. Instructions (which the intrinsics maps to) which use the | |||
3010 | // df/m field. | |||
3011 | // These intrinsics take an unsigned 3 bit immediate. | |||
3012 | case Mips::BI__builtin_msa_bclri_b: | |||
3013 | case Mips::BI__builtin_msa_bnegi_b: | |||
3014 | case Mips::BI__builtin_msa_bseti_b: | |||
3015 | case Mips::BI__builtin_msa_sat_s_b: | |||
3016 | case Mips::BI__builtin_msa_sat_u_b: | |||
3017 | case Mips::BI__builtin_msa_slli_b: | |||
3018 | case Mips::BI__builtin_msa_srai_b: | |||
3019 | case Mips::BI__builtin_msa_srari_b: | |||
3020 | case Mips::BI__builtin_msa_srli_b: | |||
3021 | case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; | |||
3022 | case Mips::BI__builtin_msa_binsli_b: | |||
3023 | case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; | |||
3024 | // These intrinsics take an unsigned 4 bit immediate. | |||
3025 | case Mips::BI__builtin_msa_bclri_h: | |||
3026 | case Mips::BI__builtin_msa_bnegi_h: | |||
3027 | case Mips::BI__builtin_msa_bseti_h: | |||
3028 | case Mips::BI__builtin_msa_sat_s_h: | |||
3029 | case Mips::BI__builtin_msa_sat_u_h: | |||
3030 | case Mips::BI__builtin_msa_slli_h: | |||
3031 | case Mips::BI__builtin_msa_srai_h: | |||
3032 | case Mips::BI__builtin_msa_srari_h: | |||
3033 | case Mips::BI__builtin_msa_srli_h: | |||
3034 | case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; | |||
3035 | case Mips::BI__builtin_msa_binsli_h: | |||
3036 | case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; | |||
3037 | // These intrinsics take an unsigned 5 bit immediate. | |||
3038 | // The first block of intrinsics actually have an unsigned 5 bit field, | |||
3039 | // not a df/n field. | |||
3040 | case Mips::BI__builtin_msa_cfcmsa: | |||
3041 | case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; | |||
3042 | case Mips::BI__builtin_msa_clei_u_b: | |||
3043 | case Mips::BI__builtin_msa_clei_u_h: | |||
3044 | case Mips::BI__builtin_msa_clei_u_w: | |||
3045 | case Mips::BI__builtin_msa_clei_u_d: | |||
3046 | case Mips::BI__builtin_msa_clti_u_b: | |||
3047 | case Mips::BI__builtin_msa_clti_u_h: | |||
3048 | case Mips::BI__builtin_msa_clti_u_w: | |||
3049 | case Mips::BI__builtin_msa_clti_u_d: | |||
3050 | case Mips::BI__builtin_msa_maxi_u_b: | |||
3051 | case Mips::BI__builtin_msa_maxi_u_h: | |||
3052 | case Mips::BI__builtin_msa_maxi_u_w: | |||
3053 | case Mips::BI__builtin_msa_maxi_u_d: | |||
3054 | case Mips::BI__builtin_msa_mini_u_b: | |||
3055 | case Mips::BI__builtin_msa_mini_u_h: | |||
3056 | case Mips::BI__builtin_msa_mini_u_w: | |||
3057 | case Mips::BI__builtin_msa_mini_u_d: | |||
3058 | case Mips::BI__builtin_msa_addvi_b: | |||
3059 | case Mips::BI__builtin_msa_addvi_h: | |||
3060 | case Mips::BI__builtin_msa_addvi_w: | |||
3061 | case Mips::BI__builtin_msa_addvi_d: | |||
3062 | case Mips::BI__builtin_msa_bclri_w: | |||
3063 | case Mips::BI__builtin_msa_bnegi_w: | |||
3064 | case Mips::BI__builtin_msa_bseti_w: | |||
3065 | case Mips::BI__builtin_msa_sat_s_w: | |||
3066 | case Mips::BI__builtin_msa_sat_u_w: | |||
3067 | case Mips::BI__builtin_msa_slli_w: | |||
3068 | case Mips::BI__builtin_msa_srai_w: | |||
3069 | case Mips::BI__builtin_msa_srari_w: | |||
3070 | case Mips::BI__builtin_msa_srli_w: | |||
3071 | case Mips::BI__builtin_msa_srlri_w: | |||
3072 | case Mips::BI__builtin_msa_subvi_b: | |||
3073 | case Mips::BI__builtin_msa_subvi_h: | |||
3074 | case Mips::BI__builtin_msa_subvi_w: | |||
3075 | case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; | |||
3076 | case Mips::BI__builtin_msa_binsli_w: | |||
3077 | case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; | |||
3078 | // These intrinsics take an unsigned 6 bit immediate. | |||
3079 | case Mips::BI__builtin_msa_bclri_d: | |||
3080 | case Mips::BI__builtin_msa_bnegi_d: | |||
3081 | case Mips::BI__builtin_msa_bseti_d: | |||
3082 | case Mips::BI__builtin_msa_sat_s_d: | |||
3083 | case Mips::BI__builtin_msa_sat_u_d: | |||
3084 | case Mips::BI__builtin_msa_slli_d: | |||
3085 | case Mips::BI__builtin_msa_srai_d: | |||
3086 | case Mips::BI__builtin_msa_srari_d: | |||
3087 | case Mips::BI__builtin_msa_srli_d: | |||
3088 | case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; | |||
3089 | case Mips::BI__builtin_msa_binsli_d: | |||
3090 | case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; | |||
3091 | // These intrinsics take a signed 5 bit immediate. | |||
3092 | case Mips::BI__builtin_msa_ceqi_b: | |||
3093 | case Mips::BI__builtin_msa_ceqi_h: | |||
3094 | case Mips::BI__builtin_msa_ceqi_w: | |||
3095 | case Mips::BI__builtin_msa_ceqi_d: | |||
3096 | case Mips::BI__builtin_msa_clti_s_b: | |||
3097 | case Mips::BI__builtin_msa_clti_s_h: | |||
3098 | case Mips::BI__builtin_msa_clti_s_w: | |||
3099 | case Mips::BI__builtin_msa_clti_s_d: | |||
3100 | case Mips::BI__builtin_msa_clei_s_b: | |||
3101 | case Mips::BI__builtin_msa_clei_s_h: | |||
3102 | case Mips::BI__builtin_msa_clei_s_w: | |||
3103 | case Mips::BI__builtin_msa_clei_s_d: | |||
3104 | case Mips::BI__builtin_msa_maxi_s_b: | |||
3105 | case Mips::BI__builtin_msa_maxi_s_h: | |||
3106 | case Mips::BI__builtin_msa_maxi_s_w: | |||
3107 | case Mips::BI__builtin_msa_maxi_s_d: | |||
3108 | case Mips::BI__builtin_msa_mini_s_b: | |||
3109 | case Mips::BI__builtin_msa_mini_s_h: | |||
3110 | case Mips::BI__builtin_msa_mini_s_w: | |||
3111 | case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; | |||
3112 | // These intrinsics take an unsigned 8 bit immediate. | |||
3113 | case Mips::BI__builtin_msa_andi_b: | |||
3114 | case Mips::BI__builtin_msa_nori_b: | |||
3115 | case Mips::BI__builtin_msa_ori_b: | |||
3116 | case Mips::BI__builtin_msa_shf_b: | |||
3117 | case Mips::BI__builtin_msa_shf_h: | |||
3118 | case Mips::BI__builtin_msa_shf_w: | |||
3119 | case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; | |||
3120 | case Mips::BI__builtin_msa_bseli_b: | |||
3121 | case Mips::BI__builtin_msa_bmnzi_b: | |||
3122 | case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; | |||
3123 | // df/n format | |||
3124 | // These intrinsics take an unsigned 4 bit immediate. | |||
3125 | case Mips::BI__builtin_msa_copy_s_b: | |||
3126 | case Mips::BI__builtin_msa_copy_u_b: | |||
3127 | case Mips::BI__builtin_msa_insve_b: | |||
3128 | case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; | |||
3129 | case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; | |||
3130 | // These intrinsics take an unsigned 3 bit immediate. | |||
3131 | case Mips::BI__builtin_msa_copy_s_h: | |||
3132 | case Mips::BI__builtin_msa_copy_u_h: | |||
3133 | case Mips::BI__builtin_msa_insve_h: | |||
3134 | case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; | |||
3135 | case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; | |||
3136 | // These intrinsics take an unsigned 2 bit immediate. | |||
3137 | case Mips::BI__builtin_msa_copy_s_w: | |||
3138 | case Mips::BI__builtin_msa_copy_u_w: | |||
3139 | case Mips::BI__builtin_msa_insve_w: | |||
3140 | case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; | |||
3141 | case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; | |||
3142 | // These intrinsics take an unsigned 1 bit immediate. | |||
3143 | case Mips::BI__builtin_msa_copy_s_d: | |||
3144 | case Mips::BI__builtin_msa_copy_u_d: | |||
3145 | case Mips::BI__builtin_msa_insve_d: | |||
3146 | case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; | |||
3147 | case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; | |||
3148 | // Memory offsets and immediate loads. | |||
3149 | // These intrinsics take a signed 10 bit immediate. | |||
3150 | case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; | |||
3151 | case Mips::BI__builtin_msa_ldi_h: | |||
3152 | case Mips::BI__builtin_msa_ldi_w: | |||
3153 | case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; | |||
3154 | case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; | |||
3155 | case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; | |||
3156 | case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; | |||
3157 | case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; | |||
3158 | case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; | |||
3159 | case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; | |||
3160 | case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; | |||
3161 | case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; | |||
3162 | case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; | |||
3163 | case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; | |||
3164 | case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; | |||
3165 | case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; | |||
3166 | } | |||
3167 | ||||
3168 | if (!m) | |||
3169 | return SemaBuiltinConstantArgRange(TheCall, i, l, u); | |||
3170 | ||||
3171 | return SemaBuiltinConstantArgRange(TheCall, i, l, u) || | |||
3172 | SemaBuiltinConstantArgMultiple(TheCall, i, m); | |||
3173 | } | |||
3174 | ||||
3175 | /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, | |||
3176 | /// advancing the pointer over the consumed characters. The decoded type is | |||
3177 | /// returned. If the decoded type represents a constant integer with a | |||
3178 | /// constraint on its value then Mask is set to that value. The type descriptors | |||
3179 | /// used in Str are specific to PPC MMA builtins and are documented in the file | |||
3180 | /// defining the PPC builtins. | |||
3181 | static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, | |||
3182 | unsigned &Mask) { | |||
3183 | bool RequireICE = false; | |||
3184 | ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; | |||
3185 | switch (*Str++) { | |||
3186 | case 'V': | |||
3187 | return Context.getVectorType(Context.UnsignedCharTy, 16, | |||
3188 | VectorType::VectorKind::AltiVecVector); | |||
3189 | case 'i': { | |||
3190 | char *End; | |||
3191 | unsigned size = strtoul(Str, &End, 10); | |||
3192 | assert(End != Str && "Missing constant parameter constraint")((End != Str && "Missing constant parameter constraint" ) ? static_cast<void> (0) : __assert_fail ("End != Str && \"Missing constant parameter constraint\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 3192, __PRETTY_FUNCTION__)); | |||
3193 | Str = End; | |||
3194 | Mask = size; | |||
3195 | return Context.IntTy; | |||
3196 | } | |||
3197 | case 'W': { | |||
3198 | char *End; | |||
3199 | unsigned size = strtoul(Str, &End, 10); | |||
3200 | assert(End != Str && "Missing PowerPC MMA type size")((End != Str && "Missing PowerPC MMA type size") ? static_cast <void> (0) : __assert_fail ("End != Str && \"Missing PowerPC MMA type size\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 3200, __PRETTY_FUNCTION__)); | |||
3201 | Str = End; | |||
3202 | QualType Type; | |||
3203 | switch (size) { | |||
3204 | #define PPC_VECTOR_TYPE(typeName, Id, size) \ | |||
3205 | case size: Type = Context.Id##Ty; break; | |||
3206 | #include "clang/Basic/PPCTypes.def" | |||
3207 | default: llvm_unreachable("Invalid PowerPC MMA vector type")::llvm::llvm_unreachable_internal("Invalid PowerPC MMA vector type" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 3207); | |||
3208 | } | |||
3209 | bool CheckVectorArgs = false; | |||
3210 | while (!CheckVectorArgs) { | |||
3211 | switch (*Str++) { | |||
3212 | case '*': | |||
3213 | Type = Context.getPointerType(Type); | |||
3214 | break; | |||
3215 | case 'C': | |||
3216 | Type = Type.withConst(); | |||
3217 | break; | |||
3218 | default: | |||
3219 | CheckVectorArgs = true; | |||
3220 | --Str; | |||
3221 | break; | |||
3222 | } | |||
3223 | } | |||
3224 | return Type; | |||
3225 | } | |||
3226 | default: | |||
3227 | return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); | |||
3228 | } | |||
3229 | } | |||
3230 | ||||
3231 | bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, | |||
3232 | CallExpr *TheCall) { | |||
3233 | unsigned i = 0, l = 0, u = 0; | |||
3234 | bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || | |||
3235 | BuiltinID == PPC::BI__builtin_divdeu || | |||
3236 | BuiltinID == PPC::BI__builtin_bpermd; | |||
3237 | bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; | |||
3238 | bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || | |||
3239 | BuiltinID == PPC::BI__builtin_divweu || | |||
3240 | BuiltinID == PPC::BI__builtin_divde || | |||
3241 | BuiltinID == PPC::BI__builtin_divdeu; | |||
3242 | ||||
3243 | if (Is64BitBltin && !IsTarget64Bit) | |||
3244 | return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) | |||
3245 | << TheCall->getSourceRange(); | |||
3246 | ||||
3247 | if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || | |||
3248 | (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) | |||
3249 | return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) | |||
3250 | << TheCall->getSourceRange(); | |||
3251 | ||||
3252 | auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { | |||
3253 | if (!TI.hasFeature("vsx")) | |||
3254 | return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) | |||
3255 | << TheCall->getSourceRange(); | |||
3256 | return false; | |||
3257 | }; | |||
3258 | ||||
3259 | switch (BuiltinID) { | |||
3260 | default: return false; | |||
3261 | case PPC::BI__builtin_altivec_crypto_vshasigmaw: | |||
3262 | case PPC::BI__builtin_altivec_crypto_vshasigmad: | |||
3263 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || | |||
3264 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); | |||
3265 | case PPC::BI__builtin_altivec_dss: | |||
3266 | return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); | |||
3267 | case PPC::BI__builtin_tbegin: | |||
3268 | case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; | |||
3269 | case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; | |||
3270 | case PPC::BI__builtin_tabortwc: | |||
3271 | case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; | |||
3272 | case PPC::BI__builtin_tabortwci: | |||
3273 | case PPC::BI__builtin_tabortdci: | |||
3274 | return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || | |||
3275 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); | |||
3276 | case PPC::BI__builtin_altivec_dst: | |||
3277 | case PPC::BI__builtin_altivec_dstt: | |||
3278 | case PPC::BI__builtin_altivec_dstst: | |||
3279 | case PPC::BI__builtin_altivec_dststt: | |||
3280 | return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); | |||
3281 | case PPC::BI__builtin_vsx_xxpermdi: | |||
3282 | case PPC::BI__builtin_vsx_xxsldwi: | |||
3283 | return SemaBuiltinVSX(TheCall); | |||
3284 | case PPC::BI__builtin_unpack_vector_int128: | |||
3285 | return SemaVSXCheck(TheCall) || | |||
3286 | SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); | |||
3287 | case PPC::BI__builtin_pack_vector_int128: | |||
3288 | return SemaVSXCheck(TheCall); | |||
3289 | case PPC::BI__builtin_altivec_vgnb: | |||
3290 | return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); | |||
3291 | case PPC::BI__builtin_altivec_vec_replace_elt: | |||
3292 | case PPC::BI__builtin_altivec_vec_replace_unaligned: { | |||
3293 | QualType VecTy = TheCall->getArg(0)->getType(); | |||
3294 | QualType EltTy = TheCall->getArg(1)->getType(); | |||
3295 | unsigned Width = Context.getIntWidth(EltTy); | |||
3296 | return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || | |||
3297 | !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); | |||
3298 | } | |||
3299 | case PPC::BI__builtin_vsx_xxeval: | |||
3300 | return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); | |||
3301 | case PPC::BI__builtin_altivec_vsldbi: | |||
3302 | return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); | |||
3303 | case PPC::BI__builtin_altivec_vsrdbi: | |||
3304 | return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); | |||
3305 | case PPC::BI__builtin_vsx_xxpermx: | |||
3306 | return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); | |||
3307 | #define CUSTOM_BUILTIN(Name, Types, Acc) \ | |||
3308 | case PPC::BI__builtin_##Name: \ | |||
3309 | return SemaBuiltinPPCMMACall(TheCall, Types); | |||
3310 | #include "clang/Basic/BuiltinsPPC.def" | |||
3311 | } | |||
3312 | return SemaBuiltinConstantArgRange(TheCall, i, l, u); | |||
3313 | } | |||
3314 | ||||
3315 | // Check if the given type is a non-pointer PPC MMA type. This function is used | |||
3316 | // in Sema to prevent invalid uses of restricted PPC MMA types. | |||
3317 | bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { | |||
3318 | if (Type->isPointerType() || Type->isArrayType()) | |||
3319 | return false; | |||
3320 | ||||
3321 | QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); | |||
3322 | #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty | |||
3323 | if (false | |||
3324 | #include "clang/Basic/PPCTypes.def" | |||
3325 | ) { | |||
3326 | Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); | |||
3327 | return true; | |||
3328 | } | |||
3329 | return false; | |||
3330 | } | |||
3331 | ||||
3332 | bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, | |||
3333 | CallExpr *TheCall) { | |||
3334 | // position of memory order and scope arguments in the builtin | |||
3335 | unsigned OrderIndex, ScopeIndex; | |||
3336 | switch (BuiltinID) { | |||
3337 | case AMDGPU::BI__builtin_amdgcn_atomic_inc32: | |||
3338 | case AMDGPU::BI__builtin_amdgcn_atomic_inc64: | |||
3339 | case AMDGPU::BI__builtin_amdgcn_atomic_dec32: | |||
3340 | case AMDGPU::BI__builtin_amdgcn_atomic_dec64: | |||
3341 | OrderIndex = 2; | |||
3342 | ScopeIndex = 3; | |||
3343 | break; | |||
3344 | case AMDGPU::BI__builtin_amdgcn_fence: | |||
3345 | OrderIndex = 0; | |||
3346 | ScopeIndex = 1; | |||
3347 | break; | |||
3348 | default: | |||
3349 | return false; | |||
3350 | } | |||
3351 | ||||
3352 | ExprResult Arg = TheCall->getArg(OrderIndex); | |||
3353 | auto ArgExpr = Arg.get(); | |||
3354 | Expr::EvalResult ArgResult; | |||
3355 | ||||
3356 | if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) | |||
3357 | return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) | |||
3358 | << ArgExpr->getType(); | |||
3359 | int ord = ArgResult.Val.getInt().getZExtValue(); | |||
3360 | ||||
3361 | // Check valididty of memory ordering as per C11 / C++11's memody model. | |||
3362 | switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { | |||
3363 | case llvm::AtomicOrderingCABI::acquire: | |||
3364 | case llvm::AtomicOrderingCABI::release: | |||
3365 | case llvm::AtomicOrderingCABI::acq_rel: | |||
3366 | case llvm::AtomicOrderingCABI::seq_cst: | |||
3367 | break; | |||
3368 | default: { | |||
3369 | return Diag(ArgExpr->getBeginLoc(), | |||
3370 | diag::warn_atomic_op_has_invalid_memory_order) | |||
3371 | << ArgExpr->getSourceRange(); | |||
3372 | } | |||
3373 | } | |||
3374 | ||||
3375 | Arg = TheCall->getArg(ScopeIndex); | |||
3376 | ArgExpr = Arg.get(); | |||
3377 | Expr::EvalResult ArgResult1; | |||
3378 | // Check that sync scope is a constant literal | |||
3379 | if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) | |||
3380 | return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) | |||
3381 | << ArgExpr->getType(); | |||
3382 | ||||
3383 | return false; | |||
3384 | } | |||
3385 | ||||
3386 | bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, | |||
3387 | CallExpr *TheCall) { | |||
3388 | if (BuiltinID == SystemZ::BI__builtin_tabort) { | |||
3389 | Expr *Arg = TheCall->getArg(0); | |||
3390 | if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) | |||
3391 | if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) | |||
3392 | return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) | |||
3393 | << Arg->getSourceRange(); | |||
3394 | } | |||
3395 | ||||
3396 | // For intrinsics which take an immediate value as part of the instruction, | |||
3397 | // range check them here. | |||
3398 | unsigned i = 0, l = 0, u = 0; | |||
3399 | switch (BuiltinID) { | |||
3400 | default: return false; | |||
3401 | case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; | |||
3402 | case SystemZ::BI__builtin_s390_verimb: | |||
3403 | case SystemZ::BI__builtin_s390_verimh: | |||
3404 | case SystemZ::BI__builtin_s390_verimf: | |||
3405 | case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; | |||
3406 | case SystemZ::BI__builtin_s390_vfaeb: | |||
3407 | case SystemZ::BI__builtin_s390_vfaeh: | |||
3408 | case SystemZ::BI__builtin_s390_vfaef: | |||
3409 | case SystemZ::BI__builtin_s390_vfaebs: | |||
3410 | case SystemZ::BI__builtin_s390_vfaehs: | |||
3411 | case SystemZ::BI__builtin_s390_vfaefs: | |||
3412 | case SystemZ::BI__builtin_s390_vfaezb: | |||
3413 | case SystemZ::BI__builtin_s390_vfaezh: | |||
3414 | case SystemZ::BI__builtin_s390_vfaezf: | |||
3415 | case SystemZ::BI__builtin_s390_vfaezbs: | |||
3416 | case SystemZ::BI__builtin_s390_vfaezhs: | |||
3417 | case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; | |||
3418 | case SystemZ::BI__builtin_s390_vfisb: | |||
3419 | case SystemZ::BI__builtin_s390_vfidb: | |||
3420 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || | |||
3421 | SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); | |||
3422 | case SystemZ::BI__builtin_s390_vftcisb: | |||
3423 | case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; | |||
3424 | case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; | |||
3425 | case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; | |||
3426 | case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; | |||
3427 | case SystemZ::BI__builtin_s390_vstrcb: | |||
3428 | case SystemZ::BI__builtin_s390_vstrch: | |||
3429 | case SystemZ::BI__builtin_s390_vstrcf: | |||
3430 | case SystemZ::BI__builtin_s390_vstrczb: | |||
3431 | case SystemZ::BI__builtin_s390_vstrczh: | |||
3432 | case SystemZ::BI__builtin_s390_vstrczf: | |||
3433 | case SystemZ::BI__builtin_s390_vstrcbs: | |||
3434 | case SystemZ::BI__builtin_s390_vstrchs: | |||
3435 | case SystemZ::BI__builtin_s390_vstrcfs: | |||
3436 | case SystemZ::BI__builtin_s390_vstrczbs: | |||
3437 | case SystemZ::BI__builtin_s390_vstrczhs: | |||
3438 | case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; | |||
3439 | case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; | |||
3440 | case SystemZ::BI__builtin_s390_vfminsb: | |||
3441 | case SystemZ::BI__builtin_s390_vfmaxsb: | |||
3442 | case SystemZ::BI__builtin_s390_vfmindb: | |||
3443 | case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; | |||
3444 | case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; | |||
3445 | case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; | |||
3446 | } | |||
3447 | return SemaBuiltinConstantArgRange(TheCall, i, l, u); | |||
3448 | } | |||
3449 | ||||
3450 | /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). | |||
3451 | /// This checks that the target supports __builtin_cpu_supports and | |||
3452 | /// that the string argument is constant and valid. | |||
3453 | static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, | |||
3454 | CallExpr *TheCall) { | |||
3455 | Expr *Arg = TheCall->getArg(0); | |||
3456 | ||||
3457 | // Check if the argument is a string literal. | |||
3458 | if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) | |||
3459 | return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) | |||
3460 | << Arg->getSourceRange(); | |||
3461 | ||||
3462 | // Check the contents of the string. | |||
3463 | StringRef Feature = | |||
3464 | cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); | |||
3465 | if (!TI.validateCpuSupports(Feature)) | |||
3466 | return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) | |||
3467 | << Arg->getSourceRange(); | |||
3468 | return false; | |||
3469 | } | |||
3470 | ||||
3471 | /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). | |||
3472 | /// This checks that the target supports __builtin_cpu_is and | |||
3473 | /// that the string argument is constant and valid. | |||
3474 | static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { | |||
3475 | Expr *Arg = TheCall->getArg(0); | |||
3476 | ||||
3477 | // Check if the argument is a string literal. | |||
3478 | if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) | |||
3479 | return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) | |||
3480 | << Arg->getSourceRange(); | |||
3481 | ||||
3482 | // Check the contents of the string. | |||
3483 | StringRef Feature = | |||
3484 | cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); | |||
3485 | if (!TI.validateCpuIs(Feature)) | |||
3486 | return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) | |||
3487 | << Arg->getSourceRange(); | |||
3488 | return false; | |||
3489 | } | |||
3490 | ||||
3491 | // Check if the rounding mode is legal. | |||
3492 | bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { | |||
3493 | // Indicates if this instruction has rounding control or just SAE. | |||
3494 | bool HasRC = false; | |||
3495 | ||||
3496 | unsigned ArgNum = 0; | |||
3497 | switch (BuiltinID) { | |||
3498 | default: | |||
3499 | return false; | |||
3500 | case X86::BI__builtin_ia32_vcvttsd2si32: | |||
3501 | case X86::BI__builtin_ia32_vcvttsd2si64: | |||
3502 | case X86::BI__builtin_ia32_vcvttsd2usi32: | |||
3503 | case X86::BI__builtin_ia32_vcvttsd2usi64: | |||
3504 | case X86::BI__builtin_ia32_vcvttss2si32: | |||
3505 | case X86::BI__builtin_ia32_vcvttss2si64: | |||
3506 | case X86::BI__builtin_ia32_vcvttss2usi32: | |||
3507 | case X86::BI__builtin_ia32_vcvttss2usi64: | |||
3508 | ArgNum = 1; | |||
3509 | break; | |||
3510 | case X86::BI__builtin_ia32_maxpd512: | |||
3511 | case X86::BI__builtin_ia32_maxps512: | |||
3512 | case X86::BI__builtin_ia32_minpd512: | |||
3513 | case X86::BI__builtin_ia32_minps512: | |||
3514 | ArgNum = 2; | |||
3515 | break; | |||
3516 | case X86::BI__builtin_ia32_cvtps2pd512_mask: | |||
3517 | case X86::BI__builtin_ia32_cvttpd2dq512_mask: | |||
3518 | case X86::BI__builtin_ia32_cvttpd2qq512_mask: | |||
3519 | case X86::BI__builtin_ia32_cvttpd2udq512_mask: | |||
3520 | case X86::BI__builtin_ia32_cvttpd2uqq512_mask: | |||
3521 | case X86::BI__builtin_ia32_cvttps2dq512_mask: | |||
3522 | case X86::BI__builtin_ia32_cvttps2qq512_mask: | |||
3523 | case X86::BI__builtin_ia32_cvttps2udq512_mask: | |||
3524 | case X86::BI__builtin_ia32_cvttps2uqq512_mask: | |||
3525 | case X86::BI__builtin_ia32_exp2pd_mask: | |||
3526 | case X86::BI__builtin_ia32_exp2ps_mask: | |||
3527 | case X86::BI__builtin_ia32_getexppd512_mask: | |||
3528 | case X86::BI__builtin_ia32_getexpps512_mask: | |||
3529 | case X86::BI__builtin_ia32_rcp28pd_mask: | |||
3530 | case X86::BI__builtin_ia32_rcp28ps_mask: | |||
3531 | case X86::BI__builtin_ia32_rsqrt28pd_mask: | |||
3532 | case X86::BI__builtin_ia32_rsqrt28ps_mask: | |||
3533 | case X86::BI__builtin_ia32_vcomisd: | |||
3534 | case X86::BI__builtin_ia32_vcomiss: | |||
3535 | case X86::BI__builtin_ia32_vcvtph2ps512_mask: | |||
3536 | ArgNum = 3; | |||
3537 | break; | |||
3538 | case X86::BI__builtin_ia32_cmppd512_mask: | |||
3539 | case X86::BI__builtin_ia32_cmpps512_mask: | |||
3540 | case X86::BI__builtin_ia32_cmpsd_mask: | |||
3541 | case X86::BI__builtin_ia32_cmpss_mask: | |||
3542 | case X86::BI__builtin_ia32_cvtss2sd_round_mask: | |||
3543 | case X86::BI__builtin_ia32_getexpsd128_round_mask: | |||
3544 | case X86::BI__builtin_ia32_getexpss128_round_mask: | |||
3545 | case X86::BI__builtin_ia32_getmantpd512_mask: | |||
3546 | case X86::BI__builtin_ia32_getmantps512_mask: | |||
3547 | case X86::BI__builtin_ia32_maxsd_round_mask: | |||
3548 | case X86::BI__builtin_ia32_maxss_round_mask: | |||
3549 | case X86::BI__builtin_ia32_minsd_round_mask: | |||
3550 | case X86::BI__builtin_ia32_minss_round_mask: | |||
3551 | case X86::BI__builtin_ia32_rcp28sd_round_mask: | |||
3552 | case X86::BI__builtin_ia32_rcp28ss_round_mask: | |||
3553 | case X86::BI__builtin_ia32_reducepd512_mask: | |||
3554 | case X86::BI__builtin_ia32_reduceps512_mask: | |||
3555 | case X86::BI__builtin_ia32_rndscalepd_mask: | |||
3556 | case X86::BI__builtin_ia32_rndscaleps_mask: | |||
3557 | case X86::BI__builtin_ia32_rsqrt28sd_round_mask: | |||
3558 | case X86::BI__builtin_ia32_rsqrt28ss_round_mask: | |||
3559 | ArgNum = 4; | |||
3560 | break; | |||
3561 | case X86::BI__builtin_ia32_fixupimmpd512_mask: | |||
3562 | case X86::BI__builtin_ia32_fixupimmpd512_maskz: | |||
3563 | case X86::BI__builtin_ia32_fixupimmps512_mask: | |||
3564 | case X86::BI__builtin_ia32_fixupimmps512_maskz: | |||
3565 | case X86::BI__builtin_ia32_fixupimmsd_mask: | |||
3566 | case X86::BI__builtin_ia32_fixupimmsd_maskz: | |||
3567 | case X86::BI__builtin_ia32_fixupimmss_mask: | |||
3568 | case X86::BI__builtin_ia32_fixupimmss_maskz: | |||
3569 | case X86::BI__builtin_ia32_getmantsd_round_mask: | |||
3570 | case X86::BI__builtin_ia32_getmantss_round_mask: | |||
3571 | case X86::BI__builtin_ia32_rangepd512_mask: | |||
3572 | case X86::BI__builtin_ia32_rangeps512_mask: | |||
3573 | case X86::BI__builtin_ia32_rangesd128_round_mask: | |||
3574 | case X86::BI__builtin_ia32_rangess128_round_mask: | |||
3575 | case X86::BI__builtin_ia32_reducesd_mask: | |||
3576 | case X86::BI__builtin_ia32_reducess_mask: | |||
3577 | case X86::BI__builtin_ia32_rndscalesd_round_mask: | |||
3578 | case X86::BI__builtin_ia32_rndscaless_round_mask: | |||
3579 | ArgNum = 5; | |||
3580 | break; | |||
3581 | case X86::BI__builtin_ia32_vcvtsd2si64: | |||
3582 | case X86::BI__builtin_ia32_vcvtsd2si32: | |||
3583 | case X86::BI__builtin_ia32_vcvtsd2usi32: | |||
3584 | case X86::BI__builtin_ia32_vcvtsd2usi64: | |||
3585 | case X86::BI__builtin_ia32_vcvtss2si32: | |||
3586 | case X86::BI__builtin_ia32_vcvtss2si64: | |||
3587 | case X86::BI__builtin_ia32_vcvtss2usi32: | |||
3588 | case X86::BI__builtin_ia32_vcvtss2usi64: | |||
3589 | case X86::BI__builtin_ia32_sqrtpd512: | |||
3590 | case X86::BI__builtin_ia32_sqrtps512: | |||
3591 | ArgNum = 1; | |||
3592 | HasRC = true; | |||
3593 | break; | |||
3594 | case X86::BI__builtin_ia32_addpd512: | |||
3595 | case X86::BI__builtin_ia32_addps512: | |||
3596 | case X86::BI__builtin_ia32_divpd512: | |||
3597 | case X86::BI__builtin_ia32_divps512: | |||
3598 | case X86::BI__builtin_ia32_mulpd512: | |||
3599 | case X86::BI__builtin_ia32_mulps512: | |||
3600 | case X86::BI__builtin_ia32_subpd512: | |||
3601 | case X86::BI__builtin_ia32_subps512: | |||
3602 | case X86::BI__builtin_ia32_cvtsi2sd64: | |||
3603 | case X86::BI__builtin_ia32_cvtsi2ss32: | |||
3604 | case X86::BI__builtin_ia32_cvtsi2ss64: | |||
3605 | case X86::BI__builtin_ia32_cvtusi2sd64: | |||
3606 | case X86::BI__builtin_ia32_cvtusi2ss32: | |||
3607 | case X86::BI__builtin_ia32_cvtusi2ss64: | |||
3608 | ArgNum = 2; | |||
3609 | HasRC = true; | |||
3610 | break; | |||
3611 | case X86::BI__builtin_ia32_cvtdq2ps512_mask: | |||
3612 | case X86::BI__builtin_ia32_cvtudq2ps512_mask: | |||
3613 | case X86::BI__builtin_ia32_cvtpd2ps512_mask: | |||
3614 | case X86::BI__builtin_ia32_cvtpd2dq512_mask: | |||
3615 | case X86::BI__builtin_ia32_cvtpd2qq512_mask: | |||
3616 | case X86::BI__builtin_ia32_cvtpd2udq512_mask: | |||
3617 | case X86::BI__builtin_ia32_cvtpd2uqq512_mask: | |||
3618 | case X86::BI__builtin_ia32_cvtps2dq512_mask: | |||
3619 | case X86::BI__builtin_ia32_cvtps2qq512_mask: | |||
3620 | case X86::BI__builtin_ia32_cvtps2udq512_mask: | |||
3621 | case X86::BI__builtin_ia32_cvtps2uqq512_mask: | |||
3622 | case X86::BI__builtin_ia32_cvtqq2pd512_mask: | |||
3623 | case X86::BI__builtin_ia32_cvtqq2ps512_mask: | |||
3624 | case X86::BI__builtin_ia32_cvtuqq2pd512_mask: | |||
3625 | case X86::BI__builtin_ia32_cvtuqq2ps512_mask: | |||
3626 | ArgNum = 3; | |||
3627 | HasRC = true; | |||
3628 | break; | |||
3629 | case X86::BI__builtin_ia32_addss_round_mask: | |||
3630 | case X86::BI__builtin_ia32_addsd_round_mask: | |||
3631 | case X86::BI__builtin_ia32_divss_round_mask: | |||
3632 | case X86::BI__builtin_ia32_divsd_round_mask: | |||
3633 | case X86::BI__builtin_ia32_mulss_round_mask: | |||
3634 | case X86::BI__builtin_ia32_mulsd_round_mask: | |||
3635 | case X86::BI__builtin_ia32_subss_round_mask: | |||
3636 | case X86::BI__builtin_ia32_subsd_round_mask: | |||
3637 | case X86::BI__builtin_ia32_scalefpd512_mask: | |||
3638 | case X86::BI__builtin_ia32_scalefps512_mask: | |||
3639 | case X86::BI__builtin_ia32_scalefsd_round_mask: | |||
3640 | case X86::BI__builtin_ia32_scalefss_round_mask: | |||
3641 | case X86::BI__builtin_ia32_cvtsd2ss_round_mask: | |||
3642 | case X86::BI__builtin_ia32_sqrtsd_round_mask: | |||
3643 | case X86::BI__builtin_ia32_sqrtss_round_mask: | |||
3644 | case X86::BI__builtin_ia32_vfmaddsd3_mask: | |||
3645 | case X86::BI__builtin_ia32_vfmaddsd3_maskz: | |||
3646 | case X86::BI__builtin_ia32_vfmaddsd3_mask3: | |||
3647 | case X86::BI__builtin_ia32_vfmaddss3_mask: | |||
3648 | case X86::BI__builtin_ia32_vfmaddss3_maskz: | |||
3649 | case X86::BI__builtin_ia32_vfmaddss3_mask3: | |||
3650 | case X86::BI__builtin_ia32_vfmaddpd512_mask: | |||
3651 | case X86::BI__builtin_ia32_vfmaddpd512_maskz: | |||
3652 | case X86::BI__builtin_ia32_vfmaddpd512_mask3: | |||
3653 | case X86::BI__builtin_ia32_vfmsubpd512_mask3: | |||
3654 | case X86::BI__builtin_ia32_vfmaddps512_mask: | |||
3655 | case X86::BI__builtin_ia32_vfmaddps512_maskz: | |||
3656 | case X86::BI__builtin_ia32_vfmaddps512_mask3: | |||
3657 | case X86::BI__builtin_ia32_vfmsubps512_mask3: | |||
3658 | case X86::BI__builtin_ia32_vfmaddsubpd512_mask: | |||
3659 | case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: | |||
3660 | case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: | |||
3661 | case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: | |||
3662 | case X86::BI__builtin_ia32_vfmaddsubps512_mask: | |||
3663 | case X86::BI__builtin_ia32_vfmaddsubps512_maskz: | |||
3664 | case X86::BI__builtin_ia32_vfmaddsubps512_mask3: | |||
3665 | case X86::BI__builtin_ia32_vfmsubaddps512_mask3: | |||
3666 | ArgNum = 4; | |||
3667 | HasRC = true; | |||
3668 | break; | |||
3669 | } | |||
3670 | ||||
3671 | llvm::APSInt Result; | |||
3672 | ||||
3673 | // We can't check the value of a dependent argument. | |||
3674 | Expr *Arg = TheCall->getArg(ArgNum); | |||
3675 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
3676 | return false; | |||
3677 | ||||
3678 | // Check constant-ness first. | |||
3679 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
3680 | return true; | |||
3681 | ||||
3682 | // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit | |||
3683 | // is set. If the intrinsic has rounding control(bits 1:0), make sure its only | |||
3684 | // combined with ROUND_NO_EXC. If the intrinsic does not have rounding | |||
3685 | // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. | |||
3686 | if (Result == 4/*ROUND_CUR_DIRECTION*/ || | |||
3687 | Result == 8/*ROUND_NO_EXC*/ || | |||
3688 | (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || | |||
3689 | (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) | |||
3690 | return false; | |||
3691 | ||||
3692 | return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) | |||
3693 | << Arg->getSourceRange(); | |||
3694 | } | |||
3695 | ||||
3696 | // Check if the gather/scatter scale is legal. | |||
3697 | bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, | |||
3698 | CallExpr *TheCall) { | |||
3699 | unsigned ArgNum = 0; | |||
3700 | switch (BuiltinID) { | |||
3701 | default: | |||
3702 | return false; | |||
3703 | case X86::BI__builtin_ia32_gatherpfdpd: | |||
3704 | case X86::BI__builtin_ia32_gatherpfdps: | |||
3705 | case X86::BI__builtin_ia32_gatherpfqpd: | |||
3706 | case X86::BI__builtin_ia32_gatherpfqps: | |||
3707 | case X86::BI__builtin_ia32_scatterpfdpd: | |||
3708 | case X86::BI__builtin_ia32_scatterpfdps: | |||
3709 | case X86::BI__builtin_ia32_scatterpfqpd: | |||
3710 | case X86::BI__builtin_ia32_scatterpfqps: | |||
3711 | ArgNum = 3; | |||
3712 | break; | |||
3713 | case X86::BI__builtin_ia32_gatherd_pd: | |||
3714 | case X86::BI__builtin_ia32_gatherd_pd256: | |||
3715 | case X86::BI__builtin_ia32_gatherq_pd: | |||
3716 | case X86::BI__builtin_ia32_gatherq_pd256: | |||
3717 | case X86::BI__builtin_ia32_gatherd_ps: | |||
3718 | case X86::BI__builtin_ia32_gatherd_ps256: | |||
3719 | case X86::BI__builtin_ia32_gatherq_ps: | |||
3720 | case X86::BI__builtin_ia32_gatherq_ps256: | |||
3721 | case X86::BI__builtin_ia32_gatherd_q: | |||
3722 | case X86::BI__builtin_ia32_gatherd_q256: | |||
3723 | case X86::BI__builtin_ia32_gatherq_q: | |||
3724 | case X86::BI__builtin_ia32_gatherq_q256: | |||
3725 | case X86::BI__builtin_ia32_gatherd_d: | |||
3726 | case X86::BI__builtin_ia32_gatherd_d256: | |||
3727 | case X86::BI__builtin_ia32_gatherq_d: | |||
3728 | case X86::BI__builtin_ia32_gatherq_d256: | |||
3729 | case X86::BI__builtin_ia32_gather3div2df: | |||
3730 | case X86::BI__builtin_ia32_gather3div2di: | |||
3731 | case X86::BI__builtin_ia32_gather3div4df: | |||
3732 | case X86::BI__builtin_ia32_gather3div4di: | |||
3733 | case X86::BI__builtin_ia32_gather3div4sf: | |||
3734 | case X86::BI__builtin_ia32_gather3div4si: | |||
3735 | case X86::BI__builtin_ia32_gather3div8sf: | |||
3736 | case X86::BI__builtin_ia32_gather3div8si: | |||
3737 | case X86::BI__builtin_ia32_gather3siv2df: | |||
3738 | case X86::BI__builtin_ia32_gather3siv2di: | |||
3739 | case X86::BI__builtin_ia32_gather3siv4df: | |||
3740 | case X86::BI__builtin_ia32_gather3siv4di: | |||
3741 | case X86::BI__builtin_ia32_gather3siv4sf: | |||
3742 | case X86::BI__builtin_ia32_gather3siv4si: | |||
3743 | case X86::BI__builtin_ia32_gather3siv8sf: | |||
3744 | case X86::BI__builtin_ia32_gather3siv8si: | |||
3745 | case X86::BI__builtin_ia32_gathersiv8df: | |||
3746 | case X86::BI__builtin_ia32_gathersiv16sf: | |||
3747 | case X86::BI__builtin_ia32_gatherdiv8df: | |||
3748 | case X86::BI__builtin_ia32_gatherdiv16sf: | |||
3749 | case X86::BI__builtin_ia32_gathersiv8di: | |||
3750 | case X86::BI__builtin_ia32_gathersiv16si: | |||
3751 | case X86::BI__builtin_ia32_gatherdiv8di: | |||
3752 | case X86::BI__builtin_ia32_gatherdiv16si: | |||
3753 | case X86::BI__builtin_ia32_scatterdiv2df: | |||
3754 | case X86::BI__builtin_ia32_scatterdiv2di: | |||
3755 | case X86::BI__builtin_ia32_scatterdiv4df: | |||
3756 | case X86::BI__builtin_ia32_scatterdiv4di: | |||
3757 | case X86::BI__builtin_ia32_scatterdiv4sf: | |||
3758 | case X86::BI__builtin_ia32_scatterdiv4si: | |||
3759 | case X86::BI__builtin_ia32_scatterdiv8sf: | |||
3760 | case X86::BI__builtin_ia32_scatterdiv8si: | |||
3761 | case X86::BI__builtin_ia32_scattersiv2df: | |||
3762 | case X86::BI__builtin_ia32_scattersiv2di: | |||
3763 | case X86::BI__builtin_ia32_scattersiv4df: | |||
3764 | case X86::BI__builtin_ia32_scattersiv4di: | |||
3765 | case X86::BI__builtin_ia32_scattersiv4sf: | |||
3766 | case X86::BI__builtin_ia32_scattersiv4si: | |||
3767 | case X86::BI__builtin_ia32_scattersiv8sf: | |||
3768 | case X86::BI__builtin_ia32_scattersiv8si: | |||
3769 | case X86::BI__builtin_ia32_scattersiv8df: | |||
3770 | case X86::BI__builtin_ia32_scattersiv16sf: | |||
3771 | case X86::BI__builtin_ia32_scatterdiv8df: | |||
3772 | case X86::BI__builtin_ia32_scatterdiv16sf: | |||
3773 | case X86::BI__builtin_ia32_scattersiv8di: | |||
3774 | case X86::BI__builtin_ia32_scattersiv16si: | |||
3775 | case X86::BI__builtin_ia32_scatterdiv8di: | |||
3776 | case X86::BI__builtin_ia32_scatterdiv16si: | |||
3777 | ArgNum = 4; | |||
3778 | break; | |||
3779 | } | |||
3780 | ||||
3781 | llvm::APSInt Result; | |||
3782 | ||||
3783 | // We can't check the value of a dependent argument. | |||
3784 | Expr *Arg = TheCall->getArg(ArgNum); | |||
3785 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
3786 | return false; | |||
3787 | ||||
3788 | // Check constant-ness first. | |||
3789 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
3790 | return true; | |||
3791 | ||||
3792 | if (Result == 1 || Result == 2 || Result == 4 || Result == 8) | |||
3793 | return false; | |||
3794 | ||||
3795 | return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) | |||
3796 | << Arg->getSourceRange(); | |||
3797 | } | |||
3798 | ||||
3799 | enum { TileRegLow = 0, TileRegHigh = 7 }; | |||
3800 | ||||
3801 | bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, | |||
3802 | ArrayRef<int> ArgNums) { | |||
3803 | for (int ArgNum : ArgNums) { | |||
3804 | if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) | |||
3805 | return true; | |||
3806 | } | |||
3807 | return false; | |||
3808 | } | |||
3809 | ||||
3810 | bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, | |||
3811 | ArrayRef<int> ArgNums) { | |||
3812 | // Because the max number of tile register is TileRegHigh + 1, so here we use | |||
3813 | // each bit to represent the usage of them in bitset. | |||
3814 | std::bitset<TileRegHigh + 1> ArgValues; | |||
3815 | for (int ArgNum : ArgNums) { | |||
3816 | Expr *Arg = TheCall->getArg(ArgNum); | |||
3817 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
3818 | continue; | |||
3819 | ||||
3820 | llvm::APSInt Result; | |||
3821 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
3822 | return true; | |||
3823 | int ArgExtValue = Result.getExtValue(); | |||
3824 | assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&(((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh ) && "Incorrect tile register num.") ? static_cast< void> (0) : __assert_fail ("(ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && \"Incorrect tile register num.\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 3825, __PRETTY_FUNCTION__)) | |||
3825 | "Incorrect tile register num.")(((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh ) && "Incorrect tile register num.") ? static_cast< void> (0) : __assert_fail ("(ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && \"Incorrect tile register num.\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 3825, __PRETTY_FUNCTION__)); | |||
3826 | if (ArgValues.test(ArgExtValue)) | |||
3827 | return Diag(TheCall->getBeginLoc(), | |||
3828 | diag::err_x86_builtin_tile_arg_duplicate) | |||
3829 | << TheCall->getArg(ArgNum)->getSourceRange(); | |||
3830 | ArgValues.set(ArgExtValue); | |||
3831 | } | |||
3832 | return false; | |||
3833 | } | |||
3834 | ||||
3835 | bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, | |||
3836 | ArrayRef<int> ArgNums) { | |||
3837 | return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || | |||
3838 | CheckX86BuiltinTileDuplicate(TheCall, ArgNums); | |||
3839 | } | |||
3840 | ||||
3841 | bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { | |||
3842 | switch (BuiltinID) { | |||
3843 | default: | |||
3844 | return false; | |||
3845 | case X86::BI__builtin_ia32_tileloadd64: | |||
3846 | case X86::BI__builtin_ia32_tileloaddt164: | |||
3847 | case X86::BI__builtin_ia32_tilestored64: | |||
3848 | case X86::BI__builtin_ia32_tilezero: | |||
3849 | return CheckX86BuiltinTileArgumentsRange(TheCall, 0); | |||
3850 | case X86::BI__builtin_ia32_tdpbssd: | |||
3851 | case X86::BI__builtin_ia32_tdpbsud: | |||
3852 | case X86::BI__builtin_ia32_tdpbusd: | |||
3853 | case X86::BI__builtin_ia32_tdpbuud: | |||
3854 | case X86::BI__builtin_ia32_tdpbf16ps: | |||
3855 | return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); | |||
3856 | } | |||
3857 | } | |||
3858 | static bool isX86_32Builtin(unsigned BuiltinID) { | |||
3859 | // These builtins only work on x86-32 targets. | |||
3860 | switch (BuiltinID) { | |||
3861 | case X86::BI__builtin_ia32_readeflags_u32: | |||
3862 | case X86::BI__builtin_ia32_writeeflags_u32: | |||
3863 | return true; | |||
3864 | } | |||
3865 | ||||
3866 | return false; | |||
3867 | } | |||
3868 | ||||
3869 | bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, | |||
3870 | CallExpr *TheCall) { | |||
3871 | if (BuiltinID == X86::BI__builtin_cpu_supports) | |||
3872 | return SemaBuiltinCpuSupports(*this, TI, TheCall); | |||
3873 | ||||
3874 | if (BuiltinID == X86::BI__builtin_cpu_is) | |||
3875 | return SemaBuiltinCpuIs(*this, TI, TheCall); | |||
3876 | ||||
3877 | // Check for 32-bit only builtins on a 64-bit target. | |||
3878 | const llvm::Triple &TT = TI.getTriple(); | |||
3879 | if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) | |||
3880 | return Diag(TheCall->getCallee()->getBeginLoc(), | |||
3881 | diag::err_32_bit_builtin_64_bit_tgt); | |||
3882 | ||||
3883 | // If the intrinsic has rounding or SAE make sure its valid. | |||
3884 | if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) | |||
3885 | return true; | |||
3886 | ||||
3887 | // If the intrinsic has a gather/scatter scale immediate make sure its valid. | |||
3888 | if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) | |||
3889 | return true; | |||
3890 | ||||
3891 | // If the intrinsic has a tile arguments, make sure they are valid. | |||
3892 | if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) | |||
3893 | return true; | |||
3894 | ||||
3895 | // For intrinsics which take an immediate value as part of the instruction, | |||
3896 | // range check them here. | |||
3897 | int i = 0, l = 0, u = 0; | |||
3898 | switch (BuiltinID) { | |||
3899 | default: | |||
3900 | return false; | |||
3901 | case X86::BI__builtin_ia32_vec_ext_v2si: | |||
3902 | case X86::BI__builtin_ia32_vec_ext_v2di: | |||
3903 | case X86::BI__builtin_ia32_vextractf128_pd256: | |||
3904 | case X86::BI__builtin_ia32_vextractf128_ps256: | |||
3905 | case X86::BI__builtin_ia32_vextractf128_si256: | |||
3906 | case X86::BI__builtin_ia32_extract128i256: | |||
3907 | case X86::BI__builtin_ia32_extractf64x4_mask: | |||
3908 | case X86::BI__builtin_ia32_extracti64x4_mask: | |||
3909 | case X86::BI__builtin_ia32_extractf32x8_mask: | |||
3910 | case X86::BI__builtin_ia32_extracti32x8_mask: | |||
3911 | case X86::BI__builtin_ia32_extractf64x2_256_mask: | |||
3912 | case X86::BI__builtin_ia32_extracti64x2_256_mask: | |||
3913 | case X86::BI__builtin_ia32_extractf32x4_256_mask: | |||
3914 | case X86::BI__builtin_ia32_extracti32x4_256_mask: | |||
3915 | i = 1; l = 0; u = 1; | |||
3916 | break; | |||
3917 | case X86::BI__builtin_ia32_vec_set_v2di: | |||
3918 | case X86::BI__builtin_ia32_vinsertf128_pd256: | |||
3919 | case X86::BI__builtin_ia32_vinsertf128_ps256: | |||
3920 | case X86::BI__builtin_ia32_vinsertf128_si256: | |||
3921 | case X86::BI__builtin_ia32_insert128i256: | |||
3922 | case X86::BI__builtin_ia32_insertf32x8: | |||
3923 | case X86::BI__builtin_ia32_inserti32x8: | |||
3924 | case X86::BI__builtin_ia32_insertf64x4: | |||
3925 | case X86::BI__builtin_ia32_inserti64x4: | |||
3926 | case X86::BI__builtin_ia32_insertf64x2_256: | |||
3927 | case X86::BI__builtin_ia32_inserti64x2_256: | |||
3928 | case X86::BI__builtin_ia32_insertf32x4_256: | |||
3929 | case X86::BI__builtin_ia32_inserti32x4_256: | |||
3930 | i = 2; l = 0; u = 1; | |||
3931 | break; | |||
3932 | case X86::BI__builtin_ia32_vpermilpd: | |||
3933 | case X86::BI__builtin_ia32_vec_ext_v4hi: | |||
3934 | case X86::BI__builtin_ia32_vec_ext_v4si: | |||
3935 | case X86::BI__builtin_ia32_vec_ext_v4sf: | |||
3936 | case X86::BI__builtin_ia32_vec_ext_v4di: | |||
3937 | case X86::BI__builtin_ia32_extractf32x4_mask: | |||
3938 | case X86::BI__builtin_ia32_extracti32x4_mask: | |||
3939 | case X86::BI__builtin_ia32_extractf64x2_512_mask: | |||
3940 | case X86::BI__builtin_ia32_extracti64x2_512_mask: | |||
3941 | i = 1; l = 0; u = 3; | |||
3942 | break; | |||
3943 | case X86::BI_mm_prefetch: | |||
3944 | case X86::BI__builtin_ia32_vec_ext_v8hi: | |||
3945 | case X86::BI__builtin_ia32_vec_ext_v8si: | |||
3946 | i = 1; l = 0; u = 7; | |||
3947 | break; | |||
3948 | case X86::BI__builtin_ia32_sha1rnds4: | |||
3949 | case X86::BI__builtin_ia32_blendpd: | |||
3950 | case X86::BI__builtin_ia32_shufpd: | |||
3951 | case X86::BI__builtin_ia32_vec_set_v4hi: | |||
3952 | case X86::BI__builtin_ia32_vec_set_v4si: | |||
3953 | case X86::BI__builtin_ia32_vec_set_v4di: | |||
3954 | case X86::BI__builtin_ia32_shuf_f32x4_256: | |||
3955 | case X86::BI__builtin_ia32_shuf_f64x2_256: | |||
3956 | case X86::BI__builtin_ia32_shuf_i32x4_256: | |||
3957 | case X86::BI__builtin_ia32_shuf_i64x2_256: | |||
3958 | case X86::BI__builtin_ia32_insertf64x2_512: | |||
3959 | case X86::BI__builtin_ia32_inserti64x2_512: | |||
3960 | case X86::BI__builtin_ia32_insertf32x4: | |||
3961 | case X86::BI__builtin_ia32_inserti32x4: | |||
3962 | i = 2; l = 0; u = 3; | |||
3963 | break; | |||
3964 | case X86::BI__builtin_ia32_vpermil2pd: | |||
3965 | case X86::BI__builtin_ia32_vpermil2pd256: | |||
3966 | case X86::BI__builtin_ia32_vpermil2ps: | |||
3967 | case X86::BI__builtin_ia32_vpermil2ps256: | |||
3968 | i = 3; l = 0; u = 3; | |||
3969 | break; | |||
3970 | case X86::BI__builtin_ia32_cmpb128_mask: | |||
3971 | case X86::BI__builtin_ia32_cmpw128_mask: | |||
3972 | case X86::BI__builtin_ia32_cmpd128_mask: | |||
3973 | case X86::BI__builtin_ia32_cmpq128_mask: | |||
3974 | case X86::BI__builtin_ia32_cmpb256_mask: | |||
3975 | case X86::BI__builtin_ia32_cmpw256_mask: | |||
3976 | case X86::BI__builtin_ia32_cmpd256_mask: | |||
3977 | case X86::BI__builtin_ia32_cmpq256_mask: | |||
3978 | case X86::BI__builtin_ia32_cmpb512_mask: | |||
3979 | case X86::BI__builtin_ia32_cmpw512_mask: | |||
3980 | case X86::BI__builtin_ia32_cmpd512_mask: | |||
3981 | case X86::BI__builtin_ia32_cmpq512_mask: | |||
3982 | case X86::BI__builtin_ia32_ucmpb128_mask: | |||
3983 | case X86::BI__builtin_ia32_ucmpw128_mask: | |||
3984 | case X86::BI__builtin_ia32_ucmpd128_mask: | |||
3985 | case X86::BI__builtin_ia32_ucmpq128_mask: | |||
3986 | case X86::BI__builtin_ia32_ucmpb256_mask: | |||
3987 | case X86::BI__builtin_ia32_ucmpw256_mask: | |||
3988 | case X86::BI__builtin_ia32_ucmpd256_mask: | |||
3989 | case X86::BI__builtin_ia32_ucmpq256_mask: | |||
3990 | case X86::BI__builtin_ia32_ucmpb512_mask: | |||
3991 | case X86::BI__builtin_ia32_ucmpw512_mask: | |||
3992 | case X86::BI__builtin_ia32_ucmpd512_mask: | |||
3993 | case X86::BI__builtin_ia32_ucmpq512_mask: | |||
3994 | case X86::BI__builtin_ia32_vpcomub: | |||
3995 | case X86::BI__builtin_ia32_vpcomuw: | |||
3996 | case X86::BI__builtin_ia32_vpcomud: | |||
3997 | case X86::BI__builtin_ia32_vpcomuq: | |||
3998 | case X86::BI__builtin_ia32_vpcomb: | |||
3999 | case X86::BI__builtin_ia32_vpcomw: | |||
4000 | case X86::BI__builtin_ia32_vpcomd: | |||
4001 | case X86::BI__builtin_ia32_vpcomq: | |||
4002 | case X86::BI__builtin_ia32_vec_set_v8hi: | |||
4003 | case X86::BI__builtin_ia32_vec_set_v8si: | |||
4004 | i = 2; l = 0; u = 7; | |||
4005 | break; | |||
4006 | case X86::BI__builtin_ia32_vpermilpd256: | |||
4007 | case X86::BI__builtin_ia32_roundps: | |||
4008 | case X86::BI__builtin_ia32_roundpd: | |||
4009 | case X86::BI__builtin_ia32_roundps256: | |||
4010 | case X86::BI__builtin_ia32_roundpd256: | |||
4011 | case X86::BI__builtin_ia32_getmantpd128_mask: | |||
4012 | case X86::BI__builtin_ia32_getmantpd256_mask: | |||
4013 | case X86::BI__builtin_ia32_getmantps128_mask: | |||
4014 | case X86::BI__builtin_ia32_getmantps256_mask: | |||
4015 | case X86::BI__builtin_ia32_getmantpd512_mask: | |||
4016 | case X86::BI__builtin_ia32_getmantps512_mask: | |||
4017 | case X86::BI__builtin_ia32_vec_ext_v16qi: | |||
4018 | case X86::BI__builtin_ia32_vec_ext_v16hi: | |||
4019 | i = 1; l = 0; u = 15; | |||
4020 | break; | |||
4021 | case X86::BI__builtin_ia32_pblendd128: | |||
4022 | case X86::BI__builtin_ia32_blendps: | |||
4023 | case X86::BI__builtin_ia32_blendpd256: | |||
4024 | case X86::BI__builtin_ia32_shufpd256: | |||
4025 | case X86::BI__builtin_ia32_roundss: | |||
4026 | case X86::BI__builtin_ia32_roundsd: | |||
4027 | case X86::BI__builtin_ia32_rangepd128_mask: | |||
4028 | case X86::BI__builtin_ia32_rangepd256_mask: | |||
4029 | case X86::BI__builtin_ia32_rangepd512_mask: | |||
4030 | case X86::BI__builtin_ia32_rangeps128_mask: | |||
4031 | case X86::BI__builtin_ia32_rangeps256_mask: | |||
4032 | case X86::BI__builtin_ia32_rangeps512_mask: | |||
4033 | case X86::BI__builtin_ia32_getmantsd_round_mask: | |||
4034 | case X86::BI__builtin_ia32_getmantss_round_mask: | |||
4035 | case X86::BI__builtin_ia32_vec_set_v16qi: | |||
4036 | case X86::BI__builtin_ia32_vec_set_v16hi: | |||
4037 | i = 2; l = 0; u = 15; | |||
4038 | break; | |||
4039 | case X86::BI__builtin_ia32_vec_ext_v32qi: | |||
4040 | i = 1; l = 0; u = 31; | |||
4041 | break; | |||
4042 | case X86::BI__builtin_ia32_cmpps: | |||
4043 | case X86::BI__builtin_ia32_cmpss: | |||
4044 | case X86::BI__builtin_ia32_cmppd: | |||
4045 | case X86::BI__builtin_ia32_cmpsd: | |||
4046 | case X86::BI__builtin_ia32_cmpps256: | |||
4047 | case X86::BI__builtin_ia32_cmppd256: | |||
4048 | case X86::BI__builtin_ia32_cmpps128_mask: | |||
4049 | case X86::BI__builtin_ia32_cmppd128_mask: | |||
4050 | case X86::BI__builtin_ia32_cmpps256_mask: | |||
4051 | case X86::BI__builtin_ia32_cmppd256_mask: | |||
4052 | case X86::BI__builtin_ia32_cmpps512_mask: | |||
4053 | case X86::BI__builtin_ia32_cmppd512_mask: | |||
4054 | case X86::BI__builtin_ia32_cmpsd_mask: | |||
4055 | case X86::BI__builtin_ia32_cmpss_mask: | |||
4056 | case X86::BI__builtin_ia32_vec_set_v32qi: | |||
4057 | i = 2; l = 0; u = 31; | |||
4058 | break; | |||
4059 | case X86::BI__builtin_ia32_permdf256: | |||
4060 | case X86::BI__builtin_ia32_permdi256: | |||
4061 | case X86::BI__builtin_ia32_permdf512: | |||
4062 | case X86::BI__builtin_ia32_permdi512: | |||
4063 | case X86::BI__builtin_ia32_vpermilps: | |||
4064 | case X86::BI__builtin_ia32_vpermilps256: | |||
4065 | case X86::BI__builtin_ia32_vpermilpd512: | |||
4066 | case X86::BI__builtin_ia32_vpermilps512: | |||
4067 | case X86::BI__builtin_ia32_pshufd: | |||
4068 | case X86::BI__builtin_ia32_pshufd256: | |||
4069 | case X86::BI__builtin_ia32_pshufd512: | |||
4070 | case X86::BI__builtin_ia32_pshufhw: | |||
4071 | case X86::BI__builtin_ia32_pshufhw256: | |||
4072 | case X86::BI__builtin_ia32_pshufhw512: | |||
4073 | case X86::BI__builtin_ia32_pshuflw: | |||
4074 | case X86::BI__builtin_ia32_pshuflw256: | |||
4075 | case X86::BI__builtin_ia32_pshuflw512: | |||
4076 | case X86::BI__builtin_ia32_vcvtps2ph: | |||
4077 | case X86::BI__builtin_ia32_vcvtps2ph_mask: | |||
4078 | case X86::BI__builtin_ia32_vcvtps2ph256: | |||
4079 | case X86::BI__builtin_ia32_vcvtps2ph256_mask: | |||
4080 | case X86::BI__builtin_ia32_vcvtps2ph512_mask: | |||
4081 | case X86::BI__builtin_ia32_rndscaleps_128_mask: | |||
4082 | case X86::BI__builtin_ia32_rndscalepd_128_mask: | |||
4083 | case X86::BI__builtin_ia32_rndscaleps_256_mask: | |||
4084 | case X86::BI__builtin_ia32_rndscalepd_256_mask: | |||
4085 | case X86::BI__builtin_ia32_rndscaleps_mask: | |||
4086 | case X86::BI__builtin_ia32_rndscalepd_mask: | |||
4087 | case X86::BI__builtin_ia32_reducepd128_mask: | |||
4088 | case X86::BI__builtin_ia32_reducepd256_mask: | |||
4089 | case X86::BI__builtin_ia32_reducepd512_mask: | |||
4090 | case X86::BI__builtin_ia32_reduceps128_mask: | |||
4091 | case X86::BI__builtin_ia32_reduceps256_mask: | |||
4092 | case X86::BI__builtin_ia32_reduceps512_mask: | |||
4093 | case X86::BI__builtin_ia32_prold512: | |||
4094 | case X86::BI__builtin_ia32_prolq512: | |||
4095 | case X86::BI__builtin_ia32_prold128: | |||
4096 | case X86::BI__builtin_ia32_prold256: | |||
4097 | case X86::BI__builtin_ia32_prolq128: | |||
4098 | case X86::BI__builtin_ia32_prolq256: | |||
4099 | case X86::BI__builtin_ia32_prord512: | |||
4100 | case X86::BI__builtin_ia32_prorq512: | |||
4101 | case X86::BI__builtin_ia32_prord128: | |||
4102 | case X86::BI__builtin_ia32_prord256: | |||
4103 | case X86::BI__builtin_ia32_prorq128: | |||
4104 | case X86::BI__builtin_ia32_prorq256: | |||
4105 | case X86::BI__builtin_ia32_fpclasspd128_mask: | |||
4106 | case X86::BI__builtin_ia32_fpclasspd256_mask: | |||
4107 | case X86::BI__builtin_ia32_fpclassps128_mask: | |||
4108 | case X86::BI__builtin_ia32_fpclassps256_mask: | |||
4109 | case X86::BI__builtin_ia32_fpclassps512_mask: | |||
4110 | case X86::BI__builtin_ia32_fpclasspd512_mask: | |||
4111 | case X86::BI__builtin_ia32_fpclasssd_mask: | |||
4112 | case X86::BI__builtin_ia32_fpclassss_mask: | |||
4113 | case X86::BI__builtin_ia32_pslldqi128_byteshift: | |||
4114 | case X86::BI__builtin_ia32_pslldqi256_byteshift: | |||
4115 | case X86::BI__builtin_ia32_pslldqi512_byteshift: | |||
4116 | case X86::BI__builtin_ia32_psrldqi128_byteshift: | |||
4117 | case X86::BI__builtin_ia32_psrldqi256_byteshift: | |||
4118 | case X86::BI__builtin_ia32_psrldqi512_byteshift: | |||
4119 | case X86::BI__builtin_ia32_kshiftliqi: | |||
4120 | case X86::BI__builtin_ia32_kshiftlihi: | |||
4121 | case X86::BI__builtin_ia32_kshiftlisi: | |||
4122 | case X86::BI__builtin_ia32_kshiftlidi: | |||
4123 | case X86::BI__builtin_ia32_kshiftriqi: | |||
4124 | case X86::BI__builtin_ia32_kshiftrihi: | |||
4125 | case X86::BI__builtin_ia32_kshiftrisi: | |||
4126 | case X86::BI__builtin_ia32_kshiftridi: | |||
4127 | i = 1; l = 0; u = 255; | |||
4128 | break; | |||
4129 | case X86::BI__builtin_ia32_vperm2f128_pd256: | |||
4130 | case X86::BI__builtin_ia32_vperm2f128_ps256: | |||
4131 | case X86::BI__builtin_ia32_vperm2f128_si256: | |||
4132 | case X86::BI__builtin_ia32_permti256: | |||
4133 | case X86::BI__builtin_ia32_pblendw128: | |||
4134 | case X86::BI__builtin_ia32_pblendw256: | |||
4135 | case X86::BI__builtin_ia32_blendps256: | |||
4136 | case X86::BI__builtin_ia32_pblendd256: | |||
4137 | case X86::BI__builtin_ia32_palignr128: | |||
4138 | case X86::BI__builtin_ia32_palignr256: | |||
4139 | case X86::BI__builtin_ia32_palignr512: | |||
4140 | case X86::BI__builtin_ia32_alignq512: | |||
4141 | case X86::BI__builtin_ia32_alignd512: | |||
4142 | case X86::BI__builtin_ia32_alignd128: | |||
4143 | case X86::BI__builtin_ia32_alignd256: | |||
4144 | case X86::BI__builtin_ia32_alignq128: | |||
4145 | case X86::BI__builtin_ia32_alignq256: | |||
4146 | case X86::BI__builtin_ia32_vcomisd: | |||
4147 | case X86::BI__builtin_ia32_vcomiss: | |||
4148 | case X86::BI__builtin_ia32_shuf_f32x4: | |||
4149 | case X86::BI__builtin_ia32_shuf_f64x2: | |||
4150 | case X86::BI__builtin_ia32_shuf_i32x4: | |||
4151 | case X86::BI__builtin_ia32_shuf_i64x2: | |||
4152 | case X86::BI__builtin_ia32_shufpd512: | |||
4153 | case X86::BI__builtin_ia32_shufps: | |||
4154 | case X86::BI__builtin_ia32_shufps256: | |||
4155 | case X86::BI__builtin_ia32_shufps512: | |||
4156 | case X86::BI__builtin_ia32_dbpsadbw128: | |||
4157 | case X86::BI__builtin_ia32_dbpsadbw256: | |||
4158 | case X86::BI__builtin_ia32_dbpsadbw512: | |||
4159 | case X86::BI__builtin_ia32_vpshldd128: | |||
4160 | case X86::BI__builtin_ia32_vpshldd256: | |||
4161 | case X86::BI__builtin_ia32_vpshldd512: | |||
4162 | case X86::BI__builtin_ia32_vpshldq128: | |||
4163 | case X86::BI__builtin_ia32_vpshldq256: | |||
4164 | case X86::BI__builtin_ia32_vpshldq512: | |||
4165 | case X86::BI__builtin_ia32_vpshldw128: | |||
4166 | case X86::BI__builtin_ia32_vpshldw256: | |||
4167 | case X86::BI__builtin_ia32_vpshldw512: | |||
4168 | case X86::BI__builtin_ia32_vpshrdd128: | |||
4169 | case X86::BI__builtin_ia32_vpshrdd256: | |||
4170 | case X86::BI__builtin_ia32_vpshrdd512: | |||
4171 | case X86::BI__builtin_ia32_vpshrdq128: | |||
4172 | case X86::BI__builtin_ia32_vpshrdq256: | |||
4173 | case X86::BI__builtin_ia32_vpshrdq512: | |||
4174 | case X86::BI__builtin_ia32_vpshrdw128: | |||
4175 | case X86::BI__builtin_ia32_vpshrdw256: | |||
4176 | case X86::BI__builtin_ia32_vpshrdw512: | |||
4177 | i = 2; l = 0; u = 255; | |||
4178 | break; | |||
4179 | case X86::BI__builtin_ia32_fixupimmpd512_mask: | |||
4180 | case X86::BI__builtin_ia32_fixupimmpd512_maskz: | |||
4181 | case X86::BI__builtin_ia32_fixupimmps512_mask: | |||
4182 | case X86::BI__builtin_ia32_fixupimmps512_maskz: | |||
4183 | case X86::BI__builtin_ia32_fixupimmsd_mask: | |||
4184 | case X86::BI__builtin_ia32_fixupimmsd_maskz: | |||
4185 | case X86::BI__builtin_ia32_fixupimmss_mask: | |||
4186 | case X86::BI__builtin_ia32_fixupimmss_maskz: | |||
4187 | case X86::BI__builtin_ia32_fixupimmpd128_mask: | |||
4188 | case X86::BI__builtin_ia32_fixupimmpd128_maskz: | |||
4189 | case X86::BI__builtin_ia32_fixupimmpd256_mask: | |||
4190 | case X86::BI__builtin_ia32_fixupimmpd256_maskz: | |||
4191 | case X86::BI__builtin_ia32_fixupimmps128_mask: | |||
4192 | case X86::BI__builtin_ia32_fixupimmps128_maskz: | |||
4193 | case X86::BI__builtin_ia32_fixupimmps256_mask: | |||
4194 | case X86::BI__builtin_ia32_fixupimmps256_maskz: | |||
4195 | case X86::BI__builtin_ia32_pternlogd512_mask: | |||
4196 | case X86::BI__builtin_ia32_pternlogd512_maskz: | |||
4197 | case X86::BI__builtin_ia32_pternlogq512_mask: | |||
4198 | case X86::BI__builtin_ia32_pternlogq512_maskz: | |||
4199 | case X86::BI__builtin_ia32_pternlogd128_mask: | |||
4200 | case X86::BI__builtin_ia32_pternlogd128_maskz: | |||
4201 | case X86::BI__builtin_ia32_pternlogd256_mask: | |||
4202 | case X86::BI__builtin_ia32_pternlogd256_maskz: | |||
4203 | case X86::BI__builtin_ia32_pternlogq128_mask: | |||
4204 | case X86::BI__builtin_ia32_pternlogq128_maskz: | |||
4205 | case X86::BI__builtin_ia32_pternlogq256_mask: | |||
4206 | case X86::BI__builtin_ia32_pternlogq256_maskz: | |||
4207 | i = 3; l = 0; u = 255; | |||
4208 | break; | |||
4209 | case X86::BI__builtin_ia32_gatherpfdpd: | |||
4210 | case X86::BI__builtin_ia32_gatherpfdps: | |||
4211 | case X86::BI__builtin_ia32_gatherpfqpd: | |||
4212 | case X86::BI__builtin_ia32_gatherpfqps: | |||
4213 | case X86::BI__builtin_ia32_scatterpfdpd: | |||
4214 | case X86::BI__builtin_ia32_scatterpfdps: | |||
4215 | case X86::BI__builtin_ia32_scatterpfqpd: | |||
4216 | case X86::BI__builtin_ia32_scatterpfqps: | |||
4217 | i = 4; l = 2; u = 3; | |||
4218 | break; | |||
4219 | case X86::BI__builtin_ia32_reducesd_mask: | |||
4220 | case X86::BI__builtin_ia32_reducess_mask: | |||
4221 | case X86::BI__builtin_ia32_rndscalesd_round_mask: | |||
4222 | case X86::BI__builtin_ia32_rndscaless_round_mask: | |||
4223 | i = 4; l = 0; u = 255; | |||
4224 | break; | |||
4225 | } | |||
4226 | ||||
4227 | // Note that we don't force a hard error on the range check here, allowing | |||
4228 | // template-generated or macro-generated dead code to potentially have out-of- | |||
4229 | // range values. These need to code generate, but don't need to necessarily | |||
4230 | // make any sense. We use a warning that defaults to an error. | |||
4231 | return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); | |||
4232 | } | |||
4233 | ||||
4234 | /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo | |||
4235 | /// parameter with the FormatAttr's correct format_idx and firstDataArg. | |||
4236 | /// Returns true when the format fits the function and the FormatStringInfo has | |||
4237 | /// been populated. | |||
4238 | bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, | |||
4239 | FormatStringInfo *FSI) { | |||
4240 | FSI->HasVAListArg = Format->getFirstArg() == 0; | |||
4241 | FSI->FormatIdx = Format->getFormatIdx() - 1; | |||
4242 | FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; | |||
4243 | ||||
4244 | // The way the format attribute works in GCC, the implicit this argument | |||
4245 | // of member functions is counted. However, it doesn't appear in our own | |||
4246 | // lists, so decrement format_idx in that case. | |||
4247 | if (IsCXXMember) { | |||
4248 | if(FSI->FormatIdx == 0) | |||
4249 | return false; | |||
4250 | --FSI->FormatIdx; | |||
4251 | if (FSI->FirstDataArg != 0) | |||
4252 | --FSI->FirstDataArg; | |||
4253 | } | |||
4254 | return true; | |||
4255 | } | |||
4256 | ||||
4257 | /// Checks if a the given expression evaluates to null. | |||
4258 | /// | |||
4259 | /// Returns true if the value evaluates to null. | |||
4260 | static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { | |||
4261 | // If the expression has non-null type, it doesn't evaluate to null. | |||
4262 | if (auto nullability | |||
4263 | = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { | |||
4264 | if (*nullability == NullabilityKind::NonNull) | |||
4265 | return false; | |||
4266 | } | |||
4267 | ||||
4268 | // As a special case, transparent unions initialized with zero are | |||
4269 | // considered null for the purposes of the nonnull attribute. | |||
4270 | if (const RecordType *UT = Expr->getType()->getAsUnionType()) { | |||
4271 | if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) | |||
4272 | if (const CompoundLiteralExpr *CLE = | |||
4273 | dyn_cast<CompoundLiteralExpr>(Expr)) | |||
4274 | if (const InitListExpr *ILE = | |||
4275 | dyn_cast<InitListExpr>(CLE->getInitializer())) | |||
4276 | Expr = ILE->getInit(0); | |||
4277 | } | |||
4278 | ||||
4279 | bool Result; | |||
4280 | return (!Expr->isValueDependent() && | |||
4281 | Expr->EvaluateAsBooleanCondition(Result, S.Context) && | |||
4282 | !Result); | |||
4283 | } | |||
4284 | ||||
4285 | static void CheckNonNullArgument(Sema &S, | |||
4286 | const Expr *ArgExpr, | |||
4287 | SourceLocation CallSiteLoc) { | |||
4288 | if (CheckNonNullExpr(S, ArgExpr)) | |||
4289 | S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, | |||
4290 | S.PDiag(diag::warn_null_arg) | |||
4291 | << ArgExpr->getSourceRange()); | |||
4292 | } | |||
4293 | ||||
4294 | bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { | |||
4295 | FormatStringInfo FSI; | |||
4296 | if ((GetFormatStringType(Format) == FST_NSString) && | |||
4297 | getFormatStringInfo(Format, false, &FSI)) { | |||
4298 | Idx = FSI.FormatIdx; | |||
4299 | return true; | |||
4300 | } | |||
4301 | return false; | |||
4302 | } | |||
4303 | ||||
4304 | /// Diagnose use of %s directive in an NSString which is being passed | |||
4305 | /// as formatting string to formatting method. | |||
4306 | static void | |||
4307 | DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, | |||
4308 | const NamedDecl *FDecl, | |||
4309 | Expr **Args, | |||
4310 | unsigned NumArgs) { | |||
4311 | unsigned Idx = 0; | |||
4312 | bool Format = false; | |||
4313 | ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); | |||
4314 | if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { | |||
4315 | Idx = 2; | |||
4316 | Format = true; | |||
4317 | } | |||
4318 | else | |||
4319 | for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { | |||
4320 | if (S.GetFormatNSStringIdx(I, Idx)) { | |||
4321 | Format = true; | |||
4322 | break; | |||
4323 | } | |||
4324 | } | |||
4325 | if (!Format || NumArgs <= Idx) | |||
4326 | return; | |||
4327 | const Expr *FormatExpr = Args[Idx]; | |||
4328 | if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) | |||
4329 | FormatExpr = CSCE->getSubExpr(); | |||
4330 | const StringLiteral *FormatString; | |||
4331 | if (const ObjCStringLiteral *OSL = | |||
4332 | dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) | |||
4333 | FormatString = OSL->getString(); | |||
4334 | else | |||
4335 | FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); | |||
4336 | if (!FormatString) | |||
4337 | return; | |||
4338 | if (S.FormatStringHasSArg(FormatString)) { | |||
4339 | S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) | |||
4340 | << "%s" << 1 << 1; | |||
4341 | S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) | |||
4342 | << FDecl->getDeclName(); | |||
4343 | } | |||
4344 | } | |||
4345 | ||||
4346 | /// Determine whether the given type has a non-null nullability annotation. | |||
4347 | static bool isNonNullType(ASTContext &ctx, QualType type) { | |||
4348 | if (auto nullability = type->getNullability(ctx)) | |||
4349 | return *nullability == NullabilityKind::NonNull; | |||
4350 | ||||
4351 | return false; | |||
4352 | } | |||
4353 | ||||
4354 | static void CheckNonNullArguments(Sema &S, | |||
4355 | const NamedDecl *FDecl, | |||
4356 | const FunctionProtoType *Proto, | |||
4357 | ArrayRef<const Expr *> Args, | |||
4358 | SourceLocation CallSiteLoc) { | |||
4359 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 4359, __PRETTY_FUNCTION__)); | |||
4360 | ||||
4361 | // Already checked by by constant evaluator. | |||
4362 | if (S.isConstantEvaluated()) | |||
4363 | return; | |||
4364 | // Check the attributes attached to the method/function itself. | |||
4365 | llvm::SmallBitVector NonNullArgs; | |||
4366 | if (FDecl) { | |||
4367 | // Handle the nonnull attribute on the function/method declaration itself. | |||
4368 | for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { | |||
4369 | if (!NonNull->args_size()) { | |||
4370 | // Easy case: all pointer arguments are nonnull. | |||
4371 | for (const auto *Arg : Args) | |||
4372 | if (S.isValidPointerAttrType(Arg->getType())) | |||
4373 | CheckNonNullArgument(S, Arg, CallSiteLoc); | |||
4374 | return; | |||
4375 | } | |||
4376 | ||||
4377 | for (const ParamIdx &Idx : NonNull->args()) { | |||
4378 | unsigned IdxAST = Idx.getASTIndex(); | |||
4379 | if (IdxAST >= Args.size()) | |||
4380 | continue; | |||
4381 | if (NonNullArgs.empty()) | |||
4382 | NonNullArgs.resize(Args.size()); | |||
4383 | NonNullArgs.set(IdxAST); | |||
4384 | } | |||
4385 | } | |||
4386 | } | |||
4387 | ||||
4388 | if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { | |||
4389 | // Handle the nonnull attribute on the parameters of the | |||
4390 | // function/method. | |||
4391 | ArrayRef<ParmVarDecl*> parms; | |||
4392 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) | |||
4393 | parms = FD->parameters(); | |||
4394 | else | |||
4395 | parms = cast<ObjCMethodDecl>(FDecl)->parameters(); | |||
4396 | ||||
4397 | unsigned ParamIndex = 0; | |||
4398 | for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); | |||
4399 | I != E; ++I, ++ParamIndex) { | |||
4400 | const ParmVarDecl *PVD = *I; | |||
4401 | if (PVD->hasAttr<NonNullAttr>() || | |||
4402 | isNonNullType(S.Context, PVD->getType())) { | |||
4403 | if (NonNullArgs.empty()) | |||
4404 | NonNullArgs.resize(Args.size()); | |||
4405 | ||||
4406 | NonNullArgs.set(ParamIndex); | |||
4407 | } | |||
4408 | } | |||
4409 | } else { | |||
4410 | // If we have a non-function, non-method declaration but no | |||
4411 | // function prototype, try to dig out the function prototype. | |||
4412 | if (!Proto) { | |||
4413 | if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { | |||
4414 | QualType type = VD->getType().getNonReferenceType(); | |||
4415 | if (auto pointerType = type->getAs<PointerType>()) | |||
4416 | type = pointerType->getPointeeType(); | |||
4417 | else if (auto blockType = type->getAs<BlockPointerType>()) | |||
4418 | type = blockType->getPointeeType(); | |||
4419 | // FIXME: data member pointers? | |||
4420 | ||||
4421 | // Dig out the function prototype, if there is one. | |||
4422 | Proto = type->getAs<FunctionProtoType>(); | |||
4423 | } | |||
4424 | } | |||
4425 | ||||
4426 | // Fill in non-null argument information from the nullability | |||
4427 | // information on the parameter types (if we have them). | |||
4428 | if (Proto) { | |||
4429 | unsigned Index = 0; | |||
4430 | for (auto paramType : Proto->getParamTypes()) { | |||
4431 | if (isNonNullType(S.Context, paramType)) { | |||
4432 | if (NonNullArgs.empty()) | |||
4433 | NonNullArgs.resize(Args.size()); | |||
4434 | ||||
4435 | NonNullArgs.set(Index); | |||
4436 | } | |||
4437 | ||||
4438 | ++Index; | |||
4439 | } | |||
4440 | } | |||
4441 | } | |||
4442 | ||||
4443 | // Check for non-null arguments. | |||
4444 | for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); | |||
4445 | ArgIndex != ArgIndexEnd; ++ArgIndex) { | |||
4446 | if (NonNullArgs[ArgIndex]) | |||
4447 | CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); | |||
4448 | } | |||
4449 | } | |||
4450 | ||||
4451 | /// Handles the checks for format strings, non-POD arguments to vararg | |||
4452 | /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if | |||
4453 | /// attributes. | |||
4454 | void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, | |||
4455 | const Expr *ThisArg, ArrayRef<const Expr *> Args, | |||
4456 | bool IsMemberFunction, SourceLocation Loc, | |||
4457 | SourceRange Range, VariadicCallType CallType) { | |||
4458 | // FIXME: We should check as much as we can in the template definition. | |||
4459 | if (CurContext->isDependentContext()) | |||
4460 | return; | |||
4461 | ||||
4462 | // Printf and scanf checking. | |||
4463 | llvm::SmallBitVector CheckedVarArgs; | |||
4464 | if (FDecl) { | |||
4465 | for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { | |||
4466 | // Only create vector if there are format attributes. | |||
4467 | CheckedVarArgs.resize(Args.size()); | |||
4468 | ||||
4469 | CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, | |||
4470 | CheckedVarArgs); | |||
4471 | } | |||
4472 | } | |||
4473 | ||||
4474 | // Refuse POD arguments that weren't caught by the format string | |||
4475 | // checks above. | |||
4476 | auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); | |||
4477 | if (CallType != VariadicDoesNotApply && | |||
4478 | (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { | |||
4479 | unsigned NumParams = Proto ? Proto->getNumParams() | |||
4480 | : FDecl && isa<FunctionDecl>(FDecl) | |||
4481 | ? cast<FunctionDecl>(FDecl)->getNumParams() | |||
4482 | : FDecl && isa<ObjCMethodDecl>(FDecl) | |||
4483 | ? cast<ObjCMethodDecl>(FDecl)->param_size() | |||
4484 | : 0; | |||
4485 | ||||
4486 | for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { | |||
4487 | // Args[ArgIdx] can be null in malformed code. | |||
4488 | if (const Expr *Arg = Args[ArgIdx]) { | |||
4489 | if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) | |||
4490 | checkVariadicArgument(Arg, CallType); | |||
4491 | } | |||
4492 | } | |||
4493 | } | |||
4494 | ||||
4495 | if (FDecl || Proto) { | |||
4496 | CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); | |||
4497 | ||||
4498 | // Type safety checking. | |||
4499 | if (FDecl) { | |||
4500 | for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) | |||
4501 | CheckArgumentWithTypeTag(I, Args, Loc); | |||
4502 | } | |||
4503 | } | |||
4504 | ||||
4505 | if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { | |||
4506 | auto *AA = FDecl->getAttr<AllocAlignAttr>(); | |||
4507 | const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; | |||
4508 | if (!Arg->isValueDependent()) { | |||
4509 | Expr::EvalResult Align; | |||
4510 | if (Arg->EvaluateAsInt(Align, Context)) { | |||
4511 | const llvm::APSInt &I = Align.Val.getInt(); | |||
4512 | if (!I.isPowerOf2()) | |||
4513 | Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) | |||
4514 | << Arg->getSourceRange(); | |||
4515 | ||||
4516 | if (I > Sema::MaximumAlignment) | |||
4517 | Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) | |||
4518 | << Arg->getSourceRange() << Sema::MaximumAlignment; | |||
4519 | } | |||
4520 | } | |||
4521 | } | |||
4522 | ||||
4523 | if (FD) | |||
4524 | diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); | |||
4525 | } | |||
4526 | ||||
4527 | /// CheckConstructorCall - Check a constructor call for correctness and safety | |||
4528 | /// properties not enforced by the C type system. | |||
4529 | void Sema::CheckConstructorCall(FunctionDecl *FDecl, | |||
4530 | ArrayRef<const Expr *> Args, | |||
4531 | const FunctionProtoType *Proto, | |||
4532 | SourceLocation Loc) { | |||
4533 | VariadicCallType CallType = | |||
4534 | Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; | |||
4535 | checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, | |||
4536 | Loc, SourceRange(), CallType); | |||
4537 | } | |||
4538 | ||||
4539 | /// CheckFunctionCall - Check a direct function call for various correctness | |||
4540 | /// and safety properties not strictly enforced by the C type system. | |||
4541 | bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, | |||
4542 | const FunctionProtoType *Proto) { | |||
4543 | bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && | |||
| ||||
4544 | isa<CXXMethodDecl>(FDecl); | |||
4545 | bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || | |||
4546 | IsMemberOperatorCall; | |||
4547 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, | |||
4548 | TheCall->getCallee()); | |||
4549 | Expr** Args = TheCall->getArgs(); | |||
4550 | unsigned NumArgs = TheCall->getNumArgs(); | |||
4551 | ||||
4552 | Expr *ImplicitThis = nullptr; | |||
4553 | if (IsMemberOperatorCall
| |||
4554 | // If this is a call to a member operator, hide the first argument | |||
4555 | // from checkCall. | |||
4556 | // FIXME: Our choice of AST representation here is less than ideal. | |||
4557 | ImplicitThis = Args[0]; | |||
4558 | ++Args; | |||
4559 | --NumArgs; | |||
4560 | } else if (IsMemberFunction
| |||
4561 | ImplicitThis = | |||
4562 | cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); | |||
4563 | ||||
4564 | checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), | |||
4565 | IsMemberFunction, TheCall->getRParenLoc(), | |||
4566 | TheCall->getCallee()->getSourceRange(), CallType); | |||
4567 | ||||
4568 | IdentifierInfo *FnInfo = FDecl->getIdentifier(); | |||
4569 | // None of the checks below are needed for functions that don't have | |||
4570 | // simple names (e.g., C++ conversion functions). | |||
4571 | if (!FnInfo) | |||
4572 | return false; | |||
4573 | ||||
4574 | CheckTCBEnforcement(TheCall, FDecl); | |||
4575 | ||||
4576 | CheckAbsoluteValueFunction(TheCall, FDecl); | |||
4577 | CheckMaxUnsignedZero(TheCall, FDecl); | |||
4578 | ||||
4579 | if (getLangOpts().ObjC) | |||
4580 | DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); | |||
4581 | ||||
4582 | unsigned CMId = FDecl->getMemoryFunctionKind(); | |||
4583 | ||||
4584 | // Handle memory setting and copying functions. | |||
4585 | switch (CMId) { | |||
4586 | case 0: | |||
4587 | return false; | |||
4588 | /* case Builtin::BIstrlcpy: // fallthrough | |||
4589 | case Builtin::BIstrlcat: | |||
4590 | CheckStrlcpycatArguments(TheCall, FnInfo); | |||
4591 | break;*/ | |||
4592 | case Builtin::BIstrncat: | |||
4593 | CheckStrncatArguments(TheCall, FnInfo); | |||
4594 | break; | |||
4595 | case Builtin::BIfree: | |||
4596 | CheckFreeArguments(TheCall); | |||
4597 | break; | |||
4598 | default: | |||
4599 | CheckMemaccessArguments(TheCall, CMId, FnInfo); | |||
4600 | } | |||
4601 | ||||
4602 | return false; | |||
4603 | } | |||
4604 | ||||
4605 | bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, | |||
4606 | ArrayRef<const Expr *> Args) { | |||
4607 | VariadicCallType CallType = | |||
4608 | Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; | |||
4609 | ||||
4610 | checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, | |||
4611 | /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), | |||
4612 | CallType); | |||
4613 | ||||
4614 | return false; | |||
4615 | } | |||
4616 | ||||
4617 | bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, | |||
4618 | const FunctionProtoType *Proto) { | |||
4619 | QualType Ty; | |||
4620 | if (const auto *V = dyn_cast<VarDecl>(NDecl)) | |||
4621 | Ty = V->getType().getNonReferenceType(); | |||
4622 | else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) | |||
4623 | Ty = F->getType().getNonReferenceType(); | |||
4624 | else | |||
4625 | return false; | |||
4626 | ||||
4627 | if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && | |||
4628 | !Ty->isFunctionProtoType()) | |||
4629 | return false; | |||
4630 | ||||
4631 | VariadicCallType CallType; | |||
4632 | if (!Proto || !Proto->isVariadic()) { | |||
4633 | CallType = VariadicDoesNotApply; | |||
4634 | } else if (Ty->isBlockPointerType()) { | |||
4635 | CallType = VariadicBlock; | |||
4636 | } else { // Ty->isFunctionPointerType() | |||
4637 | CallType = VariadicFunction; | |||
4638 | } | |||
4639 | ||||
4640 | checkCall(NDecl, Proto, /*ThisArg=*/nullptr, | |||
4641 | llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), | |||
4642 | /*IsMemberFunction=*/false, TheCall->getRParenLoc(), | |||
4643 | TheCall->getCallee()->getSourceRange(), CallType); | |||
4644 | ||||
4645 | return false; | |||
4646 | } | |||
4647 | ||||
4648 | /// Checks function calls when a FunctionDecl or a NamedDecl is not available, | |||
4649 | /// such as function pointers returned from functions. | |||
4650 | bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { | |||
4651 | VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, | |||
4652 | TheCall->getCallee()); | |||
4653 | checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, | |||
4654 | llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), | |||
4655 | /*IsMemberFunction=*/false, TheCall->getRParenLoc(), | |||
4656 | TheCall->getCallee()->getSourceRange(), CallType); | |||
4657 | ||||
4658 | return false; | |||
4659 | } | |||
4660 | ||||
4661 | static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { | |||
4662 | if (!llvm::isValidAtomicOrderingCABI(Ordering)) | |||
4663 | return false; | |||
4664 | ||||
4665 | auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; | |||
4666 | switch (Op) { | |||
4667 | case AtomicExpr::AO__c11_atomic_init: | |||
4668 | case AtomicExpr::AO__opencl_atomic_init: | |||
4669 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 4669); | |||
4670 | ||||
4671 | case AtomicExpr::AO__c11_atomic_load: | |||
4672 | case AtomicExpr::AO__opencl_atomic_load: | |||
4673 | case AtomicExpr::AO__atomic_load_n: | |||
4674 | case AtomicExpr::AO__atomic_load: | |||
4675 | return OrderingCABI != llvm::AtomicOrderingCABI::release && | |||
4676 | OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; | |||
4677 | ||||
4678 | case AtomicExpr::AO__c11_atomic_store: | |||
4679 | case AtomicExpr::AO__opencl_atomic_store: | |||
4680 | case AtomicExpr::AO__atomic_store: | |||
4681 | case AtomicExpr::AO__atomic_store_n: | |||
4682 | return OrderingCABI != llvm::AtomicOrderingCABI::consume && | |||
4683 | OrderingCABI != llvm::AtomicOrderingCABI::acquire && | |||
4684 | OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; | |||
4685 | ||||
4686 | default: | |||
4687 | return true; | |||
4688 | } | |||
4689 | } | |||
4690 | ||||
4691 | ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, | |||
4692 | AtomicExpr::AtomicOp Op) { | |||
4693 | CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); | |||
4694 | DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); | |||
4695 | MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; | |||
4696 | return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, | |||
4697 | DRE->getSourceRange(), TheCall->getRParenLoc(), Args, | |||
4698 | Op); | |||
4699 | } | |||
4700 | ||||
4701 | ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, | |||
4702 | SourceLocation RParenLoc, MultiExprArg Args, | |||
4703 | AtomicExpr::AtomicOp Op, | |||
4704 | AtomicArgumentOrder ArgOrder) { | |||
4705 | // All the non-OpenCL operations take one of the following forms. | |||
4706 | // The OpenCL operations take the __c11 forms with one extra argument for | |||
4707 | // synchronization scope. | |||
4708 | enum { | |||
4709 | // C __c11_atomic_init(A *, C) | |||
4710 | Init, | |||
4711 | ||||
4712 | // C __c11_atomic_load(A *, int) | |||
4713 | Load, | |||
4714 | ||||
4715 | // void __atomic_load(A *, CP, int) | |||
4716 | LoadCopy, | |||
4717 | ||||
4718 | // void __atomic_store(A *, CP, int) | |||
4719 | Copy, | |||
4720 | ||||
4721 | // C __c11_atomic_add(A *, M, int) | |||
4722 | Arithmetic, | |||
4723 | ||||
4724 | // C __atomic_exchange_n(A *, CP, int) | |||
4725 | Xchg, | |||
4726 | ||||
4727 | // void __atomic_exchange(A *, C *, CP, int) | |||
4728 | GNUXchg, | |||
4729 | ||||
4730 | // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) | |||
4731 | C11CmpXchg, | |||
4732 | ||||
4733 | // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) | |||
4734 | GNUCmpXchg | |||
4735 | } Form = Init; | |||
4736 | ||||
4737 | const unsigned NumForm = GNUCmpXchg + 1; | |||
4738 | const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; | |||
4739 | const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; | |||
4740 | // where: | |||
4741 | // C is an appropriate type, | |||
4742 | // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, | |||
4743 | // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, | |||
4744 | // M is C if C is an integer, and ptrdiff_t if C is a pointer, and | |||
4745 | // the int parameters are for orderings. | |||
4746 | ||||
4747 | static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm | |||
4748 | && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, | |||
4749 | "need to update code for modified forms"); | |||
4750 | static_assert(AtomicExpr::AO__c11_atomic_init == 0 && | |||
4751 | AtomicExpr::AO__c11_atomic_fetch_min + 1 == | |||
4752 | AtomicExpr::AO__atomic_load, | |||
4753 | "need to update code for modified C11 atomics"); | |||
4754 | bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && | |||
4755 | Op <= AtomicExpr::AO__opencl_atomic_fetch_max; | |||
4756 | bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && | |||
4757 | Op <= AtomicExpr::AO__c11_atomic_fetch_min) || | |||
4758 | IsOpenCL; | |||
4759 | bool IsN = Op == AtomicExpr::AO__atomic_load_n || | |||
4760 | Op == AtomicExpr::AO__atomic_store_n || | |||
4761 | Op == AtomicExpr::AO__atomic_exchange_n || | |||
4762 | Op == AtomicExpr::AO__atomic_compare_exchange_n; | |||
4763 | bool IsAddSub = false; | |||
4764 | ||||
4765 | switch (Op) { | |||
4766 | case AtomicExpr::AO__c11_atomic_init: | |||
4767 | case AtomicExpr::AO__opencl_atomic_init: | |||
4768 | Form = Init; | |||
4769 | break; | |||
4770 | ||||
4771 | case AtomicExpr::AO__c11_atomic_load: | |||
4772 | case AtomicExpr::AO__opencl_atomic_load: | |||
4773 | case AtomicExpr::AO__atomic_load_n: | |||
4774 | Form = Load; | |||
4775 | break; | |||
4776 | ||||
4777 | case AtomicExpr::AO__atomic_load: | |||
4778 | Form = LoadCopy; | |||
4779 | break; | |||
4780 | ||||
4781 | case AtomicExpr::AO__c11_atomic_store: | |||
4782 | case AtomicExpr::AO__opencl_atomic_store: | |||
4783 | case AtomicExpr::AO__atomic_store: | |||
4784 | case AtomicExpr::AO__atomic_store_n: | |||
4785 | Form = Copy; | |||
4786 | break; | |||
4787 | ||||
4788 | case AtomicExpr::AO__c11_atomic_fetch_add: | |||
4789 | case AtomicExpr::AO__c11_atomic_fetch_sub: | |||
4790 | case AtomicExpr::AO__opencl_atomic_fetch_add: | |||
4791 | case AtomicExpr::AO__opencl_atomic_fetch_sub: | |||
4792 | case AtomicExpr::AO__atomic_fetch_add: | |||
4793 | case AtomicExpr::AO__atomic_fetch_sub: | |||
4794 | case AtomicExpr::AO__atomic_add_fetch: | |||
4795 | case AtomicExpr::AO__atomic_sub_fetch: | |||
4796 | IsAddSub = true; | |||
4797 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
4798 | case AtomicExpr::AO__c11_atomic_fetch_and: | |||
4799 | case AtomicExpr::AO__c11_atomic_fetch_or: | |||
4800 | case AtomicExpr::AO__c11_atomic_fetch_xor: | |||
4801 | case AtomicExpr::AO__opencl_atomic_fetch_and: | |||
4802 | case AtomicExpr::AO__opencl_atomic_fetch_or: | |||
4803 | case AtomicExpr::AO__opencl_atomic_fetch_xor: | |||
4804 | case AtomicExpr::AO__atomic_fetch_and: | |||
4805 | case AtomicExpr::AO__atomic_fetch_or: | |||
4806 | case AtomicExpr::AO__atomic_fetch_xor: | |||
4807 | case AtomicExpr::AO__atomic_fetch_nand: | |||
4808 | case AtomicExpr::AO__atomic_and_fetch: | |||
4809 | case AtomicExpr::AO__atomic_or_fetch: | |||
4810 | case AtomicExpr::AO__atomic_xor_fetch: | |||
4811 | case AtomicExpr::AO__atomic_nand_fetch: | |||
4812 | case AtomicExpr::AO__c11_atomic_fetch_min: | |||
4813 | case AtomicExpr::AO__c11_atomic_fetch_max: | |||
4814 | case AtomicExpr::AO__opencl_atomic_fetch_min: | |||
4815 | case AtomicExpr::AO__opencl_atomic_fetch_max: | |||
4816 | case AtomicExpr::AO__atomic_min_fetch: | |||
4817 | case AtomicExpr::AO__atomic_max_fetch: | |||
4818 | case AtomicExpr::AO__atomic_fetch_min: | |||
4819 | case AtomicExpr::AO__atomic_fetch_max: | |||
4820 | Form = Arithmetic; | |||
4821 | break; | |||
4822 | ||||
4823 | case AtomicExpr::AO__c11_atomic_exchange: | |||
4824 | case AtomicExpr::AO__opencl_atomic_exchange: | |||
4825 | case AtomicExpr::AO__atomic_exchange_n: | |||
4826 | Form = Xchg; | |||
4827 | break; | |||
4828 | ||||
4829 | case AtomicExpr::AO__atomic_exchange: | |||
4830 | Form = GNUXchg; | |||
4831 | break; | |||
4832 | ||||
4833 | case AtomicExpr::AO__c11_atomic_compare_exchange_strong: | |||
4834 | case AtomicExpr::AO__c11_atomic_compare_exchange_weak: | |||
4835 | case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: | |||
4836 | case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: | |||
4837 | Form = C11CmpXchg; | |||
4838 | break; | |||
4839 | ||||
4840 | case AtomicExpr::AO__atomic_compare_exchange: | |||
4841 | case AtomicExpr::AO__atomic_compare_exchange_n: | |||
4842 | Form = GNUCmpXchg; | |||
4843 | break; | |||
4844 | } | |||
4845 | ||||
4846 | unsigned AdjustedNumArgs = NumArgs[Form]; | |||
4847 | if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) | |||
4848 | ++AdjustedNumArgs; | |||
4849 | // Check we have the right number of arguments. | |||
4850 | if (Args.size() < AdjustedNumArgs) { | |||
4851 | Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) | |||
4852 | << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) | |||
4853 | << ExprRange; | |||
4854 | return ExprError(); | |||
4855 | } else if (Args.size() > AdjustedNumArgs) { | |||
4856 | Diag(Args[AdjustedNumArgs]->getBeginLoc(), | |||
4857 | diag::err_typecheck_call_too_many_args) | |||
4858 | << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) | |||
4859 | << ExprRange; | |||
4860 | return ExprError(); | |||
4861 | } | |||
4862 | ||||
4863 | // Inspect the first argument of the atomic operation. | |||
4864 | Expr *Ptr = Args[0]; | |||
4865 | ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); | |||
4866 | if (ConvertedPtr.isInvalid()) | |||
4867 | return ExprError(); | |||
4868 | ||||
4869 | Ptr = ConvertedPtr.get(); | |||
4870 | const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); | |||
4871 | if (!pointerType) { | |||
4872 | Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) | |||
4873 | << Ptr->getType() << Ptr->getSourceRange(); | |||
4874 | return ExprError(); | |||
4875 | } | |||
4876 | ||||
4877 | // For a __c11 builtin, this should be a pointer to an _Atomic type. | |||
4878 | QualType AtomTy = pointerType->getPointeeType(); // 'A' | |||
4879 | QualType ValType = AtomTy; // 'C' | |||
4880 | if (IsC11) { | |||
4881 | if (!AtomTy->isAtomicType()) { | |||
4882 | Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) | |||
4883 | << Ptr->getType() << Ptr->getSourceRange(); | |||
4884 | return ExprError(); | |||
4885 | } | |||
4886 | if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || | |||
4887 | AtomTy.getAddressSpace() == LangAS::opencl_constant) { | |||
4888 | Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) | |||
4889 | << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() | |||
4890 | << Ptr->getSourceRange(); | |||
4891 | return ExprError(); | |||
4892 | } | |||
4893 | ValType = AtomTy->castAs<AtomicType>()->getValueType(); | |||
4894 | } else if (Form != Load && Form != LoadCopy) { | |||
4895 | if (ValType.isConstQualified()) { | |||
4896 | Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) | |||
4897 | << Ptr->getType() << Ptr->getSourceRange(); | |||
4898 | return ExprError(); | |||
4899 | } | |||
4900 | } | |||
4901 | ||||
4902 | // For an arithmetic operation, the implied arithmetic must be well-formed. | |||
4903 | if (Form == Arithmetic) { | |||
4904 | // gcc does not enforce these rules for GNU atomics, but we do so for sanity. | |||
4905 | if (IsAddSub && !ValType->isIntegerType() | |||
4906 | && !ValType->isPointerType()) { | |||
4907 | Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) | |||
4908 | << IsC11 << Ptr->getType() << Ptr->getSourceRange(); | |||
4909 | return ExprError(); | |||
4910 | } | |||
4911 | if (!IsAddSub && !ValType->isIntegerType()) { | |||
4912 | Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) | |||
4913 | << IsC11 << Ptr->getType() << Ptr->getSourceRange(); | |||
4914 | return ExprError(); | |||
4915 | } | |||
4916 | if (IsC11 && ValType->isPointerType() && | |||
4917 | RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), | |||
4918 | diag::err_incomplete_type)) { | |||
4919 | return ExprError(); | |||
4920 | } | |||
4921 | } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { | |||
4922 | // For __atomic_*_n operations, the value type must be a scalar integral or | |||
4923 | // pointer type which is 1, 2, 4, 8 or 16 bytes in length. | |||
4924 | Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) | |||
4925 | << IsC11 << Ptr->getType() << Ptr->getSourceRange(); | |||
4926 | return ExprError(); | |||
4927 | } | |||
4928 | ||||
4929 | if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && | |||
4930 | !AtomTy->isScalarType()) { | |||
4931 | // For GNU atomics, require a trivially-copyable type. This is not part of | |||
4932 | // the GNU atomics specification, but we enforce it for sanity. | |||
4933 | Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) | |||
4934 | << Ptr->getType() << Ptr->getSourceRange(); | |||
4935 | return ExprError(); | |||
4936 | } | |||
4937 | ||||
4938 | switch (ValType.getObjCLifetime()) { | |||
4939 | case Qualifiers::OCL_None: | |||
4940 | case Qualifiers::OCL_ExplicitNone: | |||
4941 | // okay | |||
4942 | break; | |||
4943 | ||||
4944 | case Qualifiers::OCL_Weak: | |||
4945 | case Qualifiers::OCL_Strong: | |||
4946 | case Qualifiers::OCL_Autoreleasing: | |||
4947 | // FIXME: Can this happen? By this point, ValType should be known | |||
4948 | // to be trivially copyable. | |||
4949 | Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) | |||
4950 | << ValType << Ptr->getSourceRange(); | |||
4951 | return ExprError(); | |||
4952 | } | |||
4953 | ||||
4954 | // All atomic operations have an overload which takes a pointer to a volatile | |||
4955 | // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself | |||
4956 | // into the result or the other operands. Similarly atomic_load takes a | |||
4957 | // pointer to a const 'A'. | |||
4958 | ValType.removeLocalVolatile(); | |||
4959 | ValType.removeLocalConst(); | |||
4960 | QualType ResultType = ValType; | |||
4961 | if (Form == Copy || Form == LoadCopy || Form == GNUXchg || | |||
4962 | Form == Init) | |||
4963 | ResultType = Context.VoidTy; | |||
4964 | else if (Form == C11CmpXchg || Form == GNUCmpXchg) | |||
4965 | ResultType = Context.BoolTy; | |||
4966 | ||||
4967 | // The type of a parameter passed 'by value'. In the GNU atomics, such | |||
4968 | // arguments are actually passed as pointers. | |||
4969 | QualType ByValType = ValType; // 'CP' | |||
4970 | bool IsPassedByAddress = false; | |||
4971 | if (!IsC11 && !IsN) { | |||
4972 | ByValType = Ptr->getType(); | |||
4973 | IsPassedByAddress = true; | |||
4974 | } | |||
4975 | ||||
4976 | SmallVector<Expr *, 5> APIOrderedArgs; | |||
4977 | if (ArgOrder == Sema::AtomicArgumentOrder::AST) { | |||
4978 | APIOrderedArgs.push_back(Args[0]); | |||
4979 | switch (Form) { | |||
4980 | case Init: | |||
4981 | case Load: | |||
4982 | APIOrderedArgs.push_back(Args[1]); // Val1/Order | |||
4983 | break; | |||
4984 | case LoadCopy: | |||
4985 | case Copy: | |||
4986 | case Arithmetic: | |||
4987 | case Xchg: | |||
4988 | APIOrderedArgs.push_back(Args[2]); // Val1 | |||
4989 | APIOrderedArgs.push_back(Args[1]); // Order | |||
4990 | break; | |||
4991 | case GNUXchg: | |||
4992 | APIOrderedArgs.push_back(Args[2]); // Val1 | |||
4993 | APIOrderedArgs.push_back(Args[3]); // Val2 | |||
4994 | APIOrderedArgs.push_back(Args[1]); // Order | |||
4995 | break; | |||
4996 | case C11CmpXchg: | |||
4997 | APIOrderedArgs.push_back(Args[2]); // Val1 | |||
4998 | APIOrderedArgs.push_back(Args[4]); // Val2 | |||
4999 | APIOrderedArgs.push_back(Args[1]); // Order | |||
5000 | APIOrderedArgs.push_back(Args[3]); // OrderFail | |||
5001 | break; | |||
5002 | case GNUCmpXchg: | |||
5003 | APIOrderedArgs.push_back(Args[2]); // Val1 | |||
5004 | APIOrderedArgs.push_back(Args[4]); // Val2 | |||
5005 | APIOrderedArgs.push_back(Args[5]); // Weak | |||
5006 | APIOrderedArgs.push_back(Args[1]); // Order | |||
5007 | APIOrderedArgs.push_back(Args[3]); // OrderFail | |||
5008 | break; | |||
5009 | } | |||
5010 | } else | |||
5011 | APIOrderedArgs.append(Args.begin(), Args.end()); | |||
5012 | ||||
5013 | // The first argument's non-CV pointer type is used to deduce the type of | |||
5014 | // subsequent arguments, except for: | |||
5015 | // - weak flag (always converted to bool) | |||
5016 | // - memory order (always converted to int) | |||
5017 | // - scope (always converted to int) | |||
5018 | for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { | |||
5019 | QualType Ty; | |||
5020 | if (i < NumVals[Form] + 1) { | |||
5021 | switch (i) { | |||
5022 | case 0: | |||
5023 | // The first argument is always a pointer. It has a fixed type. | |||
5024 | // It is always dereferenced, a nullptr is undefined. | |||
5025 | CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); | |||
5026 | // Nothing else to do: we already know all we want about this pointer. | |||
5027 | continue; | |||
5028 | case 1: | |||
5029 | // The second argument is the non-atomic operand. For arithmetic, this | |||
5030 | // is always passed by value, and for a compare_exchange it is always | |||
5031 | // passed by address. For the rest, GNU uses by-address and C11 uses | |||
5032 | // by-value. | |||
5033 | assert(Form != Load)((Form != Load) ? static_cast<void> (0) : __assert_fail ("Form != Load", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 5033, __PRETTY_FUNCTION__)); | |||
5034 | if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) | |||
5035 | Ty = ValType; | |||
5036 | else if (Form == Copy || Form == Xchg) { | |||
5037 | if (IsPassedByAddress) { | |||
5038 | // The value pointer is always dereferenced, a nullptr is undefined. | |||
5039 | CheckNonNullArgument(*this, APIOrderedArgs[i], | |||
5040 | ExprRange.getBegin()); | |||
5041 | } | |||
5042 | Ty = ByValType; | |||
5043 | } else if (Form == Arithmetic) | |||
5044 | Ty = Context.getPointerDiffType(); | |||
5045 | else { | |||
5046 | Expr *ValArg = APIOrderedArgs[i]; | |||
5047 | // The value pointer is always dereferenced, a nullptr is undefined. | |||
5048 | CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); | |||
5049 | LangAS AS = LangAS::Default; | |||
5050 | // Keep address space of non-atomic pointer type. | |||
5051 | if (const PointerType *PtrTy = | |||
5052 | ValArg->getType()->getAs<PointerType>()) { | |||
5053 | AS = PtrTy->getPointeeType().getAddressSpace(); | |||
5054 | } | |||
5055 | Ty = Context.getPointerType( | |||
5056 | Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); | |||
5057 | } | |||
5058 | break; | |||
5059 | case 2: | |||
5060 | // The third argument to compare_exchange / GNU exchange is the desired | |||
5061 | // value, either by-value (for the C11 and *_n variant) or as a pointer. | |||
5062 | if (IsPassedByAddress) | |||
5063 | CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); | |||
5064 | Ty = ByValType; | |||
5065 | break; | |||
5066 | case 3: | |||
5067 | // The fourth argument to GNU compare_exchange is a 'weak' flag. | |||
5068 | Ty = Context.BoolTy; | |||
5069 | break; | |||
5070 | } | |||
5071 | } else { | |||
5072 | // The order(s) and scope are always converted to int. | |||
5073 | Ty = Context.IntTy; | |||
5074 | } | |||
5075 | ||||
5076 | InitializedEntity Entity = | |||
5077 | InitializedEntity::InitializeParameter(Context, Ty, false); | |||
5078 | ExprResult Arg = APIOrderedArgs[i]; | |||
5079 | Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); | |||
5080 | if (Arg.isInvalid()) | |||
5081 | return true; | |||
5082 | APIOrderedArgs[i] = Arg.get(); | |||
5083 | } | |||
5084 | ||||
5085 | // Permute the arguments into a 'consistent' order. | |||
5086 | SmallVector<Expr*, 5> SubExprs; | |||
5087 | SubExprs.push_back(Ptr); | |||
5088 | switch (Form) { | |||
5089 | case Init: | |||
5090 | // Note, AtomicExpr::getVal1() has a special case for this atomic. | |||
5091 | SubExprs.push_back(APIOrderedArgs[1]); // Val1 | |||
5092 | break; | |||
5093 | case Load: | |||
5094 | SubExprs.push_back(APIOrderedArgs[1]); // Order | |||
5095 | break; | |||
5096 | case LoadCopy: | |||
5097 | case Copy: | |||
5098 | case Arithmetic: | |||
5099 | case Xchg: | |||
5100 | SubExprs.push_back(APIOrderedArgs[2]); // Order | |||
5101 | SubExprs.push_back(APIOrderedArgs[1]); // Val1 | |||
5102 | break; | |||
5103 | case GNUXchg: | |||
5104 | // Note, AtomicExpr::getVal2() has a special case for this atomic. | |||
5105 | SubExprs.push_back(APIOrderedArgs[3]); // Order | |||
5106 | SubExprs.push_back(APIOrderedArgs[1]); // Val1 | |||
5107 | SubExprs.push_back(APIOrderedArgs[2]); // Val2 | |||
5108 | break; | |||
5109 | case C11CmpXchg: | |||
5110 | SubExprs.push_back(APIOrderedArgs[3]); // Order | |||
5111 | SubExprs.push_back(APIOrderedArgs[1]); // Val1 | |||
5112 | SubExprs.push_back(APIOrderedArgs[4]); // OrderFail | |||
5113 | SubExprs.push_back(APIOrderedArgs[2]); // Val2 | |||
5114 | break; | |||
5115 | case GNUCmpXchg: | |||
5116 | SubExprs.push_back(APIOrderedArgs[4]); // Order | |||
5117 | SubExprs.push_back(APIOrderedArgs[1]); // Val1 | |||
5118 | SubExprs.push_back(APIOrderedArgs[5]); // OrderFail | |||
5119 | SubExprs.push_back(APIOrderedArgs[2]); // Val2 | |||
5120 | SubExprs.push_back(APIOrderedArgs[3]); // Weak | |||
5121 | break; | |||
5122 | } | |||
5123 | ||||
5124 | if (SubExprs.size() >= 2 && Form != Init) { | |||
5125 | if (Optional<llvm::APSInt> Result = | |||
5126 | SubExprs[1]->getIntegerConstantExpr(Context)) | |||
5127 | if (!isValidOrderingForOp(Result->getSExtValue(), Op)) | |||
5128 | Diag(SubExprs[1]->getBeginLoc(), | |||
5129 | diag::warn_atomic_op_has_invalid_memory_order) | |||
5130 | << SubExprs[1]->getSourceRange(); | |||
5131 | } | |||
5132 | ||||
5133 | if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { | |||
5134 | auto *Scope = Args[Args.size() - 1]; | |||
5135 | if (Optional<llvm::APSInt> Result = | |||
5136 | Scope->getIntegerConstantExpr(Context)) { | |||
5137 | if (!ScopeModel->isValid(Result->getZExtValue())) | |||
5138 | Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) | |||
5139 | << Scope->getSourceRange(); | |||
5140 | } | |||
5141 | SubExprs.push_back(Scope); | |||
5142 | } | |||
5143 | ||||
5144 | AtomicExpr *AE = new (Context) | |||
5145 | AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); | |||
5146 | ||||
5147 | if ((Op == AtomicExpr::AO__c11_atomic_load || | |||
5148 | Op == AtomicExpr::AO__c11_atomic_store || | |||
5149 | Op == AtomicExpr::AO__opencl_atomic_load || | |||
5150 | Op == AtomicExpr::AO__opencl_atomic_store ) && | |||
5151 | Context.AtomicUsesUnsupportedLibcall(AE)) | |||
5152 | Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) | |||
5153 | << ((Op == AtomicExpr::AO__c11_atomic_load || | |||
5154 | Op == AtomicExpr::AO__opencl_atomic_load) | |||
5155 | ? 0 | |||
5156 | : 1); | |||
5157 | ||||
5158 | if (ValType->isExtIntType()) { | |||
5159 | Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); | |||
5160 | return ExprError(); | |||
5161 | } | |||
5162 | ||||
5163 | return AE; | |||
5164 | } | |||
5165 | ||||
5166 | /// checkBuiltinArgument - Given a call to a builtin function, perform | |||
5167 | /// normal type-checking on the given argument, updating the call in | |||
5168 | /// place. This is useful when a builtin function requires custom | |||
5169 | /// type-checking for some of its arguments but not necessarily all of | |||
5170 | /// them. | |||
5171 | /// | |||
5172 | /// Returns true on error. | |||
5173 | static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { | |||
5174 | FunctionDecl *Fn = E->getDirectCallee(); | |||
5175 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 5175, __PRETTY_FUNCTION__)); | |||
5176 | ||||
5177 | ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); | |||
5178 | InitializedEntity Entity = | |||
5179 | InitializedEntity::InitializeParameter(S.Context, Param); | |||
5180 | ||||
5181 | ExprResult Arg = E->getArg(0); | |||
5182 | Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); | |||
5183 | if (Arg.isInvalid()) | |||
5184 | return true; | |||
5185 | ||||
5186 | E->setArg(ArgIndex, Arg.get()); | |||
5187 | return false; | |||
5188 | } | |||
5189 | ||||
5190 | /// We have a call to a function like __sync_fetch_and_add, which is an | |||
5191 | /// overloaded function based on the pointer type of its first argument. | |||
5192 | /// The main BuildCallExpr routines have already promoted the types of | |||
5193 | /// arguments because all of these calls are prototyped as void(...). | |||
5194 | /// | |||
5195 | /// This function goes through and does final semantic checking for these | |||
5196 | /// builtins, as well as generating any warnings. | |||
5197 | ExprResult | |||
5198 | Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { | |||
5199 | CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); | |||
5200 | Expr *Callee = TheCall->getCallee(); | |||
5201 | DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); | |||
5202 | FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); | |||
5203 | ||||
5204 | // Ensure that we have at least one argument to do type inference from. | |||
5205 | if (TheCall->getNumArgs() < 1) { | |||
5206 | Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) | |||
5207 | << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); | |||
5208 | return ExprError(); | |||
5209 | } | |||
5210 | ||||
5211 | // Inspect the first argument of the atomic builtin. This should always be | |||
5212 | // a pointer type, whose element is an integral scalar or pointer type. | |||
5213 | // Because it is a pointer type, we don't have to worry about any implicit | |||
5214 | // casts here. | |||
5215 | // FIXME: We don't allow floating point scalars as input. | |||
5216 | Expr *FirstArg = TheCall->getArg(0); | |||
5217 | ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); | |||
5218 | if (FirstArgResult.isInvalid()) | |||
5219 | return ExprError(); | |||
5220 | FirstArg = FirstArgResult.get(); | |||
5221 | TheCall->setArg(0, FirstArg); | |||
5222 | ||||
5223 | const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); | |||
5224 | if (!pointerType) { | |||
5225 | Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) | |||
5226 | << FirstArg->getType() << FirstArg->getSourceRange(); | |||
5227 | return ExprError(); | |||
5228 | } | |||
5229 | ||||
5230 | QualType ValType = pointerType->getPointeeType(); | |||
5231 | if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && | |||
5232 | !ValType->isBlockPointerType()) { | |||
5233 | Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) | |||
5234 | << FirstArg->getType() << FirstArg->getSourceRange(); | |||
5235 | return ExprError(); | |||
5236 | } | |||
5237 | ||||
5238 | if (ValType.isConstQualified()) { | |||
5239 | Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) | |||
5240 | << FirstArg->getType() << FirstArg->getSourceRange(); | |||
5241 | return ExprError(); | |||
5242 | } | |||
5243 | ||||
5244 | switch (ValType.getObjCLifetime()) { | |||
5245 | case Qualifiers::OCL_None: | |||
5246 | case Qualifiers::OCL_ExplicitNone: | |||
5247 | // okay | |||
5248 | break; | |||
5249 | ||||
5250 | case Qualifiers::OCL_Weak: | |||
5251 | case Qualifiers::OCL_Strong: | |||
5252 | case Qualifiers::OCL_Autoreleasing: | |||
5253 | Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) | |||
5254 | << ValType << FirstArg->getSourceRange(); | |||
5255 | return ExprError(); | |||
5256 | } | |||
5257 | ||||
5258 | // Strip any qualifiers off ValType. | |||
5259 | ValType = ValType.getUnqualifiedType(); | |||
5260 | ||||
5261 | // The majority of builtins return a value, but a few have special return | |||
5262 | // types, so allow them to override appropriately below. | |||
5263 | QualType ResultType = ValType; | |||
5264 | ||||
5265 | // We need to figure out which concrete builtin this maps onto. For example, | |||
5266 | // __sync_fetch_and_add with a 2 byte object turns into | |||
5267 | // __sync_fetch_and_add_2. | |||
5268 | #define BUILTIN_ROW(x) \ | |||
5269 | { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ | |||
5270 | Builtin::BI##x##_8, Builtin::BI##x##_16 } | |||
5271 | ||||
5272 | static const unsigned BuiltinIndices[][5] = { | |||
5273 | BUILTIN_ROW(__sync_fetch_and_add), | |||
5274 | BUILTIN_ROW(__sync_fetch_and_sub), | |||
5275 | BUILTIN_ROW(__sync_fetch_and_or), | |||
5276 | BUILTIN_ROW(__sync_fetch_and_and), | |||
5277 | BUILTIN_ROW(__sync_fetch_and_xor), | |||
5278 | BUILTIN_ROW(__sync_fetch_and_nand), | |||
5279 | ||||
5280 | BUILTIN_ROW(__sync_add_and_fetch), | |||
5281 | BUILTIN_ROW(__sync_sub_and_fetch), | |||
5282 | BUILTIN_ROW(__sync_and_and_fetch), | |||
5283 | BUILTIN_ROW(__sync_or_and_fetch), | |||
5284 | BUILTIN_ROW(__sync_xor_and_fetch), | |||
5285 | BUILTIN_ROW(__sync_nand_and_fetch), | |||
5286 | ||||
5287 | BUILTIN_ROW(__sync_val_compare_and_swap), | |||
5288 | BUILTIN_ROW(__sync_bool_compare_and_swap), | |||
5289 | BUILTIN_ROW(__sync_lock_test_and_set), | |||
5290 | BUILTIN_ROW(__sync_lock_release), | |||
5291 | BUILTIN_ROW(__sync_swap) | |||
5292 | }; | |||
5293 | #undef BUILTIN_ROW | |||
5294 | ||||
5295 | // Determine the index of the size. | |||
5296 | unsigned SizeIndex; | |||
5297 | switch (Context.getTypeSizeInChars(ValType).getQuantity()) { | |||
5298 | case 1: SizeIndex = 0; break; | |||
5299 | case 2: SizeIndex = 1; break; | |||
5300 | case 4: SizeIndex = 2; break; | |||
5301 | case 8: SizeIndex = 3; break; | |||
5302 | case 16: SizeIndex = 4; break; | |||
5303 | default: | |||
5304 | Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) | |||
5305 | << FirstArg->getType() << FirstArg->getSourceRange(); | |||
5306 | return ExprError(); | |||
5307 | } | |||
5308 | ||||
5309 | // Each of these builtins has one pointer argument, followed by some number of | |||
5310 | // values (0, 1 or 2) followed by a potentially empty varags list of stuff | |||
5311 | // that we ignore. Find out which row of BuiltinIndices to read from as well | |||
5312 | // as the number of fixed args. | |||
5313 | unsigned BuiltinID = FDecl->getBuiltinID(); | |||
5314 | unsigned BuiltinIndex, NumFixed = 1; | |||
5315 | bool WarnAboutSemanticsChange = false; | |||
5316 | switch (BuiltinID) { | |||
5317 | default: llvm_unreachable("Unknown overloaded atomic builtin!")::llvm::llvm_unreachable_internal("Unknown overloaded atomic builtin!" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 5317); | |||
5318 | case Builtin::BI__sync_fetch_and_add: | |||
5319 | case Builtin::BI__sync_fetch_and_add_1: | |||
5320 | case Builtin::BI__sync_fetch_and_add_2: | |||
5321 | case Builtin::BI__sync_fetch_and_add_4: | |||
5322 | case Builtin::BI__sync_fetch_and_add_8: | |||
5323 | case Builtin::BI__sync_fetch_and_add_16: | |||
5324 | BuiltinIndex = 0; | |||
5325 | break; | |||
5326 | ||||
5327 | case Builtin::BI__sync_fetch_and_sub: | |||
5328 | case Builtin::BI__sync_fetch_and_sub_1: | |||
5329 | case Builtin::BI__sync_fetch_and_sub_2: | |||
5330 | case Builtin::BI__sync_fetch_and_sub_4: | |||
5331 | case Builtin::BI__sync_fetch_and_sub_8: | |||
5332 | case Builtin::BI__sync_fetch_and_sub_16: | |||
5333 | BuiltinIndex = 1; | |||
5334 | break; | |||
5335 | ||||
5336 | case Builtin::BI__sync_fetch_and_or: | |||
5337 | case Builtin::BI__sync_fetch_and_or_1: | |||
5338 | case Builtin::BI__sync_fetch_and_or_2: | |||
5339 | case Builtin::BI__sync_fetch_and_or_4: | |||
5340 | case Builtin::BI__sync_fetch_and_or_8: | |||
5341 | case Builtin::BI__sync_fetch_and_or_16: | |||
5342 | BuiltinIndex = 2; | |||
5343 | break; | |||
5344 | ||||
5345 | case Builtin::BI__sync_fetch_and_and: | |||
5346 | case Builtin::BI__sync_fetch_and_and_1: | |||
5347 | case Builtin::BI__sync_fetch_and_and_2: | |||
5348 | case Builtin::BI__sync_fetch_and_and_4: | |||
5349 | case Builtin::BI__sync_fetch_and_and_8: | |||
5350 | case Builtin::BI__sync_fetch_and_and_16: | |||
5351 | BuiltinIndex = 3; | |||
5352 | break; | |||
5353 | ||||
5354 | case Builtin::BI__sync_fetch_and_xor: | |||
5355 | case Builtin::BI__sync_fetch_and_xor_1: | |||
5356 | case Builtin::BI__sync_fetch_and_xor_2: | |||
5357 | case Builtin::BI__sync_fetch_and_xor_4: | |||
5358 | case Builtin::BI__sync_fetch_and_xor_8: | |||
5359 | case Builtin::BI__sync_fetch_and_xor_16: | |||
5360 | BuiltinIndex = 4; | |||
5361 | break; | |||
5362 | ||||
5363 | case Builtin::BI__sync_fetch_and_nand: | |||
5364 | case Builtin::BI__sync_fetch_and_nand_1: | |||
5365 | case Builtin::BI__sync_fetch_and_nand_2: | |||
5366 | case Builtin::BI__sync_fetch_and_nand_4: | |||
5367 | case Builtin::BI__sync_fetch_and_nand_8: | |||
5368 | case Builtin::BI__sync_fetch_and_nand_16: | |||
5369 | BuiltinIndex = 5; | |||
5370 | WarnAboutSemanticsChange = true; | |||
5371 | break; | |||
5372 | ||||
5373 | case Builtin::BI__sync_add_and_fetch: | |||
5374 | case Builtin::BI__sync_add_and_fetch_1: | |||
5375 | case Builtin::BI__sync_add_and_fetch_2: | |||
5376 | case Builtin::BI__sync_add_and_fetch_4: | |||
5377 | case Builtin::BI__sync_add_and_fetch_8: | |||
5378 | case Builtin::BI__sync_add_and_fetch_16: | |||
5379 | BuiltinIndex = 6; | |||
5380 | break; | |||
5381 | ||||
5382 | case Builtin::BI__sync_sub_and_fetch: | |||
5383 | case Builtin::BI__sync_sub_and_fetch_1: | |||
5384 | case Builtin::BI__sync_sub_and_fetch_2: | |||
5385 | case Builtin::BI__sync_sub_and_fetch_4: | |||
5386 | case Builtin::BI__sync_sub_and_fetch_8: | |||
5387 | case Builtin::BI__sync_sub_and_fetch_16: | |||
5388 | BuiltinIndex = 7; | |||
5389 | break; | |||
5390 | ||||
5391 | case Builtin::BI__sync_and_and_fetch: | |||
5392 | case Builtin::BI__sync_and_and_fetch_1: | |||
5393 | case Builtin::BI__sync_and_and_fetch_2: | |||
5394 | case Builtin::BI__sync_and_and_fetch_4: | |||
5395 | case Builtin::BI__sync_and_and_fetch_8: | |||
5396 | case Builtin::BI__sync_and_and_fetch_16: | |||
5397 | BuiltinIndex = 8; | |||
5398 | break; | |||
5399 | ||||
5400 | case Builtin::BI__sync_or_and_fetch: | |||
5401 | case Builtin::BI__sync_or_and_fetch_1: | |||
5402 | case Builtin::BI__sync_or_and_fetch_2: | |||
5403 | case Builtin::BI__sync_or_and_fetch_4: | |||
5404 | case Builtin::BI__sync_or_and_fetch_8: | |||
5405 | case Builtin::BI__sync_or_and_fetch_16: | |||
5406 | BuiltinIndex = 9; | |||
5407 | break; | |||
5408 | ||||
5409 | case Builtin::BI__sync_xor_and_fetch: | |||
5410 | case Builtin::BI__sync_xor_and_fetch_1: | |||
5411 | case Builtin::BI__sync_xor_and_fetch_2: | |||
5412 | case Builtin::BI__sync_xor_and_fetch_4: | |||
5413 | case Builtin::BI__sync_xor_and_fetch_8: | |||
5414 | case Builtin::BI__sync_xor_and_fetch_16: | |||
5415 | BuiltinIndex = 10; | |||
5416 | break; | |||
5417 | ||||
5418 | case Builtin::BI__sync_nand_and_fetch: | |||
5419 | case Builtin::BI__sync_nand_and_fetch_1: | |||
5420 | case Builtin::BI__sync_nand_and_fetch_2: | |||
5421 | case Builtin::BI__sync_nand_and_fetch_4: | |||
5422 | case Builtin::BI__sync_nand_and_fetch_8: | |||
5423 | case Builtin::BI__sync_nand_and_fetch_16: | |||
5424 | BuiltinIndex = 11; | |||
5425 | WarnAboutSemanticsChange = true; | |||
5426 | break; | |||
5427 | ||||
5428 | case Builtin::BI__sync_val_compare_and_swap: | |||
5429 | case Builtin::BI__sync_val_compare_and_swap_1: | |||
5430 | case Builtin::BI__sync_val_compare_and_swap_2: | |||
5431 | case Builtin::BI__sync_val_compare_and_swap_4: | |||
5432 | case Builtin::BI__sync_val_compare_and_swap_8: | |||
5433 | case Builtin::BI__sync_val_compare_and_swap_16: | |||
5434 | BuiltinIndex = 12; | |||
5435 | NumFixed = 2; | |||
5436 | break; | |||
5437 | ||||
5438 | case Builtin::BI__sync_bool_compare_and_swap: | |||
5439 | case Builtin::BI__sync_bool_compare_and_swap_1: | |||
5440 | case Builtin::BI__sync_bool_compare_and_swap_2: | |||
5441 | case Builtin::BI__sync_bool_compare_and_swap_4: | |||
5442 | case Builtin::BI__sync_bool_compare_and_swap_8: | |||
5443 | case Builtin::BI__sync_bool_compare_and_swap_16: | |||
5444 | BuiltinIndex = 13; | |||
5445 | NumFixed = 2; | |||
5446 | ResultType = Context.BoolTy; | |||
5447 | break; | |||
5448 | ||||
5449 | case Builtin::BI__sync_lock_test_and_set: | |||
5450 | case Builtin::BI__sync_lock_test_and_set_1: | |||
5451 | case Builtin::BI__sync_lock_test_and_set_2: | |||
5452 | case Builtin::BI__sync_lock_test_and_set_4: | |||
5453 | case Builtin::BI__sync_lock_test_and_set_8: | |||
5454 | case Builtin::BI__sync_lock_test_and_set_16: | |||
5455 | BuiltinIndex = 14; | |||
5456 | break; | |||
5457 | ||||
5458 | case Builtin::BI__sync_lock_release: | |||
5459 | case Builtin::BI__sync_lock_release_1: | |||
5460 | case Builtin::BI__sync_lock_release_2: | |||
5461 | case Builtin::BI__sync_lock_release_4: | |||
5462 | case Builtin::BI__sync_lock_release_8: | |||
5463 | case Builtin::BI__sync_lock_release_16: | |||
5464 | BuiltinIndex = 15; | |||
5465 | NumFixed = 0; | |||
5466 | ResultType = Context.VoidTy; | |||
5467 | break; | |||
5468 | ||||
5469 | case Builtin::BI__sync_swap: | |||
5470 | case Builtin::BI__sync_swap_1: | |||
5471 | case Builtin::BI__sync_swap_2: | |||
5472 | case Builtin::BI__sync_swap_4: | |||
5473 | case Builtin::BI__sync_swap_8: | |||
5474 | case Builtin::BI__sync_swap_16: | |||
5475 | BuiltinIndex = 16; | |||
5476 | break; | |||
5477 | } | |||
5478 | ||||
5479 | // Now that we know how many fixed arguments we expect, first check that we | |||
5480 | // have at least that many. | |||
5481 | if (TheCall->getNumArgs() < 1+NumFixed) { | |||
5482 | Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) | |||
5483 | << 0 << 1 + NumFixed << TheCall->getNumArgs() | |||
5484 | << Callee->getSourceRange(); | |||
5485 | return ExprError(); | |||
5486 | } | |||
5487 | ||||
5488 | Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) | |||
5489 | << Callee->getSourceRange(); | |||
5490 | ||||
5491 | if (WarnAboutSemanticsChange) { | |||
5492 | Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) | |||
5493 | << Callee->getSourceRange(); | |||
5494 | } | |||
5495 | ||||
5496 | // Get the decl for the concrete builtin from this, we can tell what the | |||
5497 | // concrete integer type we should convert to is. | |||
5498 | unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; | |||
5499 | const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); | |||
5500 | FunctionDecl *NewBuiltinDecl; | |||
5501 | if (NewBuiltinID == BuiltinID) | |||
5502 | NewBuiltinDecl = FDecl; | |||
5503 | else { | |||
5504 | // Perform builtin lookup to avoid redeclaring it. | |||
5505 | DeclarationName DN(&Context.Idents.get(NewBuiltinName)); | |||
5506 | LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); | |||
5507 | LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); | |||
5508 | assert(Res.getFoundDecl())((Res.getFoundDecl()) ? static_cast<void> (0) : __assert_fail ("Res.getFoundDecl()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 5508, __PRETTY_FUNCTION__)); | |||
5509 | NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); | |||
5510 | if (!NewBuiltinDecl) | |||
5511 | return ExprError(); | |||
5512 | } | |||
5513 | ||||
5514 | // The first argument --- the pointer --- has a fixed type; we | |||
5515 | // deduce the types of the rest of the arguments accordingly. Walk | |||
5516 | // the remaining arguments, converting them to the deduced value type. | |||
5517 | for (unsigned i = 0; i != NumFixed; ++i) { | |||
5518 | ExprResult Arg = TheCall->getArg(i+1); | |||
5519 | ||||
5520 | // GCC does an implicit conversion to the pointer or integer ValType. This | |||
5521 | // can fail in some cases (1i -> int**), check for this error case now. | |||
5522 | // Initialize the argument. | |||
5523 | InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, | |||
5524 | ValType, /*consume*/ false); | |||
5525 | Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); | |||
5526 | if (Arg.isInvalid()) | |||
5527 | return ExprError(); | |||
5528 | ||||
5529 | // Okay, we have something that *can* be converted to the right type. Check | |||
5530 | // to see if there is a potentially weird extension going on here. This can | |||
5531 | // happen when you do an atomic operation on something like an char* and | |||
5532 | // pass in 42. The 42 gets converted to char. This is even more strange | |||
5533 | // for things like 45.123 -> char, etc. | |||
5534 | // FIXME: Do this check. | |||
5535 | TheCall->setArg(i+1, Arg.get()); | |||
5536 | } | |||
5537 | ||||
5538 | // Create a new DeclRefExpr to refer to the new decl. | |||
5539 | DeclRefExpr *NewDRE = DeclRefExpr::Create( | |||
5540 | Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, | |||
5541 | /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, | |||
5542 | DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); | |||
5543 | ||||
5544 | // Set the callee in the CallExpr. | |||
5545 | // FIXME: This loses syntactic information. | |||
5546 | QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); | |||
5547 | ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, | |||
5548 | CK_BuiltinFnToFnPtr); | |||
5549 | TheCall->setCallee(PromotedCall.get()); | |||
5550 | ||||
5551 | // Change the result type of the call to match the original value type. This | |||
5552 | // is arbitrary, but the codegen for these builtins ins design to handle it | |||
5553 | // gracefully. | |||
5554 | TheCall->setType(ResultType); | |||
5555 | ||||
5556 | // Prohibit use of _ExtInt with atomic builtins. | |||
5557 | // The arguments would have already been converted to the first argument's | |||
5558 | // type, so only need to check the first argument. | |||
5559 | const auto *ExtIntValType = ValType->getAs<ExtIntType>(); | |||
5560 | if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { | |||
5561 | Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); | |||
5562 | return ExprError(); | |||
5563 | } | |||
5564 | ||||
5565 | return TheCallResult; | |||
5566 | } | |||
5567 | ||||
5568 | /// SemaBuiltinNontemporalOverloaded - We have a call to | |||
5569 | /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an | |||
5570 | /// overloaded function based on the pointer type of its last argument. | |||
5571 | /// | |||
5572 | /// This function goes through and does final semantic checking for these | |||
5573 | /// builtins. | |||
5574 | ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { | |||
5575 | CallExpr *TheCall = (CallExpr *)TheCallResult.get(); | |||
5576 | DeclRefExpr *DRE = | |||
5577 | cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); | |||
5578 | FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); | |||
5579 | unsigned BuiltinID = FDecl->getBuiltinID(); | |||
5580 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 5582, __PRETTY_FUNCTION__)) | |||
5581 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 5582, __PRETTY_FUNCTION__)) | |||
5582 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 5582, __PRETTY_FUNCTION__)); | |||
5583 | bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; | |||
5584 | unsigned numArgs = isStore ? 2 : 1; | |||
5585 | ||||
5586 | // Ensure that we have the proper number of arguments. | |||
5587 | if (checkArgCount(*this, TheCall, numArgs)) | |||
5588 | return ExprError(); | |||
5589 | ||||
5590 | // Inspect the last argument of the nontemporal builtin. This should always | |||
5591 | // be a pointer type, from which we imply the type of the memory access. | |||
5592 | // Because it is a pointer type, we don't have to worry about any implicit | |||
5593 | // casts here. | |||
5594 | Expr *PointerArg = TheCall->getArg(numArgs - 1); | |||
5595 | ExprResult PointerArgResult = | |||
5596 | DefaultFunctionArrayLvalueConversion(PointerArg); | |||
5597 | ||||
5598 | if (PointerArgResult.isInvalid()) | |||
5599 | return ExprError(); | |||
5600 | PointerArg = PointerArgResult.get(); | |||
5601 | TheCall->setArg(numArgs - 1, PointerArg); | |||
5602 | ||||
5603 | const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); | |||
5604 | if (!pointerType) { | |||
5605 | Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) | |||
5606 | << PointerArg->getType() << PointerArg->getSourceRange(); | |||
5607 | return ExprError(); | |||
5608 | } | |||
5609 | ||||
5610 | QualType ValType = pointerType->getPointeeType(); | |||
5611 | ||||
5612 | // Strip any qualifiers off ValType. | |||
5613 | ValType = ValType.getUnqualifiedType(); | |||
5614 | if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && | |||
5615 | !ValType->isBlockPointerType() && !ValType->isFloatingType() && | |||
5616 | !ValType->isVectorType()) { | |||
5617 | Diag(DRE->getBeginLoc(), | |||
5618 | diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) | |||
5619 | << PointerArg->getType() << PointerArg->getSourceRange(); | |||
5620 | return ExprError(); | |||
5621 | } | |||
5622 | ||||
5623 | if (!isStore) { | |||
5624 | TheCall->setType(ValType); | |||
5625 | return TheCallResult; | |||
5626 | } | |||
5627 | ||||
5628 | ExprResult ValArg = TheCall->getArg(0); | |||
5629 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
5630 | Context, ValType, /*consume*/ false); | |||
5631 | ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); | |||
5632 | if (ValArg.isInvalid()) | |||
5633 | return ExprError(); | |||
5634 | ||||
5635 | TheCall->setArg(0, ValArg.get()); | |||
5636 | TheCall->setType(Context.VoidTy); | |||
5637 | return TheCallResult; | |||
5638 | } | |||
5639 | ||||
5640 | /// CheckObjCString - Checks that the argument to the builtin | |||
5641 | /// CFString constructor is correct | |||
5642 | /// Note: It might also make sense to do the UTF-16 conversion here (would | |||
5643 | /// simplify the backend). | |||
5644 | bool Sema::CheckObjCString(Expr *Arg) { | |||
5645 | Arg = Arg->IgnoreParenCasts(); | |||
5646 | StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); | |||
5647 | ||||
5648 | if (!Literal || !Literal->isAscii()) { | |||
5649 | Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) | |||
5650 | << Arg->getSourceRange(); | |||
5651 | return true; | |||
5652 | } | |||
5653 | ||||
5654 | if (Literal->containsNonAsciiOrNull()) { | |||
5655 | StringRef String = Literal->getString(); | |||
5656 | unsigned NumBytes = String.size(); | |||
5657 | SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); | |||
5658 | const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); | |||
5659 | llvm::UTF16 *ToPtr = &ToBuf[0]; | |||
5660 | ||||
5661 | llvm::ConversionResult Result = | |||
5662 | llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, | |||
5663 | ToPtr + NumBytes, llvm::strictConversion); | |||
5664 | // Check for conversion failure. | |||
5665 | if (Result != llvm::conversionOK) | |||
5666 | Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) | |||
5667 | << Arg->getSourceRange(); | |||
5668 | } | |||
5669 | return false; | |||
5670 | } | |||
5671 | ||||
5672 | /// CheckObjCString - Checks that the format string argument to the os_log() | |||
5673 | /// and os_trace() functions is correct, and converts it to const char *. | |||
5674 | ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { | |||
5675 | Arg = Arg->IgnoreParenCasts(); | |||
5676 | auto *Literal = dyn_cast<StringLiteral>(Arg); | |||
5677 | if (!Literal) { | |||
5678 | if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { | |||
5679 | Literal = ObjcLiteral->getString(); | |||
5680 | } | |||
5681 | } | |||
5682 | ||||
5683 | if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { | |||
5684 | return ExprError( | |||
5685 | Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) | |||
5686 | << Arg->getSourceRange()); | |||
5687 | } | |||
5688 | ||||
5689 | ExprResult Result(Literal); | |||
5690 | QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); | |||
5691 | InitializedEntity Entity = | |||
5692 | InitializedEntity::InitializeParameter(Context, ResultTy, false); | |||
5693 | Result = PerformCopyInitialization(Entity, SourceLocation(), Result); | |||
5694 | return Result; | |||
5695 | } | |||
5696 | ||||
5697 | /// Check that the user is calling the appropriate va_start builtin for the | |||
5698 | /// target and calling convention. | |||
5699 | static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { | |||
5700 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | |||
5701 | bool IsX64 = TT.getArch() == llvm::Triple::x86_64; | |||
5702 | bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || | |||
5703 | TT.getArch() == llvm::Triple::aarch64_32); | |||
5704 | bool IsWindows = TT.isOSWindows(); | |||
5705 | bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; | |||
5706 | if (IsX64 || IsAArch64) { | |||
5707 | CallingConv CC = CC_C; | |||
5708 | if (const FunctionDecl *FD = S.getCurFunctionDecl()) | |||
5709 | CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | |||
5710 | if (IsMSVAStart) { | |||
5711 | // Don't allow this in System V ABI functions. | |||
5712 | if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) | |||
5713 | return S.Diag(Fn->getBeginLoc(), | |||
5714 | diag::err_ms_va_start_used_in_sysv_function); | |||
5715 | } else { | |||
5716 | // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. | |||
5717 | // On x64 Windows, don't allow this in System V ABI functions. | |||
5718 | // (Yes, that means there's no corresponding way to support variadic | |||
5719 | // System V ABI functions on Windows.) | |||
5720 | if ((IsWindows && CC == CC_X86_64SysV) || | |||
5721 | (!IsWindows && CC == CC_Win64)) | |||
5722 | return S.Diag(Fn->getBeginLoc(), | |||
5723 | diag::err_va_start_used_in_wrong_abi_function) | |||
5724 | << !IsWindows; | |||
5725 | } | |||
5726 | return false; | |||
5727 | } | |||
5728 | ||||
5729 | if (IsMSVAStart) | |||
5730 | return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); | |||
5731 | return false; | |||
5732 | } | |||
5733 | ||||
5734 | static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, | |||
5735 | ParmVarDecl **LastParam = nullptr) { | |||
5736 | // Determine whether the current function, block, or obj-c method is variadic | |||
5737 | // and get its parameter list. | |||
5738 | bool IsVariadic = false; | |||
5739 | ArrayRef<ParmVarDecl *> Params; | |||
5740 | DeclContext *Caller = S.CurContext; | |||
5741 | if (auto *Block = dyn_cast<BlockDecl>(Caller)) { | |||
5742 | IsVariadic = Block->isVariadic(); | |||
5743 | Params = Block->parameters(); | |||
5744 | } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { | |||
5745 | IsVariadic = FD->isVariadic(); | |||
5746 | Params = FD->parameters(); | |||
5747 | } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { | |||
5748 | IsVariadic = MD->isVariadic(); | |||
5749 | // FIXME: This isn't correct for methods (results in bogus warning). | |||
5750 | Params = MD->parameters(); | |||
5751 | } else if (isa<CapturedDecl>(Caller)) { | |||
5752 | // We don't support va_start in a CapturedDecl. | |||
5753 | S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); | |||
5754 | return true; | |||
5755 | } else { | |||
5756 | // This must be some other declcontext that parses exprs. | |||
5757 | S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); | |||
5758 | return true; | |||
5759 | } | |||
5760 | ||||
5761 | if (!IsVariadic) { | |||
5762 | S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); | |||
5763 | return true; | |||
5764 | } | |||
5765 | ||||
5766 | if (LastParam) | |||
5767 | *LastParam = Params.empty() ? nullptr : Params.back(); | |||
5768 | ||||
5769 | return false; | |||
5770 | } | |||
5771 | ||||
5772 | /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' | |||
5773 | /// for validity. Emit an error and return true on failure; return false | |||
5774 | /// on success. | |||
5775 | bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { | |||
5776 | Expr *Fn = TheCall->getCallee(); | |||
5777 | ||||
5778 | if (checkVAStartABI(*this, BuiltinID, Fn)) | |||
5779 | return true; | |||
5780 | ||||
5781 | if (checkArgCount(*this, TheCall, 2)) | |||
5782 | return true; | |||
5783 | ||||
5784 | // Type-check the first argument normally. | |||
5785 | if (checkBuiltinArgument(*this, TheCall, 0)) | |||
5786 | return true; | |||
5787 | ||||
5788 | // Check that the current function is variadic, and get its last parameter. | |||
5789 | ParmVarDecl *LastParam; | |||
5790 | if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) | |||
5791 | return true; | |||
5792 | ||||
5793 | // Verify that the second argument to the builtin is the last argument of the | |||
5794 | // current function or method. | |||
5795 | bool SecondArgIsLastNamedArgument = false; | |||
5796 | const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); | |||
5797 | ||||
5798 | // These are valid if SecondArgIsLastNamedArgument is false after the next | |||
5799 | // block. | |||
5800 | QualType Type; | |||
5801 | SourceLocation ParamLoc; | |||
5802 | bool IsCRegister = false; | |||
5803 | ||||
5804 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { | |||
5805 | if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { | |||
5806 | SecondArgIsLastNamedArgument = PV == LastParam; | |||
5807 | ||||
5808 | Type = PV->getType(); | |||
5809 | ParamLoc = PV->getLocation(); | |||
5810 | IsCRegister = | |||
5811 | PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; | |||
5812 | } | |||
5813 | } | |||
5814 | ||||
5815 | if (!SecondArgIsLastNamedArgument) | |||
5816 | Diag(TheCall->getArg(1)->getBeginLoc(), | |||
5817 | diag::warn_second_arg_of_va_start_not_last_named_param); | |||
5818 | else if (IsCRegister || Type->isReferenceType() || | |||
5819 | Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { | |||
5820 | // Promotable integers are UB, but enumerations need a bit of | |||
5821 | // extra checking to see what their promotable type actually is. | |||
5822 | if (!Type->isPromotableIntegerType()) | |||
5823 | return false; | |||
5824 | if (!Type->isEnumeralType()) | |||
5825 | return true; | |||
5826 | const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); | |||
5827 | return !(ED && | |||
5828 | Context.typesAreCompatible(ED->getPromotionType(), Type)); | |||
5829 | }()) { | |||
5830 | unsigned Reason = 0; | |||
5831 | if (Type->isReferenceType()) Reason = 1; | |||
5832 | else if (IsCRegister) Reason = 2; | |||
5833 | Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; | |||
5834 | Diag(ParamLoc, diag::note_parameter_type) << Type; | |||
5835 | } | |||
5836 | ||||
5837 | TheCall->setType(Context.VoidTy); | |||
5838 | return false; | |||
5839 | } | |||
5840 | ||||
5841 | bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { | |||
5842 | // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, | |||
5843 | // const char *named_addr); | |||
5844 | ||||
5845 | Expr *Func = Call->getCallee(); | |||
5846 | ||||
5847 | if (Call->getNumArgs() < 3) | |||
5848 | return Diag(Call->getEndLoc(), | |||
5849 | diag::err_typecheck_call_too_few_args_at_least) | |||
5850 | << 0 /*function call*/ << 3 << Call->getNumArgs(); | |||
5851 | ||||
5852 | // Type-check the first argument normally. | |||
5853 | if (checkBuiltinArgument(*this, Call, 0)) | |||
5854 | return true; | |||
5855 | ||||
5856 | // Check that the current function is variadic. | |||
5857 | if (checkVAStartIsInVariadicFunction(*this, Func)) | |||
5858 | return true; | |||
5859 | ||||
5860 | // __va_start on Windows does not validate the parameter qualifiers | |||
5861 | ||||
5862 | const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); | |||
5863 | const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); | |||
5864 | ||||
5865 | const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); | |||
5866 | const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); | |||
5867 | ||||
5868 | const QualType &ConstCharPtrTy = | |||
5869 | Context.getPointerType(Context.CharTy.withConst()); | |||
5870 | if (!Arg1Ty->isPointerType() || | |||
5871 | Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) | |||
5872 | Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) | |||
5873 | << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ | |||
5874 | << 0 /* qualifier difference */ | |||
5875 | << 3 /* parameter mismatch */ | |||
5876 | << 2 << Arg1->getType() << ConstCharPtrTy; | |||
5877 | ||||
5878 | const QualType SizeTy = Context.getSizeType(); | |||
5879 | if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) | |||
5880 | Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) | |||
5881 | << Arg2->getType() << SizeTy << 1 /* different class */ | |||
5882 | << 0 /* qualifier difference */ | |||
5883 | << 3 /* parameter mismatch */ | |||
5884 | << 3 << Arg2->getType() << SizeTy; | |||
5885 | ||||
5886 | return false; | |||
5887 | } | |||
5888 | ||||
5889 | /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and | |||
5890 | /// friends. This is declared to take (...), so we have to check everything. | |||
5891 | bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { | |||
5892 | if (checkArgCount(*this, TheCall, 2)) | |||
5893 | return true; | |||
5894 | ||||
5895 | ExprResult OrigArg0 = TheCall->getArg(0); | |||
5896 | ExprResult OrigArg1 = TheCall->getArg(1); | |||
5897 | ||||
5898 | // Do standard promotions between the two arguments, returning their common | |||
5899 | // type. | |||
5900 | QualType Res = UsualArithmeticConversions( | |||
5901 | OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); | |||
5902 | if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) | |||
5903 | return true; | |||
5904 | ||||
5905 | // Make sure any conversions are pushed back into the call; this is | |||
5906 | // type safe since unordered compare builtins are declared as "_Bool | |||
5907 | // foo(...)". | |||
5908 | TheCall->setArg(0, OrigArg0.get()); | |||
5909 | TheCall->setArg(1, OrigArg1.get()); | |||
5910 | ||||
5911 | if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) | |||
5912 | return false; | |||
5913 | ||||
5914 | // If the common type isn't a real floating type, then the arguments were | |||
5915 | // invalid for this operation. | |||
5916 | if (Res.isNull() || !Res->isRealFloatingType()) | |||
5917 | return Diag(OrigArg0.get()->getBeginLoc(), | |||
5918 | diag::err_typecheck_call_invalid_ordered_compare) | |||
5919 | << OrigArg0.get()->getType() << OrigArg1.get()->getType() | |||
5920 | << SourceRange(OrigArg0.get()->getBeginLoc(), | |||
5921 | OrigArg1.get()->getEndLoc()); | |||
5922 | ||||
5923 | return false; | |||
5924 | } | |||
5925 | ||||
5926 | /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like | |||
5927 | /// __builtin_isnan and friends. This is declared to take (...), so we have | |||
5928 | /// to check everything. We expect the last argument to be a floating point | |||
5929 | /// value. | |||
5930 | bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { | |||
5931 | if (checkArgCount(*this, TheCall, NumArgs)) | |||
5932 | return true; | |||
5933 | ||||
5934 | // __builtin_fpclassify is the only case where NumArgs != 1, so we can count | |||
5935 | // on all preceding parameters just being int. Try all of those. | |||
5936 | for (unsigned i = 0; i < NumArgs - 1; ++i) { | |||
5937 | Expr *Arg = TheCall->getArg(i); | |||
5938 | ||||
5939 | if (Arg->isTypeDependent()) | |||
5940 | return false; | |||
5941 | ||||
5942 | ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); | |||
5943 | ||||
5944 | if (Res.isInvalid()) | |||
5945 | return true; | |||
5946 | TheCall->setArg(i, Res.get()); | |||
5947 | } | |||
5948 | ||||
5949 | Expr *OrigArg = TheCall->getArg(NumArgs-1); | |||
5950 | ||||
5951 | if (OrigArg->isTypeDependent()) | |||
5952 | return false; | |||
5953 | ||||
5954 | // Usual Unary Conversions will convert half to float, which we want for | |||
5955 | // machines that use fp16 conversion intrinsics. Else, we wnat to leave the | |||
5956 | // type how it is, but do normal L->Rvalue conversions. | |||
5957 | if (Context.getTargetInfo().useFP16ConversionIntrinsics()) | |||
5958 | OrigArg = UsualUnaryConversions(OrigArg).get(); | |||
5959 | else | |||
5960 | OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); | |||
5961 | TheCall->setArg(NumArgs - 1, OrigArg); | |||
5962 | ||||
5963 | // This operation requires a non-_Complex floating-point number. | |||
5964 | if (!OrigArg->getType()->isRealFloatingType()) | |||
5965 | return Diag(OrigArg->getBeginLoc(), | |||
5966 | diag::err_typecheck_call_invalid_unary_fp) | |||
5967 | << OrigArg->getType() << OrigArg->getSourceRange(); | |||
5968 | ||||
5969 | return false; | |||
5970 | } | |||
5971 | ||||
5972 | /// Perform semantic analysis for a call to __builtin_complex. | |||
5973 | bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { | |||
5974 | if (checkArgCount(*this, TheCall, 2)) | |||
5975 | return true; | |||
5976 | ||||
5977 | bool Dependent = false; | |||
5978 | for (unsigned I = 0; I != 2; ++I) { | |||
5979 | Expr *Arg = TheCall->getArg(I); | |||
5980 | QualType T = Arg->getType(); | |||
5981 | if (T->isDependentType()) { | |||
5982 | Dependent = true; | |||
5983 | continue; | |||
5984 | } | |||
5985 | ||||
5986 | // Despite supporting _Complex int, GCC requires a real floating point type | |||
5987 | // for the operands of __builtin_complex. | |||
5988 | if (!T->isRealFloatingType()) { | |||
5989 | return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) | |||
5990 | << Arg->getType() << Arg->getSourceRange(); | |||
5991 | } | |||
5992 | ||||
5993 | ExprResult Converted = DefaultLvalueConversion(Arg); | |||
5994 | if (Converted.isInvalid()) | |||
5995 | return true; | |||
5996 | TheCall->setArg(I, Converted.get()); | |||
5997 | } | |||
5998 | ||||
5999 | if (Dependent) { | |||
6000 | TheCall->setType(Context.DependentTy); | |||
6001 | return false; | |||
6002 | } | |||
6003 | ||||
6004 | Expr *Real = TheCall->getArg(0); | |||
6005 | Expr *Imag = TheCall->getArg(1); | |||
6006 | if (!Context.hasSameType(Real->getType(), Imag->getType())) { | |||
6007 | return Diag(Real->getBeginLoc(), | |||
6008 | diag::err_typecheck_call_different_arg_types) | |||
6009 | << Real->getType() << Imag->getType() | |||
6010 | << Real->getSourceRange() << Imag->getSourceRange(); | |||
6011 | } | |||
6012 | ||||
6013 | // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; | |||
6014 | // don't allow this builtin to form those types either. | |||
6015 | // FIXME: Should we allow these types? | |||
6016 | if (Real->getType()->isFloat16Type()) | |||
6017 | return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) | |||
6018 | << "_Float16"; | |||
6019 | if (Real->getType()->isHalfType()) | |||
6020 | return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) | |||
6021 | << "half"; | |||
6022 | ||||
6023 | TheCall->setType(Context.getComplexType(Real->getType())); | |||
6024 | return false; | |||
6025 | } | |||
6026 | ||||
6027 | // Customized Sema Checking for VSX builtins that have the following signature: | |||
6028 | // vector [...] builtinName(vector [...], vector [...], const int); | |||
6029 | // Which takes the same type of vectors (any legal vector type) for the first | |||
6030 | // two arguments and takes compile time constant for the third argument. | |||
6031 | // Example builtins are : | |||
6032 | // vector double vec_xxpermdi(vector double, vector double, int); | |||
6033 | // vector short vec_xxsldwi(vector short, vector short, int); | |||
6034 | bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { | |||
6035 | unsigned ExpectedNumArgs = 3; | |||
6036 | if (checkArgCount(*this, TheCall, ExpectedNumArgs)) | |||
6037 | return true; | |||
6038 | ||||
6039 | // Check the third argument is a compile time constant | |||
6040 | if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) | |||
6041 | return Diag(TheCall->getBeginLoc(), | |||
6042 | diag::err_vsx_builtin_nonconstant_argument) | |||
6043 | << 3 /* argument index */ << TheCall->getDirectCallee() | |||
6044 | << SourceRange(TheCall->getArg(2)->getBeginLoc(), | |||
6045 | TheCall->getArg(2)->getEndLoc()); | |||
6046 | ||||
6047 | QualType Arg1Ty = TheCall->getArg(0)->getType(); | |||
6048 | QualType Arg2Ty = TheCall->getArg(1)->getType(); | |||
6049 | ||||
6050 | // Check the type of argument 1 and argument 2 are vectors. | |||
6051 | SourceLocation BuiltinLoc = TheCall->getBeginLoc(); | |||
6052 | if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || | |||
6053 | (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { | |||
6054 | return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) | |||
6055 | << TheCall->getDirectCallee() | |||
6056 | << SourceRange(TheCall->getArg(0)->getBeginLoc(), | |||
6057 | TheCall->getArg(1)->getEndLoc()); | |||
6058 | } | |||
6059 | ||||
6060 | // Check the first two arguments are the same type. | |||
6061 | if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { | |||
6062 | return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) | |||
6063 | << TheCall->getDirectCallee() | |||
6064 | << SourceRange(TheCall->getArg(0)->getBeginLoc(), | |||
6065 | TheCall->getArg(1)->getEndLoc()); | |||
6066 | } | |||
6067 | ||||
6068 | // When default clang type checking is turned off and the customized type | |||
6069 | // checking is used, the returning type of the function must be explicitly | |||
6070 | // set. Otherwise it is _Bool by default. | |||
6071 | TheCall->setType(Arg1Ty); | |||
6072 | ||||
6073 | return false; | |||
6074 | } | |||
6075 | ||||
6076 | /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. | |||
6077 | // This is declared to take (...), so we have to check everything. | |||
6078 | ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { | |||
6079 | if (TheCall->getNumArgs() < 2) | |||
6080 | return ExprError(Diag(TheCall->getEndLoc(), | |||
6081 | diag::err_typecheck_call_too_few_args_at_least) | |||
6082 | << 0 /*function call*/ << 2 << TheCall->getNumArgs() | |||
6083 | << TheCall->getSourceRange()); | |||
6084 | ||||
6085 | // Determine which of the following types of shufflevector we're checking: | |||
6086 | // 1) unary, vector mask: (lhs, mask) | |||
6087 | // 2) binary, scalar mask: (lhs, rhs, index, ..., index) | |||
6088 | QualType resType = TheCall->getArg(0)->getType(); | |||
6089 | unsigned numElements = 0; | |||
6090 | ||||
6091 | if (!TheCall->getArg(0)->isTypeDependent() && | |||
6092 | !TheCall->getArg(1)->isTypeDependent()) { | |||
6093 | QualType LHSType = TheCall->getArg(0)->getType(); | |||
6094 | QualType RHSType = TheCall->getArg(1)->getType(); | |||
6095 | ||||
6096 | if (!LHSType->isVectorType() || !RHSType->isVectorType()) | |||
6097 | return ExprError( | |||
6098 | Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) | |||
6099 | << TheCall->getDirectCallee() | |||
6100 | << SourceRange(TheCall->getArg(0)->getBeginLoc(), | |||
6101 | TheCall->getArg(1)->getEndLoc())); | |||
6102 | ||||
6103 | numElements = LHSType->castAs<VectorType>()->getNumElements(); | |||
6104 | unsigned numResElements = TheCall->getNumArgs() - 2; | |||
6105 | ||||
6106 | // Check to see if we have a call with 2 vector arguments, the unary shuffle | |||
6107 | // with mask. If so, verify that RHS is an integer vector type with the | |||
6108 | // same number of elts as lhs. | |||
6109 | if (TheCall->getNumArgs() == 2) { | |||
6110 | if (!RHSType->hasIntegerRepresentation() || | |||
6111 | RHSType->castAs<VectorType>()->getNumElements() != numElements) | |||
6112 | return ExprError(Diag(TheCall->getBeginLoc(), | |||
6113 | diag::err_vec_builtin_incompatible_vector) | |||
6114 | << TheCall->getDirectCallee() | |||
6115 | << SourceRange(TheCall->getArg(1)->getBeginLoc(), | |||
6116 | TheCall->getArg(1)->getEndLoc())); | |||
6117 | } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { | |||
6118 | return ExprError(Diag(TheCall->getBeginLoc(), | |||
6119 | diag::err_vec_builtin_incompatible_vector) | |||
6120 | << TheCall->getDirectCallee() | |||
6121 | << SourceRange(TheCall->getArg(0)->getBeginLoc(), | |||
6122 | TheCall->getArg(1)->getEndLoc())); | |||
6123 | } else if (numElements != numResElements) { | |||
6124 | QualType eltType = LHSType->castAs<VectorType>()->getElementType(); | |||
6125 | resType = Context.getVectorType(eltType, numResElements, | |||
6126 | VectorType::GenericVector); | |||
6127 | } | |||
6128 | } | |||
6129 | ||||
6130 | for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { | |||
6131 | if (TheCall->getArg(i)->isTypeDependent() || | |||
6132 | TheCall->getArg(i)->isValueDependent()) | |||
6133 | continue; | |||
6134 | ||||
6135 | Optional<llvm::APSInt> Result; | |||
6136 | if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) | |||
6137 | return ExprError(Diag(TheCall->getBeginLoc(), | |||
6138 | diag::err_shufflevector_nonconstant_argument) | |||
6139 | << TheCall->getArg(i)->getSourceRange()); | |||
6140 | ||||
6141 | // Allow -1 which will be translated to undef in the IR. | |||
6142 | if (Result->isSigned() && Result->isAllOnesValue()) | |||
6143 | continue; | |||
6144 | ||||
6145 | if (Result->getActiveBits() > 64 || | |||
6146 | Result->getZExtValue() >= numElements * 2) | |||
6147 | return ExprError(Diag(TheCall->getBeginLoc(), | |||
6148 | diag::err_shufflevector_argument_too_large) | |||
6149 | << TheCall->getArg(i)->getSourceRange()); | |||
6150 | } | |||
6151 | ||||
6152 | SmallVector<Expr*, 32> exprs; | |||
6153 | ||||
6154 | for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { | |||
6155 | exprs.push_back(TheCall->getArg(i)); | |||
6156 | TheCall->setArg(i, nullptr); | |||
6157 | } | |||
6158 | ||||
6159 | return new (Context) ShuffleVectorExpr(Context, exprs, resType, | |||
6160 | TheCall->getCallee()->getBeginLoc(), | |||
6161 | TheCall->getRParenLoc()); | |||
6162 | } | |||
6163 | ||||
6164 | /// SemaConvertVectorExpr - Handle __builtin_convertvector | |||
6165 | ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, | |||
6166 | SourceLocation BuiltinLoc, | |||
6167 | SourceLocation RParenLoc) { | |||
6168 | ExprValueKind VK = VK_RValue; | |||
6169 | ExprObjectKind OK = OK_Ordinary; | |||
6170 | QualType DstTy = TInfo->getType(); | |||
6171 | QualType SrcTy = E->getType(); | |||
6172 | ||||
6173 | if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) | |||
6174 | return ExprError(Diag(BuiltinLoc, | |||
6175 | diag::err_convertvector_non_vector) | |||
6176 | << E->getSourceRange()); | |||
6177 | if (!DstTy->isVectorType() && !DstTy->isDependentType()) | |||
6178 | return ExprError(Diag(BuiltinLoc, | |||
6179 | diag::err_convertvector_non_vector_type)); | |||
6180 | ||||
6181 | if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { | |||
6182 | unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); | |||
6183 | unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); | |||
6184 | if (SrcElts != DstElts) | |||
6185 | return ExprError(Diag(BuiltinLoc, | |||
6186 | diag::err_convertvector_incompatible_vector) | |||
6187 | << E->getSourceRange()); | |||
6188 | } | |||
6189 | ||||
6190 | return new (Context) | |||
6191 | ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); | |||
6192 | } | |||
6193 | ||||
6194 | /// SemaBuiltinPrefetch - Handle __builtin_prefetch. | |||
6195 | // This is declared to take (const void*, ...) and can take two | |||
6196 | // optional constant int args. | |||
6197 | bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { | |||
6198 | unsigned NumArgs = TheCall->getNumArgs(); | |||
6199 | ||||
6200 | if (NumArgs > 3) | |||
6201 | return Diag(TheCall->getEndLoc(), | |||
6202 | diag::err_typecheck_call_too_many_args_at_most) | |||
6203 | << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); | |||
6204 | ||||
6205 | // Argument 0 is checked for us and the remaining arguments must be | |||
6206 | // constant integers. | |||
6207 | for (unsigned i = 1; i != NumArgs; ++i) | |||
6208 | if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) | |||
6209 | return true; | |||
6210 | ||||
6211 | return false; | |||
6212 | } | |||
6213 | ||||
6214 | /// SemaBuiltinAssume - Handle __assume (MS Extension). | |||
6215 | // __assume does not evaluate its arguments, and should warn if its argument | |||
6216 | // has side effects. | |||
6217 | bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { | |||
6218 | Expr *Arg = TheCall->getArg(0); | |||
6219 | if (Arg->isInstantiationDependent()) return false; | |||
6220 | ||||
6221 | if (Arg->HasSideEffects(Context)) | |||
6222 | Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) | |||
6223 | << Arg->getSourceRange() | |||
6224 | << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); | |||
6225 | ||||
6226 | return false; | |||
6227 | } | |||
6228 | ||||
6229 | /// Handle __builtin_alloca_with_align. This is declared | |||
6230 | /// as (size_t, size_t) where the second size_t must be a power of 2 greater | |||
6231 | /// than 8. | |||
6232 | bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { | |||
6233 | // The alignment must be a constant integer. | |||
6234 | Expr *Arg = TheCall->getArg(1); | |||
6235 | ||||
6236 | // We can't check the value of a dependent argument. | |||
6237 | if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { | |||
6238 | if (const auto *UE = | |||
6239 | dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) | |||
6240 | if (UE->getKind() == UETT_AlignOf || | |||
6241 | UE->getKind() == UETT_PreferredAlignOf) | |||
6242 | Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) | |||
6243 | << Arg->getSourceRange(); | |||
6244 | ||||
6245 | llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); | |||
6246 | ||||
6247 | if (!Result.isPowerOf2()) | |||
6248 | return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) | |||
6249 | << Arg->getSourceRange(); | |||
6250 | ||||
6251 | if (Result < Context.getCharWidth()) | |||
6252 | return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) | |||
6253 | << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); | |||
6254 | ||||
6255 | if (Result > std::numeric_limits<int32_t>::max()) | |||
6256 | return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) | |||
6257 | << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); | |||
6258 | } | |||
6259 | ||||
6260 | return false; | |||
6261 | } | |||
6262 | ||||
6263 | /// Handle __builtin_assume_aligned. This is declared | |||
6264 | /// as (const void*, size_t, ...) and can take one optional constant int arg. | |||
6265 | bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { | |||
6266 | unsigned NumArgs = TheCall->getNumArgs(); | |||
6267 | ||||
6268 | if (NumArgs > 3) | |||
6269 | return Diag(TheCall->getEndLoc(), | |||
6270 | diag::err_typecheck_call_too_many_args_at_most) | |||
6271 | << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); | |||
6272 | ||||
6273 | // The alignment must be a constant integer. | |||
6274 | Expr *Arg = TheCall->getArg(1); | |||
6275 | ||||
6276 | // We can't check the value of a dependent argument. | |||
6277 | if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { | |||
6278 | llvm::APSInt Result; | |||
6279 | if (SemaBuiltinConstantArg(TheCall, 1, Result)) | |||
6280 | return true; | |||
6281 | ||||
6282 | if (!Result.isPowerOf2()) | |||
6283 | return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) | |||
6284 | << Arg->getSourceRange(); | |||
6285 | ||||
6286 | if (Result > Sema::MaximumAlignment) | |||
6287 | Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) | |||
6288 | << Arg->getSourceRange() << Sema::MaximumAlignment; | |||
6289 | } | |||
6290 | ||||
6291 | if (NumArgs > 2) { | |||
6292 | ExprResult Arg(TheCall->getArg(2)); | |||
6293 | InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, | |||
6294 | Context.getSizeType(), false); | |||
6295 | Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); | |||
6296 | if (Arg.isInvalid()) return true; | |||
6297 | TheCall->setArg(2, Arg.get()); | |||
6298 | } | |||
6299 | ||||
6300 | return false; | |||
6301 | } | |||
6302 | ||||
6303 | bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { | |||
6304 | unsigned BuiltinID = | |||
6305 | cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); | |||
6306 | bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; | |||
6307 | ||||
6308 | unsigned NumArgs = TheCall->getNumArgs(); | |||
6309 | unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; | |||
6310 | if (NumArgs < NumRequiredArgs) { | |||
6311 | return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) | |||
6312 | << 0 /* function call */ << NumRequiredArgs << NumArgs | |||
6313 | << TheCall->getSourceRange(); | |||
6314 | } | |||
6315 | if (NumArgs >= NumRequiredArgs + 0x100) { | |||
6316 | return Diag(TheCall->getEndLoc(), | |||
6317 | diag::err_typecheck_call_too_many_args_at_most) | |||
6318 | << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs | |||
6319 | << TheCall->getSourceRange(); | |||
6320 | } | |||
6321 | unsigned i = 0; | |||
6322 | ||||
6323 | // For formatting call, check buffer arg. | |||
6324 | if (!IsSizeCall) { | |||
6325 | ExprResult Arg(TheCall->getArg(i)); | |||
6326 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
6327 | Context, Context.VoidPtrTy, false); | |||
6328 | Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); | |||
6329 | if (Arg.isInvalid()) | |||
6330 | return true; | |||
6331 | TheCall->setArg(i, Arg.get()); | |||
6332 | i++; | |||
6333 | } | |||
6334 | ||||
6335 | // Check string literal arg. | |||
6336 | unsigned FormatIdx = i; | |||
6337 | { | |||
6338 | ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); | |||
6339 | if (Arg.isInvalid()) | |||
6340 | return true; | |||
6341 | TheCall->setArg(i, Arg.get()); | |||
6342 | i++; | |||
6343 | } | |||
6344 | ||||
6345 | // Make sure variadic args are scalar. | |||
6346 | unsigned FirstDataArg = i; | |||
6347 | while (i < NumArgs) { | |||
6348 | ExprResult Arg = DefaultVariadicArgumentPromotion( | |||
6349 | TheCall->getArg(i), VariadicFunction, nullptr); | |||
6350 | if (Arg.isInvalid()) | |||
6351 | return true; | |||
6352 | CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); | |||
6353 | if (ArgSize.getQuantity() >= 0x100) { | |||
6354 | return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) | |||
6355 | << i << (int)ArgSize.getQuantity() << 0xff | |||
6356 | << TheCall->getSourceRange(); | |||
6357 | } | |||
6358 | TheCall->setArg(i, Arg.get()); | |||
6359 | i++; | |||
6360 | } | |||
6361 | ||||
6362 | // Check formatting specifiers. NOTE: We're only doing this for the non-size | |||
6363 | // call to avoid duplicate diagnostics. | |||
6364 | if (!IsSizeCall) { | |||
6365 | llvm::SmallBitVector CheckedVarArgs(NumArgs, false); | |||
6366 | ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); | |||
6367 | bool Success = CheckFormatArguments( | |||
6368 | Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, | |||
6369 | VariadicFunction, TheCall->getBeginLoc(), SourceRange(), | |||
6370 | CheckedVarArgs); | |||
6371 | if (!Success) | |||
6372 | return true; | |||
6373 | } | |||
6374 | ||||
6375 | if (IsSizeCall) { | |||
6376 | TheCall->setType(Context.getSizeType()); | |||
6377 | } else { | |||
6378 | TheCall->setType(Context.VoidPtrTy); | |||
6379 | } | |||
6380 | return false; | |||
6381 | } | |||
6382 | ||||
6383 | /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr | |||
6384 | /// TheCall is a constant expression. | |||
6385 | bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, | |||
6386 | llvm::APSInt &Result) { | |||
6387 | Expr *Arg = TheCall->getArg(ArgNum); | |||
6388 | DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); | |||
6389 | FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); | |||
6390 | ||||
6391 | if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; | |||
6392 | ||||
6393 | Optional<llvm::APSInt> R; | |||
6394 | if (!(R = Arg->getIntegerConstantExpr(Context))) | |||
6395 | return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) | |||
6396 | << FDecl->getDeclName() << Arg->getSourceRange(); | |||
6397 | Result = *R; | |||
6398 | return false; | |||
6399 | } | |||
6400 | ||||
6401 | /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr | |||
6402 | /// TheCall is a constant expression in the range [Low, High]. | |||
6403 | bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, | |||
6404 | int Low, int High, bool RangeIsError) { | |||
6405 | if (isConstantEvaluated()) | |||
6406 | return false; | |||
6407 | llvm::APSInt Result; | |||
6408 | ||||
6409 | // We can't check the value of a dependent argument. | |||
6410 | Expr *Arg = TheCall->getArg(ArgNum); | |||
6411 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
6412 | return false; | |||
6413 | ||||
6414 | // Check constant-ness first. | |||
6415 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
6416 | return true; | |||
6417 | ||||
6418 | if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { | |||
6419 | if (RangeIsError) | |||
6420 | return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) | |||
6421 | << Result.toString(10) << Low << High << Arg->getSourceRange(); | |||
6422 | else | |||
6423 | // Defer the warning until we know if the code will be emitted so that | |||
6424 | // dead code can ignore this. | |||
6425 | DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, | |||
6426 | PDiag(diag::warn_argument_invalid_range) | |||
6427 | << Result.toString(10) << Low << High | |||
6428 | << Arg->getSourceRange()); | |||
6429 | } | |||
6430 | ||||
6431 | return false; | |||
6432 | } | |||
6433 | ||||
6434 | /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr | |||
6435 | /// TheCall is a constant expression is a multiple of Num.. | |||
6436 | bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, | |||
6437 | unsigned Num) { | |||
6438 | llvm::APSInt Result; | |||
6439 | ||||
6440 | // We can't check the value of a dependent argument. | |||
6441 | Expr *Arg = TheCall->getArg(ArgNum); | |||
6442 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
6443 | return false; | |||
6444 | ||||
6445 | // Check constant-ness first. | |||
6446 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
6447 | return true; | |||
6448 | ||||
6449 | if (Result.getSExtValue() % Num != 0) | |||
6450 | return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) | |||
6451 | << Num << Arg->getSourceRange(); | |||
6452 | ||||
6453 | return false; | |||
6454 | } | |||
6455 | ||||
6456 | /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a | |||
6457 | /// constant expression representing a power of 2. | |||
6458 | bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { | |||
6459 | llvm::APSInt Result; | |||
6460 | ||||
6461 | // We can't check the value of a dependent argument. | |||
6462 | Expr *Arg = TheCall->getArg(ArgNum); | |||
6463 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
6464 | return false; | |||
6465 | ||||
6466 | // Check constant-ness first. | |||
6467 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
6468 | return true; | |||
6469 | ||||
6470 | // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if | |||
6471 | // and only if x is a power of 2. | |||
6472 | if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) | |||
6473 | return false; | |||
6474 | ||||
6475 | return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) | |||
6476 | << Arg->getSourceRange(); | |||
6477 | } | |||
6478 | ||||
6479 | static bool IsShiftedByte(llvm::APSInt Value) { | |||
6480 | if (Value.isNegative()) | |||
6481 | return false; | |||
6482 | ||||
6483 | // Check if it's a shifted byte, by shifting it down | |||
6484 | while (true) { | |||
6485 | // If the value fits in the bottom byte, the check passes. | |||
6486 | if (Value < 0x100) | |||
6487 | return true; | |||
6488 | ||||
6489 | // Otherwise, if the value has _any_ bits in the bottom byte, the check | |||
6490 | // fails. | |||
6491 | if ((Value & 0xFF) != 0) | |||
6492 | return false; | |||
6493 | ||||
6494 | // If the bottom 8 bits are all 0, but something above that is nonzero, | |||
6495 | // then shifting the value right by 8 bits won't affect whether it's a | |||
6496 | // shifted byte or not. So do that, and go round again. | |||
6497 | Value >>= 8; | |||
6498 | } | |||
6499 | } | |||
6500 | ||||
6501 | /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is | |||
6502 | /// a constant expression representing an arbitrary byte value shifted left by | |||
6503 | /// a multiple of 8 bits. | |||
6504 | bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, | |||
6505 | unsigned ArgBits) { | |||
6506 | llvm::APSInt Result; | |||
6507 | ||||
6508 | // We can't check the value of a dependent argument. | |||
6509 | Expr *Arg = TheCall->getArg(ArgNum); | |||
6510 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
6511 | return false; | |||
6512 | ||||
6513 | // Check constant-ness first. | |||
6514 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
6515 | return true; | |||
6516 | ||||
6517 | // Truncate to the given size. | |||
6518 | Result = Result.getLoBits(ArgBits); | |||
6519 | Result.setIsUnsigned(true); | |||
6520 | ||||
6521 | if (IsShiftedByte(Result)) | |||
6522 | return false; | |||
6523 | ||||
6524 | return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) | |||
6525 | << Arg->getSourceRange(); | |||
6526 | } | |||
6527 | ||||
6528 | /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of | |||
6529 | /// TheCall is a constant expression representing either a shifted byte value, | |||
6530 | /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression | |||
6531 | /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some | |||
6532 | /// Arm MVE intrinsics. | |||
6533 | bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, | |||
6534 | int ArgNum, | |||
6535 | unsigned ArgBits) { | |||
6536 | llvm::APSInt Result; | |||
6537 | ||||
6538 | // We can't check the value of a dependent argument. | |||
6539 | Expr *Arg = TheCall->getArg(ArgNum); | |||
6540 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
6541 | return false; | |||
6542 | ||||
6543 | // Check constant-ness first. | |||
6544 | if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) | |||
6545 | return true; | |||
6546 | ||||
6547 | // Truncate to the given size. | |||
6548 | Result = Result.getLoBits(ArgBits); | |||
6549 | Result.setIsUnsigned(true); | |||
6550 | ||||
6551 | // Check to see if it's in either of the required forms. | |||
6552 | if (IsShiftedByte(Result) || | |||
6553 | (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) | |||
6554 | return false; | |||
6555 | ||||
6556 | return Diag(TheCall->getBeginLoc(), | |||
6557 | diag::err_argument_not_shifted_byte_or_xxff) | |||
6558 | << Arg->getSourceRange(); | |||
6559 | } | |||
6560 | ||||
6561 | /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions | |||
6562 | bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { | |||
6563 | if (BuiltinID == AArch64::BI__builtin_arm_irg) { | |||
6564 | if (checkArgCount(*this, TheCall, 2)) | |||
6565 | return true; | |||
6566 | Expr *Arg0 = TheCall->getArg(0); | |||
6567 | Expr *Arg1 = TheCall->getArg(1); | |||
6568 | ||||
6569 | ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); | |||
6570 | if (FirstArg.isInvalid()) | |||
6571 | return true; | |||
6572 | QualType FirstArgType = FirstArg.get()->getType(); | |||
6573 | if (!FirstArgType->isAnyPointerType()) | |||
6574 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) | |||
6575 | << "first" << FirstArgType << Arg0->getSourceRange(); | |||
6576 | TheCall->setArg(0, FirstArg.get()); | |||
6577 | ||||
6578 | ExprResult SecArg = DefaultLvalueConversion(Arg1); | |||
6579 | if (SecArg.isInvalid()) | |||
6580 | return true; | |||
6581 | QualType SecArgType = SecArg.get()->getType(); | |||
6582 | if (!SecArgType->isIntegerType()) | |||
6583 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) | |||
6584 | << "second" << SecArgType << Arg1->getSourceRange(); | |||
6585 | ||||
6586 | // Derive the return type from the pointer argument. | |||
6587 | TheCall->setType(FirstArgType); | |||
6588 | return false; | |||
6589 | } | |||
6590 | ||||
6591 | if (BuiltinID == AArch64::BI__builtin_arm_addg) { | |||
6592 | if (checkArgCount(*this, TheCall, 2)) | |||
6593 | return true; | |||
6594 | ||||
6595 | Expr *Arg0 = TheCall->getArg(0); | |||
6596 | ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); | |||
6597 | if (FirstArg.isInvalid()) | |||
6598 | return true; | |||
6599 | QualType FirstArgType = FirstArg.get()->getType(); | |||
6600 | if (!FirstArgType->isAnyPointerType()) | |||
6601 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) | |||
6602 | << "first" << FirstArgType << Arg0->getSourceRange(); | |||
6603 | TheCall->setArg(0, FirstArg.get()); | |||
6604 | ||||
6605 | // Derive the return type from the pointer argument. | |||
6606 | TheCall->setType(FirstArgType); | |||
6607 | ||||
6608 | // Second arg must be an constant in range [0,15] | |||
6609 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); | |||
6610 | } | |||
6611 | ||||
6612 | if (BuiltinID == AArch64::BI__builtin_arm_gmi) { | |||
6613 | if (checkArgCount(*this, TheCall, 2)) | |||
6614 | return true; | |||
6615 | Expr *Arg0 = TheCall->getArg(0); | |||
6616 | Expr *Arg1 = TheCall->getArg(1); | |||
6617 | ||||
6618 | ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); | |||
6619 | if (FirstArg.isInvalid()) | |||
6620 | return true; | |||
6621 | QualType FirstArgType = FirstArg.get()->getType(); | |||
6622 | if (!FirstArgType->isAnyPointerType()) | |||
6623 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) | |||
6624 | << "first" << FirstArgType << Arg0->getSourceRange(); | |||
6625 | ||||
6626 | QualType SecArgType = Arg1->getType(); | |||
6627 | if (!SecArgType->isIntegerType()) | |||
6628 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) | |||
6629 | << "second" << SecArgType << Arg1->getSourceRange(); | |||
6630 | TheCall->setType(Context.IntTy); | |||
6631 | return false; | |||
6632 | } | |||
6633 | ||||
6634 | if (BuiltinID == AArch64::BI__builtin_arm_ldg || | |||
6635 | BuiltinID == AArch64::BI__builtin_arm_stg) { | |||
6636 | if (checkArgCount(*this, TheCall, 1)) | |||
6637 | return true; | |||
6638 | Expr *Arg0 = TheCall->getArg(0); | |||
6639 | ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); | |||
6640 | if (FirstArg.isInvalid()) | |||
6641 | return true; | |||
6642 | ||||
6643 | QualType FirstArgType = FirstArg.get()->getType(); | |||
6644 | if (!FirstArgType->isAnyPointerType()) | |||
6645 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) | |||
6646 | << "first" << FirstArgType << Arg0->getSourceRange(); | |||
6647 | TheCall->setArg(0, FirstArg.get()); | |||
6648 | ||||
6649 | // Derive the return type from the pointer argument. | |||
6650 | if (BuiltinID == AArch64::BI__builtin_arm_ldg) | |||
6651 | TheCall->setType(FirstArgType); | |||
6652 | return false; | |||
6653 | } | |||
6654 | ||||
6655 | if (BuiltinID == AArch64::BI__builtin_arm_subp) { | |||
6656 | Expr *ArgA = TheCall->getArg(0); | |||
6657 | Expr *ArgB = TheCall->getArg(1); | |||
6658 | ||||
6659 | ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); | |||
6660 | ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); | |||
6661 | ||||
6662 | if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) | |||
6663 | return true; | |||
6664 | ||||
6665 | QualType ArgTypeA = ArgExprA.get()->getType(); | |||
6666 | QualType ArgTypeB = ArgExprB.get()->getType(); | |||
6667 | ||||
6668 | auto isNull = [&] (Expr *E) -> bool { | |||
6669 | return E->isNullPointerConstant( | |||
6670 | Context, Expr::NPC_ValueDependentIsNotNull); }; | |||
6671 | ||||
6672 | // argument should be either a pointer or null | |||
6673 | if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) | |||
6674 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) | |||
6675 | << "first" << ArgTypeA << ArgA->getSourceRange(); | |||
6676 | ||||
6677 | if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) | |||
6678 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) | |||
6679 | << "second" << ArgTypeB << ArgB->getSourceRange(); | |||
6680 | ||||
6681 | // Ensure Pointee types are compatible | |||
6682 | if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && | |||
6683 | ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { | |||
6684 | QualType pointeeA = ArgTypeA->getPointeeType(); | |||
6685 | QualType pointeeB = ArgTypeB->getPointeeType(); | |||
6686 | if (!Context.typesAreCompatible( | |||
6687 | Context.getCanonicalType(pointeeA).getUnqualifiedType(), | |||
6688 | Context.getCanonicalType(pointeeB).getUnqualifiedType())) { | |||
6689 | return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) | |||
6690 | << ArgTypeA << ArgTypeB << ArgA->getSourceRange() | |||
6691 | << ArgB->getSourceRange(); | |||
6692 | } | |||
6693 | } | |||
6694 | ||||
6695 | // at least one argument should be pointer type | |||
6696 | if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) | |||
6697 | return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) | |||
6698 | << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); | |||
6699 | ||||
6700 | if (isNull(ArgA)) // adopt type of the other pointer | |||
6701 | ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); | |||
6702 | ||||
6703 | if (isNull(ArgB)) | |||
6704 | ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); | |||
6705 | ||||
6706 | TheCall->setArg(0, ArgExprA.get()); | |||
6707 | TheCall->setArg(1, ArgExprB.get()); | |||
6708 | TheCall->setType(Context.LongLongTy); | |||
6709 | return false; | |||
6710 | } | |||
6711 | assert(false && "Unhandled ARM MTE intrinsic")((false && "Unhandled ARM MTE intrinsic") ? static_cast <void> (0) : __assert_fail ("false && \"Unhandled ARM MTE intrinsic\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6711, __PRETTY_FUNCTION__)); | |||
6712 | return true; | |||
6713 | } | |||
6714 | ||||
6715 | /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr | |||
6716 | /// TheCall is an ARM/AArch64 special register string literal. | |||
6717 | bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, | |||
6718 | int ArgNum, unsigned ExpectedFieldNum, | |||
6719 | bool AllowName) { | |||
6720 | bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || | |||
6721 | BuiltinID == ARM::BI__builtin_arm_wsr64 || | |||
6722 | BuiltinID == ARM::BI__builtin_arm_rsr || | |||
6723 | BuiltinID == ARM::BI__builtin_arm_rsrp || | |||
6724 | BuiltinID == ARM::BI__builtin_arm_wsr || | |||
6725 | BuiltinID == ARM::BI__builtin_arm_wsrp; | |||
6726 | bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || | |||
6727 | BuiltinID == AArch64::BI__builtin_arm_wsr64 || | |||
6728 | BuiltinID == AArch64::BI__builtin_arm_rsr || | |||
6729 | BuiltinID == AArch64::BI__builtin_arm_rsrp || | |||
6730 | BuiltinID == AArch64::BI__builtin_arm_wsr || | |||
6731 | BuiltinID == AArch64::BI__builtin_arm_wsrp; | |||
6732 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6732, __PRETTY_FUNCTION__)); | |||
6733 | ||||
6734 | // We can't check the value of a dependent argument. | |||
6735 | Expr *Arg = TheCall->getArg(ArgNum); | |||
6736 | if (Arg->isTypeDependent() || Arg->isValueDependent()) | |||
6737 | return false; | |||
6738 | ||||
6739 | // Check if the argument is a string literal. | |||
6740 | if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) | |||
6741 | return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) | |||
6742 | << Arg->getSourceRange(); | |||
6743 | ||||
6744 | // Check the type of special register given. | |||
6745 | StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); | |||
6746 | SmallVector<StringRef, 6> Fields; | |||
6747 | Reg.split(Fields, ":"); | |||
6748 | ||||
6749 | if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) | |||
6750 | return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) | |||
6751 | << Arg->getSourceRange(); | |||
6752 | ||||
6753 | // If the string is the name of a register then we cannot check that it is | |||
6754 | // valid here but if the string is of one the forms described in ACLE then we | |||
6755 | // can check that the supplied fields are integers and within the valid | |||
6756 | // ranges. | |||
6757 | if (Fields.size() > 1) { | |||
6758 | bool FiveFields = Fields.size() == 5; | |||
6759 | ||||
6760 | bool ValidString = true; | |||
6761 | if (IsARMBuiltin) { | |||
6762 | ValidString &= Fields[0].startswith_lower("cp") || | |||
6763 | Fields[0].startswith_lower("p"); | |||
6764 | if (ValidString) | |||
6765 | Fields[0] = | |||
6766 | Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); | |||
6767 | ||||
6768 | ValidString &= Fields[2].startswith_lower("c"); | |||
6769 | if (ValidString) | |||
6770 | Fields[2] = Fields[2].drop_front(1); | |||
6771 | ||||
6772 | if (FiveFields) { | |||
6773 | ValidString &= Fields[3].startswith_lower("c"); | |||
6774 | if (ValidString) | |||
6775 | Fields[3] = Fields[3].drop_front(1); | |||
6776 | } | |||
6777 | } | |||
6778 | ||||
6779 | SmallVector<int, 5> Ranges; | |||
6780 | if (FiveFields) | |||
6781 | Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); | |||
6782 | else | |||
6783 | Ranges.append({15, 7, 15}); | |||
6784 | ||||
6785 | for (unsigned i=0; i<Fields.size(); ++i) { | |||
6786 | int IntField; | |||
6787 | ValidString &= !Fields[i].getAsInteger(10, IntField); | |||
6788 | ValidString &= (IntField >= 0 && IntField <= Ranges[i]); | |||
6789 | } | |||
6790 | ||||
6791 | if (!ValidString) | |||
6792 | return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) | |||
6793 | << Arg->getSourceRange(); | |||
6794 | } else if (IsAArch64Builtin && Fields.size() == 1) { | |||
6795 | // If the register name is one of those that appear in the condition below | |||
6796 | // and the special register builtin being used is one of the write builtins, | |||
6797 | // then we require that the argument provided for writing to the register | |||
6798 | // is an integer constant expression. This is because it will be lowered to | |||
6799 | // an MSR (immediate) instruction, so we need to know the immediate at | |||
6800 | // compile time. | |||
6801 | if (TheCall->getNumArgs() != 2) | |||
6802 | return false; | |||
6803 | ||||
6804 | std::string RegLower = Reg.lower(); | |||
6805 | if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && | |||
6806 | RegLower != "pan" && RegLower != "uao") | |||
6807 | return false; | |||
6808 | ||||
6809 | return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); | |||
6810 | } | |||
6811 | ||||
6812 | return false; | |||
6813 | } | |||
6814 | ||||
6815 | /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. | |||
6816 | /// Emit an error and return true on failure; return false on success. | |||
6817 | /// TypeStr is a string containing the type descriptor of the value returned by | |||
6818 | /// the builtin and the descriptors of the expected type of the arguments. | |||
6819 | bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { | |||
6820 | ||||
6821 | assert((TypeStr[0] != '\0') &&(((TypeStr[0] != '\0') && "Invalid types in PPC MMA builtin declaration" ) ? static_cast<void> (0) : __assert_fail ("(TypeStr[0] != '\\0') && \"Invalid types in PPC MMA builtin declaration\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6822, __PRETTY_FUNCTION__)) | |||
6822 | "Invalid types in PPC MMA builtin declaration")(((TypeStr[0] != '\0') && "Invalid types in PPC MMA builtin declaration" ) ? static_cast<void> (0) : __assert_fail ("(TypeStr[0] != '\\0') && \"Invalid types in PPC MMA builtin declaration\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6822, __PRETTY_FUNCTION__)); | |||
6823 | ||||
6824 | unsigned Mask = 0; | |||
6825 | unsigned ArgNum = 0; | |||
6826 | ||||
6827 | // The first type in TypeStr is the type of the value returned by the | |||
6828 | // builtin. So we first read that type and change the type of TheCall. | |||
6829 | QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); | |||
6830 | TheCall->setType(type); | |||
6831 | ||||
6832 | while (*TypeStr != '\0') { | |||
6833 | Mask = 0; | |||
6834 | QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); | |||
6835 | if (ArgNum >= TheCall->getNumArgs()) { | |||
6836 | ArgNum++; | |||
6837 | break; | |||
6838 | } | |||
6839 | ||||
6840 | Expr *Arg = TheCall->getArg(ArgNum); | |||
6841 | QualType ArgType = Arg->getType(); | |||
6842 | ||||
6843 | if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || | |||
6844 | (!ExpectedType->isVoidPointerType() && | |||
6845 | ArgType.getCanonicalType() != ExpectedType)) | |||
6846 | return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) | |||
6847 | << ArgType << ExpectedType << 1 << 0 << 0; | |||
6848 | ||||
6849 | // If the value of the Mask is not 0, we have a constraint in the size of | |||
6850 | // the integer argument so here we ensure the argument is a constant that | |||
6851 | // is in the valid range. | |||
6852 | if (Mask != 0 && | |||
6853 | SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) | |||
6854 | return true; | |||
6855 | ||||
6856 | ArgNum++; | |||
6857 | } | |||
6858 | ||||
6859 | // In case we exited early from the previous loop, there are other types to | |||
6860 | // read from TypeStr. So we need to read them all to ensure we have the right | |||
6861 | // number of arguments in TheCall and if it is not the case, to display a | |||
6862 | // better error message. | |||
6863 | while (*TypeStr != '\0') { | |||
6864 | (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); | |||
6865 | ArgNum++; | |||
6866 | } | |||
6867 | if (checkArgCount(*this, TheCall, ArgNum)) | |||
6868 | return true; | |||
6869 | ||||
6870 | return false; | |||
6871 | } | |||
6872 | ||||
6873 | /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). | |||
6874 | /// This checks that the target supports __builtin_longjmp and | |||
6875 | /// that val is a constant 1. | |||
6876 | bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { | |||
6877 | if (!Context.getTargetInfo().hasSjLjLowering()) | |||
6878 | return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) | |||
6879 | << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); | |||
6880 | ||||
6881 | Expr *Arg = TheCall->getArg(1); | |||
6882 | llvm::APSInt Result; | |||
6883 | ||||
6884 | // TODO: This is less than ideal. Overload this to take a value. | |||
6885 | if (SemaBuiltinConstantArg(TheCall, 1, Result)) | |||
6886 | return true; | |||
6887 | ||||
6888 | if (Result != 1) | |||
6889 | return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) | |||
6890 | << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); | |||
6891 | ||||
6892 | return false; | |||
6893 | } | |||
6894 | ||||
6895 | /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). | |||
6896 | /// This checks that the target supports __builtin_setjmp. | |||
6897 | bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { | |||
6898 | if (!Context.getTargetInfo().hasSjLjLowering()) | |||
6899 | return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) | |||
6900 | << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); | |||
6901 | return false; | |||
6902 | } | |||
6903 | ||||
6904 | namespace { | |||
6905 | ||||
6906 | class UncoveredArgHandler { | |||
6907 | enum { Unknown = -1, AllCovered = -2 }; | |||
6908 | ||||
6909 | signed FirstUncoveredArg = Unknown; | |||
6910 | SmallVector<const Expr *, 4> DiagnosticExprs; | |||
6911 | ||||
6912 | public: | |||
6913 | UncoveredArgHandler() = default; | |||
6914 | ||||
6915 | bool hasUncoveredArg() const { | |||
6916 | return (FirstUncoveredArg >= 0); | |||
6917 | } | |||
6918 | ||||
6919 | unsigned getUncoveredArg() const { | |||
6920 | assert(hasUncoveredArg() && "no uncovered argument")((hasUncoveredArg() && "no uncovered argument") ? static_cast <void> (0) : __assert_fail ("hasUncoveredArg() && \"no uncovered argument\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6920, __PRETTY_FUNCTION__)); | |||
6921 | return FirstUncoveredArg; | |||
6922 | } | |||
6923 | ||||
6924 | void setAllCovered() { | |||
6925 | // A string has been found with all arguments covered, so clear out | |||
6926 | // the diagnostics. | |||
6927 | DiagnosticExprs.clear(); | |||
6928 | FirstUncoveredArg = AllCovered; | |||
6929 | } | |||
6930 | ||||
6931 | void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { | |||
6932 | assert(NewFirstUncoveredArg >= 0 && "Outside range")((NewFirstUncoveredArg >= 0 && "Outside range") ? static_cast <void> (0) : __assert_fail ("NewFirstUncoveredArg >= 0 && \"Outside range\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6932, __PRETTY_FUNCTION__)); | |||
6933 | ||||
6934 | // Don't update if a previous string covers all arguments. | |||
6935 | if (FirstUncoveredArg == AllCovered) | |||
6936 | return; | |||
6937 | ||||
6938 | // UncoveredArgHandler tracks the highest uncovered argument index | |||
6939 | // and with it all the strings that match this index. | |||
6940 | if (NewFirstUncoveredArg == FirstUncoveredArg) | |||
6941 | DiagnosticExprs.push_back(StrExpr); | |||
6942 | else if (NewFirstUncoveredArg > FirstUncoveredArg) { | |||
6943 | DiagnosticExprs.clear(); | |||
6944 | DiagnosticExprs.push_back(StrExpr); | |||
6945 | FirstUncoveredArg = NewFirstUncoveredArg; | |||
6946 | } | |||
6947 | } | |||
6948 | ||||
6949 | void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); | |||
6950 | }; | |||
6951 | ||||
6952 | enum StringLiteralCheckType { | |||
6953 | SLCT_NotALiteral, | |||
6954 | SLCT_UncheckedLiteral, | |||
6955 | SLCT_CheckedLiteral | |||
6956 | }; | |||
6957 | ||||
6958 | } // namespace | |||
6959 | ||||
6960 | static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, | |||
6961 | BinaryOperatorKind BinOpKind, | |||
6962 | bool AddendIsRight) { | |||
6963 | unsigned BitWidth = Offset.getBitWidth(); | |||
6964 | unsigned AddendBitWidth = Addend.getBitWidth(); | |||
6965 | // There might be negative interim results. | |||
6966 | if (Addend.isUnsigned()) { | |||
6967 | Addend = Addend.zext(++AddendBitWidth); | |||
6968 | Addend.setIsSigned(true); | |||
6969 | } | |||
6970 | // Adjust the bit width of the APSInts. | |||
6971 | if (AddendBitWidth > BitWidth) { | |||
6972 | Offset = Offset.sext(AddendBitWidth); | |||
6973 | BitWidth = AddendBitWidth; | |||
6974 | } else if (BitWidth > AddendBitWidth) { | |||
6975 | Addend = Addend.sext(BitWidth); | |||
6976 | } | |||
6977 | ||||
6978 | bool Ov = false; | |||
6979 | llvm::APSInt ResOffset = Offset; | |||
6980 | if (BinOpKind == BO_Add) | |||
6981 | ResOffset = Offset.sadd_ov(Addend, Ov); | |||
6982 | else { | |||
6983 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6984, __PRETTY_FUNCTION__)) | |||
6984 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6984, __PRETTY_FUNCTION__)); | |||
6985 | ResOffset = Offset.ssub_ov(Addend, Ov); | |||
6986 | } | |||
6987 | ||||
6988 | // We add an offset to a pointer here so we should support an offset as big as | |||
6989 | // possible. | |||
6990 | if (Ov) { | |||
6991 | assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&((BitWidth <= std::numeric_limits<unsigned>::max() / 2 && "index (intermediate) result too big") ? static_cast <void> (0) : __assert_fail ("BitWidth <= std::numeric_limits<unsigned>::max() / 2 && \"index (intermediate) result too big\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6992, __PRETTY_FUNCTION__)) | |||
6992 | "index (intermediate) result too big")((BitWidth <= std::numeric_limits<unsigned>::max() / 2 && "index (intermediate) result too big") ? static_cast <void> (0) : __assert_fail ("BitWidth <= std::numeric_limits<unsigned>::max() / 2 && \"index (intermediate) result too big\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 6992, __PRETTY_FUNCTION__)); | |||
6993 | Offset = Offset.sext(2 * BitWidth); | |||
6994 | sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); | |||
6995 | return; | |||
6996 | } | |||
6997 | ||||
6998 | Offset = ResOffset; | |||
6999 | } | |||
7000 | ||||
7001 | namespace { | |||
7002 | ||||
7003 | // This is a wrapper class around StringLiteral to support offsetted string | |||
7004 | // literals as format strings. It takes the offset into account when returning | |||
7005 | // the string and its length or the source locations to display notes correctly. | |||
7006 | class FormatStringLiteral { | |||
7007 | const StringLiteral *FExpr; | |||
7008 | int64_t Offset; | |||
7009 | ||||
7010 | public: | |||
7011 | FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) | |||
7012 | : FExpr(fexpr), Offset(Offset) {} | |||
7013 | ||||
7014 | StringRef getString() const { | |||
7015 | return FExpr->getString().drop_front(Offset); | |||
7016 | } | |||
7017 | ||||
7018 | unsigned getByteLength() const { | |||
7019 | return FExpr->getByteLength() - getCharByteWidth() * Offset; | |||
7020 | } | |||
7021 | ||||
7022 | unsigned getLength() const { return FExpr->getLength() - Offset; } | |||
7023 | unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } | |||
7024 | ||||
7025 | StringLiteral::StringKind getKind() const { return FExpr->getKind(); } | |||
7026 | ||||
7027 | QualType getType() const { return FExpr->getType(); } | |||
7028 | ||||
7029 | bool isAscii() const { return FExpr->isAscii(); } | |||
7030 | bool isWide() const { return FExpr->isWide(); } | |||
7031 | bool isUTF8() const { return FExpr->isUTF8(); } | |||
7032 | bool isUTF16() const { return FExpr->isUTF16(); } | |||
7033 | bool isUTF32() const { return FExpr->isUTF32(); } | |||
7034 | bool isPascal() const { return FExpr->isPascal(); } | |||
7035 | ||||
7036 | SourceLocation getLocationOfByte( | |||
7037 | unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, | |||
7038 | const TargetInfo &Target, unsigned *StartToken = nullptr, | |||
7039 | unsigned *StartTokenByteOffset = nullptr) const { | |||
7040 | return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, | |||
7041 | StartToken, StartTokenByteOffset); | |||
7042 | } | |||
7043 | ||||
7044 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { | |||
7045 | return FExpr->getBeginLoc().getLocWithOffset(Offset); | |||
7046 | } | |||
7047 | ||||
7048 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return FExpr->getEndLoc(); } | |||
7049 | }; | |||
7050 | ||||
7051 | } // namespace | |||
7052 | ||||
7053 | static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, | |||
7054 | const Expr *OrigFormatExpr, | |||
7055 | ArrayRef<const Expr *> Args, | |||
7056 | bool HasVAListArg, unsigned format_idx, | |||
7057 | unsigned firstDataArg, | |||
7058 | Sema::FormatStringType Type, | |||
7059 | bool inFunctionCall, | |||
7060 | Sema::VariadicCallType CallType, | |||
7061 | llvm::SmallBitVector &CheckedVarArgs, | |||
7062 | UncoveredArgHandler &UncoveredArg, | |||
7063 | bool IgnoreStringsWithoutSpecifiers); | |||
7064 | ||||
7065 | // Determine if an expression is a string literal or constant string. | |||
7066 | // If this function returns false on the arguments to a function expecting a | |||
7067 | // format string, we will usually need to emit a warning. | |||
7068 | // True string literals are then checked by CheckFormatString. | |||
7069 | static StringLiteralCheckType | |||
7070 | checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, | |||
7071 | bool HasVAListArg, unsigned format_idx, | |||
7072 | unsigned firstDataArg, Sema::FormatStringType Type, | |||
7073 | Sema::VariadicCallType CallType, bool InFunctionCall, | |||
7074 | llvm::SmallBitVector &CheckedVarArgs, | |||
7075 | UncoveredArgHandler &UncoveredArg, | |||
7076 | llvm::APSInt Offset, | |||
7077 | bool IgnoreStringsWithoutSpecifiers = false) { | |||
7078 | if (S.isConstantEvaluated()) | |||
7079 | return SLCT_NotALiteral; | |||
7080 | tryAgain: | |||
7081 | assert(Offset.isSigned() && "invalid offset")((Offset.isSigned() && "invalid offset") ? static_cast <void> (0) : __assert_fail ("Offset.isSigned() && \"invalid offset\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 7081, __PRETTY_FUNCTION__)); | |||
7082 | ||||
7083 | if (E->isTypeDependent() || E->isValueDependent()) | |||
7084 | return SLCT_NotALiteral; | |||
7085 | ||||
7086 | E = E->IgnoreParenCasts(); | |||
7087 | ||||
7088 | if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) | |||
7089 | // Technically -Wformat-nonliteral does not warn about this case. | |||
7090 | // The behavior of printf and friends in this case is implementation | |||
7091 | // dependent. Ideally if the format string cannot be null then | |||
7092 | // it should have a 'nonnull' attribute in the function prototype. | |||
7093 | return SLCT_UncheckedLiteral; | |||
7094 | ||||
7095 | switch (E->getStmtClass()) { | |||
7096 | case Stmt::BinaryConditionalOperatorClass: | |||
7097 | case Stmt::ConditionalOperatorClass: { | |||
7098 | // The expression is a literal if both sub-expressions were, and it was | |||
7099 | // completely checked only if both sub-expressions were checked. | |||
7100 | const AbstractConditionalOperator *C = | |||
7101 | cast<AbstractConditionalOperator>(E); | |||
7102 | ||||
7103 | // Determine whether it is necessary to check both sub-expressions, for | |||
7104 | // example, because the condition expression is a constant that can be | |||
7105 | // evaluated at compile time. | |||
7106 | bool CheckLeft = true, CheckRight = true; | |||
7107 | ||||
7108 | bool Cond; | |||
7109 | if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), | |||
7110 | S.isConstantEvaluated())) { | |||
7111 | if (Cond) | |||
7112 | CheckRight = false; | |||
7113 | else | |||
7114 | CheckLeft = false; | |||
7115 | } | |||
7116 | ||||
7117 | // We need to maintain the offsets for the right and the left hand side | |||
7118 | // separately to check if every possible indexed expression is a valid | |||
7119 | // string literal. They might have different offsets for different string | |||
7120 | // literals in the end. | |||
7121 | StringLiteralCheckType Left; | |||
7122 | if (!CheckLeft) | |||
7123 | Left = SLCT_UncheckedLiteral; | |||
7124 | else { | |||
7125 | Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, | |||
7126 | HasVAListArg, format_idx, firstDataArg, | |||
7127 | Type, CallType, InFunctionCall, | |||
7128 | CheckedVarArgs, UncoveredArg, Offset, | |||
7129 | IgnoreStringsWithoutSpecifiers); | |||
7130 | if (Left == SLCT_NotALiteral || !CheckRight) { | |||
7131 | return Left; | |||
7132 | } | |||
7133 | } | |||
7134 | ||||
7135 | StringLiteralCheckType Right = checkFormatStringExpr( | |||
7136 | S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, | |||
7137 | Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, | |||
7138 | IgnoreStringsWithoutSpecifiers); | |||
7139 | ||||
7140 | return (CheckLeft && Left < Right) ? Left : Right; | |||
7141 | } | |||
7142 | ||||
7143 | case Stmt::ImplicitCastExprClass: | |||
7144 | E = cast<ImplicitCastExpr>(E)->getSubExpr(); | |||
7145 | goto tryAgain; | |||
7146 | ||||
7147 | case Stmt::OpaqueValueExprClass: | |||
7148 | if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { | |||
7149 | E = src; | |||
7150 | goto tryAgain; | |||
7151 | } | |||
7152 | return SLCT_NotALiteral; | |||
7153 | ||||
7154 | case Stmt::PredefinedExprClass: | |||
7155 | // While __func__, etc., are technically not string literals, they | |||
7156 | // cannot contain format specifiers and thus are not a security | |||
7157 | // liability. | |||
7158 | return SLCT_UncheckedLiteral; | |||
7159 | ||||
7160 | case Stmt::DeclRefExprClass: { | |||
7161 | const DeclRefExpr *DR = cast<DeclRefExpr>(E); | |||
7162 | ||||
7163 | // As an exception, do not flag errors for variables binding to | |||
7164 | // const string literals. | |||
7165 | if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { | |||
7166 | bool isConstant = false; | |||
7167 | QualType T = DR->getType(); | |||
7168 | ||||
7169 | if (const ArrayType *AT = S.Context.getAsArrayType(T)) { | |||
7170 | isConstant = AT->getElementType().isConstant(S.Context); | |||
7171 | } else if (const PointerType *PT = T->getAs<PointerType>()) { | |||
7172 | isConstant = T.isConstant(S.Context) && | |||
7173 | PT->getPointeeType().isConstant(S.Context); | |||
7174 | } else if (T->isObjCObjectPointerType()) { | |||
7175 | // In ObjC, there is usually no "const ObjectPointer" type, | |||
7176 | // so don't check if the pointee type is constant. | |||
7177 | isConstant = T.isConstant(S.Context); | |||
7178 | } | |||
7179 | ||||
7180 | if (isConstant) { | |||
7181 | if (const Expr *Init = VD->getAnyInitializer()) { | |||
7182 | // Look through initializers like const char c[] = { "foo" } | |||
7183 | if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { | |||
7184 | if (InitList->isStringLiteralInit()) | |||
7185 | Init = InitList->getInit(0)->IgnoreParenImpCasts(); | |||
7186 | } | |||
7187 | return checkFormatStringExpr(S, Init, Args, | |||
7188 | HasVAListArg, format_idx, | |||
7189 | firstDataArg, Type, CallType, | |||
7190 | /*InFunctionCall*/ false, CheckedVarArgs, | |||
7191 | UncoveredArg, Offset); | |||
7192 | } | |||
7193 | } | |||
7194 | ||||
7195 | // For vprintf* functions (i.e., HasVAListArg==true), we add a | |||
7196 | // special check to see if the format string is a function parameter | |||
7197 | // of the function calling the printf function. If the function | |||
7198 | // has an attribute indicating it is a printf-like function, then we | |||
7199 | // should suppress warnings concerning non-literals being used in a call | |||
7200 | // to a vprintf function. For example: | |||
7201 | // | |||
7202 | // void | |||
7203 | // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ | |||
7204 | // va_list ap; | |||
7205 | // va_start(ap, fmt); | |||
7206 | // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". | |||
7207 | // ... | |||
7208 | // } | |||
7209 | if (HasVAListArg) { | |||
7210 | if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { | |||
7211 | if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { | |||
7212 | int PVIndex = PV->getFunctionScopeIndex() + 1; | |||
7213 | for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { | |||
7214 | // adjust for implicit parameter | |||
7215 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) | |||
7216 | if (MD->isInstance()) | |||
7217 | ++PVIndex; | |||
7218 | // We also check if the formats are compatible. | |||
7219 | // We can't pass a 'scanf' string to a 'printf' function. | |||
7220 | if (PVIndex == PVFormat->getFormatIdx() && | |||
7221 | Type == S.GetFormatStringType(PVFormat)) | |||
7222 | return SLCT_UncheckedLiteral; | |||
7223 | } | |||
7224 | } | |||
7225 | } | |||
7226 | } | |||
7227 | } | |||
7228 | ||||
7229 | return SLCT_NotALiteral; | |||
7230 | } | |||
7231 | ||||
7232 | case Stmt::CallExprClass: | |||
7233 | case Stmt::CXXMemberCallExprClass: { | |||
7234 | const CallExpr *CE = cast<CallExpr>(E); | |||
7235 | if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { | |||
7236 | bool IsFirst = true; | |||
7237 | StringLiteralCheckType CommonResult; | |||
7238 | for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { | |||
7239 | const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); | |||
7240 | StringLiteralCheckType Result = checkFormatStringExpr( | |||
7241 | S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, | |||
7242 | CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, | |||
7243 | IgnoreStringsWithoutSpecifiers); | |||
7244 | if (IsFirst) { | |||
7245 | CommonResult = Result; | |||
7246 | IsFirst = false; | |||
7247 | } | |||
7248 | } | |||
7249 | if (!IsFirst) | |||
7250 | return CommonResult; | |||
7251 | ||||
7252 | if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { | |||
7253 | unsigned BuiltinID = FD->getBuiltinID(); | |||
7254 | if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || | |||
7255 | BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { | |||
7256 | const Expr *Arg = CE->getArg(0); | |||
7257 | return checkFormatStringExpr(S, Arg, Args, | |||
7258 | HasVAListArg, format_idx, | |||
7259 | firstDataArg, Type, CallType, | |||
7260 | InFunctionCall, CheckedVarArgs, | |||
7261 | UncoveredArg, Offset, | |||
7262 | IgnoreStringsWithoutSpecifiers); | |||
7263 | } | |||
7264 | } | |||
7265 | } | |||
7266 | ||||
7267 | return SLCT_NotALiteral; | |||
7268 | } | |||
7269 | case Stmt::ObjCMessageExprClass: { | |||
7270 | const auto *ME = cast<ObjCMessageExpr>(E); | |||
7271 | if (const auto *MD = ME->getMethodDecl()) { | |||
7272 | if (const auto *FA = MD->getAttr<FormatArgAttr>()) { | |||
7273 | // As a special case heuristic, if we're using the method -[NSBundle | |||
7274 | // localizedStringForKey:value:table:], ignore any key strings that lack | |||
7275 | // format specifiers. The idea is that if the key doesn't have any | |||
7276 | // format specifiers then its probably just a key to map to the | |||
7277 | // localized strings. If it does have format specifiers though, then its | |||
7278 | // likely that the text of the key is the format string in the | |||
7279 | // programmer's language, and should be checked. | |||
7280 | const ObjCInterfaceDecl *IFace; | |||
7281 | if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && | |||
7282 | IFace->getIdentifier()->isStr("NSBundle") && | |||
7283 | MD->getSelector().isKeywordSelector( | |||
7284 | {"localizedStringForKey", "value", "table"})) { | |||
7285 | IgnoreStringsWithoutSpecifiers = true; | |||
7286 | } | |||
7287 | ||||
7288 | const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); | |||
7289 | return checkFormatStringExpr( | |||
7290 | S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, | |||
7291 | CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, | |||
7292 | IgnoreStringsWithoutSpecifiers); | |||
7293 | } | |||
7294 | } | |||
7295 | ||||
7296 | return SLCT_NotALiteral; | |||
7297 | } | |||
7298 | case Stmt::ObjCStringLiteralClass: | |||
7299 | case Stmt::StringLiteralClass: { | |||
7300 | const StringLiteral *StrE = nullptr; | |||
7301 | ||||
7302 | if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) | |||
7303 | StrE = ObjCFExpr->getString(); | |||
7304 | else | |||
7305 | StrE = cast<StringLiteral>(E); | |||
7306 | ||||
7307 | if (StrE) { | |||
7308 | if (Offset.isNegative() || Offset > StrE->getLength()) { | |||
7309 | // TODO: It would be better to have an explicit warning for out of | |||
7310 | // bounds literals. | |||
7311 | return SLCT_NotALiteral; | |||
7312 | } | |||
7313 | FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); | |||
7314 | CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, | |||
7315 | firstDataArg, Type, InFunctionCall, CallType, | |||
7316 | CheckedVarArgs, UncoveredArg, | |||
7317 | IgnoreStringsWithoutSpecifiers); | |||
7318 | return SLCT_CheckedLiteral; | |||
7319 | } | |||
7320 | ||||
7321 | return SLCT_NotALiteral; | |||
7322 | } | |||
7323 | case Stmt::BinaryOperatorClass: { | |||
7324 | const BinaryOperator *BinOp = cast<BinaryOperator>(E); | |||
7325 | ||||
7326 | // A string literal + an int offset is still a string literal. | |||
7327 | if (BinOp->isAdditiveOp()) { | |||
7328 | Expr::EvalResult LResult, RResult; | |||
7329 | ||||
7330 | bool LIsInt = BinOp->getLHS()->EvaluateAsInt( | |||
7331 | LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); | |||
7332 | bool RIsInt = BinOp->getRHS()->EvaluateAsInt( | |||
7333 | RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); | |||
7334 | ||||
7335 | if (LIsInt != RIsInt) { | |||
7336 | BinaryOperatorKind BinOpKind = BinOp->getOpcode(); | |||
7337 | ||||
7338 | if (LIsInt) { | |||
7339 | if (BinOpKind == BO_Add) { | |||
7340 | sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); | |||
7341 | E = BinOp->getRHS(); | |||
7342 | goto tryAgain; | |||
7343 | } | |||
7344 | } else { | |||
7345 | sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); | |||
7346 | E = BinOp->getLHS(); | |||
7347 | goto tryAgain; | |||
7348 | } | |||
7349 | } | |||
7350 | } | |||
7351 | ||||
7352 | return SLCT_NotALiteral; | |||
7353 | } | |||
7354 | case Stmt::UnaryOperatorClass: { | |||
7355 | const UnaryOperator *UnaOp = cast<UnaryOperator>(E); | |||
7356 | auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); | |||
7357 | if (UnaOp->getOpcode() == UO_AddrOf && ASE) { | |||
7358 | Expr::EvalResult IndexResult; | |||
7359 | if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, | |||
7360 | Expr::SE_NoSideEffects, | |||
7361 | S.isConstantEvaluated())) { | |||
7362 | sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, | |||
7363 | /*RHS is int*/ true); | |||
7364 | E = ASE->getBase(); | |||
7365 | goto tryAgain; | |||
7366 | } | |||
7367 | } | |||
7368 | ||||
7369 | return SLCT_NotALiteral; | |||
7370 | } | |||
7371 | ||||
7372 | default: | |||
7373 | return SLCT_NotALiteral; | |||
7374 | } | |||
7375 | } | |||
7376 | ||||
7377 | Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { | |||
7378 | return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) | |||
7379 | .Case("scanf", FST_Scanf) | |||
7380 | .Cases("printf", "printf0", FST_Printf) | |||
7381 | .Cases("NSString", "CFString", FST_NSString) | |||
7382 | .Case("strftime", FST_Strftime) | |||
7383 | .Case("strfmon", FST_Strfmon) | |||
7384 | .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) | |||
7385 | .Case("freebsd_kprintf", FST_FreeBSDKPrintf) | |||
7386 | .Case("os_trace", FST_OSLog) | |||
7387 | .Case("os_log", FST_OSLog) | |||
7388 | .Default(FST_Unknown); | |||
7389 | } | |||
7390 | ||||
7391 | /// CheckFormatArguments - Check calls to printf and scanf (and similar | |||
7392 | /// functions) for correct use of format strings. | |||
7393 | /// Returns true if a format string has been fully checked. | |||
7394 | bool Sema::CheckFormatArguments(const FormatAttr *Format, | |||
7395 | ArrayRef<const Expr *> Args, | |||
7396 | bool IsCXXMember, | |||
7397 | VariadicCallType CallType, | |||
7398 | SourceLocation Loc, SourceRange Range, | |||
7399 | llvm::SmallBitVector &CheckedVarArgs) { | |||
7400 | FormatStringInfo FSI; | |||
7401 | if (getFormatStringInfo(Format, IsCXXMember, &FSI)) | |||
7402 | return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, | |||
7403 | FSI.FirstDataArg, GetFormatStringType(Format), | |||
7404 | CallType, Loc, Range, CheckedVarArgs); | |||
7405 | return false; | |||
7406 | } | |||
7407 | ||||
7408 | bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, | |||
7409 | bool HasVAListArg, unsigned format_idx, | |||
7410 | unsigned firstDataArg, FormatStringType Type, | |||
7411 | VariadicCallType CallType, | |||
7412 | SourceLocation Loc, SourceRange Range, | |||
7413 | llvm::SmallBitVector &CheckedVarArgs) { | |||
7414 | // CHECK: printf/scanf-like function is called with no format string. | |||
7415 | if (format_idx >= Args.size()) { | |||
7416 | Diag(Loc, diag::warn_missing_format_string) << Range; | |||
7417 | return false; | |||
7418 | } | |||
7419 | ||||
7420 | const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); | |||
7421 | ||||
7422 | // CHECK: format string is not a string literal. | |||
7423 | // | |||
7424 | // Dynamically generated format strings are difficult to | |||
7425 | // automatically vet at compile time. Requiring that format strings | |||
7426 | // are string literals: (1) permits the checking of format strings by | |||
7427 | // the compiler and thereby (2) can practically remove the source of | |||
7428 | // many format string exploits. | |||
7429 | ||||
7430 | // Format string can be either ObjC string (e.g. @"%d") or | |||
7431 | // C string (e.g. "%d") | |||
7432 | // ObjC string uses the same format specifiers as C string, so we can use | |||
7433 | // the same format string checking logic for both ObjC and C strings. | |||
7434 | UncoveredArgHandler UncoveredArg; | |||
7435 | StringLiteralCheckType CT = | |||
7436 | checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, | |||
7437 | format_idx, firstDataArg, Type, CallType, | |||
7438 | /*IsFunctionCall*/ true, CheckedVarArgs, | |||
7439 | UncoveredArg, | |||
7440 | /*no string offset*/ llvm::APSInt(64, false) = 0); | |||
7441 | ||||
7442 | // Generate a diagnostic where an uncovered argument is detected. | |||
7443 | if (UncoveredArg.hasUncoveredArg()) { | |||
7444 | unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; | |||
7445 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 7445, __PRETTY_FUNCTION__)); | |||
7446 | UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); | |||
7447 | } | |||
7448 | ||||
7449 | if (CT != SLCT_NotALiteral) | |||
7450 | // Literal format string found, check done! | |||
7451 | return CT == SLCT_CheckedLiteral; | |||
7452 | ||||
7453 | // Strftime is particular as it always uses a single 'time' argument, | |||
7454 | // so it is safe to pass a non-literal string. | |||
7455 | if (Type == FST_Strftime) | |||
7456 | return false; | |||
7457 | ||||
7458 | // Do not emit diag when the string param is a macro expansion and the | |||
7459 | // format is either NSString or CFString. This is a hack to prevent | |||
7460 | // diag when using the NSLocalizedString and CFCopyLocalizedString macros | |||
7461 | // which are usually used in place of NS and CF string literals. | |||
7462 | SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); | |||
7463 | if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) | |||
7464 | return false; | |||
7465 | ||||
7466 | // If there are no arguments specified, warn with -Wformat-security, otherwise | |||
7467 | // warn only with -Wformat-nonliteral. | |||
7468 | if (Args.size() == firstDataArg) { | |||
7469 | Diag(FormatLoc, diag::warn_format_nonliteral_noargs) | |||
7470 | << OrigFormatExpr->getSourceRange(); | |||
7471 | switch (Type) { | |||
7472 | default: | |||
7473 | break; | |||
7474 | case FST_Kprintf: | |||
7475 | case FST_FreeBSDKPrintf: | |||
7476 | case FST_Printf: | |||
7477 | Diag(FormatLoc, diag::note_format_security_fixit) | |||
7478 | << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); | |||
7479 | break; | |||
7480 | case FST_NSString: | |||
7481 | Diag(FormatLoc, diag::note_format_security_fixit) | |||
7482 | << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); | |||
7483 | break; | |||
7484 | } | |||
7485 | } else { | |||
7486 | Diag(FormatLoc, diag::warn_format_nonliteral) | |||
7487 | << OrigFormatExpr->getSourceRange(); | |||
7488 | } | |||
7489 | return false; | |||
7490 | } | |||
7491 | ||||
7492 | namespace { | |||
7493 | ||||
7494 | class CheckFormatHandler : public analyze_format_string::FormatStringHandler { | |||
7495 | protected: | |||
7496 | Sema &S; | |||
7497 | const FormatStringLiteral *FExpr; | |||
7498 | const Expr *OrigFormatExpr; | |||
7499 | const Sema::FormatStringType FSType; | |||
7500 | const unsigned FirstDataArg; | |||
7501 | const unsigned NumDataArgs; | |||
7502 | const char *Beg; // Start of format string. | |||
7503 | const bool HasVAListArg; | |||
7504 | ArrayRef<const Expr *> Args; | |||
7505 | unsigned FormatIdx; | |||
7506 | llvm::SmallBitVector CoveredArgs; | |||
7507 | bool usesPositionalArgs = false; | |||
7508 | bool atFirstArg = true; | |||
7509 | bool inFunctionCall; | |||
7510 | Sema::VariadicCallType CallType; | |||
7511 | llvm::SmallBitVector &CheckedVarArgs; | |||
7512 | UncoveredArgHandler &UncoveredArg; | |||
7513 | ||||
7514 | public: | |||
7515 | CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, | |||
7516 | const Expr *origFormatExpr, | |||
7517 | const Sema::FormatStringType type, unsigned firstDataArg, | |||
7518 | unsigned numDataArgs, const char *beg, bool hasVAListArg, | |||
7519 | ArrayRef<const Expr *> Args, unsigned formatIdx, | |||
7520 | bool inFunctionCall, Sema::VariadicCallType callType, | |||
7521 | llvm::SmallBitVector &CheckedVarArgs, | |||
7522 | UncoveredArgHandler &UncoveredArg) | |||
7523 | : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), | |||
7524 | FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), | |||
7525 | HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), | |||
7526 | inFunctionCall(inFunctionCall), CallType(callType), | |||
7527 | CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { | |||
7528 | CoveredArgs.resize(numDataArgs); | |||
7529 | CoveredArgs.reset(); | |||
7530 | } | |||
7531 | ||||
7532 | void DoneProcessing(); | |||
7533 | ||||
7534 | void HandleIncompleteSpecifier(const char *startSpecifier, | |||
7535 | unsigned specifierLen) override; | |||
7536 | ||||
7537 | void HandleInvalidLengthModifier( | |||
7538 | const analyze_format_string::FormatSpecifier &FS, | |||
7539 | const analyze_format_string::ConversionSpecifier &CS, | |||
7540 | const char *startSpecifier, unsigned specifierLen, | |||
7541 | unsigned DiagID); | |||
7542 | ||||
7543 | void HandleNonStandardLengthModifier( | |||
7544 | const analyze_format_string::FormatSpecifier &FS, | |||
7545 | const char *startSpecifier, unsigned specifierLen); | |||
7546 | ||||
7547 | void HandleNonStandardConversionSpecifier( | |||
7548 | const analyze_format_string::ConversionSpecifier &CS, | |||
7549 | const char *startSpecifier, unsigned specifierLen); | |||
7550 | ||||
7551 | void HandlePosition(const char *startPos, unsigned posLen) override; | |||
7552 | ||||
7553 | void HandleInvalidPosition(const char *startSpecifier, | |||
7554 | unsigned specifierLen, | |||
7555 | analyze_format_string::PositionContext p) override; | |||
7556 | ||||
7557 | void HandleZeroPosition(const char *startPos, unsigned posLen) override; | |||
7558 | ||||
7559 | void HandleNullChar(const char *nullCharacter) override; | |||
7560 | ||||
7561 | template <typename Range> | |||
7562 | static void | |||
7563 | EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, | |||
7564 | const PartialDiagnostic &PDiag, SourceLocation StringLoc, | |||
7565 | bool IsStringLocation, Range StringRange, | |||
7566 | ArrayRef<FixItHint> Fixit = None); | |||
7567 | ||||
7568 | protected: | |||
7569 | bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, | |||
7570 | const char *startSpec, | |||
7571 | unsigned specifierLen, | |||
7572 | const char *csStart, unsigned csLen); | |||
7573 | ||||
7574 | void HandlePositionalNonpositionalArgs(SourceLocation Loc, | |||
7575 | const char *startSpec, | |||
7576 | unsigned specifierLen); | |||
7577 | ||||
7578 | SourceRange getFormatStringRange(); | |||
7579 | CharSourceRange getSpecifierRange(const char *startSpecifier, | |||
7580 | unsigned specifierLen); | |||
7581 | SourceLocation getLocationOfByte(const char *x); | |||
7582 | ||||
7583 | const Expr *getDataArg(unsigned i) const; | |||
7584 | ||||
7585 | bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, | |||
7586 | const analyze_format_string::ConversionSpecifier &CS, | |||
7587 | const char *startSpecifier, unsigned specifierLen, | |||
7588 | unsigned argIndex); | |||
7589 | ||||
7590 | template <typename Range> | |||
7591 | void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, | |||
7592 | bool IsStringLocation, Range StringRange, | |||
7593 | ArrayRef<FixItHint> Fixit = None); | |||
7594 | }; | |||
7595 | ||||
7596 | } // namespace | |||
7597 | ||||
7598 | SourceRange CheckFormatHandler::getFormatStringRange() { | |||
7599 | return OrigFormatExpr->getSourceRange(); | |||
7600 | } | |||
7601 | ||||
7602 | CharSourceRange CheckFormatHandler:: | |||
7603 | getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { | |||
7604 | SourceLocation Start = getLocationOfByte(startSpecifier); | |||
7605 | SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); | |||
7606 | ||||
7607 | // Advance the end SourceLocation by one due to half-open ranges. | |||
7608 | End = End.getLocWithOffset(1); | |||
7609 | ||||
7610 | return CharSourceRange::getCharRange(Start, End); | |||
7611 | } | |||
7612 | ||||
7613 | SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { | |||
7614 | return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), | |||
7615 | S.getLangOpts(), S.Context.getTargetInfo()); | |||
7616 | } | |||
7617 | ||||
7618 | void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, | |||
7619 | unsigned specifierLen){ | |||
7620 | EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), | |||
7621 | getLocationOfByte(startSpecifier), | |||
7622 | /*IsStringLocation*/true, | |||
7623 | getSpecifierRange(startSpecifier, specifierLen)); | |||
7624 | } | |||
7625 | ||||
7626 | void CheckFormatHandler::HandleInvalidLengthModifier( | |||
7627 | const analyze_format_string::FormatSpecifier &FS, | |||
7628 | const analyze_format_string::ConversionSpecifier &CS, | |||
7629 | const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { | |||
7630 | using namespace analyze_format_string; | |||
7631 | ||||
7632 | const LengthModifier &LM = FS.getLengthModifier(); | |||
7633 | CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); | |||
7634 | ||||
7635 | // See if we know how to fix this length modifier. | |||
7636 | Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); | |||
7637 | if (FixedLM) { | |||
7638 | EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), | |||
7639 | getLocationOfByte(LM.getStart()), | |||
7640 | /*IsStringLocation*/true, | |||
7641 | getSpecifierRange(startSpecifier, specifierLen)); | |||
7642 | ||||
7643 | S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) | |||
7644 | << FixedLM->toString() | |||
7645 | << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); | |||
7646 | ||||
7647 | } else { | |||
7648 | FixItHint Hint; | |||
7649 | if (DiagID == diag::warn_format_nonsensical_length) | |||
7650 | Hint = FixItHint::CreateRemoval(LMRange); | |||
7651 | ||||
7652 | EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), | |||
7653 | getLocationOfByte(LM.getStart()), | |||
7654 | /*IsStringLocation*/true, | |||
7655 | getSpecifierRange(startSpecifier, specifierLen), | |||
7656 | Hint); | |||
7657 | } | |||
7658 | } | |||
7659 | ||||
7660 | void CheckFormatHandler::HandleNonStandardLengthModifier( | |||
7661 | const analyze_format_string::FormatSpecifier &FS, | |||
7662 | const char *startSpecifier, unsigned specifierLen) { | |||
7663 | using namespace analyze_format_string; | |||
7664 | ||||
7665 | const LengthModifier &LM = FS.getLengthModifier(); | |||
7666 | CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); | |||
7667 | ||||
7668 | // See if we know how to fix this length modifier. | |||
7669 | Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); | |||
7670 | if (FixedLM) { | |||
7671 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) | |||
7672 | << LM.toString() << 0, | |||
7673 | getLocationOfByte(LM.getStart()), | |||
7674 | /*IsStringLocation*/true, | |||
7675 | getSpecifierRange(startSpecifier, specifierLen)); | |||
7676 | ||||
7677 | S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) | |||
7678 | << FixedLM->toString() | |||
7679 | << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); | |||
7680 | ||||
7681 | } else { | |||
7682 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) | |||
7683 | << LM.toString() << 0, | |||
7684 | getLocationOfByte(LM.getStart()), | |||
7685 | /*IsStringLocation*/true, | |||
7686 | getSpecifierRange(startSpecifier, specifierLen)); | |||
7687 | } | |||
7688 | } | |||
7689 | ||||
7690 | void CheckFormatHandler::HandleNonStandardConversionSpecifier( | |||
7691 | const analyze_format_string::ConversionSpecifier &CS, | |||
7692 | const char *startSpecifier, unsigned specifierLen) { | |||
7693 | using namespace analyze_format_string; | |||
7694 | ||||
7695 | // See if we know how to fix this conversion specifier. | |||
7696 | Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); | |||
7697 | if (FixedCS) { | |||
7698 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) | |||
7699 | << CS.toString() << /*conversion specifier*/1, | |||
7700 | getLocationOfByte(CS.getStart()), | |||
7701 | /*IsStringLocation*/true, | |||
7702 | getSpecifierRange(startSpecifier, specifierLen)); | |||
7703 | ||||
7704 | CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); | |||
7705 | S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) | |||
7706 | << FixedCS->toString() | |||
7707 | << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); | |||
7708 | } else { | |||
7709 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) | |||
7710 | << CS.toString() << /*conversion specifier*/1, | |||
7711 | getLocationOfByte(CS.getStart()), | |||
7712 | /*IsStringLocation*/true, | |||
7713 | getSpecifierRange(startSpecifier, specifierLen)); | |||
7714 | } | |||
7715 | } | |||
7716 | ||||
7717 | void CheckFormatHandler::HandlePosition(const char *startPos, | |||
7718 | unsigned posLen) { | |||
7719 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), | |||
7720 | getLocationOfByte(startPos), | |||
7721 | /*IsStringLocation*/true, | |||
7722 | getSpecifierRange(startPos, posLen)); | |||
7723 | } | |||
7724 | ||||
7725 | void | |||
7726 | CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, | |||
7727 | analyze_format_string::PositionContext p) { | |||
7728 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) | |||
7729 | << (unsigned) p, | |||
7730 | getLocationOfByte(startPos), /*IsStringLocation*/true, | |||
7731 | getSpecifierRange(startPos, posLen)); | |||
7732 | } | |||
7733 | ||||
7734 | void CheckFormatHandler::HandleZeroPosition(const char *startPos, | |||
7735 | unsigned posLen) { | |||
7736 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), | |||
7737 | getLocationOfByte(startPos), | |||
7738 | /*IsStringLocation*/true, | |||
7739 | getSpecifierRange(startPos, posLen)); | |||
7740 | } | |||
7741 | ||||
7742 | void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { | |||
7743 | if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { | |||
7744 | // The presence of a null character is likely an error. | |||
7745 | EmitFormatDiagnostic( | |||
7746 | S.PDiag(diag::warn_printf_format_string_contains_null_char), | |||
7747 | getLocationOfByte(nullCharacter), /*IsStringLocation*/true, | |||
7748 | getFormatStringRange()); | |||
7749 | } | |||
7750 | } | |||
7751 | ||||
7752 | // Note that this may return NULL if there was an error parsing or building | |||
7753 | // one of the argument expressions. | |||
7754 | const Expr *CheckFormatHandler::getDataArg(unsigned i) const { | |||
7755 | return Args[FirstDataArg + i]; | |||
7756 | } | |||
7757 | ||||
7758 | void CheckFormatHandler::DoneProcessing() { | |||
7759 | // Does the number of data arguments exceed the number of | |||
7760 | // format conversions in the format string? | |||
7761 | if (!HasVAListArg) { | |||
7762 | // Find any arguments that weren't covered. | |||
7763 | CoveredArgs.flip(); | |||
7764 | signed notCoveredArg = CoveredArgs.find_first(); | |||
7765 | if (notCoveredArg >= 0) { | |||
7766 | assert((unsigned)notCoveredArg < NumDataArgs)(((unsigned)notCoveredArg < NumDataArgs) ? static_cast< void> (0) : __assert_fail ("(unsigned)notCoveredArg < NumDataArgs" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 7766, __PRETTY_FUNCTION__)); | |||
7767 | UncoveredArg.Update(notCoveredArg, OrigFormatExpr); | |||
7768 | } else { | |||
7769 | UncoveredArg.setAllCovered(); | |||
7770 | } | |||
7771 | } | |||
7772 | } | |||
7773 | ||||
7774 | void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, | |||
7775 | const Expr *ArgExpr) { | |||
7776 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 7777, __PRETTY_FUNCTION__)) | |||
7777 | "Invalid state")((hasUncoveredArg() && DiagnosticExprs.size() > 0 && "Invalid state") ? static_cast<void> (0) : __assert_fail ("hasUncoveredArg() && DiagnosticExprs.size() > 0 && \"Invalid state\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 7777, __PRETTY_FUNCTION__)); | |||
7778 | ||||
7779 | if (!ArgExpr) | |||
7780 | return; | |||
7781 | ||||
7782 | SourceLocation Loc = ArgExpr->getBeginLoc(); | |||
7783 | ||||
7784 | if (S.getSourceManager().isInSystemMacro(Loc)) | |||
7785 | return; | |||
7786 | ||||
7787 | PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); | |||
7788 | for (auto E : DiagnosticExprs) | |||
7789 | PDiag << E->getSourceRange(); | |||
7790 | ||||
7791 | CheckFormatHandler::EmitFormatDiagnostic( | |||
7792 | S, IsFunctionCall, DiagnosticExprs[0], | |||
7793 | PDiag, Loc, /*IsStringLocation*/false, | |||
7794 | DiagnosticExprs[0]->getSourceRange()); | |||
7795 | } | |||
7796 | ||||
7797 | bool | |||
7798 | CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, | |||
7799 | SourceLocation Loc, | |||
7800 | const char *startSpec, | |||
7801 | unsigned specifierLen, | |||
7802 | const char *csStart, | |||
7803 | unsigned csLen) { | |||
7804 | bool keepGoing = true; | |||
7805 | if (argIndex < NumDataArgs) { | |||
7806 | // Consider the argument coverered, even though the specifier doesn't | |||
7807 | // make sense. | |||
7808 | CoveredArgs.set(argIndex); | |||
7809 | } | |||
7810 | else { | |||
7811 | // If argIndex exceeds the number of data arguments we | |||
7812 | // don't issue a warning because that is just a cascade of warnings (and | |||
7813 | // they may have intended '%%' anyway). We don't want to continue processing | |||
7814 | // the format string after this point, however, as we will like just get | |||
7815 | // gibberish when trying to match arguments. | |||
7816 | keepGoing = false; | |||
7817 | } | |||
7818 | ||||
7819 | StringRef Specifier(csStart, csLen); | |||
7820 | ||||
7821 | // If the specifier in non-printable, it could be the first byte of a UTF-8 | |||
7822 | // sequence. In that case, print the UTF-8 code point. If not, print the byte | |||
7823 | // hex value. | |||
7824 | std::string CodePointStr; | |||
7825 | if (!llvm::sys::locale::isPrint(*csStart)) { | |||
7826 | llvm::UTF32 CodePoint; | |||
7827 | const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); | |||
7828 | const llvm::UTF8 *E = | |||
7829 | reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); | |||
7830 | llvm::ConversionResult Result = | |||
7831 | llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); | |||
7832 | ||||
7833 | if (Result != llvm::conversionOK) { | |||
7834 | unsigned char FirstChar = *csStart; | |||
7835 | CodePoint = (llvm::UTF32)FirstChar; | |||
7836 | } | |||
7837 | ||||
7838 | llvm::raw_string_ostream OS(CodePointStr); | |||
7839 | if (CodePoint < 256) | |||
7840 | OS << "\\x" << llvm::format("%02x", CodePoint); | |||
7841 | else if (CodePoint <= 0xFFFF) | |||
7842 | OS << "\\u" << llvm::format("%04x", CodePoint); | |||
7843 | else | |||
7844 | OS << "\\U" << llvm::format("%08x", CodePoint); | |||
7845 | OS.flush(); | |||
7846 | Specifier = CodePointStr; | |||
7847 | } | |||
7848 | ||||
7849 | EmitFormatDiagnostic( | |||
7850 | S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, | |||
7851 | /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); | |||
7852 | ||||
7853 | return keepGoing; | |||
7854 | } | |||
7855 | ||||
7856 | void | |||
7857 | CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, | |||
7858 | const char *startSpec, | |||
7859 | unsigned specifierLen) { | |||
7860 | EmitFormatDiagnostic( | |||
7861 | S.PDiag(diag::warn_format_mix_positional_nonpositional_args), | |||
7862 | Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); | |||
7863 | } | |||
7864 | ||||
7865 | bool | |||
7866 | CheckFormatHandler::CheckNumArgs( | |||
7867 | const analyze_format_string::FormatSpecifier &FS, | |||
7868 | const analyze_format_string::ConversionSpecifier &CS, | |||
7869 | const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { | |||
7870 | ||||
7871 | if (argIndex >= NumDataArgs) { | |||
7872 | PartialDiagnostic PDiag = FS.usesPositionalArg() | |||
7873 | ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) | |||
7874 | << (argIndex+1) << NumDataArgs) | |||
7875 | : S.PDiag(diag::warn_printf_insufficient_data_args); | |||
7876 | EmitFormatDiagnostic( | |||
7877 | PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, | |||
7878 | getSpecifierRange(startSpecifier, specifierLen)); | |||
7879 | ||||
7880 | // Since more arguments than conversion tokens are given, by extension | |||
7881 | // all arguments are covered, so mark this as so. | |||
7882 | UncoveredArg.setAllCovered(); | |||
7883 | return false; | |||
7884 | } | |||
7885 | return true; | |||
7886 | } | |||
7887 | ||||
7888 | template<typename Range> | |||
7889 | void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, | |||
7890 | SourceLocation Loc, | |||
7891 | bool IsStringLocation, | |||
7892 | Range StringRange, | |||
7893 | ArrayRef<FixItHint> FixIt) { | |||
7894 | EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, | |||
7895 | Loc, IsStringLocation, StringRange, FixIt); | |||
7896 | } | |||
7897 | ||||
7898 | /// If the format string is not within the function call, emit a note | |||
7899 | /// so that the function call and string are in diagnostic messages. | |||
7900 | /// | |||
7901 | /// \param InFunctionCall if true, the format string is within the function | |||
7902 | /// call and only one diagnostic message will be produced. Otherwise, an | |||
7903 | /// extra note will be emitted pointing to location of the format string. | |||
7904 | /// | |||
7905 | /// \param ArgumentExpr the expression that is passed as the format string | |||
7906 | /// argument in the function call. Used for getting locations when two | |||
7907 | /// diagnostics are emitted. | |||
7908 | /// | |||
7909 | /// \param PDiag the callee should already have provided any strings for the | |||
7910 | /// diagnostic message. This function only adds locations and fixits | |||
7911 | /// to diagnostics. | |||
7912 | /// | |||
7913 | /// \param Loc primary location for diagnostic. If two diagnostics are | |||
7914 | /// required, one will be at Loc and a new SourceLocation will be created for | |||
7915 | /// the other one. | |||
7916 | /// | |||
7917 | /// \param IsStringLocation if true, Loc points to the format string should be | |||
7918 | /// used for the note. Otherwise, Loc points to the argument list and will | |||
7919 | /// be used with PDiag. | |||
7920 | /// | |||
7921 | /// \param StringRange some or all of the string to highlight. This is | |||
7922 | /// templated so it can accept either a CharSourceRange or a SourceRange. | |||
7923 | /// | |||
7924 | /// \param FixIt optional fix it hint for the format string. | |||
7925 | template <typename Range> | |||
7926 | void CheckFormatHandler::EmitFormatDiagnostic( | |||
7927 | Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, | |||
7928 | const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, | |||
7929 | Range StringRange, ArrayRef<FixItHint> FixIt) { | |||
7930 | if (InFunctionCall) { | |||
7931 | const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); | |||
7932 | D << StringRange; | |||
7933 | D << FixIt; | |||
7934 | } else { | |||
7935 | S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) | |||
7936 | << ArgumentExpr->getSourceRange(); | |||
7937 | ||||
7938 | const Sema::SemaDiagnosticBuilder &Note = | |||
7939 | S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), | |||
7940 | diag::note_format_string_defined); | |||
7941 | ||||
7942 | Note << StringRange; | |||
7943 | Note << FixIt; | |||
7944 | } | |||
7945 | } | |||
7946 | ||||
7947 | //===--- CHECK: Printf format string checking ------------------------------===// | |||
7948 | ||||
7949 | namespace { | |||
7950 | ||||
7951 | class CheckPrintfHandler : public CheckFormatHandler { | |||
7952 | public: | |||
7953 | CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, | |||
7954 | const Expr *origFormatExpr, | |||
7955 | const Sema::FormatStringType type, unsigned firstDataArg, | |||
7956 | unsigned numDataArgs, bool isObjC, const char *beg, | |||
7957 | bool hasVAListArg, ArrayRef<const Expr *> Args, | |||
7958 | unsigned formatIdx, bool inFunctionCall, | |||
7959 | Sema::VariadicCallType CallType, | |||
7960 | llvm::SmallBitVector &CheckedVarArgs, | |||
7961 | UncoveredArgHandler &UncoveredArg) | |||
7962 | : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, | |||
7963 | numDataArgs, beg, hasVAListArg, Args, formatIdx, | |||
7964 | inFunctionCall, CallType, CheckedVarArgs, | |||
7965 | UncoveredArg) {} | |||
7966 | ||||
7967 | bool isObjCContext() const { return FSType == Sema::FST_NSString; } | |||
7968 | ||||
7969 | /// Returns true if '%@' specifiers are allowed in the format string. | |||
7970 | bool allowsObjCArg() const { | |||
7971 | return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || | |||
7972 | FSType == Sema::FST_OSTrace; | |||
7973 | } | |||
7974 | ||||
7975 | bool HandleInvalidPrintfConversionSpecifier( | |||
7976 | const analyze_printf::PrintfSpecifier &FS, | |||
7977 | const char *startSpecifier, | |||
7978 | unsigned specifierLen) override; | |||
7979 | ||||
7980 | void handleInvalidMaskType(StringRef MaskType) override; | |||
7981 | ||||
7982 | bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, | |||
7983 | const char *startSpecifier, | |||
7984 | unsigned specifierLen) override; | |||
7985 | bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, | |||
7986 | const char *StartSpecifier, | |||
7987 | unsigned SpecifierLen, | |||
7988 | const Expr *E); | |||
7989 | ||||
7990 | bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, | |||
7991 | const char *startSpecifier, unsigned specifierLen); | |||
7992 | void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, | |||
7993 | const analyze_printf::OptionalAmount &Amt, | |||
7994 | unsigned type, | |||
7995 | const char *startSpecifier, unsigned specifierLen); | |||
7996 | void HandleFlag(const analyze_printf::PrintfSpecifier &FS, | |||
7997 | const analyze_printf::OptionalFlag &flag, | |||
7998 | const char *startSpecifier, unsigned specifierLen); | |||
7999 | void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, | |||
8000 | const analyze_printf::OptionalFlag &ignoredFlag, | |||
8001 | const analyze_printf::OptionalFlag &flag, | |||
8002 | const char *startSpecifier, unsigned specifierLen); | |||
8003 | bool checkForCStrMembers(const analyze_printf::ArgType &AT, | |||
8004 | const Expr *E); | |||
8005 | ||||
8006 | void HandleEmptyObjCModifierFlag(const char *startFlag, | |||
8007 | unsigned flagLen) override; | |||
8008 | ||||
8009 | void HandleInvalidObjCModifierFlag(const char *startFlag, | |||
8010 | unsigned flagLen) override; | |||
8011 | ||||
8012 | void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, | |||
8013 | const char *flagsEnd, | |||
8014 | const char *conversionPosition) | |||
8015 | override; | |||
8016 | }; | |||
8017 | ||||
8018 | } // namespace | |||
8019 | ||||
8020 | bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( | |||
8021 | const analyze_printf::PrintfSpecifier &FS, | |||
8022 | const char *startSpecifier, | |||
8023 | unsigned specifierLen) { | |||
8024 | const analyze_printf::PrintfConversionSpecifier &CS = | |||
8025 | FS.getConversionSpecifier(); | |||
8026 | ||||
8027 | return HandleInvalidConversionSpecifier(FS.getArgIndex(), | |||
8028 | getLocationOfByte(CS.getStart()), | |||
8029 | startSpecifier, specifierLen, | |||
8030 | CS.getStart(), CS.getLength()); | |||
8031 | } | |||
8032 | ||||
8033 | void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { | |||
8034 | S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); | |||
8035 | } | |||
8036 | ||||
8037 | bool CheckPrintfHandler::HandleAmount( | |||
8038 | const analyze_format_string::OptionalAmount &Amt, | |||
8039 | unsigned k, const char *startSpecifier, | |||
8040 | unsigned specifierLen) { | |||
8041 | if (Amt.hasDataArgument()) { | |||
8042 | if (!HasVAListArg) { | |||
8043 | unsigned argIndex = Amt.getArgIndex(); | |||
8044 | if (argIndex >= NumDataArgs) { | |||
8045 | EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) | |||
8046 | << k, | |||
8047 | getLocationOfByte(Amt.getStart()), | |||
8048 | /*IsStringLocation*/true, | |||
8049 | getSpecifierRange(startSpecifier, specifierLen)); | |||
8050 | // Don't do any more checking. We will just emit | |||
8051 | // spurious errors. | |||
8052 | return false; | |||
8053 | } | |||
8054 | ||||
8055 | // Type check the data argument. It should be an 'int'. | |||
8056 | // Although not in conformance with C99, we also allow the argument to be | |||
8057 | // an 'unsigned int' as that is a reasonably safe case. GCC also | |||
8058 | // doesn't emit a warning for that case. | |||
8059 | CoveredArgs.set(argIndex); | |||
8060 | const Expr *Arg = getDataArg(argIndex); | |||
8061 | if (!Arg) | |||
8062 | return false; | |||
8063 | ||||
8064 | QualType T = Arg->getType(); | |||
8065 | ||||
8066 | const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); | |||
8067 | assert(AT.isValid())((AT.isValid()) ? static_cast<void> (0) : __assert_fail ("AT.isValid()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 8067, __PRETTY_FUNCTION__)); | |||
8068 | ||||
8069 | if (!AT.matchesType(S.Context, T)) { | |||
8070 | EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) | |||
8071 | << k << AT.getRepresentativeTypeName(S.Context) | |||
8072 | << T << Arg->getSourceRange(), | |||
8073 | getLocationOfByte(Amt.getStart()), | |||
8074 | /*IsStringLocation*/true, | |||
8075 | getSpecifierRange(startSpecifier, specifierLen)); | |||
8076 | // Don't do any more checking. We will just emit | |||
8077 | // spurious errors. | |||
8078 | return false; | |||
8079 | } | |||
8080 | } | |||
8081 | } | |||
8082 | return true; | |||
8083 | } | |||
8084 | ||||
8085 | void CheckPrintfHandler::HandleInvalidAmount( | |||
8086 | const analyze_printf::PrintfSpecifier &FS, | |||
8087 | const analyze_printf::OptionalAmount &Amt, | |||
8088 | unsigned type, | |||
8089 | const char *startSpecifier, | |||
8090 | unsigned specifierLen) { | |||
8091 | const analyze_printf::PrintfConversionSpecifier &CS = | |||
8092 | FS.getConversionSpecifier(); | |||
8093 | ||||
8094 | FixItHint fixit = | |||
8095 | Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant | |||
8096 | ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), | |||
8097 | Amt.getConstantLength())) | |||
8098 | : FixItHint(); | |||
8099 | ||||
8100 | EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) | |||
8101 | << type << CS.toString(), | |||
8102 | getLocationOfByte(Amt.getStart()), | |||
8103 | /*IsStringLocation*/true, | |||
8104 | getSpecifierRange(startSpecifier, specifierLen), | |||
8105 | fixit); | |||
8106 | } | |||
8107 | ||||
8108 | void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, | |||
8109 | const analyze_printf::OptionalFlag &flag, | |||
8110 | const char *startSpecifier, | |||
8111 | unsigned specifierLen) { | |||
8112 | // Warn about pointless flag with a fixit removal. | |||
8113 | const analyze_printf::PrintfConversionSpecifier &CS = | |||
8114 | FS.getConversionSpecifier(); | |||
8115 | EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) | |||
8116 | << flag.toString() << CS.toString(), | |||
8117 | getLocationOfByte(flag.getPosition()), | |||
8118 | /*IsStringLocation*/true, | |||
8119 | getSpecifierRange(startSpecifier, specifierLen), | |||
8120 | FixItHint::CreateRemoval( | |||
8121 | getSpecifierRange(flag.getPosition(), 1))); | |||
8122 | } | |||
8123 | ||||
8124 | void CheckPrintfHandler::HandleIgnoredFlag( | |||
8125 | const analyze_printf::PrintfSpecifier &FS, | |||
8126 | const analyze_printf::OptionalFlag &ignoredFlag, | |||
8127 | const analyze_printf::OptionalFlag &flag, | |||
8128 | const char *startSpecifier, | |||
8129 | unsigned specifierLen) { | |||
8130 | // Warn about ignored flag with a fixit removal. | |||
8131 | EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) | |||
8132 | << ignoredFlag.toString() << flag.toString(), | |||
8133 | getLocationOfByte(ignoredFlag.getPosition()), | |||
8134 | /*IsStringLocation*/true, | |||
8135 | getSpecifierRange(startSpecifier, specifierLen), | |||
8136 | FixItHint::CreateRemoval( | |||
8137 | getSpecifierRange(ignoredFlag.getPosition(), 1))); | |||
8138 | } | |||
8139 | ||||
8140 | void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, | |||
8141 | unsigned flagLen) { | |||
8142 | // Warn about an empty flag. | |||
8143 | EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), | |||
8144 | getLocationOfByte(startFlag), | |||
8145 | /*IsStringLocation*/true, | |||
8146 | getSpecifierRange(startFlag, flagLen)); | |||
8147 | } | |||
8148 | ||||
8149 | void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, | |||
8150 | unsigned flagLen) { | |||
8151 | // Warn about an invalid flag. | |||
8152 | auto Range = getSpecifierRange(startFlag, flagLen); | |||
8153 | StringRef flag(startFlag, flagLen); | |||
8154 | EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, | |||
8155 | getLocationOfByte(startFlag), | |||
8156 | /*IsStringLocation*/true, | |||
8157 | Range, FixItHint::CreateRemoval(Range)); | |||
8158 | } | |||
8159 | ||||
8160 | void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( | |||
8161 | const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { | |||
8162 | // Warn about using '[...]' without a '@' conversion. | |||
8163 | auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); | |||
8164 | auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; | |||
8165 | EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), | |||
8166 | getLocationOfByte(conversionPosition), | |||
8167 | /*IsStringLocation*/true, | |||
8168 | Range, FixItHint::CreateRemoval(Range)); | |||
8169 | } | |||
8170 | ||||
8171 | // Determines if the specified is a C++ class or struct containing | |||
8172 | // a member with the specified name and kind (e.g. a CXXMethodDecl named | |||
8173 | // "c_str()"). | |||
8174 | template<typename MemberKind> | |||
8175 | static llvm::SmallPtrSet<MemberKind*, 1> | |||
8176 | CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { | |||
8177 | const RecordType *RT = Ty->getAs<RecordType>(); | |||
8178 | llvm::SmallPtrSet<MemberKind*, 1> Results; | |||
8179 | ||||
8180 | if (!RT) | |||
8181 | return Results; | |||
8182 | const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); | |||
8183 | if (!RD || !RD->getDefinition()) | |||
8184 | return Results; | |||
8185 | ||||
8186 | LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), | |||
8187 | Sema::LookupMemberName); | |||
8188 | R.suppressDiagnostics(); | |||
8189 | ||||
8190 | // We just need to include all members of the right kind turned up by the | |||
8191 | // filter, at this point. | |||
8192 | if (S.LookupQualifiedName(R, RT->getDecl())) | |||
8193 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { | |||
8194 | NamedDecl *decl = (*I)->getUnderlyingDecl(); | |||
8195 | if (MemberKind *FK = dyn_cast<MemberKind>(decl)) | |||
8196 | Results.insert(FK); | |||
8197 | } | |||
8198 | return Results; | |||
8199 | } | |||
8200 | ||||
8201 | /// Check if we could call '.c_str()' on an object. | |||
8202 | /// | |||
8203 | /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't | |||
8204 | /// allow the call, or if it would be ambiguous). | |||
8205 | bool Sema::hasCStrMethod(const Expr *E) { | |||
8206 | using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; | |||
8207 | ||||
8208 | MethodSet Results = | |||
8209 | CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); | |||
8210 | for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); | |||
8211 | MI != ME; ++MI) | |||
8212 | if ((*MI)->getMinRequiredArguments() == 0) | |||
8213 | return true; | |||
8214 | return false; | |||
8215 | } | |||
8216 | ||||
8217 | // Check if a (w)string was passed when a (w)char* was needed, and offer a | |||
8218 | // better diagnostic if so. AT is assumed to be valid. | |||
8219 | // Returns true when a c_str() conversion method is found. | |||
8220 | bool CheckPrintfHandler::checkForCStrMembers( | |||
8221 | const analyze_printf::ArgType &AT, const Expr *E) { | |||
8222 | using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; | |||
8223 | ||||
8224 | MethodSet Results = | |||
8225 | CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); | |||
8226 | ||||
8227 | for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); | |||
8228 | MI != ME; ++MI) { | |||
8229 | const CXXMethodDecl *Method = *MI; | |||
8230 | if (Method->getMinRequiredArguments() == 0 && | |||
8231 | AT.matchesType(S.Context, Method->getReturnType())) { | |||
8232 | // FIXME: Suggest parens if the expression needs them. | |||
8233 | SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); | |||
8234 | S.Diag(E->getBeginLoc(), diag::note_printf_c_str) | |||
8235 | << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); | |||
8236 | return true; | |||
8237 | } | |||
8238 | } | |||
8239 | ||||
8240 | return false; | |||
8241 | } | |||
8242 | ||||
8243 | bool | |||
8244 | CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier | |||
8245 | &FS, | |||
8246 | const char *startSpecifier, | |||
8247 | unsigned specifierLen) { | |||
8248 | using namespace analyze_format_string; | |||
8249 | using namespace analyze_printf; | |||
8250 | ||||
8251 | const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); | |||
8252 | ||||
8253 | if (FS.consumesDataArgument()) { | |||
8254 | if (atFirstArg) { | |||
8255 | atFirstArg = false; | |||
8256 | usesPositionalArgs = FS.usesPositionalArg(); | |||
8257 | } | |||
8258 | else if (usesPositionalArgs != FS.usesPositionalArg()) { | |||
8259 | HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), | |||
8260 | startSpecifier, specifierLen); | |||
8261 | return false; | |||
8262 | } | |||
8263 | } | |||
8264 | ||||
8265 | // First check if the field width, precision, and conversion specifier | |||
8266 | // have matching data arguments. | |||
8267 | if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, | |||
8268 | startSpecifier, specifierLen)) { | |||
8269 | return false; | |||
8270 | } | |||
8271 | ||||
8272 | if (!HandleAmount(FS.getPrecision(), /* precision */ 1, | |||
8273 | startSpecifier, specifierLen)) { | |||
8274 | return false; | |||
8275 | } | |||
8276 | ||||
8277 | if (!CS.consumesDataArgument()) { | |||
8278 | // FIXME: Technically specifying a precision or field width here | |||
8279 | // makes no sense. Worth issuing a warning at some point. | |||
8280 | return true; | |||
8281 | } | |||
8282 | ||||
8283 | // Consume the argument. | |||
8284 | unsigned argIndex = FS.getArgIndex(); | |||
8285 | if (argIndex < NumDataArgs) { | |||
8286 | // The check to see if the argIndex is valid will come later. | |||
8287 | // We set the bit here because we may exit early from this | |||
8288 | // function if we encounter some other error. | |||
8289 | CoveredArgs.set(argIndex); | |||
8290 | } | |||
8291 | ||||
8292 | // FreeBSD kernel extensions. | |||
8293 | if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || | |||
8294 | CS.getKind() == ConversionSpecifier::FreeBSDDArg) { | |||
8295 | // We need at least two arguments. | |||
8296 | if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) | |||
8297 | return false; | |||
8298 | ||||
8299 | // Claim the second argument. | |||
8300 | CoveredArgs.set(argIndex + 1); | |||
8301 | ||||
8302 | // Type check the first argument (int for %b, pointer for %D) | |||
8303 | const Expr *Ex = getDataArg(argIndex); | |||
8304 | const analyze_printf::ArgType &AT = | |||
8305 | (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? | |||
8306 | ArgType(S.Context.IntTy) : ArgType::CPointerTy; | |||
8307 | if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) | |||
8308 | EmitFormatDiagnostic( | |||
8309 | S.PDiag(diag::warn_format_conversion_argument_type_mismatch) | |||
8310 | << AT.getRepresentativeTypeName(S.Context) << Ex->getType() | |||
8311 | << false << Ex->getSourceRange(), | |||
8312 | Ex->getBeginLoc(), /*IsStringLocation*/ false, | |||
8313 | getSpecifierRange(startSpecifier, specifierLen)); | |||
8314 | ||||
8315 | // Type check the second argument (char * for both %b and %D) | |||
8316 | Ex = getDataArg(argIndex + 1); | |||
8317 | const analyze_printf::ArgType &AT2 = ArgType::CStrTy; | |||
8318 | if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) | |||
8319 | EmitFormatDiagnostic( | |||
8320 | S.PDiag(diag::warn_format_conversion_argument_type_mismatch) | |||
8321 | << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() | |||
8322 | << false << Ex->getSourceRange(), | |||
8323 | Ex->getBeginLoc(), /*IsStringLocation*/ false, | |||
8324 | getSpecifierRange(startSpecifier, specifierLen)); | |||
8325 | ||||
8326 | return true; | |||
8327 | } | |||
8328 | ||||
8329 | // Check for using an Objective-C specific conversion specifier | |||
8330 | // in a non-ObjC literal. | |||
8331 | if (!allowsObjCArg() && CS.isObjCArg()) { | |||
8332 | return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, | |||
8333 | specifierLen); | |||
8334 | } | |||
8335 | ||||
8336 | // %P can only be used with os_log. | |||
8337 | if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { | |||
8338 | return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, | |||
8339 | specifierLen); | |||
8340 | } | |||
8341 | ||||
8342 | // %n is not allowed with os_log. | |||
8343 | if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { | |||
8344 | EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), | |||
8345 | getLocationOfByte(CS.getStart()), | |||
8346 | /*IsStringLocation*/ false, | |||
8347 | getSpecifierRange(startSpecifier, specifierLen)); | |||
8348 | ||||
8349 | return true; | |||
8350 | } | |||
8351 | ||||
8352 | // Only scalars are allowed for os_trace. | |||
8353 | if (FSType == Sema::FST_OSTrace && | |||
8354 | (CS.getKind() == ConversionSpecifier::PArg || | |||
8355 | CS.getKind() == ConversionSpecifier::sArg || | |||
8356 | CS.getKind() == ConversionSpecifier::ObjCObjArg)) { | |||
8357 | return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, | |||
8358 | specifierLen); | |||
8359 | } | |||
8360 | ||||
8361 | // Check for use of public/private annotation outside of os_log(). | |||
8362 | if (FSType != Sema::FST_OSLog) { | |||
8363 | if (FS.isPublic().isSet()) { | |||
8364 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) | |||
8365 | << "public", | |||
8366 | getLocationOfByte(FS.isPublic().getPosition()), | |||
8367 | /*IsStringLocation*/ false, | |||
8368 | getSpecifierRange(startSpecifier, specifierLen)); | |||
8369 | } | |||
8370 | if (FS.isPrivate().isSet()) { | |||
8371 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) | |||
8372 | << "private", | |||
8373 | getLocationOfByte(FS.isPrivate().getPosition()), | |||
8374 | /*IsStringLocation*/ false, | |||
8375 | getSpecifierRange(startSpecifier, specifierLen)); | |||
8376 | } | |||
8377 | } | |||
8378 | ||||
8379 | // Check for invalid use of field width | |||
8380 | if (!FS.hasValidFieldWidth()) { | |||
8381 | HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, | |||
8382 | startSpecifier, specifierLen); | |||
8383 | } | |||
8384 | ||||
8385 | // Check for invalid use of precision | |||
8386 | if (!FS.hasValidPrecision()) { | |||
8387 | HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, | |||
8388 | startSpecifier, specifierLen); | |||
8389 | } | |||
8390 | ||||
8391 | // Precision is mandatory for %P specifier. | |||
8392 | if (CS.getKind() == ConversionSpecifier::PArg && | |||
8393 | FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { | |||
8394 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), | |||
8395 | getLocationOfByte(startSpecifier), | |||
8396 | /*IsStringLocation*/ false, | |||
8397 | getSpecifierRange(startSpecifier, specifierLen)); | |||
8398 | } | |||
8399 | ||||
8400 | // Check each flag does not conflict with any other component. | |||
8401 | if (!FS.hasValidThousandsGroupingPrefix()) | |||
8402 | HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); | |||
8403 | if (!FS.hasValidLeadingZeros()) | |||
8404 | HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); | |||
8405 | if (!FS.hasValidPlusPrefix()) | |||
8406 | HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); | |||
8407 | if (!FS.hasValidSpacePrefix()) | |||
8408 | HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); | |||
8409 | if (!FS.hasValidAlternativeForm()) | |||
8410 | HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); | |||
8411 | if (!FS.hasValidLeftJustified()) | |||
8412 | HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); | |||
8413 | ||||
8414 | // Check that flags are not ignored by another flag | |||
8415 | if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' | |||
8416 | HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), | |||
8417 | startSpecifier, specifierLen); | |||
8418 | if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' | |||
8419 | HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), | |||
8420 | startSpecifier, specifierLen); | |||
8421 | ||||
8422 | // Check the length modifier is valid with the given conversion specifier. | |||
8423 | if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), | |||
8424 | S.getLangOpts())) | |||
8425 | HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, | |||
8426 | diag::warn_format_nonsensical_length); | |||
8427 | else if (!FS.hasStandardLengthModifier()) | |||
8428 | HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); | |||
8429 | else if (!FS.hasStandardLengthConversionCombination()) | |||
8430 | HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, | |||
8431 | diag::warn_format_non_standard_conversion_spec); | |||
8432 | ||||
8433 | if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) | |||
8434 | HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); | |||
8435 | ||||
8436 | // The remaining checks depend on the data arguments. | |||
8437 | if (HasVAListArg) | |||
8438 | return true; | |||
8439 | ||||
8440 | if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) | |||
8441 | return false; | |||
8442 | ||||
8443 | const Expr *Arg = getDataArg(argIndex); | |||
8444 | if (!Arg) | |||
8445 | return true; | |||
8446 | ||||
8447 | return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); | |||
8448 | } | |||
8449 | ||||
8450 | static bool requiresParensToAddCast(const Expr *E) { | |||
8451 | // FIXME: We should have a general way to reason about operator | |||
8452 | // precedence and whether parens are actually needed here. | |||
8453 | // Take care of a few common cases where they aren't. | |||
8454 | const Expr *Inside = E->IgnoreImpCasts(); | |||
8455 | if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) | |||
8456 | Inside = POE->getSyntacticForm()->IgnoreImpCasts(); | |||
8457 | ||||
8458 | switch (Inside->getStmtClass()) { | |||
8459 | case Stmt::ArraySubscriptExprClass: | |||
8460 | case Stmt::CallExprClass: | |||
8461 | case Stmt::CharacterLiteralClass: | |||
8462 | case Stmt::CXXBoolLiteralExprClass: | |||
8463 | case Stmt::DeclRefExprClass: | |||
8464 | case Stmt::FloatingLiteralClass: | |||
8465 | case Stmt::IntegerLiteralClass: | |||
8466 | case Stmt::MemberExprClass: | |||
8467 | case Stmt::ObjCArrayLiteralClass: | |||
8468 | case Stmt::ObjCBoolLiteralExprClass: | |||
8469 | case Stmt::ObjCBoxedExprClass: | |||
8470 | case Stmt::ObjCDictionaryLiteralClass: | |||
8471 | case Stmt::ObjCEncodeExprClass: | |||
8472 | case Stmt::ObjCIvarRefExprClass: | |||
8473 | case Stmt::ObjCMessageExprClass: | |||
8474 | case Stmt::ObjCPropertyRefExprClass: | |||
8475 | case Stmt::ObjCStringLiteralClass: | |||
8476 | case Stmt::ObjCSubscriptRefExprClass: | |||
8477 | case Stmt::ParenExprClass: | |||
8478 | case Stmt::StringLiteralClass: | |||
8479 | case Stmt::UnaryOperatorClass: | |||
8480 | return false; | |||
8481 | default: | |||
8482 | return true; | |||
8483 | } | |||
8484 | } | |||
8485 | ||||
8486 | static std::pair<QualType, StringRef> | |||
8487 | shouldNotPrintDirectly(const ASTContext &Context, | |||
8488 | QualType IntendedTy, | |||
8489 | const Expr *E) { | |||
8490 | // Use a 'while' to peel off layers of typedefs. | |||
8491 | QualType TyTy = IntendedTy; | |||
8492 | while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { | |||
8493 | StringRef Name = UserTy->getDecl()->getName(); | |||
8494 | QualType CastTy = llvm::StringSwitch<QualType>(Name) | |||
8495 | .Case("CFIndex", Context.getNSIntegerType()) | |||
8496 | .Case("NSInteger", Context.getNSIntegerType()) | |||
8497 | .Case("NSUInteger", Context.getNSUIntegerType()) | |||
8498 | .Case("SInt32", Context.IntTy) | |||
8499 | .Case("UInt32", Context.UnsignedIntTy) | |||
8500 | .Default(QualType()); | |||
8501 | ||||
8502 | if (!CastTy.isNull()) | |||
8503 | return std::make_pair(CastTy, Name); | |||
8504 | ||||
8505 | TyTy = UserTy->desugar(); | |||
8506 | } | |||
8507 | ||||
8508 | // Strip parens if necessary. | |||
8509 | if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) | |||
8510 | return shouldNotPrintDirectly(Context, | |||
8511 | PE->getSubExpr()->getType(), | |||
8512 | PE->getSubExpr()); | |||
8513 | ||||
8514 | // If this is a conditional expression, then its result type is constructed | |||
8515 | // via usual arithmetic conversions and thus there might be no necessary | |||
8516 | // typedef sugar there. Recurse to operands to check for NSInteger & | |||
8517 | // Co. usage condition. | |||
8518 | if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | |||
8519 | QualType TrueTy, FalseTy; | |||
8520 | StringRef TrueName, FalseName; | |||
8521 | ||||
8522 | std::tie(TrueTy, TrueName) = | |||
8523 | shouldNotPrintDirectly(Context, | |||
8524 | CO->getTrueExpr()->getType(), | |||
8525 | CO->getTrueExpr()); | |||
8526 | std::tie(FalseTy, FalseName) = | |||
8527 | shouldNotPrintDirectly(Context, | |||
8528 | CO->getFalseExpr()->getType(), | |||
8529 | CO->getFalseExpr()); | |||
8530 | ||||
8531 | if (TrueTy == FalseTy) | |||
8532 | return std::make_pair(TrueTy, TrueName); | |||
8533 | else if (TrueTy.isNull()) | |||
8534 | return std::make_pair(FalseTy, FalseName); | |||
8535 | else if (FalseTy.isNull()) | |||
8536 | return std::make_pair(TrueTy, TrueName); | |||
8537 | } | |||
8538 | ||||
8539 | return std::make_pair(QualType(), StringRef()); | |||
8540 | } | |||
8541 | ||||
8542 | /// Return true if \p ICE is an implicit argument promotion of an arithmetic | |||
8543 | /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked | |||
8544 | /// type do not count. | |||
8545 | static bool | |||
8546 | isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { | |||
8547 | QualType From = ICE->getSubExpr()->getType(); | |||
8548 | QualType To = ICE->getType(); | |||
8549 | // It's an integer promotion if the destination type is the promoted | |||
8550 | // source type. | |||
8551 | if (ICE->getCastKind() == CK_IntegralCast && | |||
8552 | From->isPromotableIntegerType() && | |||
8553 | S.Context.getPromotedIntegerType(From) == To) | |||
8554 | return true; | |||
8555 | // Look through vector types, since we do default argument promotion for | |||
8556 | // those in OpenCL. | |||
8557 | if (const auto *VecTy = From->getAs<ExtVectorType>()) | |||
8558 | From = VecTy->getElementType(); | |||
8559 | if (const auto *VecTy = To->getAs<ExtVectorType>()) | |||
8560 | To = VecTy->getElementType(); | |||
8561 | // It's a floating promotion if the source type is a lower rank. | |||
8562 | return ICE->getCastKind() == CK_FloatingCast && | |||
8563 | S.Context.getFloatingTypeOrder(From, To) < 0; | |||
8564 | } | |||
8565 | ||||
8566 | bool | |||
8567 | CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, | |||
8568 | const char *StartSpecifier, | |||
8569 | unsigned SpecifierLen, | |||
8570 | const Expr *E) { | |||
8571 | using namespace analyze_format_string; | |||
8572 | using namespace analyze_printf; | |||
8573 | ||||
8574 | // Now type check the data expression that matches the | |||
8575 | // format specifier. | |||
8576 | const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); | |||
8577 | if (!AT.isValid()) | |||
8578 | return true; | |||
8579 | ||||
8580 | QualType ExprTy = E->getType(); | |||
8581 | while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { | |||
8582 | ExprTy = TET->getUnderlyingExpr()->getType(); | |||
8583 | } | |||
8584 | ||||
8585 | // Diagnose attempts to print a boolean value as a character. Unlike other | |||
8586 | // -Wformat diagnostics, this is fine from a type perspective, but it still | |||
8587 | // doesn't make sense. | |||
8588 | if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && | |||
8589 | E->isKnownToHaveBooleanValue()) { | |||
8590 | const CharSourceRange &CSR = | |||
8591 | getSpecifierRange(StartSpecifier, SpecifierLen); | |||
8592 | SmallString<4> FSString; | |||
8593 | llvm::raw_svector_ostream os(FSString); | |||
8594 | FS.toString(os); | |||
8595 | EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) | |||
8596 | << FSString, | |||
8597 | E->getExprLoc(), false, CSR); | |||
8598 | return true; | |||
8599 | } | |||
8600 | ||||
8601 | analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); | |||
8602 | if (Match == analyze_printf::ArgType::Match) | |||
8603 | return true; | |||
8604 | ||||
8605 | // Look through argument promotions for our error message's reported type. | |||
8606 | // This includes the integral and floating promotions, but excludes array | |||
8607 | // and function pointer decay (seeing that an argument intended to be a | |||
8608 | // string has type 'char [6]' is probably more confusing than 'char *') and | |||
8609 | // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). | |||
8610 | if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { | |||
8611 | if (isArithmeticArgumentPromotion(S, ICE)) { | |||
8612 | E = ICE->getSubExpr(); | |||
8613 | ExprTy = E->getType(); | |||
8614 | ||||
8615 | // Check if we didn't match because of an implicit cast from a 'char' | |||
8616 | // or 'short' to an 'int'. This is done because printf is a varargs | |||
8617 | // function. | |||
8618 | if (ICE->getType() == S.Context.IntTy || | |||
8619 | ICE->getType() == S.Context.UnsignedIntTy) { | |||
8620 | // All further checking is done on the subexpression | |||
8621 | const analyze_printf::ArgType::MatchKind ImplicitMatch = | |||
8622 | AT.matchesType(S.Context, ExprTy); | |||
8623 | if (ImplicitMatch == analyze_printf::ArgType::Match) | |||
8624 | return true; | |||
8625 | if (ImplicitMatch == ArgType::NoMatchPedantic || | |||
8626 | ImplicitMatch == ArgType::NoMatchTypeConfusion) | |||
8627 | Match = ImplicitMatch; | |||
8628 | } | |||
8629 | } | |||
8630 | } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { | |||
8631 | // Special case for 'a', which has type 'int' in C. | |||
8632 | // Note, however, that we do /not/ want to treat multibyte constants like | |||
8633 | // 'MooV' as characters! This form is deprecated but still exists. | |||
8634 | if (ExprTy == S.Context.IntTy) | |||
8635 | if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) | |||
8636 | ExprTy = S.Context.CharTy; | |||
8637 | } | |||
8638 | ||||
8639 | // Look through enums to their underlying type. | |||
8640 | bool IsEnum = false; | |||
8641 | if (auto EnumTy = ExprTy->getAs<EnumType>()) { | |||
8642 | ExprTy = EnumTy->getDecl()->getIntegerType(); | |||
8643 | IsEnum = true; | |||
8644 | } | |||
8645 | ||||
8646 | // %C in an Objective-C context prints a unichar, not a wchar_t. | |||
8647 | // If the argument is an integer of some kind, believe the %C and suggest | |||
8648 | // a cast instead of changing the conversion specifier. | |||
8649 | QualType IntendedTy = ExprTy; | |||
8650 | if (isObjCContext() && | |||
8651 | FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { | |||
8652 | if (ExprTy->isIntegralOrUnscopedEnumerationType() && | |||
8653 | !ExprTy->isCharType()) { | |||
8654 | // 'unichar' is defined as a typedef of unsigned short, but we should | |||
8655 | // prefer using the typedef if it is visible. | |||
8656 | IntendedTy = S.Context.UnsignedShortTy; | |||
8657 | ||||
8658 | // While we are here, check if the value is an IntegerLiteral that happens | |||
8659 | // to be within the valid range. | |||
8660 | if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { | |||
8661 | const llvm::APInt &V = IL->getValue(); | |||
8662 | if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) | |||
8663 | return true; | |||
8664 | } | |||
8665 | ||||
8666 | LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), | |||
8667 | Sema::LookupOrdinaryName); | |||
8668 | if (S.LookupName(Result, S.getCurScope())) { | |||
8669 | NamedDecl *ND = Result.getFoundDecl(); | |||
8670 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) | |||
8671 | if (TD->getUnderlyingType() == IntendedTy) | |||
8672 | IntendedTy = S.Context.getTypedefType(TD); | |||
8673 | } | |||
8674 | } | |||
8675 | } | |||
8676 | ||||
8677 | // Special-case some of Darwin's platform-independence types by suggesting | |||
8678 | // casts to primitive types that are known to be large enough. | |||
8679 | bool ShouldNotPrintDirectly = false; StringRef CastTyName; | |||
8680 | if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { | |||
8681 | QualType CastTy; | |||
8682 | std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); | |||
8683 | if (!CastTy.isNull()) { | |||
8684 | // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int | |||
8685 | // (long in ASTContext). Only complain to pedants. | |||
8686 | if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && | |||
8687 | (AT.isSizeT() || AT.isPtrdiffT()) && | |||
8688 | AT.matchesType(S.Context, CastTy)) | |||
8689 | Match = ArgType::NoMatchPedantic; | |||
8690 | IntendedTy = CastTy; | |||
8691 | ShouldNotPrintDirectly = true; | |||
8692 | } | |||
8693 | } | |||
8694 | ||||
8695 | // We may be able to offer a FixItHint if it is a supported type. | |||
8696 | PrintfSpecifier fixedFS = FS; | |||
8697 | bool Success = | |||
8698 | fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); | |||
8699 | ||||
8700 | if (Success) { | |||
8701 | // Get the fix string from the fixed format specifier | |||
8702 | SmallString<16> buf; | |||
8703 | llvm::raw_svector_ostream os(buf); | |||
8704 | fixedFS.toString(os); | |||
8705 | ||||
8706 | CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); | |||
8707 | ||||
8708 | if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { | |||
8709 | unsigned Diag; | |||
8710 | switch (Match) { | |||
8711 | case ArgType::Match: llvm_unreachable("expected non-matching")::llvm::llvm_unreachable_internal("expected non-matching", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 8711); | |||
8712 | case ArgType::NoMatchPedantic: | |||
8713 | Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; | |||
8714 | break; | |||
8715 | case ArgType::NoMatchTypeConfusion: | |||
8716 | Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; | |||
8717 | break; | |||
8718 | case ArgType::NoMatch: | |||
8719 | Diag = diag::warn_format_conversion_argument_type_mismatch; | |||
8720 | break; | |||
8721 | } | |||
8722 | ||||
8723 | // In this case, the specifier is wrong and should be changed to match | |||
8724 | // the argument. | |||
8725 | EmitFormatDiagnostic(S.PDiag(Diag) | |||
8726 | << AT.getRepresentativeTypeName(S.Context) | |||
8727 | << IntendedTy << IsEnum << E->getSourceRange(), | |||
8728 | E->getBeginLoc(), | |||
8729 | /*IsStringLocation*/ false, SpecRange, | |||
8730 | FixItHint::CreateReplacement(SpecRange, os.str())); | |||
8731 | } else { | |||
8732 | // The canonical type for formatting this value is different from the | |||
8733 | // actual type of the expression. (This occurs, for example, with Darwin's | |||
8734 | // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but | |||
8735 | // should be printed as 'long' for 64-bit compatibility.) | |||
8736 | // Rather than emitting a normal format/argument mismatch, we want to | |||
8737 | // add a cast to the recommended type (and correct the format string | |||
8738 | // if necessary). | |||
8739 | SmallString<16> CastBuf; | |||
8740 | llvm::raw_svector_ostream CastFix(CastBuf); | |||
8741 | CastFix << "("; | |||
8742 | IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); | |||
8743 | CastFix << ")"; | |||
8744 | ||||
8745 | SmallVector<FixItHint,4> Hints; | |||
8746 | if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) | |||
8747 | Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); | |||
8748 | ||||
8749 | if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { | |||
8750 | // If there's already a cast present, just replace it. | |||
8751 | SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); | |||
8752 | Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); | |||
8753 | ||||
8754 | } else if (!requiresParensToAddCast(E)) { | |||
8755 | // If the expression has high enough precedence, | |||
8756 | // just write the C-style cast. | |||
8757 | Hints.push_back( | |||
8758 | FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); | |||
8759 | } else { | |||
8760 | // Otherwise, add parens around the expression as well as the cast. | |||
8761 | CastFix << "("; | |||
8762 | Hints.push_back( | |||
8763 | FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); | |||
8764 | ||||
8765 | SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); | |||
8766 | Hints.push_back(FixItHint::CreateInsertion(After, ")")); | |||
8767 | } | |||
8768 | ||||
8769 | if (ShouldNotPrintDirectly) { | |||
8770 | // The expression has a type that should not be printed directly. | |||
8771 | // We extract the name from the typedef because we don't want to show | |||
8772 | // the underlying type in the diagnostic. | |||
8773 | StringRef Name; | |||
8774 | if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) | |||
8775 | Name = TypedefTy->getDecl()->getName(); | |||
8776 | else | |||
8777 | Name = CastTyName; | |||
8778 | unsigned Diag = Match == ArgType::NoMatchPedantic | |||
8779 | ? diag::warn_format_argument_needs_cast_pedantic | |||
8780 | : diag::warn_format_argument_needs_cast; | |||
8781 | EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum | |||
8782 | << E->getSourceRange(), | |||
8783 | E->getBeginLoc(), /*IsStringLocation=*/false, | |||
8784 | SpecRange, Hints); | |||
8785 | } else { | |||
8786 | // In this case, the expression could be printed using a different | |||
8787 | // specifier, but we've decided that the specifier is probably correct | |||
8788 | // and we should cast instead. Just use the normal warning message. | |||
8789 | EmitFormatDiagnostic( | |||
8790 | S.PDiag(diag::warn_format_conversion_argument_type_mismatch) | |||
8791 | << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum | |||
8792 | << E->getSourceRange(), | |||
8793 | E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); | |||
8794 | } | |||
8795 | } | |||
8796 | } else { | |||
8797 | const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, | |||
8798 | SpecifierLen); | |||
8799 | // Since the warning for passing non-POD types to variadic functions | |||
8800 | // was deferred until now, we emit a warning for non-POD | |||
8801 | // arguments here. | |||
8802 | switch (S.isValidVarArgType(ExprTy)) { | |||
8803 | case Sema::VAK_Valid: | |||
8804 | case Sema::VAK_ValidInCXX11: { | |||
8805 | unsigned Diag; | |||
8806 | switch (Match) { | |||
8807 | case ArgType::Match: llvm_unreachable("expected non-matching")::llvm::llvm_unreachable_internal("expected non-matching", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 8807); | |||
8808 | case ArgType::NoMatchPedantic: | |||
8809 | Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; | |||
8810 | break; | |||
8811 | case ArgType::NoMatchTypeConfusion: | |||
8812 | Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; | |||
8813 | break; | |||
8814 | case ArgType::NoMatch: | |||
8815 | Diag = diag::warn_format_conversion_argument_type_mismatch; | |||
8816 | break; | |||
8817 | } | |||
8818 | ||||
8819 | EmitFormatDiagnostic( | |||
8820 | S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy | |||
8821 | << IsEnum << CSR << E->getSourceRange(), | |||
8822 | E->getBeginLoc(), /*IsStringLocation*/ false, CSR); | |||
8823 | break; | |||
8824 | } | |||
8825 | case Sema::VAK_Undefined: | |||
8826 | case Sema::VAK_MSVCUndefined: | |||
8827 | EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) | |||
8828 | << S.getLangOpts().CPlusPlus11 << ExprTy | |||
8829 | << CallType | |||
8830 | << AT.getRepresentativeTypeName(S.Context) << CSR | |||
8831 | << E->getSourceRange(), | |||
8832 | E->getBeginLoc(), /*IsStringLocation*/ false, CSR); | |||
8833 | checkForCStrMembers(AT, E); | |||
8834 | break; | |||
8835 | ||||
8836 | case Sema::VAK_Invalid: | |||
8837 | if (ExprTy->isObjCObjectType()) | |||
8838 | EmitFormatDiagnostic( | |||
8839 | S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) | |||
8840 | << S.getLangOpts().CPlusPlus11 << ExprTy << CallType | |||
8841 | << AT.getRepresentativeTypeName(S.Context) << CSR | |||
8842 | << E->getSourceRange(), | |||
8843 | E->getBeginLoc(), /*IsStringLocation*/ false, CSR); | |||
8844 | else | |||
8845 | // FIXME: If this is an initializer list, suggest removing the braces | |||
8846 | // or inserting a cast to the target type. | |||
8847 | S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) | |||
8848 | << isa<InitListExpr>(E) << ExprTy << CallType | |||
8849 | << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); | |||
8850 | break; | |||
8851 | } | |||
8852 | ||||
8853 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 8854, __PRETTY_FUNCTION__)) | |||
8854 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 8854, __PRETTY_FUNCTION__)); | |||
8855 | CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; | |||
8856 | } | |||
8857 | ||||
8858 | return true; | |||
8859 | } | |||
8860 | ||||
8861 | //===--- CHECK: Scanf format string checking ------------------------------===// | |||
8862 | ||||
8863 | namespace { | |||
8864 | ||||
8865 | class CheckScanfHandler : public CheckFormatHandler { | |||
8866 | public: | |||
8867 | CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, | |||
8868 | const Expr *origFormatExpr, Sema::FormatStringType type, | |||
8869 | unsigned firstDataArg, unsigned numDataArgs, | |||
8870 | const char *beg, bool hasVAListArg, | |||
8871 | ArrayRef<const Expr *> Args, unsigned formatIdx, | |||
8872 | bool inFunctionCall, Sema::VariadicCallType CallType, | |||
8873 | llvm::SmallBitVector &CheckedVarArgs, | |||
8874 | UncoveredArgHandler &UncoveredArg) | |||
8875 | : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, | |||
8876 | numDataArgs, beg, hasVAListArg, Args, formatIdx, | |||
8877 | inFunctionCall, CallType, CheckedVarArgs, | |||
8878 | UncoveredArg) {} | |||
8879 | ||||
8880 | bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, | |||
8881 | const char *startSpecifier, | |||
8882 | unsigned specifierLen) override; | |||
8883 | ||||
8884 | bool HandleInvalidScanfConversionSpecifier( | |||
8885 | const analyze_scanf::ScanfSpecifier &FS, | |||
8886 | const char *startSpecifier, | |||
8887 | unsigned specifierLen) override; | |||
8888 | ||||
8889 | void HandleIncompleteScanList(const char *start, const char *end) override; | |||
8890 | }; | |||
8891 | ||||
8892 | } // namespace | |||
8893 | ||||
8894 | void CheckScanfHandler::HandleIncompleteScanList(const char *start, | |||
8895 | const char *end) { | |||
8896 | EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), | |||
8897 | getLocationOfByte(end), /*IsStringLocation*/true, | |||
8898 | getSpecifierRange(start, end - start)); | |||
8899 | } | |||
8900 | ||||
8901 | bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( | |||
8902 | const analyze_scanf::ScanfSpecifier &FS, | |||
8903 | const char *startSpecifier, | |||
8904 | unsigned specifierLen) { | |||
8905 | const analyze_scanf::ScanfConversionSpecifier &CS = | |||
8906 | FS.getConversionSpecifier(); | |||
8907 | ||||
8908 | return HandleInvalidConversionSpecifier(FS.getArgIndex(), | |||
8909 | getLocationOfByte(CS.getStart()), | |||
8910 | startSpecifier, specifierLen, | |||
8911 | CS.getStart(), CS.getLength()); | |||
8912 | } | |||
8913 | ||||
8914 | bool CheckScanfHandler::HandleScanfSpecifier( | |||
8915 | const analyze_scanf::ScanfSpecifier &FS, | |||
8916 | const char *startSpecifier, | |||
8917 | unsigned specifierLen) { | |||
8918 | using namespace analyze_scanf; | |||
8919 | using namespace analyze_format_string; | |||
8920 | ||||
8921 | const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); | |||
8922 | ||||
8923 | // Handle case where '%' and '*' don't consume an argument. These shouldn't | |||
8924 | // be used to decide if we are using positional arguments consistently. | |||
8925 | if (FS.consumesDataArgument()) { | |||
8926 | if (atFirstArg) { | |||
8927 | atFirstArg = false; | |||
8928 | usesPositionalArgs = FS.usesPositionalArg(); | |||
8929 | } | |||
8930 | else if (usesPositionalArgs != FS.usesPositionalArg()) { | |||
8931 | HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), | |||
8932 | startSpecifier, specifierLen); | |||
8933 | return false; | |||
8934 | } | |||
8935 | } | |||
8936 | ||||
8937 | // Check if the field with is non-zero. | |||
8938 | const OptionalAmount &Amt = FS.getFieldWidth(); | |||
8939 | if (Amt.getHowSpecified() == OptionalAmount::Constant) { | |||
8940 | if (Amt.getConstantAmount() == 0) { | |||
8941 | const CharSourceRange &R = getSpecifierRange(Amt.getStart(), | |||
8942 | Amt.getConstantLength()); | |||
8943 | EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), | |||
8944 | getLocationOfByte(Amt.getStart()), | |||
8945 | /*IsStringLocation*/true, R, | |||
8946 | FixItHint::CreateRemoval(R)); | |||
8947 | } | |||
8948 | } | |||
8949 | ||||
8950 | if (!FS.consumesDataArgument()) { | |||
8951 | // FIXME: Technically specifying a precision or field width here | |||
8952 | // makes no sense. Worth issuing a warning at some point. | |||
8953 | return true; | |||
8954 | } | |||
8955 | ||||
8956 | // Consume the argument. | |||
8957 | unsigned argIndex = FS.getArgIndex(); | |||
8958 | if (argIndex < NumDataArgs) { | |||
8959 | // The check to see if the argIndex is valid will come later. | |||
8960 | // We set the bit here because we may exit early from this | |||
8961 | // function if we encounter some other error. | |||
8962 | CoveredArgs.set(argIndex); | |||
8963 | } | |||
8964 | ||||
8965 | // Check the length modifier is valid with the given conversion specifier. | |||
8966 | if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), | |||
8967 | S.getLangOpts())) | |||
8968 | HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, | |||
8969 | diag::warn_format_nonsensical_length); | |||
8970 | else if (!FS.hasStandardLengthModifier()) | |||
8971 | HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); | |||
8972 | else if (!FS.hasStandardLengthConversionCombination()) | |||
8973 | HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, | |||
8974 | diag::warn_format_non_standard_conversion_spec); | |||
8975 | ||||
8976 | if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) | |||
8977 | HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); | |||
8978 | ||||
8979 | // The remaining checks depend on the data arguments. | |||
8980 | if (HasVAListArg) | |||
8981 | return true; | |||
8982 | ||||
8983 | if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) | |||
8984 | return false; | |||
8985 | ||||
8986 | // Check that the argument type matches the format specifier. | |||
8987 | const Expr *Ex = getDataArg(argIndex); | |||
8988 | if (!Ex) | |||
8989 | return true; | |||
8990 | ||||
8991 | const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); | |||
8992 | ||||
8993 | if (!AT.isValid()) { | |||
8994 | return true; | |||
8995 | } | |||
8996 | ||||
8997 | analyze_format_string::ArgType::MatchKind Match = | |||
8998 | AT.matchesType(S.Context, Ex->getType()); | |||
8999 | bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; | |||
9000 | if (Match == analyze_format_string::ArgType::Match) | |||
9001 | return true; | |||
9002 | ||||
9003 | ScanfSpecifier fixedFS = FS; | |||
9004 | bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), | |||
9005 | S.getLangOpts(), S.Context); | |||
9006 | ||||
9007 | unsigned Diag = | |||
9008 | Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic | |||
9009 | : diag::warn_format_conversion_argument_type_mismatch; | |||
9010 | ||||
9011 | if (Success) { | |||
9012 | // Get the fix string from the fixed format specifier. | |||
9013 | SmallString<128> buf; | |||
9014 | llvm::raw_svector_ostream os(buf); | |||
9015 | fixedFS.toString(os); | |||
9016 | ||||
9017 | EmitFormatDiagnostic( | |||
9018 | S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) | |||
9019 | << Ex->getType() << false << Ex->getSourceRange(), | |||
9020 | Ex->getBeginLoc(), | |||
9021 | /*IsStringLocation*/ false, | |||
9022 | getSpecifierRange(startSpecifier, specifierLen), | |||
9023 | FixItHint::CreateReplacement( | |||
9024 | getSpecifierRange(startSpecifier, specifierLen), os.str())); | |||
9025 | } else { | |||
9026 | EmitFormatDiagnostic(S.PDiag(Diag) | |||
9027 | << AT.getRepresentativeTypeName(S.Context) | |||
9028 | << Ex->getType() << false << Ex->getSourceRange(), | |||
9029 | Ex->getBeginLoc(), | |||
9030 | /*IsStringLocation*/ false, | |||
9031 | getSpecifierRange(startSpecifier, specifierLen)); | |||
9032 | } | |||
9033 | ||||
9034 | return true; | |||
9035 | } | |||
9036 | ||||
9037 | static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, | |||
9038 | const Expr *OrigFormatExpr, | |||
9039 | ArrayRef<const Expr *> Args, | |||
9040 | bool HasVAListArg, unsigned format_idx, | |||
9041 | unsigned firstDataArg, | |||
9042 | Sema::FormatStringType Type, | |||
9043 | bool inFunctionCall, | |||
9044 | Sema::VariadicCallType CallType, | |||
9045 | llvm::SmallBitVector &CheckedVarArgs, | |||
9046 | UncoveredArgHandler &UncoveredArg, | |||
9047 | bool IgnoreStringsWithoutSpecifiers) { | |||
9048 | // CHECK: is the format string a wide literal? | |||
9049 | if (!FExpr->isAscii() && !FExpr->isUTF8()) { | |||
9050 | CheckFormatHandler::EmitFormatDiagnostic( | |||
9051 | S, inFunctionCall, Args[format_idx], | |||
9052 | S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), | |||
9053 | /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); | |||
9054 | return; | |||
9055 | } | |||
9056 | ||||
9057 | // Str - The format string. NOTE: this is NOT null-terminated! | |||
9058 | StringRef StrRef = FExpr->getString(); | |||
9059 | const char *Str = StrRef.data(); | |||
9060 | // Account for cases where the string literal is truncated in a declaration. | |||
9061 | const ConstantArrayType *T = | |||
9062 | S.Context.getAsConstantArrayType(FExpr->getType()); | |||
9063 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 9063, __PRETTY_FUNCTION__)); | |||
9064 | size_t TypeSize = T->getSize().getZExtValue(); | |||
9065 | size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); | |||
9066 | const unsigned numDataArgs = Args.size() - firstDataArg; | |||
9067 | ||||
9068 | if (IgnoreStringsWithoutSpecifiers && | |||
9069 | !analyze_format_string::parseFormatStringHasFormattingSpecifiers( | |||
9070 | Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) | |||
9071 | return; | |||
9072 | ||||
9073 | // Emit a warning if the string literal is truncated and does not contain an | |||
9074 | // embedded null character. | |||
9075 | if (TypeSize <= StrRef.size() && | |||
9076 | StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { | |||
9077 | CheckFormatHandler::EmitFormatDiagnostic( | |||
9078 | S, inFunctionCall, Args[format_idx], | |||
9079 | S.PDiag(diag::warn_printf_format_string_not_null_terminated), | |||
9080 | FExpr->getBeginLoc(), | |||
9081 | /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); | |||
9082 | return; | |||
9083 | } | |||
9084 | ||||
9085 | // CHECK: empty format string? | |||
9086 | if (StrLen == 0 && numDataArgs > 0) { | |||
9087 | CheckFormatHandler::EmitFormatDiagnostic( | |||
9088 | S, inFunctionCall, Args[format_idx], | |||
9089 | S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), | |||
9090 | /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); | |||
9091 | return; | |||
9092 | } | |||
9093 | ||||
9094 | if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || | |||
9095 | Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || | |||
9096 | Type == Sema::FST_OSTrace) { | |||
9097 | CheckPrintfHandler H( | |||
9098 | S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, | |||
9099 | (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, | |||
9100 | HasVAListArg, Args, format_idx, inFunctionCall, CallType, | |||
9101 | CheckedVarArgs, UncoveredArg); | |||
9102 | ||||
9103 | if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, | |||
9104 | S.getLangOpts(), | |||
9105 | S.Context.getTargetInfo(), | |||
9106 | Type == Sema::FST_FreeBSDKPrintf)) | |||
9107 | H.DoneProcessing(); | |||
9108 | } else if (Type == Sema::FST_Scanf) { | |||
9109 | CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, | |||
9110 | numDataArgs, Str, HasVAListArg, Args, format_idx, | |||
9111 | inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); | |||
9112 | ||||
9113 | if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, | |||
9114 | S.getLangOpts(), | |||
9115 | S.Context.getTargetInfo())) | |||
9116 | H.DoneProcessing(); | |||
9117 | } // TODO: handle other formats | |||
9118 | } | |||
9119 | ||||
9120 | bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { | |||
9121 | // Str - The format string. NOTE: this is NOT null-terminated! | |||
9122 | StringRef StrRef = FExpr->getString(); | |||
9123 | const char *Str = StrRef.data(); | |||
9124 | // Account for cases where the string literal is truncated in a declaration. | |||
9125 | const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); | |||
9126 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 9126, __PRETTY_FUNCTION__)); | |||
9127 | size_t TypeSize = T->getSize().getZExtValue(); | |||
9128 | size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); | |||
9129 | return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, | |||
9130 | getLangOpts(), | |||
9131 | Context.getTargetInfo()); | |||
9132 | } | |||
9133 | ||||
9134 | //===--- CHECK: Warn on use of wrong absolute value function. -------------===// | |||
9135 | ||||
9136 | // Returns the related absolute value function that is larger, of 0 if one | |||
9137 | // does not exist. | |||
9138 | static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { | |||
9139 | switch (AbsFunction) { | |||
9140 | default: | |||
9141 | return 0; | |||
9142 | ||||
9143 | case Builtin::BI__builtin_abs: | |||
9144 | return Builtin::BI__builtin_labs; | |||
9145 | case Builtin::BI__builtin_labs: | |||
9146 | return Builtin::BI__builtin_llabs; | |||
9147 | case Builtin::BI__builtin_llabs: | |||
9148 | return 0; | |||
9149 | ||||
9150 | case Builtin::BI__builtin_fabsf: | |||
9151 | return Builtin::BI__builtin_fabs; | |||
9152 | case Builtin::BI__builtin_fabs: | |||
9153 | return Builtin::BI__builtin_fabsl; | |||
9154 | case Builtin::BI__builtin_fabsl: | |||
9155 | return 0; | |||
9156 | ||||
9157 | case Builtin::BI__builtin_cabsf: | |||
9158 | return Builtin::BI__builtin_cabs; | |||
9159 | case Builtin::BI__builtin_cabs: | |||
9160 | return Builtin::BI__builtin_cabsl; | |||
9161 | case Builtin::BI__builtin_cabsl: | |||
9162 | return 0; | |||
9163 | ||||
9164 | case Builtin::BIabs: | |||
9165 | return Builtin::BIlabs; | |||
9166 | case Builtin::BIlabs: | |||
9167 | return Builtin::BIllabs; | |||
9168 | case Builtin::BIllabs: | |||
9169 | return 0; | |||
9170 | ||||
9171 | case Builtin::BIfabsf: | |||
9172 | return Builtin::BIfabs; | |||
9173 | case Builtin::BIfabs: | |||
9174 | return Builtin::BIfabsl; | |||
9175 | case Builtin::BIfabsl: | |||
9176 | return 0; | |||
9177 | ||||
9178 | case Builtin::BIcabsf: | |||
9179 | return Builtin::BIcabs; | |||
9180 | case Builtin::BIcabs: | |||
9181 | return Builtin::BIcabsl; | |||
9182 | case Builtin::BIcabsl: | |||
9183 | return 0; | |||
9184 | } | |||
9185 | } | |||
9186 | ||||
9187 | // Returns the argument type of the absolute value function. | |||
9188 | static QualType getAbsoluteValueArgumentType(ASTContext &Context, | |||
9189 | unsigned AbsType) { | |||
9190 | if (AbsType == 0) | |||
9191 | return QualType(); | |||
9192 | ||||
9193 | ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; | |||
9194 | QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); | |||
9195 | if (Error != ASTContext::GE_None) | |||
9196 | return QualType(); | |||
9197 | ||||
9198 | const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); | |||
9199 | if (!FT) | |||
9200 | return QualType(); | |||
9201 | ||||
9202 | if (FT->getNumParams() != 1) | |||
9203 | return QualType(); | |||
9204 | ||||
9205 | return FT->getParamType(0); | |||
9206 | } | |||
9207 | ||||
9208 | // Returns the best absolute value function, or zero, based on type and | |||
9209 | // current absolute value function. | |||
9210 | static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, | |||
9211 | unsigned AbsFunctionKind) { | |||
9212 | unsigned BestKind = 0; | |||
9213 | uint64_t ArgSize = Context.getTypeSize(ArgType); | |||
9214 | for (unsigned Kind = AbsFunctionKind; Kind != 0; | |||
9215 | Kind = getLargerAbsoluteValueFunction(Kind)) { | |||
9216 | QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); | |||
9217 | if (Context.getTypeSize(ParamType) >= ArgSize) { | |||
9218 | if (BestKind == 0) | |||
9219 | BestKind = Kind; | |||
9220 | else if (Context.hasSameType(ParamType, ArgType)) { | |||
9221 | BestKind = Kind; | |||
9222 | break; | |||
9223 | } | |||
9224 | } | |||
9225 | } | |||
9226 | return BestKind; | |||
9227 | } | |||
9228 | ||||
9229 | enum AbsoluteValueKind { | |||
9230 | AVK_Integer, | |||
9231 | AVK_Floating, | |||
9232 | AVK_Complex | |||
9233 | }; | |||
9234 | ||||
9235 | static AbsoluteValueKind getAbsoluteValueKind(QualType T) { | |||
9236 | if (T->isIntegralOrEnumerationType()) | |||
9237 | return AVK_Integer; | |||
9238 | if (T->isRealFloatingType()) | |||
9239 | return AVK_Floating; | |||
9240 | if (T->isAnyComplexType()) | |||
9241 | return AVK_Complex; | |||
9242 | ||||
9243 | llvm_unreachable("Type not integer, floating, or complex")::llvm::llvm_unreachable_internal("Type not integer, floating, or complex" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 9243); | |||
9244 | } | |||
9245 | ||||
9246 | // Changes the absolute value function to a different type. Preserves whether | |||
9247 | // the function is a builtin. | |||
9248 | static unsigned changeAbsFunction(unsigned AbsKind, | |||
9249 | AbsoluteValueKind ValueKind) { | |||
9250 | switch (ValueKind) { | |||
9251 | case AVK_Integer: | |||
9252 | switch (AbsKind) { | |||
9253 | default: | |||
9254 | return 0; | |||
9255 | case Builtin::BI__builtin_fabsf: | |||
9256 | case Builtin::BI__builtin_fabs: | |||
9257 | case Builtin::BI__builtin_fabsl: | |||
9258 | case Builtin::BI__builtin_cabsf: | |||
9259 | case Builtin::BI__builtin_cabs: | |||
9260 | case Builtin::BI__builtin_cabsl: | |||
9261 | return Builtin::BI__builtin_abs; | |||
9262 | case Builtin::BIfabsf: | |||
9263 | case Builtin::BIfabs: | |||
9264 | case Builtin::BIfabsl: | |||
9265 | case Builtin::BIcabsf: | |||
9266 | case Builtin::BIcabs: | |||
9267 | case Builtin::BIcabsl: | |||
9268 | return Builtin::BIabs; | |||
9269 | } | |||
9270 | case AVK_Floating: | |||
9271 | switch (AbsKind) { | |||
9272 | default: | |||
9273 | return 0; | |||
9274 | case Builtin::BI__builtin_abs: | |||
9275 | case Builtin::BI__builtin_labs: | |||
9276 | case Builtin::BI__builtin_llabs: | |||
9277 | case Builtin::BI__builtin_cabsf: | |||
9278 | case Builtin::BI__builtin_cabs: | |||
9279 | case Builtin::BI__builtin_cabsl: | |||
9280 | return Builtin::BI__builtin_fabsf; | |||
9281 | case Builtin::BIabs: | |||
9282 | case Builtin::BIlabs: | |||
9283 | case Builtin::BIllabs: | |||
9284 | case Builtin::BIcabsf: | |||
9285 | case Builtin::BIcabs: | |||
9286 | case Builtin::BIcabsl: | |||
9287 | return Builtin::BIfabsf; | |||
9288 | } | |||
9289 | case AVK_Complex: | |||
9290 | switch (AbsKind) { | |||
9291 | default: | |||
9292 | return 0; | |||
9293 | case Builtin::BI__builtin_abs: | |||
9294 | case Builtin::BI__builtin_labs: | |||
9295 | case Builtin::BI__builtin_llabs: | |||
9296 | case Builtin::BI__builtin_fabsf: | |||
9297 | case Builtin::BI__builtin_fabs: | |||
9298 | case Builtin::BI__builtin_fabsl: | |||
9299 | return Builtin::BI__builtin_cabsf; | |||
9300 | case Builtin::BIabs: | |||
9301 | case Builtin::BIlabs: | |||
9302 | case Builtin::BIllabs: | |||
9303 | case Builtin::BIfabsf: | |||
9304 | case Builtin::BIfabs: | |||
9305 | case Builtin::BIfabsl: | |||
9306 | return Builtin::BIcabsf; | |||
9307 | } | |||
9308 | } | |||
9309 | llvm_unreachable("Unable to convert function")::llvm::llvm_unreachable_internal("Unable to convert function" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 9309); | |||
9310 | } | |||
9311 | ||||
9312 | static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { | |||
9313 | const IdentifierInfo *FnInfo = FDecl->getIdentifier(); | |||
9314 | if (!FnInfo) | |||
9315 | return 0; | |||
9316 | ||||
9317 | switch (FDecl->getBuiltinID()) { | |||
9318 | default: | |||
9319 | return 0; | |||
9320 | case Builtin::BI__builtin_abs: | |||
9321 | case Builtin::BI__builtin_fabs: | |||
9322 | case Builtin::BI__builtin_fabsf: | |||
9323 | case Builtin::BI__builtin_fabsl: | |||
9324 | case Builtin::BI__builtin_labs: | |||
9325 | case Builtin::BI__builtin_llabs: | |||
9326 | case Builtin::BI__builtin_cabs: | |||
9327 | case Builtin::BI__builtin_cabsf: | |||
9328 | case Builtin::BI__builtin_cabsl: | |||
9329 | case Builtin::BIabs: | |||
9330 | case Builtin::BIlabs: | |||
9331 | case Builtin::BIllabs: | |||
9332 | case Builtin::BIfabs: | |||
9333 | case Builtin::BIfabsf: | |||
9334 | case Builtin::BIfabsl: | |||
9335 | case Builtin::BIcabs: | |||
9336 | case Builtin::BIcabsf: | |||
9337 | case Builtin::BIcabsl: | |||
9338 | return FDecl->getBuiltinID(); | |||
9339 | } | |||
9340 | llvm_unreachable("Unknown Builtin type")::llvm::llvm_unreachable_internal("Unknown Builtin type", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 9340); | |||
9341 | } | |||
9342 | ||||
9343 | // If the replacement is valid, emit a note with replacement function. | |||
9344 | // Additionally, suggest including the proper header if not already included. | |||
9345 | static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, | |||
9346 | unsigned AbsKind, QualType ArgType) { | |||
9347 | bool EmitHeaderHint = true; | |||
9348 | const char *HeaderName = nullptr; | |||
9349 | const char *FunctionName = nullptr; | |||
9350 | if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { | |||
9351 | FunctionName = "std::abs"; | |||
9352 | if (ArgType->isIntegralOrEnumerationType()) { | |||
9353 | HeaderName = "cstdlib"; | |||
9354 | } else if (ArgType->isRealFloatingType()) { | |||
9355 | HeaderName = "cmath"; | |||
9356 | } else { | |||
9357 | llvm_unreachable("Invalid Type")::llvm::llvm_unreachable_internal("Invalid Type", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 9357); | |||
9358 | } | |||
9359 | ||||
9360 | // Lookup all std::abs | |||
9361 | if (NamespaceDecl *Std = S.getStdNamespace()) { | |||
9362 | LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); | |||
9363 | R.suppressDiagnostics(); | |||
9364 | S.LookupQualifiedName(R, Std); | |||
9365 | ||||
9366 | for (const auto *I : R) { | |||
9367 | const FunctionDecl *FDecl = nullptr; | |||
9368 | if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { | |||
9369 | FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); | |||
9370 | } else { | |||
9371 | FDecl = dyn_cast<FunctionDecl>(I); | |||
9372 | } | |||
9373 | if (!FDecl) | |||
9374 | continue; | |||
9375 | ||||
9376 | // Found std::abs(), check that they are the right ones. | |||
9377 | if (FDecl->getNumParams() != 1) | |||
9378 | continue; | |||
9379 | ||||
9380 | // Check that the parameter type can handle the argument. | |||
9381 | QualType ParamType = FDecl->getParamDecl(0)->getType(); | |||
9382 | if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && | |||
9383 | S.Context.getTypeSize(ArgType) <= | |||
9384 | S.Context.getTypeSize(ParamType)) { | |||
9385 | // Found a function, don't need the header hint. | |||
9386 | EmitHeaderHint = false; | |||
9387 | break; | |||
9388 | } | |||
9389 | } | |||
9390 | } | |||
9391 | } else { | |||
9392 | FunctionName = S.Context.BuiltinInfo.getName(AbsKind); | |||
9393 | HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); | |||
9394 | ||||
9395 | if (HeaderName) { | |||
9396 | DeclarationName DN(&S.Context.Idents.get(FunctionName)); | |||
9397 | LookupResult R(S, DN, Loc, Sema::LookupAnyName); | |||
9398 | R.suppressDiagnostics(); | |||
9399 | S.LookupName(R, S.getCurScope()); | |||
9400 | ||||
9401 | if (R.isSingleResult()) { | |||
9402 | FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | |||
9403 | if (FD && FD->getBuiltinID() == AbsKind) { | |||
9404 | EmitHeaderHint = false; | |||
9405 | } else { | |||
9406 | return; | |||
9407 | } | |||
9408 | } else if (!R.empty()) { | |||
9409 | return; | |||
9410 | } | |||
9411 | } | |||
9412 | } | |||
9413 | ||||
9414 | S.Diag(Loc, diag::note_replace_abs_function) | |||
9415 | << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); | |||
9416 | ||||
9417 | if (!HeaderName) | |||
9418 | return; | |||
9419 | ||||
9420 | if (!EmitHeaderHint) | |||
9421 | return; | |||
9422 | ||||
9423 | S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName | |||
9424 | << FunctionName; | |||
9425 | } | |||
9426 | ||||
9427 | template <std::size_t StrLen> | |||
9428 | static bool IsStdFunction(const FunctionDecl *FDecl, | |||
9429 | const char (&Str)[StrLen]) { | |||
9430 | if (!FDecl) | |||
9431 | return false; | |||
9432 | if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) | |||
9433 | return false; | |||
9434 | if (!FDecl->isInStdNamespace()) | |||
9435 | return false; | |||
9436 | ||||
9437 | return true; | |||
9438 | } | |||
9439 | ||||
9440 | // Warn when using the wrong abs() function. | |||
9441 | void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, | |||
9442 | const FunctionDecl *FDecl) { | |||
9443 | if (Call->getNumArgs() != 1) | |||
9444 | return; | |||
9445 | ||||
9446 | unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); | |||
9447 | bool IsStdAbs = IsStdFunction(FDecl, "abs"); | |||
9448 | if (AbsKind == 0 && !IsStdAbs) | |||
9449 | return; | |||
9450 | ||||
9451 | QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); | |||
9452 | QualType ParamType = Call->getArg(0)->getType(); | |||
9453 | ||||
9454 | // Unsigned types cannot be negative. Suggest removing the absolute value | |||
9455 | // function call. | |||
9456 | if (ArgType->isUnsignedIntegerType()) { | |||
9457 | const char *FunctionName = | |||
9458 | IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); | |||
9459 | Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; | |||
9460 | Diag(Call->getExprLoc(), diag::note_remove_abs) | |||
9461 | << FunctionName | |||
9462 | << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); | |||
9463 | return; | |||
9464 | } | |||
9465 | ||||
9466 | // Taking the absolute value of a pointer is very suspicious, they probably | |||
9467 | // wanted to index into an array, dereference a pointer, call a function, etc. | |||
9468 | if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { | |||
9469 | unsigned DiagType = 0; | |||
9470 | if (ArgType->isFunctionType()) | |||
9471 | DiagType = 1; | |||
9472 | else if (ArgType->isArrayType()) | |||
9473 | DiagType = 2; | |||
9474 | ||||
9475 | Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; | |||
9476 | return; | |||
9477 | } | |||
9478 | ||||
9479 | // std::abs has overloads which prevent most of the absolute value problems | |||
9480 | // from occurring. | |||
9481 | if (IsStdAbs) | |||
9482 | return; | |||
9483 | ||||
9484 | AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); | |||
9485 | AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); | |||
9486 | ||||
9487 | // The argument and parameter are the same kind. Check if they are the right | |||
9488 | // size. | |||
9489 | if (ArgValueKind == ParamValueKind) { | |||
9490 | if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) | |||
9491 | return; | |||
9492 | ||||
9493 | unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); | |||
9494 | Diag(Call->getExprLoc(), diag::warn_abs_too_small) | |||
9495 | << FDecl << ArgType << ParamType; | |||
9496 | ||||
9497 | if (NewAbsKind == 0) | |||
9498 | return; | |||
9499 | ||||
9500 | emitReplacement(*this, Call->getExprLoc(), | |||
9501 | Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); | |||
9502 | return; | |||
9503 | } | |||
9504 | ||||
9505 | // ArgValueKind != ParamValueKind | |||
9506 | // The wrong type of absolute value function was used. Attempt to find the | |||
9507 | // proper one. | |||
9508 | unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); | |||
9509 | NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); | |||
9510 | if (NewAbsKind == 0) | |||
9511 | return; | |||
9512 | ||||
9513 | Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) | |||
9514 | << FDecl << ParamValueKind << ArgValueKind; | |||
9515 | ||||
9516 | emitReplacement(*this, Call->getExprLoc(), | |||
9517 | Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); | |||
9518 | } | |||
9519 | ||||
9520 | //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// | |||
9521 | void Sema::CheckMaxUnsignedZero(const CallExpr *Call, | |||
9522 | const FunctionDecl *FDecl) { | |||
9523 | if (!Call || !FDecl) return; | |||
9524 | ||||
9525 | // Ignore template specializations and macros. | |||
9526 | if (inTemplateInstantiation()) return; | |||
9527 | if (Call->getExprLoc().isMacroID()) return; | |||
9528 | ||||
9529 | // Only care about the one template argument, two function parameter std::max | |||
9530 | if (Call->getNumArgs() != 2) return; | |||
9531 | if (!IsStdFunction(FDecl, "max")) return; | |||
9532 | const auto * ArgList = FDecl->getTemplateSpecializationArgs(); | |||
9533 | if (!ArgList) return; | |||
9534 | if (ArgList->size() != 1) return; | |||
9535 | ||||
9536 | // Check that template type argument is unsigned integer. | |||
9537 | const auto& TA = ArgList->get(0); | |||
9538 | if (TA.getKind() != TemplateArgument::Type) return; | |||
9539 | QualType ArgType = TA.getAsType(); | |||
9540 | if (!ArgType->isUnsignedIntegerType()) return; | |||
9541 | ||||
9542 | // See if either argument is a literal zero. | |||
9543 | auto IsLiteralZeroArg = [](const Expr* E) -> bool { | |||
9544 | const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); | |||
9545 | if (!MTE) return false; | |||
9546 | const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); | |||
9547 | if (!Num) return false; | |||
9548 | if (Num->getValue() != 0) return false; | |||
9549 | return true; | |||
9550 | }; | |||
9551 | ||||
9552 | const Expr *FirstArg = Call->getArg(0); | |||
9553 | const Expr *SecondArg = Call->getArg(1); | |||
9554 | const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); | |||
9555 | const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); | |||
9556 | ||||
9557 | // Only warn when exactly one argument is zero. | |||
9558 | if (IsFirstArgZero == IsSecondArgZero) return; | |||
9559 | ||||
9560 | SourceRange FirstRange = FirstArg->getSourceRange(); | |||
9561 | SourceRange SecondRange = SecondArg->getSourceRange(); | |||
9562 | ||||
9563 | SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; | |||
9564 | ||||
9565 | Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) | |||
9566 | << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; | |||
9567 | ||||
9568 | // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". | |||
9569 | SourceRange RemovalRange; | |||
9570 | if (IsFirstArgZero) { | |||
9571 | RemovalRange = SourceRange(FirstRange.getBegin(), | |||
9572 | SecondRange.getBegin().getLocWithOffset(-1)); | |||
9573 | } else { | |||
9574 | RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), | |||
9575 | SecondRange.getEnd()); | |||
9576 | } | |||
9577 | ||||
9578 | Diag(Call->getExprLoc(), diag::note_remove_max_call) | |||
9579 | << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) | |||
9580 | << FixItHint::CreateRemoval(RemovalRange); | |||
9581 | } | |||
9582 | ||||
9583 | //===--- CHECK: Standard memory functions ---------------------------------===// | |||
9584 | ||||
9585 | /// Takes the expression passed to the size_t parameter of functions | |||
9586 | /// such as memcmp, strncat, etc and warns if it's a comparison. | |||
9587 | /// | |||
9588 | /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. | |||
9589 | static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, | |||
9590 | IdentifierInfo *FnName, | |||
9591 | SourceLocation FnLoc, | |||
9592 | SourceLocation RParenLoc) { | |||
9593 | const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); | |||
9594 | if (!Size) | |||
9595 | return false; | |||
9596 | ||||
9597 | // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: | |||
9598 | if (!Size->isComparisonOp() && !Size->isLogicalOp()) | |||
9599 | return false; | |||
9600 | ||||
9601 | SourceRange SizeRange = Size->getSourceRange(); | |||
9602 | S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) | |||
9603 | << SizeRange << FnName; | |||
9604 | S.Diag(FnLoc, diag::note_memsize_comparison_paren) | |||
9605 | << FnName | |||
9606 | << FixItHint::CreateInsertion( | |||
9607 | S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") | |||
9608 | << FixItHint::CreateRemoval(RParenLoc); | |||
9609 | S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) | |||
9610 | << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") | |||
9611 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), | |||
9612 | ")"); | |||
9613 | ||||
9614 | return true; | |||
9615 | } | |||
9616 | ||||
9617 | /// Determine whether the given type is or contains a dynamic class type | |||
9618 | /// (e.g., whether it has a vtable). | |||
9619 | static const CXXRecordDecl *getContainedDynamicClass(QualType T, | |||
9620 | bool &IsContained) { | |||
9621 | // Look through array types while ignoring qualifiers. | |||
9622 | const Type *Ty = T->getBaseElementTypeUnsafe(); | |||
9623 | IsContained = false; | |||
9624 | ||||
9625 | const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); | |||
9626 | RD = RD ? RD->getDefinition() : nullptr; | |||
9627 | if (!RD || RD->isInvalidDecl()) | |||
9628 | return nullptr; | |||
9629 | ||||
9630 | if (RD->isDynamicClass()) | |||
9631 | return RD; | |||
9632 | ||||
9633 | // Check all the fields. If any bases were dynamic, the class is dynamic. | |||
9634 | // It's impossible for a class to transitively contain itself by value, so | |||
9635 | // infinite recursion is impossible. | |||
9636 | for (auto *FD : RD->fields()) { | |||
9637 | bool SubContained; | |||
9638 | if (const CXXRecordDecl *ContainedRD = | |||
9639 | getContainedDynamicClass(FD->getType(), SubContained)) { | |||
9640 | IsContained = true; | |||
9641 | return ContainedRD; | |||
9642 | } | |||
9643 | } | |||
9644 | ||||
9645 | return nullptr; | |||
9646 | } | |||
9647 | ||||
9648 | static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { | |||
9649 | if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) | |||
9650 | if (Unary->getKind() == UETT_SizeOf) | |||
9651 | return Unary; | |||
9652 | return nullptr; | |||
9653 | } | |||
9654 | ||||
9655 | /// If E is a sizeof expression, returns its argument expression, | |||
9656 | /// otherwise returns NULL. | |||
9657 | static const Expr *getSizeOfExprArg(const Expr *E) { | |||
9658 | if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) | |||
9659 | if (!SizeOf->isArgumentType()) | |||
9660 | return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); | |||
9661 | return nullptr; | |||
9662 | } | |||
9663 | ||||
9664 | /// If E is a sizeof expression, returns its argument type. | |||
9665 | static QualType getSizeOfArgType(const Expr *E) { | |||
9666 | if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) | |||
9667 | return SizeOf->getTypeOfArgument(); | |||
9668 | return QualType(); | |||
9669 | } | |||
9670 | ||||
9671 | namespace { | |||
9672 | ||||
9673 | struct SearchNonTrivialToInitializeField | |||
9674 | : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { | |||
9675 | using Super = | |||
9676 | DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; | |||
9677 | ||||
9678 | SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} | |||
9679 | ||||
9680 | void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, | |||
9681 | SourceLocation SL) { | |||
9682 | if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { | |||
9683 | asDerived().visitArray(PDIK, AT, SL); | |||
9684 | return; | |||
9685 | } | |||
9686 | ||||
9687 | Super::visitWithKind(PDIK, FT, SL); | |||
9688 | } | |||
9689 | ||||
9690 | void visitARCStrong(QualType FT, SourceLocation SL) { | |||
9691 | S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); | |||
9692 | } | |||
9693 | void visitARCWeak(QualType FT, SourceLocation SL) { | |||
9694 | S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); | |||
9695 | } | |||
9696 | void visitStruct(QualType FT, SourceLocation SL) { | |||
9697 | for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) | |||
9698 | visit(FD->getType(), FD->getLocation()); | |||
9699 | } | |||
9700 | void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, | |||
9701 | const ArrayType *AT, SourceLocation SL) { | |||
9702 | visit(getContext().getBaseElementType(AT), SL); | |||
9703 | } | |||
9704 | void visitTrivial(QualType FT, SourceLocation SL) {} | |||
9705 | ||||
9706 | static void diag(QualType RT, const Expr *E, Sema &S) { | |||
9707 | SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); | |||
9708 | } | |||
9709 | ||||
9710 | ASTContext &getContext() { return S.getASTContext(); } | |||
9711 | ||||
9712 | const Expr *E; | |||
9713 | Sema &S; | |||
9714 | }; | |||
9715 | ||||
9716 | struct SearchNonTrivialToCopyField | |||
9717 | : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { | |||
9718 | using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; | |||
9719 | ||||
9720 | SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} | |||
9721 | ||||
9722 | void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, | |||
9723 | SourceLocation SL) { | |||
9724 | if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { | |||
9725 | asDerived().visitArray(PCK, AT, SL); | |||
9726 | return; | |||
9727 | } | |||
9728 | ||||
9729 | Super::visitWithKind(PCK, FT, SL); | |||
9730 | } | |||
9731 | ||||
9732 | void visitARCStrong(QualType FT, SourceLocation SL) { | |||
9733 | S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); | |||
9734 | } | |||
9735 | void visitARCWeak(QualType FT, SourceLocation SL) { | |||
9736 | S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); | |||
9737 | } | |||
9738 | void visitStruct(QualType FT, SourceLocation SL) { | |||
9739 | for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) | |||
9740 | visit(FD->getType(), FD->getLocation()); | |||
9741 | } | |||
9742 | void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, | |||
9743 | SourceLocation SL) { | |||
9744 | visit(getContext().getBaseElementType(AT), SL); | |||
9745 | } | |||
9746 | void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, | |||
9747 | SourceLocation SL) {} | |||
9748 | void visitTrivial(QualType FT, SourceLocation SL) {} | |||
9749 | void visitVolatileTrivial(QualType FT, SourceLocation SL) {} | |||
9750 | ||||
9751 | static void diag(QualType RT, const Expr *E, Sema &S) { | |||
9752 | SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); | |||
9753 | } | |||
9754 | ||||
9755 | ASTContext &getContext() { return S.getASTContext(); } | |||
9756 | ||||
9757 | const Expr *E; | |||
9758 | Sema &S; | |||
9759 | }; | |||
9760 | ||||
9761 | } | |||
9762 | ||||
9763 | /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. | |||
9764 | static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { | |||
9765 | SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); | |||
9766 | ||||
9767 | if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { | |||
9768 | if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) | |||
9769 | return false; | |||
9770 | ||||
9771 | return doesExprLikelyComputeSize(BO->getLHS()) || | |||
9772 | doesExprLikelyComputeSize(BO->getRHS()); | |||
9773 | } | |||
9774 | ||||
9775 | return getAsSizeOfExpr(SizeofExpr) != nullptr; | |||
9776 | } | |||
9777 | ||||
9778 | /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. | |||
9779 | /// | |||
9780 | /// \code | |||
9781 | /// #define MACRO 0 | |||
9782 | /// foo(MACRO); | |||
9783 | /// foo(0); | |||
9784 | /// \endcode | |||
9785 | /// | |||
9786 | /// This should return true for the first call to foo, but not for the second | |||
9787 | /// (regardless of whether foo is a macro or function). | |||
9788 | static bool isArgumentExpandedFromMacro(SourceManager &SM, | |||
9789 | SourceLocation CallLoc, | |||
9790 | SourceLocation ArgLoc) { | |||
9791 | if (!CallLoc.isMacroID()) | |||
9792 | return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); | |||
9793 | ||||
9794 | return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != | |||
9795 | SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); | |||
9796 | } | |||
9797 | ||||
9798 | /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the | |||
9799 | /// last two arguments transposed. | |||
9800 | static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { | |||
9801 | if (BId != Builtin::BImemset && BId != Builtin::BIbzero) | |||
9802 | return; | |||
9803 | ||||
9804 | const Expr *SizeArg = | |||
9805 | Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); | |||
9806 | ||||
9807 | auto isLiteralZero = [](const Expr *E) { | |||
9808 | return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; | |||
9809 | }; | |||
9810 | ||||
9811 | // If we're memsetting or bzeroing 0 bytes, then this is likely an error. | |||
9812 | SourceLocation CallLoc = Call->getRParenLoc(); | |||
9813 | SourceManager &SM = S.getSourceManager(); | |||
9814 | if (isLiteralZero(SizeArg) && | |||
9815 | !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { | |||
9816 | ||||
9817 | SourceLocation DiagLoc = SizeArg->getExprLoc(); | |||
9818 | ||||
9819 | // Some platforms #define bzero to __builtin_memset. See if this is the | |||
9820 | // case, and if so, emit a better diagnostic. | |||
9821 | if (BId == Builtin::BIbzero || | |||
9822 | (CallLoc.isMacroID() && Lexer::getImmediateMacroName( | |||
9823 | CallLoc, SM, S.getLangOpts()) == "bzero")) { | |||
9824 | S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); | |||
9825 | S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); | |||
9826 | } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { | |||
9827 | S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; | |||
9828 | S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; | |||
9829 | } | |||
9830 | return; | |||
9831 | } | |||
9832 | ||||
9833 | // If the second argument to a memset is a sizeof expression and the third | |||
9834 | // isn't, this is also likely an error. This should catch | |||
9835 | // 'memset(buf, sizeof(buf), 0xff)'. | |||
9836 | if (BId == Builtin::BImemset && | |||
9837 | doesExprLikelyComputeSize(Call->getArg(1)) && | |||
9838 | !doesExprLikelyComputeSize(Call->getArg(2))) { | |||
9839 | SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); | |||
9840 | S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; | |||
9841 | S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; | |||
9842 | return; | |||
9843 | } | |||
9844 | } | |||
9845 | ||||
9846 | /// Check for dangerous or invalid arguments to memset(). | |||
9847 | /// | |||
9848 | /// This issues warnings on known problematic, dangerous or unspecified | |||
9849 | /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' | |||
9850 | /// function calls. | |||
9851 | /// | |||
9852 | /// \param Call The call expression to diagnose. | |||
9853 | void Sema::CheckMemaccessArguments(const CallExpr *Call, | |||
9854 | unsigned BId, | |||
9855 | IdentifierInfo *FnName) { | |||
9856 | assert(BId != 0)((BId != 0) ? static_cast<void> (0) : __assert_fail ("BId != 0" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 9856, __PRETTY_FUNCTION__)); | |||
9857 | ||||
9858 | // It is possible to have a non-standard definition of memset. Validate | |||
9859 | // we have enough arguments, and if not, abort further checking. | |||
9860 | unsigned ExpectedNumArgs = | |||
9861 | (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); | |||
9862 | if (Call->getNumArgs() < ExpectedNumArgs) | |||
9863 | return; | |||
9864 | ||||
9865 | unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || | |||
9866 | BId == Builtin::BIstrndup ? 1 : 2); | |||
9867 | unsigned LenArg = | |||
9868 | (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); | |||
9869 | const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); | |||
9870 | ||||
9871 | if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, | |||
9872 | Call->getBeginLoc(), Call->getRParenLoc())) | |||
9873 | return; | |||
9874 | ||||
9875 | // Catch cases like 'memset(buf, sizeof(buf), 0)'. | |||
9876 | CheckMemaccessSize(*this, BId, Call); | |||
9877 | ||||
9878 | // We have special checking when the length is a sizeof expression. | |||
9879 | QualType SizeOfArgTy = getSizeOfArgType(LenExpr); | |||
9880 | const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); | |||
9881 | llvm::FoldingSetNodeID SizeOfArgID; | |||
9882 | ||||
9883 | // Although widely used, 'bzero' is not a standard function. Be more strict | |||
9884 | // with the argument types before allowing diagnostics and only allow the | |||
9885 | // form bzero(ptr, sizeof(...)). | |||
9886 | QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); | |||
9887 | if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) | |||
9888 | return; | |||
9889 | ||||
9890 | for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { | |||
9891 | const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); | |||
9892 | SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); | |||
9893 | ||||
9894 | QualType DestTy = Dest->getType(); | |||
9895 | QualType PointeeTy; | |||
9896 | if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { | |||
9897 | PointeeTy = DestPtrTy->getPointeeType(); | |||
9898 | ||||
9899 | // Never warn about void type pointers. This can be used to suppress | |||
9900 | // false positives. | |||
9901 | if (PointeeTy->isVoidType()) | |||
9902 | continue; | |||
9903 | ||||
9904 | // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by | |||
9905 | // actually comparing the expressions for equality. Because computing the | |||
9906 | // expression IDs can be expensive, we only do this if the diagnostic is | |||
9907 | // enabled. | |||
9908 | if (SizeOfArg && | |||
9909 | !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, | |||
9910 | SizeOfArg->getExprLoc())) { | |||
9911 | // We only compute IDs for expressions if the warning is enabled, and | |||
9912 | // cache the sizeof arg's ID. | |||
9913 | if (SizeOfArgID == llvm::FoldingSetNodeID()) | |||
9914 | SizeOfArg->Profile(SizeOfArgID, Context, true); | |||
9915 | llvm::FoldingSetNodeID DestID; | |||
9916 | Dest->Profile(DestID, Context, true); | |||
9917 | if (DestID == SizeOfArgID) { | |||
9918 | // TODO: For strncpy() and friends, this could suggest sizeof(dst) | |||
9919 | // over sizeof(src) as well. | |||
9920 | unsigned ActionIdx = 0; // Default is to suggest dereferencing. | |||
9921 | StringRef ReadableName = FnName->getName(); | |||
9922 | ||||
9923 | if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) | |||
9924 | if (UnaryOp->getOpcode() == UO_AddrOf) | |||
9925 | ActionIdx = 1; // If its an address-of operator, just remove it. | |||
9926 | if (!PointeeTy->isIncompleteType() && | |||
9927 | (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) | |||
9928 | ActionIdx = 2; // If the pointee's size is sizeof(char), | |||
9929 | // suggest an explicit length. | |||
9930 | ||||
9931 | // If the function is defined as a builtin macro, do not show macro | |||
9932 | // expansion. | |||
9933 | SourceLocation SL = SizeOfArg->getExprLoc(); | |||
9934 | SourceRange DSR = Dest->getSourceRange(); | |||
9935 | SourceRange SSR = SizeOfArg->getSourceRange(); | |||
9936 | SourceManager &SM = getSourceManager(); | |||
9937 | ||||
9938 | if (SM.isMacroArgExpansion(SL)) { | |||
9939 | ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); | |||
9940 | SL = SM.getSpellingLoc(SL); | |||
9941 | DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), | |||
9942 | SM.getSpellingLoc(DSR.getEnd())); | |||
9943 | SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), | |||
9944 | SM.getSpellingLoc(SSR.getEnd())); | |||
9945 | } | |||
9946 | ||||
9947 | DiagRuntimeBehavior(SL, SizeOfArg, | |||
9948 | PDiag(diag::warn_sizeof_pointer_expr_memaccess) | |||
9949 | << ReadableName | |||
9950 | << PointeeTy | |||
9951 | << DestTy | |||
9952 | << DSR | |||
9953 | << SSR); | |||
9954 | DiagRuntimeBehavior(SL, SizeOfArg, | |||
9955 | PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) | |||
9956 | << ActionIdx | |||
9957 | << SSR); | |||
9958 | ||||
9959 | break; | |||
9960 | } | |||
9961 | } | |||
9962 | ||||
9963 | // Also check for cases where the sizeof argument is the exact same | |||
9964 | // type as the memory argument, and where it points to a user-defined | |||
9965 | // record type. | |||
9966 | if (SizeOfArgTy != QualType()) { | |||
9967 | if (PointeeTy->isRecordType() && | |||
9968 | Context.typesAreCompatible(SizeOfArgTy, DestTy)) { | |||
9969 | DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, | |||
9970 | PDiag(diag::warn_sizeof_pointer_type_memaccess) | |||
9971 | << FnName << SizeOfArgTy << ArgIdx | |||
9972 | << PointeeTy << Dest->getSourceRange() | |||
9973 | << LenExpr->getSourceRange()); | |||
9974 | break; | |||
9975 | } | |||
9976 | } | |||
9977 | } else if (DestTy->isArrayType()) { | |||
9978 | PointeeTy = DestTy; | |||
9979 | } | |||
9980 | ||||
9981 | if (PointeeTy == QualType()) | |||
9982 | continue; | |||
9983 | ||||
9984 | // Always complain about dynamic classes. | |||
9985 | bool IsContained; | |||
9986 | if (const CXXRecordDecl *ContainedRD = | |||
9987 | getContainedDynamicClass(PointeeTy, IsContained)) { | |||
9988 | ||||
9989 | unsigned OperationType = 0; | |||
9990 | const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; | |||
9991 | // "overwritten" if we're warning about the destination for any call | |||
9992 | // but memcmp; otherwise a verb appropriate to the call. | |||
9993 | if (ArgIdx != 0 || IsCmp) { | |||
9994 | if (BId == Builtin::BImemcpy) | |||
9995 | OperationType = 1; | |||
9996 | else if(BId == Builtin::BImemmove) | |||
9997 | OperationType = 2; | |||
9998 | else if (IsCmp) | |||
9999 | OperationType = 3; | |||
10000 | } | |||
10001 | ||||
10002 | DiagRuntimeBehavior(Dest->getExprLoc(), Dest, | |||
10003 | PDiag(diag::warn_dyn_class_memaccess) | |||
10004 | << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName | |||
10005 | << IsContained << ContainedRD << OperationType | |||
10006 | << Call->getCallee()->getSourceRange()); | |||
10007 | } else if (PointeeTy.hasNonTrivialObjCLifetime() && | |||
10008 | BId != Builtin::BImemset) | |||
10009 | DiagRuntimeBehavior( | |||
10010 | Dest->getExprLoc(), Dest, | |||
10011 | PDiag(diag::warn_arc_object_memaccess) | |||
10012 | << ArgIdx << FnName << PointeeTy | |||
10013 | << Call->getCallee()->getSourceRange()); | |||
10014 | else if (const auto *RT = PointeeTy->getAs<RecordType>()) { | |||
10015 | if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && | |||
10016 | RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { | |||
10017 | DiagRuntimeBehavior(Dest->getExprLoc(), Dest, | |||
10018 | PDiag(diag::warn_cstruct_memaccess) | |||
10019 | << ArgIdx << FnName << PointeeTy << 0); | |||
10020 | SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); | |||
10021 | } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && | |||
10022 | RT->getDecl()->isNonTrivialToPrimitiveCopy()) { | |||
10023 | DiagRuntimeBehavior(Dest->getExprLoc(), Dest, | |||
10024 | PDiag(diag::warn_cstruct_memaccess) | |||
10025 | << ArgIdx << FnName << PointeeTy << 1); | |||
10026 | SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); | |||
10027 | } else { | |||
10028 | continue; | |||
10029 | } | |||
10030 | } else | |||
10031 | continue; | |||
10032 | ||||
10033 | DiagRuntimeBehavior( | |||
10034 | Dest->getExprLoc(), Dest, | |||
10035 | PDiag(diag::note_bad_memaccess_silence) | |||
10036 | << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); | |||
10037 | break; | |||
10038 | } | |||
10039 | } | |||
10040 | ||||
10041 | // A little helper routine: ignore addition and subtraction of integer literals. | |||
10042 | // This intentionally does not ignore all integer constant expressions because | |||
10043 | // we don't want to remove sizeof(). | |||
10044 | static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { | |||
10045 | Ex = Ex->IgnoreParenCasts(); | |||
10046 | ||||
10047 | while (true) { | |||
10048 | const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); | |||
10049 | if (!BO || !BO->isAdditiveOp()) | |||
10050 | break; | |||
10051 | ||||
10052 | const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); | |||
10053 | const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); | |||
10054 | ||||
10055 | if (isa<IntegerLiteral>(RHS)) | |||
10056 | Ex = LHS; | |||
10057 | else if (isa<IntegerLiteral>(LHS)) | |||
10058 | Ex = RHS; | |||
10059 | else | |||
10060 | break; | |||
10061 | } | |||
10062 | ||||
10063 | return Ex; | |||
10064 | } | |||
10065 | ||||
10066 | static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, | |||
10067 | ASTContext &Context) { | |||
10068 | // Only handle constant-sized or VLAs, but not flexible members. | |||
10069 | if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { | |||
10070 | // Only issue the FIXIT for arrays of size > 1. | |||
10071 | if (CAT->getSize().getSExtValue() <= 1) | |||
10072 | return false; | |||
10073 | } else if (!Ty->isVariableArrayType()) { | |||
10074 | return false; | |||
10075 | } | |||
10076 | return true; | |||
10077 | } | |||
10078 | ||||
10079 | // Warn if the user has made the 'size' argument to strlcpy or strlcat | |||
10080 | // be the size of the source, instead of the destination. | |||
10081 | void Sema::CheckStrlcpycatArguments(const CallExpr *Call, | |||
10082 | IdentifierInfo *FnName) { | |||
10083 | ||||
10084 | // Don't crash if the user has the wrong number of arguments | |||
10085 | unsigned NumArgs = Call->getNumArgs(); | |||
10086 | if ((NumArgs != 3) && (NumArgs != 4)) | |||
10087 | return; | |||
10088 | ||||
10089 | const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); | |||
10090 | const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); | |||
10091 | const Expr *CompareWithSrc = nullptr; | |||
10092 | ||||
10093 | if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, | |||
10094 | Call->getBeginLoc(), Call->getRParenLoc())) | |||
10095 | return; | |||
10096 | ||||
10097 | // Look for 'strlcpy(dst, x, sizeof(x))' | |||
10098 | if (const Expr *Ex = getSizeOfExprArg(SizeArg)) | |||
10099 | CompareWithSrc = Ex; | |||
10100 | else { | |||
10101 | // Look for 'strlcpy(dst, x, strlen(x))' | |||
10102 | if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { | |||
10103 | if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && | |||
10104 | SizeCall->getNumArgs() == 1) | |||
10105 | CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); | |||
10106 | } | |||
10107 | } | |||
10108 | ||||
10109 | if (!CompareWithSrc) | |||
10110 | return; | |||
10111 | ||||
10112 | // Determine if the argument to sizeof/strlen is equal to the source | |||
10113 | // argument. In principle there's all kinds of things you could do | |||
10114 | // here, for instance creating an == expression and evaluating it with | |||
10115 | // EvaluateAsBooleanCondition, but this uses a more direct technique: | |||
10116 | const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); | |||
10117 | if (!SrcArgDRE) | |||
10118 | return; | |||
10119 | ||||
10120 | const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); | |||
10121 | if (!CompareWithSrcDRE || | |||
10122 | SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) | |||
10123 | return; | |||
10124 | ||||
10125 | const Expr *OriginalSizeArg = Call->getArg(2); | |||
10126 | Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) | |||
10127 | << OriginalSizeArg->getSourceRange() << FnName; | |||
10128 | ||||
10129 | // Output a FIXIT hint if the destination is an array (rather than a | |||
10130 | // pointer to an array). This could be enhanced to handle some | |||
10131 | // pointers if we know the actual size, like if DstArg is 'array+2' | |||
10132 | // we could say 'sizeof(array)-2'. | |||
10133 | const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); | |||
10134 | if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) | |||
10135 | return; | |||
10136 | ||||
10137 | SmallString<128> sizeString; | |||
10138 | llvm::raw_svector_ostream OS(sizeString); | |||
10139 | OS << "sizeof("; | |||
10140 | DstArg->printPretty(OS, nullptr, getPrintingPolicy()); | |||
10141 | OS << ")"; | |||
10142 | ||||
10143 | Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) | |||
10144 | << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), | |||
10145 | OS.str()); | |||
10146 | } | |||
10147 | ||||
10148 | /// Check if two expressions refer to the same declaration. | |||
10149 | static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { | |||
10150 | if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) | |||
10151 | if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) | |||
10152 | return D1->getDecl() == D2->getDecl(); | |||
10153 | return false; | |||
10154 | } | |||
10155 | ||||
10156 | static const Expr *getStrlenExprArg(const Expr *E) { | |||
10157 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | |||
10158 | const FunctionDecl *FD = CE->getDirectCallee(); | |||
10159 | if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) | |||
10160 | return nullptr; | |||
10161 | return CE->getArg(0)->IgnoreParenCasts(); | |||
10162 | } | |||
10163 | return nullptr; | |||
10164 | } | |||
10165 | ||||
10166 | // Warn on anti-patterns as the 'size' argument to strncat. | |||
10167 | // The correct size argument should look like following: | |||
10168 | // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); | |||
10169 | void Sema::CheckStrncatArguments(const CallExpr *CE, | |||
10170 | IdentifierInfo *FnName) { | |||
10171 | // Don't crash if the user has the wrong number of arguments. | |||
10172 | if (CE->getNumArgs() < 3) | |||
10173 | return; | |||
10174 | const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); | |||
10175 | const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); | |||
10176 | const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); | |||
10177 | ||||
10178 | if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), | |||
10179 | CE->getRParenLoc())) | |||
10180 | return; | |||
10181 | ||||
10182 | // Identify common expressions, which are wrongly used as the size argument | |||
10183 | // to strncat and may lead to buffer overflows. | |||
10184 | unsigned PatternType = 0; | |||
10185 | if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { | |||
10186 | // - sizeof(dst) | |||
10187 | if (referToTheSameDecl(SizeOfArg, DstArg)) | |||
10188 | PatternType = 1; | |||
10189 | // - sizeof(src) | |||
10190 | else if (referToTheSameDecl(SizeOfArg, SrcArg)) | |||
10191 | PatternType = 2; | |||
10192 | } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { | |||
10193 | if (BE->getOpcode() == BO_Sub) { | |||
10194 | const Expr *L = BE->getLHS()->IgnoreParenCasts(); | |||
10195 | const Expr *R = BE->getRHS()->IgnoreParenCasts(); | |||
10196 | // - sizeof(dst) - strlen(dst) | |||
10197 | if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && | |||
10198 | referToTheSameDecl(DstArg, getStrlenExprArg(R))) | |||
10199 | PatternType = 1; | |||
10200 | // - sizeof(src) - (anything) | |||
10201 | else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) | |||
10202 | PatternType = 2; | |||
10203 | } | |||
10204 | } | |||
10205 | ||||
10206 | if (PatternType == 0) | |||
10207 | return; | |||
10208 | ||||
10209 | // Generate the diagnostic. | |||
10210 | SourceLocation SL = LenArg->getBeginLoc(); | |||
10211 | SourceRange SR = LenArg->getSourceRange(); | |||
10212 | SourceManager &SM = getSourceManager(); | |||
10213 | ||||
10214 | // If the function is defined as a builtin macro, do not show macro expansion. | |||
10215 | if (SM.isMacroArgExpansion(SL)) { | |||
10216 | SL = SM.getSpellingLoc(SL); | |||
10217 | SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), | |||
10218 | SM.getSpellingLoc(SR.getEnd())); | |||
10219 | } | |||
10220 | ||||
10221 | // Check if the destination is an array (rather than a pointer to an array). | |||
10222 | QualType DstTy = DstArg->getType(); | |||
10223 | bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, | |||
10224 | Context); | |||
10225 | if (!isKnownSizeArray) { | |||
10226 | if (PatternType == 1) | |||
10227 | Diag(SL, diag::warn_strncat_wrong_size) << SR; | |||
10228 | else | |||
10229 | Diag(SL, diag::warn_strncat_src_size) << SR; | |||
10230 | return; | |||
10231 | } | |||
10232 | ||||
10233 | if (PatternType == 1) | |||
10234 | Diag(SL, diag::warn_strncat_large_size) << SR; | |||
10235 | else | |||
10236 | Diag(SL, diag::warn_strncat_src_size) << SR; | |||
10237 | ||||
10238 | SmallString<128> sizeString; | |||
10239 | llvm::raw_svector_ostream OS(sizeString); | |||
10240 | OS << "sizeof("; | |||
10241 | DstArg->printPretty(OS, nullptr, getPrintingPolicy()); | |||
10242 | OS << ") - "; | |||
10243 | OS << "strlen("; | |||
10244 | DstArg->printPretty(OS, nullptr, getPrintingPolicy()); | |||
10245 | OS << ") - 1"; | |||
10246 | ||||
10247 | Diag(SL, diag::note_strncat_wrong_size) | |||
10248 | << FixItHint::CreateReplacement(SR, OS.str()); | |||
10249 | } | |||
10250 | ||||
10251 | namespace { | |||
10252 | void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, | |||
10253 | const UnaryOperator *UnaryExpr, | |||
10254 | const VarDecl *Var) { | |||
10255 | StorageClass Class = Var->getStorageClass(); | |||
10256 | if (Class == StorageClass::SC_Extern || | |||
10257 | Class == StorageClass::SC_PrivateExtern || | |||
10258 | Var->getType()->isReferenceType()) | |||
10259 | return; | |||
10260 | ||||
10261 | S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) | |||
10262 | << CalleeName << Var; | |||
10263 | } | |||
10264 | ||||
10265 | void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, | |||
10266 | const UnaryOperator *UnaryExpr, const Decl *D) { | |||
10267 | if (const auto *Field = dyn_cast<FieldDecl>(D)) | |||
10268 | S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) | |||
10269 | << CalleeName << Field; | |||
10270 | } | |||
10271 | ||||
10272 | void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, | |||
10273 | const UnaryOperator *UnaryExpr) { | |||
10274 | if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf) | |||
10275 | return; | |||
10276 | ||||
10277 | if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) | |||
10278 | if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl())) | |||
10279 | return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var); | |||
10280 | ||||
10281 | if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) | |||
10282 | return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, | |||
10283 | Lvalue->getMemberDecl()); | |||
10284 | } | |||
10285 | ||||
10286 | void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, | |||
10287 | const DeclRefExpr *Lvalue) { | |||
10288 | if (!Lvalue->getType()->isArrayType()) | |||
10289 | return; | |||
10290 | ||||
10291 | const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); | |||
10292 | if (Var == nullptr) | |||
10293 | return; | |||
10294 | ||||
10295 | S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) | |||
10296 | << CalleeName << Var; | |||
10297 | } | |||
10298 | } // namespace | |||
10299 | ||||
10300 | /// Alerts the user that they are attempting to free a non-malloc'd object. | |||
10301 | void Sema::CheckFreeArguments(const CallExpr *E) { | |||
10302 | const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); | |||
10303 | const std::string CalleeName = | |||
10304 | dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); | |||
| ||||
10305 | ||||
10306 | if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) | |||
10307 | return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); | |||
10308 | ||||
10309 | if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) | |||
10310 | return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); | |||
10311 | } | |||
10312 | ||||
10313 | void | |||
10314 | Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, | |||
10315 | SourceLocation ReturnLoc, | |||
10316 | bool isObjCMethod, | |||
10317 | const AttrVec *Attrs, | |||
10318 | const FunctionDecl *FD) { | |||
10319 | // Check if the return value is null but should not be. | |||
10320 | if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || | |||
10321 | (!isObjCMethod && isNonNullType(Context, lhsType))) && | |||
10322 | CheckNonNullExpr(*this, RetValExp)) | |||
10323 | Diag(ReturnLoc, diag::warn_null_ret) | |||
10324 | << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); | |||
10325 | ||||
10326 | // C++11 [basic.stc.dynamic.allocation]p4: | |||
10327 | // If an allocation function declared with a non-throwing | |||
10328 | // exception-specification fails to allocate storage, it shall return | |||
10329 | // a null pointer. Any other allocation function that fails to allocate | |||
10330 | // storage shall indicate failure only by throwing an exception [...] | |||
10331 | if (FD) { | |||
10332 | OverloadedOperatorKind Op = FD->getOverloadedOperator(); | |||
10333 | if (Op == OO_New || Op == OO_Array_New) { | |||
10334 | const FunctionProtoType *Proto | |||
10335 | = FD->getType()->castAs<FunctionProtoType>(); | |||
10336 | if (!Proto->isNothrow(/*ResultIfDependent*/true) && | |||
10337 | CheckNonNullExpr(*this, RetValExp)) | |||
10338 | Diag(ReturnLoc, diag::warn_operator_new_returns_null) | |||
10339 | << FD << getLangOpts().CPlusPlus11; | |||
10340 | } | |||
10341 | } | |||
10342 | ||||
10343 | // PPC MMA non-pointer types are not allowed as return type. Checking the type | |||
10344 | // here prevent the user from using a PPC MMA type as trailing return type. | |||
10345 | if (Context.getTargetInfo().getTriple().isPPC64()) | |||
10346 | CheckPPCMMAType(RetValExp->getType(), ReturnLoc); | |||
10347 | } | |||
10348 | ||||
10349 | //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// | |||
10350 | ||||
10351 | /// Check for comparisons of floating point operands using != and ==. | |||
10352 | /// Issue a warning if these are no self-comparisons, as they are not likely | |||
10353 | /// to do what the programmer intended. | |||
10354 | void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { | |||
10355 | Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); | |||
10356 | Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); | |||
10357 | ||||
10358 | // Special case: check for x == x (which is OK). | |||
10359 | // Do not emit warnings for such cases. | |||
10360 | if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) | |||
10361 | if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) | |||
10362 | if (DRL->getDecl() == DRR->getDecl()) | |||
10363 | return; | |||
10364 | ||||
10365 | // Special case: check for comparisons against literals that can be exactly | |||
10366 | // represented by APFloat. In such cases, do not emit a warning. This | |||
10367 | // is a heuristic: often comparison against such literals are used to | |||
10368 | // detect if a value in a variable has not changed. This clearly can | |||
10369 | // lead to false negatives. | |||
10370 | if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { | |||
10371 | if (FLL->isExact()) | |||
10372 | return; | |||
10373 | } else | |||
10374 | if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) | |||
10375 | if (FLR->isExact()) | |||
10376 | return; | |||
10377 | ||||
10378 | // Check for comparisons with builtin types. | |||
10379 | if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) | |||
10380 | if (CL->getBuiltinCallee()) | |||
10381 | return; | |||
10382 | ||||
10383 | if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) | |||
10384 | if (CR->getBuiltinCallee()) | |||
10385 | return; | |||
10386 | ||||
10387 | // Emit the diagnostic. | |||
10388 | Diag(Loc, diag::warn_floatingpoint_eq) | |||
10389 | << LHS->getSourceRange() << RHS->getSourceRange(); | |||
10390 | } | |||
10391 | ||||
10392 | //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// | |||
10393 | //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// | |||
10394 | ||||
10395 | namespace { | |||
10396 | ||||
10397 | /// Structure recording the 'active' range of an integer-valued | |||
10398 | /// expression. | |||
10399 | struct IntRange { | |||
10400 | /// The number of bits active in the int. Note that this includes exactly one | |||
10401 | /// sign bit if !NonNegative. | |||
10402 | unsigned Width; | |||
10403 | ||||
10404 | /// True if the int is known not to have negative values. If so, all leading | |||
10405 | /// bits before Width are known zero, otherwise they are known to be the | |||
10406 | /// same as the MSB within Width. | |||
10407 | bool NonNegative; | |||
10408 | ||||
10409 | IntRange(unsigned Width, bool NonNegative) | |||
10410 | : Width(Width), NonNegative(NonNegative) {} | |||
10411 | ||||
10412 | /// Number of bits excluding the sign bit. | |||
10413 | unsigned valueBits() const { | |||
10414 | return NonNegative ? Width : Width - 1; | |||
10415 | } | |||
10416 | ||||
10417 | /// Returns the range of the bool type. | |||
10418 | static IntRange forBoolType() { | |||
10419 | return IntRange(1, true); | |||
10420 | } | |||
10421 | ||||
10422 | /// Returns the range of an opaque value of the given integral type. | |||
10423 | static IntRange forValueOfType(ASTContext &C, QualType T) { | |||
10424 | return forValueOfCanonicalType(C, | |||
10425 | T->getCanonicalTypeInternal().getTypePtr()); | |||
10426 | } | |||
10427 | ||||
10428 | /// Returns the range of an opaque value of a canonical integral type. | |||
10429 | static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { | |||
10430 | assert(T->isCanonicalUnqualified())((T->isCanonicalUnqualified()) ? static_cast<void> ( 0) : __assert_fail ("T->isCanonicalUnqualified()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 10430, __PRETTY_FUNCTION__)); | |||
10431 | ||||
10432 | if (const VectorType *VT = dyn_cast<VectorType>(T)) | |||
10433 | T = VT->getElementType().getTypePtr(); | |||
10434 | if (const ComplexType *CT = dyn_cast<ComplexType>(T)) | |||
10435 | T = CT->getElementType().getTypePtr(); | |||
10436 | if (const AtomicType *AT = dyn_cast<AtomicType>(T)) | |||
10437 | T = AT->getValueType().getTypePtr(); | |||
10438 | ||||
10439 | if (!C.getLangOpts().CPlusPlus) { | |||
10440 | // For enum types in C code, use the underlying datatype. | |||
10441 | if (const EnumType *ET = dyn_cast<EnumType>(T)) | |||
10442 | T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); | |||
10443 | } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { | |||
10444 | // For enum types in C++, use the known bit width of the enumerators. | |||
10445 | EnumDecl *Enum = ET->getDecl(); | |||
10446 | // In C++11, enums can have a fixed underlying type. Use this type to | |||
10447 | // compute the range. | |||
10448 | if (Enum->isFixed()) { | |||
10449 | return IntRange(C.getIntWidth(QualType(T, 0)), | |||
10450 | !ET->isSignedIntegerOrEnumerationType()); | |||
10451 | } | |||
10452 | ||||
10453 | unsigned NumPositive = Enum->getNumPositiveBits(); | |||
10454 | unsigned NumNegative = Enum->getNumNegativeBits(); | |||
10455 | ||||
10456 | if (NumNegative == 0) | |||
10457 | return IntRange(NumPositive, true/*NonNegative*/); | |||
10458 | else | |||
10459 | return IntRange(std::max(NumPositive + 1, NumNegative), | |||
10460 | false/*NonNegative*/); | |||
10461 | } | |||
10462 | ||||
10463 | if (const auto *EIT = dyn_cast<ExtIntType>(T)) | |||
10464 | return IntRange(EIT->getNumBits(), EIT->isUnsigned()); | |||
10465 | ||||
10466 | const BuiltinType *BT = cast<BuiltinType>(T); | |||
10467 | assert(BT->isInteger())((BT->isInteger()) ? static_cast<void> (0) : __assert_fail ("BT->isInteger()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 10467, __PRETTY_FUNCTION__)); | |||
10468 | ||||
10469 | return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); | |||
10470 | } | |||
10471 | ||||
10472 | /// Returns the "target" range of a canonical integral type, i.e. | |||
10473 | /// the range of values expressible in the type. | |||
10474 | /// | |||
10475 | /// This matches forValueOfCanonicalType except that enums have the | |||
10476 | /// full range of their type, not the range of their enumerators. | |||
10477 | static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { | |||
10478 | assert(T->isCanonicalUnqualified())((T->isCanonicalUnqualified()) ? static_cast<void> ( 0) : __assert_fail ("T->isCanonicalUnqualified()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 10478, __PRETTY_FUNCTION__)); | |||
10479 | ||||
10480 | if (const VectorType *VT = dyn_cast<VectorType>(T)) | |||
10481 | T = VT->getElementType().getTypePtr(); | |||
10482 | if (const ComplexType *CT = dyn_cast<ComplexType>(T)) | |||
10483 | T = CT->getElementType().getTypePtr(); | |||
10484 | if (const AtomicType *AT = dyn_cast<AtomicType>(T)) | |||
10485 | T = AT->getValueType().getTypePtr(); | |||
10486 | if (const EnumType *ET = dyn_cast<EnumType>(T)) | |||
10487 | T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); | |||
10488 | ||||
10489 | if (const auto *EIT = dyn_cast<ExtIntType>(T)) | |||
10490 | return IntRange(EIT->getNumBits(), EIT->isUnsigned()); | |||
10491 | ||||
10492 | const BuiltinType *BT = cast<BuiltinType>(T); | |||
10493 | assert(BT->isInteger())((BT->isInteger()) ? static_cast<void> (0) : __assert_fail ("BT->isInteger()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 10493, __PRETTY_FUNCTION__)); | |||
10494 | ||||
10495 | return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); | |||
10496 | } | |||
10497 | ||||
10498 | /// Returns the supremum of two ranges: i.e. their conservative merge. | |||
10499 | static IntRange join(IntRange L, IntRange R) { | |||
10500 | bool Unsigned = L.NonNegative && R.NonNegative; | |||
10501 | return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, | |||
10502 | L.NonNegative && R.NonNegative); | |||
10503 | } | |||
10504 | ||||
10505 | /// Return the range of a bitwise-AND of the two ranges. | |||
10506 | static IntRange bit_and(IntRange L, IntRange R) { | |||
10507 | unsigned Bits = std::max(L.Width, R.Width); | |||
10508 | bool NonNegative = false; | |||
10509 | if (L.NonNegative) { | |||
10510 | Bits = std::min(Bits, L.Width); | |||
10511 | NonNegative = true; | |||
10512 | } | |||
10513 | if (R.NonNegative) { | |||
10514 | Bits = std::min(Bits, R.Width); | |||
10515 | NonNegative = true; | |||
10516 | } | |||
10517 | return IntRange(Bits, NonNegative); | |||
10518 | } | |||
10519 | ||||
10520 | /// Return the range of a sum of the two ranges. | |||
10521 | static IntRange sum(IntRange L, IntRange R) { | |||
10522 | bool Unsigned = L.NonNegative && R.NonNegative; | |||
10523 | return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, | |||
10524 | Unsigned); | |||
10525 | } | |||
10526 | ||||
10527 | /// Return the range of a difference of the two ranges. | |||
10528 | static IntRange difference(IntRange L, IntRange R) { | |||
10529 | // We need a 1-bit-wider range if: | |||
10530 | // 1) LHS can be negative: least value can be reduced. | |||
10531 | // 2) RHS can be negative: greatest value can be increased. | |||
10532 | bool CanWiden = !L.NonNegative || !R.NonNegative; | |||
10533 | bool Unsigned = L.NonNegative && R.Width == 0; | |||
10534 | return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + | |||
10535 | !Unsigned, | |||
10536 | Unsigned); | |||
10537 | } | |||
10538 | ||||
10539 | /// Return the range of a product of the two ranges. | |||
10540 | static IntRange product(IntRange L, IntRange R) { | |||
10541 | // If both LHS and RHS can be negative, we can form | |||
10542 | // -2^L * -2^R = 2^(L + R) | |||
10543 | // which requires L + R + 1 value bits to represent. | |||
10544 | bool CanWiden = !L.NonNegative && !R.NonNegative; | |||
10545 | bool Unsigned = L.NonNegative && R.NonNegative; | |||
10546 | return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, | |||
10547 | Unsigned); | |||
10548 | } | |||
10549 | ||||
10550 | /// Return the range of a remainder operation between the two ranges. | |||
10551 | static IntRange rem(IntRange L, IntRange R) { | |||
10552 | // The result of a remainder can't be larger than the result of | |||
10553 | // either side. The sign of the result is the sign of the LHS. | |||
10554 | bool Unsigned = L.NonNegative; | |||
10555 | return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, | |||
10556 | Unsigned); | |||
10557 | } | |||
10558 | }; | |||
10559 | ||||
10560 | } // namespace | |||
10561 | ||||
10562 | static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, | |||
10563 | unsigned MaxWidth) { | |||
10564 | if (value.isSigned() && value.isNegative()) | |||
10565 | return IntRange(value.getMinSignedBits(), false); | |||
10566 | ||||
10567 | if (value.getBitWidth() > MaxWidth) | |||
10568 | value = value.trunc(MaxWidth); | |||
10569 | ||||
10570 | // isNonNegative() just checks the sign bit without considering | |||
10571 | // signedness. | |||
10572 | return IntRange(value.getActiveBits(), true); | |||
10573 | } | |||
10574 | ||||
10575 | static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, | |||
10576 | unsigned MaxWidth) { | |||
10577 | if (result.isInt()) | |||
10578 | return GetValueRange(C, result.getInt(), MaxWidth); | |||
10579 | ||||
10580 | if (result.isVector()) { | |||
10581 | IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); | |||
10582 | for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { | |||
10583 | IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); | |||
10584 | R = IntRange::join(R, El); | |||
10585 | } | |||
10586 | return R; | |||
10587 | } | |||
10588 | ||||
10589 | if (result.isComplexInt()) { | |||
10590 | IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); | |||
10591 | IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); | |||
10592 | return IntRange::join(R, I); | |||
10593 | } | |||
10594 | ||||
10595 | // This can happen with lossless casts to intptr_t of "based" lvalues. | |||
10596 | // Assume it might use arbitrary bits. | |||
10597 | // FIXME: The only reason we need to pass the type in here is to get | |||
10598 | // the sign right on this one case. It would be nice if APValue | |||
10599 | // preserved this. | |||
10600 | assert(result.isLValue() || result.isAddrLabelDiff())((result.isLValue() || result.isAddrLabelDiff()) ? static_cast <void> (0) : __assert_fail ("result.isLValue() || result.isAddrLabelDiff()" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 10600, __PRETTY_FUNCTION__)); | |||
10601 | return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); | |||
10602 | } | |||
10603 | ||||
10604 | static QualType GetExprType(const Expr *E) { | |||
10605 | QualType Ty = E->getType(); | |||
10606 | if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) | |||
10607 | Ty = AtomicRHS->getValueType(); | |||
10608 | return Ty; | |||
10609 | } | |||
10610 | ||||
10611 | /// Pseudo-evaluate the given integer expression, estimating the | |||
10612 | /// range of values it might take. | |||
10613 | /// | |||
10614 | /// \param MaxWidth The width to which the value will be truncated. | |||
10615 | /// \param Approximate If \c true, return a likely range for the result: in | |||
10616 | /// particular, assume that aritmetic on narrower types doesn't leave | |||
10617 | /// those types. If \c false, return a range including all possible | |||
10618 | /// result values. | |||
10619 | static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, | |||
10620 | bool InConstantContext, bool Approximate) { | |||
10621 | E = E->IgnoreParens(); | |||
10622 | ||||
10623 | // Try a full evaluation first. | |||
10624 | Expr::EvalResult result; | |||
10625 | if (E->EvaluateAsRValue(result, C, InConstantContext)) | |||
10626 | return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); | |||
10627 | ||||
10628 | // I think we only want to look through implicit casts here; if the | |||
10629 | // user has an explicit widening cast, we should treat the value as | |||
10630 | // being of the new, wider type. | |||
10631 | if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { | |||
10632 | if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) | |||
10633 | return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, | |||
10634 | Approximate); | |||
10635 | ||||
10636 | IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); | |||
10637 | ||||
10638 | bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || | |||
10639 | CE->getCastKind() == CK_BooleanToSignedIntegral; | |||
10640 | ||||
10641 | // Assume that non-integer casts can span the full range of the type. | |||
10642 | if (!isIntegerCast) | |||
10643 | return OutputTypeRange; | |||
10644 | ||||
10645 | IntRange SubRange = GetExprRange(C, CE->getSubExpr(), | |||
10646 | std::min(MaxWidth, OutputTypeRange.Width), | |||
10647 | InConstantContext, Approximate); | |||
10648 | ||||
10649 | // Bail out if the subexpr's range is as wide as the cast type. | |||
10650 | if (SubRange.Width >= OutputTypeRange.Width) | |||
10651 | return OutputTypeRange; | |||
10652 | ||||
10653 | // Otherwise, we take the smaller width, and we're non-negative if | |||
10654 | // either the output type or the subexpr is. | |||
10655 | return IntRange(SubRange.Width, | |||
10656 | SubRange.NonNegative || OutputTypeRange.NonNegative); | |||
10657 | } | |||
10658 | ||||
10659 | if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { | |||
10660 | // If we can fold the condition, just take that operand. | |||
10661 | bool CondResult; | |||
10662 | if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) | |||
10663 | return GetExprRange(C, | |||
10664 | CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), | |||
10665 | MaxWidth, InConstantContext, Approximate); | |||
10666 | ||||
10667 | // Otherwise, conservatively merge. | |||
10668 | // GetExprRange requires an integer expression, but a throw expression | |||
10669 | // results in a void type. | |||
10670 | Expr *E = CO->getTrueExpr(); | |||
10671 | IntRange L = E->getType()->isVoidType() | |||
10672 | ? IntRange{0, true} | |||
10673 | : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); | |||
10674 | E = CO->getFalseExpr(); | |||
10675 | IntRange R = E->getType()->isVoidType() | |||
10676 | ? IntRange{0, true} | |||
10677 | : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); | |||
10678 | return IntRange::join(L, R); | |||
10679 | } | |||
10680 | ||||
10681 | if (const auto *BO = dyn_cast<BinaryOperator>(E)) { | |||
10682 | IntRange (*Combine)(IntRange, IntRange) = IntRange::join; | |||
10683 | ||||
10684 | switch (BO->getOpcode()) { | |||
10685 | case BO_Cmp: | |||
10686 | llvm_unreachable("builtin <=> should have class type")::llvm::llvm_unreachable_internal("builtin <=> should have class type" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 10686); | |||
10687 | ||||
10688 | // Boolean-valued operations are single-bit and positive. | |||
10689 | case BO_LAnd: | |||
10690 | case BO_LOr: | |||
10691 | case BO_LT: | |||
10692 | case BO_GT: | |||
10693 | case BO_LE: | |||
10694 | case BO_GE: | |||
10695 | case BO_EQ: | |||
10696 | case BO_NE: | |||
10697 | return IntRange::forBoolType(); | |||
10698 | ||||
10699 | // The type of the assignments is the type of the LHS, so the RHS | |||
10700 | // is not necessarily the same type. | |||
10701 | case BO_MulAssign: | |||
10702 | case BO_DivAssign: | |||
10703 | case BO_RemAssign: | |||
10704 | case BO_AddAssign: | |||
10705 | case BO_SubAssign: | |||
10706 | case BO_XorAssign: | |||
10707 | case BO_OrAssign: | |||
10708 | // TODO: bitfields? | |||
10709 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
10710 | ||||
10711 | // Simple assignments just pass through the RHS, which will have | |||
10712 | // been coerced to the LHS type. | |||
10713 | case BO_Assign: | |||
10714 | // TODO: bitfields? | |||
10715 | return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, | |||
10716 | Approximate); | |||
10717 | ||||
10718 | // Operations with opaque sources are black-listed. | |||
10719 | case BO_PtrMemD: | |||
10720 | case BO_PtrMemI: | |||
10721 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
10722 | ||||
10723 | // Bitwise-and uses the *infinum* of the two source ranges. | |||
10724 | case BO_And: | |||
10725 | case BO_AndAssign: | |||
10726 | Combine = IntRange::bit_and; | |||
10727 | break; | |||
10728 | ||||
10729 | // Left shift gets black-listed based on a judgement call. | |||
10730 | case BO_Shl: | |||
10731 | // ...except that we want to treat '1 << (blah)' as logically | |||
10732 | // positive. It's an important idiom. | |||
10733 | if (IntegerLiteral *I | |||
10734 | = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { | |||
10735 | if (I->getValue() == 1) { | |||
10736 | IntRange R = IntRange::forValueOfType(C, GetExprType(E)); | |||
10737 | return IntRange(R.Width, /*NonNegative*/ true); | |||
10738 | } | |||
10739 | } | |||
10740 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
10741 | ||||
10742 | case BO_ShlAssign: | |||
10743 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
10744 | ||||
10745 | // Right shift by a constant can narrow its left argument. | |||
10746 | case BO_Shr: | |||
10747 | case BO_ShrAssign: { | |||
10748 | IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, | |||
10749 | Approximate); | |||
10750 | ||||
10751 | // If the shift amount is a positive constant, drop the width by | |||
10752 | // that much. | |||
10753 | if (Optional<llvm::APSInt> shift = | |||
10754 | BO->getRHS()->getIntegerConstantExpr(C)) { | |||
10755 | if (shift->isNonNegative()) { | |||
10756 | unsigned zext = shift->getZExtValue(); | |||
10757 | if (zext >= L.Width) | |||
10758 | L.Width = (L.NonNegative ? 0 : 1); | |||
10759 | else | |||
10760 | L.Width -= zext; | |||
10761 | } | |||
10762 | } | |||
10763 | ||||
10764 | return L; | |||
10765 | } | |||
10766 | ||||
10767 | // Comma acts as its right operand. | |||
10768 | case BO_Comma: | |||
10769 | return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, | |||
10770 | Approximate); | |||
10771 | ||||
10772 | case BO_Add: | |||
10773 | if (!Approximate) | |||
10774 | Combine = IntRange::sum; | |||
10775 | break; | |||
10776 | ||||
10777 | case BO_Sub: | |||
10778 | if (BO->getLHS()->getType()->isPointerType()) | |||
10779 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
10780 | if (!Approximate) | |||
10781 | Combine = IntRange::difference; | |||
10782 | break; | |||
10783 | ||||
10784 | case BO_Mul: | |||
10785 | if (!Approximate) | |||
10786 | Combine = IntRange::product; | |||
10787 | break; | |||
10788 | ||||
10789 | // The width of a division result is mostly determined by the size | |||
10790 | // of the LHS. | |||
10791 | case BO_Div: { | |||
10792 | // Don't 'pre-truncate' the operands. | |||
10793 | unsigned opWidth = C.getIntWidth(GetExprType(E)); | |||
10794 | IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, | |||
10795 | Approximate); | |||
10796 | ||||
10797 | // If the divisor is constant, use that. | |||
10798 | if (Optional<llvm::APSInt> divisor = | |||
10799 | BO->getRHS()->getIntegerConstantExpr(C)) { | |||
10800 | unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) | |||
10801 | if (log2 >= L.Width) | |||
10802 | L.Width = (L.NonNegative ? 0 : 1); | |||
10803 | else | |||
10804 | L.Width = std::min(L.Width - log2, MaxWidth); | |||
10805 | return L; | |||
10806 | } | |||
10807 | ||||
10808 | // Otherwise, just use the LHS's width. | |||
10809 | // FIXME: This is wrong if the LHS could be its minimal value and the RHS | |||
10810 | // could be -1. | |||
10811 | IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, | |||
10812 | Approximate); | |||
10813 | return IntRange(L.Width, L.NonNegative && R.NonNegative); | |||
10814 | } | |||
10815 | ||||
10816 | case BO_Rem: | |||
10817 | Combine = IntRange::rem; | |||
10818 | break; | |||
10819 | ||||
10820 | // The default behavior is okay for these. | |||
10821 | case BO_Xor: | |||
10822 | case BO_Or: | |||
10823 | break; | |||
10824 | } | |||
10825 | ||||
10826 | // Combine the two ranges, but limit the result to the type in which we | |||
10827 | // performed the computation. | |||
10828 | QualType T = GetExprType(E); | |||
10829 | unsigned opWidth = C.getIntWidth(T); | |||
10830 | IntRange L = | |||
10831 | GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); | |||
10832 | IntRange R = | |||
10833 | GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); | |||
10834 | IntRange C = Combine(L, R); | |||
10835 | C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); | |||
10836 | C.Width = std::min(C.Width, MaxWidth); | |||
10837 | return C; | |||
10838 | } | |||
10839 | ||||
10840 | if (const auto *UO = dyn_cast<UnaryOperator>(E)) { | |||
10841 | switch (UO->getOpcode()) { | |||
10842 | // Boolean-valued operations are white-listed. | |||
10843 | case UO_LNot: | |||
10844 | return IntRange::forBoolType(); | |||
10845 | ||||
10846 | // Operations with opaque sources are black-listed. | |||
10847 | case UO_Deref: | |||
10848 | case UO_AddrOf: // should be impossible | |||
10849 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
10850 | ||||
10851 | default: | |||
10852 | return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, | |||
10853 | Approximate); | |||
10854 | } | |||
10855 | } | |||
10856 | ||||
10857 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) | |||
10858 | return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, | |||
10859 | Approximate); | |||
10860 | ||||
10861 | if (const auto *BitField = E->getSourceBitField()) | |||
10862 | return IntRange(BitField->getBitWidthValue(C), | |||
10863 | BitField->getType()->isUnsignedIntegerOrEnumerationType()); | |||
10864 | ||||
10865 | return IntRange::forValueOfType(C, GetExprType(E)); | |||
10866 | } | |||
10867 | ||||
10868 | static IntRange GetExprRange(ASTContext &C, const Expr *E, | |||
10869 | bool InConstantContext, bool Approximate) { | |||
10870 | return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, | |||
10871 | Approximate); | |||
10872 | } | |||
10873 | ||||
10874 | /// Checks whether the given value, which currently has the given | |||
10875 | /// source semantics, has the same value when coerced through the | |||
10876 | /// target semantics. | |||
10877 | static bool IsSameFloatAfterCast(const llvm::APFloat &value, | |||
10878 | const llvm::fltSemantics &Src, | |||
10879 | const llvm::fltSemantics &Tgt) { | |||
10880 | llvm::APFloat truncated = value; | |||
10881 | ||||
10882 | bool ignored; | |||
10883 | truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); | |||
10884 | truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); | |||
10885 | ||||
10886 | return truncated.bitwiseIsEqual(value); | |||
10887 | } | |||
10888 | ||||
10889 | /// Checks whether the given value, which currently has the given | |||
10890 | /// source semantics, has the same value when coerced through the | |||
10891 | /// target semantics. | |||
10892 | /// | |||
10893 | /// The value might be a vector of floats (or a complex number). | |||
10894 | static bool IsSameFloatAfterCast(const APValue &value, | |||
10895 | const llvm::fltSemantics &Src, | |||
10896 | const llvm::fltSemantics &Tgt) { | |||
10897 | if (value.isFloat()) | |||
10898 | return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); | |||
10899 | ||||
10900 | if (value.isVector()) { | |||
10901 | for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) | |||
10902 | if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) | |||
10903 | return false; | |||
10904 | return true; | |||
10905 | } | |||
10906 | ||||
10907 | assert(value.isComplexFloat())((value.isComplexFloat()) ? static_cast<void> (0) : __assert_fail ("value.isComplexFloat()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 10907, __PRETTY_FUNCTION__)); | |||
10908 | return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && | |||
10909 | IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); | |||
10910 | } | |||
10911 | ||||
10912 | static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, | |||
10913 | bool IsListInit = false); | |||
10914 | ||||
10915 | static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { | |||
10916 | // Suppress cases where we are comparing against an enum constant. | |||
10917 | if (const DeclRefExpr *DR = | |||
10918 | dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) | |||
10919 | if (isa<EnumConstantDecl>(DR->getDecl())) | |||
10920 | return true; | |||
10921 | ||||
10922 | // Suppress cases where the value is expanded from a macro, unless that macro | |||
10923 | // is how a language represents a boolean literal. This is the case in both C | |||
10924 | // and Objective-C. | |||
10925 | SourceLocation BeginLoc = E->getBeginLoc(); | |||
10926 | if (BeginLoc.isMacroID()) { | |||
10927 | StringRef MacroName = Lexer::getImmediateMacroName( | |||
10928 | BeginLoc, S.getSourceManager(), S.getLangOpts()); | |||
10929 | return MacroName != "YES" && MacroName != "NO" && | |||
10930 | MacroName != "true" && MacroName != "false"; | |||
10931 | } | |||
10932 | ||||
10933 | return false; | |||
10934 | } | |||
10935 | ||||
10936 | static bool isKnownToHaveUnsignedValue(Expr *E) { | |||
10937 | return E->getType()->isIntegerType() && | |||
10938 | (!E->getType()->isSignedIntegerType() || | |||
10939 | !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); | |||
10940 | } | |||
10941 | ||||
10942 | namespace { | |||
10943 | /// The promoted range of values of a type. In general this has the | |||
10944 | /// following structure: | |||
10945 | /// | |||
10946 | /// |-----------| . . . |-----------| | |||
10947 | /// ^ ^ ^ ^ | |||
10948 | /// Min HoleMin HoleMax Max | |||
10949 | /// | |||
10950 | /// ... where there is only a hole if a signed type is promoted to unsigned | |||
10951 | /// (in which case Min and Max are the smallest and largest representable | |||
10952 | /// values). | |||
10953 | struct PromotedRange { | |||
10954 | // Min, or HoleMax if there is a hole. | |||
10955 | llvm::APSInt PromotedMin; | |||
10956 | // Max, or HoleMin if there is a hole. | |||
10957 | llvm::APSInt PromotedMax; | |||
10958 | ||||
10959 | PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { | |||
10960 | if (R.Width == 0) | |||
10961 | PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); | |||
10962 | else if (R.Width >= BitWidth && !Unsigned) { | |||
10963 | // Promotion made the type *narrower*. This happens when promoting | |||
10964 | // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. | |||
10965 | // Treat all values of 'signed int' as being in range for now. | |||
10966 | PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); | |||
10967 | PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); | |||
10968 | } else { | |||
10969 | PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) | |||
10970 | .extOrTrunc(BitWidth); | |||
10971 | PromotedMin.setIsUnsigned(Unsigned); | |||
10972 | ||||
10973 | PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) | |||
10974 | .extOrTrunc(BitWidth); | |||
10975 | PromotedMax.setIsUnsigned(Unsigned); | |||
10976 | } | |||
10977 | } | |||
10978 | ||||
10979 | // Determine whether this range is contiguous (has no hole). | |||
10980 | bool isContiguous() const { return PromotedMin <= PromotedMax; } | |||
10981 | ||||
10982 | // Where a constant value is within the range. | |||
10983 | enum ComparisonResult { | |||
10984 | LT = 0x1, | |||
10985 | LE = 0x2, | |||
10986 | GT = 0x4, | |||
10987 | GE = 0x8, | |||
10988 | EQ = 0x10, | |||
10989 | NE = 0x20, | |||
10990 | InRangeFlag = 0x40, | |||
10991 | ||||
10992 | Less = LE | LT | NE, | |||
10993 | Min = LE | InRangeFlag, | |||
10994 | InRange = InRangeFlag, | |||
10995 | Max = GE | InRangeFlag, | |||
10996 | Greater = GE | GT | NE, | |||
10997 | ||||
10998 | OnlyValue = LE | GE | EQ | InRangeFlag, | |||
10999 | InHole = NE | |||
11000 | }; | |||
11001 | ||||
11002 | ComparisonResult compare(const llvm::APSInt &Value) const { | |||
11003 | assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&((Value.getBitWidth() == PromotedMin.getBitWidth() && Value.isUnsigned() == PromotedMin.isUnsigned()) ? static_cast <void> (0) : __assert_fail ("Value.getBitWidth() == PromotedMin.getBitWidth() && Value.isUnsigned() == PromotedMin.isUnsigned()" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11004, __PRETTY_FUNCTION__)) | |||
11004 | Value.isUnsigned() == PromotedMin.isUnsigned())((Value.getBitWidth() == PromotedMin.getBitWidth() && Value.isUnsigned() == PromotedMin.isUnsigned()) ? static_cast <void> (0) : __assert_fail ("Value.getBitWidth() == PromotedMin.getBitWidth() && Value.isUnsigned() == PromotedMin.isUnsigned()" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11004, __PRETTY_FUNCTION__)); | |||
11005 | if (!isContiguous()) { | |||
11006 | assert(Value.isUnsigned() && "discontiguous range for signed compare")((Value.isUnsigned() && "discontiguous range for signed compare" ) ? static_cast<void> (0) : __assert_fail ("Value.isUnsigned() && \"discontiguous range for signed compare\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11006, __PRETTY_FUNCTION__)); | |||
11007 | if (Value.isMinValue()) return Min; | |||
11008 | if (Value.isMaxValue()) return Max; | |||
11009 | if (Value >= PromotedMin) return InRange; | |||
11010 | if (Value <= PromotedMax) return InRange; | |||
11011 | return InHole; | |||
11012 | } | |||
11013 | ||||
11014 | switch (llvm::APSInt::compareValues(Value, PromotedMin)) { | |||
11015 | case -1: return Less; | |||
11016 | case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; | |||
11017 | case 1: | |||
11018 | switch (llvm::APSInt::compareValues(Value, PromotedMax)) { | |||
11019 | case -1: return InRange; | |||
11020 | case 0: return Max; | |||
11021 | case 1: return Greater; | |||
11022 | } | |||
11023 | } | |||
11024 | ||||
11025 | llvm_unreachable("impossible compare result")::llvm::llvm_unreachable_internal("impossible compare result" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11025); | |||
11026 | } | |||
11027 | ||||
11028 | static llvm::Optional<StringRef> | |||
11029 | constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { | |||
11030 | if (Op == BO_Cmp) { | |||
11031 | ComparisonResult LTFlag = LT, GTFlag = GT; | |||
11032 | if (ConstantOnRHS) std::swap(LTFlag, GTFlag); | |||
11033 | ||||
11034 | if (R & EQ) return StringRef("'std::strong_ordering::equal'"); | |||
11035 | if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); | |||
11036 | if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); | |||
11037 | return llvm::None; | |||
11038 | } | |||
11039 | ||||
11040 | ComparisonResult TrueFlag, FalseFlag; | |||
11041 | if (Op == BO_EQ) { | |||
11042 | TrueFlag = EQ; | |||
11043 | FalseFlag = NE; | |||
11044 | } else if (Op == BO_NE) { | |||
11045 | TrueFlag = NE; | |||
11046 | FalseFlag = EQ; | |||
11047 | } else { | |||
11048 | if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { | |||
11049 | TrueFlag = LT; | |||
11050 | FalseFlag = GE; | |||
11051 | } else { | |||
11052 | TrueFlag = GT; | |||
11053 | FalseFlag = LE; | |||
11054 | } | |||
11055 | if (Op == BO_GE || Op == BO_LE) | |||
11056 | std::swap(TrueFlag, FalseFlag); | |||
11057 | } | |||
11058 | if (R & TrueFlag) | |||
11059 | return StringRef("true"); | |||
11060 | if (R & FalseFlag) | |||
11061 | return StringRef("false"); | |||
11062 | return llvm::None; | |||
11063 | } | |||
11064 | }; | |||
11065 | } | |||
11066 | ||||
11067 | static bool HasEnumType(Expr *E) { | |||
11068 | // Strip off implicit integral promotions. | |||
11069 | while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { | |||
11070 | if (ICE->getCastKind() != CK_IntegralCast && | |||
11071 | ICE->getCastKind() != CK_NoOp) | |||
11072 | break; | |||
11073 | E = ICE->getSubExpr(); | |||
11074 | } | |||
11075 | ||||
11076 | return E->getType()->isEnumeralType(); | |||
11077 | } | |||
11078 | ||||
11079 | static int classifyConstantValue(Expr *Constant) { | |||
11080 | // The values of this enumeration are used in the diagnostics | |||
11081 | // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. | |||
11082 | enum ConstantValueKind { | |||
11083 | Miscellaneous = 0, | |||
11084 | LiteralTrue, | |||
11085 | LiteralFalse | |||
11086 | }; | |||
11087 | if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) | |||
11088 | return BL->getValue() ? ConstantValueKind::LiteralTrue | |||
11089 | : ConstantValueKind::LiteralFalse; | |||
11090 | return ConstantValueKind::Miscellaneous; | |||
11091 | } | |||
11092 | ||||
11093 | static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, | |||
11094 | Expr *Constant, Expr *Other, | |||
11095 | const llvm::APSInt &Value, | |||
11096 | bool RhsConstant) { | |||
11097 | if (S.inTemplateInstantiation()) | |||
11098 | return false; | |||
11099 | ||||
11100 | Expr *OriginalOther = Other; | |||
11101 | ||||
11102 | Constant = Constant->IgnoreParenImpCasts(); | |||
11103 | Other = Other->IgnoreParenImpCasts(); | |||
11104 | ||||
11105 | // Suppress warnings on tautological comparisons between values of the same | |||
11106 | // enumeration type. There are only two ways we could warn on this: | |||
11107 | // - If the constant is outside the range of representable values of | |||
11108 | // the enumeration. In such a case, we should warn about the cast | |||
11109 | // to enumeration type, not about the comparison. | |||
11110 | // - If the constant is the maximum / minimum in-range value. For an | |||
11111 | // enumeratin type, such comparisons can be meaningful and useful. | |||
11112 | if (Constant->getType()->isEnumeralType() && | |||
11113 | S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) | |||
11114 | return false; | |||
11115 | ||||
11116 | IntRange OtherValueRange = GetExprRange( | |||
11117 | S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); | |||
11118 | ||||
11119 | QualType OtherT = Other->getType(); | |||
11120 | if (const auto *AT = OtherT->getAs<AtomicType>()) | |||
11121 | OtherT = AT->getValueType(); | |||
11122 | IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); | |||
11123 | ||||
11124 | // Special case for ObjC BOOL on targets where its a typedef for a signed char | |||
11125 | // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. | |||
11126 | bool IsObjCSignedCharBool = S.getLangOpts().ObjC && | |||
11127 | S.NSAPIObj->isObjCBOOLType(OtherT) && | |||
11128 | OtherT->isSpecificBuiltinType(BuiltinType::SChar); | |||
11129 | ||||
11130 | // Whether we're treating Other as being a bool because of the form of | |||
11131 | // expression despite it having another type (typically 'int' in C). | |||
11132 | bool OtherIsBooleanDespiteType = | |||
11133 | !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); | |||
11134 | if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) | |||
11135 | OtherTypeRange = OtherValueRange = IntRange::forBoolType(); | |||
11136 | ||||
11137 | // Check if all values in the range of possible values of this expression | |||
11138 | // lead to the same comparison outcome. | |||
11139 | PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), | |||
11140 | Value.isUnsigned()); | |||
11141 | auto Cmp = OtherPromotedValueRange.compare(Value); | |||
11142 | auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); | |||
11143 | if (!Result) | |||
11144 | return false; | |||
11145 | ||||
11146 | // Also consider the range determined by the type alone. This allows us to | |||
11147 | // classify the warning under the proper diagnostic group. | |||
11148 | bool TautologicalTypeCompare = false; | |||
11149 | { | |||
11150 | PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), | |||
11151 | Value.isUnsigned()); | |||
11152 | auto TypeCmp = OtherPromotedTypeRange.compare(Value); | |||
11153 | if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, | |||
11154 | RhsConstant)) { | |||
11155 | TautologicalTypeCompare = true; | |||
11156 | Cmp = TypeCmp; | |||
11157 | Result = TypeResult; | |||
11158 | } | |||
11159 | } | |||
11160 | ||||
11161 | // Don't warn if the non-constant operand actually always evaluates to the | |||
11162 | // same value. | |||
11163 | if (!TautologicalTypeCompare && OtherValueRange.Width == 0) | |||
11164 | return false; | |||
11165 | ||||
11166 | // Suppress the diagnostic for an in-range comparison if the constant comes | |||
11167 | // from a macro or enumerator. We don't want to diagnose | |||
11168 | // | |||
11169 | // some_long_value <= INT_MAX | |||
11170 | // | |||
11171 | // when sizeof(int) == sizeof(long). | |||
11172 | bool InRange = Cmp & PromotedRange::InRangeFlag; | |||
11173 | if (InRange && IsEnumConstOrFromMacro(S, Constant)) | |||
11174 | return false; | |||
11175 | ||||
11176 | // A comparison of an unsigned bit-field against 0 is really a type problem, | |||
11177 | // even though at the type level the bit-field might promote to 'signed int'. | |||
11178 | if (Other->refersToBitField() && InRange && Value == 0 && | |||
11179 | Other->getType()->isUnsignedIntegerOrEnumerationType()) | |||
11180 | TautologicalTypeCompare = true; | |||
11181 | ||||
11182 | // If this is a comparison to an enum constant, include that | |||
11183 | // constant in the diagnostic. | |||
11184 | const EnumConstantDecl *ED = nullptr; | |||
11185 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) | |||
11186 | ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); | |||
11187 | ||||
11188 | // Should be enough for uint128 (39 decimal digits) | |||
11189 | SmallString<64> PrettySourceValue; | |||
11190 | llvm::raw_svector_ostream OS(PrettySourceValue); | |||
11191 | if (ED) { | |||
11192 | OS << '\'' << *ED << "' (" << Value << ")"; | |||
11193 | } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( | |||
11194 | Constant->IgnoreParenImpCasts())) { | |||
11195 | OS << (BL->getValue() ? "YES" : "NO"); | |||
11196 | } else { | |||
11197 | OS << Value; | |||
11198 | } | |||
11199 | ||||
11200 | if (!TautologicalTypeCompare) { | |||
11201 | S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) | |||
11202 | << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative | |||
11203 | << E->getOpcodeStr() << OS.str() << *Result | |||
11204 | << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); | |||
11205 | return true; | |||
11206 | } | |||
11207 | ||||
11208 | if (IsObjCSignedCharBool) { | |||
11209 | S.DiagRuntimeBehavior(E->getOperatorLoc(), E, | |||
11210 | S.PDiag(diag::warn_tautological_compare_objc_bool) | |||
11211 | << OS.str() << *Result); | |||
11212 | return true; | |||
11213 | } | |||
11214 | ||||
11215 | // FIXME: We use a somewhat different formatting for the in-range cases and | |||
11216 | // cases involving boolean values for historical reasons. We should pick a | |||
11217 | // consistent way of presenting these diagnostics. | |||
11218 | if (!InRange || Other->isKnownToHaveBooleanValue()) { | |||
11219 | ||||
11220 | S.DiagRuntimeBehavior( | |||
11221 | E->getOperatorLoc(), E, | |||
11222 | S.PDiag(!InRange ? diag::warn_out_of_range_compare | |||
11223 | : diag::warn_tautological_bool_compare) | |||
11224 | << OS.str() << classifyConstantValue(Constant) << OtherT | |||
11225 | << OtherIsBooleanDespiteType << *Result | |||
11226 | << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); | |||
11227 | } else { | |||
11228 | unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) | |||
11229 | ? (HasEnumType(OriginalOther) | |||
11230 | ? diag::warn_unsigned_enum_always_true_comparison | |||
11231 | : diag::warn_unsigned_always_true_comparison) | |||
11232 | : diag::warn_tautological_constant_compare; | |||
11233 | ||||
11234 | S.Diag(E->getOperatorLoc(), Diag) | |||
11235 | << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result | |||
11236 | << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); | |||
11237 | } | |||
11238 | ||||
11239 | return true; | |||
11240 | } | |||
11241 | ||||
11242 | /// Analyze the operands of the given comparison. Implements the | |||
11243 | /// fallback case from AnalyzeComparison. | |||
11244 | static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { | |||
11245 | AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); | |||
11246 | AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); | |||
11247 | } | |||
11248 | ||||
11249 | /// Implements -Wsign-compare. | |||
11250 | /// | |||
11251 | /// \param E the binary operator to check for warnings | |||
11252 | static void AnalyzeComparison(Sema &S, BinaryOperator *E) { | |||
11253 | // The type the comparison is being performed in. | |||
11254 | QualType T = E->getLHS()->getType(); | |||
11255 | ||||
11256 | // Only analyze comparison operators where both sides have been converted to | |||
11257 | // the same type. | |||
11258 | if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) | |||
11259 | return AnalyzeImpConvsInComparison(S, E); | |||
11260 | ||||
11261 | // Don't analyze value-dependent comparisons directly. | |||
11262 | if (E->isValueDependent()) | |||
11263 | return AnalyzeImpConvsInComparison(S, E); | |||
11264 | ||||
11265 | Expr *LHS = E->getLHS(); | |||
11266 | Expr *RHS = E->getRHS(); | |||
11267 | ||||
11268 | if (T->isIntegralType(S.Context)) { | |||
11269 | Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); | |||
11270 | Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); | |||
11271 | ||||
11272 | // We don't care about expressions whose result is a constant. | |||
11273 | if (RHSValue && LHSValue) | |||
11274 | return AnalyzeImpConvsInComparison(S, E); | |||
11275 | ||||
11276 | // We only care about expressions where just one side is literal | |||
11277 | if ((bool)RHSValue ^ (bool)LHSValue) { | |||
11278 | // Is the constant on the RHS or LHS? | |||
11279 | const bool RhsConstant = (bool)RHSValue; | |||
11280 | Expr *Const = RhsConstant ? RHS : LHS; | |||
11281 | Expr *Other = RhsConstant ? LHS : RHS; | |||
11282 | const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; | |||
11283 | ||||
11284 | // Check whether an integer constant comparison results in a value | |||
11285 | // of 'true' or 'false'. | |||
11286 | if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) | |||
11287 | return AnalyzeImpConvsInComparison(S, E); | |||
11288 | } | |||
11289 | } | |||
11290 | ||||
11291 | if (!T->hasUnsignedIntegerRepresentation()) { | |||
11292 | // We don't do anything special if this isn't an unsigned integral | |||
11293 | // comparison: we're only interested in integral comparisons, and | |||
11294 | // signed comparisons only happen in cases we don't care to warn about. | |||
11295 | return AnalyzeImpConvsInComparison(S, E); | |||
11296 | } | |||
11297 | ||||
11298 | LHS = LHS->IgnoreParenImpCasts(); | |||
11299 | RHS = RHS->IgnoreParenImpCasts(); | |||
11300 | ||||
11301 | if (!S.getLangOpts().CPlusPlus) { | |||
11302 | // Avoid warning about comparison of integers with different signs when | |||
11303 | // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of | |||
11304 | // the type of `E`. | |||
11305 | if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) | |||
11306 | LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); | |||
11307 | if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) | |||
11308 | RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); | |||
11309 | } | |||
11310 | ||||
11311 | // Check to see if one of the (unmodified) operands is of different | |||
11312 | // signedness. | |||
11313 | Expr *signedOperand, *unsignedOperand; | |||
11314 | if (LHS->getType()->hasSignedIntegerRepresentation()) { | |||
11315 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11316, __PRETTY_FUNCTION__)) | |||
11316 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11316, __PRETTY_FUNCTION__)); | |||
11317 | signedOperand = LHS; | |||
11318 | unsignedOperand = RHS; | |||
11319 | } else if (RHS->getType()->hasSignedIntegerRepresentation()) { | |||
11320 | signedOperand = RHS; | |||
11321 | unsignedOperand = LHS; | |||
11322 | } else { | |||
11323 | return AnalyzeImpConvsInComparison(S, E); | |||
11324 | } | |||
11325 | ||||
11326 | // Otherwise, calculate the effective range of the signed operand. | |||
11327 | IntRange signedRange = GetExprRange( | |||
11328 | S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); | |||
11329 | ||||
11330 | // Go ahead and analyze implicit conversions in the operands. Note | |||
11331 | // that we skip the implicit conversions on both sides. | |||
11332 | AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); | |||
11333 | AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); | |||
11334 | ||||
11335 | // If the signed range is non-negative, -Wsign-compare won't fire. | |||
11336 | if (signedRange.NonNegative) | |||
11337 | return; | |||
11338 | ||||
11339 | // For (in)equality comparisons, if the unsigned operand is a | |||
11340 | // constant which cannot collide with a overflowed signed operand, | |||
11341 | // then reinterpreting the signed operand as unsigned will not | |||
11342 | // change the result of the comparison. | |||
11343 | if (E->isEqualityOp()) { | |||
11344 | unsigned comparisonWidth = S.Context.getIntWidth(T); | |||
11345 | IntRange unsignedRange = | |||
11346 | GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), | |||
11347 | /*Approximate*/ true); | |||
11348 | ||||
11349 | // We should never be unable to prove that the unsigned operand is | |||
11350 | // non-negative. | |||
11351 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11351, __PRETTY_FUNCTION__)); | |||
11352 | ||||
11353 | if (unsignedRange.Width < comparisonWidth) | |||
11354 | return; | |||
11355 | } | |||
11356 | ||||
11357 | S.DiagRuntimeBehavior(E->getOperatorLoc(), E, | |||
11358 | S.PDiag(diag::warn_mixed_sign_comparison) | |||
11359 | << LHS->getType() << RHS->getType() | |||
11360 | << LHS->getSourceRange() << RHS->getSourceRange()); | |||
11361 | } | |||
11362 | ||||
11363 | /// Analyzes an attempt to assign the given value to a bitfield. | |||
11364 | /// | |||
11365 | /// Returns true if there was something fishy about the attempt. | |||
11366 | static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, | |||
11367 | SourceLocation InitLoc) { | |||
11368 | assert(Bitfield->isBitField())((Bitfield->isBitField()) ? static_cast<void> (0) : __assert_fail ("Bitfield->isBitField()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11368, __PRETTY_FUNCTION__)); | |||
11369 | if (Bitfield->isInvalidDecl()) | |||
11370 | return false; | |||
11371 | ||||
11372 | // White-list bool bitfields. | |||
11373 | QualType BitfieldType = Bitfield->getType(); | |||
11374 | if (BitfieldType->isBooleanType()) | |||
11375 | return false; | |||
11376 | ||||
11377 | if (BitfieldType->isEnumeralType()) { | |||
11378 | EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); | |||
11379 | // If the underlying enum type was not explicitly specified as an unsigned | |||
11380 | // type and the enum contain only positive values, MSVC++ will cause an | |||
11381 | // inconsistency by storing this as a signed type. | |||
11382 | if (S.getLangOpts().CPlusPlus11 && | |||
11383 | !BitfieldEnumDecl->getIntegerTypeSourceInfo() && | |||
11384 | BitfieldEnumDecl->getNumPositiveBits() > 0 && | |||
11385 | BitfieldEnumDecl->getNumNegativeBits() == 0) { | |||
11386 | S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) | |||
11387 | << BitfieldEnumDecl; | |||
11388 | } | |||
11389 | } | |||
11390 | ||||
11391 | if (Bitfield->getType()->isBooleanType()) | |||
11392 | return false; | |||
11393 | ||||
11394 | // Ignore value- or type-dependent expressions. | |||
11395 | if (Bitfield->getBitWidth()->isValueDependent() || | |||
11396 | Bitfield->getBitWidth()->isTypeDependent() || | |||
11397 | Init->isValueDependent() || | |||
11398 | Init->isTypeDependent()) | |||
11399 | return false; | |||
11400 | ||||
11401 | Expr *OriginalInit = Init->IgnoreParenImpCasts(); | |||
11402 | unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); | |||
11403 | ||||
11404 | Expr::EvalResult Result; | |||
11405 | if (!OriginalInit->EvaluateAsInt(Result, S.Context, | |||
11406 | Expr::SE_AllowSideEffects)) { | |||
11407 | // The RHS is not constant. If the RHS has an enum type, make sure the | |||
11408 | // bitfield is wide enough to hold all the values of the enum without | |||
11409 | // truncation. | |||
11410 | if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { | |||
11411 | EnumDecl *ED = EnumTy->getDecl(); | |||
11412 | bool SignedBitfield = BitfieldType->isSignedIntegerType(); | |||
11413 | ||||
11414 | // Enum types are implicitly signed on Windows, so check if there are any | |||
11415 | // negative enumerators to see if the enum was intended to be signed or | |||
11416 | // not. | |||
11417 | bool SignedEnum = ED->getNumNegativeBits() > 0; | |||
11418 | ||||
11419 | // Check for surprising sign changes when assigning enum values to a | |||
11420 | // bitfield of different signedness. If the bitfield is signed and we | |||
11421 | // have exactly the right number of bits to store this unsigned enum, | |||
11422 | // suggest changing the enum to an unsigned type. This typically happens | |||
11423 | // on Windows where unfixed enums always use an underlying type of 'int'. | |||
11424 | unsigned DiagID = 0; | |||
11425 | if (SignedEnum && !SignedBitfield) { | |||
11426 | DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; | |||
11427 | } else if (SignedBitfield && !SignedEnum && | |||
11428 | ED->getNumPositiveBits() == FieldWidth) { | |||
11429 | DiagID = diag::warn_signed_bitfield_enum_conversion; | |||
11430 | } | |||
11431 | ||||
11432 | if (DiagID) { | |||
11433 | S.Diag(InitLoc, DiagID) << Bitfield << ED; | |||
11434 | TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); | |||
11435 | SourceRange TypeRange = | |||
11436 | TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); | |||
11437 | S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) | |||
11438 | << SignedEnum << TypeRange; | |||
11439 | } | |||
11440 | ||||
11441 | // Compute the required bitwidth. If the enum has negative values, we need | |||
11442 | // one more bit than the normal number of positive bits to represent the | |||
11443 | // sign bit. | |||
11444 | unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, | |||
11445 | ED->getNumNegativeBits()) | |||
11446 | : ED->getNumPositiveBits(); | |||
11447 | ||||
11448 | // Check the bitwidth. | |||
11449 | if (BitsNeeded > FieldWidth) { | |||
11450 | Expr *WidthExpr = Bitfield->getBitWidth(); | |||
11451 | S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) | |||
11452 | << Bitfield << ED; | |||
11453 | S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) | |||
11454 | << BitsNeeded << ED << WidthExpr->getSourceRange(); | |||
11455 | } | |||
11456 | } | |||
11457 | ||||
11458 | return false; | |||
11459 | } | |||
11460 | ||||
11461 | llvm::APSInt Value = Result.Val.getInt(); | |||
11462 | ||||
11463 | unsigned OriginalWidth = Value.getBitWidth(); | |||
11464 | ||||
11465 | if (!Value.isSigned() || Value.isNegative()) | |||
11466 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) | |||
11467 | if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) | |||
11468 | OriginalWidth = Value.getMinSignedBits(); | |||
11469 | ||||
11470 | if (OriginalWidth <= FieldWidth) | |||
11471 | return false; | |||
11472 | ||||
11473 | // Compute the value which the bitfield will contain. | |||
11474 | llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); | |||
11475 | TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); | |||
11476 | ||||
11477 | // Check whether the stored value is equal to the original value. | |||
11478 | TruncatedValue = TruncatedValue.extend(OriginalWidth); | |||
11479 | if (llvm::APSInt::isSameValue(Value, TruncatedValue)) | |||
11480 | return false; | |||
11481 | ||||
11482 | // Special-case bitfields of width 1: booleans are naturally 0/1, and | |||
11483 | // therefore don't strictly fit into a signed bitfield of width 1. | |||
11484 | if (FieldWidth == 1 && Value == 1) | |||
11485 | return false; | |||
11486 | ||||
11487 | std::string PrettyValue = Value.toString(10); | |||
11488 | std::string PrettyTrunc = TruncatedValue.toString(10); | |||
11489 | ||||
11490 | S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) | |||
11491 | << PrettyValue << PrettyTrunc << OriginalInit->getType() | |||
11492 | << Init->getSourceRange(); | |||
11493 | ||||
11494 | return true; | |||
11495 | } | |||
11496 | ||||
11497 | /// Analyze the given simple or compound assignment for warning-worthy | |||
11498 | /// operations. | |||
11499 | static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { | |||
11500 | // Just recurse on the LHS. | |||
11501 | AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); | |||
11502 | ||||
11503 | // We want to recurse on the RHS as normal unless we're assigning to | |||
11504 | // a bitfield. | |||
11505 | if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { | |||
11506 | if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), | |||
11507 | E->getOperatorLoc())) { | |||
11508 | // Recurse, ignoring any implicit conversions on the RHS. | |||
11509 | return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), | |||
11510 | E->getOperatorLoc()); | |||
11511 | } | |||
11512 | } | |||
11513 | ||||
11514 | AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); | |||
11515 | ||||
11516 | // Diagnose implicitly sequentially-consistent atomic assignment. | |||
11517 | if (E->getLHS()->getType()->isAtomicType()) | |||
11518 | S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); | |||
11519 | } | |||
11520 | ||||
11521 | /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. | |||
11522 | static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, | |||
11523 | SourceLocation CContext, unsigned diag, | |||
11524 | bool pruneControlFlow = false) { | |||
11525 | if (pruneControlFlow) { | |||
11526 | S.DiagRuntimeBehavior(E->getExprLoc(), E, | |||
11527 | S.PDiag(diag) | |||
11528 | << SourceType << T << E->getSourceRange() | |||
11529 | << SourceRange(CContext)); | |||
11530 | return; | |||
11531 | } | |||
11532 | S.Diag(E->getExprLoc(), diag) | |||
11533 | << SourceType << T << E->getSourceRange() << SourceRange(CContext); | |||
11534 | } | |||
11535 | ||||
11536 | /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. | |||
11537 | static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, | |||
11538 | SourceLocation CContext, | |||
11539 | unsigned diag, bool pruneControlFlow = false) { | |||
11540 | DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); | |||
11541 | } | |||
11542 | ||||
11543 | static bool isObjCSignedCharBool(Sema &S, QualType Ty) { | |||
11544 | return Ty->isSpecificBuiltinType(BuiltinType::SChar) && | |||
11545 | S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); | |||
11546 | } | |||
11547 | ||||
11548 | static void adornObjCBoolConversionDiagWithTernaryFixit( | |||
11549 | Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { | |||
11550 | Expr *Ignored = SourceExpr->IgnoreImplicit(); | |||
11551 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) | |||
11552 | Ignored = OVE->getSourceExpr(); | |||
11553 | bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || | |||
11554 | isa<BinaryOperator>(Ignored) || | |||
11555 | isa<CXXOperatorCallExpr>(Ignored); | |||
11556 | SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); | |||
11557 | if (NeedsParens) | |||
11558 | Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") | |||
11559 | << FixItHint::CreateInsertion(EndLoc, ")"); | |||
11560 | Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); | |||
11561 | } | |||
11562 | ||||
11563 | /// Diagnose an implicit cast from a floating point value to an integer value. | |||
11564 | static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, | |||
11565 | SourceLocation CContext) { | |||
11566 | const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); | |||
11567 | const bool PruneWarnings = S.inTemplateInstantiation(); | |||
11568 | ||||
11569 | Expr *InnerE = E->IgnoreParenImpCasts(); | |||
11570 | // We also want to warn on, e.g., "int i = -1.234" | |||
11571 | if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) | |||
11572 | if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) | |||
11573 | InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); | |||
11574 | ||||
11575 | const bool IsLiteral = | |||
11576 | isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); | |||
11577 | ||||
11578 | llvm::APFloat Value(0.0); | |||
11579 | bool IsConstant = | |||
11580 | E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); | |||
11581 | if (!IsConstant) { | |||
11582 | if (isObjCSignedCharBool(S, T)) { | |||
11583 | return adornObjCBoolConversionDiagWithTernaryFixit( | |||
11584 | S, E, | |||
11585 | S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) | |||
11586 | << E->getType()); | |||
11587 | } | |||
11588 | ||||
11589 | return DiagnoseImpCast(S, E, T, CContext, | |||
11590 | diag::warn_impcast_float_integer, PruneWarnings); | |||
11591 | } | |||
11592 | ||||
11593 | bool isExact = false; | |||
11594 | ||||
11595 | llvm::APSInt IntegerValue(S.Context.getIntWidth(T), | |||
11596 | T->hasUnsignedIntegerRepresentation()); | |||
11597 | llvm::APFloat::opStatus Result = Value.convertToInteger( | |||
11598 | IntegerValue, llvm::APFloat::rmTowardZero, &isExact); | |||
11599 | ||||
11600 | // FIXME: Force the precision of the source value down so we don't print | |||
11601 | // digits which are usually useless (we don't really care here if we | |||
11602 | // truncate a digit by accident in edge cases). Ideally, APFloat::toString | |||
11603 | // would automatically print the shortest representation, but it's a bit | |||
11604 | // tricky to implement. | |||
11605 | SmallString<16> PrettySourceValue; | |||
11606 | unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); | |||
11607 | precision = (precision * 59 + 195) / 196; | |||
11608 | Value.toString(PrettySourceValue, precision); | |||
11609 | ||||
11610 | if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { | |||
11611 | return adornObjCBoolConversionDiagWithTernaryFixit( | |||
11612 | S, E, | |||
11613 | S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) | |||
11614 | << PrettySourceValue); | |||
11615 | } | |||
11616 | ||||
11617 | if (Result == llvm::APFloat::opOK && isExact) { | |||
11618 | if (IsLiteral) return; | |||
11619 | return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, | |||
11620 | PruneWarnings); | |||
11621 | } | |||
11622 | ||||
11623 | // Conversion of a floating-point value to a non-bool integer where the | |||
11624 | // integral part cannot be represented by the integer type is undefined. | |||
11625 | if (!IsBool && Result == llvm::APFloat::opInvalidOp) | |||
11626 | return DiagnoseImpCast( | |||
11627 | S, E, T, CContext, | |||
11628 | IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range | |||
11629 | : diag::warn_impcast_float_to_integer_out_of_range, | |||
11630 | PruneWarnings); | |||
11631 | ||||
11632 | unsigned DiagID = 0; | |||
11633 | if (IsLiteral) { | |||
11634 | // Warn on floating point literal to integer. | |||
11635 | DiagID = diag::warn_impcast_literal_float_to_integer; | |||
11636 | } else if (IntegerValue == 0) { | |||
11637 | if (Value.isZero()) { // Skip -0.0 to 0 conversion. | |||
11638 | return DiagnoseImpCast(S, E, T, CContext, | |||
11639 | diag::warn_impcast_float_integer, PruneWarnings); | |||
11640 | } | |||
11641 | // Warn on non-zero to zero conversion. | |||
11642 | DiagID = diag::warn_impcast_float_to_integer_zero; | |||
11643 | } else { | |||
11644 | if (IntegerValue.isUnsigned()) { | |||
11645 | if (!IntegerValue.isMaxValue()) { | |||
11646 | return DiagnoseImpCast(S, E, T, CContext, | |||
11647 | diag::warn_impcast_float_integer, PruneWarnings); | |||
11648 | } | |||
11649 | } else { // IntegerValue.isSigned() | |||
11650 | if (!IntegerValue.isMaxSignedValue() && | |||
11651 | !IntegerValue.isMinSignedValue()) { | |||
11652 | return DiagnoseImpCast(S, E, T, CContext, | |||
11653 | diag::warn_impcast_float_integer, PruneWarnings); | |||
11654 | } | |||
11655 | } | |||
11656 | // Warn on evaluatable floating point expression to integer conversion. | |||
11657 | DiagID = diag::warn_impcast_float_to_integer; | |||
11658 | } | |||
11659 | ||||
11660 | SmallString<16> PrettyTargetValue; | |||
11661 | if (IsBool) | |||
11662 | PrettyTargetValue = Value.isZero() ? "false" : "true"; | |||
11663 | else | |||
11664 | IntegerValue.toString(PrettyTargetValue); | |||
11665 | ||||
11666 | if (PruneWarnings) { | |||
11667 | S.DiagRuntimeBehavior(E->getExprLoc(), E, | |||
11668 | S.PDiag(DiagID) | |||
11669 | << E->getType() << T.getUnqualifiedType() | |||
11670 | << PrettySourceValue << PrettyTargetValue | |||
11671 | << E->getSourceRange() << SourceRange(CContext)); | |||
11672 | } else { | |||
11673 | S.Diag(E->getExprLoc(), DiagID) | |||
11674 | << E->getType() << T.getUnqualifiedType() << PrettySourceValue | |||
11675 | << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); | |||
11676 | } | |||
11677 | } | |||
11678 | ||||
11679 | /// Analyze the given compound assignment for the possible losing of | |||
11680 | /// floating-point precision. | |||
11681 | static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { | |||
11682 | assert(isa<CompoundAssignOperator>(E) &&((isa<CompoundAssignOperator>(E) && "Must be compound assignment operation" ) ? static_cast<void> (0) : __assert_fail ("isa<CompoundAssignOperator>(E) && \"Must be compound assignment operation\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11683, __PRETTY_FUNCTION__)) | |||
11683 | "Must be compound assignment operation")((isa<CompoundAssignOperator>(E) && "Must be compound assignment operation" ) ? static_cast<void> (0) : __assert_fail ("isa<CompoundAssignOperator>(E) && \"Must be compound assignment operation\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 11683, __PRETTY_FUNCTION__)); | |||
11684 | // Recurse on the LHS and RHS in here | |||
11685 | AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); | |||
11686 | AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); | |||
11687 | ||||
11688 | if (E->getLHS()->getType()->isAtomicType()) | |||
11689 | S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); | |||
11690 | ||||
11691 | // Now check the outermost expression | |||
11692 | const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); | |||
11693 | const auto *RBT = cast<CompoundAssignOperator>(E) | |||
11694 | ->getComputationResultType() | |||
11695 | ->getAs<BuiltinType>(); | |||
11696 | ||||
11697 | // The below checks assume source is floating point. | |||
11698 | if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; | |||
11699 | ||||
11700 | // If source is floating point but target is an integer. | |||
11701 | if (ResultBT->isInteger()) | |||
11702 | return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), | |||
11703 | E->getExprLoc(), diag::warn_impcast_float_integer); | |||
11704 | ||||
11705 | if (!ResultBT->isFloatingPoint()) | |||
11706 | return; | |||
11707 | ||||
11708 | // If both source and target are floating points, warn about losing precision. | |||
11709 | int Order = S.getASTContext().getFloatingTypeSemanticOrder( | |||
11710 | QualType(ResultBT, 0), QualType(RBT, 0)); | |||
11711 | if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) | |||
11712 | // warn about dropping FP rank. | |||
11713 | DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), | |||
11714 | diag::warn_impcast_float_result_precision); | |||
11715 | } | |||
11716 | ||||
11717 | static std::string PrettyPrintInRange(const llvm::APSInt &Value, | |||
11718 | IntRange Range) { | |||
11719 | if (!Range.Width) return "0"; | |||
11720 | ||||
11721 | llvm::APSInt ValueInRange = Value; | |||
11722 | ValueInRange.setIsSigned(!Range.NonNegative); | |||
11723 | ValueInRange = ValueInRange.trunc(Range.Width); | |||
11724 | return ValueInRange.toString(10); | |||
11725 | } | |||
11726 | ||||
11727 | static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { | |||
11728 | if (!isa<ImplicitCastExpr>(Ex)) | |||
11729 | return false; | |||
11730 | ||||
11731 | Expr *InnerE = Ex->IgnoreParenImpCasts(); | |||
11732 | const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); | |||
11733 | const Type *Source = | |||
11734 | S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); | |||
11735 | if (Target->isDependentType()) | |||
11736 | return false; | |||
11737 | ||||
11738 | const BuiltinType *FloatCandidateBT = | |||
11739 | dyn_cast<BuiltinType>(ToBool ? Source : Target); | |||
11740 | const Type *BoolCandidateType = ToBool ? Target : Source; | |||
11741 | ||||
11742 | return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && | |||
11743 | FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); | |||
11744 | } | |||
11745 | ||||
11746 | static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, | |||
11747 | SourceLocation CC) { | |||
11748 | unsigned NumArgs = TheCall->getNumArgs(); | |||
11749 | for (unsigned i = 0; i < NumArgs; ++i) { | |||
11750 | Expr *CurrA = TheCall->getArg(i); | |||
11751 | if (!IsImplicitBoolFloatConversion(S, CurrA, true)) | |||
11752 | continue; | |||
11753 | ||||
11754 | bool IsSwapped = ((i > 0) && | |||
11755 | IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); | |||
11756 | IsSwapped |= ((i < (NumArgs - 1)) && | |||
11757 | IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); | |||
11758 | if (IsSwapped) { | |||
11759 | // Warn on this floating-point to bool conversion. | |||
11760 | DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), | |||
11761 | CurrA->getType(), CC, | |||
11762 | diag::warn_impcast_floating_point_to_bool); | |||
11763 | } | |||
11764 | } | |||
11765 | } | |||
11766 | ||||
11767 | static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, | |||
11768 | SourceLocation CC) { | |||
11769 | if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, | |||
11770 | E->getExprLoc())) | |||
11771 | return; | |||
11772 | ||||
11773 | // Don't warn on functions which have return type nullptr_t. | |||
11774 | if (isa<CallExpr>(E)) | |||
11775 | return; | |||
11776 | ||||
11777 | // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). | |||
11778 | const Expr::NullPointerConstantKind NullKind = | |||
11779 | E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); | |||
11780 | if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) | |||
11781 | return; | |||
11782 | ||||
11783 | // Return if target type is a safe conversion. | |||
11784 | if (T->isAnyPointerType() || T->isBlockPointerType() || | |||
11785 | T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) | |||
11786 | return; | |||
11787 | ||||
11788 | SourceLocation Loc = E->getSourceRange().getBegin(); | |||
11789 | ||||
11790 | // Venture through the macro stacks to get to the source of macro arguments. | |||
11791 | // The new location is a better location than the complete location that was | |||
11792 | // passed in. | |||
11793 | Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); | |||
11794 | CC = S.SourceMgr.getTopMacroCallerLoc(CC); | |||
11795 | ||||
11796 | // __null is usually wrapped in a macro. Go up a macro if that is the case. | |||
11797 | if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { | |||
11798 | StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( | |||
11799 | Loc, S.SourceMgr, S.getLangOpts()); | |||
11800 | if (MacroName == "NULL") | |||
11801 | Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); | |||
11802 | } | |||
11803 | ||||
11804 | // Only warn if the null and context location are in the same macro expansion. | |||
11805 | if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) | |||
11806 | return; | |||
11807 | ||||
11808 | S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) | |||
11809 | << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) | |||
11810 | << FixItHint::CreateReplacement(Loc, | |||
11811 | S.getFixItZeroLiteralForType(T, Loc)); | |||
11812 | } | |||
11813 | ||||
11814 | static void checkObjCArrayLiteral(Sema &S, QualType TargetType, | |||
11815 | ObjCArrayLiteral *ArrayLiteral); | |||
11816 | ||||
11817 | static void | |||
11818 | checkObjCDictionaryLiteral(Sema &S, QualType TargetType, | |||
11819 | ObjCDictionaryLiteral *DictionaryLiteral); | |||
11820 | ||||
11821 | /// Check a single element within a collection literal against the | |||
11822 | /// target element type. | |||
11823 | static void checkObjCCollectionLiteralElement(Sema &S, | |||
11824 | QualType TargetElementType, | |||
11825 | Expr *Element, | |||
11826 | unsigned ElementKind) { | |||
11827 | // Skip a bitcast to 'id' or qualified 'id'. | |||
11828 | if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { | |||
11829 | if (ICE->getCastKind() == CK_BitCast && | |||
11830 | ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) | |||
11831 | Element = ICE->getSubExpr(); | |||
11832 | } | |||
11833 | ||||
11834 | QualType ElementType = Element->getType(); | |||
11835 | ExprResult ElementResult(Element); | |||
11836 | if (ElementType->getAs<ObjCObjectPointerType>() && | |||
11837 | S.CheckSingleAssignmentConstraints(TargetElementType, | |||
11838 | ElementResult, | |||
11839 | false, false) | |||
11840 | != Sema::Compatible) { | |||
11841 | S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) | |||
11842 | << ElementType << ElementKind << TargetElementType | |||
11843 | << Element->getSourceRange(); | |||
11844 | } | |||
11845 | ||||
11846 | if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) | |||
11847 | checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); | |||
11848 | else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) | |||
11849 | checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); | |||
11850 | } | |||
11851 | ||||
11852 | /// Check an Objective-C array literal being converted to the given | |||
11853 | /// target type. | |||
11854 | static void checkObjCArrayLiteral(Sema &S, QualType TargetType, | |||
11855 | ObjCArrayLiteral *ArrayLiteral) { | |||
11856 | if (!S.NSArrayDecl) | |||
11857 | return; | |||
11858 | ||||
11859 | const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); | |||
11860 | if (!TargetObjCPtr) | |||
11861 | return; | |||
11862 | ||||
11863 | if (TargetObjCPtr->isUnspecialized() || | |||
11864 | TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() | |||
11865 | != S.NSArrayDecl->getCanonicalDecl()) | |||
11866 | return; | |||
11867 | ||||
11868 | auto TypeArgs = TargetObjCPtr->getTypeArgs(); | |||
11869 | if (TypeArgs.size() != 1) | |||
11870 | return; | |||
11871 | ||||
11872 | QualType TargetElementType = TypeArgs[0]; | |||
11873 | for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { | |||
11874 | checkObjCCollectionLiteralElement(S, TargetElementType, | |||
11875 | ArrayLiteral->getElement(I), | |||
11876 | 0); | |||
11877 | } | |||
11878 | } | |||
11879 | ||||
11880 | /// Check an Objective-C dictionary literal being converted to the given | |||
11881 | /// target type. | |||
11882 | static void | |||
11883 | checkObjCDictionaryLiteral(Sema &S, QualType TargetType, | |||
11884 | ObjCDictionaryLiteral *DictionaryLiteral) { | |||
11885 | if (!S.NSDictionaryDecl) | |||
11886 | return; | |||
11887 | ||||
11888 | const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); | |||
11889 | if (!TargetObjCPtr) | |||
11890 | return; | |||
11891 | ||||
11892 | if (TargetObjCPtr->isUnspecialized() || | |||
11893 | TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() | |||
11894 | != S.NSDictionaryDecl->getCanonicalDecl()) | |||
11895 | return; | |||
11896 | ||||
11897 | auto TypeArgs = TargetObjCPtr->getTypeArgs(); | |||
11898 | if (TypeArgs.size() != 2) | |||
11899 | return; | |||
11900 | ||||
11901 | QualType TargetKeyType = TypeArgs[0]; | |||
11902 | QualType TargetObjectType = TypeArgs[1]; | |||
11903 | for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { | |||
11904 | auto Element = DictionaryLiteral->getKeyValueElement(I); | |||
11905 | checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); | |||
11906 | checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); | |||
11907 | } | |||
11908 | } | |||
11909 | ||||
11910 | // Helper function to filter out cases for constant width constant conversion. | |||
11911 | // Don't warn on char array initialization or for non-decimal values. | |||
11912 | static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, | |||
11913 | SourceLocation CC) { | |||
11914 | // If initializing from a constant, and the constant starts with '0', | |||
11915 | // then it is a binary, octal, or hexadecimal. Allow these constants | |||
11916 | // to fill all the bits, even if there is a sign change. | |||
11917 | if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { | |||
11918 | const char FirstLiteralCharacter = | |||
11919 | S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; | |||
11920 | if (FirstLiteralCharacter == '0') | |||
11921 | return false; | |||
11922 | } | |||
11923 | ||||
11924 | // If the CC location points to a '{', and the type is char, then assume | |||
11925 | // assume it is an array initialization. | |||
11926 | if (CC.isValid() && T->isCharType()) { | |||
11927 | const char FirstContextCharacter = | |||
11928 | S.getSourceManager().getCharacterData(CC)[0]; | |||
11929 | if (FirstContextCharacter == '{') | |||
11930 | return false; | |||
11931 | } | |||
11932 | ||||
11933 | return true; | |||
11934 | } | |||
11935 | ||||
11936 | static const IntegerLiteral *getIntegerLiteral(Expr *E) { | |||
11937 | const auto *IL = dyn_cast<IntegerLiteral>(E); | |||
11938 | if (!IL) { | |||
11939 | if (auto *UO = dyn_cast<UnaryOperator>(E)) { | |||
11940 | if (UO->getOpcode() == UO_Minus) | |||
11941 | return dyn_cast<IntegerLiteral>(UO->getSubExpr()); | |||
11942 | } | |||
11943 | } | |||
11944 | ||||
11945 | return IL; | |||
11946 | } | |||
11947 | ||||
11948 | static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { | |||
11949 | E = E->IgnoreParenImpCasts(); | |||
11950 | SourceLocation ExprLoc = E->getExprLoc(); | |||
11951 | ||||
11952 | if (const auto *BO = dyn_cast<BinaryOperator>(E)) { | |||
11953 | BinaryOperator::Opcode Opc = BO->getOpcode(); | |||
11954 | Expr::EvalResult Result; | |||
11955 | // Do not diagnose unsigned shifts. | |||
11956 | if (Opc == BO_Shl) { | |||
11957 | const auto *LHS = getIntegerLiteral(BO->getLHS()); | |||
11958 | const auto *RHS = getIntegerLiteral(BO->getRHS()); | |||
11959 | if (LHS && LHS->getValue() == 0) | |||
11960 | S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; | |||
11961 | else if (!E->isValueDependent() && LHS && RHS && | |||
11962 | RHS->getValue().isNonNegative() && | |||
11963 | E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) | |||
11964 | S.Diag(ExprLoc, diag::warn_left_shift_always) | |||
11965 | << (Result.Val.getInt() != 0); | |||
11966 | else if (E->getType()->isSignedIntegerType()) | |||
11967 | S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; | |||
11968 | } | |||
11969 | } | |||
11970 | ||||
11971 | if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { | |||
11972 | const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); | |||
11973 | const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); | |||
11974 | if (!LHS || !RHS) | |||
11975 | return; | |||
11976 | if ((LHS->getValue() == 0 || LHS->getValue() == 1) && | |||
11977 | (RHS->getValue() == 0 || RHS->getValue() == 1)) | |||
11978 | // Do not diagnose common idioms. | |||
11979 | return; | |||
11980 | if (LHS->getValue() != 0 && RHS->getValue() != 0) | |||
11981 | S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); | |||
11982 | } | |||
11983 | } | |||
11984 | ||||
11985 | static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, | |||
11986 | SourceLocation CC, | |||
11987 | bool *ICContext = nullptr, | |||
11988 | bool IsListInit = false) { | |||
11989 | if (E->isTypeDependent() || E->isValueDependent()) return; | |||
11990 | ||||
11991 | const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); | |||
11992 | const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); | |||
11993 | if (Source == Target) return; | |||
11994 | if (Target->isDependentType()) return; | |||
11995 | ||||
11996 | // If the conversion context location is invalid don't complain. We also | |||
11997 | // don't want to emit a warning if the issue occurs from the expansion of | |||
11998 | // a system macro. The problem is that 'getSpellingLoc()' is slow, so we | |||
11999 | // delay this check as long as possible. Once we detect we are in that | |||
12000 | // scenario, we just return. | |||
12001 | if (CC.isInvalid()) | |||
12002 | return; | |||
12003 | ||||
12004 | if (Source->isAtomicType()) | |||
12005 | S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); | |||
12006 | ||||
12007 | // Diagnose implicit casts to bool. | |||
12008 | if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { | |||
12009 | if (isa<StringLiteral>(E)) | |||
12010 | // Warn on string literal to bool. Checks for string literals in logical | |||
12011 | // and expressions, for instance, assert(0 && "error here"), are | |||
12012 | // prevented by a check in AnalyzeImplicitConversions(). | |||
12013 | return DiagnoseImpCast(S, E, T, CC, | |||
12014 | diag::warn_impcast_string_literal_to_bool); | |||
12015 | if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || | |||
12016 | isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { | |||
12017 | // This covers the literal expressions that evaluate to Objective-C | |||
12018 | // objects. | |||
12019 | return DiagnoseImpCast(S, E, T, CC, | |||
12020 | diag::warn_impcast_objective_c_literal_to_bool); | |||
12021 | } | |||
12022 | if (Source->isPointerType() || Source->canDecayToPointerType()) { | |||
12023 | // Warn on pointer to bool conversion that is always true. | |||
12024 | S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, | |||
12025 | SourceRange(CC)); | |||
12026 | } | |||
12027 | } | |||
12028 | ||||
12029 | // If the we're converting a constant to an ObjC BOOL on a platform where BOOL | |||
12030 | // is a typedef for signed char (macOS), then that constant value has to be 1 | |||
12031 | // or 0. | |||
12032 | if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { | |||
12033 | Expr::EvalResult Result; | |||
12034 | if (E->EvaluateAsInt(Result, S.getASTContext(), | |||
12035 | Expr::SE_AllowSideEffects)) { | |||
12036 | if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { | |||
12037 | adornObjCBoolConversionDiagWithTernaryFixit( | |||
12038 | S, E, | |||
12039 | S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) | |||
12040 | << Result.Val.getInt().toString(10)); | |||
12041 | } | |||
12042 | return; | |||
12043 | } | |||
12044 | } | |||
12045 | ||||
12046 | // Check implicit casts from Objective-C collection literals to specialized | |||
12047 | // collection types, e.g., NSArray<NSString *> *. | |||
12048 | if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) | |||
12049 | checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); | |||
12050 | else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) | |||
12051 | checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); | |||
12052 | ||||
12053 | // Strip vector types. | |||
12054 | if (isa<VectorType>(Source)) { | |||
12055 | if (!isa<VectorType>(Target)) { | |||
12056 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
12057 | return; | |||
12058 | return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); | |||
12059 | } | |||
12060 | ||||
12061 | // If the vector cast is cast between two vectors of the same size, it is | |||
12062 | // a bitcast, not a conversion. | |||
12063 | if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) | |||
12064 | return; | |||
12065 | ||||
12066 | Source = cast<VectorType>(Source)->getElementType().getTypePtr(); | |||
12067 | Target = cast<VectorType>(Target)->getElementType().getTypePtr(); | |||
12068 | } | |||
12069 | if (auto VecTy = dyn_cast<VectorType>(Target)) | |||
12070 | Target = VecTy->getElementType().getTypePtr(); | |||
12071 | ||||
12072 | // Strip complex types. | |||
12073 | if (isa<ComplexType>(Source)) { | |||
12074 | if (!isa<ComplexType>(Target)) { | |||
12075 | if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) | |||
12076 | return; | |||
12077 | ||||
12078 | return DiagnoseImpCast(S, E, T, CC, | |||
12079 | S.getLangOpts().CPlusPlus | |||
12080 | ? diag::err_impcast_complex_scalar | |||
12081 | : diag::warn_impcast_complex_scalar); | |||
12082 | } | |||
12083 | ||||
12084 | Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); | |||
12085 | Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); | |||
12086 | } | |||
12087 | ||||
12088 | const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); | |||
12089 | const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); | |||
12090 | ||||
12091 | // If the source is floating point... | |||
12092 | if (SourceBT && SourceBT->isFloatingPoint()) { | |||
12093 | // ...and the target is floating point... | |||
12094 | if (TargetBT && TargetBT->isFloatingPoint()) { | |||
12095 | // ...then warn if we're dropping FP rank. | |||
12096 | ||||
12097 | int Order = S.getASTContext().getFloatingTypeSemanticOrder( | |||
12098 | QualType(SourceBT, 0), QualType(TargetBT, 0)); | |||
12099 | if (Order > 0) { | |||
12100 | // Don't warn about float constants that are precisely | |||
12101 | // representable in the target type. | |||
12102 | Expr::EvalResult result; | |||
12103 | if (E->EvaluateAsRValue(result, S.Context)) { | |||
12104 | // Value might be a float, a float vector, or a float complex. | |||
12105 | if (IsSameFloatAfterCast(result.Val, | |||
12106 | S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), | |||
12107 | S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) | |||
12108 | return; | |||
12109 | } | |||
12110 | ||||
12111 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
12112 | return; | |||
12113 | ||||
12114 | DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); | |||
12115 | } | |||
12116 | // ... or possibly if we're increasing rank, too | |||
12117 | else if (Order < 0) { | |||
12118 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
12119 | return; | |||
12120 | ||||
12121 | DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); | |||
12122 | } | |||
12123 | return; | |||
12124 | } | |||
12125 | ||||
12126 | // If the target is integral, always warn. | |||
12127 | if (TargetBT && TargetBT->isInteger()) { | |||
12128 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
12129 | return; | |||
12130 | ||||
12131 | DiagnoseFloatingImpCast(S, E, T, CC); | |||
12132 | } | |||
12133 | ||||
12134 | // Detect the case where a call result is converted from floating-point to | |||
12135 | // to bool, and the final argument to the call is converted from bool, to | |||
12136 | // discover this typo: | |||
12137 | // | |||
12138 | // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" | |||
12139 | // | |||
12140 | // FIXME: This is an incredibly special case; is there some more general | |||
12141 | // way to detect this class of misplaced-parentheses bug? | |||
12142 | if (Target->isBooleanType() && isa<CallExpr>(E)) { | |||
12143 | // Check last argument of function call to see if it is an | |||
12144 | // implicit cast from a type matching the type the result | |||
12145 | // is being cast to. | |||
12146 | CallExpr *CEx = cast<CallExpr>(E); | |||
12147 | if (unsigned NumArgs = CEx->getNumArgs()) { | |||
12148 | Expr *LastA = CEx->getArg(NumArgs - 1); | |||
12149 | Expr *InnerE = LastA->IgnoreParenImpCasts(); | |||
12150 | if (isa<ImplicitCastExpr>(LastA) && | |||
12151 | InnerE->getType()->isBooleanType()) { | |||
12152 | // Warn on this floating-point to bool conversion | |||
12153 | DiagnoseImpCast(S, E, T, CC, | |||
12154 | diag::warn_impcast_floating_point_to_bool); | |||
12155 | } | |||
12156 | } | |||
12157 | } | |||
12158 | return; | |||
12159 | } | |||
12160 | ||||
12161 | // Valid casts involving fixed point types should be accounted for here. | |||
12162 | if (Source->isFixedPointType()) { | |||
12163 | if (Target->isUnsaturatedFixedPointType()) { | |||
12164 | Expr::EvalResult Result; | |||
12165 | if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, | |||
12166 | S.isConstantEvaluated())) { | |||
12167 | llvm::APFixedPoint Value = Result.Val.getFixedPoint(); | |||
12168 | llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); | |||
12169 | llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); | |||
12170 | if (Value > MaxVal || Value < MinVal) { | |||
12171 | S.DiagRuntimeBehavior(E->getExprLoc(), E, | |||
12172 | S.PDiag(diag::warn_impcast_fixed_point_range) | |||
12173 | << Value.toString() << T | |||
12174 | << E->getSourceRange() | |||
12175 | << clang::SourceRange(CC)); | |||
12176 | return; | |||
12177 | } | |||
12178 | } | |||
12179 | } else if (Target->isIntegerType()) { | |||
12180 | Expr::EvalResult Result; | |||
12181 | if (!S.isConstantEvaluated() && | |||
12182 | E->EvaluateAsFixedPoint(Result, S.Context, | |||
12183 | Expr::SE_AllowSideEffects)) { | |||
12184 | llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); | |||
12185 | ||||
12186 | bool Overflowed; | |||
12187 | llvm::APSInt IntResult = FXResult.convertToInt( | |||
12188 | S.Context.getIntWidth(T), | |||
12189 | Target->isSignedIntegerOrEnumerationType(), &Overflowed); | |||
12190 | ||||
12191 | if (Overflowed) { | |||
12192 | S.DiagRuntimeBehavior(E->getExprLoc(), E, | |||
12193 | S.PDiag(diag::warn_impcast_fixed_point_range) | |||
12194 | << FXResult.toString() << T | |||
12195 | << E->getSourceRange() | |||
12196 | << clang::SourceRange(CC)); | |||
12197 | return; | |||
12198 | } | |||
12199 | } | |||
12200 | } | |||
12201 | } else if (Target->isUnsaturatedFixedPointType()) { | |||
12202 | if (Source->isIntegerType()) { | |||
12203 | Expr::EvalResult Result; | |||
12204 | if (!S.isConstantEvaluated() && | |||
12205 | E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { | |||
12206 | llvm::APSInt Value = Result.Val.getInt(); | |||
12207 | ||||
12208 | bool Overflowed; | |||
12209 | llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( | |||
12210 | Value, S.Context.getFixedPointSemantics(T), &Overflowed); | |||
12211 | ||||
12212 | if (Overflowed) { | |||
12213 | S.DiagRuntimeBehavior(E->getExprLoc(), E, | |||
12214 | S.PDiag(diag::warn_impcast_fixed_point_range) | |||
12215 | << Value.toString(/*Radix=*/10) << T | |||
12216 | << E->getSourceRange() | |||
12217 | << clang::SourceRange(CC)); | |||
12218 | return; | |||
12219 | } | |||
12220 | } | |||
12221 | } | |||
12222 | } | |||
12223 | ||||
12224 | // If we are casting an integer type to a floating point type without | |||
12225 | // initialization-list syntax, we might lose accuracy if the floating | |||
12226 | // point type has a narrower significand than the integer type. | |||
12227 | if (SourceBT && TargetBT && SourceBT->isIntegerType() && | |||
12228 | TargetBT->isFloatingType() && !IsListInit) { | |||
12229 | // Determine the number of precision bits in the source integer type. | |||
12230 | IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), | |||
12231 | /*Approximate*/ true); | |||
12232 | unsigned int SourcePrecision = SourceRange.Width; | |||
12233 | ||||
12234 | // Determine the number of precision bits in the | |||
12235 | // target floating point type. | |||
12236 | unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( | |||
12237 | S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); | |||
12238 | ||||
12239 | if (SourcePrecision > 0 && TargetPrecision > 0 && | |||
12240 | SourcePrecision > TargetPrecision) { | |||
12241 | ||||
12242 | if (Optional<llvm::APSInt> SourceInt = | |||
12243 | E->getIntegerConstantExpr(S.Context)) { | |||
12244 | // If the source integer is a constant, convert it to the target | |||
12245 | // floating point type. Issue a warning if the value changes | |||
12246 | // during the whole conversion. | |||
12247 | llvm::APFloat TargetFloatValue( | |||
12248 | S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); | |||
12249 | llvm::APFloat::opStatus ConversionStatus = | |||
12250 | TargetFloatValue.convertFromAPInt( | |||
12251 | *SourceInt, SourceBT->isSignedInteger(), | |||
12252 | llvm::APFloat::rmNearestTiesToEven); | |||
12253 | ||||
12254 | if (ConversionStatus != llvm::APFloat::opOK) { | |||
12255 | std::string PrettySourceValue = SourceInt->toString(10); | |||
12256 | SmallString<32> PrettyTargetValue; | |||
12257 | TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); | |||
12258 | ||||
12259 | S.DiagRuntimeBehavior( | |||
12260 | E->getExprLoc(), E, | |||
12261 | S.PDiag(diag::warn_impcast_integer_float_precision_constant) | |||
12262 | << PrettySourceValue << PrettyTargetValue << E->getType() << T | |||
12263 | << E->getSourceRange() << clang::SourceRange(CC)); | |||
12264 | } | |||
12265 | } else { | |||
12266 | // Otherwise, the implicit conversion may lose precision. | |||
12267 | DiagnoseImpCast(S, E, T, CC, | |||
12268 | diag::warn_impcast_integer_float_precision); | |||
12269 | } | |||
12270 | } | |||
12271 | } | |||
12272 | ||||
12273 | DiagnoseNullConversion(S, E, T, CC); | |||
12274 | ||||
12275 | S.DiscardMisalignedMemberAddress(Target, E); | |||
12276 | ||||
12277 | if (Target->isBooleanType()) | |||
12278 | DiagnoseIntInBoolContext(S, E); | |||
12279 | ||||
12280 | if (!Source->isIntegerType() || !Target->isIntegerType()) | |||
12281 | return; | |||
12282 | ||||
12283 | // TODO: remove this early return once the false positives for constant->bool | |||
12284 | // in templates, macros, etc, are reduced or removed. | |||
12285 | if (Target->isSpecificBuiltinType(BuiltinType::Bool)) | |||
12286 | return; | |||
12287 | ||||
12288 | if (isObjCSignedCharBool(S, T) && !Source->isCharType() && | |||
12289 | !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { | |||
12290 | return adornObjCBoolConversionDiagWithTernaryFixit( | |||
12291 | S, E, | |||
12292 | S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) | |||
12293 | << E->getType()); | |||
12294 | } | |||
12295 | ||||
12296 | IntRange SourceTypeRange = | |||
12297 | IntRange::forTargetOfCanonicalType(S.Context, Source); | |||
12298 | IntRange LikelySourceRange = | |||
12299 | GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); | |||
12300 | IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); | |||
12301 | ||||
12302 | if (LikelySourceRange.Width > TargetRange.Width) { | |||
12303 | // If the source is a constant, use a default-on diagnostic. | |||
12304 | // TODO: this should happen for bitfield stores, too. | |||
12305 | Expr::EvalResult Result; | |||
12306 | if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, | |||
12307 | S.isConstantEvaluated())) { | |||
12308 | llvm::APSInt Value(32); | |||
12309 | Value = Result.Val.getInt(); | |||
12310 | ||||
12311 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
12312 | return; | |||
12313 | ||||
12314 | std::string PrettySourceValue = Value.toString(10); | |||
12315 | std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); | |||
12316 | ||||
12317 | S.DiagRuntimeBehavior( | |||
12318 | E->getExprLoc(), E, | |||
12319 | S.PDiag(diag::warn_impcast_integer_precision_constant) | |||
12320 | << PrettySourceValue << PrettyTargetValue << E->getType() << T | |||
12321 | << E->getSourceRange() << SourceRange(CC)); | |||
12322 | return; | |||
12323 | } | |||
12324 | ||||
12325 | // People want to build with -Wshorten-64-to-32 and not -Wconversion. | |||
12326 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
12327 | return; | |||
12328 | ||||
12329 | if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) | |||
12330 | return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, | |||
12331 | /* pruneControlFlow */ true); | |||
12332 | return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); | |||
12333 | } | |||
12334 | ||||
12335 | if (TargetRange.Width > SourceTypeRange.Width) { | |||
12336 | if (auto *UO = dyn_cast<UnaryOperator>(E)) | |||
12337 | if (UO->getOpcode() == UO_Minus) | |||
12338 | if (Source->isUnsignedIntegerType()) { | |||
12339 | if (Target->isUnsignedIntegerType()) | |||
12340 | return DiagnoseImpCast(S, E, T, CC, | |||
12341 | diag::warn_impcast_high_order_zero_bits); | |||
12342 | if (Target->isSignedIntegerType()) | |||
12343 | return DiagnoseImpCast(S, E, T, CC, | |||
12344 | diag::warn_impcast_nonnegative_result); | |||
12345 | } | |||
12346 | } | |||
12347 | ||||
12348 | if (TargetRange.Width == LikelySourceRange.Width && | |||
12349 | !TargetRange.NonNegative && LikelySourceRange.NonNegative && | |||
12350 | Source->isSignedIntegerType()) { | |||
12351 | // Warn when doing a signed to signed conversion, warn if the positive | |||
12352 | // source value is exactly the width of the target type, which will | |||
12353 | // cause a negative value to be stored. | |||
12354 | ||||
12355 | Expr::EvalResult Result; | |||
12356 | if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && | |||
12357 | !S.SourceMgr.isInSystemMacro(CC)) { | |||
12358 | llvm::APSInt Value = Result.Val.getInt(); | |||
12359 | if (isSameWidthConstantConversion(S, E, T, CC)) { | |||
12360 | std::string PrettySourceValue = Value.toString(10); | |||
12361 | std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); | |||
12362 | ||||
12363 | S.DiagRuntimeBehavior( | |||
12364 | E->getExprLoc(), E, | |||
12365 | S.PDiag(diag::warn_impcast_integer_precision_constant) | |||
12366 | << PrettySourceValue << PrettyTargetValue << E->getType() << T | |||
12367 | << E->getSourceRange() << SourceRange(CC)); | |||
12368 | return; | |||
12369 | } | |||
12370 | } | |||
12371 | ||||
12372 | // Fall through for non-constants to give a sign conversion warning. | |||
12373 | } | |||
12374 | ||||
12375 | if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || | |||
12376 | (!TargetRange.NonNegative && LikelySourceRange.NonNegative && | |||
12377 | LikelySourceRange.Width == TargetRange.Width)) { | |||
12378 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
12379 | return; | |||
12380 | ||||
12381 | unsigned DiagID = diag::warn_impcast_integer_sign; | |||
12382 | ||||
12383 | // Traditionally, gcc has warned about this under -Wsign-compare. | |||
12384 | // We also want to warn about it in -Wconversion. | |||
12385 | // So if -Wconversion is off, use a completely identical diagnostic | |||
12386 | // in the sign-compare group. | |||
12387 | // The conditional-checking code will | |||
12388 | if (ICContext) { | |||
12389 | DiagID = diag::warn_impcast_integer_sign_conditional; | |||
12390 | *ICContext = true; | |||
12391 | } | |||
12392 | ||||
12393 | return DiagnoseImpCast(S, E, T, CC, DiagID); | |||
12394 | } | |||
12395 | ||||
12396 | // Diagnose conversions between different enumeration types. | |||
12397 | // In C, we pretend that the type of an EnumConstantDecl is its enumeration | |||
12398 | // type, to give us better diagnostics. | |||
12399 | QualType SourceType = E->getType(); | |||
12400 | if (!S.getLangOpts().CPlusPlus) { | |||
12401 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | |||
12402 | if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { | |||
12403 | EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); | |||
12404 | SourceType = S.Context.getTypeDeclType(Enum); | |||
12405 | Source = S.Context.getCanonicalType(SourceType).getTypePtr(); | |||
12406 | } | |||
12407 | } | |||
12408 | ||||
12409 | if (const EnumType *SourceEnum = Source->getAs<EnumType>()) | |||
12410 | if (const EnumType *TargetEnum = Target->getAs<EnumType>()) | |||
12411 | if (SourceEnum->getDecl()->hasNameForLinkage() && | |||
12412 | TargetEnum->getDecl()->hasNameForLinkage() && | |||
12413 | SourceEnum != TargetEnum) { | |||
12414 | if (S.SourceMgr.isInSystemMacro(CC)) | |||
12415 | return; | |||
12416 | ||||
12417 | return DiagnoseImpCast(S, E, SourceType, T, CC, | |||
12418 | diag::warn_impcast_different_enum_types); | |||
12419 | } | |||
12420 | } | |||
12421 | ||||
12422 | static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, | |||
12423 | SourceLocation CC, QualType T); | |||
12424 | ||||
12425 | static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, | |||
12426 | SourceLocation CC, bool &ICContext) { | |||
12427 | E = E->IgnoreParenImpCasts(); | |||
12428 | ||||
12429 | if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) | |||
12430 | return CheckConditionalOperator(S, CO, CC, T); | |||
12431 | ||||
12432 | AnalyzeImplicitConversions(S, E, CC); | |||
12433 | if (E->getType() != T) | |||
12434 | return CheckImplicitConversion(S, E, T, CC, &ICContext); | |||
12435 | } | |||
12436 | ||||
12437 | static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, | |||
12438 | SourceLocation CC, QualType T) { | |||
12439 | AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); | |||
12440 | ||||
12441 | Expr *TrueExpr = E->getTrueExpr(); | |||
12442 | if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) | |||
12443 | TrueExpr = BCO->getCommon(); | |||
12444 | ||||
12445 | bool Suspicious = false; | |||
12446 | CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); | |||
12447 | CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); | |||
12448 | ||||
12449 | if (T->isBooleanType()) | |||
12450 | DiagnoseIntInBoolContext(S, E); | |||
12451 | ||||
12452 | // If -Wconversion would have warned about either of the candidates | |||
12453 | // for a signedness conversion to the context type... | |||
12454 | if (!Suspicious) return; | |||
12455 | ||||
12456 | // ...but it's currently ignored... | |||
12457 | if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) | |||
12458 | return; | |||
12459 | ||||
12460 | // ...then check whether it would have warned about either of the | |||
12461 | // candidates for a signedness conversion to the condition type. | |||
12462 | if (E->getType() == T) return; | |||
12463 | ||||
12464 | Suspicious = false; | |||
12465 | CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), | |||
12466 | E->getType(), CC, &Suspicious); | |||
12467 | if (!Suspicious) | |||
12468 | CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), | |||
12469 | E->getType(), CC, &Suspicious); | |||
12470 | } | |||
12471 | ||||
12472 | /// Check conversion of given expression to boolean. | |||
12473 | /// Input argument E is a logical expression. | |||
12474 | static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { | |||
12475 | if (S.getLangOpts().Bool) | |||
12476 | return; | |||
12477 | if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) | |||
12478 | return; | |||
12479 | CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); | |||
12480 | } | |||
12481 | ||||
12482 | namespace { | |||
12483 | struct AnalyzeImplicitConversionsWorkItem { | |||
12484 | Expr *E; | |||
12485 | SourceLocation CC; | |||
12486 | bool IsListInit; | |||
12487 | }; | |||
12488 | } | |||
12489 | ||||
12490 | /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions | |||
12491 | /// that should be visited are added to WorkList. | |||
12492 | static void AnalyzeImplicitConversions( | |||
12493 | Sema &S, AnalyzeImplicitConversionsWorkItem Item, | |||
12494 | llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { | |||
12495 | Expr *OrigE = Item.E; | |||
12496 | SourceLocation CC = Item.CC; | |||
12497 | ||||
12498 | QualType T = OrigE->getType(); | |||
12499 | Expr *E = OrigE->IgnoreParenImpCasts(); | |||
12500 | ||||
12501 | // Propagate whether we are in a C++ list initialization expression. | |||
12502 | // If so, we do not issue warnings for implicit int-float conversion | |||
12503 | // precision loss, because C++11 narrowing already handles it. | |||
12504 | bool IsListInit = Item.IsListInit || | |||
12505 | (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); | |||
12506 | ||||
12507 | if (E->isTypeDependent() || E->isValueDependent()) | |||
12508 | return; | |||
12509 | ||||
12510 | Expr *SourceExpr = E; | |||
12511 | // Examine, but don't traverse into the source expression of an | |||
12512 | // OpaqueValueExpr, since it may have multiple parents and we don't want to | |||
12513 | // emit duplicate diagnostics. Its fine to examine the form or attempt to | |||
12514 | // evaluate it in the context of checking the specific conversion to T though. | |||
12515 | if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) | |||
12516 | if (auto *Src = OVE->getSourceExpr()) | |||
12517 | SourceExpr = Src; | |||
12518 | ||||
12519 | if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) | |||
12520 | if (UO->getOpcode() == UO_Not && | |||
12521 | UO->getSubExpr()->isKnownToHaveBooleanValue()) | |||
12522 | S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) | |||
12523 | << OrigE->getSourceRange() << T->isBooleanType() | |||
12524 | << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); | |||
12525 | ||||
12526 | // For conditional operators, we analyze the arguments as if they | |||
12527 | // were being fed directly into the output. | |||
12528 | if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { | |||
12529 | CheckConditionalOperator(S, CO, CC, T); | |||
12530 | return; | |||
12531 | } | |||
12532 | ||||
12533 | // Check implicit argument conversions for function calls. | |||
12534 | if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) | |||
12535 | CheckImplicitArgumentConversions(S, Call, CC); | |||
12536 | ||||
12537 | // Go ahead and check any implicit conversions we might have skipped. | |||
12538 | // The non-canonical typecheck is just an optimization; | |||
12539 | // CheckImplicitConversion will filter out dead implicit conversions. | |||
12540 | if (SourceExpr->getType() != T) | |||
12541 | CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); | |||
12542 | ||||
12543 | // Now continue drilling into this expression. | |||
12544 | ||||
12545 | if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { | |||
12546 | // The bound subexpressions in a PseudoObjectExpr are not reachable | |||
12547 | // as transitive children. | |||
12548 | // FIXME: Use a more uniform representation for this. | |||
12549 | for (auto *SE : POE->semantics()) | |||
12550 | if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) | |||
12551 | WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); | |||
12552 | } | |||
12553 | ||||
12554 | // Skip past explicit casts. | |||
12555 | if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { | |||
12556 | E = CE->getSubExpr()->IgnoreParenImpCasts(); | |||
12557 | if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) | |||
12558 | S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); | |||
12559 | WorkList.push_back({E, CC, IsListInit}); | |||
12560 | return; | |||
12561 | } | |||
12562 | ||||
12563 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
12564 | // Do a somewhat different check with comparison operators. | |||
12565 | if (BO->isComparisonOp()) | |||
12566 | return AnalyzeComparison(S, BO); | |||
12567 | ||||
12568 | // And with simple assignments. | |||
12569 | if (BO->getOpcode() == BO_Assign) | |||
12570 | return AnalyzeAssignment(S, BO); | |||
12571 | // And with compound assignments. | |||
12572 | if (BO->isAssignmentOp()) | |||
12573 | return AnalyzeCompoundAssignment(S, BO); | |||
12574 | } | |||
12575 | ||||
12576 | // These break the otherwise-useful invariant below. Fortunately, | |||
12577 | // we don't really need to recurse into them, because any internal | |||
12578 | // expressions should have been analyzed already when they were | |||
12579 | // built into statements. | |||
12580 | if (isa<StmtExpr>(E)) return; | |||
12581 | ||||
12582 | // Don't descend into unevaluated contexts. | |||
12583 | if (isa<UnaryExprOrTypeTraitExpr>(E)) return; | |||
12584 | ||||
12585 | // Now just recurse over the expression's children. | |||
12586 | CC = E->getExprLoc(); | |||
12587 | BinaryOperator *BO = dyn_cast<BinaryOperator>(E); | |||
12588 | bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; | |||
12589 | for (Stmt *SubStmt : E->children()) { | |||
12590 | Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); | |||
12591 | if (!ChildExpr) | |||
12592 | continue; | |||
12593 | ||||
12594 | if (IsLogicalAndOperator && | |||
12595 | isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) | |||
12596 | // Ignore checking string literals that are in logical and operators. | |||
12597 | // This is a common pattern for asserts. | |||
12598 | continue; | |||
12599 | WorkList.push_back({ChildExpr, CC, IsListInit}); | |||
12600 | } | |||
12601 | ||||
12602 | if (BO && BO->isLogicalOp()) { | |||
12603 | Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); | |||
12604 | if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) | |||
12605 | ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); | |||
12606 | ||||
12607 | SubExpr = BO->getRHS()->IgnoreParenImpCasts(); | |||
12608 | if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) | |||
12609 | ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); | |||
12610 | } | |||
12611 | ||||
12612 | if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { | |||
12613 | if (U->getOpcode() == UO_LNot) { | |||
12614 | ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); | |||
12615 | } else if (U->getOpcode() != UO_AddrOf) { | |||
12616 | if (U->getSubExpr()->getType()->isAtomicType()) | |||
12617 | S.Diag(U->getSubExpr()->getBeginLoc(), | |||
12618 | diag::warn_atomic_implicit_seq_cst); | |||
12619 | } | |||
12620 | } | |||
12621 | } | |||
12622 | ||||
12623 | /// AnalyzeImplicitConversions - Find and report any interesting | |||
12624 | /// implicit conversions in the given expression. There are a couple | |||
12625 | /// of competing diagnostics here, -Wconversion and -Wsign-compare. | |||
12626 | static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, | |||
12627 | bool IsListInit/*= false*/) { | |||
12628 | llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; | |||
12629 | WorkList.push_back({OrigE, CC, IsListInit}); | |||
12630 | while (!WorkList.empty()) | |||
12631 | AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); | |||
12632 | } | |||
12633 | ||||
12634 | /// Diagnose integer type and any valid implicit conversion to it. | |||
12635 | static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { | |||
12636 | // Taking into account implicit conversions, | |||
12637 | // allow any integer. | |||
12638 | if (!E->getType()->isIntegerType()) { | |||
12639 | S.Diag(E->getBeginLoc(), | |||
12640 | diag::err_opencl_enqueue_kernel_invalid_local_size_type); | |||
12641 | return true; | |||
12642 | } | |||
12643 | // Potentially emit standard warnings for implicit conversions if enabled | |||
12644 | // using -Wconversion. | |||
12645 | CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); | |||
12646 | return false; | |||
12647 | } | |||
12648 | ||||
12649 | // Helper function for Sema::DiagnoseAlwaysNonNullPointer. | |||
12650 | // Returns true when emitting a warning about taking the address of a reference. | |||
12651 | static bool CheckForReference(Sema &SemaRef, const Expr *E, | |||
12652 | const PartialDiagnostic &PD) { | |||
12653 | E = E->IgnoreParenImpCasts(); | |||
12654 | ||||
12655 | const FunctionDecl *FD = nullptr; | |||
12656 | ||||
12657 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
12658 | if (!DRE->getDecl()->getType()->isReferenceType()) | |||
12659 | return false; | |||
12660 | } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { | |||
12661 | if (!M->getMemberDecl()->getType()->isReferenceType()) | |||
12662 | return false; | |||
12663 | } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { | |||
12664 | if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) | |||
12665 | return false; | |||
12666 | FD = Call->getDirectCallee(); | |||
12667 | } else { | |||
12668 | return false; | |||
12669 | } | |||
12670 | ||||
12671 | SemaRef.Diag(E->getExprLoc(), PD); | |||
12672 | ||||
12673 | // If possible, point to location of function. | |||
12674 | if (FD) { | |||
12675 | SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; | |||
12676 | } | |||
12677 | ||||
12678 | return true; | |||
12679 | } | |||
12680 | ||||
12681 | // Returns true if the SourceLocation is expanded from any macro body. | |||
12682 | // Returns false if the SourceLocation is invalid, is from not in a macro | |||
12683 | // expansion, or is from expanded from a top-level macro argument. | |||
12684 | static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { | |||
12685 | if (Loc.isInvalid()) | |||
12686 | return false; | |||
12687 | ||||
12688 | while (Loc.isMacroID()) { | |||
12689 | if (SM.isMacroBodyExpansion(Loc)) | |||
12690 | return true; | |||
12691 | Loc = SM.getImmediateMacroCallerLoc(Loc); | |||
12692 | } | |||
12693 | ||||
12694 | return false; | |||
12695 | } | |||
12696 | ||||
12697 | /// Diagnose pointers that are always non-null. | |||
12698 | /// \param E the expression containing the pointer | |||
12699 | /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is | |||
12700 | /// compared to a null pointer | |||
12701 | /// \param IsEqual True when the comparison is equal to a null pointer | |||
12702 | /// \param Range Extra SourceRange to highlight in the diagnostic | |||
12703 | void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, | |||
12704 | Expr::NullPointerConstantKind NullKind, | |||
12705 | bool IsEqual, SourceRange Range) { | |||
12706 | if (!E) | |||
12707 | return; | |||
12708 | ||||
12709 | // Don't warn inside macros. | |||
12710 | if (E->getExprLoc().isMacroID()) { | |||
12711 | const SourceManager &SM = getSourceManager(); | |||
12712 | if (IsInAnyMacroBody(SM, E->getExprLoc()) || | |||
12713 | IsInAnyMacroBody(SM, Range.getBegin())) | |||
12714 | return; | |||
12715 | } | |||
12716 | E = E->IgnoreImpCasts(); | |||
12717 | ||||
12718 | const bool IsCompare = NullKind != Expr::NPCK_NotNull; | |||
12719 | ||||
12720 | if (isa<CXXThisExpr>(E)) { | |||
12721 | unsigned DiagID = IsCompare ? diag::warn_this_null_compare | |||
12722 | : diag::warn_this_bool_conversion; | |||
12723 | Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; | |||
12724 | return; | |||
12725 | } | |||
12726 | ||||
12727 | bool IsAddressOf = false; | |||
12728 | ||||
12729 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
12730 | if (UO->getOpcode() != UO_AddrOf) | |||
12731 | return; | |||
12732 | IsAddressOf = true; | |||
12733 | E = UO->getSubExpr(); | |||
12734 | } | |||
12735 | ||||
12736 | if (IsAddressOf) { | |||
12737 | unsigned DiagID = IsCompare | |||
12738 | ? diag::warn_address_of_reference_null_compare | |||
12739 | : diag::warn_address_of_reference_bool_conversion; | |||
12740 | PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range | |||
12741 | << IsEqual; | |||
12742 | if (CheckForReference(*this, E, PD)) { | |||
12743 | return; | |||
12744 | } | |||
12745 | } | |||
12746 | ||||
12747 | auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { | |||
12748 | bool IsParam = isa<NonNullAttr>(NonnullAttr); | |||
12749 | std::string Str; | |||
12750 | llvm::raw_string_ostream S(Str); | |||
12751 | E->printPretty(S, nullptr, getPrintingPolicy()); | |||
12752 | unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare | |||
12753 | : diag::warn_cast_nonnull_to_bool; | |||
12754 | Diag(E->getExprLoc(), DiagID) << IsParam << S.str() | |||
12755 | << E->getSourceRange() << Range << IsEqual; | |||
12756 | Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; | |||
12757 | }; | |||
12758 | ||||
12759 | // If we have a CallExpr that is tagged with returns_nonnull, we can complain. | |||
12760 | if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { | |||
12761 | if (auto *Callee = Call->getDirectCallee()) { | |||
12762 | if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { | |||
12763 | ComplainAboutNonnullParamOrCall(A); | |||
12764 | return; | |||
12765 | } | |||
12766 | } | |||
12767 | } | |||
12768 | ||||
12769 | // Expect to find a single Decl. Skip anything more complicated. | |||
12770 | ValueDecl *D = nullptr; | |||
12771 | if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { | |||
12772 | D = R->getDecl(); | |||
12773 | } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { | |||
12774 | D = M->getMemberDecl(); | |||
12775 | } | |||
12776 | ||||
12777 | // Weak Decls can be null. | |||
12778 | if (!D || D->isWeak()) | |||
12779 | return; | |||
12780 | ||||
12781 | // Check for parameter decl with nonnull attribute | |||
12782 | if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { | |||
12783 | if (getCurFunction() && | |||
12784 | !getCurFunction()->ModifiedNonNullParams.count(PV)) { | |||
12785 | if (const Attr *A = PV->getAttr<NonNullAttr>()) { | |||
12786 | ComplainAboutNonnullParamOrCall(A); | |||
12787 | return; | |||
12788 | } | |||
12789 | ||||
12790 | if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { | |||
12791 | // Skip function template not specialized yet. | |||
12792 | if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) | |||
12793 | return; | |||
12794 | auto ParamIter = llvm::find(FD->parameters(), PV); | |||
12795 | assert(ParamIter != FD->param_end())((ParamIter != FD->param_end()) ? static_cast<void> ( 0) : __assert_fail ("ParamIter != FD->param_end()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 12795, __PRETTY_FUNCTION__)); | |||
12796 | unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); | |||
12797 | ||||
12798 | for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { | |||
12799 | if (!NonNull->args_size()) { | |||
12800 | ComplainAboutNonnullParamOrCall(NonNull); | |||
12801 | return; | |||
12802 | } | |||
12803 | ||||
12804 | for (const ParamIdx &ArgNo : NonNull->args()) { | |||
12805 | if (ArgNo.getASTIndex() == ParamNo) { | |||
12806 | ComplainAboutNonnullParamOrCall(NonNull); | |||
12807 | return; | |||
12808 | } | |||
12809 | } | |||
12810 | } | |||
12811 | } | |||
12812 | } | |||
12813 | } | |||
12814 | ||||
12815 | QualType T = D->getType(); | |||
12816 | const bool IsArray = T->isArrayType(); | |||
12817 | const bool IsFunction = T->isFunctionType(); | |||
12818 | ||||
12819 | // Address of function is used to silence the function warning. | |||
12820 | if (IsAddressOf && IsFunction) { | |||
12821 | return; | |||
12822 | } | |||
12823 | ||||
12824 | // Found nothing. | |||
12825 | if (!IsAddressOf && !IsFunction && !IsArray) | |||
12826 | return; | |||
12827 | ||||
12828 | // Pretty print the expression for the diagnostic. | |||
12829 | std::string Str; | |||
12830 | llvm::raw_string_ostream S(Str); | |||
12831 | E->printPretty(S, nullptr, getPrintingPolicy()); | |||
12832 | ||||
12833 | unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare | |||
12834 | : diag::warn_impcast_pointer_to_bool; | |||
12835 | enum { | |||
12836 | AddressOf, | |||
12837 | FunctionPointer, | |||
12838 | ArrayPointer | |||
12839 | } DiagType; | |||
12840 | if (IsAddressOf) | |||
12841 | DiagType = AddressOf; | |||
12842 | else if (IsFunction) | |||
12843 | DiagType = FunctionPointer; | |||
12844 | else if (IsArray) | |||
12845 | DiagType = ArrayPointer; | |||
12846 | else | |||
12847 | llvm_unreachable("Could not determine diagnostic.")::llvm::llvm_unreachable_internal("Could not determine diagnostic." , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 12847); | |||
12848 | Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() | |||
12849 | << Range << IsEqual; | |||
12850 | ||||
12851 | if (!IsFunction) | |||
12852 | return; | |||
12853 | ||||
12854 | // Suggest '&' to silence the function warning. | |||
12855 | Diag(E->getExprLoc(), diag::note_function_warning_silence) | |||
12856 | << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); | |||
12857 | ||||
12858 | // Check to see if '()' fixit should be emitted. | |||
12859 | QualType ReturnType; | |||
12860 | UnresolvedSet<4> NonTemplateOverloads; | |||
12861 | tryExprAsCall(*E, ReturnType, NonTemplateOverloads); | |||
12862 | if (ReturnType.isNull()) | |||
12863 | return; | |||
12864 | ||||
12865 | if (IsCompare) { | |||
12866 | // There are two cases here. If there is null constant, the only suggest | |||
12867 | // for a pointer return type. If the null is 0, then suggest if the return | |||
12868 | // type is a pointer or an integer type. | |||
12869 | if (!ReturnType->isPointerType()) { | |||
12870 | if (NullKind == Expr::NPCK_ZeroExpression || | |||
12871 | NullKind == Expr::NPCK_ZeroLiteral) { | |||
12872 | if (!ReturnType->isIntegerType()) | |||
12873 | return; | |||
12874 | } else { | |||
12875 | return; | |||
12876 | } | |||
12877 | } | |||
12878 | } else { // !IsCompare | |||
12879 | // For function to bool, only suggest if the function pointer has bool | |||
12880 | // return type. | |||
12881 | if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) | |||
12882 | return; | |||
12883 | } | |||
12884 | Diag(E->getExprLoc(), diag::note_function_to_function_call) | |||
12885 | << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); | |||
12886 | } | |||
12887 | ||||
12888 | /// Diagnoses "dangerous" implicit conversions within the given | |||
12889 | /// expression (which is a full expression). Implements -Wconversion | |||
12890 | /// and -Wsign-compare. | |||
12891 | /// | |||
12892 | /// \param CC the "context" location of the implicit conversion, i.e. | |||
12893 | /// the most location of the syntactic entity requiring the implicit | |||
12894 | /// conversion | |||
12895 | void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { | |||
12896 | // Don't diagnose in unevaluated contexts. | |||
12897 | if (isUnevaluatedContext()) | |||
12898 | return; | |||
12899 | ||||
12900 | // Don't diagnose for value- or type-dependent expressions. | |||
12901 | if (E->isTypeDependent() || E->isValueDependent()) | |||
12902 | return; | |||
12903 | ||||
12904 | // Check for array bounds violations in cases where the check isn't triggered | |||
12905 | // elsewhere for other Expr types (like BinaryOperators), e.g. when an | |||
12906 | // ArraySubscriptExpr is on the RHS of a variable initialization. | |||
12907 | CheckArrayAccess(E); | |||
12908 | ||||
12909 | // This is not the right CC for (e.g.) a variable initialization. | |||
12910 | AnalyzeImplicitConversions(*this, E, CC); | |||
12911 | } | |||
12912 | ||||
12913 | /// CheckBoolLikeConversion - Check conversion of given expression to boolean. | |||
12914 | /// Input argument E is a logical expression. | |||
12915 | void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { | |||
12916 | ::CheckBoolLikeConversion(*this, E, CC); | |||
12917 | } | |||
12918 | ||||
12919 | /// Diagnose when expression is an integer constant expression and its evaluation | |||
12920 | /// results in integer overflow | |||
12921 | void Sema::CheckForIntOverflow (Expr *E) { | |||
12922 | // Use a work list to deal with nested struct initializers. | |||
12923 | SmallVector<Expr *, 2> Exprs(1, E); | |||
12924 | ||||
12925 | do { | |||
12926 | Expr *OriginalE = Exprs.pop_back_val(); | |||
12927 | Expr *E = OriginalE->IgnoreParenCasts(); | |||
12928 | ||||
12929 | if (isa<BinaryOperator>(E)) { | |||
12930 | E->EvaluateForOverflow(Context); | |||
12931 | continue; | |||
12932 | } | |||
12933 | ||||
12934 | if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) | |||
12935 | Exprs.append(InitList->inits().begin(), InitList->inits().end()); | |||
12936 | else if (isa<ObjCBoxedExpr>(OriginalE)) | |||
12937 | E->EvaluateForOverflow(Context); | |||
12938 | else if (auto Call = dyn_cast<CallExpr>(E)) | |||
12939 | Exprs.append(Call->arg_begin(), Call->arg_end()); | |||
12940 | else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) | |||
12941 | Exprs.append(Message->arg_begin(), Message->arg_end()); | |||
12942 | } while (!Exprs.empty()); | |||
12943 | } | |||
12944 | ||||
12945 | namespace { | |||
12946 | ||||
12947 | /// Visitor for expressions which looks for unsequenced operations on the | |||
12948 | /// same object. | |||
12949 | class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { | |||
12950 | using Base = ConstEvaluatedExprVisitor<SequenceChecker>; | |||
12951 | ||||
12952 | /// A tree of sequenced regions within an expression. Two regions are | |||
12953 | /// unsequenced if one is an ancestor or a descendent of the other. When we | |||
12954 | /// finish processing an expression with sequencing, such as a comma | |||
12955 | /// expression, we fold its tree nodes into its parent, since they are | |||
12956 | /// unsequenced with respect to nodes we will visit later. | |||
12957 | class SequenceTree { | |||
12958 | struct Value { | |||
12959 | explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} | |||
12960 | unsigned Parent : 31; | |||
12961 | unsigned Merged : 1; | |||
12962 | }; | |||
12963 | SmallVector<Value, 8> Values; | |||
12964 | ||||
12965 | public: | |||
12966 | /// A region within an expression which may be sequenced with respect | |||
12967 | /// to some other region. | |||
12968 | class Seq { | |||
12969 | friend class SequenceTree; | |||
12970 | ||||
12971 | unsigned Index; | |||
12972 | ||||
12973 | explicit Seq(unsigned N) : Index(N) {} | |||
12974 | ||||
12975 | public: | |||
12976 | Seq() : Index(0) {} | |||
12977 | }; | |||
12978 | ||||
12979 | SequenceTree() { Values.push_back(Value(0)); } | |||
12980 | Seq root() const { return Seq(0); } | |||
12981 | ||||
12982 | /// Create a new sequence of operations, which is an unsequenced | |||
12983 | /// subset of \p Parent. This sequence of operations is sequenced with | |||
12984 | /// respect to other children of \p Parent. | |||
12985 | Seq allocate(Seq Parent) { | |||
12986 | Values.push_back(Value(Parent.Index)); | |||
12987 | return Seq(Values.size() - 1); | |||
12988 | } | |||
12989 | ||||
12990 | /// Merge a sequence of operations into its parent. | |||
12991 | void merge(Seq S) { | |||
12992 | Values[S.Index].Merged = true; | |||
12993 | } | |||
12994 | ||||
12995 | /// Determine whether two operations are unsequenced. This operation | |||
12996 | /// is asymmetric: \p Cur should be the more recent sequence, and \p Old | |||
12997 | /// should have been merged into its parent as appropriate. | |||
12998 | bool isUnsequenced(Seq Cur, Seq Old) { | |||
12999 | unsigned C = representative(Cur.Index); | |||
13000 | unsigned Target = representative(Old.Index); | |||
13001 | while (C >= Target) { | |||
13002 | if (C == Target) | |||
13003 | return true; | |||
13004 | C = Values[C].Parent; | |||
13005 | } | |||
13006 | return false; | |||
13007 | } | |||
13008 | ||||
13009 | private: | |||
13010 | /// Pick a representative for a sequence. | |||
13011 | unsigned representative(unsigned K) { | |||
13012 | if (Values[K].Merged) | |||
13013 | // Perform path compression as we go. | |||
13014 | return Values[K].Parent = representative(Values[K].Parent); | |||
13015 | return K; | |||
13016 | } | |||
13017 | }; | |||
13018 | ||||
13019 | /// An object for which we can track unsequenced uses. | |||
13020 | using Object = const NamedDecl *; | |||
13021 | ||||
13022 | /// Different flavors of object usage which we track. We only track the | |||
13023 | /// least-sequenced usage of each kind. | |||
13024 | enum UsageKind { | |||
13025 | /// A read of an object. Multiple unsequenced reads are OK. | |||
13026 | UK_Use, | |||
13027 | ||||
13028 | /// A modification of an object which is sequenced before the value | |||
13029 | /// computation of the expression, such as ++n in C++. | |||
13030 | UK_ModAsValue, | |||
13031 | ||||
13032 | /// A modification of an object which is not sequenced before the value | |||
13033 | /// computation of the expression, such as n++. | |||
13034 | UK_ModAsSideEffect, | |||
13035 | ||||
13036 | UK_Count = UK_ModAsSideEffect + 1 | |||
13037 | }; | |||
13038 | ||||
13039 | /// Bundle together a sequencing region and the expression corresponding | |||
13040 | /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. | |||
13041 | struct Usage { | |||
13042 | const Expr *UsageExpr; | |||
13043 | SequenceTree::Seq Seq; | |||
13044 | ||||
13045 | Usage() : UsageExpr(nullptr), Seq() {} | |||
13046 | }; | |||
13047 | ||||
13048 | struct UsageInfo { | |||
13049 | Usage Uses[UK_Count]; | |||
13050 | ||||
13051 | /// Have we issued a diagnostic for this object already? | |||
13052 | bool Diagnosed; | |||
13053 | ||||
13054 | UsageInfo() : Uses(), Diagnosed(false) {} | |||
13055 | }; | |||
13056 | using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; | |||
13057 | ||||
13058 | Sema &SemaRef; | |||
13059 | ||||
13060 | /// Sequenced regions within the expression. | |||
13061 | SequenceTree Tree; | |||
13062 | ||||
13063 | /// Declaration modifications and references which we have seen. | |||
13064 | UsageInfoMap UsageMap; | |||
13065 | ||||
13066 | /// The region we are currently within. | |||
13067 | SequenceTree::Seq Region; | |||
13068 | ||||
13069 | /// Filled in with declarations which were modified as a side-effect | |||
13070 | /// (that is, post-increment operations). | |||
13071 | SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; | |||
13072 | ||||
13073 | /// Expressions to check later. We defer checking these to reduce | |||
13074 | /// stack usage. | |||
13075 | SmallVectorImpl<const Expr *> &WorkList; | |||
13076 | ||||
13077 | /// RAII object wrapping the visitation of a sequenced subexpression of an | |||
13078 | /// expression. At the end of this process, the side-effects of the evaluation | |||
13079 | /// become sequenced with respect to the value computation of the result, so | |||
13080 | /// we downgrade any UK_ModAsSideEffect within the evaluation to | |||
13081 | /// UK_ModAsValue. | |||
13082 | struct SequencedSubexpression { | |||
13083 | SequencedSubexpression(SequenceChecker &Self) | |||
13084 | : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { | |||
13085 | Self.ModAsSideEffect = &ModAsSideEffect; | |||
13086 | } | |||
13087 | ||||
13088 | ~SequencedSubexpression() { | |||
13089 | for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { | |||
13090 | // Add a new usage with usage kind UK_ModAsValue, and then restore | |||
13091 | // the previous usage with UK_ModAsSideEffect (thus clearing it if | |||
13092 | // the previous one was empty). | |||
13093 | UsageInfo &UI = Self.UsageMap[M.first]; | |||
13094 | auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; | |||
13095 | Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); | |||
13096 | SideEffectUsage = M.second; | |||
13097 | } | |||
13098 | Self.ModAsSideEffect = OldModAsSideEffect; | |||
13099 | } | |||
13100 | ||||
13101 | SequenceChecker &Self; | |||
13102 | SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; | |||
13103 | SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; | |||
13104 | }; | |||
13105 | ||||
13106 | /// RAII object wrapping the visitation of a subexpression which we might | |||
13107 | /// choose to evaluate as a constant. If any subexpression is evaluated and | |||
13108 | /// found to be non-constant, this allows us to suppress the evaluation of | |||
13109 | /// the outer expression. | |||
13110 | class EvaluationTracker { | |||
13111 | public: | |||
13112 | EvaluationTracker(SequenceChecker &Self) | |||
13113 | : Self(Self), Prev(Self.EvalTracker) { | |||
13114 | Self.EvalTracker = this; | |||
13115 | } | |||
13116 | ||||
13117 | ~EvaluationTracker() { | |||
13118 | Self.EvalTracker = Prev; | |||
13119 | if (Prev) | |||
13120 | Prev->EvalOK &= EvalOK; | |||
13121 | } | |||
13122 | ||||
13123 | bool evaluate(const Expr *E, bool &Result) { | |||
13124 | if (!EvalOK || E->isValueDependent()) | |||
13125 | return false; | |||
13126 | EvalOK = E->EvaluateAsBooleanCondition( | |||
13127 | Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); | |||
13128 | return EvalOK; | |||
13129 | } | |||
13130 | ||||
13131 | private: | |||
13132 | SequenceChecker &Self; | |||
13133 | EvaluationTracker *Prev; | |||
13134 | bool EvalOK = true; | |||
13135 | } *EvalTracker = nullptr; | |||
13136 | ||||
13137 | /// Find the object which is produced by the specified expression, | |||
13138 | /// if any. | |||
13139 | Object getObject(const Expr *E, bool Mod) const { | |||
13140 | E = E->IgnoreParenCasts(); | |||
13141 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
13142 | if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) | |||
13143 | return getObject(UO->getSubExpr(), Mod); | |||
13144 | } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
13145 | if (BO->getOpcode() == BO_Comma) | |||
13146 | return getObject(BO->getRHS(), Mod); | |||
13147 | if (Mod && BO->isAssignmentOp()) | |||
13148 | return getObject(BO->getLHS(), Mod); | |||
13149 | } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
13150 | // FIXME: Check for more interesting cases, like "x.n = ++x.n". | |||
13151 | if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) | |||
13152 | return ME->getMemberDecl(); | |||
13153 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | |||
13154 | // FIXME: If this is a reference, map through to its value. | |||
13155 | return DRE->getDecl(); | |||
13156 | return nullptr; | |||
13157 | } | |||
13158 | ||||
13159 | /// Note that an object \p O was modified or used by an expression | |||
13160 | /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for | |||
13161 | /// the object \p O as obtained via the \p UsageMap. | |||
13162 | void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { | |||
13163 | // Get the old usage for the given object and usage kind. | |||
13164 | Usage &U = UI.Uses[UK]; | |||
13165 | if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { | |||
13166 | // If we have a modification as side effect and are in a sequenced | |||
13167 | // subexpression, save the old Usage so that we can restore it later | |||
13168 | // in SequencedSubexpression::~SequencedSubexpression. | |||
13169 | if (UK == UK_ModAsSideEffect && ModAsSideEffect) | |||
13170 | ModAsSideEffect->push_back(std::make_pair(O, U)); | |||
13171 | // Then record the new usage with the current sequencing region. | |||
13172 | U.UsageExpr = UsageExpr; | |||
13173 | U.Seq = Region; | |||
13174 | } | |||
13175 | } | |||
13176 | ||||
13177 | /// Check whether a modification or use of an object \p O in an expression | |||
13178 | /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is | |||
13179 | /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. | |||
13180 | /// \p IsModMod is true when we are checking for a mod-mod unsequenced | |||
13181 | /// usage and false we are checking for a mod-use unsequenced usage. | |||
13182 | void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, | |||
13183 | UsageKind OtherKind, bool IsModMod) { | |||
13184 | if (UI.Diagnosed) | |||
13185 | return; | |||
13186 | ||||
13187 | const Usage &U = UI.Uses[OtherKind]; | |||
13188 | if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) | |||
13189 | return; | |||
13190 | ||||
13191 | const Expr *Mod = U.UsageExpr; | |||
13192 | const Expr *ModOrUse = UsageExpr; | |||
13193 | if (OtherKind == UK_Use) | |||
13194 | std::swap(Mod, ModOrUse); | |||
13195 | ||||
13196 | SemaRef.DiagRuntimeBehavior( | |||
13197 | Mod->getExprLoc(), {Mod, ModOrUse}, | |||
13198 | SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod | |||
13199 | : diag::warn_unsequenced_mod_use) | |||
13200 | << O << SourceRange(ModOrUse->getExprLoc())); | |||
13201 | UI.Diagnosed = true; | |||
13202 | } | |||
13203 | ||||
13204 | // A note on note{Pre, Post}{Use, Mod}: | |||
13205 | // | |||
13206 | // (It helps to follow the algorithm with an expression such as | |||
13207 | // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced | |||
13208 | // operations before C++17 and both are well-defined in C++17). | |||
13209 | // | |||
13210 | // When visiting a node which uses/modify an object we first call notePreUse | |||
13211 | // or notePreMod before visiting its sub-expression(s). At this point the | |||
13212 | // children of the current node have not yet been visited and so the eventual | |||
13213 | // uses/modifications resulting from the children of the current node have not | |||
13214 | // been recorded yet. | |||
13215 | // | |||
13216 | // We then visit the children of the current node. After that notePostUse or | |||
13217 | // notePostMod is called. These will 1) detect an unsequenced modification | |||
13218 | // as side effect (as in "k++ + k") and 2) add a new usage with the | |||
13219 | // appropriate usage kind. | |||
13220 | // | |||
13221 | // We also have to be careful that some operation sequences modification as | |||
13222 | // side effect as well (for example: || or ,). To account for this we wrap | |||
13223 | // the visitation of such a sub-expression (for example: the LHS of || or ,) | |||
13224 | // with SequencedSubexpression. SequencedSubexpression is an RAII object | |||
13225 | // which record usages which are modifications as side effect, and then | |||
13226 | // downgrade them (or more accurately restore the previous usage which was a | |||
13227 | // modification as side effect) when exiting the scope of the sequenced | |||
13228 | // subexpression. | |||
13229 | ||||
13230 | void notePreUse(Object O, const Expr *UseExpr) { | |||
13231 | UsageInfo &UI = UsageMap[O]; | |||
13232 | // Uses conflict with other modifications. | |||
13233 | checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); | |||
13234 | } | |||
13235 | ||||
13236 | void notePostUse(Object O, const Expr *UseExpr) { | |||
13237 | UsageInfo &UI = UsageMap[O]; | |||
13238 | checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, | |||
13239 | /*IsModMod=*/false); | |||
13240 | addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); | |||
13241 | } | |||
13242 | ||||
13243 | void notePreMod(Object O, const Expr *ModExpr) { | |||
13244 | UsageInfo &UI = UsageMap[O]; | |||
13245 | // Modifications conflict with other modifications and with uses. | |||
13246 | checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); | |||
13247 | checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); | |||
13248 | } | |||
13249 | ||||
13250 | void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { | |||
13251 | UsageInfo &UI = UsageMap[O]; | |||
13252 | checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, | |||
13253 | /*IsModMod=*/true); | |||
13254 | addUsage(O, UI, ModExpr, /*UsageKind=*/UK); | |||
13255 | } | |||
13256 | ||||
13257 | public: | |||
13258 | SequenceChecker(Sema &S, const Expr *E, | |||
13259 | SmallVectorImpl<const Expr *> &WorkList) | |||
13260 | : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { | |||
13261 | Visit(E); | |||
13262 | // Silence a -Wunused-private-field since WorkList is now unused. | |||
13263 | // TODO: Evaluate if it can be used, and if not remove it. | |||
13264 | (void)this->WorkList; | |||
13265 | } | |||
13266 | ||||
13267 | void VisitStmt(const Stmt *S) { | |||
13268 | // Skip all statements which aren't expressions for now. | |||
13269 | } | |||
13270 | ||||
13271 | void VisitExpr(const Expr *E) { | |||
13272 | // By default, just recurse to evaluated subexpressions. | |||
13273 | Base::VisitStmt(E); | |||
13274 | } | |||
13275 | ||||
13276 | void VisitCastExpr(const CastExpr *E) { | |||
13277 | Object O = Object(); | |||
13278 | if (E->getCastKind() == CK_LValueToRValue) | |||
13279 | O = getObject(E->getSubExpr(), false); | |||
13280 | ||||
13281 | if (O) | |||
13282 | notePreUse(O, E); | |||
13283 | VisitExpr(E); | |||
13284 | if (O) | |||
13285 | notePostUse(O, E); | |||
13286 | } | |||
13287 | ||||
13288 | void VisitSequencedExpressions(const Expr *SequencedBefore, | |||
13289 | const Expr *SequencedAfter) { | |||
13290 | SequenceTree::Seq BeforeRegion = Tree.allocate(Region); | |||
13291 | SequenceTree::Seq AfterRegion = Tree.allocate(Region); | |||
13292 | SequenceTree::Seq OldRegion = Region; | |||
13293 | ||||
13294 | { | |||
13295 | SequencedSubexpression SeqBefore(*this); | |||
13296 | Region = BeforeRegion; | |||
13297 | Visit(SequencedBefore); | |||
13298 | } | |||
13299 | ||||
13300 | Region = AfterRegion; | |||
13301 | Visit(SequencedAfter); | |||
13302 | ||||
13303 | Region = OldRegion; | |||
13304 | ||||
13305 | Tree.merge(BeforeRegion); | |||
13306 | Tree.merge(AfterRegion); | |||
13307 | } | |||
13308 | ||||
13309 | void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { | |||
13310 | // C++17 [expr.sub]p1: | |||
13311 | // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The | |||
13312 | // expression E1 is sequenced before the expression E2. | |||
13313 | if (SemaRef.getLangOpts().CPlusPlus17) | |||
13314 | VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); | |||
13315 | else { | |||
13316 | Visit(ASE->getLHS()); | |||
13317 | Visit(ASE->getRHS()); | |||
13318 | } | |||
13319 | } | |||
13320 | ||||
13321 | void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } | |||
13322 | void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } | |||
13323 | void VisitBinPtrMem(const BinaryOperator *BO) { | |||
13324 | // C++17 [expr.mptr.oper]p4: | |||
13325 | // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] | |||
13326 | // the expression E1 is sequenced before the expression E2. | |||
13327 | if (SemaRef.getLangOpts().CPlusPlus17) | |||
13328 | VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); | |||
13329 | else { | |||
13330 | Visit(BO->getLHS()); | |||
13331 | Visit(BO->getRHS()); | |||
13332 | } | |||
13333 | } | |||
13334 | ||||
13335 | void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } | |||
13336 | void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } | |||
13337 | void VisitBinShlShr(const BinaryOperator *BO) { | |||
13338 | // C++17 [expr.shift]p4: | |||
13339 | // The expression E1 is sequenced before the expression E2. | |||
13340 | if (SemaRef.getLangOpts().CPlusPlus17) | |||
13341 | VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); | |||
13342 | else { | |||
13343 | Visit(BO->getLHS()); | |||
13344 | Visit(BO->getRHS()); | |||
13345 | } | |||
13346 | } | |||
13347 | ||||
13348 | void VisitBinComma(const BinaryOperator *BO) { | |||
13349 | // C++11 [expr.comma]p1: | |||
13350 | // Every value computation and side effect associated with the left | |||
13351 | // expression is sequenced before every value computation and side | |||
13352 | // effect associated with the right expression. | |||
13353 | VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); | |||
13354 | } | |||
13355 | ||||
13356 | void VisitBinAssign(const BinaryOperator *BO) { | |||
13357 | SequenceTree::Seq RHSRegion; | |||
13358 | SequenceTree::Seq LHSRegion; | |||
13359 | if (SemaRef.getLangOpts().CPlusPlus17) { | |||
13360 | RHSRegion = Tree.allocate(Region); | |||
13361 | LHSRegion = Tree.allocate(Region); | |||
13362 | } else { | |||
13363 | RHSRegion = Region; | |||
13364 | LHSRegion = Region; | |||
13365 | } | |||
13366 | SequenceTree::Seq OldRegion = Region; | |||
13367 | ||||
13368 | // C++11 [expr.ass]p1: | |||
13369 | // [...] the assignment is sequenced after the value computation | |||
13370 | // of the right and left operands, [...] | |||
13371 | // | |||
13372 | // so check it before inspecting the operands and update the | |||
13373 | // map afterwards. | |||
13374 | Object O = getObject(BO->getLHS(), /*Mod=*/true); | |||
13375 | if (O) | |||
13376 | notePreMod(O, BO); | |||
13377 | ||||
13378 | if (SemaRef.getLangOpts().CPlusPlus17) { | |||
13379 | // C++17 [expr.ass]p1: | |||
13380 | // [...] The right operand is sequenced before the left operand. [...] | |||
13381 | { | |||
13382 | SequencedSubexpression SeqBefore(*this); | |||
13383 | Region = RHSRegion; | |||
13384 | Visit(BO->getRHS()); | |||
13385 | } | |||
13386 | ||||
13387 | Region = LHSRegion; | |||
13388 | Visit(BO->getLHS()); | |||
13389 | ||||
13390 | if (O && isa<CompoundAssignOperator>(BO)) | |||
13391 | notePostUse(O, BO); | |||
13392 | ||||
13393 | } else { | |||
13394 | // C++11 does not specify any sequencing between the LHS and RHS. | |||
13395 | Region = LHSRegion; | |||
13396 | Visit(BO->getLHS()); | |||
13397 | ||||
13398 | if (O && isa<CompoundAssignOperator>(BO)) | |||
13399 | notePostUse(O, BO); | |||
13400 | ||||
13401 | Region = RHSRegion; | |||
13402 | Visit(BO->getRHS()); | |||
13403 | } | |||
13404 | ||||
13405 | // C++11 [expr.ass]p1: | |||
13406 | // the assignment is sequenced [...] before the value computation of the | |||
13407 | // assignment expression. | |||
13408 | // C11 6.5.16/3 has no such rule. | |||
13409 | Region = OldRegion; | |||
13410 | if (O) | |||
13411 | notePostMod(O, BO, | |||
13412 | SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue | |||
13413 | : UK_ModAsSideEffect); | |||
13414 | if (SemaRef.getLangOpts().CPlusPlus17) { | |||
13415 | Tree.merge(RHSRegion); | |||
13416 | Tree.merge(LHSRegion); | |||
13417 | } | |||
13418 | } | |||
13419 | ||||
13420 | void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { | |||
13421 | VisitBinAssign(CAO); | |||
13422 | } | |||
13423 | ||||
13424 | void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } | |||
13425 | void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } | |||
13426 | void VisitUnaryPreIncDec(const UnaryOperator *UO) { | |||
13427 | Object O = getObject(UO->getSubExpr(), true); | |||
13428 | if (!O) | |||
13429 | return VisitExpr(UO); | |||
13430 | ||||
13431 | notePreMod(O, UO); | |||
13432 | Visit(UO->getSubExpr()); | |||
13433 | // C++11 [expr.pre.incr]p1: | |||
13434 | // the expression ++x is equivalent to x+=1 | |||
13435 | notePostMod(O, UO, | |||
13436 | SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue | |||
13437 | : UK_ModAsSideEffect); | |||
13438 | } | |||
13439 | ||||
13440 | void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } | |||
13441 | void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } | |||
13442 | void VisitUnaryPostIncDec(const UnaryOperator *UO) { | |||
13443 | Object O = getObject(UO->getSubExpr(), true); | |||
13444 | if (!O) | |||
13445 | return VisitExpr(UO); | |||
13446 | ||||
13447 | notePreMod(O, UO); | |||
13448 | Visit(UO->getSubExpr()); | |||
13449 | notePostMod(O, UO, UK_ModAsSideEffect); | |||
13450 | } | |||
13451 | ||||
13452 | void VisitBinLOr(const BinaryOperator *BO) { | |||
13453 | // C++11 [expr.log.or]p2: | |||
13454 | // If the second expression is evaluated, every value computation and | |||
13455 | // side effect associated with the first expression is sequenced before | |||
13456 | // every value computation and side effect associated with the | |||
13457 | // second expression. | |||
13458 | SequenceTree::Seq LHSRegion = Tree.allocate(Region); | |||
13459 | SequenceTree::Seq RHSRegion = Tree.allocate(Region); | |||
13460 | SequenceTree::Seq OldRegion = Region; | |||
13461 | ||||
13462 | EvaluationTracker Eval(*this); | |||
13463 | { | |||
13464 | SequencedSubexpression Sequenced(*this); | |||
13465 | Region = LHSRegion; | |||
13466 | Visit(BO->getLHS()); | |||
13467 | } | |||
13468 | ||||
13469 | // C++11 [expr.log.or]p1: | |||
13470 | // [...] the second operand is not evaluated if the first operand | |||
13471 | // evaluates to true. | |||
13472 | bool EvalResult = false; | |||
13473 | bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); | |||
13474 | bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); | |||
13475 | if (ShouldVisitRHS) { | |||
13476 | Region = RHSRegion; | |||
13477 | Visit(BO->getRHS()); | |||
13478 | } | |||
13479 | ||||
13480 | Region = OldRegion; | |||
13481 | Tree.merge(LHSRegion); | |||
13482 | Tree.merge(RHSRegion); | |||
13483 | } | |||
13484 | ||||
13485 | void VisitBinLAnd(const BinaryOperator *BO) { | |||
13486 | // C++11 [expr.log.and]p2: | |||
13487 | // If the second expression is evaluated, every value computation and | |||
13488 | // side effect associated with the first expression is sequenced before | |||
13489 | // every value computation and side effect associated with the | |||
13490 | // second expression. | |||
13491 | SequenceTree::Seq LHSRegion = Tree.allocate(Region); | |||
13492 | SequenceTree::Seq RHSRegion = Tree.allocate(Region); | |||
13493 | SequenceTree::Seq OldRegion = Region; | |||
13494 | ||||
13495 | EvaluationTracker Eval(*this); | |||
13496 | { | |||
13497 | SequencedSubexpression Sequenced(*this); | |||
13498 | Region = LHSRegion; | |||
13499 | Visit(BO->getLHS()); | |||
13500 | } | |||
13501 | ||||
13502 | // C++11 [expr.log.and]p1: | |||
13503 | // [...] the second operand is not evaluated if the first operand is false. | |||
13504 | bool EvalResult = false; | |||
13505 | bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); | |||
13506 | bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); | |||
13507 | if (ShouldVisitRHS) { | |||
13508 | Region = RHSRegion; | |||
13509 | Visit(BO->getRHS()); | |||
13510 | } | |||
13511 | ||||
13512 | Region = OldRegion; | |||
13513 | Tree.merge(LHSRegion); | |||
13514 | Tree.merge(RHSRegion); | |||
13515 | } | |||
13516 | ||||
13517 | void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { | |||
13518 | // C++11 [expr.cond]p1: | |||
13519 | // [...] Every value computation and side effect associated with the first | |||
13520 | // expression is sequenced before every value computation and side effect | |||
13521 | // associated with the second or third expression. | |||
13522 | SequenceTree::Seq ConditionRegion = Tree.allocate(Region); | |||
13523 | ||||
13524 | // No sequencing is specified between the true and false expression. | |||
13525 | // However since exactly one of both is going to be evaluated we can | |||
13526 | // consider them to be sequenced. This is needed to avoid warning on | |||
13527 | // something like "x ? y+= 1 : y += 2;" in the case where we will visit | |||
13528 | // both the true and false expressions because we can't evaluate x. | |||
13529 | // This will still allow us to detect an expression like (pre C++17) | |||
13530 | // "(x ? y += 1 : y += 2) = y". | |||
13531 | // | |||
13532 | // We don't wrap the visitation of the true and false expression with | |||
13533 | // SequencedSubexpression because we don't want to downgrade modifications | |||
13534 | // as side effect in the true and false expressions after the visition | |||
13535 | // is done. (for example in the expression "(x ? y++ : y++) + y" we should | |||
13536 | // not warn between the two "y++", but we should warn between the "y++" | |||
13537 | // and the "y". | |||
13538 | SequenceTree::Seq TrueRegion = Tree.allocate(Region); | |||
13539 | SequenceTree::Seq FalseRegion = Tree.allocate(Region); | |||
13540 | SequenceTree::Seq OldRegion = Region; | |||
13541 | ||||
13542 | EvaluationTracker Eval(*this); | |||
13543 | { | |||
13544 | SequencedSubexpression Sequenced(*this); | |||
13545 | Region = ConditionRegion; | |||
13546 | Visit(CO->getCond()); | |||
13547 | } | |||
13548 | ||||
13549 | // C++11 [expr.cond]p1: | |||
13550 | // [...] The first expression is contextually converted to bool (Clause 4). | |||
13551 | // It is evaluated and if it is true, the result of the conditional | |||
13552 | // expression is the value of the second expression, otherwise that of the | |||
13553 | // third expression. Only one of the second and third expressions is | |||
13554 | // evaluated. [...] | |||
13555 | bool EvalResult = false; | |||
13556 | bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); | |||
13557 | bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); | |||
13558 | bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); | |||
13559 | if (ShouldVisitTrueExpr) { | |||
13560 | Region = TrueRegion; | |||
13561 | Visit(CO->getTrueExpr()); | |||
13562 | } | |||
13563 | if (ShouldVisitFalseExpr) { | |||
13564 | Region = FalseRegion; | |||
13565 | Visit(CO->getFalseExpr()); | |||
13566 | } | |||
13567 | ||||
13568 | Region = OldRegion; | |||
13569 | Tree.merge(ConditionRegion); | |||
13570 | Tree.merge(TrueRegion); | |||
13571 | Tree.merge(FalseRegion); | |||
13572 | } | |||
13573 | ||||
13574 | void VisitCallExpr(const CallExpr *CE) { | |||
13575 | // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. | |||
13576 | ||||
13577 | if (CE->isUnevaluatedBuiltinCall(Context)) | |||
13578 | return; | |||
13579 | ||||
13580 | // C++11 [intro.execution]p15: | |||
13581 | // When calling a function [...], every value computation and side effect | |||
13582 | // associated with any argument expression, or with the postfix expression | |||
13583 | // designating the called function, is sequenced before execution of every | |||
13584 | // expression or statement in the body of the function [and thus before | |||
13585 | // the value computation of its result]. | |||
13586 | SequencedSubexpression Sequenced(*this); | |||
13587 | SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { | |||
13588 | // C++17 [expr.call]p5 | |||
13589 | // The postfix-expression is sequenced before each expression in the | |||
13590 | // expression-list and any default argument. [...] | |||
13591 | SequenceTree::Seq CalleeRegion; | |||
13592 | SequenceTree::Seq OtherRegion; | |||
13593 | if (SemaRef.getLangOpts().CPlusPlus17) { | |||
13594 | CalleeRegion = Tree.allocate(Region); | |||
13595 | OtherRegion = Tree.allocate(Region); | |||
13596 | } else { | |||
13597 | CalleeRegion = Region; | |||
13598 | OtherRegion = Region; | |||
13599 | } | |||
13600 | SequenceTree::Seq OldRegion = Region; | |||
13601 | ||||
13602 | // Visit the callee expression first. | |||
13603 | Region = CalleeRegion; | |||
13604 | if (SemaRef.getLangOpts().CPlusPlus17) { | |||
13605 | SequencedSubexpression Sequenced(*this); | |||
13606 | Visit(CE->getCallee()); | |||
13607 | } else { | |||
13608 | Visit(CE->getCallee()); | |||
13609 | } | |||
13610 | ||||
13611 | // Then visit the argument expressions. | |||
13612 | Region = OtherRegion; | |||
13613 | for (const Expr *Argument : CE->arguments()) | |||
13614 | Visit(Argument); | |||
13615 | ||||
13616 | Region = OldRegion; | |||
13617 | if (SemaRef.getLangOpts().CPlusPlus17) { | |||
13618 | Tree.merge(CalleeRegion); | |||
13619 | Tree.merge(OtherRegion); | |||
13620 | } | |||
13621 | }); | |||
13622 | } | |||
13623 | ||||
13624 | void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { | |||
13625 | // C++17 [over.match.oper]p2: | |||
13626 | // [...] the operator notation is first transformed to the equivalent | |||
13627 | // function-call notation as summarized in Table 12 (where @ denotes one | |||
13628 | // of the operators covered in the specified subclause). However, the | |||
13629 | // operands are sequenced in the order prescribed for the built-in | |||
13630 | // operator (Clause 8). | |||
13631 | // | |||
13632 | // From the above only overloaded binary operators and overloaded call | |||
13633 | // operators have sequencing rules in C++17 that we need to handle | |||
13634 | // separately. | |||
13635 | if (!SemaRef.getLangOpts().CPlusPlus17 || | |||
13636 | (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) | |||
13637 | return VisitCallExpr(CXXOCE); | |||
13638 | ||||
13639 | enum { | |||
13640 | NoSequencing, | |||
13641 | LHSBeforeRHS, | |||
13642 | RHSBeforeLHS, | |||
13643 | LHSBeforeRest | |||
13644 | } SequencingKind; | |||
13645 | switch (CXXOCE->getOperator()) { | |||
13646 | case OO_Equal: | |||
13647 | case OO_PlusEqual: | |||
13648 | case OO_MinusEqual: | |||
13649 | case OO_StarEqual: | |||
13650 | case OO_SlashEqual: | |||
13651 | case OO_PercentEqual: | |||
13652 | case OO_CaretEqual: | |||
13653 | case OO_AmpEqual: | |||
13654 | case OO_PipeEqual: | |||
13655 | case OO_LessLessEqual: | |||
13656 | case OO_GreaterGreaterEqual: | |||
13657 | SequencingKind = RHSBeforeLHS; | |||
13658 | break; | |||
13659 | ||||
13660 | case OO_LessLess: | |||
13661 | case OO_GreaterGreater: | |||
13662 | case OO_AmpAmp: | |||
13663 | case OO_PipePipe: | |||
13664 | case OO_Comma: | |||
13665 | case OO_ArrowStar: | |||
13666 | case OO_Subscript: | |||
13667 | SequencingKind = LHSBeforeRHS; | |||
13668 | break; | |||
13669 | ||||
13670 | case OO_Call: | |||
13671 | SequencingKind = LHSBeforeRest; | |||
13672 | break; | |||
13673 | ||||
13674 | default: | |||
13675 | SequencingKind = NoSequencing; | |||
13676 | break; | |||
13677 | } | |||
13678 | ||||
13679 | if (SequencingKind == NoSequencing) | |||
13680 | return VisitCallExpr(CXXOCE); | |||
13681 | ||||
13682 | // This is a call, so all subexpressions are sequenced before the result. | |||
13683 | SequencedSubexpression Sequenced(*this); | |||
13684 | ||||
13685 | SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { | |||
13686 | assert(SemaRef.getLangOpts().CPlusPlus17 &&((SemaRef.getLangOpts().CPlusPlus17 && "Should only get there with C++17 and above!" ) ? static_cast<void> (0) : __assert_fail ("SemaRef.getLangOpts().CPlusPlus17 && \"Should only get there with C++17 and above!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13687, __PRETTY_FUNCTION__)) | |||
13687 | "Should only get there with C++17 and above!")((SemaRef.getLangOpts().CPlusPlus17 && "Should only get there with C++17 and above!" ) ? static_cast<void> (0) : __assert_fail ("SemaRef.getLangOpts().CPlusPlus17 && \"Should only get there with C++17 and above!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13687, __PRETTY_FUNCTION__)); | |||
13688 | assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&(((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && "Should only get there with an overloaded binary operator" " or an overloaded call operator!") ? static_cast<void> (0) : __assert_fail ("(CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && \"Should only get there with an overloaded binary operator\" \" or an overloaded call operator!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13690, __PRETTY_FUNCTION__)) | |||
13689 | "Should only get there with an overloaded binary operator"(((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && "Should only get there with an overloaded binary operator" " or an overloaded call operator!") ? static_cast<void> (0) : __assert_fail ("(CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && \"Should only get there with an overloaded binary operator\" \" or an overloaded call operator!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13690, __PRETTY_FUNCTION__)) | |||
13690 | " or an overloaded call operator!")(((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && "Should only get there with an overloaded binary operator" " or an overloaded call operator!") ? static_cast<void> (0) : __assert_fail ("(CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && \"Should only get there with an overloaded binary operator\" \" or an overloaded call operator!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13690, __PRETTY_FUNCTION__)); | |||
13691 | ||||
13692 | if (SequencingKind == LHSBeforeRest) { | |||
13693 | assert(CXXOCE->getOperator() == OO_Call &&((CXXOCE->getOperator() == OO_Call && "We should only have an overloaded call operator here!" ) ? static_cast<void> (0) : __assert_fail ("CXXOCE->getOperator() == OO_Call && \"We should only have an overloaded call operator here!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13694, __PRETTY_FUNCTION__)) | |||
13694 | "We should only have an overloaded call operator here!")((CXXOCE->getOperator() == OO_Call && "We should only have an overloaded call operator here!" ) ? static_cast<void> (0) : __assert_fail ("CXXOCE->getOperator() == OO_Call && \"We should only have an overloaded call operator here!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13694, __PRETTY_FUNCTION__)); | |||
13695 | ||||
13696 | // This is very similar to VisitCallExpr, except that we only have the | |||
13697 | // C++17 case. The postfix-expression is the first argument of the | |||
13698 | // CXXOperatorCallExpr. The expressions in the expression-list, if any, | |||
13699 | // are in the following arguments. | |||
13700 | // | |||
13701 | // Note that we intentionally do not visit the callee expression since | |||
13702 | // it is just a decayed reference to a function. | |||
13703 | SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); | |||
13704 | SequenceTree::Seq ArgsRegion = Tree.allocate(Region); | |||
13705 | SequenceTree::Seq OldRegion = Region; | |||
13706 | ||||
13707 | assert(CXXOCE->getNumArgs() >= 1 &&((CXXOCE->getNumArgs() >= 1 && "An overloaded call operator must have at least one argument" " for the postfix-expression!") ? static_cast<void> (0 ) : __assert_fail ("CXXOCE->getNumArgs() >= 1 && \"An overloaded call operator must have at least one argument\" \" for the postfix-expression!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13709, __PRETTY_FUNCTION__)) | |||
13708 | "An overloaded call operator must have at least one argument"((CXXOCE->getNumArgs() >= 1 && "An overloaded call operator must have at least one argument" " for the postfix-expression!") ? static_cast<void> (0 ) : __assert_fail ("CXXOCE->getNumArgs() >= 1 && \"An overloaded call operator must have at least one argument\" \" for the postfix-expression!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13709, __PRETTY_FUNCTION__)) | |||
13709 | " for the postfix-expression!")((CXXOCE->getNumArgs() >= 1 && "An overloaded call operator must have at least one argument" " for the postfix-expression!") ? static_cast<void> (0 ) : __assert_fail ("CXXOCE->getNumArgs() >= 1 && \"An overloaded call operator must have at least one argument\" \" for the postfix-expression!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13709, __PRETTY_FUNCTION__)); | |||
13710 | const Expr *PostfixExpr = CXXOCE->getArgs()[0]; | |||
13711 | llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, | |||
13712 | CXXOCE->getNumArgs() - 1); | |||
13713 | ||||
13714 | // Visit the postfix-expression first. | |||
13715 | { | |||
13716 | Region = PostfixExprRegion; | |||
13717 | SequencedSubexpression Sequenced(*this); | |||
13718 | Visit(PostfixExpr); | |||
13719 | } | |||
13720 | ||||
13721 | // Then visit the argument expressions. | |||
13722 | Region = ArgsRegion; | |||
13723 | for (const Expr *Arg : Args) | |||
13724 | Visit(Arg); | |||
13725 | ||||
13726 | Region = OldRegion; | |||
13727 | Tree.merge(PostfixExprRegion); | |||
13728 | Tree.merge(ArgsRegion); | |||
13729 | } else { | |||
13730 | assert(CXXOCE->getNumArgs() == 2 &&((CXXOCE->getNumArgs() == 2 && "Should only have two arguments here!" ) ? static_cast<void> (0) : __assert_fail ("CXXOCE->getNumArgs() == 2 && \"Should only have two arguments here!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13731, __PRETTY_FUNCTION__)) | |||
13731 | "Should only have two arguments here!")((CXXOCE->getNumArgs() == 2 && "Should only have two arguments here!" ) ? static_cast<void> (0) : __assert_fail ("CXXOCE->getNumArgs() == 2 && \"Should only have two arguments here!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13731, __PRETTY_FUNCTION__)); | |||
13732 | assert((SequencingKind == LHSBeforeRHS ||(((SequencingKind == LHSBeforeRHS || SequencingKind == RHSBeforeLHS ) && "Unexpected sequencing kind!") ? static_cast< void> (0) : __assert_fail ("(SequencingKind == LHSBeforeRHS || SequencingKind == RHSBeforeLHS) && \"Unexpected sequencing kind!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13734, __PRETTY_FUNCTION__)) | |||
13733 | SequencingKind == RHSBeforeLHS) &&(((SequencingKind == LHSBeforeRHS || SequencingKind == RHSBeforeLHS ) && "Unexpected sequencing kind!") ? static_cast< void> (0) : __assert_fail ("(SequencingKind == LHSBeforeRHS || SequencingKind == RHSBeforeLHS) && \"Unexpected sequencing kind!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13734, __PRETTY_FUNCTION__)) | |||
13734 | "Unexpected sequencing kind!")(((SequencingKind == LHSBeforeRHS || SequencingKind == RHSBeforeLHS ) && "Unexpected sequencing kind!") ? static_cast< void> (0) : __assert_fail ("(SequencingKind == LHSBeforeRHS || SequencingKind == RHSBeforeLHS) && \"Unexpected sequencing kind!\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 13734, __PRETTY_FUNCTION__)); | |||
13735 | ||||
13736 | // We do not visit the callee expression since it is just a decayed | |||
13737 | // reference to a function. | |||
13738 | const Expr *E1 = CXXOCE->getArg(0); | |||
13739 | const Expr *E2 = CXXOCE->getArg(1); | |||
13740 | if (SequencingKind == RHSBeforeLHS) | |||
13741 | std::swap(E1, E2); | |||
13742 | ||||
13743 | return VisitSequencedExpressions(E1, E2); | |||
13744 | } | |||
13745 | }); | |||
13746 | } | |||
13747 | ||||
13748 | void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { | |||
13749 | // This is a call, so all subexpressions are sequenced before the result. | |||
13750 | SequencedSubexpression Sequenced(*this); | |||
13751 | ||||
13752 | if (!CCE->isListInitialization()) | |||
13753 | return VisitExpr(CCE); | |||
13754 | ||||
13755 | // In C++11, list initializations are sequenced. | |||
13756 | SmallVector<SequenceTree::Seq, 32> Elts; | |||
13757 | SequenceTree::Seq Parent = Region; | |||
13758 | for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), | |||
13759 | E = CCE->arg_end(); | |||
13760 | I != E; ++I) { | |||
13761 | Region = Tree.allocate(Parent); | |||
13762 | Elts.push_back(Region); | |||
13763 | Visit(*I); | |||
13764 | } | |||
13765 | ||||
13766 | // Forget that the initializers are sequenced. | |||
13767 | Region = Parent; | |||
13768 | for (unsigned I = 0; I < Elts.size(); ++I) | |||
13769 | Tree.merge(Elts[I]); | |||
13770 | } | |||
13771 | ||||
13772 | void VisitInitListExpr(const InitListExpr *ILE) { | |||
13773 | if (!SemaRef.getLangOpts().CPlusPlus11) | |||
13774 | return VisitExpr(ILE); | |||
13775 | ||||
13776 | // In C++11, list initializations are sequenced. | |||
13777 | SmallVector<SequenceTree::Seq, 32> Elts; | |||
13778 | SequenceTree::Seq Parent = Region; | |||
13779 | for (unsigned I = 0; I < ILE->getNumInits(); ++I) { | |||
13780 | const Expr *E = ILE->getInit(I); | |||
13781 | if (!E) | |||
13782 | continue; | |||
13783 | Region = Tree.allocate(Parent); | |||
13784 | Elts.push_back(Region); | |||
13785 | Visit(E); | |||
13786 | } | |||
13787 | ||||
13788 | // Forget that the initializers are sequenced. | |||
13789 | Region = Parent; | |||
13790 | for (unsigned I = 0; I < Elts.size(); ++I) | |||
13791 | Tree.merge(Elts[I]); | |||
13792 | } | |||
13793 | }; | |||
13794 | ||||
13795 | } // namespace | |||
13796 | ||||
13797 | void Sema::CheckUnsequencedOperations(const Expr *E) { | |||
13798 | SmallVector<const Expr *, 8> WorkList; | |||
13799 | WorkList.push_back(E); | |||
13800 | while (!WorkList.empty()) { | |||
13801 | const Expr *Item = WorkList.pop_back_val(); | |||
13802 | SequenceChecker(*this, Item, WorkList); | |||
13803 | } | |||
13804 | } | |||
13805 | ||||
13806 | void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, | |||
13807 | bool IsConstexpr) { | |||
13808 | llvm::SaveAndRestore<bool> ConstantContext( | |||
13809 | isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); | |||
13810 | CheckImplicitConversions(E, CheckLoc); | |||
13811 | if (!E->isInstantiationDependent()) | |||
13812 | CheckUnsequencedOperations(E); | |||
13813 | if (!IsConstexpr && !E->isValueDependent()) | |||
13814 | CheckForIntOverflow(E); | |||
13815 | DiagnoseMisalignedMembers(); | |||
13816 | } | |||
13817 | ||||
13818 | void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, | |||
13819 | FieldDecl *BitField, | |||
13820 | Expr *Init) { | |||
13821 | (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); | |||
13822 | } | |||
13823 | ||||
13824 | static void diagnoseArrayStarInParamType(Sema &S, QualType PType, | |||
13825 | SourceLocation Loc) { | |||
13826 | if (!PType->isVariablyModifiedType()) | |||
13827 | return; | |||
13828 | if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { | |||
13829 | diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); | |||
13830 | return; | |||
13831 | } | |||
13832 | if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { | |||
13833 | diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); | |||
13834 | return; | |||
13835 | } | |||
13836 | if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { | |||
13837 | diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); | |||
13838 | return; | |||
13839 | } | |||
13840 | ||||
13841 | const ArrayType *AT = S.Context.getAsArrayType(PType); | |||
13842 | if (!AT) | |||
13843 | return; | |||
13844 | ||||
13845 | if (AT->getSizeModifier() != ArrayType::Star) { | |||
13846 | diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); | |||
13847 | return; | |||
13848 | } | |||
13849 | ||||
13850 | S.Diag(Loc, diag::err_array_star_in_function_definition); | |||
13851 | } | |||
13852 | ||||
13853 | /// CheckParmsForFunctionDef - Check that the parameters of the given | |||
13854 | /// function are appropriate for the definition of a function. This | |||
13855 | /// takes care of any checks that cannot be performed on the | |||
13856 | /// declaration itself, e.g., that the types of each of the function | |||
13857 | /// parameters are complete. | |||
13858 | bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, | |||
13859 | bool CheckParameterNames) { | |||
13860 | bool HasInvalidParm = false; | |||
13861 | for (ParmVarDecl *Param : Parameters) { | |||
13862 | // C99 6.7.5.3p4: the parameters in a parameter type list in a | |||
13863 | // function declarator that is part of a function definition of | |||
13864 | // that function shall not have incomplete type. | |||
13865 | // | |||
13866 | // This is also C++ [dcl.fct]p6. | |||
13867 | if (!Param->isInvalidDecl() && | |||
13868 | RequireCompleteType(Param->getLocation(), Param->getType(), | |||
13869 | diag::err_typecheck_decl_incomplete_type)) { | |||
13870 | Param->setInvalidDecl(); | |||
13871 | HasInvalidParm = true; | |||
13872 | } | |||
13873 | ||||
13874 | // C99 6.9.1p5: If the declarator includes a parameter type list, the | |||
13875 | // declaration of each parameter shall include an identifier. | |||
13876 | if (CheckParameterNames && Param->getIdentifier() == nullptr && | |||
13877 | !Param->isImplicit() && !getLangOpts().CPlusPlus) { | |||
13878 | // Diagnose this as an extension in C17 and earlier. | |||
13879 | if (!getLangOpts().C2x) | |||
13880 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | |||
13881 | } | |||
13882 | ||||
13883 | // C99 6.7.5.3p12: | |||
13884 | // If the function declarator is not part of a definition of that | |||
13885 | // function, parameters may have incomplete type and may use the [*] | |||
13886 | // notation in their sequences of declarator specifiers to specify | |||
13887 | // variable length array types. | |||
13888 | QualType PType = Param->getOriginalType(); | |||
13889 | // FIXME: This diagnostic should point the '[*]' if source-location | |||
13890 | // information is added for it. | |||
13891 | diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); | |||
13892 | ||||
13893 | // If the parameter is a c++ class type and it has to be destructed in the | |||
13894 | // callee function, declare the destructor so that it can be called by the | |||
13895 | // callee function. Do not perform any direct access check on the dtor here. | |||
13896 | if (!Param->isInvalidDecl()) { | |||
13897 | if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { | |||
13898 | if (!ClassDecl->isInvalidDecl() && | |||
13899 | !ClassDecl->hasIrrelevantDestructor() && | |||
13900 | !ClassDecl->isDependentContext() && | |||
13901 | ClassDecl->isParamDestroyedInCallee()) { | |||
13902 | CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); | |||
13903 | MarkFunctionReferenced(Param->getLocation(), Destructor); | |||
13904 | DiagnoseUseOfDecl(Destructor, Param->getLocation()); | |||
13905 | } | |||
13906 | } | |||
13907 | } | |||
13908 | ||||
13909 | // Parameters with the pass_object_size attribute only need to be marked | |||
13910 | // constant at function definitions. Because we lack information about | |||
13911 | // whether we're on a declaration or definition when we're instantiating the | |||
13912 | // attribute, we need to check for constness here. | |||
13913 | if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) | |||
13914 | if (!Param->getType().isConstQualified()) | |||
13915 | Diag(Param->getLocation(), diag::err_attribute_pointers_only) | |||
13916 | << Attr->getSpelling() << 1; | |||
13917 | ||||
13918 | // Check for parameter names shadowing fields from the class. | |||
13919 | if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { | |||
13920 | // The owning context for the parameter should be the function, but we | |||
13921 | // want to see if this function's declaration context is a record. | |||
13922 | DeclContext *DC = Param->getDeclContext(); | |||
13923 | if (DC && DC->isFunctionOrMethod()) { | |||
13924 | if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) | |||
13925 | CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), | |||
13926 | RD, /*DeclIsField*/ false); | |||
13927 | } | |||
13928 | } | |||
13929 | } | |||
13930 | ||||
13931 | return HasInvalidParm; | |||
13932 | } | |||
13933 | ||||
13934 | Optional<std::pair<CharUnits, CharUnits>> | |||
13935 | static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); | |||
13936 | ||||
13937 | /// Compute the alignment and offset of the base class object given the | |||
13938 | /// derived-to-base cast expression and the alignment and offset of the derived | |||
13939 | /// class object. | |||
13940 | static std::pair<CharUnits, CharUnits> | |||
13941 | getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, | |||
13942 | CharUnits BaseAlignment, CharUnits Offset, | |||
13943 | ASTContext &Ctx) { | |||
13944 | for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; | |||
13945 | ++PathI) { | |||
13946 | const CXXBaseSpecifier *Base = *PathI; | |||
13947 | const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); | |||
13948 | if (Base->isVirtual()) { | |||
13949 | // The complete object may have a lower alignment than the non-virtual | |||
13950 | // alignment of the base, in which case the base may be misaligned. Choose | |||
13951 | // the smaller of the non-virtual alignment and BaseAlignment, which is a | |||
13952 | // conservative lower bound of the complete object alignment. | |||
13953 | CharUnits NonVirtualAlignment = | |||
13954 | Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); | |||
13955 | BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); | |||
13956 | Offset = CharUnits::Zero(); | |||
13957 | } else { | |||
13958 | const ASTRecordLayout &RL = | |||
13959 | Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); | |||
13960 | Offset += RL.getBaseClassOffset(BaseDecl); | |||
13961 | } | |||
13962 | DerivedType = Base->getType(); | |||
13963 | } | |||
13964 | ||||
13965 | return std::make_pair(BaseAlignment, Offset); | |||
13966 | } | |||
13967 | ||||
13968 | /// Compute the alignment and offset of a binary additive operator. | |||
13969 | static Optional<std::pair<CharUnits, CharUnits>> | |||
13970 | getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, | |||
13971 | bool IsSub, ASTContext &Ctx) { | |||
13972 | QualType PointeeType = PtrE->getType()->getPointeeType(); | |||
13973 | ||||
13974 | if (!PointeeType->isConstantSizeType()) | |||
13975 | return llvm::None; | |||
13976 | ||||
13977 | auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); | |||
13978 | ||||
13979 | if (!P) | |||
13980 | return llvm::None; | |||
13981 | ||||
13982 | CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); | |||
13983 | if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { | |||
13984 | CharUnits Offset = EltSize * IdxRes->getExtValue(); | |||
13985 | if (IsSub) | |||
13986 | Offset = -Offset; | |||
13987 | return std::make_pair(P->first, P->second + Offset); | |||
13988 | } | |||
13989 | ||||
13990 | // If the integer expression isn't a constant expression, compute the lower | |||
13991 | // bound of the alignment using the alignment and offset of the pointer | |||
13992 | // expression and the element size. | |||
13993 | return std::make_pair( | |||
13994 | P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), | |||
13995 | CharUnits::Zero()); | |||
13996 | } | |||
13997 | ||||
13998 | /// This helper function takes an lvalue expression and returns the alignment of | |||
13999 | /// a VarDecl and a constant offset from the VarDecl. | |||
14000 | Optional<std::pair<CharUnits, CharUnits>> | |||
14001 | static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { | |||
14002 | E = E->IgnoreParens(); | |||
14003 | switch (E->getStmtClass()) { | |||
14004 | default: | |||
14005 | break; | |||
14006 | case Stmt::CStyleCastExprClass: | |||
14007 | case Stmt::CXXStaticCastExprClass: | |||
14008 | case Stmt::ImplicitCastExprClass: { | |||
14009 | auto *CE = cast<CastExpr>(E); | |||
14010 | const Expr *From = CE->getSubExpr(); | |||
14011 | switch (CE->getCastKind()) { | |||
14012 | default: | |||
14013 | break; | |||
14014 | case CK_NoOp: | |||
14015 | return getBaseAlignmentAndOffsetFromLValue(From, Ctx); | |||
14016 | case CK_UncheckedDerivedToBase: | |||
14017 | case CK_DerivedToBase: { | |||
14018 | auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); | |||
14019 | if (!P) | |||
14020 | break; | |||
14021 | return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, | |||
14022 | P->second, Ctx); | |||
14023 | } | |||
14024 | } | |||
14025 | break; | |||
14026 | } | |||
14027 | case Stmt::ArraySubscriptExprClass: { | |||
14028 | auto *ASE = cast<ArraySubscriptExpr>(E); | |||
14029 | return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), | |||
14030 | false, Ctx); | |||
14031 | } | |||
14032 | case Stmt::DeclRefExprClass: { | |||
14033 | if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { | |||
14034 | // FIXME: If VD is captured by copy or is an escaping __block variable, | |||
14035 | // use the alignment of VD's type. | |||
14036 | if (!VD->getType()->isReferenceType()) | |||
14037 | return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); | |||
14038 | if (VD->hasInit()) | |||
14039 | return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); | |||
14040 | } | |||
14041 | break; | |||
14042 | } | |||
14043 | case Stmt::MemberExprClass: { | |||
14044 | auto *ME = cast<MemberExpr>(E); | |||
14045 | auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | |||
14046 | if (!FD || FD->getType()->isReferenceType()) | |||
14047 | break; | |||
14048 | Optional<std::pair<CharUnits, CharUnits>> P; | |||
14049 | if (ME->isArrow()) | |||
14050 | P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); | |||
14051 | else | |||
14052 | P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); | |||
14053 | if (!P) | |||
14054 | break; | |||
14055 | const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); | |||
14056 | uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); | |||
14057 | return std::make_pair(P->first, | |||
14058 | P->second + CharUnits::fromQuantity(Offset)); | |||
14059 | } | |||
14060 | case Stmt::UnaryOperatorClass: { | |||
14061 | auto *UO = cast<UnaryOperator>(E); | |||
14062 | switch (UO->getOpcode()) { | |||
14063 | default: | |||
14064 | break; | |||
14065 | case UO_Deref: | |||
14066 | return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); | |||
14067 | } | |||
14068 | break; | |||
14069 | } | |||
14070 | case Stmt::BinaryOperatorClass: { | |||
14071 | auto *BO = cast<BinaryOperator>(E); | |||
14072 | auto Opcode = BO->getOpcode(); | |||
14073 | switch (Opcode) { | |||
14074 | default: | |||
14075 | break; | |||
14076 | case BO_Comma: | |||
14077 | return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); | |||
14078 | } | |||
14079 | break; | |||
14080 | } | |||
14081 | } | |||
14082 | return llvm::None; | |||
14083 | } | |||
14084 | ||||
14085 | /// This helper function takes a pointer expression and returns the alignment of | |||
14086 | /// a VarDecl and a constant offset from the VarDecl. | |||
14087 | Optional<std::pair<CharUnits, CharUnits>> | |||
14088 | static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { | |||
14089 | E = E->IgnoreParens(); | |||
14090 | switch (E->getStmtClass()) { | |||
14091 | default: | |||
14092 | break; | |||
14093 | case Stmt::CStyleCastExprClass: | |||
14094 | case Stmt::CXXStaticCastExprClass: | |||
14095 | case Stmt::ImplicitCastExprClass: { | |||
14096 | auto *CE = cast<CastExpr>(E); | |||
14097 | const Expr *From = CE->getSubExpr(); | |||
14098 | switch (CE->getCastKind()) { | |||
14099 | default: | |||
14100 | break; | |||
14101 | case CK_NoOp: | |||
14102 | return getBaseAlignmentAndOffsetFromPtr(From, Ctx); | |||
14103 | case CK_ArrayToPointerDecay: | |||
14104 | return getBaseAlignmentAndOffsetFromLValue(From, Ctx); | |||
14105 | case CK_UncheckedDerivedToBase: | |||
14106 | case CK_DerivedToBase: { | |||
14107 | auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); | |||
14108 | if (!P) | |||
14109 | break; | |||
14110 | return getDerivedToBaseAlignmentAndOffset( | |||
14111 | CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); | |||
14112 | } | |||
14113 | } | |||
14114 | break; | |||
14115 | } | |||
14116 | case Stmt::CXXThisExprClass: { | |||
14117 | auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); | |||
14118 | CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); | |||
14119 | return std::make_pair(Alignment, CharUnits::Zero()); | |||
14120 | } | |||
14121 | case Stmt::UnaryOperatorClass: { | |||
14122 | auto *UO = cast<UnaryOperator>(E); | |||
14123 | if (UO->getOpcode() == UO_AddrOf) | |||
14124 | return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); | |||
14125 | break; | |||
14126 | } | |||
14127 | case Stmt::BinaryOperatorClass: { | |||
14128 | auto *BO = cast<BinaryOperator>(E); | |||
14129 | auto Opcode = BO->getOpcode(); | |||
14130 | switch (Opcode) { | |||
14131 | default: | |||
14132 | break; | |||
14133 | case BO_Add: | |||
14134 | case BO_Sub: { | |||
14135 | const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); | |||
14136 | if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) | |||
14137 | std::swap(LHS, RHS); | |||
14138 | return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, | |||
14139 | Ctx); | |||
14140 | } | |||
14141 | case BO_Comma: | |||
14142 | return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); | |||
14143 | } | |||
14144 | break; | |||
14145 | } | |||
14146 | } | |||
14147 | return llvm::None; | |||
14148 | } | |||
14149 | ||||
14150 | static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { | |||
14151 | // See if we can compute the alignment of a VarDecl and an offset from it. | |||
14152 | Optional<std::pair<CharUnits, CharUnits>> P = | |||
14153 | getBaseAlignmentAndOffsetFromPtr(E, S.Context); | |||
14154 | ||||
14155 | if (P) | |||
14156 | return P->first.alignmentAtOffset(P->second); | |||
14157 | ||||
14158 | // If that failed, return the type's alignment. | |||
14159 | return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); | |||
14160 | } | |||
14161 | ||||
14162 | /// CheckCastAlign - Implements -Wcast-align, which warns when a | |||
14163 | /// pointer cast increases the alignment requirements. | |||
14164 | void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { | |||
14165 | // This is actually a lot of work to potentially be doing on every | |||
14166 | // cast; don't do it if we're ignoring -Wcast_align (as is the default). | |||
14167 | if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) | |||
14168 | return; | |||
14169 | ||||
14170 | // Ignore dependent types. | |||
14171 | if (T->isDependentType() || Op->getType()->isDependentType()) | |||
14172 | return; | |||
14173 | ||||
14174 | // Require that the destination be a pointer type. | |||
14175 | const PointerType *DestPtr = T->getAs<PointerType>(); | |||
14176 | if (!DestPtr) return; | |||
14177 | ||||
14178 | // If the destination has alignment 1, we're done. | |||
14179 | QualType DestPointee = DestPtr->getPointeeType(); | |||
14180 | if (DestPointee->isIncompleteType()) return; | |||
14181 | CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); | |||
14182 | if (DestAlign.isOne()) return; | |||
14183 | ||||
14184 | // Require that the source be a pointer type. | |||
14185 | const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); | |||
14186 | if (!SrcPtr) return; | |||
14187 | QualType SrcPointee = SrcPtr->getPointeeType(); | |||
14188 | ||||
14189 | // Explicitly allow casts from cv void*. We already implicitly | |||
14190 | // allowed casts to cv void*, since they have alignment 1. | |||
14191 | // Also allow casts involving incomplete types, which implicitly | |||
14192 | // includes 'void'. | |||
14193 | if (SrcPointee->isIncompleteType()) return; | |||
14194 | ||||
14195 | CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); | |||
14196 | ||||
14197 | if (SrcAlign >= DestAlign) return; | |||
14198 | ||||
14199 | Diag(TRange.getBegin(), diag::warn_cast_align) | |||
14200 | << Op->getType() << T | |||
14201 | << static_cast<unsigned>(SrcAlign.getQuantity()) | |||
14202 | << static_cast<unsigned>(DestAlign.getQuantity()) | |||
14203 | << TRange << Op->getSourceRange(); | |||
14204 | } | |||
14205 | ||||
14206 | /// Check whether this array fits the idiom of a size-one tail padded | |||
14207 | /// array member of a struct. | |||
14208 | /// | |||
14209 | /// We avoid emitting out-of-bounds access warnings for such arrays as they are | |||
14210 | /// commonly used to emulate flexible arrays in C89 code. | |||
14211 | static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, | |||
14212 | const NamedDecl *ND) { | |||
14213 | if (Size != 1 || !ND) return false; | |||
14214 | ||||
14215 | const FieldDecl *FD = dyn_cast<FieldDecl>(ND); | |||
14216 | if (!FD) return false; | |||
14217 | ||||
14218 | // Don't consider sizes resulting from macro expansions or template argument | |||
14219 | // substitution to form C89 tail-padded arrays. | |||
14220 | ||||
14221 | TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); | |||
14222 | while (TInfo) { | |||
14223 | TypeLoc TL = TInfo->getTypeLoc(); | |||
14224 | // Look through typedefs. | |||
14225 | if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { | |||
14226 | const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); | |||
14227 | TInfo = TDL->getTypeSourceInfo(); | |||
14228 | continue; | |||
14229 | } | |||
14230 | if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { | |||
14231 | const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); | |||
14232 | if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) | |||
14233 | return false; | |||
14234 | } | |||
14235 | break; | |||
14236 | } | |||
14237 | ||||
14238 | const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); | |||
14239 | if (!RD) return false; | |||
14240 | if (RD->isUnion()) return false; | |||
14241 | if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | |||
14242 | if (!CRD->isStandardLayout()) return false; | |||
14243 | } | |||
14244 | ||||
14245 | // See if this is the last field decl in the record. | |||
14246 | const Decl *D = FD; | |||
14247 | while ((D = D->getNextDeclInContext())) | |||
14248 | if (isa<FieldDecl>(D)) | |||
14249 | return false; | |||
14250 | return true; | |||
14251 | } | |||
14252 | ||||
14253 | void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, | |||
14254 | const ArraySubscriptExpr *ASE, | |||
14255 | bool AllowOnePastEnd, bool IndexNegated) { | |||
14256 | // Already diagnosed by the constant evaluator. | |||
14257 | if (isConstantEvaluated()) | |||
14258 | return; | |||
14259 | ||||
14260 | IndexExpr = IndexExpr->IgnoreParenImpCasts(); | |||
14261 | if (IndexExpr->isValueDependent()) | |||
14262 | return; | |||
14263 | ||||
14264 | const Type *EffectiveType = | |||
14265 | BaseExpr->getType()->getPointeeOrArrayElementType(); | |||
14266 | BaseExpr = BaseExpr->IgnoreParenCasts(); | |||
14267 | const ConstantArrayType *ArrayTy = | |||
14268 | Context.getAsConstantArrayType(BaseExpr->getType()); | |||
14269 | ||||
14270 | if (!ArrayTy) | |||
14271 | return; | |||
14272 | ||||
14273 | const Type *BaseType = ArrayTy->getElementType().getTypePtr(); | |||
14274 | if (EffectiveType->isDependentType() || BaseType->isDependentType()) | |||
14275 | return; | |||
14276 | ||||
14277 | Expr::EvalResult Result; | |||
14278 | if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) | |||
14279 | return; | |||
14280 | ||||
14281 | llvm::APSInt index = Result.Val.getInt(); | |||
14282 | if (IndexNegated) | |||
14283 | index = -index; | |||
14284 | ||||
14285 | const NamedDecl *ND = nullptr; | |||
14286 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) | |||
14287 | ND = DRE->getDecl(); | |||
14288 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) | |||
14289 | ND = ME->getMemberDecl(); | |||
14290 | ||||
14291 | if (index.isUnsigned() || !index.isNegative()) { | |||
14292 | // It is possible that the type of the base expression after | |||
14293 | // IgnoreParenCasts is incomplete, even though the type of the base | |||
14294 | // expression before IgnoreParenCasts is complete (see PR39746 for an | |||
14295 | // example). In this case we have no information about whether the array | |||
14296 | // access exceeds the array bounds. However we can still diagnose an array | |||
14297 | // access which precedes the array bounds. | |||
14298 | if (BaseType->isIncompleteType()) | |||
14299 | return; | |||
14300 | ||||
14301 | llvm::APInt size = ArrayTy->getSize(); | |||
14302 | if (!size.isStrictlyPositive()) | |||
14303 | return; | |||
14304 | ||||
14305 | if (BaseType != EffectiveType) { | |||
14306 | // Make sure we're comparing apples to apples when comparing index to size | |||
14307 | uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); | |||
14308 | uint64_t array_typesize = Context.getTypeSize(BaseType); | |||
14309 | // Handle ptrarith_typesize being zero, such as when casting to void* | |||
14310 | if (!ptrarith_typesize) ptrarith_typesize = 1; | |||
14311 | if (ptrarith_typesize != array_typesize) { | |||
14312 | // There's a cast to a different size type involved | |||
14313 | uint64_t ratio = array_typesize / ptrarith_typesize; | |||
14314 | // TODO: Be smarter about handling cases where array_typesize is not a | |||
14315 | // multiple of ptrarith_typesize | |||
14316 | if (ptrarith_typesize * ratio == array_typesize) | |||
14317 | size *= llvm::APInt(size.getBitWidth(), ratio); | |||
14318 | } | |||
14319 | } | |||
14320 | ||||
14321 | if (size.getBitWidth() > index.getBitWidth()) | |||
14322 | index = index.zext(size.getBitWidth()); | |||
14323 | else if (size.getBitWidth() < index.getBitWidth()) | |||
14324 | size = size.zext(index.getBitWidth()); | |||
14325 | ||||
14326 | // For array subscripting the index must be less than size, but for pointer | |||
14327 | // arithmetic also allow the index (offset) to be equal to size since | |||
14328 | // computing the next address after the end of the array is legal and | |||
14329 | // commonly done e.g. in C++ iterators and range-based for loops. | |||
14330 | if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) | |||
14331 | return; | |||
14332 | ||||
14333 | // Also don't warn for arrays of size 1 which are members of some | |||
14334 | // structure. These are often used to approximate flexible arrays in C89 | |||
14335 | // code. | |||
14336 | if (IsTailPaddedMemberArray(*this, size, ND)) | |||
14337 | return; | |||
14338 | ||||
14339 | // Suppress the warning if the subscript expression (as identified by the | |||
14340 | // ']' location) and the index expression are both from macro expansions | |||
14341 | // within a system header. | |||
14342 | if (ASE) { | |||
14343 | SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( | |||
14344 | ASE->getRBracketLoc()); | |||
14345 | if (SourceMgr.isInSystemHeader(RBracketLoc)) { | |||
14346 | SourceLocation IndexLoc = | |||
14347 | SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); | |||
14348 | if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) | |||
14349 | return; | |||
14350 | } | |||
14351 | } | |||
14352 | ||||
14353 | unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; | |||
14354 | if (ASE) | |||
14355 | DiagID = diag::warn_array_index_exceeds_bounds; | |||
14356 | ||||
14357 | DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, | |||
14358 | PDiag(DiagID) << index.toString(10, true) | |||
14359 | << size.toString(10, true) | |||
14360 | << (unsigned)size.getLimitedValue(~0U) | |||
14361 | << IndexExpr->getSourceRange()); | |||
14362 | } else { | |||
14363 | unsigned DiagID = diag::warn_array_index_precedes_bounds; | |||
14364 | if (!ASE) { | |||
14365 | DiagID = diag::warn_ptr_arith_precedes_bounds; | |||
14366 | if (index.isNegative()) index = -index; | |||
14367 | } | |||
14368 | ||||
14369 | DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, | |||
14370 | PDiag(DiagID) << index.toString(10, true) | |||
14371 | << IndexExpr->getSourceRange()); | |||
14372 | } | |||
14373 | ||||
14374 | if (!ND) { | |||
14375 | // Try harder to find a NamedDecl to point at in the note. | |||
14376 | while (const ArraySubscriptExpr *ASE = | |||
14377 | dyn_cast<ArraySubscriptExpr>(BaseExpr)) | |||
14378 | BaseExpr = ASE->getBase()->IgnoreParenCasts(); | |||
14379 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) | |||
14380 | ND = DRE->getDecl(); | |||
14381 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) | |||
14382 | ND = ME->getMemberDecl(); | |||
14383 | } | |||
14384 | ||||
14385 | if (ND) | |||
14386 | DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, | |||
14387 | PDiag(diag::note_array_declared_here) << ND); | |||
14388 | } | |||
14389 | ||||
14390 | void Sema::CheckArrayAccess(const Expr *expr) { | |||
14391 | int AllowOnePastEnd = 0; | |||
14392 | while (expr) { | |||
14393 | expr = expr->IgnoreParenImpCasts(); | |||
14394 | switch (expr->getStmtClass()) { | |||
14395 | case Stmt::ArraySubscriptExprClass: { | |||
14396 | const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); | |||
14397 | CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, | |||
14398 | AllowOnePastEnd > 0); | |||
14399 | expr = ASE->getBase(); | |||
14400 | break; | |||
14401 | } | |||
14402 | case Stmt::MemberExprClass: { | |||
14403 | expr = cast<MemberExpr>(expr)->getBase(); | |||
14404 | break; | |||
14405 | } | |||
14406 | case Stmt::OMPArraySectionExprClass: { | |||
14407 | const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); | |||
14408 | if (ASE->getLowerBound()) | |||
14409 | CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), | |||
14410 | /*ASE=*/nullptr, AllowOnePastEnd > 0); | |||
14411 | return; | |||
14412 | } | |||
14413 | case Stmt::UnaryOperatorClass: { | |||
14414 | // Only unwrap the * and & unary operators | |||
14415 | const UnaryOperator *UO = cast<UnaryOperator>(expr); | |||
14416 | expr = UO->getSubExpr(); | |||
14417 | switch (UO->getOpcode()) { | |||
14418 | case UO_AddrOf: | |||
14419 | AllowOnePastEnd++; | |||
14420 | break; | |||
14421 | case UO_Deref: | |||
14422 | AllowOnePastEnd--; | |||
14423 | break; | |||
14424 | default: | |||
14425 | return; | |||
14426 | } | |||
14427 | break; | |||
14428 | } | |||
14429 | case Stmt::ConditionalOperatorClass: { | |||
14430 | const ConditionalOperator *cond = cast<ConditionalOperator>(expr); | |||
14431 | if (const Expr *lhs = cond->getLHS()) | |||
14432 | CheckArrayAccess(lhs); | |||
14433 | if (const Expr *rhs = cond->getRHS()) | |||
14434 | CheckArrayAccess(rhs); | |||
14435 | return; | |||
14436 | } | |||
14437 | case Stmt::CXXOperatorCallExprClass: { | |||
14438 | const auto *OCE = cast<CXXOperatorCallExpr>(expr); | |||
14439 | for (const auto *Arg : OCE->arguments()) | |||
14440 | CheckArrayAccess(Arg); | |||
14441 | return; | |||
14442 | } | |||
14443 | default: | |||
14444 | return; | |||
14445 | } | |||
14446 | } | |||
14447 | } | |||
14448 | ||||
14449 | //===--- CHECK: Objective-C retain cycles ----------------------------------// | |||
14450 | ||||
14451 | namespace { | |||
14452 | ||||
14453 | struct RetainCycleOwner { | |||
14454 | VarDecl *Variable = nullptr; | |||
14455 | SourceRange Range; | |||
14456 | SourceLocation Loc; | |||
14457 | bool Indirect = false; | |||
14458 | ||||
14459 | RetainCycleOwner() = default; | |||
14460 | ||||
14461 | void setLocsFrom(Expr *e) { | |||
14462 | Loc = e->getExprLoc(); | |||
14463 | Range = e->getSourceRange(); | |||
14464 | } | |||
14465 | }; | |||
14466 | ||||
14467 | } // namespace | |||
14468 | ||||
14469 | /// Consider whether capturing the given variable can possibly lead to | |||
14470 | /// a retain cycle. | |||
14471 | static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { | |||
14472 | // In ARC, it's captured strongly iff the variable has __strong | |||
14473 | // lifetime. In MRR, it's captured strongly if the variable is | |||
14474 | // __block and has an appropriate type. | |||
14475 | if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) | |||
14476 | return false; | |||
14477 | ||||
14478 | owner.Variable = var; | |||
14479 | if (ref) | |||
14480 | owner.setLocsFrom(ref); | |||
14481 | return true; | |||
14482 | } | |||
14483 | ||||
14484 | static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { | |||
14485 | while (true) { | |||
14486 | e = e->IgnoreParens(); | |||
14487 | if (CastExpr *cast = dyn_cast<CastExpr>(e)) { | |||
14488 | switch (cast->getCastKind()) { | |||
14489 | case CK_BitCast: | |||
14490 | case CK_LValueBitCast: | |||
14491 | case CK_LValueToRValue: | |||
14492 | case CK_ARCReclaimReturnedObject: | |||
14493 | e = cast->getSubExpr(); | |||
14494 | continue; | |||
14495 | ||||
14496 | default: | |||
14497 | return false; | |||
14498 | } | |||
14499 | } | |||
14500 | ||||
14501 | if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { | |||
14502 | ObjCIvarDecl *ivar = ref->getDecl(); | |||
14503 | if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) | |||
14504 | return false; | |||
14505 | ||||
14506 | // Try to find a retain cycle in the base. | |||
14507 | if (!findRetainCycleOwner(S, ref->getBase(), owner)) | |||
14508 | return false; | |||
14509 | ||||
14510 | if (ref->isFreeIvar()) owner.setLocsFrom(ref); | |||
14511 | owner.Indirect = true; | |||
14512 | return true; | |||
14513 | } | |||
14514 | ||||
14515 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { | |||
14516 | VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); | |||
14517 | if (!var) return false; | |||
14518 | return considerVariable(var, ref, owner); | |||
14519 | } | |||
14520 | ||||
14521 | if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { | |||
14522 | if (member->isArrow()) return false; | |||
14523 | ||||
14524 | // Don't count this as an indirect ownership. | |||
14525 | e = member->getBase(); | |||
14526 | continue; | |||
14527 | } | |||
14528 | ||||
14529 | if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { | |||
14530 | // Only pay attention to pseudo-objects on property references. | |||
14531 | ObjCPropertyRefExpr *pre | |||
14532 | = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() | |||
14533 | ->IgnoreParens()); | |||
14534 | if (!pre) return false; | |||
14535 | if (pre->isImplicitProperty()) return false; | |||
14536 | ObjCPropertyDecl *property = pre->getExplicitProperty(); | |||
14537 | if (!property->isRetaining() && | |||
14538 | !(property->getPropertyIvarDecl() && | |||
14539 | property->getPropertyIvarDecl()->getType() | |||
14540 | .getObjCLifetime() == Qualifiers::OCL_Strong)) | |||
14541 | return false; | |||
14542 | ||||
14543 | owner.Indirect = true; | |||
14544 | if (pre->isSuperReceiver()) { | |||
14545 | owner.Variable = S.getCurMethodDecl()->getSelfDecl(); | |||
14546 | if (!owner.Variable) | |||
14547 | return false; | |||
14548 | owner.Loc = pre->getLocation(); | |||
14549 | owner.Range = pre->getSourceRange(); | |||
14550 | return true; | |||
14551 | } | |||
14552 | e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) | |||
14553 | ->getSourceExpr()); | |||
14554 | continue; | |||
14555 | } | |||
14556 | ||||
14557 | // Array ivars? | |||
14558 | ||||
14559 | return false; | |||
14560 | } | |||
14561 | } | |||
14562 | ||||
14563 | namespace { | |||
14564 | ||||
14565 | struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { | |||
14566 | ASTContext &Context; | |||
14567 | VarDecl *Variable; | |||
14568 | Expr *Capturer = nullptr; | |||
14569 | bool VarWillBeReased = false; | |||
14570 | ||||
14571 | FindCaptureVisitor(ASTContext &Context, VarDecl *variable) | |||
14572 | : EvaluatedExprVisitor<FindCaptureVisitor>(Context), | |||
14573 | Context(Context), Variable(variable) {} | |||
14574 | ||||
14575 | void VisitDeclRefExpr(DeclRefExpr *ref) { | |||
14576 | if (ref->getDecl() == Variable && !Capturer) | |||
14577 | Capturer = ref; | |||
14578 | } | |||
14579 | ||||
14580 | void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { | |||
14581 | if (Capturer) return; | |||
14582 | Visit(ref->getBase()); | |||
14583 | if (Capturer && ref->isFreeIvar()) | |||
14584 | Capturer = ref; | |||
14585 | } | |||
14586 | ||||
14587 | void VisitBlockExpr(BlockExpr *block) { | |||
14588 | // Look inside nested blocks | |||
14589 | if (block->getBlockDecl()->capturesVariable(Variable)) | |||
14590 | Visit(block->getBlockDecl()->getBody()); | |||
14591 | } | |||
14592 | ||||
14593 | void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { | |||
14594 | if (Capturer) return; | |||
14595 | if (OVE->getSourceExpr()) | |||
14596 | Visit(OVE->getSourceExpr()); | |||
14597 | } | |||
14598 | ||||
14599 | void VisitBinaryOperator(BinaryOperator *BinOp) { | |||
14600 | if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) | |||
14601 | return; | |||
14602 | Expr *LHS = BinOp->getLHS(); | |||
14603 | if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { | |||
14604 | if (DRE->getDecl() != Variable) | |||
14605 | return; | |||
14606 | if (Expr *RHS = BinOp->getRHS()) { | |||
14607 | RHS = RHS->IgnoreParenCasts(); | |||
14608 | Optional<llvm::APSInt> Value; | |||
14609 | VarWillBeReased = | |||
14610 | (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && | |||
14611 | *Value == 0); | |||
14612 | } | |||
14613 | } | |||
14614 | } | |||
14615 | }; | |||
14616 | ||||
14617 | } // namespace | |||
14618 | ||||
14619 | /// Check whether the given argument is a block which captures a | |||
14620 | /// variable. | |||
14621 | static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { | |||
14622 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 14622, __PRETTY_FUNCTION__)); | |||
14623 | ||||
14624 | e = e->IgnoreParenCasts(); | |||
14625 | ||||
14626 | // Look through [^{...} copy] and Block_copy(^{...}). | |||
14627 | if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { | |||
14628 | Selector Cmd = ME->getSelector(); | |||
14629 | if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { | |||
14630 | e = ME->getInstanceReceiver(); | |||
14631 | if (!e) | |||
14632 | return nullptr; | |||
14633 | e = e->IgnoreParenCasts(); | |||
14634 | } | |||
14635 | } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { | |||
14636 | if (CE->getNumArgs() == 1) { | |||
14637 | FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); | |||
14638 | if (Fn) { | |||
14639 | const IdentifierInfo *FnI = Fn->getIdentifier(); | |||
14640 | if (FnI && FnI->isStr("_Block_copy")) { | |||
14641 | e = CE->getArg(0)->IgnoreParenCasts(); | |||
14642 | } | |||
14643 | } | |||
14644 | } | |||
14645 | } | |||
14646 | ||||
14647 | BlockExpr *block = dyn_cast<BlockExpr>(e); | |||
14648 | if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) | |||
14649 | return nullptr; | |||
14650 | ||||
14651 | FindCaptureVisitor visitor(S.Context, owner.Variable); | |||
14652 | visitor.Visit(block->getBlockDecl()->getBody()); | |||
14653 | return visitor.VarWillBeReased ? nullptr : visitor.Capturer; | |||
14654 | } | |||
14655 | ||||
14656 | static void diagnoseRetainCycle(Sema &S, Expr *capturer, | |||
14657 | RetainCycleOwner &owner) { | |||
14658 | assert(capturer)((capturer) ? static_cast<void> (0) : __assert_fail ("capturer" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 14658, __PRETTY_FUNCTION__)); | |||
14659 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 14659, __PRETTY_FUNCTION__)); | |||
14660 | ||||
14661 | S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) | |||
14662 | << owner.Variable << capturer->getSourceRange(); | |||
14663 | S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) | |||
14664 | << owner.Indirect << owner.Range; | |||
14665 | } | |||
14666 | ||||
14667 | /// Check for a keyword selector that starts with the word 'add' or | |||
14668 | /// 'set'. | |||
14669 | static bool isSetterLikeSelector(Selector sel) { | |||
14670 | if (sel.isUnarySelector()) return false; | |||
14671 | ||||
14672 | StringRef str = sel.getNameForSlot(0); | |||
14673 | while (!str.empty() && str.front() == '_') str = str.substr(1); | |||
14674 | if (str.startswith("set")) | |||
14675 | str = str.substr(3); | |||
14676 | else if (str.startswith("add")) { | |||
14677 | // Specially allow 'addOperationWithBlock:'. | |||
14678 | if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) | |||
14679 | return false; | |||
14680 | str = str.substr(3); | |||
14681 | } | |||
14682 | else | |||
14683 | return false; | |||
14684 | ||||
14685 | if (str.empty()) return true; | |||
14686 | return !isLowercase(str.front()); | |||
14687 | } | |||
14688 | ||||
14689 | static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, | |||
14690 | ObjCMessageExpr *Message) { | |||
14691 | bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( | |||
14692 | Message->getReceiverInterface(), | |||
14693 | NSAPI::ClassId_NSMutableArray); | |||
14694 | if (!IsMutableArray) { | |||
14695 | return None; | |||
14696 | } | |||
14697 | ||||
14698 | Selector Sel = Message->getSelector(); | |||
14699 | ||||
14700 | Optional<NSAPI::NSArrayMethodKind> MKOpt = | |||
14701 | S.NSAPIObj->getNSArrayMethodKind(Sel); | |||
14702 | if (!MKOpt) { | |||
14703 | return None; | |||
14704 | } | |||
14705 | ||||
14706 | NSAPI::NSArrayMethodKind MK = *MKOpt; | |||
14707 | ||||
14708 | switch (MK) { | |||
14709 | case NSAPI::NSMutableArr_addObject: | |||
14710 | case NSAPI::NSMutableArr_insertObjectAtIndex: | |||
14711 | case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: | |||
14712 | return 0; | |||
14713 | case NSAPI::NSMutableArr_replaceObjectAtIndex: | |||
14714 | return 1; | |||
14715 | ||||
14716 | default: | |||
14717 | return None; | |||
14718 | } | |||
14719 | ||||
14720 | return None; | |||
14721 | } | |||
14722 | ||||
14723 | static | |||
14724 | Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, | |||
14725 | ObjCMessageExpr *Message) { | |||
14726 | bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( | |||
14727 | Message->getReceiverInterface(), | |||
14728 | NSAPI::ClassId_NSMutableDictionary); | |||
14729 | if (!IsMutableDictionary) { | |||
14730 | return None; | |||
14731 | } | |||
14732 | ||||
14733 | Selector Sel = Message->getSelector(); | |||
14734 | ||||
14735 | Optional<NSAPI::NSDictionaryMethodKind> MKOpt = | |||
14736 | S.NSAPIObj->getNSDictionaryMethodKind(Sel); | |||
14737 | if (!MKOpt) { | |||
14738 | return None; | |||
14739 | } | |||
14740 | ||||
14741 | NSAPI::NSDictionaryMethodKind MK = *MKOpt; | |||
14742 | ||||
14743 | switch (MK) { | |||
14744 | case NSAPI::NSMutableDict_setObjectForKey: | |||
14745 | case NSAPI::NSMutableDict_setValueForKey: | |||
14746 | case NSAPI::NSMutableDict_setObjectForKeyedSubscript: | |||
14747 | return 0; | |||
14748 | ||||
14749 | default: | |||
14750 | return None; | |||
14751 | } | |||
14752 | ||||
14753 | return None; | |||
14754 | } | |||
14755 | ||||
14756 | static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { | |||
14757 | bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( | |||
14758 | Message->getReceiverInterface(), | |||
14759 | NSAPI::ClassId_NSMutableSet); | |||
14760 | ||||
14761 | bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( | |||
14762 | Message->getReceiverInterface(), | |||
14763 | NSAPI::ClassId_NSMutableOrderedSet); | |||
14764 | if (!IsMutableSet && !IsMutableOrderedSet) { | |||
14765 | return None; | |||
14766 | } | |||
14767 | ||||
14768 | Selector Sel = Message->getSelector(); | |||
14769 | ||||
14770 | Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); | |||
14771 | if (!MKOpt) { | |||
14772 | return None; | |||
14773 | } | |||
14774 | ||||
14775 | NSAPI::NSSetMethodKind MK = *MKOpt; | |||
14776 | ||||
14777 | switch (MK) { | |||
14778 | case NSAPI::NSMutableSet_addObject: | |||
14779 | case NSAPI::NSOrderedSet_setObjectAtIndex: | |||
14780 | case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: | |||
14781 | case NSAPI::NSOrderedSet_insertObjectAtIndex: | |||
14782 | return 0; | |||
14783 | case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: | |||
14784 | return 1; | |||
14785 | } | |||
14786 | ||||
14787 | return None; | |||
14788 | } | |||
14789 | ||||
14790 | void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { | |||
14791 | if (!Message->isInstanceMessage()) { | |||
14792 | return; | |||
14793 | } | |||
14794 | ||||
14795 | Optional<int> ArgOpt; | |||
14796 | ||||
14797 | if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && | |||
14798 | !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && | |||
14799 | !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { | |||
14800 | return; | |||
14801 | } | |||
14802 | ||||
14803 | int ArgIndex = *ArgOpt; | |||
14804 | ||||
14805 | Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); | |||
14806 | if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { | |||
14807 | Arg = OE->getSourceExpr()->IgnoreImpCasts(); | |||
14808 | } | |||
14809 | ||||
14810 | if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { | |||
14811 | if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { | |||
14812 | if (ArgRE->isObjCSelfExpr()) { | |||
14813 | Diag(Message->getSourceRange().getBegin(), | |||
14814 | diag::warn_objc_circular_container) | |||
14815 | << ArgRE->getDecl() << StringRef("'super'"); | |||
14816 | } | |||
14817 | } | |||
14818 | } else { | |||
14819 | Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); | |||
14820 | ||||
14821 | if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { | |||
14822 | Receiver = OE->getSourceExpr()->IgnoreImpCasts(); | |||
14823 | } | |||
14824 | ||||
14825 | if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { | |||
14826 | if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { | |||
14827 | if (ReceiverRE->getDecl() == ArgRE->getDecl()) { | |||
14828 | ValueDecl *Decl = ReceiverRE->getDecl(); | |||
14829 | Diag(Message->getSourceRange().getBegin(), | |||
14830 | diag::warn_objc_circular_container) | |||
14831 | << Decl << Decl; | |||
14832 | if (!ArgRE->isObjCSelfExpr()) { | |||
14833 | Diag(Decl->getLocation(), | |||
14834 | diag::note_objc_circular_container_declared_here) | |||
14835 | << Decl; | |||
14836 | } | |||
14837 | } | |||
14838 | } | |||
14839 | } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { | |||
14840 | if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { | |||
14841 | if (IvarRE->getDecl() == IvarArgRE->getDecl()) { | |||
14842 | ObjCIvarDecl *Decl = IvarRE->getDecl(); | |||
14843 | Diag(Message->getSourceRange().getBegin(), | |||
14844 | diag::warn_objc_circular_container) | |||
14845 | << Decl << Decl; | |||
14846 | Diag(Decl->getLocation(), | |||
14847 | diag::note_objc_circular_container_declared_here) | |||
14848 | << Decl; | |||
14849 | } | |||
14850 | } | |||
14851 | } | |||
14852 | } | |||
14853 | } | |||
14854 | ||||
14855 | /// Check a message send to see if it's likely to cause a retain cycle. | |||
14856 | void Sema::checkRetainCycles(ObjCMessageExpr *msg) { | |||
14857 | // Only check instance methods whose selector looks like a setter. | |||
14858 | if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) | |||
14859 | return; | |||
14860 | ||||
14861 | // Try to find a variable that the receiver is strongly owned by. | |||
14862 | RetainCycleOwner owner; | |||
14863 | if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { | |||
14864 | if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) | |||
14865 | return; | |||
14866 | } else { | |||
14867 | assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance)((msg->getReceiverKind() == ObjCMessageExpr::SuperInstance ) ? static_cast<void> (0) : __assert_fail ("msg->getReceiverKind() == ObjCMessageExpr::SuperInstance" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 14867, __PRETTY_FUNCTION__)); | |||
14868 | owner.Variable = getCurMethodDecl()->getSelfDecl(); | |||
14869 | owner.Loc = msg->getSuperLoc(); | |||
14870 | owner.Range = msg->getSuperLoc(); | |||
14871 | } | |||
14872 | ||||
14873 | // Check whether the receiver is captured by any of the arguments. | |||
14874 | const ObjCMethodDecl *MD = msg->getMethodDecl(); | |||
14875 | for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { | |||
14876 | if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { | |||
14877 | // noescape blocks should not be retained by the method. | |||
14878 | if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) | |||
14879 | continue; | |||
14880 | return diagnoseRetainCycle(*this, capturer, owner); | |||
14881 | } | |||
14882 | } | |||
14883 | } | |||
14884 | ||||
14885 | /// Check a property assign to see if it's likely to cause a retain cycle. | |||
14886 | void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { | |||
14887 | RetainCycleOwner owner; | |||
14888 | if (!findRetainCycleOwner(*this, receiver, owner)) | |||
14889 | return; | |||
14890 | ||||
14891 | if (Expr *capturer = findCapturingExpr(*this, argument, owner)) | |||
14892 | diagnoseRetainCycle(*this, capturer, owner); | |||
14893 | } | |||
14894 | ||||
14895 | void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { | |||
14896 | RetainCycleOwner Owner; | |||
14897 | if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) | |||
14898 | return; | |||
14899 | ||||
14900 | // Because we don't have an expression for the variable, we have to set the | |||
14901 | // location explicitly here. | |||
14902 | Owner.Loc = Var->getLocation(); | |||
14903 | Owner.Range = Var->getSourceRange(); | |||
14904 | ||||
14905 | if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) | |||
14906 | diagnoseRetainCycle(*this, Capturer, Owner); | |||
14907 | } | |||
14908 | ||||
14909 | static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, | |||
14910 | Expr *RHS, bool isProperty) { | |||
14911 | // Check if RHS is an Objective-C object literal, which also can get | |||
14912 | // immediately zapped in a weak reference. Note that we explicitly | |||
14913 | // allow ObjCStringLiterals, since those are designed to never really die. | |||
14914 | RHS = RHS->IgnoreParenImpCasts(); | |||
14915 | ||||
14916 | // This enum needs to match with the 'select' in | |||
14917 | // warn_objc_arc_literal_assign (off-by-1). | |||
14918 | Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); | |||
14919 | if (Kind == Sema::LK_String || Kind == Sema::LK_None) | |||
14920 | return false; | |||
14921 | ||||
14922 | S.Diag(Loc, diag::warn_arc_literal_assign) | |||
14923 | << (unsigned) Kind | |||
14924 | << (isProperty ? 0 : 1) | |||
14925 | << RHS->getSourceRange(); | |||
14926 | ||||
14927 | return true; | |||
14928 | } | |||
14929 | ||||
14930 | static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, | |||
14931 | Qualifiers::ObjCLifetime LT, | |||
14932 | Expr *RHS, bool isProperty) { | |||
14933 | // Strip off any implicit cast added to get to the one ARC-specific. | |||
14934 | while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { | |||
14935 | if (cast->getCastKind() == CK_ARCConsumeObject) { | |||
14936 | S.Diag(Loc, diag::warn_arc_retained_assign) | |||
14937 | << (LT == Qualifiers::OCL_ExplicitNone) | |||
14938 | << (isProperty ? 0 : 1) | |||
14939 | << RHS->getSourceRange(); | |||
14940 | return true; | |||
14941 | } | |||
14942 | RHS = cast->getSubExpr(); | |||
14943 | } | |||
14944 | ||||
14945 | if (LT == Qualifiers::OCL_Weak && | |||
14946 | checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) | |||
14947 | return true; | |||
14948 | ||||
14949 | return false; | |||
14950 | } | |||
14951 | ||||
14952 | bool Sema::checkUnsafeAssigns(SourceLocation Loc, | |||
14953 | QualType LHS, Expr *RHS) { | |||
14954 | Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); | |||
14955 | ||||
14956 | if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) | |||
14957 | return false; | |||
14958 | ||||
14959 | if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) | |||
14960 | return true; | |||
14961 | ||||
14962 | return false; | |||
14963 | } | |||
14964 | ||||
14965 | void Sema::checkUnsafeExprAssigns(SourceLocation Loc, | |||
14966 | Expr *LHS, Expr *RHS) { | |||
14967 | QualType LHSType; | |||
14968 | // PropertyRef on LHS type need be directly obtained from | |||
14969 | // its declaration as it has a PseudoType. | |||
14970 | ObjCPropertyRefExpr *PRE | |||
14971 | = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); | |||
14972 | if (PRE && !PRE->isImplicitProperty()) { | |||
14973 | const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); | |||
14974 | if (PD) | |||
14975 | LHSType = PD->getType(); | |||
14976 | } | |||
14977 | ||||
14978 | if (LHSType.isNull()) | |||
14979 | LHSType = LHS->getType(); | |||
14980 | ||||
14981 | Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); | |||
14982 | ||||
14983 | if (LT == Qualifiers::OCL_Weak) { | |||
14984 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | |||
14985 | getCurFunction()->markSafeWeakUse(LHS); | |||
14986 | } | |||
14987 | ||||
14988 | if (checkUnsafeAssigns(Loc, LHSType, RHS)) | |||
14989 | return; | |||
14990 | ||||
14991 | // FIXME. Check for other life times. | |||
14992 | if (LT != Qualifiers::OCL_None) | |||
14993 | return; | |||
14994 | ||||
14995 | if (PRE) { | |||
14996 | if (PRE->isImplicitProperty()) | |||
14997 | return; | |||
14998 | const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); | |||
14999 | if (!PD) | |||
15000 | return; | |||
15001 | ||||
15002 | unsigned Attributes = PD->getPropertyAttributes(); | |||
15003 | if (Attributes & ObjCPropertyAttribute::kind_assign) { | |||
15004 | // when 'assign' attribute was not explicitly specified | |||
15005 | // by user, ignore it and rely on property type itself | |||
15006 | // for lifetime info. | |||
15007 | unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); | |||
15008 | if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && | |||
15009 | LHSType->isObjCRetainableType()) | |||
15010 | return; | |||
15011 | ||||
15012 | while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { | |||
15013 | if (cast->getCastKind() == CK_ARCConsumeObject) { | |||
15014 | Diag(Loc, diag::warn_arc_retained_property_assign) | |||
15015 | << RHS->getSourceRange(); | |||
15016 | return; | |||
15017 | } | |||
15018 | RHS = cast->getSubExpr(); | |||
15019 | } | |||
15020 | } else if (Attributes & ObjCPropertyAttribute::kind_weak) { | |||
15021 | if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) | |||
15022 | return; | |||
15023 | } | |||
15024 | } | |||
15025 | } | |||
15026 | ||||
15027 | //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// | |||
15028 | ||||
15029 | static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, | |||
15030 | SourceLocation StmtLoc, | |||
15031 | const NullStmt *Body) { | |||
15032 | // Do not warn if the body is a macro that expands to nothing, e.g: | |||
15033 | // | |||
15034 | // #define CALL(x) | |||
15035 | // if (condition) | |||
15036 | // CALL(0); | |||
15037 | if (Body->hasLeadingEmptyMacro()) | |||
15038 | return false; | |||
15039 | ||||
15040 | // Get line numbers of statement and body. | |||
15041 | bool StmtLineInvalid; | |||
15042 | unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, | |||
15043 | &StmtLineInvalid); | |||
15044 | if (StmtLineInvalid) | |||
15045 | return false; | |||
15046 | ||||
15047 | bool BodyLineInvalid; | |||
15048 | unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), | |||
15049 | &BodyLineInvalid); | |||
15050 | if (BodyLineInvalid) | |||
15051 | return false; | |||
15052 | ||||
15053 | // Warn if null statement and body are on the same line. | |||
15054 | if (StmtLine != BodyLine) | |||
15055 | return false; | |||
15056 | ||||
15057 | return true; | |||
15058 | } | |||
15059 | ||||
15060 | void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, | |||
15061 | const Stmt *Body, | |||
15062 | unsigned DiagID) { | |||
15063 | // Since this is a syntactic check, don't emit diagnostic for template | |||
15064 | // instantiations, this just adds noise. | |||
15065 | if (CurrentInstantiationScope) | |||
15066 | return; | |||
15067 | ||||
15068 | // The body should be a null statement. | |||
15069 | const NullStmt *NBody = dyn_cast<NullStmt>(Body); | |||
15070 | if (!NBody) | |||
15071 | return; | |||
15072 | ||||
15073 | // Do the usual checks. | |||
15074 | if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) | |||
15075 | return; | |||
15076 | ||||
15077 | Diag(NBody->getSemiLoc(), DiagID); | |||
15078 | Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); | |||
15079 | } | |||
15080 | ||||
15081 | void Sema::DiagnoseEmptyLoopBody(const Stmt *S, | |||
15082 | const Stmt *PossibleBody) { | |||
15083 | assert(!CurrentInstantiationScope)((!CurrentInstantiationScope) ? static_cast<void> (0) : __assert_fail ("!CurrentInstantiationScope", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 15083, __PRETTY_FUNCTION__)); // Ensured by caller | |||
15084 | ||||
15085 | SourceLocation StmtLoc; | |||
15086 | const Stmt *Body; | |||
15087 | unsigned DiagID; | |||
15088 | if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { | |||
15089 | StmtLoc = FS->getRParenLoc(); | |||
15090 | Body = FS->getBody(); | |||
15091 | DiagID = diag::warn_empty_for_body; | |||
15092 | } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { | |||
15093 | StmtLoc = WS->getCond()->getSourceRange().getEnd(); | |||
15094 | Body = WS->getBody(); | |||
15095 | DiagID = diag::warn_empty_while_body; | |||
15096 | } else | |||
15097 | return; // Neither `for' nor `while'. | |||
15098 | ||||
15099 | // The body should be a null statement. | |||
15100 | const NullStmt *NBody = dyn_cast<NullStmt>(Body); | |||
15101 | if (!NBody) | |||
15102 | return; | |||
15103 | ||||
15104 | // Skip expensive checks if diagnostic is disabled. | |||
15105 | if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) | |||
15106 | return; | |||
15107 | ||||
15108 | // Do the usual checks. | |||
15109 | if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) | |||
15110 | return; | |||
15111 | ||||
15112 | // `for(...);' and `while(...);' are popular idioms, so in order to keep | |||
15113 | // noise level low, emit diagnostics only if for/while is followed by a | |||
15114 | // CompoundStmt, e.g.: | |||
15115 | // for (int i = 0; i < n; i++); | |||
15116 | // { | |||
15117 | // a(i); | |||
15118 | // } | |||
15119 | // or if for/while is followed by a statement with more indentation | |||
15120 | // than for/while itself: | |||
15121 | // for (int i = 0; i < n; i++); | |||
15122 | // a(i); | |||
15123 | bool ProbableTypo = isa<CompoundStmt>(PossibleBody); | |||
15124 | if (!ProbableTypo) { | |||
15125 | bool BodyColInvalid; | |||
15126 | unsigned BodyCol = SourceMgr.getPresumedColumnNumber( | |||
15127 | PossibleBody->getBeginLoc(), &BodyColInvalid); | |||
15128 | if (BodyColInvalid) | |||
15129 | return; | |||
15130 | ||||
15131 | bool StmtColInvalid; | |||
15132 | unsigned StmtCol = | |||
15133 | SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); | |||
15134 | if (StmtColInvalid) | |||
15135 | return; | |||
15136 | ||||
15137 | if (BodyCol > StmtCol) | |||
15138 | ProbableTypo = true; | |||
15139 | } | |||
15140 | ||||
15141 | if (ProbableTypo) { | |||
15142 | Diag(NBody->getSemiLoc(), DiagID); | |||
15143 | Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); | |||
15144 | } | |||
15145 | } | |||
15146 | ||||
15147 | //===--- CHECK: Warn on self move with std::move. -------------------------===// | |||
15148 | ||||
15149 | /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. | |||
15150 | void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, | |||
15151 | SourceLocation OpLoc) { | |||
15152 | if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) | |||
15153 | return; | |||
15154 | ||||
15155 | if (inTemplateInstantiation()) | |||
15156 | return; | |||
15157 | ||||
15158 | // Strip parens and casts away. | |||
15159 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | |||
15160 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | |||
15161 | ||||
15162 | // Check for a call expression | |||
15163 | const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); | |||
15164 | if (!CE || CE->getNumArgs() != 1) | |||
15165 | return; | |||
15166 | ||||
15167 | // Check for a call to std::move | |||
15168 | if (!CE->isCallToStdMove()) | |||
15169 | return; | |||
15170 | ||||
15171 | // Get argument from std::move | |||
15172 | RHSExpr = CE->getArg(0); | |||
15173 | ||||
15174 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | |||
15175 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | |||
15176 | ||||
15177 | // Two DeclRefExpr's, check that the decls are the same. | |||
15178 | if (LHSDeclRef && RHSDeclRef) { | |||
15179 | if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) | |||
15180 | return; | |||
15181 | if (LHSDeclRef->getDecl()->getCanonicalDecl() != | |||
15182 | RHSDeclRef->getDecl()->getCanonicalDecl()) | |||
15183 | return; | |||
15184 | ||||
15185 | Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() | |||
15186 | << LHSExpr->getSourceRange() | |||
15187 | << RHSExpr->getSourceRange(); | |||
15188 | return; | |||
15189 | } | |||
15190 | ||||
15191 | // Member variables require a different approach to check for self moves. | |||
15192 | // MemberExpr's are the same if every nested MemberExpr refers to the same | |||
15193 | // Decl and that the base Expr's are DeclRefExpr's with the same Decl or | |||
15194 | // the base Expr's are CXXThisExpr's. | |||
15195 | const Expr *LHSBase = LHSExpr; | |||
15196 | const Expr *RHSBase = RHSExpr; | |||
15197 | const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); | |||
15198 | const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); | |||
15199 | if (!LHSME || !RHSME) | |||
15200 | return; | |||
15201 | ||||
15202 | while (LHSME && RHSME) { | |||
15203 | if (LHSME->getMemberDecl()->getCanonicalDecl() != | |||
15204 | RHSME->getMemberDecl()->getCanonicalDecl()) | |||
15205 | return; | |||
15206 | ||||
15207 | LHSBase = LHSME->getBase(); | |||
15208 | RHSBase = RHSME->getBase(); | |||
15209 | LHSME = dyn_cast<MemberExpr>(LHSBase); | |||
15210 | RHSME = dyn_cast<MemberExpr>(RHSBase); | |||
15211 | } | |||
15212 | ||||
15213 | LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); | |||
15214 | RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); | |||
15215 | if (LHSDeclRef && RHSDeclRef) { | |||
15216 | if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) | |||
15217 | return; | |||
15218 | if (LHSDeclRef->getDecl()->getCanonicalDecl() != | |||
15219 | RHSDeclRef->getDecl()->getCanonicalDecl()) | |||
15220 | return; | |||
15221 | ||||
15222 | Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() | |||
15223 | << LHSExpr->getSourceRange() | |||
15224 | << RHSExpr->getSourceRange(); | |||
15225 | return; | |||
15226 | } | |||
15227 | ||||
15228 | if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) | |||
15229 | Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() | |||
15230 | << LHSExpr->getSourceRange() | |||
15231 | << RHSExpr->getSourceRange(); | |||
15232 | } | |||
15233 | ||||
15234 | //===--- Layout compatibility ----------------------------------------------// | |||
15235 | ||||
15236 | static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); | |||
15237 | ||||
15238 | /// Check if two enumeration types are layout-compatible. | |||
15239 | static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { | |||
15240 | // C++11 [dcl.enum] p8: | |||
15241 | // Two enumeration types are layout-compatible if they have the same | |||
15242 | // underlying type. | |||
15243 | return ED1->isComplete() && ED2->isComplete() && | |||
15244 | C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); | |||
15245 | } | |||
15246 | ||||
15247 | /// Check if two fields are layout-compatible. | |||
15248 | static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, | |||
15249 | FieldDecl *Field2) { | |||
15250 | if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) | |||
15251 | return false; | |||
15252 | ||||
15253 | if (Field1->isBitField() != Field2->isBitField()) | |||
15254 | return false; | |||
15255 | ||||
15256 | if (Field1->isBitField()) { | |||
15257 | // Make sure that the bit-fields are the same length. | |||
15258 | unsigned Bits1 = Field1->getBitWidthValue(C); | |||
15259 | unsigned Bits2 = Field2->getBitWidthValue(C); | |||
15260 | ||||
15261 | if (Bits1 != Bits2) | |||
15262 | return false; | |||
15263 | } | |||
15264 | ||||
15265 | return true; | |||
15266 | } | |||
15267 | ||||
15268 | /// Check if two standard-layout structs are layout-compatible. | |||
15269 | /// (C++11 [class.mem] p17) | |||
15270 | static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, | |||
15271 | RecordDecl *RD2) { | |||
15272 | // If both records are C++ classes, check that base classes match. | |||
15273 | if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { | |||
15274 | // If one of records is a CXXRecordDecl we are in C++ mode, | |||
15275 | // thus the other one is a CXXRecordDecl, too. | |||
15276 | const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); | |||
15277 | // Check number of base classes. | |||
15278 | if (D1CXX->getNumBases() != D2CXX->getNumBases()) | |||
15279 | return false; | |||
15280 | ||||
15281 | // Check the base classes. | |||
15282 | for (CXXRecordDecl::base_class_const_iterator | |||
15283 | Base1 = D1CXX->bases_begin(), | |||
15284 | BaseEnd1 = D1CXX->bases_end(), | |||
15285 | Base2 = D2CXX->bases_begin(); | |||
15286 | Base1 != BaseEnd1; | |||
15287 | ++Base1, ++Base2) { | |||
15288 | if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) | |||
15289 | return false; | |||
15290 | } | |||
15291 | } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { | |||
15292 | // If only RD2 is a C++ class, it should have zero base classes. | |||
15293 | if (D2CXX->getNumBases() > 0) | |||
15294 | return false; | |||
15295 | } | |||
15296 | ||||
15297 | // Check the fields. | |||
15298 | RecordDecl::field_iterator Field2 = RD2->field_begin(), | |||
15299 | Field2End = RD2->field_end(), | |||
15300 | Field1 = RD1->field_begin(), | |||
15301 | Field1End = RD1->field_end(); | |||
15302 | for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { | |||
15303 | if (!isLayoutCompatible(C, *Field1, *Field2)) | |||
15304 | return false; | |||
15305 | } | |||
15306 | if (Field1 != Field1End || Field2 != Field2End) | |||
15307 | return false; | |||
15308 | ||||
15309 | return true; | |||
15310 | } | |||
15311 | ||||
15312 | /// Check if two standard-layout unions are layout-compatible. | |||
15313 | /// (C++11 [class.mem] p18) | |||
15314 | static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, | |||
15315 | RecordDecl *RD2) { | |||
15316 | llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; | |||
15317 | for (auto *Field2 : RD2->fields()) | |||
15318 | UnmatchedFields.insert(Field2); | |||
15319 | ||||
15320 | for (auto *Field1 : RD1->fields()) { | |||
15321 | llvm::SmallPtrSet<FieldDecl *, 8>::iterator | |||
15322 | I = UnmatchedFields.begin(), | |||
15323 | E = UnmatchedFields.end(); | |||
15324 | ||||
15325 | for ( ; I != E; ++I) { | |||
15326 | if (isLayoutCompatible(C, Field1, *I)) { | |||
15327 | bool Result = UnmatchedFields.erase(*I); | |||
15328 | (void) Result; | |||
15329 | assert(Result)((Result) ? static_cast<void> (0) : __assert_fail ("Result" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 15329, __PRETTY_FUNCTION__)); | |||
15330 | break; | |||
15331 | } | |||
15332 | } | |||
15333 | if (I == E) | |||
15334 | return false; | |||
15335 | } | |||
15336 | ||||
15337 | return UnmatchedFields.empty(); | |||
15338 | } | |||
15339 | ||||
15340 | static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, | |||
15341 | RecordDecl *RD2) { | |||
15342 | if (RD1->isUnion() != RD2->isUnion()) | |||
15343 | return false; | |||
15344 | ||||
15345 | if (RD1->isUnion()) | |||
15346 | return isLayoutCompatibleUnion(C, RD1, RD2); | |||
15347 | else | |||
15348 | return isLayoutCompatibleStruct(C, RD1, RD2); | |||
15349 | } | |||
15350 | ||||
15351 | /// Check if two types are layout-compatible in C++11 sense. | |||
15352 | static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { | |||
15353 | if (T1.isNull() || T2.isNull()) | |||
15354 | return false; | |||
15355 | ||||
15356 | // C++11 [basic.types] p11: | |||
15357 | // If two types T1 and T2 are the same type, then T1 and T2 are | |||
15358 | // layout-compatible types. | |||
15359 | if (C.hasSameType(T1, T2)) | |||
15360 | return true; | |||
15361 | ||||
15362 | T1 = T1.getCanonicalType().getUnqualifiedType(); | |||
15363 | T2 = T2.getCanonicalType().getUnqualifiedType(); | |||
15364 | ||||
15365 | const Type::TypeClass TC1 = T1->getTypeClass(); | |||
15366 | const Type::TypeClass TC2 = T2->getTypeClass(); | |||
15367 | ||||
15368 | if (TC1 != TC2) | |||
15369 | return false; | |||
15370 | ||||
15371 | if (TC1 == Type::Enum) { | |||
15372 | return isLayoutCompatible(C, | |||
15373 | cast<EnumType>(T1)->getDecl(), | |||
15374 | cast<EnumType>(T2)->getDecl()); | |||
15375 | } else if (TC1 == Type::Record) { | |||
15376 | if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) | |||
15377 | return false; | |||
15378 | ||||
15379 | return isLayoutCompatible(C, | |||
15380 | cast<RecordType>(T1)->getDecl(), | |||
15381 | cast<RecordType>(T2)->getDecl()); | |||
15382 | } | |||
15383 | ||||
15384 | return false; | |||
15385 | } | |||
15386 | ||||
15387 | //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// | |||
15388 | ||||
15389 | /// Given a type tag expression find the type tag itself. | |||
15390 | /// | |||
15391 | /// \param TypeExpr Type tag expression, as it appears in user's code. | |||
15392 | /// | |||
15393 | /// \param VD Declaration of an identifier that appears in a type tag. | |||
15394 | /// | |||
15395 | /// \param MagicValue Type tag magic value. | |||
15396 | /// | |||
15397 | /// \param isConstantEvaluated wether the evalaution should be performed in | |||
15398 | ||||
15399 | /// constant context. | |||
15400 | static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, | |||
15401 | const ValueDecl **VD, uint64_t *MagicValue, | |||
15402 | bool isConstantEvaluated) { | |||
15403 | while(true) { | |||
15404 | if (!TypeExpr) | |||
15405 | return false; | |||
15406 | ||||
15407 | TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); | |||
15408 | ||||
15409 | switch (TypeExpr->getStmtClass()) { | |||
15410 | case Stmt::UnaryOperatorClass: { | |||
15411 | const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); | |||
15412 | if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { | |||
15413 | TypeExpr = UO->getSubExpr(); | |||
15414 | continue; | |||
15415 | } | |||
15416 | return false; | |||
15417 | } | |||
15418 | ||||
15419 | case Stmt::DeclRefExprClass: { | |||
15420 | const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); | |||
15421 | *VD = DRE->getDecl(); | |||
15422 | return true; | |||
15423 | } | |||
15424 | ||||
15425 | case Stmt::IntegerLiteralClass: { | |||
15426 | const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); | |||
15427 | llvm::APInt MagicValueAPInt = IL->getValue(); | |||
15428 | if (MagicValueAPInt.getActiveBits() <= 64) { | |||
15429 | *MagicValue = MagicValueAPInt.getZExtValue(); | |||
15430 | return true; | |||
15431 | } else | |||
15432 | return false; | |||
15433 | } | |||
15434 | ||||
15435 | case Stmt::BinaryConditionalOperatorClass: | |||
15436 | case Stmt::ConditionalOperatorClass: { | |||
15437 | const AbstractConditionalOperator *ACO = | |||
15438 | cast<AbstractConditionalOperator>(TypeExpr); | |||
15439 | bool Result; | |||
15440 | if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, | |||
15441 | isConstantEvaluated)) { | |||
15442 | if (Result) | |||
15443 | TypeExpr = ACO->getTrueExpr(); | |||
15444 | else | |||
15445 | TypeExpr = ACO->getFalseExpr(); | |||
15446 | continue; | |||
15447 | } | |||
15448 | return false; | |||
15449 | } | |||
15450 | ||||
15451 | case Stmt::BinaryOperatorClass: { | |||
15452 | const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); | |||
15453 | if (BO->getOpcode() == BO_Comma) { | |||
15454 | TypeExpr = BO->getRHS(); | |||
15455 | continue; | |||
15456 | } | |||
15457 | return false; | |||
15458 | } | |||
15459 | ||||
15460 | default: | |||
15461 | return false; | |||
15462 | } | |||
15463 | } | |||
15464 | } | |||
15465 | ||||
15466 | /// Retrieve the C type corresponding to type tag TypeExpr. | |||
15467 | /// | |||
15468 | /// \param TypeExpr Expression that specifies a type tag. | |||
15469 | /// | |||
15470 | /// \param MagicValues Registered magic values. | |||
15471 | /// | |||
15472 | /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong | |||
15473 | /// kind. | |||
15474 | /// | |||
15475 | /// \param TypeInfo Information about the corresponding C type. | |||
15476 | /// | |||
15477 | /// \param isConstantEvaluated wether the evalaution should be performed in | |||
15478 | /// constant context. | |||
15479 | /// | |||
15480 | /// \returns true if the corresponding C type was found. | |||
15481 | static bool GetMatchingCType( | |||
15482 | const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, | |||
15483 | const ASTContext &Ctx, | |||
15484 | const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> | |||
15485 | *MagicValues, | |||
15486 | bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, | |||
15487 | bool isConstantEvaluated) { | |||
15488 | FoundWrongKind = false; | |||
15489 | ||||
15490 | // Variable declaration that has type_tag_for_datatype attribute. | |||
15491 | const ValueDecl *VD = nullptr; | |||
15492 | ||||
15493 | uint64_t MagicValue; | |||
15494 | ||||
15495 | if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) | |||
15496 | return false; | |||
15497 | ||||
15498 | if (VD) { | |||
15499 | if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { | |||
15500 | if (I->getArgumentKind() != ArgumentKind) { | |||
15501 | FoundWrongKind = true; | |||
15502 | return false; | |||
15503 | } | |||
15504 | TypeInfo.Type = I->getMatchingCType(); | |||
15505 | TypeInfo.LayoutCompatible = I->getLayoutCompatible(); | |||
15506 | TypeInfo.MustBeNull = I->getMustBeNull(); | |||
15507 | return true; | |||
15508 | } | |||
15509 | return false; | |||
15510 | } | |||
15511 | ||||
15512 | if (!MagicValues) | |||
15513 | return false; | |||
15514 | ||||
15515 | llvm::DenseMap<Sema::TypeTagMagicValue, | |||
15516 | Sema::TypeTagData>::const_iterator I = | |||
15517 | MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); | |||
15518 | if (I == MagicValues->end()) | |||
15519 | return false; | |||
15520 | ||||
15521 | TypeInfo = I->second; | |||
15522 | return true; | |||
15523 | } | |||
15524 | ||||
15525 | void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, | |||
15526 | uint64_t MagicValue, QualType Type, | |||
15527 | bool LayoutCompatible, | |||
15528 | bool MustBeNull) { | |||
15529 | if (!TypeTagForDatatypeMagicValues) | |||
15530 | TypeTagForDatatypeMagicValues.reset( | |||
15531 | new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); | |||
15532 | ||||
15533 | TypeTagMagicValue Magic(ArgumentKind, MagicValue); | |||
15534 | (*TypeTagForDatatypeMagicValues)[Magic] = | |||
15535 | TypeTagData(Type, LayoutCompatible, MustBeNull); | |||
15536 | } | |||
15537 | ||||
15538 | static bool IsSameCharType(QualType T1, QualType T2) { | |||
15539 | const BuiltinType *BT1 = T1->getAs<BuiltinType>(); | |||
15540 | if (!BT1) | |||
15541 | return false; | |||
15542 | ||||
15543 | const BuiltinType *BT2 = T2->getAs<BuiltinType>(); | |||
15544 | if (!BT2) | |||
15545 | return false; | |||
15546 | ||||
15547 | BuiltinType::Kind T1Kind = BT1->getKind(); | |||
15548 | BuiltinType::Kind T2Kind = BT2->getKind(); | |||
15549 | ||||
15550 | return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || | |||
15551 | (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || | |||
15552 | (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || | |||
15553 | (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); | |||
15554 | } | |||
15555 | ||||
15556 | void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, | |||
15557 | const ArrayRef<const Expr *> ExprArgs, | |||
15558 | SourceLocation CallSiteLoc) { | |||
15559 | const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); | |||
15560 | bool IsPointerAttr = Attr->getIsPointer(); | |||
15561 | ||||
15562 | // Retrieve the argument representing the 'type_tag'. | |||
15563 | unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); | |||
15564 | if (TypeTagIdxAST >= ExprArgs.size()) { | |||
15565 | Diag(CallSiteLoc, diag::err_tag_index_out_of_range) | |||
15566 | << 0 << Attr->getTypeTagIdx().getSourceIndex(); | |||
15567 | return; | |||
15568 | } | |||
15569 | const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; | |||
15570 | bool FoundWrongKind; | |||
15571 | TypeTagData TypeInfo; | |||
15572 | if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, | |||
15573 | TypeTagForDatatypeMagicValues.get(), FoundWrongKind, | |||
15574 | TypeInfo, isConstantEvaluated())) { | |||
15575 | if (FoundWrongKind) | |||
15576 | Diag(TypeTagExpr->getExprLoc(), | |||
15577 | diag::warn_type_tag_for_datatype_wrong_kind) | |||
15578 | << TypeTagExpr->getSourceRange(); | |||
15579 | return; | |||
15580 | } | |||
15581 | ||||
15582 | // Retrieve the argument representing the 'arg_idx'. | |||
15583 | unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); | |||
15584 | if (ArgumentIdxAST >= ExprArgs.size()) { | |||
15585 | Diag(CallSiteLoc, diag::err_tag_index_out_of_range) | |||
15586 | << 1 << Attr->getArgumentIdx().getSourceIndex(); | |||
15587 | return; | |||
15588 | } | |||
15589 | const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; | |||
15590 | if (IsPointerAttr) { | |||
15591 | // Skip implicit cast of pointer to `void *' (as a function argument). | |||
15592 | if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) | |||
15593 | if (ICE->getType()->isVoidPointerType() && | |||
15594 | ICE->getCastKind() == CK_BitCast) | |||
15595 | ArgumentExpr = ICE->getSubExpr(); | |||
15596 | } | |||
15597 | QualType ArgumentType = ArgumentExpr->getType(); | |||
15598 | ||||
15599 | // Passing a `void*' pointer shouldn't trigger a warning. | |||
15600 | if (IsPointerAttr && ArgumentType->isVoidPointerType()) | |||
15601 | return; | |||
15602 | ||||
15603 | if (TypeInfo.MustBeNull) { | |||
15604 | // Type tag with matching void type requires a null pointer. | |||
15605 | if (!ArgumentExpr->isNullPointerConstant(Context, | |||
15606 | Expr::NPC_ValueDependentIsNotNull)) { | |||
15607 | Diag(ArgumentExpr->getExprLoc(), | |||
15608 | diag::warn_type_safety_null_pointer_required) | |||
15609 | << ArgumentKind->getName() | |||
15610 | << ArgumentExpr->getSourceRange() | |||
15611 | << TypeTagExpr->getSourceRange(); | |||
15612 | } | |||
15613 | return; | |||
15614 | } | |||
15615 | ||||
15616 | QualType RequiredType = TypeInfo.Type; | |||
15617 | if (IsPointerAttr) | |||
15618 | RequiredType = Context.getPointerType(RequiredType); | |||
15619 | ||||
15620 | bool mismatch = false; | |||
15621 | if (!TypeInfo.LayoutCompatible) { | |||
15622 | mismatch = !Context.hasSameType(ArgumentType, RequiredType); | |||
15623 | ||||
15624 | // C++11 [basic.fundamental] p1: | |||
15625 | // Plain char, signed char, and unsigned char are three distinct types. | |||
15626 | // | |||
15627 | // But we treat plain `char' as equivalent to `signed char' or `unsigned | |||
15628 | // char' depending on the current char signedness mode. | |||
15629 | if (mismatch) | |||
15630 | if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), | |||
15631 | RequiredType->getPointeeType())) || | |||
15632 | (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) | |||
15633 | mismatch = false; | |||
15634 | } else | |||
15635 | if (IsPointerAttr) | |||
15636 | mismatch = !isLayoutCompatible(Context, | |||
15637 | ArgumentType->getPointeeType(), | |||
15638 | RequiredType->getPointeeType()); | |||
15639 | else | |||
15640 | mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); | |||
15641 | ||||
15642 | if (mismatch) | |||
15643 | Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) | |||
15644 | << ArgumentType << ArgumentKind | |||
15645 | << TypeInfo.LayoutCompatible << RequiredType | |||
15646 | << ArgumentExpr->getSourceRange() | |||
15647 | << TypeTagExpr->getSourceRange(); | |||
15648 | } | |||
15649 | ||||
15650 | void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, | |||
15651 | CharUnits Alignment) { | |||
15652 | MisalignedMembers.emplace_back(E, RD, MD, Alignment); | |||
15653 | } | |||
15654 | ||||
15655 | void Sema::DiagnoseMisalignedMembers() { | |||
15656 | for (MisalignedMember &m : MisalignedMembers) { | |||
15657 | const NamedDecl *ND = m.RD; | |||
15658 | if (ND->getName().empty()) { | |||
15659 | if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) | |||
15660 | ND = TD; | |||
15661 | } | |||
15662 | Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) | |||
15663 | << m.MD << ND << m.E->getSourceRange(); | |||
15664 | } | |||
15665 | MisalignedMembers.clear(); | |||
15666 | } | |||
15667 | ||||
15668 | void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { | |||
15669 | E = E->IgnoreParens(); | |||
15670 | if (!T->isPointerType() && !T->isIntegerType()) | |||
15671 | return; | |||
15672 | if (isa<UnaryOperator>(E) && | |||
15673 | cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { | |||
15674 | auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); | |||
15675 | if (isa<MemberExpr>(Op)) { | |||
15676 | auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); | |||
15677 | if (MA != MisalignedMembers.end() && | |||
15678 | (T->isIntegerType() || | |||
15679 | (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || | |||
15680 | Context.getTypeAlignInChars( | |||
15681 | T->getPointeeType()) <= MA->Alignment)))) | |||
15682 | MisalignedMembers.erase(MA); | |||
15683 | } | |||
15684 | } | |||
15685 | } | |||
15686 | ||||
15687 | void Sema::RefersToMemberWithReducedAlignment( | |||
15688 | Expr *E, | |||
15689 | llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> | |||
15690 | Action) { | |||
15691 | const auto *ME = dyn_cast<MemberExpr>(E); | |||
15692 | if (!ME) | |||
15693 | return; | |||
15694 | ||||
15695 | // No need to check expressions with an __unaligned-qualified type. | |||
15696 | if (E->getType().getQualifiers().hasUnaligned()) | |||
15697 | return; | |||
15698 | ||||
15699 | // For a chain of MemberExpr like "a.b.c.d" this list | |||
15700 | // will keep FieldDecl's like [d, c, b]. | |||
15701 | SmallVector<FieldDecl *, 4> ReverseMemberChain; | |||
15702 | const MemberExpr *TopME = nullptr; | |||
15703 | bool AnyIsPacked = false; | |||
15704 | do { | |||
15705 | QualType BaseType = ME->getBase()->getType(); | |||
15706 | if (BaseType->isDependentType()) | |||
15707 | return; | |||
15708 | if (ME->isArrow()) | |||
15709 | BaseType = BaseType->getPointeeType(); | |||
15710 | RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); | |||
15711 | if (RD->isInvalidDecl()) | |||
15712 | return; | |||
15713 | ||||
15714 | ValueDecl *MD = ME->getMemberDecl(); | |||
15715 | auto *FD = dyn_cast<FieldDecl>(MD); | |||
15716 | // We do not care about non-data members. | |||
15717 | if (!FD || FD->isInvalidDecl()) | |||
15718 | return; | |||
15719 | ||||
15720 | AnyIsPacked = | |||
15721 | AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); | |||
15722 | ReverseMemberChain.push_back(FD); | |||
15723 | ||||
15724 | TopME = ME; | |||
15725 | ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); | |||
15726 | } while (ME); | |||
15727 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 15727, __PRETTY_FUNCTION__)); | |||
15728 | ||||
15729 | // Not the scope of this diagnostic. | |||
15730 | if (!AnyIsPacked) | |||
15731 | return; | |||
15732 | ||||
15733 | const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); | |||
15734 | const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); | |||
15735 | // TODO: The innermost base of the member expression may be too complicated. | |||
15736 | // For now, just disregard these cases. This is left for future | |||
15737 | // improvement. | |||
15738 | if (!DRE && !isa<CXXThisExpr>(TopBase)) | |||
15739 | return; | |||
15740 | ||||
15741 | // Alignment expected by the whole expression. | |||
15742 | CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); | |||
15743 | ||||
15744 | // No need to do anything else with this case. | |||
15745 | if (ExpectedAlignment.isOne()) | |||
15746 | return; | |||
15747 | ||||
15748 | // Synthesize offset of the whole access. | |||
15749 | CharUnits Offset; | |||
15750 | for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); | |||
15751 | I++) { | |||
15752 | Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); | |||
15753 | } | |||
15754 | ||||
15755 | // Compute the CompleteObjectAlignment as the alignment of the whole chain. | |||
15756 | CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( | |||
15757 | ReverseMemberChain.back()->getParent()->getTypeForDecl()); | |||
15758 | ||||
15759 | // The base expression of the innermost MemberExpr may give | |||
15760 | // stronger guarantees than the class containing the member. | |||
15761 | if (DRE && !TopME->isArrow()) { | |||
15762 | const ValueDecl *VD = DRE->getDecl(); | |||
15763 | if (!VD->getType()->isReferenceType()) | |||
15764 | CompleteObjectAlignment = | |||
15765 | std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); | |||
15766 | } | |||
15767 | ||||
15768 | // Check if the synthesized offset fulfills the alignment. | |||
15769 | if (Offset % ExpectedAlignment != 0 || | |||
15770 | // It may fulfill the offset it but the effective alignment may still be | |||
15771 | // lower than the expected expression alignment. | |||
15772 | CompleteObjectAlignment < ExpectedAlignment) { | |||
15773 | // If this happens, we want to determine a sensible culprit of this. | |||
15774 | // Intuitively, watching the chain of member expressions from right to | |||
15775 | // left, we start with the required alignment (as required by the field | |||
15776 | // type) but some packed attribute in that chain has reduced the alignment. | |||
15777 | // It may happen that another packed structure increases it again. But if | |||
15778 | // we are here such increase has not been enough. So pointing the first | |||
15779 | // FieldDecl that either is packed or else its RecordDecl is, | |||
15780 | // seems reasonable. | |||
15781 | FieldDecl *FD = nullptr; | |||
15782 | CharUnits Alignment; | |||
15783 | for (FieldDecl *FDI : ReverseMemberChain) { | |||
15784 | if (FDI->hasAttr<PackedAttr>() || | |||
15785 | FDI->getParent()->hasAttr<PackedAttr>()) { | |||
15786 | FD = FDI; | |||
15787 | Alignment = std::min( | |||
15788 | Context.getTypeAlignInChars(FD->getType()), | |||
15789 | Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); | |||
15790 | break; | |||
15791 | } | |||
15792 | } | |||
15793 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaChecking.cpp" , 15793, __PRETTY_FUNCTION__)); | |||
15794 | Action(E, FD->getParent(), FD, Alignment); | |||
15795 | } | |||
15796 | } | |||
15797 | ||||
15798 | void Sema::CheckAddressOfPackedMember(Expr *rhs) { | |||
15799 | using namespace std::placeholders; | |||
15800 | ||||
15801 | RefersToMemberWithReducedAlignment( | |||
15802 | rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, | |||
15803 | _2, _3, _4)); | |||
15804 | } | |||
15805 | ||||
15806 | ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, | |||
15807 | ExprResult CallResult) { | |||
15808 | if (checkArgCount(*this, TheCall, 1)) | |||
15809 | return ExprError(); | |||
15810 | ||||
15811 | ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); | |||
15812 | if (MatrixArg.isInvalid()) | |||
15813 | return MatrixArg; | |||
15814 | Expr *Matrix = MatrixArg.get(); | |||
15815 | ||||
15816 | auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); | |||
15817 | if (!MType) { | |||
15818 | Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); | |||
15819 | return ExprError(); | |||
15820 | } | |||
15821 | ||||
15822 | // Create returned matrix type by swapping rows and columns of the argument | |||
15823 | // matrix type. | |||
15824 | QualType ResultType = Context.getConstantMatrixType( | |||
15825 | MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); | |||
15826 | ||||
15827 | // Change the return type to the type of the returned matrix. | |||
15828 | TheCall->setType(ResultType); | |||
15829 | ||||
15830 | // Update call argument to use the possibly converted matrix argument. | |||
15831 | TheCall->setArg(0, Matrix); | |||
15832 | return CallResult; | |||
15833 | } | |||
15834 | ||||
15835 | // Get and verify the matrix dimensions. | |||
15836 | static llvm::Optional<unsigned> | |||
15837 | getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { | |||
15838 | SourceLocation ErrorPos; | |||
15839 | Optional<llvm::APSInt> Value = | |||
15840 | Expr->getIntegerConstantExpr(S.Context, &ErrorPos); | |||
15841 | if (!Value) { | |||
15842 | S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) | |||
15843 | << Name; | |||
15844 | return {}; | |||
15845 | } | |||
15846 | uint64_t Dim = Value->getZExtValue(); | |||
15847 | if (!ConstantMatrixType::isDimensionValid(Dim)) { | |||
15848 | S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) | |||
15849 | << Name << ConstantMatrixType::getMaxElementsPerDimension(); | |||
15850 | return {}; | |||
15851 | } | |||
15852 | return Dim; | |||
15853 | } | |||
15854 | ||||
15855 | ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, | |||
15856 | ExprResult CallResult) { | |||
15857 | if (!getLangOpts().MatrixTypes) { | |||
15858 | Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); | |||
15859 | return ExprError(); | |||
15860 | } | |||
15861 | ||||
15862 | if (checkArgCount(*this, TheCall, 4)) | |||
15863 | return ExprError(); | |||
15864 | ||||
15865 | unsigned PtrArgIdx = 0; | |||
15866 | Expr *PtrExpr = TheCall->getArg(PtrArgIdx); | |||
15867 | Expr *RowsExpr = TheCall->getArg(1); | |||
15868 | Expr *ColumnsExpr = TheCall->getArg(2); | |||
15869 | Expr *StrideExpr = TheCall->getArg(3); | |||
15870 | ||||
15871 | bool ArgError = false; | |||
15872 | ||||
15873 | // Check pointer argument. | |||
15874 | { | |||
15875 | ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); | |||
15876 | if (PtrConv.isInvalid()) | |||
15877 | return PtrConv; | |||
15878 | PtrExpr = PtrConv.get(); | |||
15879 | TheCall->setArg(0, PtrExpr); | |||
15880 | if (PtrExpr->isTypeDependent()) { | |||
15881 | TheCall->setType(Context.DependentTy); | |||
15882 | return TheCall; | |||
15883 | } | |||
15884 | } | |||
15885 | ||||
15886 | auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); | |||
15887 | QualType ElementTy; | |||
15888 | if (!PtrTy) { | |||
15889 | Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) | |||
15890 | << PtrArgIdx + 1; | |||
15891 | ArgError = true; | |||
15892 | } else { | |||
15893 | ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); | |||
15894 | ||||
15895 | if (!ConstantMatrixType::isValidElementType(ElementTy)) { | |||
15896 | Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) | |||
15897 | << PtrArgIdx + 1; | |||
15898 | ArgError = true; | |||
15899 | } | |||
15900 | } | |||
15901 | ||||
15902 | // Apply default Lvalue conversions and convert the expression to size_t. | |||
15903 | auto ApplyArgumentConversions = [this](Expr *E) { | |||
15904 | ExprResult Conv = DefaultLvalueConversion(E); | |||
15905 | if (Conv.isInvalid()) | |||
15906 | return Conv; | |||
15907 | ||||
15908 | return tryConvertExprToType(Conv.get(), Context.getSizeType()); | |||
15909 | }; | |||
15910 | ||||
15911 | // Apply conversion to row and column expressions. | |||
15912 | ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); | |||
15913 | if (!RowsConv.isInvalid()) { | |||
15914 | RowsExpr = RowsConv.get(); | |||
15915 | TheCall->setArg(1, RowsExpr); | |||
15916 | } else | |||
15917 | RowsExpr = nullptr; | |||
15918 | ||||
15919 | ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); | |||
15920 | if (!ColumnsConv.isInvalid()) { | |||
15921 | ColumnsExpr = ColumnsConv.get(); | |||
15922 | TheCall->setArg(2, ColumnsExpr); | |||
15923 | } else | |||
15924 | ColumnsExpr = nullptr; | |||
15925 | ||||
15926 | // If any any part of the result matrix type is still pending, just use | |||
15927 | // Context.DependentTy, until all parts are resolved. | |||
15928 | if ((RowsExpr && RowsExpr->isTypeDependent()) || | |||
15929 | (ColumnsExpr && ColumnsExpr->isTypeDependent())) { | |||
15930 | TheCall->setType(Context.DependentTy); | |||
15931 | return CallResult; | |||
15932 | } | |||
15933 | ||||
15934 | // Check row and column dimenions. | |||
15935 | llvm::Optional<unsigned> MaybeRows; | |||
15936 | if (RowsExpr) | |||
15937 | MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); | |||
15938 | ||||
15939 | llvm::Optional<unsigned> MaybeColumns; | |||
15940 | if (ColumnsExpr) | |||
15941 | MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); | |||
15942 | ||||
15943 | // Check stride argument. | |||
15944 | ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); | |||
15945 | if (StrideConv.isInvalid()) | |||
15946 | return ExprError(); | |||
15947 | StrideExpr = StrideConv.get(); | |||
15948 | TheCall->setArg(3, StrideExpr); | |||
15949 | ||||
15950 | if (MaybeRows) { | |||
15951 | if (Optional<llvm::APSInt> Value = | |||
15952 | StrideExpr->getIntegerConstantExpr(Context)) { | |||
15953 | uint64_t Stride = Value->getZExtValue(); | |||
15954 | if (Stride < *MaybeRows) { | |||
15955 | Diag(StrideExpr->getBeginLoc(), | |||
15956 | diag::err_builtin_matrix_stride_too_small); | |||
15957 | ArgError = true; | |||
15958 | } | |||
15959 | } | |||
15960 | } | |||
15961 | ||||
15962 | if (ArgError || !MaybeRows || !MaybeColumns) | |||
15963 | return ExprError(); | |||
15964 | ||||
15965 | TheCall->setType( | |||
15966 | Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); | |||
15967 | return CallResult; | |||
15968 | } | |||
15969 | ||||
15970 | ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, | |||
15971 | ExprResult CallResult) { | |||
15972 | if (checkArgCount(*this, TheCall, 3)) | |||
15973 | return ExprError(); | |||
15974 | ||||
15975 | unsigned PtrArgIdx = 1; | |||
15976 | Expr *MatrixExpr = TheCall->getArg(0); | |||
15977 | Expr *PtrExpr = TheCall->getArg(PtrArgIdx); | |||
15978 | Expr *StrideExpr = TheCall->getArg(2); | |||
15979 | ||||
15980 | bool ArgError = false; | |||
15981 | ||||
15982 | { | |||
15983 | ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); | |||
15984 | if (MatrixConv.isInvalid()) | |||
15985 | return MatrixConv; | |||
15986 | MatrixExpr = MatrixConv.get(); | |||
15987 | TheCall->setArg(0, MatrixExpr); | |||
15988 | } | |||
15989 | if (MatrixExpr->isTypeDependent()) { | |||
15990 | TheCall->setType(Context.DependentTy); | |||
15991 | return TheCall; | |||
15992 | } | |||
15993 | ||||
15994 | auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); | |||
15995 | if (!MatrixTy) { | |||
15996 | Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; | |||
15997 | ArgError = true; | |||
15998 | } | |||
15999 | ||||
16000 | { | |||
16001 | ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); | |||
16002 | if (PtrConv.isInvalid()) | |||
16003 | return PtrConv; | |||
16004 | PtrExpr = PtrConv.get(); | |||
16005 | TheCall->setArg(1, PtrExpr); | |||
16006 | if (PtrExpr->isTypeDependent()) { | |||
16007 | TheCall->setType(Context.DependentTy); | |||
16008 | return TheCall; | |||
16009 | } | |||
16010 | } | |||
16011 | ||||
16012 | // Check pointer argument. | |||
16013 | auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); | |||
16014 | if (!PtrTy) { | |||
16015 | Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) | |||
16016 | << PtrArgIdx + 1; | |||
16017 | ArgError = true; | |||
16018 | } else { | |||
16019 | QualType ElementTy = PtrTy->getPointeeType(); | |||
16020 | if (ElementTy.isConstQualified()) { | |||
16021 | Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); | |||
16022 | ArgError = true; | |||
16023 | } | |||
16024 | ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); | |||
16025 | if (MatrixTy && | |||
16026 | !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { | |||
16027 | Diag(PtrExpr->getBeginLoc(), | |||
16028 | diag::err_builtin_matrix_pointer_arg_mismatch) | |||
16029 | << ElementTy << MatrixTy->getElementType(); | |||
16030 | ArgError = true; | |||
16031 | } | |||
16032 | } | |||
16033 | ||||
16034 | // Apply default Lvalue conversions and convert the stride expression to | |||
16035 | // size_t. | |||
16036 | { | |||
16037 | ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); | |||
16038 | if (StrideConv.isInvalid()) | |||
16039 | return StrideConv; | |||
16040 | ||||
16041 | StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); | |||
16042 | if (StrideConv.isInvalid()) | |||
16043 | return StrideConv; | |||
16044 | StrideExpr = StrideConv.get(); | |||
16045 | TheCall->setArg(2, StrideExpr); | |||
16046 | } | |||
16047 | ||||
16048 | // Check stride argument. | |||
16049 | if (MatrixTy) { | |||
16050 | if (Optional<llvm::APSInt> Value = | |||
16051 | StrideExpr->getIntegerConstantExpr(Context)) { | |||
16052 | uint64_t Stride = Value->getZExtValue(); | |||
16053 | if (Stride < MatrixTy->getNumRows()) { | |||
16054 | Diag(StrideExpr->getBeginLoc(), | |||
16055 | diag::err_builtin_matrix_stride_too_small); | |||
16056 | ArgError = true; | |||
16057 | } | |||
16058 | } | |||
16059 | } | |||
16060 | ||||
16061 | if (ArgError) | |||
16062 | return ExprError(); | |||
16063 | ||||
16064 | return CallResult; | |||
16065 | } | |||
16066 | ||||
16067 | /// \brief Enforce the bounds of a TCB | |||
16068 | /// CheckTCBEnforcement - Enforces that every function in a named TCB only | |||
16069 | /// directly calls other functions in the same TCB as marked by the enforce_tcb | |||
16070 | /// and enforce_tcb_leaf attributes. | |||
16071 | void Sema::CheckTCBEnforcement(const CallExpr *TheCall, | |||
16072 | const FunctionDecl *Callee) { | |||
16073 | const FunctionDecl *Caller = getCurFunctionDecl(); | |||
16074 | ||||
16075 | // Calls to builtins are not enforced. | |||
16076 | if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || | |||
16077 | Callee->getBuiltinID() != 0) | |||
16078 | return; | |||
16079 | ||||
16080 | // Search through the enforce_tcb and enforce_tcb_leaf attributes to find | |||
16081 | // all TCBs the callee is a part of. | |||
16082 | llvm::StringSet<> CalleeTCBs; | |||
16083 | for_each(Callee->specific_attrs<EnforceTCBAttr>(), | |||
16084 | [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); | |||
16085 | for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), | |||
16086 | [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); | |||
16087 | ||||
16088 | // Go through the TCBs the caller is a part of and emit warnings if Caller | |||
16089 | // is in a TCB that the Callee is not. | |||
16090 | for_each( | |||
16091 | Caller->specific_attrs<EnforceTCBAttr>(), | |||
16092 | [&](const auto *A) { | |||
16093 | StringRef CallerTCB = A->getTCBName(); | |||
16094 | if (CalleeTCBs.count(CallerTCB) == 0) { | |||
16095 | this->Diag(TheCall->getExprLoc(), | |||
16096 | diag::warn_tcb_enforcement_violation) << Callee | |||
16097 | << CallerTCB; | |||
16098 | } | |||
16099 | }); | |||
16100 | } |